-
Notifications
You must be signed in to change notification settings - Fork 0
/
seed_factory.ex
1612 lines (1356 loc) · 53.4 KB
/
seed_factory.ex
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule SeedFactory do
@moduledoc """
A toolkit for test data generation.
The main idea of `SeedFactory` is to generate data in tests according to your application business logic (read as
context functions if you use [Phoenix Contexts](https://hexdocs.pm/phoenix/contexts.html)) whenever it is possible
and avoid direct inserts to the database (as opposed to `ex_machina`).
This approach allows you to minimize testing of invalid states as you're not forced to keep complex database structure in your head in order to prepare test data.
The library is completely agnostic to the database toolkit.
**Context**, **entities** and **commands** are the core concepts of the library.
Context is a `t:map/0` which can be populated with entities using commands.
The schema with instructions on how commands modify context is described using DSL with the help of `SeedFactory.Schema` module.
Commands can be used to:
* produce entity (put new data in the context)
* update entity (replace the existing entity in the context)
* delete entity (remove the entity from the context)
When a command is executed, produced entities are assigned to the context using the name of the entity as a key.
A command has params with instructions on how to generate arguments for a resolver if they are not passed explicitly with `exec/3` function.
The instruction can be specified using one of these options:
* `:value` - any term. This option is used by default with the value of `nil`.
* `:generate` - a zero-arity function for generating data.
* `:entity` - an atom which points to an entity which should be taken from the context. If a required entity cannot
be found in a context, then `SeedFactory` automatically executes a corresponding command which produces the entity.
Entities can have traits.
Think about them as labels which are assigned to produced/updated entities when specific commands with specific arguments are executed.
Let's take a look at an example of a simple schema.
```elixir
defmodule MyApp.SeedFactorySchema do
use SeedFactory.Schema
command :create_company do
param :name, generate: &Faker.Company.name/0
resolve(fn args ->
with {:ok, company} <- MyApp.Companies.create_company(args) do
{:ok, %{company: company}}
end
end)
produce :company
end
command :create_user do
param :name, generate: &Faker.Person.name/0
param :role, value: :normal
param :company, entity: :company
resolve(fn args -> MyApp.Users.create_user(args.company, args.name, args.role) end)
produce :user
produce :profile
end
command :activate_user do
param :user, entity: :user, with_traits: [:pending]
resolve(fn args ->
user = MyApp.Users.activate_user!(args.user)
{:ok, %{user: user}}
end)
update :user
end
trait :pending, :user do
exec :create_user
end
trait :active, :user do
from :pending
exec :activate_user
end
trait :admin, :user do
exec :create_user, args_pattern: %{role: :admin}
end
trait :normal, :user do
exec :create_user, args_pattern: %{role: :normal}
end
end
```
The schema above describes how to produce 3 entities (`:company`, `:user` and `:profile`) using 2 commands (`:create_user` and `:create_company`).
There is a third command which only updates the `:user` entity.
There are 4 traits defined for the `:user` entity.
To start using the schema, put metadata about it to the context using `init/2` function:
```elixir
context = %{}
context = init(context, MyApp.SeedFactorySchema)
```
If you use `SeedFactory` in tests with `ExUnit`, check out `SeedFactory.Test`. This module adds initialization using `ExUnit.Callbacks.setup_all/2` callback
and imports functions.
Now, `exec/2` function can be used to execute a command:
```elixir
context = exec(context, :create_company)
```
The code above will generate arguments for `:create_company` command, execute a resolver with generated arguments and put company to context using `:company` key.
`exec/3` can be used if you want to specify parameters explicitly:
```elixir
context = exec(context, :create_company, name: "GitHub")
```
Because exec function returns `t:context/0`, it is convenient to chain `exec` calls with the pipe operator:
```elixir
context =
context
|> exec(:create_company)
|> exec(:create_user, name: "John Doe")
```
In order to get a value for the `:company` parameter of the `:create_user` command, the corresponding entity was taken from the context.
However, it is not necessary to do so, as `SeedFactory` can automatically execute commands which produce dependent entities.
The code above has the same effect as a single call to `:create_user` command:
```elixir
context = exec(context, :create_user, name: "John Doe")
```
If you're not interested in explicit providing of parameters to commands, then you can use `produce/2` function to produce
requested entities with automatic execution of all dependent commands:
```elixir
context = produce(context, :user)
```
Even though `:user` is the only entity specified explicitly, `context` will have 3 new keys: `:company`, `:user` and `:profile`.
> #### Tip {: .tip}
> It is recommended to explicitly specify all entities in which you're insterested:
> ```elixir
> # good
> %{user: user} = produce(contex, :user)
>
> # good
> %{user: user, profile: profile} = produce(contex, [:user, :profile])
>
> # good
> %{user: user, company: company} = produce(contex, [:user, :company])
>
> # bad
> %{user: user, profile: profile, company: company} = produce(contex, :user)
> ```
`exec/3` fails if produced entities are already present in the context.
It is possible to rebind entities in order to assign them to the context with different names:
```elixir
context =
context
|> rebind([user: :user1, profile: :profile1], &exec(&1, :create_user))
|> rebind([user: :user2, profile: :profile2], &exec(&1, :create_user))
```
The snippet above puts the following keys to the context: `:company`, `:user1`, `:profile1`, `:user2` and `:profile2`.
The `:company` is shared in this case, so two users have different profiles and belong to the same company.
A shorter counterpart using `produce/2` is the following:
```elixir
context =
context
|> produce(user: :user1, profile: :profile1)
|> produce(user: :user2, profile: :profile2)
```
As was pointed out previously, traits are assigned to entities when commands produce/update them.
`SeedFactory` does this automatically by tracking commands and arguments.
You can inspect `__seed_factory_meta__` key in the context to review currently assigned traits:
```elixir
context |> exec(:create_user) |> IO.inspect()
# %{
# __seed_factory_meta__: #SeedFactory.Meta<
# current_traits: %{user: [:normal, :pending]},
# ...
# >,
# ...
# }
context |> exec(:create_user, role: :admin) |> exec(:activate_user) |> IO.inspect()
# %{
# __seed_factory_meta__: #SeedFactory.Meta<
# current_traits: %{user: [:admin, :active]},
# ...
# >,
# ...
# }
```
The same result can be achieved by passing traits using `produce/2`:
```elixir
produce(context, user: [:admin, :active])
```
If you want to specify traits and assign an entity to the context with the different name, then use `:as` option:
```elixir
%{active_admin: active_admin} = produce(context, user: [:admin, :active, as: :active_admin])
```
"""
@type context :: map()
@type entity_name :: atom()
@type rebinding_rule :: {entity_name(), rebind_as :: atom()}
@doc """
Puts metadata about `schema` to `context`, so `context` becomes usable by other functions from this module.
## Example
iex> context = %{}
...> init(context, MySeedFactorySchema)
%{__seed_factory_meta__: #SeedFactory.Meta<...>}
"""
@spec init(context(), schema :: module) :: context()
def init(context, schema) do
Map.put(context, :__seed_factory_meta__, SeedFactory.Meta.new(schema))
end
@doc """
Changes default behaviour of entities assignment.
Modifies a context, so commands engage with entities in the context using provided names.
If a command requires/produces/updates/deletes an entity, the provided name will be used instead of the entity name to get value from the context or modify it.
It helps to produce the same entity multiple times and assign it to the context with different names.
## Example
# Let's assume that `:product` entity requires `:company` entity.
# In this example we create 2 companies, `:product1` will be linked to `:company1`.
%{company1: _, company2: _, product1: _} =
context
|> rebind([company: :company1, product: :product1], fn context ->
context
|> exec(:create_company, name: "GitHub")
|> produce(:product)
end)
|> rebind([company: :company2], fn context ->
exec(context, :create_company, name: "Microsoft")
end)
"""
@spec rebind(context(), [rebinding_rule()], (context() -> context())) :: context()
def rebind(context, rebinding, callback) when is_function(callback, 1) do
ensure_entities_exist_in_rebinding_rules!(context.__seed_factory_meta__.entities, rebinding)
do_rebind(context, rebinding, callback)
end
defp ensure_entities_exist_in_rebinding_rules!(entities, rebinding) do
for {entity_name, _rebind_as} <- rebinding do
if not Map.has_key?(entities, entity_name) do
raise ArgumentError, "Unknown entity #{inspect(entity_name)}"
end
end
end
defp do_rebind(context, rebinding, callback) do
case rebinding do
[] ->
callback.(context)
rebinding ->
current_rebinding = context.__seed_factory_meta__.entities_rebinding
new_rebinding = merge_rebinding!(current_rebinding, Map.new(rebinding))
context
|> put_meta(:entities_rebinding, new_rebinding)
|> callback.()
|> put_meta(:entities_rebinding, current_rebinding)
end
end
defp merge_rebinding!(current_rebinding, new_rebinding) do
Map.merge(
current_rebinding,
new_rebinding,
fn
_key, v, v ->
v
key, v1, v2 ->
raise ArgumentError,
"Rebinding conflict. Cannot rebind `#{inspect(key)}` to `#{inspect(v2)}`. Current value `#{inspect(v1)}`."
end
)
end
@doc """
Produces entities if they don't exist in the context.
The order of specified entities doesn't matter.
It invokes a series of commands to produce entities with specified traits.
If the same entity can be produced by multiple commands, then the first declared command is used by default.
In order to produce the entity using the rest of the commands use traits or `exec/3` explicitly.
## Examples
# specify a single entity
%{user: _} = produce(context, :user)
# specify a list of entitities
%{user: _, company: _} = produce(context, [:user, :company])
# rebind :user entity as :user1
%{user1: _} = produce(context, user: :user1)
# specify traits
%{user: _} = produce(context, user: [:active, :admin])
%{user: _} = context |> produce(user: [:pending, :admin]) |> produce(user: [:active])
# specify traits and :as option
%{user1: _} = produce(context, user: [:active, :admin, as: :user1])
"""
@spec produce(
context(),
entity_name()
| [
entity_name()
| rebinding_rule()
| {entity_name(), [trait_name :: atom() | {:as, rebind_as :: atom()}]}
]
) :: context()
def produce(context, entities_and_rebinding) when is_list(entities_and_rebinding) do
{entities_with_trait_names, rebinding} = split_entities_and_rebinding(entities_and_rebinding)
do_rebind(context, rebinding, fn context ->
requirements =
init_requirements()
|> collect_requirements_for_entities_with_trait_names(
context,
entities_with_trait_names,
nil,
build_restrictions(context, entities_with_trait_names)
)
|> resolve_conflicts()
lock_creation_of_dependent_entities(context, &exec_requirements(requirements, &1))
end)
end
def produce(context, entity) when is_atom(entity) do
produce(context, [entity])
end
@doc """
Produces dependencies needed for specified entities.
See `pre_exec/3` for problems it solves.
## Example
# pre_produce produces a company and puts it into context,
# so produced user1 and user2 will belong to the same company
context = pre_produce(context, :user)
%{user: user1} = produce(context, :user)
%{user: user2} = produce(context, :user)
"""
@spec pre_produce(
context(),
entity_name()
| [
entity_name()
| rebinding_rule()
| {entity_name(), [trait_name :: atom() | {:as, rebind_as :: atom()}]}
]
) :: context()
def pre_produce(context, entities_and_rebinding) when is_list(entities_and_rebinding) do
{entities_with_trait_names, rebinding} = split_entities_and_rebinding(entities_and_rebinding)
do_rebind(context, rebinding, fn context ->
requirements =
init_requirements()
|> collect_requirements_for_entities_with_trait_names(
context,
entities_with_trait_names,
nil,
build_restrictions(context, entities_with_trait_names)
)
|> resolve_conflicts()
|> delete_requirements_which_are_requested_explicitly()
lock_creation_of_dependent_entities(context, &exec_requirements(requirements, &1))
end)
end
def pre_produce(context, entity) when is_atom(entity) do
pre_produce(context, [entity])
end
defp delete_requirements_which_are_requested_explicitly(requirements) do
Enum.reduce(requirements.commands, requirements, fn {command_name, data}, acc ->
if requested_explicitly?(data) do
delete_requirement(acc, command_name)
else
acc
end
end)
end
defp requested_explicitly?(data) do
nil in data.required_by
end
defp delete_requirement(requirements, command_name_to_delete) do
case requirements.commands[command_name_to_delete] do
nil ->
requirements
data ->
Enum.reduce(
data.required_by,
%{requirements | commands: Map.delete(requirements.commands, command_name_to_delete)},
&delete_requirement(&2, &1)
)
end
end
defp split_entities_and_rebinding(entities_and_rebinding) do
Enum.map_reduce(entities_and_rebinding, [], fn
{entity_name, rebind_as} = rebinding_rule, acc when is_atom(rebind_as) ->
{{entity_name, []}, [rebinding_rule | acc]}
{entity_name, list}, acc when is_list(list) ->
{trait_names, opts} = Enum.split_while(list, &is_atom/1)
acc =
case opts[:as] do
nil -> acc
rebind_as -> [{entity_name, rebind_as} | acc]
end
{{entity_name, trait_names}, acc}
entity_name, acc ->
{{entity_name, []}, acc}
end)
end
defp anything_was_produced_by_command?(context, command) do
Enum.any?(command.producing_instructions, fn instruction ->
binding_name = binding_name(context, instruction.entity)
Map.has_key?(context, binding_name)
end)
end
defp collect_requirements_for_command(
requirements,
context,
command,
initial_input,
required_by,
restrictions
) do
entities_with_trait_names = parameter_requirements(command, initial_input)
collect_requirements_for_entities_with_trait_names(
requirements,
context,
entities_with_trait_names,
required_by,
restrictions
)
end
defp collect_requirements_for_entities_with_trait_names(
requirements,
_context,
entities_with_trait_names,
_required_by,
_limitations
)
when map_size(entities_with_trait_names) == 0 do
requirements
end
defp collect_requirements_for_entities_with_trait_names(
initial_requirements,
context,
entities_with_trait_names,
required_by,
restrictions
) do
{requirements, command_names} =
Enum.reduce(
entities_with_trait_names,
{initial_requirements, MapSet.new()},
fn {entity_name, trait_names}, {requirements, command_names} = acc ->
# duplicated values are produced by parameter_requirements function after recursive calls to
# `collect_requirements_for_command` function
trait_names = Enum.uniq(trait_names)
binding_name = binding_name(context, entity_name)
if Map.has_key?(context, binding_name) do
if trait_names == [] do
acc
else
current_trait_names = current_trait_names(context, binding_name)
absent_trait_names = trait_names -- current_trait_names
if absent_trait_names == [] do
acc
else
%{by_name: trait_by_name} = fetch_traits!(context, entity_name)
trail =
context.__seed_factory_meta__.trails[binding_name] ||
raise """
Can't find trail for #{inspect(binding_name)} entity.
Please don't put entities that can have traits manually in the context.
"""
currently_executed =
if current_trait_names == [] do
%{trail.produced_by => %{}}
else
current_trait_names
|> select_traits_with_dependencies_by_names(
trait_by_name,
entity_name,
trail
)
|> ensure_no_restrictions!(restrictions, entity_name, :current)
|> executed_commands_from_traits()
end
absent_trait_names
|> select_traits_with_dependencies_by_names(
trait_by_name,
entity_name,
context.__seed_factory_meta__.trails[entity_name]
)
|> Enum.group_by(& &1.exec_step.command_name)
|> Enum.reduce(acc, fn {command_name, traits},
{requirements, command_names} = acc ->
case currently_executed[command_name] do
nil ->
{add_non_conflicting_command_to_requirements(
requirements,
command_name,
required_by,
traits
), MapSet.put(command_names, command_name)}
already_applied_args ->
args = squash_args(traits)
if deep_equal_maps?(args, already_applied_args) do
acc
else
raise ArgumentError, """
Args to previously executed command #{inspect(command_name)} do not match:
args from previously applied traits: #{inspect(already_applied_args)}
args for specified traits: #{inspect(args)}
"""
end
end
end)
end
end
else
if trait_names == [] do
restrictions.traits
|> Enum.filter(fn trait ->
context
|> fetch_command_by_name!(trait.exec_step.command_name)
|> command_produces?(entity_name)
end)
|> Enum.group_by(& &1.exec_step.command_name)
|> Enum.to_list()
|> case do
[] ->
command_names_that_can_produce_entity =
fetch_command_names_by_entity_name!(context, entity_name)
{requirements, added_command_names} =
add_conflicting_commands_to_requirements(
requirements,
command_names_that_can_produce_entity,
required_by
)
{requirements, MapSet.union(command_names, added_command_names)}
[{command_name, traits}] ->
{add_non_conflicting_command_to_requirements(
requirements,
command_name,
required_by,
traits
), MapSet.put(command_names, command_name)}
end
else
%{by_name: trait_by_name} = fetch_traits!(context, entity_name)
{acc, _} =
trait_names
|> select_traits_with_dependencies_by_names(
trait_by_name,
entity_name,
context.__seed_factory_meta__.trails[entity_name]
)
|> ensure_no_restrictions!(restrictions, entity_name, :new)
|> Enum.reduce({acc, nil}, fn trait,
{{requirements, command_names},
previous_command_name} ->
dependency_for_previous_trait? = trait.name not in trait_names
required_by =
if dependency_for_previous_trait? do
previous_command_name
else
required_by
end
command_name = trait.exec_step.command_name
{{add_non_conflicting_command_to_requirements(
requirements,
command_name,
required_by,
[trait]
), MapSet.put(command_names, command_name)}, command_name}
end)
acc
end
end
end
)
Enum.reduce(command_names, requirements, fn command_name, requirements ->
command = Map.fetch!(context.__seed_factory_meta__.commands, command_name)
added_to_requirements_in_previous_iterations? =
Map.has_key?(initial_requirements.commands, command_name)
removed_from_requirements_in_current_iteration? =
not Map.has_key?(requirements.commands, command_name)
if added_to_requirements_in_previous_iterations? or
removed_from_requirements_in_current_iteration? or
anything_was_produced_by_command?(context, command) do
requirements
else
collect_requirements_for_command(
requirements,
context,
command,
%{},
command.name,
restrictions
)
end
end)
end
defp command_produces?(command, entity_name) do
Enum.any?(command.producing_instructions, fn instruction ->
instruction.entity == entity_name
end)
end
defp fetch_command_by_name!(context, command_name) do
case Map.fetch(context.__seed_factory_meta__.commands, command_name) do
{:ok, command} -> command
:error -> raise ArgumentError, "Unknown command #{inspect(command_name)}"
end
end
defp fetch_command_names_by_entity_name!(context, entity_name) do
case Map.fetch(context.__seed_factory_meta__.entities, entity_name) do
{:ok, command_names} -> command_names
:error -> raise ArgumentError, "Unknown entity #{inspect(entity_name)}"
end
end
defp ensure_no_restrictions!(traits, restrictions, entity_name, scenario) do
case restrictions.trait_names_by_entity do
%{^entity_name => requested_trait_names} ->
case Enum.find(traits, fn
%SeedFactory.Trait{from: nil} -> false
%SeedFactory.Trait{from: from} -> from in requested_trait_names
end) do
nil ->
traits
trait ->
message =
case scenario do
:new ->
"""
Cannot apply trait #{inspect(trait.name)} to entity #{inspect(entity_name)}.
The entity was requested with the following traits: #{inspect(requested_trait_names)}
"""
:current ->
"""
Cannot apply traits #{inspect(requested_trait_names)} to entity #{inspect(entity_name)}.
The entity already exists with traits that depend on requested ones.
"""
end
raise ArgumentError, message
end
_ ->
traits
end
end
defp add_conflicting_commands_to_requirements(requirements, [command_name], required_by) do
{add_non_conflicting_command_to_requirements(requirements, command_name, required_by, []),
MapSet.new([command_name])}
end
defp add_conflicting_commands_to_requirements(requirements, command_names, required_by) do
# if the command can be found in requirements, and it doesn't have any conflict, it means, that it was requested
# without ambiguity, so we can skip conflict resolution for the command
case Enum.find(
command_names,
fn command_name ->
Map.has_key?(requirements.commands, command_name) and
not command_or_anything_in_vertical_conflicts?(
requirements.commands,
command_name
)
end
) do
nil ->
case analyze_conflict_group(requirements, command_names) do
:new_group ->
requirements =
command_names
|> Enum.reduce(requirements, fn command_name, requirements ->
add_conflicting_command_to_requirements(
requirements,
command_name,
required_by,
command_names
)
end)
|> Map.update!(:unresolved_conflict_groups, &[command_names | &1])
{requirements, MapSet.new(command_names)}
:exists ->
requirements = link_commands(requirements, command_names, required_by)
{requirements, MapSet.new([])}
{:is_subset, diff} ->
requirements =
diff
|> Enum.reduce(requirements, &remove_command(&2, &1))
|> link_commands(command_names, required_by)
{requirements, MapSet.new([])}
{:contains_subset, subset} ->
requirements = link_commands(requirements, subset, required_by)
{requirements, MapSet.new([])}
end
command_name ->
requirements = link_commands(requirements, command_name, required_by)
{requirements, MapSet.new()}
end
end
defp analyze_conflict_group(requirements, conflict_group_to_analyze) do
unresolved_conflict_groups = requirements.unresolved_conflict_groups
conflict_group_to_analyze_mapset = MapSet.new(conflict_group_to_analyze)
Enum.find_value(unresolved_conflict_groups, :new_group, fn unresolved_conflict_group ->
unresolved_conflict_group_mapset = MapSet.new(unresolved_conflict_group)
cond do
conflict_group_to_analyze == unresolved_conflict_group ->
:exists
MapSet.subset?(conflict_group_to_analyze_mapset, unresolved_conflict_group_mapset) ->
{:is_subset,
MapSet.difference(unresolved_conflict_group_mapset, conflict_group_to_analyze_mapset)}
MapSet.subset?(unresolved_conflict_group_mapset, conflict_group_to_analyze_mapset) ->
{:contains_subset, unresolved_conflict_group}
true ->
false
end
end)
end
defp command_or_anything_in_vertical_conflicts?(commands, command_name) do
data = commands[command_name]
data.conflict_groups != [] or anything_in_vertical_conflicts?(commands, command_name)
end
defp anything_in_vertical_conflicts?(commands, command_name) do
data = commands[command_name]
Enum.any?(data.required_by, fn
nil -> false
command_name -> command_or_anything_in_vertical_conflicts?(commands, command_name)
end)
end
defp add_non_conflicting_command_to_requirements(
requirements,
command_name,
required_by,
traits
) do
case requirements.commands do
%{^command_name => data} ->
requirements
|> update_in(
[:commands, command_name],
&%{
&1
| args: squash_args(traits, &1.args),
required_by: MapSet.put(&1.required_by, required_by)
}
)
|> add_command_name_to_requires_field(required_by, command_name)
|> auto_resolve_conflict_if_possible(command_name, data.conflict_groups)
_ ->
add_new_command_to_requirements(requirements, command_name, %{
conflict_groups: [],
traits: traits,
required_by: required_by
})
end
end
defp auto_resolve_conflict_if_possible(requirements, command_name, conflict_groups) do
has_conflict? = conflict_groups != []
if has_conflict? and
not anything_in_vertical_conflicts?(requirements.commands, command_name) do
resolve_conflicts_in_favour_of_the_command(requirements, command_name)
else
requirements
end
end
defp add_conflicting_command_to_requirements(
requirements,
command_name,
required_by,
conflict_group
) do
if Map.has_key?(requirements.commands, command_name) do
requirements
|> update_in(
[:commands, command_name],
&%{
&1
| required_by: MapSet.put(&1.required_by, required_by),
conflict_groups: [conflict_group | &1.conflict_groups]
}
)
|> add_command_name_to_requires_field(required_by, command_name)
else
add_new_command_to_requirements(requirements, command_name, %{
conflict_groups: [conflict_group],
traits: [],
required_by: required_by
})
end
end
defp add_new_command_to_requirements(requirements, command_name, params) do
requirements
|> put_in([:commands, command_name], %{
conflict_groups: params.conflict_groups,
requires: MapSet.new(),
args: squash_args(params.traits),
required_by: MapSet.new([params.required_by])
})
|> add_command_name_to_requires_field(params.required_by, command_name)
end
defp link_commands(requirements, command_names, required_by) when is_list(command_names) do
Enum.reduce(command_names, requirements, &link_commands(&2, &1, required_by))
end
defp link_commands(requirements, command_name, required_by) do
requirements
|> add_command_name_to_required_by_field(command_name, required_by)
|> add_command_name_to_requires_field(required_by, command_name)
end
defp add_command_name_to_required_by_field(requirements, command_name, command_name_to_add) do
update_in(
requirements,
[:commands, command_name, :required_by],
&MapSet.put(&1, command_name_to_add)
)
end
defp add_command_name_to_requires_field(requirements, command_name, command_name_to_add) do
case command_name do
nil ->
requirements
command_name ->
update_in(
requirements,
[:commands, command_name, :requires],
&MapSet.put(&1, command_name_to_add)
)
end
end
defp parameter_requirements(command, initial_input) do
parameter_requirements(command.params, %{}, initial_input)
end
defp parameter_requirements(params, acc, initial_input) do
Enum.reduce(params, acc, fn {key, parameter}, acc ->
case parameter.type do
:container ->
parameter_requirements(parameter.params, acc, initial_input)
:entity ->
if Map.has_key?(initial_input, key) do
acc
else
trait_names = parameter.with_traits || []
Map.update(acc, parameter.entity, trait_names, &(trait_names ++ &1))
end
_ ->
acc
end
end)
end
defp fetch_traits!(context, entity_name) do
case Map.fetch(context.__seed_factory_meta__.traits, entity_name) do
{:ok, value} -> value
:error -> raise ArgumentError, "Entity #{inspect(entity_name)} doesn't have traits"
end
end
defp executed_commands_from_traits(traits) do
traits
|> Enum.group_by(& &1.exec_step.command_name)
|> Map.new(fn {command_name, traits} -> {command_name, squash_args(traits)} end)
end
defp select_traits_with_dependencies_by_names(trait_names, trait_by_name, entity_name, trail) do
Enum.flat_map(trait_names, fn trait_name ->
case Map.fetch(trait_by_name, trait_name) do
{:ok, trait} ->
resolve_trait_depedencies(trait, trait_by_name, trail)
:error ->
raise ArgumentError,
"Entity #{inspect(entity_name)} doesn't have trait #{inspect(trait_name)}"
end
end)
end
defp squash_args(traits, initial_args \\ %{}) do
Enum.reduce(traits, initial_args, fn trait, acc ->
case trait.exec_step do
%{args_pattern: nil, generate_args: nil, args_match: nil} ->
acc
%{args_pattern: pattern} when is_map(pattern) ->
try do
deep_merge_maps!(acc, pattern, [])
catch
{:conflict, v1, v2, path} ->
raise ArgumentError, """
Cannot merge arguments generated by traits for command #{inspect(trait.exec_step.command_name)}.
Path: #{inspect(path)}
Value 1: #{inspect(v1)}
Value 2: #{inspect(v2)}
"""
end
%{generate_args: generate_args, args_match: args_match} ->
try do
deep_merge_maps!(acc, generate_args.(), [])
catch
{:conflict, _v1, _v2, _path} ->
if args_match.(acc) do
acc
else
raise ArgumentError, """
Cannot apply trait #{inspect(trait.name)} of entity #{inspect(trait.entity)} to generated args for command #{inspect(trait.exec_step.command_name)}.
Generated args: #{inspect(acc)}
"""