-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathtest_macros.py
1212 lines (987 loc) · 41.3 KB
/
test_macros.py
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
import inspect
from typing import List, Set
import pandas as pd
import pytest
import hamilton.function_modifiers
from hamilton import async_driver, base, driver, function_modifiers, models, node
from hamilton.function_modifiers import does
from hamilton.function_modifiers.dependencies import source, value
from hamilton.function_modifiers.macros import (
Applicable,
apply_to,
ensure_function_empty,
mutate,
pipe_input,
pipe_output,
step,
)
from hamilton.node import DependencyType
import tests.resources.mutate
import tests.resources.mutate_async
import tests.resources.pipe_async
import tests.resources.pipe_input
import tests.resources.pipe_output
def test_no_code_validator():
def no_code():
pass
def no_code_with_docstring():
"""This should still show up as having no code, even though it has a docstring"""
pass
def yes_code():
"""This should show up as having no code"""
a = 0
return a
ensure_function_empty(no_code)
ensure_function_empty(no_code_with_docstring)
with pytest.raises(hamilton.function_modifiers.base.InvalidDecoratorException):
ensure_function_empty(yes_code)
# Functions for @does -- these are the functions we're "replacing"
def _no_params() -> int:
pass
def _one_param(a: int) -> int:
pass
def _two_params(a: int, b: int) -> int:
pass
def _three_params(a: int, b: int, c: int) -> int:
pass
def _three_params_with_defaults(a: int, b: int = 1, c: int = 2) -> int:
pass
def _empty() -> int:
return 1
def _kwargs(**kwargs: int) -> int:
return sum(kwargs.values())
def _kwargs_with_a(a: int, **kwargs: int) -> int:
return a + sum(kwargs.values())
def _just_a(a: int) -> int:
return a
def _just_b(b: int) -> int:
return b
def _a_b_c(a: int, b: int, c: int) -> int:
return a + b + c
@pytest.mark.parametrize(
"fn,replace_with,argument_mapping,matches",
[
(_no_params, _empty, {}, True),
(_no_params, _kwargs, {}, True),
(_no_params, _kwargs_with_a, {}, False),
(_no_params, _just_a, {}, False),
(_no_params, _a_b_c, {}, False),
(_one_param, _empty, {}, False),
(_one_param, _kwargs, {}, True),
(_one_param, _kwargs_with_a, {}, True),
(_one_param, _just_a, {}, True),
(_one_param, _just_b, {}, False),
(_one_param, _just_b, {"b": "a"}, True), # Replacing a with b makes the signatures match
(_one_param, _just_b, {"c": "a"}, False), # Replacing a with b makes the signatures match
(_two_params, _empty, {}, False),
(_two_params, _kwargs, {}, True),
(_two_params, _kwargs_with_a, {}, True), # b gets fed to kwargs
(_two_params, _kwargs_with_a, {"foo": "b"}, True), # Any kwargs work
(_two_params, _kwargs_with_a, {"bar": "a"}, False), # No param bar
(_two_params, _just_a, {}, False),
(_two_params, _just_b, {}, False),
(_three_params, _a_b_c, {}, True),
(_three_params, _a_b_c, {"d": "a"}, False),
(_three_params, _a_b_c, {}, True),
(_three_params, _a_b_c, {"a": "b", "b": "a"}, True), # Weird case but why not?
(_three_params, _kwargs_with_a, {}, True),
(_three_params_with_defaults, _a_b_c, {}, True),
(_three_params_with_defaults, _a_b_c, {"d": "a"}, False),
(_three_params_with_defaults, _a_b_c, {}, True),
],
)
def test_ensure_function_signatures_compatible(fn, replace_with, argument_mapping, matches):
assert (
does.test_function_signatures_compatible(
inspect.signature(fn), inspect.signature(replace_with), argument_mapping
)
== matches
)
def test_does_function_modifier():
def sum_(**kwargs: int) -> int:
return sum(kwargs.values())
def to_modify(param1: int, param2: int) -> int:
"""This sums the inputs it gets..."""
pass
annotation = does(sum_)
(node_,) = annotation.generate_nodes(to_modify, {})
assert node_.name == "to_modify"
assert node_.callable(param1=1, param2=1) == 2
assert node_.documentation == to_modify.__doc__
def test_does_function_modifier_complex_types():
def setify(**kwargs: List[int]) -> Set[int]:
return set(sum(kwargs.values(), []))
def to_modify(param1: List[int], param2: List[int]) -> int:
"""This sums the inputs it gets..."""
pass
annotation = does(setify)
(node_,) = annotation.generate_nodes(to_modify, {})
assert node_.name == "to_modify"
assert node_.callable(param1=[1, 2, 3], param2=[4, 5, 6]) == {1, 2, 3, 4, 5, 6}
assert node_.documentation == to_modify.__doc__
def test_does_function_modifier_optionals():
def sum_(param0: int, **kwargs: int) -> int:
return sum(kwargs.values())
def to_modify(param0: int, param1: int = 1, param2: int = 2) -> int:
"""This sums the inputs it gets..."""
pass
annotation = does(sum_)
(node_,) = annotation.generate_nodes(to_modify, {})
assert node_.name == "to_modify"
assert node_.input_types["param0"][1] == DependencyType.REQUIRED
assert node_.input_types["param1"][1] == DependencyType.OPTIONAL
assert node_.input_types["param2"][1] == DependencyType.OPTIONAL
assert node_.callable(param0=0) == 3
assert node_.callable(param0=0, param1=0, param2=0) == 0
assert node_.documentation == to_modify.__doc__
def test_does_with_argument_mapping():
def _sum_multiply(param0: int, param1: int, param2: int) -> int:
return param0 + param1 * param2
def to_modify(parama: int, paramb: int = 1, paramc: int = 2) -> int:
"""This sums the inputs it gets..."""
pass
annotation = does(_sum_multiply, param0="parama", param1="paramb", param2="paramc")
(node_,) = annotation.generate_nodes(to_modify, {})
assert node_.name == "to_modify"
assert node_.input_types["parama"][1] == DependencyType.REQUIRED
assert node_.input_types["paramb"][1] == DependencyType.OPTIONAL
assert node_.input_types["paramc"][1] == DependencyType.OPTIONAL
assert node_.callable(parama=0) == 2
assert node_.callable(parama=0, paramb=1, paramc=2) == 2
assert node_.callable(parama=1, paramb=4) == 9
assert node_.documentation == to_modify.__doc__
def test_model_modifier():
config = {
"my_column_model_params": {
"col_1": 0.5,
"col_2": 0.5,
}
}
class LinearCombination(models.BaseModel):
def get_dependents(self) -> List[str]:
return list(self.config_parameters.keys())
def predict(self, **columns: pd.Series) -> pd.Series:
return sum(
self.config_parameters[column_name] * column
for column_name, column in columns.items()
)
def my_column() -> pd.Series:
"""Column that will be annotated by a model"""
pass
annotation = function_modifiers.model(LinearCombination, "my_column_model_params")
annotation.validate(my_column)
(model_node,) = annotation.generate_nodes(my_column, config)
assert model_node.input_types["col_1"][0] == model_node.input_types["col_2"][0] == pd.Series
assert model_node.type == pd.Series
pd.testing.assert_series_equal(
model_node.callable(col_1=pd.Series([1]), col_2=pd.Series([2])), pd.Series([1.5])
)
def bad_model(col_1: pd.Series, col_2: pd.Series) -> pd.Series:
return col_1 * 0.5 + col_2 * 0.5
with pytest.raises(hamilton.function_modifiers.base.InvalidDecoratorException):
annotation.validate(bad_model)
def _test_apply_function(foo: int, bar: int, baz: int = 100) -> int:
return foo + bar + baz
@pytest.mark.parametrize(
"args,kwargs,chain_first_param",
[
([source("foo_upstream"), value(1)], {}, False),
([value(1)], {}, True),
([source("foo_upstream"), value(1), value(2)], {}, False),
([value(1), value(2)], {}, True),
([source("foo_upstream")], {"bar": value(1)}, False),
([], {"bar": value(1)}, True),
([], {"foo": source("foo_upstream"), "bar": value(1)}, False),
([], {"bar": value(1)}, True),
([], {"foo": source("foo_upstream"), "bar": value(1), "baz": value(1)}, False),
([], {"bar": value(1), "baz": value(1)}, True),
],
)
def test_applicable_validates_correctly(args, kwargs, chain_first_param: bool):
applicable = Applicable(_test_apply_function, args=args, kwargs=kwargs)
applicable.validate(chain_first_param=chain_first_param, allow_custom_namespace=True)
@pytest.mark.parametrize(
"args,kwargs,chain_first_param",
[
(
[source("foo_upstream"), value(1)],
{"foo": source("foo_upstream")},
True,
), # We chain the first parameter, not pass it in
([value(1)], {}, False), # Not enough first parameters
([source("foo_upstream"), value(1), value(2)], {}, True),
([value(2)], {"foo": source("foo_upstream")}, False),
([source("foo_upstream")], {"bar": value(1)}, True),
([], {"bar": value(1)}, False),
([], {"foo": source("foo_upstream"), "bar": value(1)}, True),
([], {"bar": value(1)}, False),
([], {"foo": source("foo_upstream"), "bar": value(1), "baz": value(1)}, True),
([], {"bar": value(1), "baz": value(1)}, False),
],
)
def test_applicable_does_not_validate(args, kwargs, chain_first_param: bool):
with pytest.raises(hamilton.function_modifiers.base.InvalidDecoratorException):
applicable = Applicable(_test_apply_function, args=args, kwargs=kwargs)
applicable.validate(chain_first_param=chain_first_param, allow_custom_namespace=True)
def test_applicable_does_not_validate_invalid_function_pos_only():
def foo(a: int, /, b: int) -> int:
return a + b
with pytest.raises(hamilton.function_modifiers.base.InvalidDecoratorException):
applicable = Applicable(foo, args=(source("a"), source("b")), kwargs={})
applicable.validate(chain_first_param=True, allow_custom_namespace=True)
# We will likely start supporting this in the future, but for now we don't
def test_applicable_does_not_validate_no_param_type_hints():
def foo(a, b) -> int:
return a + b
with pytest.raises(hamilton.function_modifiers.base.InvalidDecoratorException):
applicable = Applicable(foo, args=(source("a"), source("b")), kwargs={})
applicable.validate(chain_first_param=True, allow_custom_namespace=True)
def test_applicable_does_not_validate_no_return_type_hints():
def foo(a: int, b: int):
return a + b
with pytest.raises(hamilton.function_modifiers.base.InvalidDecoratorException):
applicable = Applicable(foo, args=(source("a"), source("b")), kwargs={})
applicable.validate(chain_first_param=True, allow_custom_namespace=True)
def test_applicable_does_not_validate_invalid_function_no_params():
def foo() -> int:
return 1
with pytest.raises(hamilton.function_modifiers.base.InvalidDecoratorException):
applicable = Applicable(foo, args=(), kwargs={})
applicable.validate(chain_first_param=True, allow_custom_namespace=True)
def general_downstream_function(result: int) -> int:
return result
def function_multiple_same_type_params(p1: int, p2: int, p3: int) -> int:
return p1 + p2 + p3
# TODO: in case of multiple paramters need some type checking
# def function_multiple_diverse_type_params(p1: int, p2: str, p3: int) -> int:
# return p1 + len(p2) + p3
def test_pipe_input_on_input_error_unless_string_or_none():
with pytest.raises(NotImplementedError):
decorator = pipe_input( # noqa
step(_test_apply_function, source("bar_upstream"), baz=value(10)).named("node_1"),
step(_test_apply_function, source("bar_upstream"), baz=value(100)).named("node_2"),
step(_test_apply_function, source("bar_upstream"), baz=value(1000)).named("node_3"),
on_input=["p2", "p3"],
namespace="abc",
)
def test_pipe_input_mapping_args_targets_global():
n = node.Node.from_fn(function_multiple_same_type_params)
decorator = pipe_input(
step(_test_apply_function, source("bar_upstream"), baz=value(10)).named("node_1"),
step(_test_apply_function, source("bar_upstream"), baz=value(100)).named("node_2"),
step(_test_apply_function, source("bar_upstream"), baz=value(1000)).named("node_3"),
on_input="p2",
namespace="abc",
)
nodes = decorator.transform_dag([n], {}, function_multiple_same_type_params)
nodes_by_name = {item.name: item for item in nodes}
chain_node = nodes_by_name["abc.node_1"]
assert chain_node(p2=1, bar_upstream=3) == 14
# TODO: multiple parameter tests
# def test_pipe_input_no_namespace_with_target():
# n = node.Node.from_fn(function_multiple_diverse_type_params)
# decorator = pipe_input(
# step(_test_apply_function, source("bar_upstream"), baz=value(10))
# .on_input(["p1", "p3"])
# .named("node_1"),
# step(_test_apply_function, source("bar_upstream"), baz=value(100)).named("node_2"),
# step(_test_apply_function, source("bar_upstream"), baz=value(1000))
# .on_input("p3")
# .named("node_3"),
# on_input="p2",
# namespace=None,
# )
# nodes = decorator.transform_dag([n], {}, function_multiple_diverse_type_params)
# final_node = nodes[0].name
# p1_node = nodes[1].name
# p2_node1 = nodes[2].name
# p2_node2 = nodes[3].name
# p2_node3 = nodes[4].name
# p3_node1 = nodes[5].name
# p3_node2 = nodes[6].name
# assert final_node == "function_multiple_diverse_type_params"
# assert p1_node == "p1.node_1"
# assert p2_node1 == "p2.node_1"
# assert p2_node2 == "p2.node_2"
# assert p2_node3 == "p2.node_3"
# assert p3_node1 == "p3.node_1"
# assert p3_node2 == "p3.node_3"
# def test_pipe_input_elipsis_namespace_with_target():
# n = node.Node.from_fn(function_multiple_diverse_type_params)
# decorator = pipe_input(
# step(_test_apply_function, source("bar_upstream"), baz=value(10))
# .on_input(["p1", "p3"])
# .named("node_1"),
# step(_test_apply_function, source("bar_upstream"), baz=value(100)).named("node_2"),
# step(_test_apply_function, source("bar_upstream"), baz=value(1000))
# .on_input("p3")
# .named("node_3"),
# namespace=...,
# on_input="p2",
# )
# nodes = decorator.transform_dag([n], {}, function_multiple_diverse_type_params)
# final_node = nodes[0].name
# p1_node = nodes[1].name
# p2_node1 = nodes[2].name
# p2_node2 = nodes[3].name
# p2_node3 = nodes[4].name
# p3_node1 = nodes[5].name
# p3_node2 = nodes[6].name
# assert final_node == "function_multiple_diverse_type_params"
# assert p1_node == "p1.node_1"
# assert p2_node1 == "p2.node_1"
# assert p2_node2 == "p2.node_2"
# assert p2_node3 == "p2.node_3"
# assert p3_node1 == "p3.node_1"
# assert p3_node2 == "p3.node_3"
# def test_pipe_input_custom_namespace_with_target():
# n = node.Node.from_fn(function_multiple_diverse_type_params)
# decorator = pipe_input(
# step(_test_apply_function, source("bar_upstream"), baz=value(10))
# .on_input(["p1", "p3"])
# .named("node_1"),
# step(_test_apply_function, source("bar_upstream"), baz=value(100)).named("node_2"),
# step(_test_apply_function, source("bar_upstream"), baz=value(1000))
# .on_input("p3")
# .named("node_3"),
# namespace="abc",
# on_input="p2",
# )
# nodes = decorator.transform_dag([n], {}, function_multiple_diverse_type_params)
# final_node = nodes[0].name
# p1_node = nodes[1].name
# p2_node1 = nodes[2].name
# p2_node2 = nodes[3].name
# p2_node3 = nodes[4].name
# p3_node1 = nodes[5].name
# p3_node2 = nodes[6].name
# assert final_node == "function_multiple_diverse_type_params"
# assert p1_node == "abc_p1.node_1"
# assert p2_node1 == "abc_p2.node_1"
# assert p2_node2 == "abc_p2.node_2"
# assert p2_node3 == "abc_p2.node_3"
# assert p3_node1 == "abc_p3.node_1"
# assert p3_node2 == "abc_p3.node_3"
# def test_pipe_input_mapping_args_targets_local():
# n = node.Node.from_fn(function_multiple_diverse_type_params)
# decorator = pipe_input(
# step(_test_apply_function, source("bar_upstream"), baz=value(10))
# .on_input(["p1", "p3"])
# .named("node_1"),
# step(_test_apply_function, source("bar_upstream"), baz=value(100))
# .on_input("p2")
# .named("node_2"),
# step(_test_apply_function, source("bar_upstream"), baz=value(1000))
# .on_input("p3")
# .named("node_3"),
# namespace="abc",
# )
# nodes = decorator.transform_dag([n], {}, function_multiple_diverse_type_params)
# nodes_by_name = {item.name: item for item in nodes}
# chain_node_1 = nodes_by_name["abc_p1.node_1"]
# chain_node_2 = nodes_by_name["abc_p2.node_2"]
# chain_node_3_first = nodes_by_name["abc_p3.node_1"]
# assert chain_node_1(p1=1, bar_upstream=3) == 14
# assert chain_node_2(p2=1, bar_upstream=3) == 104
# assert chain_node_3_first(p3=7, bar_upstream=3) == 20
#
#
# def test_pipe_input_mapping_args_targets_local_adds_to_global():
# n = node.Node.from_fn(function_multiple_same_type_params)
# decorator = pipe_input(
# step(_test_apply_function, source("bar_upstream"), baz=value(10))
# .on_input(["p1", "p2"])
# .named("node_1"),
# step(_test_apply_function, source("bar_upstream"), baz=value(100))
# .on_input("p2")
# .named("node_2"),
# step(_test_apply_function, source("bar_upstream"), baz=value(1000)).named("node_3"),
# on_input="p3",
# namespace="abc",
# )
# nodes = decorator.transform_dag([n], {}, function_multiple_diverse_type_params)
# nodes_by_name = {item.name: item for item in nodes}
# p1_node = nodes_by_name["abc_p1.node_1"]
# p2_node1 = nodes_by_name["abc_p2.node_1"]
# p2_node2 = nodes_by_name["abc_p2.node_2"]
# p3_node1 = nodes_by_name["abc_p3.node_1"]
# p3_node2 = nodes_by_name["abc_p3.node_2"]
# p3_node3 = nodes_by_name["abc_p3.node_3"]
# assert p1_node(p1=1, bar_upstream=3) == 14
# assert p2_node1(p2=7, bar_upstream=3) == 20
# assert p2_node2(**{"abc_p2.node_1": 2, "bar_upstream": 3}) == 105
# assert p3_node1(p3=9, bar_upstream=3) == 22
# assert p3_node2(**{"abc_p3.node_1": 13, "bar_upstream": 3}) == 116
# assert p3_node3(**{"abc_p3.node_2": 17, "bar_upstream": 3}) == 1020
# def test_pipe_input_fails_with_missing_targets():
# n = node.Node.from_fn(function_multiple_same_type_params)
# decorator = pipe_input(
# step(_test_apply_function, source("bar_upstream"), baz=value(10))
# .on_input(["p1", "p2"])
# .named("node_1"),
# step(_test_apply_function, source("bar_upstream"), baz=value(100))
# .on_input("p2")
# .named("node_2"),
# step(_test_apply_function, source("bar_upstream"), baz=value(1000)).named("node_3"),
# namespace="abc",
# )
# with pytest.raises(hamilton.function_modifiers.macros.MissingTargetError):
# nodes = decorator.transform_dag([n], {}, function_multiple_same_type_params) # noqa
# def test_pipe_input_decorator_with_target_no_collapse_multi_node():
# n = node.Node.from_fn(function_multiple_same_type_params)
# decorator = pipe_input(
# step(_test_apply_function, source("bar_upstream"), baz=value(10))
# .on_input(["p1", "p3"])
# .named("node_1"),
# step(_test_apply_function, source("bar_upstream"), baz=value(100))
# .on_input("p2")
# .named("node_2"),
# step(_test_apply_function, source("bar_upstream"), baz=value(1000))
# .on_input("p3")
# .named("node_3"),
# namespace="abc",
# )
# nodes = decorator.transform_dag([n], {}, function_multiple_diverse_type_params)
# nodes_by_name = {item.name: item for item in nodes}
# final_node = nodes_by_name["function_multiple_same_type_params"]
# chain_node_1 = nodes_by_name["abc_p1.node_1"]
# chain_node_2 = nodes_by_name["abc_p2.node_2"]
# chain_node_3_first = nodes_by_name["abc_p3.node_1"]
# chain_node_3_second = nodes_by_name["abc_p3.node_3"]
# assert len(nodes_by_name) == 5
# assert chain_node_1(p1=1, bar_upstream=3) == 14
# assert chain_node_2(p2=1, bar_upstream=3) == 104
# assert chain_node_3_first(p3=7, bar_upstream=3) == 20
# assert chain_node_3_second(**{"abc_p3.node_1": 13, "bar_upstream": 3}) == 1016
# assert final_node(**{"abc_p1.node_1": 3, "abc_p2.node_2": 4, "abc_p3.node_3": 5}) == 12
def test_pipe_decorator_positional_variable_args():
n = node.Node.from_fn(general_downstream_function)
decorator = pipe_input(
step(_test_apply_function, source("bar_upstream"), baz=value(1000)).named("node_1"),
namespace=None,
)
nodes = decorator.transform_dag([n], {}, general_downstream_function)
nodes_by_name = {item.name: item for item in nodes}
chain_node = nodes_by_name["node_1"]
assert chain_node(result=1, bar_upstream=10) == 1011 # This chains it through
assert sorted(chain_node.input_types) == ["bar_upstream", "result"]
final_node = nodes_by_name["general_downstream_function"]
assert final_node(node_1=1) == 1
def test_pipe_decorator_no_collapse_multi_node():
n = node.Node.from_fn(general_downstream_function)
decorator = pipe_input(
step(_test_apply_function, bar=source("bar_upstream"), baz=100).named("node_1"),
step(_test_apply_function, bar=value(10), baz=value(100)).named("node_2"),
namespace=None,
)
nodes = decorator.transform_dag([n], {}, general_downstream_function)
nodes_by_name = {item.name: item for item in nodes}
final_node = nodes_by_name["general_downstream_function"]
assert len(nodes_by_name) == 3
assert nodes_by_name["node_1"](result=1, bar_upstream=10) == 111
assert nodes_by_name["node_2"](node_1=1) == 111
assert final_node(node_2=100) == 100
def test_resolve_namespace_inherit():
applicable = Applicable(
_test_apply_function, args=(), kwargs=dict(bar=source("bar_upstream"), baz=100)
).named("node_1")
assert applicable.resolve_namespace("inherited") == ("inherited",)
def test_resolve_namespace_discard():
applicable = Applicable(
_test_apply_function, args=(), kwargs=dict(bar=source("bar_upstream"), baz=100)
).named("node_1", namespace=None)
assert applicable.resolve_namespace("unused") == ()
def test_resolve_namespace_replaced():
applicable = Applicable(
_test_apply_function, args=(), kwargs=dict(bar=source("bar_upstream"), baz=100)
).named("node_1", namespace="replaced")
assert applicable.resolve_namespace("unused") == ("replaced",)
def test_validate_pipe_fails_with_conflicting_namespace():
decorator = pipe_input(
step(_test_apply_function, bar=source("bar_upstream"), baz=100).named(
"node_1", namespace="custom"
),
namespace=None, # Not allowed to have custom namespacess if the namespace is None
)
with pytest.raises(hamilton.function_modifiers.base.InvalidDecoratorException):
decorator.validate(general_downstream_function)
def test_inherits_null_namespace():
n = node.Node.from_fn(general_downstream_function)
decorator = pipe_input(
step(_test_apply_function, bar=source("bar_upstream"), baz=100).named(
"node_1", namespace=...
),
namespace=None, # Not allowed to have custom namespacess if the namespace is None
)
decorator.validate(general_downstream_function)
nodes = decorator.transform_dag([n], {}, general_downstream_function)
assert "node_1" in {item.name for item in nodes}
assert "general_downstream_function" in {item.name for item in nodes}
def test_pipe_end_to_end_1():
dr = (
driver.Builder()
.with_modules(tests.resources.pipe_input)
.with_adapter(base.DefaultAdapter())
.with_config({"calc_c": True})
.build()
)
inputs = {
"input_1": 10,
"input_2": 20,
"input_3": 30,
}
result = dr.execute(
[
"chain_1_using_pipe",
"chain_2_using_pipe",
"chain_1_not_using_pipe",
"chain_2_not_using_pipe",
],
inputs=inputs,
)
assert result["chain_1_using_pipe"] == result["chain_1_not_using_pipe"]
assert result["chain_2_using_pipe"] == result["chain_2_not_using_pipe"]
def test_pipe_end_to_end_target_global():
dr = (
driver.Builder()
.with_modules(tests.resources.pipe_input)
.with_adapter(base.DefaultAdapter())
.with_config({"calc_c": True})
.build()
)
inputs = {
"input_1": 10,
"input_2": 20,
"input_3": 30,
}
result = dr.execute(
[
"chain_1_using_pipe_input_target_global",
"chain_1_not_using_pipe_input_target_global",
],
inputs=inputs,
)
assert (
result["chain_1_not_using_pipe_input_target_global"]
== result["chain_1_using_pipe_input_target_global"]
)
# TODO: For multiple parameters end-to-end
# def test_pipe_end_to_end_target_local():
# dr = (
# driver.Builder()
# .with_modules(tests.resources.pipe_input)
# .with_adapter(base.DefaultAdapter())
# .with_config({"calc_c": True})
# .build()
# )
# inputs = {
# "input_1": 10,
# "input_2": 20,
# "input_3": 30,
# }
# result = dr.execute(
# [
# "chain_1_using_pipe_input_target_local",
# "chain_1_not_using_pipe_input_target_local",
# ],
# inputs=inputs,
# )
# assert (
# result["chain_1_not_using_pipe_input_target_local"]
# == result["chain_1_using_pipe_input_target_local"]
# )
# def test_pipe_end_to_end_target_mixed():
# dr = (
# driver.Builder()
# .with_modules(tests.resources.pipe_input)
# .with_adapter(base.DefaultAdapter())
# .with_config({"calc_c": True})
# .build()
# )
# inputs = {
# "input_1": 10,
# "input_2": 20,
# "input_3": 30,
# }
# result = dr.execute(
# [
# "chain_1_using_pipe_input_target_mixed",
# "chain_1_not_using_pipe_input_target_mixed",
# ],
# inputs=inputs,
# )
# assert (
# result["chain_1_not_using_pipe_input_target_mixed"]
# == result["chain_1_using_pipe_input_target_mixed"]
# )
def result_from_downstream_function() -> int:
return 2
def test_pipe_output_single_target_level_error():
with pytest.raises(hamilton.function_modifiers.macros.SingleTargetError):
pipe_output(
step(_test_apply_function, source("bar_upstream"), baz=value(100)).on_output(
"some_node"
),
on_output="some_other_node",
)
def test_pipe_output_shortcircuit():
n = node.Node.from_fn(result_from_downstream_function)
decorator = pipe_output()
nodes = decorator.transform_dag([n], {}, result_from_downstream_function)
assert len(nodes) == 1
assert n == nodes[0]
def test_pipe_output_decorator_positional_single_node():
n = node.Node.from_fn(result_from_downstream_function)
decorator = pipe_output(
step(_test_apply_function, source("bar_upstream"), baz=value(100)).named("node_1"),
namespace=None,
)
nodes = decorator.transform_dag([n], {}, result_from_downstream_function)
nodes_by_name = {item.name: item for item in nodes}
chain_node = nodes_by_name["node_1"]
assert chain_node(**{"result_from_downstream_function.raw": 2, "bar_upstream": 10}) == 112
assert sorted(chain_node.input_types) == [
"bar_upstream",
"result_from_downstream_function.raw",
]
final_node = nodes_by_name["result_from_downstream_function"]
assert final_node(foo=112) == 112 # original arg name
assert final_node(node_1=112) == 112 # renamed to match the last node
def test_pipe_output_decorator_no_collapse_multi_node():
n = node.Node.from_fn(result_from_downstream_function)
decorator = pipe_output(
step(_test_apply_function, bar=source("bar_upstream"), baz=100).named("node_1"),
step(_test_apply_function, bar=value(10), baz=value(100)).named("node_2"),
namespace=None,
)
nodes = decorator.transform_dag([n], {}, result_from_downstream_function)
nodes_by_name = {item.name: item for item in nodes}
final_node = nodes_by_name["result_from_downstream_function"]
assert len(nodes_by_name) == 4 # We add fn_raw and identity
assert (
nodes_by_name["node_1"](**{"result_from_downstream_function.raw": 1, "bar_upstream": 10})
== 111
)
assert nodes_by_name["node_2"](node_1=4) == 114
assert final_node(node_2=13) == 13
def test_validate_pipe_output_fails_with_conflicting_namespace():
decorator = pipe_output(
step(_test_apply_function, bar=source("bar_upstream"), baz=100).named(
"node_1", namespace="custom"
),
namespace=None, # Not allowed to have custom namespacess if the namespace is None
)
with pytest.raises(hamilton.function_modifiers.base.InvalidDecoratorException):
decorator.validate(result_from_downstream_function)
def test_pipe_output_inherits_null_namespace():
n = node.Node.from_fn(result_from_downstream_function)
decorator = pipe_output(
step(_test_apply_function, bar=source("bar_upstream"), baz=100).named(
"node_1", namespace=...
),
namespace=None, # Not allowed to have custom namespacess if the namespace is None
)
decorator.validate(result_from_downstream_function)
nodes = decorator.transform_dag([n], {}, result_from_downstream_function)
assert "node_1" in {item.name for item in nodes}
assert "result_from_downstream_function.raw" in {item.name for item in nodes}
assert "result_from_downstream_function" in {item.name for item in nodes}
def test_pipe_output_global_on_output_all():
n1 = node.Node.from_fn(result_from_downstream_function, name="node_1")
n2 = node.Node.from_fn(result_from_downstream_function, name="node_2")
decorator = pipe_output(
step(_test_apply_function, source("bar_upstream"), baz=value(100)),
)
nodes = decorator.select_nodes(decorator.target, [n1, n2])
assert len(nodes) == 2
assert [node_.name for node_ in nodes] == ["node_1", "node_2"]
def test_pipe_output_global_on_output_string():
n1 = node.Node.from_fn(result_from_downstream_function, name="node_1")
n2 = node.Node.from_fn(result_from_downstream_function, name="node_2")
decorator = pipe_output(
step(_test_apply_function, source("bar_upstream"), baz=value(100)), on_output="node_2"
)
nodes = decorator.select_nodes(decorator.target, [n1, n2])
assert len(nodes) == 1
assert nodes[0].name == "node_2"
def test_pipe_output_global_on_output_list_strings():
n1 = node.Node.from_fn(result_from_downstream_function, name="node_1")
n2 = node.Node.from_fn(result_from_downstream_function, name="node_2")
n3 = node.Node.from_fn(result_from_downstream_function, name="node_3")
decorator = pipe_output(
step(_test_apply_function, source("bar_upstream"), baz=value(100)),
on_output=["node_1", "node_2"],
)
nodes = decorator.select_nodes(decorator.target, [n1, n2, n3])
assert len(nodes) == 2
assert [node_.name for node_ in nodes] == ["node_1", "node_2"]
def test_pipe_output_elipsis_error():
with pytest.raises(ValueError):
pipe_output(
step(_test_apply_function, source("bar_upstream"), baz=value(100)), on_output=...
)
def test_pipe_output_local_on_output_string():
n1 = node.Node.from_fn(result_from_downstream_function, name="node_1")
n2 = node.Node.from_fn(result_from_downstream_function, name="node_2")
decorator = pipe_output(
step(_test_apply_function, source("bar_upstream"), baz=value(100))
.named("correct_transform")
.on_output("node_2"),
step(_test_apply_function, source("bar_upstream"), baz=value(100))
.named("wrong_transform")
.on_output("node_3"),
)
steps = decorator._filter_individual_target(n1)
assert len(steps) == 0
steps = decorator._filter_individual_target(n2)
assert len(steps) == 1
assert steps[0].name == "correct_transform"
def test_pipe_output_local_on_output_list_string():
n1 = node.Node.from_fn(result_from_downstream_function, name="node_1")
n2 = node.Node.from_fn(result_from_downstream_function, name="node_2")
n3 = node.Node.from_fn(result_from_downstream_function, name="node_3")
decorator = pipe_output(
step(_test_apply_function, source("bar_upstream"), baz=value(100))
.named("correct_transform_list")
.on_output(["node_2", "node_3"]),
step(_test_apply_function, source("bar_upstream"), baz=value(100))
.named("correct_transform_string")
.on_output("node_2"),
step(_test_apply_function, source("bar_upstream"), baz=value(100))
.named("wrong_transform")
.on_output("node_5"),
)
steps = decorator._filter_individual_target(n1)
assert len(steps) == 0
steps = decorator._filter_individual_target(n2)
assert len(steps) == 2
assert steps[0].name == "correct_transform_list"
assert steps[1].name == "correct_transform_string"
steps = decorator._filter_individual_target(n3)
assert len(steps) == 1
assert steps[0].name == "correct_transform_list"
def test_pipe_output_end_to_end_simple():
dr = driver.Builder().with_config({"calc_c": True}).build()
dr = (
driver.Builder()
.with_modules(tests.resources.pipe_output)
.with_adapter(base.DefaultAdapter())
.build()
)
inputs = {}
result = dr.execute(
[
"downstream_f",
"chain_not_using_pipe_output",
],
inputs=inputs,
)
assert result["downstream_f"] == result["chain_not_using_pipe_output"]
def test_pipe_output_end_to_end():
dr = (
driver.Builder()
.with_modules(tests.resources.pipe_output)
.with_adapter(base.DefaultAdapter())
.with_config({"calc_c": True})
.build()
)
inputs = {
"input_1": 10,
"input_2": 20,
"input_3": 30,
}
result = dr.execute(
[
"chain_1_using_pipe_output",
"chain_2_using_pipe_output",
"chain_1_not_using_pipe_output",
"chain_2_not_using_pipe_output",
],
inputs=inputs,
)
assert result["chain_1_using_pipe_output"] == result["chain_1_not_using_pipe_output"]
assert result["chain_2_using_pipe_output"] == result["chain_2_not_using_pipe_output"]
def test_pipe_output_end_to_end_with_config():
inputs = {
"input_1": 10,
"input_2": 20,
"input_3": 30,
}
dr = (
driver.Builder()
.with_modules(tests.resources.pipe_output)
.with_adapter(base.DefaultAdapter())
.with_config({"key": "Yes"})
.build()
)
result = dr.execute(
[
"chain_3_using_pipe_output",
"chain_3_not_using_pipe_output_config_true",
],