-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathstrukt_test.exs
563 lines (449 loc) · 19.3 KB
/
strukt_test.exs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
defmodule Strukt.Test do
use ExUnit.Case, async: true
doctest Strukt
alias Uniq.UUID
# See test/support/defstruct_fixtures.ex
alias Strukt.Test.Fixtures
test "when defstruct/1 is given a list of field names, it delegates to Kernel.defstruct/1" do
assert %Fixtures.Classic{name: nil} = %Fixtures.Classic{}
refute function_exported?(Fixtures.Classic, :new, 1)
refute Map.has_key?(Map.from_struct(%Fixtures.Classic{}), :uuid)
end
test "default values are present when creating new struct" do
assert {:ok, %Fixtures.Simple{name: ""}} = Fixtures.Simple.new()
end
test "default primary key is autogenerated by new/1" do
assert {:ok, %Fixtures.Simple{uuid: uuid}} = Fixtures.Simple.new()
assert {:ok, info} = UUID.info(uuid)
assert 4 == info.version
end
test "can cast primary key from params" do
uuid = UUID.uuid4()
assert {:ok, %Fixtures.Simple{uuid: ^uuid}} = Fixtures.Simple.new(uuid: uuid)
end
test "can define a struct and its containing module inline using defstruct/2" do
uuid = UUID.uuid4()
assert {:ok, %Fixtures.Inline{uuid: ^uuid, name: ""}} = Fixtures.Inline.new(uuid: uuid)
assert true = Fixtures.Inline.test()
end
test "can define embedded structs, using the same syntax as defstruct" do
assert {:ok, %Fixtures.Embedded{uuid: uuid, items: []}} = Fixtures.Embedded.new()
refute is_nil(uuid)
assert {:ok, %Fixtures.Embedded.Item{uuid: item_uuid, name: "foo"}} =
Fixtures.Embedded.Item.new(name: "foo")
refute is_nil(item_uuid)
end
test "can cast embeds from params" do
assert {:ok, %Fixtures.Embedded{items: [item]}} =
Fixtures.Embedded.new(items: [%{name: "foo"}])
assert %Fixtures.Embedded.Item{name: "foo"} = item
assert {:ok, %Fixtures.Embedded{items: []} = embed} = Fixtures.Embedded.new()
assert {:ok, %Fixtures.Embedded{items: [^item]}} =
Fixtures.Embedded.change(embed, items: [Map.from_struct(item)])
|> Fixtures.Embedded.from_changeset()
end
test "can specify an alternate primary key field" do
assert {:ok, %Fixtures.AltPrimaryKey{id: nil, name: ""}} = Fixtures.AltPrimaryKey.new()
refute Map.has_key?(Map.from_struct(%Fixtures.AltPrimaryKey{}), :uuid)
end
test "can specify an alternate primary key field via @primary_key attribute" do
assert {:ok, %Fixtures.AttrPrimaryKey{id: id, name: ""}} = Fixtures.AttrPrimaryKey.new()
refute is_nil(id)
assert is_integer(id)
refute Map.has_key?(Map.from_struct(%Fixtures.AttrPrimaryKey{}), :uuid)
end
test "generated primary keys are unique" do
assert {:ok, %Fixtures.Simple{uuid: uuid1}} = Fixtures.Simple.new()
assert {:ok, %Fixtures.Simple{uuid: uuid2}} = Fixtures.Simple.new()
refute uuid1 == uuid2
assert {:ok, %Fixtures.AttrPrimaryKey{id: id1}} = Fixtures.AttrPrimaryKey.new()
assert {:ok, %Fixtures.AttrPrimaryKey{id: id2}} = Fixtures.AttrPrimaryKey.new()
refute id1 == id2
end
test "using ecto schema reflection to form a struct" do
params = %{NAME: "name", camelCaseKey: "key"}
assert {
:ok,
%Strukt.Test.Fixtures.CustomFields{
camel_case_key: "key",
name: "name",
uuid: _
}
} = Fixtures.CustomFields.new(params)
end
test "can parse custom fields for embedded schema" do
params = %{
NAME: "embedded",
items: [%{itemName: "first item"}, %{itemName: "second item"}],
meta: %{SOURCE: "iOS", Status: 1}
}
assert {:ok,
%Strukt.Test.Fixtures.CustomFieldsWithEmbeddedSchema{
items: [
%Strukt.Test.Fixtures.CustomFieldsWithEmbeddedSchema.Item{
name: "first item",
uuid: _
},
%Strukt.Test.Fixtures.CustomFieldsWithEmbeddedSchema.Item{
name: "second item",
uuid: _
}
],
meta: %Strukt.Test.Fixtures.CustomFieldsWithEmbeddedSchema.Meta{
source: "iOS",
status: 1,
uuid: _
},
name: "embedded",
uuid: uuid
}} = Fixtures.CustomFieldsWithEmbeddedSchema.new(params)
refute is_nil(uuid)
params_with_nil_value = %{
NAME: nil,
items: nil,
meta: nil
}
assert {:ok,
%Strukt.Test.Fixtures.CustomFieldsWithEmbeddedSchema{
items: [],
meta: nil,
name: nil,
uuid: uuid2
}} = Fixtures.CustomFieldsWithEmbeddedSchema.new(params_with_nil_value)
refute is_nil(uuid2)
end
test "can parse the params that inside the embedded module with required virtual field" do
params = %{
profile: %{name: "Rafael", PHONE: "+886999888777"},
wallets: [%{currency: "BTC", amount: 10, native_currency: "USD"}]
}
assert {:ok,
%Strukt.Test.Fixtures.EmbeddedWithVirtualField{
profile: %Strukt.Test.Fixtures.ProfileWithVirtualField{
name: "Rafael",
phone: "+886999888777",
uuid: _
},
uuid: _uuid,
wallets: [
%Strukt.Test.Fixtures.WalletWithVirtualField{
amount: 10,
currency: "BTC",
native_currency: "USD",
uuid: _
}
]
}} = Fixtures.EmbeddedWithVirtualField.new(params)
struct_params = %{
profile: %Strukt.Test.Fixtures.ProfileWithVirtualField{
name: "Rafael",
phone: "+886999888777"
},
wallets: [
%Strukt.Test.Fixtures.WalletWithVirtualField{
currency: "BTC",
amount: 10,
native_currency: "USD"
}
]
}
assert {:ok,
%Strukt.Test.Fixtures.EmbeddedWithVirtualField{
profile: %Strukt.Test.Fixtures.ProfileWithVirtualField{
name: "Rafael",
phone: nil,
uuid: nil
},
uuid: _uuid,
wallets: [
%Strukt.Test.Fixtures.WalletWithVirtualField{
amount: 10,
currency: "BTC",
native_currency: "USD",
uuid: nil
}
]
}} = Fixtures.EmbeddedWithVirtualField.new(struct_params)
end
test "can parse the params that inside the embedded inline module with required virtual field" do
params = %{
profile: %{name: "Rafael"},
wallets: [%{currency: "BTC"}]
}
assert {:ok,
%Strukt.Test.Fixtures.EmbeddedInlineModuleWithVirtualField{
profile: %Strukt.Test.Fixtures.EmbeddedInlineModuleWithVirtualField.Profile{
name: "Rafael",
uuid: _
},
uuid: _uuid,
wallets: [
%Strukt.Test.Fixtures.EmbeddedInlineModuleWithVirtualField.Wallet{
currency: "BTC",
uuid: _
}
]
}} = Fixtures.EmbeddedInlineModuleWithVirtualField.new(params)
string_key_params = %{
"profile" => %{"name" => "Rafael"},
"wallets" => [%{"currency" => "BTC"}]
}
assert {:ok,
%Strukt.Test.Fixtures.EmbeddedInlineModuleWithVirtualField{
profile: %Strukt.Test.Fixtures.EmbeddedInlineModuleWithVirtualField.Profile{
name: "Rafael",
uuid: _
},
uuid: _,
wallets: [
%Strukt.Test.Fixtures.EmbeddedInlineModuleWithVirtualField.Wallet{
currency: "BTC",
uuid: _
}
]
}} = Fixtures.EmbeddedInlineModuleWithVirtualField.new(string_key_params)
end
test "can parse the params that contain nil value in embedded field" do
params = %{profile: nil, walles: nil}
assert {:ok,
%Strukt.Test.Fixtures.EmbeddedParentSchema{profile: nil, uuid: uuid, wallets: []}} =
Fixtures.EmbeddedParentSchema.new(params)
refute is_nil(uuid)
end
test "can parse the params to the virtual field" do
params = %{name: "Daniel", phone: "+85299887766"}
assert {:ok,
%Strukt.Test.Fixtures.VirtualField{
name: "Daniel",
phone: "+85299887766",
uuid: uuid
}} = Fixtures.VirtualField.new(params)
refute is_nil(uuid)
end
test "can parse the params to the InlineSchema virtual field" do
params = %{name: "Daniel", phone: "+85299887766"}
assert {
:ok,
%Strukt.Test.Fixtures.InlineVirtualField{
name: "Daniel",
phone: "+85299887766",
uuid: uuid
}
} = Fixtures.InlineVirtualField.new(params)
refute is_nil(uuid)
end
test "parse custom fields with empty params" do
assert {:ok,
%Strukt.Test.Fixtures.CustomFieldsWithEmbeddedSchema{
items: [],
meta: nil,
name: nil,
uuid: uuid
}} = Fixtures.CustomFieldsWithEmbeddedSchema.new()
refute is_nil(uuid)
end
test "parse custom fields with boolean value" do
assert {:ok, %Strukt.Test.Fixtures.CustomFieldsWithBoolean{enabled: false, uuid: uuid}} =
Fixtures.CustomFieldsWithBoolean.new(%{Enabled: false})
refute is_nil(uuid)
end
test "can derive a json encoder" do
assert {:ok, %Fixtures.JSON{} = obj} = Fixtures.JSON.new()
assert {:ok, json} = Jason.encode(obj)
assert {:ok, ^obj} = Fixtures.JSON.from_json(json)
end
test "can control struct generation with outer attributes" do
assert {:ok, %Fixtures.OuterAttrs{} = obj} = Fixtures.OuterAttrs.new()
assert {:ok, _} = UUID.info(obj.uuid)
assert %DateTime{} = obj.inserted_at
assert {:ok, json} = Jason.encode(obj)
assert {:ok, ^obj} = Fixtures.OuterAttrs.from_json(json)
end
test "usings/imports are scoped correctly when using defstruct/2" do
assert {:ok, %Fixtures.OuterScope.InnerScope{} = scope} = Fixtures.OuterScope.InnerScope.new()
refute scope.uuid == nil
assert %DateTime{} = scope.inserted_at
end
test "can express validations inline with field definitions" do
assert {:error, changeset} = Fixtures.Validations.new()
assert %{name: ["can't be blank"], email: ["must provide an email"]} ==
changeset_errors(changeset)
end
test "can modify a struct and validate the changes" do
assert {:ok, valid} =
Fixtures.Validations.new(
name: "Bobby Tables",
email: "bobby.tables@example.com",
age: 120,
status: :green
)
assert %Ecto.Changeset{} = changeset = Fixtures.Validations.change(valid, age: 0)
assert {:error, %Ecto.Changeset{}} = Fixtures.Validations.from_changeset(changeset)
assert %{age: ["must be greater than 0"]} = changeset_errors(changeset)
end
test "can require that an embed be present" do
assert {:error, changeset} = Fixtures.ValidateRequiredEmbed.new()
assert %{embedded: ["embed must be set"]} = changeset_errors(changeset)
end
test "can correctly validate enums" do
params = [
name: "Bobby Tables",
email: "bobby.tables@example.com",
age: 120
]
assert {:error, %Ecto.Changeset{} = changeset} =
Fixtures.Validations.new(Keyword.merge(params, status: 123))
assert %{status: ["is invalid"]} = changeset_errors(changeset)
end
test "can correctly validate string lengths" do
params = [exact: "abc", bounded_graphemes: "ááá", bounded_bytes: "abc"]
assert {:ok, _} = Fixtures.ValidateLengths.new(params)
assert {:error, changeset} = Fixtures.ValidateLengths.new(Keyword.merge(params, exact: ""))
assert %{exact: ["must be 3 characters"]} = changeset_errors(changeset)
assert {:error, changeset} =
Fixtures.ValidateLengths.new(Keyword.merge(params, exact: "abcd"))
assert %{exact: ["must be 3 characters"]} = changeset_errors(changeset)
assert {:error, changeset} =
Fixtures.ValidateLengths.new(Keyword.merge(params, bounded_bytes: ""))
assert %{bounded_bytes: ["must be between 1 and 3 bytes"]} = changeset_errors(changeset)
assert {:error, changeset} =
Fixtures.ValidateLengths.new(Keyword.merge(params, bounded_bytes: "ábc"))
assert %{bounded_bytes: ["must be between 1 and 3 bytes"]} = changeset_errors(changeset)
assert {:error, changeset} =
Fixtures.ValidateLengths.new(Keyword.merge(params, bounded_graphemes: ""))
assert %{bounded_graphemes: ["must be between 1 and 3 graphemes"]} =
changeset_errors(changeset)
assert {:error, changeset} =
Fixtures.ValidateLengths.new(Keyword.merge(params, bounded_graphemes: "áááá"))
assert %{bounded_graphemes: ["must be between 1 and 3 graphemes"]} =
changeset_errors(changeset)
end
test "can correctly validate set membership" do
params = [one_of: "a", none_of: "d", subset_of: ["a", "c"]]
assert {:ok, _} = Fixtures.ValidateSets.new(params)
assert {:error, changeset} = Fixtures.ValidateSets.new(Keyword.merge(params, one_of: "d"))
assert %{one_of: ["must be one of [a, b, c]"]} = changeset_errors(changeset)
assert {:error, changeset} = Fixtures.ValidateSets.new(Keyword.merge(params, none_of: "a"))
assert %{none_of: ["cannot be one of [a, b, c]"]} = changeset_errors(changeset)
assert {:error, changeset} =
Fixtures.ValidateSets.new(Keyword.merge(params, subset_of: ["a", "b", "d"]))
assert %{subset_of: ["has an invalid entry"]} = changeset_errors(changeset)
end
test "can correctly validate numbers" do
params = [bounds: 2, bounds_inclusive: 1, eq: 1, neq: 0, range: 1]
assert {:ok, _} = Fixtures.ValidateNumbers.new(params)
assert {:error, changeset} = Fixtures.ValidateNumbers.new(Keyword.merge(params, bounds: 1))
assert %{bounds: ["must be greater than 1"]} = changeset_errors(changeset)
assert {:error, changeset} = Fixtures.ValidateNumbers.new(Keyword.merge(params, bounds: 100))
assert %{bounds: ["must be less than 100"]} = changeset_errors(changeset)
assert {:ok, _} = Fixtures.ValidateNumbers.new(Keyword.merge(params, bounds_inclusive: 100))
assert {:error, changeset} =
Fixtures.ValidateNumbers.new(Keyword.merge(params, bounds_inclusive: 0))
assert %{bounds_inclusive: ["must be greater than or equal to 1"]} =
changeset_errors(changeset)
assert {:error, changeset} =
Fixtures.ValidateNumbers.new(Keyword.merge(params, bounds_inclusive: 101))
assert %{bounds_inclusive: ["must be less than or equal to 100"]} =
changeset_errors(changeset)
assert {:error, changeset} = Fixtures.ValidateNumbers.new(Keyword.merge(params, eq: 2))
assert %{eq: ["must be equal to 1"]} = changeset_errors(changeset)
assert {:error, changeset} = Fixtures.ValidateNumbers.new(Keyword.merge(params, neq: 1))
assert %{neq: ["must be not equal to 1"]} = changeset_errors(changeset)
assert {:error, changeset} = Fixtures.ValidateNumbers.new(Keyword.merge(params, range: 0))
assert %{range: ["must be in the range 1..100"]} = changeset_errors(changeset)
end
test "validate runs a validation pipeline if present" do
# The initial insert action should succeed because the validator which always fails,
# validate_content_type is only applied on updates which include changes to the content type
assert {:ok, strukt} =
Fixtures.ValidationPipelines.new(
filename: "foo.pdf",
content_type: "application/pdf"
)
# This should also succeed because the content type and filename match, and the content type wasn't changed,
# so the validate_content_type validator won't be run
assert {:ok, strukt} =
Fixtures.ValidationPipelines.change(strukt, filename: "bar.pdf")
|> Fixtures.ValidationPipelines.from_changeset()
# This will fail with two errors:
# - The validate_content_type disallows any changes to the content type
# - The ValidateFileAndContentType validator will reject a change with a mismatched filename/content type
assert {:error, changeset} =
Fixtures.ValidationPipelines.change(strukt, content_type: "application/json")
|> Fixtures.ValidationPipelines.from_changeset()
assert %{
content_type: [
"mismatched content type and file extension",
"cannot change content type"
]
} = changeset_errors(changeset)
# This will fail with one error:
# - The ValidateFileAndContentType validator will reject a change with a mismatched filename/content type
assert {:error, changeset} =
Fixtures.ValidationPipelines.change(strukt, filename: "bar.json")
|> Fixtures.ValidationPipelines.from_changeset()
assert %{filename: ["filename must match content type of file"]} = changeset_errors(changeset)
end
test "can generate simple type spec and nullable respect default/required setting" do
require Fixtures.TypeSpec
assert inspect(
Strukt.Typespec.generate(%Strukt.Typespec{
caller: Strukt.Test.Fixtures.TypeSpec,
fields: [:required_filed, :optional_field, :default_field, :default_nil_field],
info: %{
required_filed: %{type: :any, value_type: :integer, required: true, default: nil},
optional_field: %{
type: :any,
value_type: :integer,
required: false,
default: nil
},
default_field: %{type: :any, value_type: :integer, required: false, default: ""},
default_nil_field: %{
type: :any,
value_type: :integer,
required: false,
default: nil
}
},
embeds: []
})
) ==
Fixtures.TypeSpec.expected_type_spec_ast_str()
end
test "embeds_one nilable type" do
require Fixtures.EmbedsOneTypeSpec
assert inspect(
Strukt.Typespec.generate(%Strukt.Typespec{
caller: Strukt.Test.Fixtures.EmbedsOneTypeSpec,
fields: [],
info: %{
required_embeds_one: %{
type: :embeds_one,
value_type: :Aux,
required: true
},
optional_embeds_one: %{
type: :embeds_one,
value_type: :Aux
}
},
embeds: [:required_embeds_one, :optional_embeds_one]
})
) ==
Fixtures.EmbedsOneTypeSpec.expected_type_spec_ast_str()
end
defp changeset_errors(%Ecto.Changeset{} = cs) do
cs
|> Ecto.Changeset.traverse_errors(fn {msg, opts} ->
Enum.reduce(opts, msg, fn
{key, {:parameterized, Ecto.Enum, %{mappings: values}}}, acc ->
String.replace(acc, "%{#{key}}", values |> Keyword.values() |> Enum.join(", "))
{key, %Range{} = value}, acc ->
String.replace(acc, "%{#{key}}", inspect(value))
{key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)
end
end