-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathtest_dagbuilder.py
More file actions
1421 lines (1224 loc) · 52.8 KB
/
Copy pathtest_dagbuilder.py
File metadata and controls
1421 lines (1224 loc) · 52.8 KB
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 datetime
import functools
import os
from pathlib import Path
from unittest.mock import mock_open, patch
import pendulum
import pytest
try:
from airflow.sdk.definitions.dag import DAG
except ImportError:
from airflow.models import DAG
import yaml
from airflow.providers.common.sql.sensors.sql import SqlSensor
from airflow.providers.http.sensors.http import HttpSensor
from airflow.version import version as AIRFLOW_VERSION
from packaging import version
from dagfactory.dagbuilder import INSTALLED_AIRFLOW_VERSION, DagBuilder, DagFactoryConfigException, Dataset
from dagfactory.utils import cast_with_type
from tests.utils import (
get_bash_operator_path,
get_http_sensor_path,
get_python_operator_path,
get_schedule_key,
get_sql_sensor_path,
one_hour_ago,
read_yml,
)
try:
from airflow.providers.standard.operators.bash import BashOperator
except ImportError:
from airflow.operators.bash import BashOperator
try: # Try Airflow 3
from airflow.providers.standard.operators.python import PythonOperator
except ImportError:
from airflow.operators.python import PythonOperator
from dagfactory import dagbuilder
try:
from airflow.sdk.definitions.mappedoperator import MappedOperator
except ImportError:
from airflow.models import MappedOperator
here = Path(__file__).parent
schedule_path = here / "schedule"
PROJECT_ROOT_PATH = str(here.parent)
UTC = pendulum.timezone("UTC")
DEFAULT_CONFIG = {
"default_args": {
"owner": "default_owner",
"start_date": datetime.date(2018, 3, 1),
"end_date": datetime.date(2018, 3, 5),
"retries": 1,
"retry_delay_sec": 300,
},
"concurrency": 1,
"max_active_runs": 1,
"dagrun_timeout_sec": 600,
get_schedule_key(): "0 1 * * *",
}
DAG_CONFIG = {
"doc_md": "##here is a doc md string",
"default_args": {"owner": "custom_owner"},
"description": "this is an example dag",
"dag_display_name": "Pretty example dag",
get_schedule_key(): "0 3 * * *",
"tags": ["tag1", "tag2"],
"render_template_as_native_obj": True,
"tasks": {
"task_1": {
"operator": get_bash_operator_path(),
"bash_command": "echo 1",
"execution_timeout_secs": 5,
},
"task_2": {
"operator": get_bash_operator_path(),
"bash_command": "echo 2",
"dependencies": ["task_1"],
},
"task_3": {
"operator": get_bash_operator_path(),
"bash_command": "echo 3",
"dependencies": ["task_1"],
},
},
}
DAG_CONFIG_TASK_GROUP = {
"default_args": {"owner": "custom_owner"},
get_schedule_key(): "0 3 * * *",
"task_groups": {
"task_group_1": {
"tooltip": "this is a task group",
"dependencies": ["task_1"],
},
"task_group_2": {
"dependencies": ["task_group_1"],
},
"task_group_3": {},
},
"tasks": {
"task_1": {
"operator": get_bash_operator_path(),
"bash_command": "echo 1",
},
"task_2": {
"operator": get_bash_operator_path(),
"bash_command": "echo 2",
"task_group_name": "task_group_1",
},
"task_3": {
"operator": get_bash_operator_path(),
"bash_command": "echo 3",
"task_group_name": "task_group_1",
"dependencies": ["task_2"],
},
"task_4": {
"operator": get_bash_operator_path(),
"bash_command": "echo 4",
"dependencies": ["task_group_1"],
},
"task_5": {
"operator": get_bash_operator_path(),
"bash_command": "echo 5",
"task_group_name": "task_group_2",
},
"task_6": {
"operator": get_bash_operator_path(),
"bash_command": "echo 6",
"task_group_name": "task_group_2",
"dependencies": ["task_5"],
},
},
}
DAG_CONFIG_DYNAMIC_TASK_MAPPING = {
"default_args": {"owner": "custom_owner"},
"description": "This is an example dag with dynamic task mapping",
get_schedule_key(): "0 4 * * *",
"tasks": {
"request": {
"operator": get_python_operator_path(),
"python_callable_name": "example_task_mapping",
"python_callable_file": os.path.realpath(__file__),
},
"process_1": {
"operator": get_python_operator_path(),
"python_callable_name": "expand_task",
"python_callable_file": os.path.realpath(__file__),
"partial": {"op_kwargs": {"test_id": "test"}},
"expand": {"op_args": {"request_output": "request.output"}},
},
},
}
DAG_CONFIG_ML = {
"tasks": {
"task_2": {
"bash_command": "echo 2",
}
}
}
DAG_CONFIG_DEFAULT_ML = {
get_schedule_key(): "0 0 * * *",
"default_args": {"start_date": "2025-01-01", "owner": "custom_owner"},
"tasks": {
"task_1": {
"operator": get_bash_operator_path(),
"bash_command": "echo 1",
},
"task_2": {
"operator": get_bash_operator_path(),
},
},
}
DAG_CONFIG_CALLBACKS = {
"doc_md": "##here is a doc md string",
"default_args": {
"owner": "custom_owner",
"on_execute_callback": f"{__name__}.print_context_callback",
"on_success_callback": f"{__name__}.print_context_callback",
# "on_failure_callback": f"{__name__}.print_context_callback", # Passing this in at the Task-level
"on_retry_callback": f"{__name__}.print_context_callback",
"on_skipped_callback": f"{__name__}.print_context_callback",
},
"description": "this is an example dag",
get_schedule_key(): "0 3 * * *",
"tags": ["tag1", "tag2"],
# This includes each of the four options (str function, str function with params, file and name, provider)
"on_execute_callback": f"{__name__}.print_context_callback",
"on_success_callback": {
"callback": f"{__name__}.empty_callback_with_params",
"param_1": "value_1",
"param_2": "value_2",
},
"on_failure_callback_name": "print_context_callback",
"on_failure_callback_file": __file__,
"tasks": {
"task_1": { # Make sure that default_args are applied to this Task
"operator": get_bash_operator_path(),
"bash_command": "echo 1",
"execution_timeout_secs": 5,
"on_failure_callback_name": "print_context_callback",
"on_failure_callback_file": __file__,
}
},
}
DAG_CONFIG_TASK_GROUP_WITH_CALLBACKS = {
"default_args": {
"owner": "custom_owner",
"on_failure_callback": { # Include this to assert that these are overridden by TaskGroup callbacks
"callback": f"{__name__}.empty_callback_with_params",
"param_1": "value_1",
"param_2": "value_2",
},
},
get_schedule_key(): "0 3 * * *",
"task_groups": {
"task_group_1": {
"tooltip": "this is a task group",
"default_args": {
"on_execute_callback": f"{__name__}.print_context_callback",
"on_success_callback": f"{__name__}.print_context_callback",
"on_failure_callback": f"{__name__}.print_context_callback",
"on_retry_callback": f"{__name__}.print_context_callback",
"on_skip_callback": f"{__name__}.print_context_callback", # Throwing this in for good measure
},
},
},
"tasks": {
"task_1": {
"operator": get_bash_operator_path(),
"bash_command": "echo 1",
"task_group_name": "task_group_1",
},
"task_2": {
"operator": get_bash_operator_path(),
"bash_command": "echo 2",
"task_group_name": "task_group_1",
"on_failure_callback": {
"callback": f"{__name__}.empty_callback_with_params",
"param_1": "value_1",
"param_2": "value_2",
},
},
"task_3": {
"operator": get_bash_operator_path(),
"bash_command": "echo 3",
"task_group_name": "task_group_1",
"dependencies": ["task_2"],
},
# This is not part of the TaskGroup, we'll add additional callbacks here. These are going to include:
# - String with no parameters
# - String with parameters
# - File name and path
"task_4": {
"operator": get_bash_operator_path(),
"bash_command": "echo 4",
"dependencies": ["task_group_1"],
"on_execute_callback": f"{__name__}.print_context_callback",
"on_success_callback": {
"callback": f"{__name__}.empty_callback_with_params",
"param_1": "value_1",
"param_2": "value_2",
},
"on_failure_callback_name": "print_context_callback",
"on_failure_callback_file": __file__,
},
},
}
class MockTaskGroup:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class MockPythonOperator(MockTaskGroup):
"""
Mock PythonOperator
"""
def test_get_dag_params():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
expected = {
"doc_md": "##here is a doc md string",
"dag_display_name": "Pretty example dag",
"dag_id": "test_dag",
"default_args": {
"owner": "custom_owner",
"start_date": datetime.datetime(2018, 3, 1, 0, 0, tzinfo=UTC),
"end_date": datetime.datetime(2018, 3, 5, 0, 0, tzinfo=UTC),
"retries": 1,
"retry_delay": datetime.timedelta(seconds=300),
},
"description": "this is an example dag",
get_schedule_key(): "0 3 * * *",
"concurrency": 1,
"max_active_runs": 1,
"dagrun_timeout": datetime.timedelta(seconds=600),
"render_template_as_native_obj": True,
"tags": ["tag1", "tag2"],
"tasks": {
"task_1": {
"operator": get_bash_operator_path(),
"bash_command": "echo 1",
"execution_timeout_secs": 5,
},
"task_2": {
"operator": get_bash_operator_path(),
"bash_command": "echo 2",
"dependencies": ["task_1"],
},
"task_3": {
"operator": get_bash_operator_path(),
"bash_command": "echo 3",
"dependencies": ["task_1"],
},
},
}
actual = td.get_dag_params()
assert actual == expected
def test_get_dag_params_no_start_date():
td = dagbuilder.DagBuilder("test_dag", {}, {})
with pytest.raises(Exception):
td.get_dag_params()
def test_adjust_general_task_params_external_sensor_arguments():
task_params = {"execution_date_fn": "tests.utils.one_hour_ago"}
DagBuilder.adjust_general_task_params(task_params)
assert task_params["execution_date_fn"] == one_hour_ago
task_params = {"execution_delta": "1 days"}
DagBuilder.adjust_general_task_params(task_params)
assert task_params["execution_delta"] == datetime.timedelta(days=1)
def test_make_task_valid():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = get_bash_operator_path()
task_params = {
"task_id": "test_task",
"bash_command": "echo 1",
"execution_timeout_secs": 5,
}
actual = td.make_task(operator, task_params)
assert actual.task_id == "test_task"
assert actual.bash_command == "echo 1"
assert isinstance(actual, BashOperator)
def test_make_task_bad_operator():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = "not_real"
task_params = {"task_id": "test_task", "bash_command": "echo 1"}
with pytest.raises(Exception):
td.make_task(operator, task_params)
def test_make_task_missing_required_param():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = get_bash_operator_path()
task_params = {"task_id": "test_task"}
with pytest.raises(Exception):
td.make_task(operator, task_params)
def print_test():
print("test")
def expand_task(x, test_id):
print(test_id)
print(x)
return [x]
def example_task_mapping():
return [[1], [2], [3]]
def test_make_python_operator():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = get_python_operator_path()
task_params = {
"task_id": "test_task",
"python_callable_name": "print_test",
"python_callable_file": os.path.realpath(__file__),
}
actual = td.make_task(operator, task_params)
assert actual.task_id == "test_task"
assert callable(actual.python_callable)
assert isinstance(actual, PythonOperator)
def test_make_python_operator_with_callable_str():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = get_python_operator_path()
task_params = {
"task_id": "test_task",
"python_callable": "builtins.print",
}
actual = td.make_task(operator, task_params)
assert actual.task_id == "test_task"
assert callable(actual.python_callable)
assert isinstance(actual, PythonOperator)
def test_make_python_operator_missing_param():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = get_python_operator_path()
task_params = {"task_id": "test_task", "python_callable_name": "print_test"}
with pytest.raises(Exception):
td.make_task(operator, task_params)
def test_make_python_operator_missing_params():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = get_python_operator_path()
task_params = {"task_id": "test_task"}
with pytest.raises(Exception):
td.make_task(operator, task_params)
def test_make_http_sensor():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = get_http_sensor_path()
task_params = {
"task_id": "test_task",
"http_conn_id": "test-http",
"method": "GET",
"endpoint": "",
"response_check_name": "print_test",
"response_check_file": os.path.realpath(__file__),
}
actual = td.make_task(operator, task_params)
assert actual.task_id == "test_task"
assert callable(actual.response_check)
assert isinstance(actual, HttpSensor)
def test_make_http_sensor_lambda():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = get_http_sensor_path()
task_params = {
"task_id": "test_task",
"http_conn_id": "test-http",
"method": "GET",
"endpoint": "",
"response_check_lambda": 'lambda response: "ok" in response.text',
}
actual = td.make_task(operator, task_params)
assert actual.task_id == "test_task"
assert callable(actual.response_check)
assert isinstance(actual, HttpSensor)
def test_make_sql_sensor_success():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
sensor = get_sql_sensor_path()
task_params = {
"task_id": "test_task",
"conn_id": "test-sql",
"sql": "SELECT 1 AS status;",
"success_check_name": "print_test",
"success_check_file": os.path.realpath(__file__),
}
actual = td.make_task(sensor, task_params)
assert actual.task_id == "test_task"
assert callable(actual.success)
assert isinstance(actual, SqlSensor)
def test_make_sql_sensor_success_lambda():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
sensor = get_sql_sensor_path()
task_params = {
"task_id": "test_task",
"conn_id": "test-sql",
"sql": "SELECT 1 AS status;",
"success_check_lambda": "lambda res: res > 0",
}
actual = td.make_task(sensor, task_params)
assert actual.task_id == "test_task"
assert callable(actual.success)
assert isinstance(actual, SqlSensor)
def test_make_sql_sensor_failure():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
sensor = get_sql_sensor_path()
task_params = {
"task_id": "test_task",
"conn_id": "test-sql",
"sql": "SELECT 1 AS status;",
"failure_check_name": "print_test",
"failure_check_file": os.path.realpath(__file__),
}
actual = td.make_task(sensor, task_params)
assert actual.task_id == "test_task"
assert not callable(actual.success)
assert callable(actual.failure)
assert isinstance(actual, SqlSensor)
def test_make_sql_sensor_failure_lambda():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
sensor = get_sql_sensor_path()
task_params = {
"task_id": "test_task",
"conn_id": "test-sql",
"sql": "SELECT 1 AS status;",
"failure_check_lambda": "lambda res: res > 0",
}
actual = td.make_task(sensor, task_params)
assert actual.task_id == "test_task"
assert not callable(actual.success)
assert callable(actual.failure)
assert isinstance(actual, SqlSensor)
def test_make_http_sensor_missing_param():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
operator = get_http_sensor_path()
task_params = {
"task_id": "test_task",
"http_conn_id": "test-http",
"method": "GET",
"endpoint": "",
"response_check_name": "print_test",
}
with pytest.raises(Exception):
td.make_task(operator, task_params)
def test_build():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
actual = td.build()
assert actual["dag_id"] == "test_dag"
assert isinstance(actual["dag"], DAG)
assert len(actual["dag"].tasks) == 3
assert actual["dag"].task_dict["task_1"].downstream_task_ids == {"task_2", "task_3"}
if version.parse(AIRFLOW_VERSION) >= version.parse("2.9.0"):
assert actual["dag"].dag_display_name == "Pretty example dag"
assert sorted(actual["dag"].tags) == sorted(["tag1", "tag2", "dagfactory"])
def test_get_dag_params_dag_with_task_group():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG_TASK_GROUP, DEFAULT_CONFIG)
expected = {
"default_args": {
"owner": "custom_owner",
"start_date": datetime.datetime(2018, 3, 1, 0, 0, tzinfo=UTC),
"end_date": datetime.datetime(2018, 3, 5, 0, 0, tzinfo=UTC),
"retries": 1,
"retry_delay": datetime.timedelta(seconds=300),
},
get_schedule_key(): "0 3 * * *",
"task_groups": {
"task_group_1": {
"tooltip": "this is a task group",
"dependencies": ["task_1"],
},
"task_group_2": {"dependencies": ["task_group_1"]},
"task_group_3": {},
},
"tasks": {
"task_1": {
"operator": get_bash_operator_path(),
"bash_command": "echo 1",
},
"task_2": {
"operator": get_bash_operator_path(),
"bash_command": "echo 2",
"task_group_name": "task_group_1",
},
"task_3": {
"operator": get_bash_operator_path(),
"bash_command": "echo 3",
"task_group_name": "task_group_1",
"dependencies": ["task_2"],
},
"task_4": {
"operator": get_bash_operator_path(),
"bash_command": "echo 4",
"dependencies": ["task_group_1"],
},
"task_5": {
"operator": get_bash_operator_path(),
"bash_command": "echo 5",
"task_group_name": "task_group_2",
},
"task_6": {
"operator": get_bash_operator_path(),
"bash_command": "echo 6",
"task_group_name": "task_group_2",
"dependencies": ["task_5"],
},
},
"concurrency": 1,
"max_active_runs": 1,
"dag_id": "test_dag",
"dagrun_timeout": datetime.timedelta(seconds=600),
}
assert td.get_dag_params() == expected
def test_build_task_groups():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG_TASK_GROUP, DEFAULT_CONFIG)
actual = td.build()
task_group_1 = {t for t in actual["dag"].task_dict if t.startswith("task_group_1")}
task_group_2 = {t for t in actual["dag"].task_dict if t.startswith("task_group_2")}
assert actual["dag_id"] == "test_dag"
assert isinstance(actual["dag"], DAG)
assert len(actual["dag"].tasks) == 6
assert actual["dag"].task_dict["task_1"].downstream_task_ids == {"task_group_1.task_2"}
assert actual["dag"].task_dict["task_group_1.task_2"].downstream_task_ids == {"task_group_1.task_3"}
assert actual["dag"].task_dict["task_group_1.task_3"].downstream_task_ids == {
"task_4",
"task_group_2.task_5",
}
assert actual["dag"].task_dict["task_group_2.task_5"].downstream_task_ids == {
"task_group_2.task_6",
}
assert {"task_group_1.task_2", "task_group_1.task_3"} == task_group_1
assert {"task_group_2.task_5", "task_group_2.task_6"} == task_group_2
@patch("dagfactory.dagbuilder.TaskGroup", new=MockTaskGroup)
def test_make_task_groups():
task_group_dict = {
"task_group": {
"tooltip": "this is a task group",
},
}
dag = "dag"
task_groups = dagbuilder.DagBuilder.make_task_groups(task_group_dict, dag)
expected = MockTaskGroup(tooltip="this is a task group", group_id="task_group", dag=dag)
assert task_groups["task_group"].__dict__ == expected.__dict__
def test_make_task_groups_empty():
task_groups = dagbuilder.DagBuilder.make_task_groups({}, None)
assert task_groups == {}
def test_dag_config_default():
td = dagbuilder.DagBuilder("test_dynamic_machine_learning_dag", DAG_CONFIG_ML, DAG_CONFIG_DEFAULT_ML)
dag = td.build()["dag"]
# Validate that the default values were applied to the machine_learning DAG
assert dag.dag_id == "test_dynamic_machine_learning_dag"
assert len(dag.tasks) == 2
task_1 = dag.task_dict["task_1"]
assert task_1.bash_command == "echo 1"
task_2 = dag.task_dict["task_2"]
assert task_2.bash_command == "echo 2"
# These functions are used to mock callbacks for the tests below
def print_context_callback(context, **kwargs):
print(context)
def empty_callback_with_params(context, param_1, param_2, **kwargs):
# Context is the first parameter passed into the callback
print(param_1)
print(param_2)
# Test the set_callback() static method
@pytest.mark.callbacks
def test_set_callback_exceptions():
"""
test_set_callback_exceptions
Validate that exceptions are being throw for an incompatible version of Airflow, as well as for an invalid type
passed to the parameter config.
"""
# Test a versioning exception
if version.parse(AIRFLOW_VERSION) < version.parse("2.0.0"):
error_message = "Cannot parse callbacks with an Airflow version less than 2.0.0"
with pytest.raises(DagFactoryConfigException, match=error_message):
DagBuilder.set_callback(
parameters={"dummy_key": "dummy_value"},
callback_type="on_execute_callback",
)
# Now, test an exception parsing the parameters dictionary
invalid_type_passed_message = "Invalid type passed to on_execute_callback"
with pytest.raises(DagFactoryConfigException, match=invalid_type_passed_message):
DagBuilder.set_callback(
parameters={"on_execute_callback": ["callback_1", "callback_2", "callback_3"]},
callback_type="on_execute_callback",
)
@pytest.mark.callbacks
def test_make_dag_with_callbacks():
"""
test_make_dag_with_callbacks
Validate that the DAG builds. Then, check callbacks configured at the DAG-level.
"""
# Build the DAG if the Airflow version check is met
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG_CALLBACKS, DEFAULT_CONFIG)
dag = td.build()["dag"] # Pull the actual DAG object, which can be used in
# Validate the .set_callback() method works as expected when importing a string (for on_execute_callback)
assert "on_execute_callback" in td.dag_config
assert callable(td.dag_config["on_execute_callback"])
assert td.dag_config["on_execute_callback"].__name__ == "print_context_callback"
# Check on_success_callback, which is a function that is configured with two key-value pairs
assert "on_success_callback" in td.dag_config
assert isinstance(dag.on_success_callback, functools.partial)
assert callable(dag.on_success_callback)
assert dag.on_success_callback.func.__name__ == "empty_callback_with_params"
assert "param_1" in dag.on_success_callback.keywords # Check the parameters
assert dag.on_success_callback.keywords["param_1"] == "value_1"
assert "param_2" in dag.on_success_callback.keywords
assert dag.on_success_callback.keywords["param_2"] == "value_2"
# Verify that the callbacks have been set up properly per DAG after specifying:
# - 'on_failure_callback_file' & 'on_failure_callback_name' for 'on_failure_callback'
assert "on_failure_callback" in td.dag_config
assert callable(dag.on_failure_callback)
assert dag.on_failure_callback.__name__ == "print_context_callback"
if version.parse(AIRFLOW_VERSION) >= version.parse("2.6.0"):
from airflow.providers.slack.notifications.slack import send_slack_notification
dag_config_callbacks__with_provider = dict(DAG_CONFIG_CALLBACKS)
dag_config_callbacks__with_provider["sla_miss_callback"] = {
"callback": "airflow.providers.slack.notifications.slack.send_slack_notification",
"slack_conn_id": "slack_conn_id",
"text": f"""Sample callback text.""",
"channel": "#channel",
"username": "username",
}
with_provider_td = dagbuilder.DagBuilder("test_dag", dag_config_callbacks__with_provider, DEFAULT_CONFIG)
with_provider_td.build()
# Assert that sla_miss_callback is part of the dag_config. If it is, pull the callback and validate the config
# of the Slack notifier
assert "sla_miss_callback" in with_provider_td.dag_config
sla_miss_callback = with_provider_td.dag_config["sla_miss_callback"]
assert isinstance(sla_miss_callback, send_slack_notification)
assert callable(sla_miss_callback)
assert sla_miss_callback.slack_conn_id == "slack_conn_id"
assert sla_miss_callback.channel == "#channel"
assert sla_miss_callback.username == "username"
def test_make_timetable():
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG, DEFAULT_CONFIG)
timetable = "airflow.timetables.interval.CronDataIntervalTimetable"
timetable_params = {"cron": "0 8,16 * * 1-5", "timezone": "UTC"}
actual = td.make_timetable(timetable, timetable_params)
assert actual.periodic
try:
assert actual.can_run
except AttributeError:
# can_run attribute was removed and replaced with can_be_scheduled in later versions of Airflow.
assert actual.can_be_scheduled
@pytest.mark.callbacks
def test_make_dag_with_callbacks_default_args():
"""
test_make_dag_with_callbacks_default_args
Check callbacks configured in default args.
"""
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG_CALLBACKS, DEFAULT_CONFIG)
dag = td.build()["dag"]
default_args = td.dag_config["default_args"] # Pull the default_args
# Validate at the Task-level
assert "task_1" in dag.task_dict
task_1 = dag.task_dict["task_1"]
# Validate the .set_callback() method works as expected when importing a string
for callback_type in (
"on_execute_callback",
"on_success_callback",
# "on_failure_callback", # Set at the Task-level, tested below
"on_retry_callback",
"on_skipped_callback",
):
# on_skipped_callback could only be added to default_args starting in Airflow version 2.7.0
# TODO: Address this, this should be 2.7.0
if not (version.parse(AIRFLOW_VERSION) < version.parse("2.9.0") and callback_type == "on_skipped_callback"):
assert callback_type in default_args
assert callable(default_args.get(callback_type))
assert default_args.get(callback_type).__name__ == "print_context_callback"
# Assert that these callbacks have been applied at the Task-level
assert callback_type in task_1.__dict__
# Airflow 3 callback type is sequence
if version.parse(AIRFLOW_VERSION) >= version.parse("3.0.0"):
assert callable(task_1.__dict__[callback_type][0])
assert task_1.__dict__[callback_type][0].__name__ == "print_context_callback"
else:
assert callable(task_1.__dict__[callback_type])
assert task_1.__dict__[callback_type].__name__ == "print_context_callback"
# Assert that these callbacks have been applied at the Task-level
assert "on_failure_callback" in task_1.__dict__
# Airflow 3 callback type is sequence
if version.parse(AIRFLOW_VERSION) >= version.parse("3.0.0"):
assert callable(task_1.__dict__["on_failure_callback"][0])
assert task_1.__dict__["on_failure_callback"][0].__name__ == "print_context_callback"
else:
assert callable(task_1.__dict__["on_failure_callback"])
assert task_1.__dict__["on_failure_callback"].__name__ == "print_context_callback"
@pytest.mark.callbacks
def test_make_dag_with_task_group_callbacks():
"""
test_dag_with_task_group_callbacks
Test the DAG with callbacks configured at both the Task and the TaskGroup level. Note that callbacks configured in
the default_args of a TaskGroup are applied to each of those Tasks. To do this, we'll use the config set in the
DAG_CONFIG_TASK_GROUP_WITH_CALLBACKS variable. We'll want to test three things:
1) The DAG is successfully built
2) There appropriate number of Tasks that make up this DAG
3) There is a TaskGroup configured as part of the DAG, which has Tasks assigned to that group
"""
# Import the DAG using the callback config that was build above
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG_TASK_GROUP_WITH_CALLBACKS, DEFAULT_CONFIG)
# This will be done only once; validate the exception that is raised if trying to use an invalid version of Airflow
# when building TaskGroups
if version.parse(AIRFLOW_VERSION) < version.parse("2.2.0"):
error_message = "`task_groups` key can only be used with Airflow 2.x.x"
with pytest.raises(Exception, match=error_message):
td.build()
else:
dag = td.build()["dag"] # Also, pull the dag
# Basic checks to ensure the DAG was built as expected
if version.parse(AIRFLOW_VERSION) < version.parse("3.0.0"):
assert dag.task_count == 4
assert len([task for task in dag.task_dict.keys() if task.startswith("task_group_1")]) == 3
assert (
"task_group_1.task_1" in dag.task_dict
and "task_group_1.task_2" in dag.task_dict
and "task_group_1.task_3" in dag.task_dict
)
@pytest.mark.callbacks
def test_make_dag_with_task_group_callbacks_default_args():
"""
test_dag_with_task_group_callbacks_default_args
Once the "build-ability" of the DAG configured in DAG_CONFIG_TASK_GROUP_WITH_CALLBACKS has been tested, we'll test
the callbacks configured for this DAG. The following assertions will be made:
- There are callbacks present in the default_args of the TaskGroup
- These callbacks are "callable", and have the name print_context_callback
- task_group_1.task_2 has overridden the on_failure_callback
- task_2 uses the empty_callback_with_params function, which takes two arguments
"""
# Import the DAG using the callback config that was build above. Previously, we matched the error message thrown
# if the version was not met. Here, we'll pass testing
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG_TASK_GROUP_WITH_CALLBACKS, DEFAULT_CONFIG)
# TODO: This should be 2.2.0
if version.parse(AIRFLOW_VERSION) >= version.parse("2.3.0"): # This is a work-around for now
dag = td.build()["dag"] # Also, pull the dag
# Now, loop through each of the callback types and validate
assert "task_group_1" in td.dag_config["task_groups"]
task_group_default_args = td.dag_config["task_groups"]["task_group_1"]["default_args"]
# Test that the on_execute_callback configured in the default_args of the TaskGroup are passed down to the Tasks
# grouped into task_group_1
assert "on_execute_callback" in task_group_default_args and "on_failure_callback" in task_group_default_args
# Airflow 3 callback type is sequence
if version.parse(AIRFLOW_VERSION) >= version.parse("3.0.0"):
assert callable(dag.task_dict["task_group_1.task_1"].on_execute_callback[0])
assert dag.task_dict["task_group_1.task_1"].on_execute_callback[0].__name__ == "print_context_callback"
else:
assert callable(dag.task_dict["task_group_1.task_1"].on_execute_callback)
assert dag.task_dict["task_group_1.task_1"].on_execute_callback.__name__ == "print_context_callback"
# task_2 overrides the on_failure_callback configured in the default_args of task_group_1. Below, this is
# validated but checking the type, "callab-ility", name, and parameters configured with it
# Airflow 3 callback type is sequence
if version.parse(AIRFLOW_VERSION) >= version.parse("3.0.0"):
assert isinstance(dag.task_dict["task_group_1.task_2"].on_failure_callback[0], functools.partial)
assert callable(dag.task_dict["task_group_1.task_2"].on_failure_callback[0])
assert (
dag.task_dict["task_group_1.task_2"].on_failure_callback[0].func.__name__
== "empty_callback_with_params"
)
assert "param_1" in dag.task_dict["task_group_1.task_2"].on_failure_callback[0].keywords
assert dag.task_dict["task_group_1.task_2"].on_failure_callback[0].keywords.get("param_1") == "value_1"
else:
assert isinstance(dag.task_dict["task_group_1.task_2"].on_failure_callback, functools.partial)
assert callable(dag.task_dict["task_group_1.task_2"].on_failure_callback)
assert (
dag.task_dict["task_group_1.task_2"].on_failure_callback.func.__name__ == "empty_callback_with_params"
)
assert "param_1" in dag.task_dict["task_group_1.task_2"].on_failure_callback.keywords
assert dag.task_dict["task_group_1.task_2"].on_failure_callback.keywords.get("param_1") == "value_1"
@pytest.mark.callbacks
def test_make_dag_with_task_group_callbacks_tasks():
"""
test_dag_with_task_group_callbacks_tasks
Here, we're testing callbacks applied at the Task-level.
"""
td = dagbuilder.DagBuilder("test_dag", DAG_CONFIG_TASK_GROUP_WITH_CALLBACKS, DEFAULT_CONFIG)
dag = td.build()["dag"]
task_4 = dag.task_dict["task_4"]
# Airflow 3 callback type is sequence
if version.parse(AIRFLOW_VERSION) >= version.parse("3.0.0"):
assert callable(task_4.on_execute_callback[0])
assert task_4.on_execute_callback[0].__name__ == "print_context_callback"
assert isinstance(task_4.on_success_callback[0], functools.partial)
assert callable(task_4.on_success_callback[0])
assert task_4.on_success_callback[0].func.__name__ == "empty_callback_with_params"
assert "param_2" in task_4.on_success_callback[0].keywords
assert task_4.on_success_callback[0].keywords["param_2"] == "value_2"
assert callable(task_4.on_failure_callback[0])
assert task_4.on_failure_callback[0].__name__ == "print_context_callback"
else:
assert callable(task_4.on_execute_callback)
assert task_4.on_execute_callback.__name__ == "print_context_callback"
assert isinstance(task_4.on_success_callback, functools.partial)
assert callable(task_4.on_success_callback)
assert task_4.on_success_callback.func.__name__ == "empty_callback_with_params"
assert "param_2" in task_4.on_success_callback.keywords
assert task_4.on_success_callback.keywords["param_2"] == "value_2"
assert callable(task_4.on_failure_callback)
assert task_4.on_failure_callback.__name__ == "print_context_callback"
def test_get_dag_params_with_template_searchpath():
from dagfactory import utils
td = dagbuilder.DagBuilder("test_dag", {"template_searchpath": ["./sql"]}, DEFAULT_CONFIG)
error_message = "template_searchpath must be absolute paths"
with pytest.raises(Exception, match=error_message):
td.get_dag_params()
td = dagbuilder.DagBuilder("test_dag", {"template_searchpath": ["/sql"]}, DEFAULT_CONFIG)
error_message = "template_searchpath must be existing paths"
with pytest.raises(Exception, match=error_message):
td.get_dag_params()
td = dagbuilder.DagBuilder("test_dag", {"template_searchpath": "./sql"}, DEFAULT_CONFIG)
error_message = "template_searchpath must be absolute paths"
with pytest.raises(Exception, match=error_message):
td.get_dag_params()
td = dagbuilder.DagBuilder("test_dag", {"template_searchpath": "/sql"}, DEFAULT_CONFIG)
error_message = "template_searchpath must be existing paths"
with pytest.raises(Exception, match=error_message):
td.get_dag_params()
assert utils.check_template_searchpath(123) == False
assert utils.check_template_searchpath(PROJECT_ROOT_PATH) == True
assert utils.check_template_searchpath([PROJECT_ROOT_PATH]) == True