-
Notifications
You must be signed in to change notification settings - Fork 14.8k
/
Copy pathtest_task_instance_endpoint.py
2513 lines (2381 loc) · 93.5 KB
/
test_task_instance_endpoint.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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import datetime as dt
import urllib
from unittest import mock
import pendulum
import pytest
from sqlalchemy import select
from sqlalchemy.orm import contains_eager
from airflow.api_connexion.exceptions import EXCEPTIONS_LINK_MAP
from airflow.jobs.job import Job
from airflow.jobs.triggerer_job_runner import TriggererJobRunner
from airflow.models import DagRun, SlaMiss, TaskInstance, Trigger
from airflow.models.renderedtifields import RenderedTaskInstanceFields as RTIF
from airflow.security import permissions
from airflow.utils.platform import getuser
from airflow.utils.session import provide_session
from airflow.utils.state import State
from airflow.utils.timezone import datetime
from airflow.utils.types import DagRunType
from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_roles, delete_user
from tests.test_utils.db import clear_db_runs, clear_db_sla_miss, clear_rendered_ti_fields
from tests.test_utils.www import _check_last_log
pytestmark = pytest.mark.db_test
DEFAULT_DATETIME_1 = datetime(2020, 1, 1)
DEFAULT_DATETIME_STR_1 = "2020-01-01T00:00:00+00:00"
DEFAULT_DATETIME_STR_2 = "2020-01-02T00:00:00+00:00"
QUOTED_DEFAULT_DATETIME_STR_1 = urllib.parse.quote(DEFAULT_DATETIME_STR_1)
QUOTED_DEFAULT_DATETIME_STR_2 = urllib.parse.quote(DEFAULT_DATETIME_STR_2)
@pytest.fixture(scope="module")
def configured_app(minimal_app_for_api):
app = minimal_app_for_api
create_user(
app, # type: ignore
username="test",
role_name="Test",
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_INSTANCE),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_TASK_INSTANCE),
],
)
create_user(
app, # type: ignore
username="test_dag_read_only",
role_name="TestDagReadOnly",
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_INSTANCE),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_TASK_INSTANCE),
],
)
create_user(
app, # type: ignore
username="test_task_read_only",
role_name="TestTaskReadOnly",
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_DAG),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_INSTANCE),
],
)
create_user(
app, # type: ignore
username="test_read_only_one_dag",
role_name="TestReadOnlyOneDag",
permissions=[
(permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG_RUN),
(permissions.ACTION_CAN_READ, permissions.RESOURCE_TASK_INSTANCE),
],
)
# For some reason, "DAG:example_python_operator" is not synced when in the above list of perms,
# so do it manually here:
app.appbuilder.sm.bulk_sync_roles(
[
{
"role": "TestReadOnlyOneDag",
"perms": [(permissions.ACTION_CAN_READ, "DAG:example_python_operator")],
}
]
)
create_user(app, username="test_no_permissions", role_name="TestNoPermissions") # type: ignore
yield app
delete_user(app, username="test") # type: ignore
delete_user(app, username="test_dag_read_only") # type: ignore
delete_user(app, username="test_task_read_only") # type: ignore
delete_user(app, username="test_no_permissions") # type: ignore
delete_user(app, username="test_read_only_one_dag") # type: ignore
delete_roles(app)
class TestTaskInstanceEndpoint:
@pytest.fixture(autouse=True)
def setup_attrs(self, configured_app, dagbag) -> None:
self.default_time = DEFAULT_DATETIME_1
self.ti_init = {
"execution_date": self.default_time,
"state": State.RUNNING,
}
self.ti_extras = {
"start_date": self.default_time + dt.timedelta(days=1),
"end_date": self.default_time + dt.timedelta(days=2),
"pid": 100,
"duration": 10000,
"pool": "default_pool",
"queue": "default_queue",
"job_id": 0,
}
self.app = configured_app
self.client = self.app.test_client() # type:ignore
clear_db_runs()
clear_db_sla_miss()
clear_rendered_ti_fields()
self.dagbag = dagbag
def create_task_instances(
self,
session,
dag_id: str = "example_python_operator",
update_extras: bool = True,
task_instances=None,
dag_run_state=State.RUNNING,
):
"""Method to create task instances using kwargs and default arguments"""
dag = self.dagbag.get_dag(dag_id)
tasks = dag.tasks
counter = len(tasks)
if task_instances is not None:
counter = min(len(task_instances), counter)
run_id = "TEST_DAG_RUN_ID"
execution_date = self.ti_init.pop("execution_date", self.default_time)
dr = None
tis = []
for i in range(counter):
if task_instances is None:
pass
elif update_extras:
self.ti_extras.update(task_instances[i])
else:
self.ti_init.update(task_instances[i])
if "execution_date" in self.ti_init:
run_id = f"TEST_DAG_RUN_ID_{i}"
execution_date = self.ti_init.pop("execution_date")
dr = None
if not dr:
dr = DagRun(
run_id=run_id,
dag_id=dag_id,
execution_date=execution_date,
run_type=DagRunType.MANUAL,
state=dag_run_state,
)
session.add(dr)
ti = TaskInstance(task=tasks[i], **self.ti_init)
ti.dag_run = dr
ti.note = "placeholder-note"
for key, value in self.ti_extras.items():
setattr(ti, key, value)
session.add(ti)
tis.append(ti)
session.commit()
return tis
class TestGetTaskInstance(TestTaskInstanceEndpoint):
def setup_method(self):
clear_db_runs()
def teardown_method(self):
clear_db_runs()
@pytest.mark.parametrize("username", ["test", "test_dag_read_only", "test_task_read_only"])
@provide_session
def test_should_respond_200(self, username, session):
self.create_task_instances(session)
# Update ti and set operator to None to
# test that operator field is nullable.
# This prevents issue when users upgrade to 2.0+
# from 1.10.x
# https://github.com/apache/airflow/issues/14421
session.query(TaskInstance).update({TaskInstance.operator: None}, synchronize_session="fetch")
session.commit()
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context",
environ_overrides={"REMOTE_USER": username},
)
assert response.status_code == 200
assert response.json == {
"dag_id": "example_python_operator",
"duration": 10000.0,
"end_date": "2020-01-03T00:00:00+00:00",
"execution_date": "2020-01-01T00:00:00+00:00",
"executor_config": "{}",
"hostname": "",
"map_index": -1,
"max_tries": 0,
"note": "placeholder-note",
"operator": None,
"pid": 100,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 9,
"queue": "default_queue",
"queued_when": None,
"sla_miss": None,
"start_date": "2020-01-02T00:00:00+00:00",
"state": "running",
"task_id": "print_the_context",
"task_display_name": "print_the_context",
"try_number": 0,
"unixname": getuser(),
"dag_run_id": "TEST_DAG_RUN_ID",
"rendered_fields": {},
"rendered_map_index": None,
"trigger": None,
"triggerer_job": None,
}
def test_should_respond_200_with_task_state_in_deferred(self, session):
now = pendulum.now("UTC")
ti = self.create_task_instances(
session, task_instances=[{"state": State.DEFERRED}], update_extras=True
)[0]
ti.trigger = Trigger("none", {})
ti.trigger.created_date = now
ti.triggerer_job = Job()
TriggererJobRunner(job=ti.triggerer_job)
ti.triggerer_job.state = "running"
session.commit()
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context",
environ_overrides={"REMOTE_USER": "test"},
)
data = response.json
# this logic in effect replicates mock.ANY for these values
values_to_ignore = {
"trigger": ["created_date", "id", "triggerer_id"],
"triggerer_job": ["executor_class", "hostname", "id", "latest_heartbeat", "start_date"],
}
for k, v in values_to_ignore.items():
for elem in v:
del data[k][elem]
assert response.status_code == 200
assert data == {
"dag_id": "example_python_operator",
"duration": 10000.0,
"end_date": "2020-01-03T00:00:00+00:00",
"execution_date": "2020-01-01T00:00:00+00:00",
"executor_config": "{}",
"hostname": "",
"map_index": -1,
"max_tries": 0,
"note": "placeholder-note",
"operator": "PythonOperator",
"pid": 100,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 9,
"queue": "default_queue",
"queued_when": None,
"sla_miss": None,
"start_date": "2020-01-02T00:00:00+00:00",
"state": "deferred",
"task_id": "print_the_context",
"task_display_name": "print_the_context",
"try_number": 0,
"unixname": getuser(),
"dag_run_id": "TEST_DAG_RUN_ID",
"rendered_fields": {},
"rendered_map_index": None,
"trigger": {
"classpath": "none",
"kwargs": "{}",
},
"triggerer_job": {
"dag_id": None,
"end_date": None,
"job_type": "TriggererJob",
"state": "running",
"unixname": getuser(),
},
}
def test_should_respond_200_with_task_state_in_removed(self, session):
self.create_task_instances(session, task_instances=[{"state": State.REMOVED}], update_extras=True)
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context",
environ_overrides={"REMOTE_USER": "test"},
)
assert response.status_code == 200
assert response.json == {
"dag_id": "example_python_operator",
"duration": 10000.0,
"end_date": "2020-01-03T00:00:00+00:00",
"execution_date": "2020-01-01T00:00:00+00:00",
"executor_config": "{}",
"hostname": "",
"map_index": -1,
"max_tries": 0,
"note": "placeholder-note",
"operator": "PythonOperator",
"pid": 100,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 9,
"queue": "default_queue",
"queued_when": None,
"sla_miss": None,
"start_date": "2020-01-02T00:00:00+00:00",
"state": "removed",
"task_id": "print_the_context",
"task_display_name": "print_the_context",
"try_number": 0,
"unixname": getuser(),
"dag_run_id": "TEST_DAG_RUN_ID",
"rendered_fields": {},
"rendered_map_index": None,
"trigger": None,
"triggerer_job": None,
}
def test_should_respond_200_task_instance_with_sla_and_rendered(self, session):
tis = self.create_task_instances(session)
session.query()
sla_miss = SlaMiss(
task_id="print_the_context",
dag_id="example_python_operator",
execution_date=self.default_time,
timestamp=self.default_time,
)
session.add(sla_miss)
rendered_fields = RTIF(tis[0], render_templates=False)
session.add(rendered_fields)
session.commit()
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context",
environ_overrides={"REMOTE_USER": "test"},
)
assert response.status_code == 200
assert response.json == {
"dag_id": "example_python_operator",
"duration": 10000.0,
"end_date": "2020-01-03T00:00:00+00:00",
"execution_date": "2020-01-01T00:00:00+00:00",
"executor_config": "{}",
"hostname": "",
"map_index": -1,
"max_tries": 0,
"note": "placeholder-note",
"operator": "PythonOperator",
"pid": 100,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 9,
"queue": "default_queue",
"queued_when": None,
"sla_miss": {
"dag_id": "example_python_operator",
"description": None,
"email_sent": False,
"execution_date": "2020-01-01T00:00:00+00:00",
"notification_sent": False,
"task_id": "print_the_context",
"timestamp": "2020-01-01T00:00:00+00:00",
},
"start_date": "2020-01-02T00:00:00+00:00",
"state": "running",
"task_id": "print_the_context",
"task_display_name": "print_the_context",
"try_number": 0,
"unixname": getuser(),
"dag_run_id": "TEST_DAG_RUN_ID",
"rendered_fields": {"op_args": [], "op_kwargs": {}, "templates_dict": None},
"rendered_map_index": None,
"trigger": None,
"triggerer_job": None,
}
def test_should_respond_200_mapped_task_instance_with_rtif(self, session):
"""Verify we don't duplicate rows through join to RTIF"""
tis = self.create_task_instances(session)
old_ti = tis[0]
for idx in (1, 2):
ti = TaskInstance(task=old_ti.task, run_id=old_ti.run_id, map_index=idx)
ti.rendered_task_instance_fields = RTIF(ti, render_templates=False)
for attr in ["duration", "end_date", "pid", "start_date", "state", "queue", "note"]:
setattr(ti, attr, getattr(old_ti, attr))
session.add(ti)
session.commit()
# in each loop, we should get the right mapped TI back
for map_index in (1, 2):
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances"
f"/print_the_context/{map_index}",
environ_overrides={"REMOTE_USER": "test"},
)
assert response.status_code == 200
assert response.json == {
"dag_id": "example_python_operator",
"duration": 10000.0,
"end_date": "2020-01-03T00:00:00+00:00",
"execution_date": "2020-01-01T00:00:00+00:00",
"executor_config": "{}",
"hostname": "",
"map_index": map_index,
"max_tries": 0,
"note": "placeholder-note",
"operator": "PythonOperator",
"pid": 100,
"pool": "default_pool",
"pool_slots": 1,
"priority_weight": 9,
"queue": "default_queue",
"queued_when": None,
"sla_miss": None,
"start_date": "2020-01-02T00:00:00+00:00",
"state": "running",
"task_id": "print_the_context",
"task_display_name": "print_the_context",
"try_number": 0,
"unixname": getuser(),
"dag_run_id": "TEST_DAG_RUN_ID",
"rendered_fields": {"op_args": [], "op_kwargs": {}, "templates_dict": None},
"rendered_map_index": None,
"trigger": None,
"triggerer_job": None,
}
def test_should_raises_401_unauthenticated(self):
response = self.client.get(
"api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context",
)
assert_401(response)
def test_should_raise_403_forbidden(self):
response = self.client.get(
"api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context",
environ_overrides={"REMOTE_USER": "test_no_permissions"},
)
assert response.status_code == 403
def test_raises_404_for_nonexistent_task_instance(self):
response = self.client.get(
"api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/nonexistent_task",
environ_overrides={"REMOTE_USER": "test"},
)
assert response.status_code == 404
assert response.json["title"] == "Task instance not found"
def test_unmapped_map_index_should_return_404(self, session):
self.create_task_instances(session)
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context/-1",
environ_overrides={"REMOTE_USER": "test"},
)
assert response.status_code == 404
def test_should_return_404_for_mapped_endpoint(self, session):
self.create_task_instances(session)
for index in ["0", "1", "2"]:
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/"
f"taskInstances/print_the_context/{index}",
environ_overrides={"REMOTE_USER": "test"},
)
assert response.status_code == 404
def test_should_return_404_for_list_mapped_endpoint(self, session):
self.create_task_instances(session)
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/"
"taskInstances/print_the_context/listMapped",
environ_overrides={"REMOTE_USER": "test"},
)
assert response.status_code == 404
class TestGetTaskInstances(TestTaskInstanceEndpoint):
@pytest.mark.parametrize(
"task_instances, update_extras, url, expected_ti",
[
pytest.param(
[
{"execution_date": DEFAULT_DATETIME_1},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=1)},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=2)},
],
False,
(
"/api/v1/dags/example_python_operator/dagRuns/~/"
f"taskInstances?execution_date_lte={QUOTED_DEFAULT_DATETIME_STR_1}"
),
1,
id="test execution date filter",
),
pytest.param(
[
{"start_date": DEFAULT_DATETIME_1},
{"start_date": DEFAULT_DATETIME_1 + dt.timedelta(days=1)},
{"start_date": DEFAULT_DATETIME_1 + dt.timedelta(days=2)},
],
True,
(
"/api/v1/dags/example_python_operator/dagRuns/~/taskInstances"
f"?start_date_gte={QUOTED_DEFAULT_DATETIME_STR_1}&"
f"start_date_lte={QUOTED_DEFAULT_DATETIME_STR_2}"
),
2,
id="test start date filter",
),
pytest.param(
[
{"end_date": DEFAULT_DATETIME_1},
{"end_date": DEFAULT_DATETIME_1 + dt.timedelta(days=1)},
{"end_date": DEFAULT_DATETIME_1 + dt.timedelta(days=2)},
],
True,
(
"/api/v1/dags/example_python_operator/dagRuns/~/taskInstances?"
f"end_date_gte={QUOTED_DEFAULT_DATETIME_STR_1}&"
f"end_date_lte={QUOTED_DEFAULT_DATETIME_STR_2}"
),
2,
id="test end date filter",
),
pytest.param(
[
{"duration": 100},
{"duration": 150},
{"duration": 200},
],
True,
(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/"
"taskInstances?duration_gte=100&duration_lte=200"
),
3,
id="test duration filter",
),
pytest.param(
[
{"duration": 100},
{"duration": 150},
{"duration": 200},
],
True,
"/api/v1/dags/~/dagRuns/~/taskInstances?duration_gte=100&duration_lte=200",
3,
id="test duration filter ~",
),
pytest.param(
[
{"state": State.RUNNING},
{"state": State.QUEUED},
{"state": State.SUCCESS},
{"state": State.NONE},
],
False,
(
"/api/v1/dags/example_python_operator/dagRuns/"
"TEST_DAG_RUN_ID/taskInstances?state=running,queued,none"
),
3,
id="test state filter",
),
pytest.param(
[
{"state": State.NONE},
{"state": State.NONE},
{"state": State.NONE},
{"state": State.NONE},
],
False,
("/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances"),
4,
id="test null states with no filter",
),
pytest.param(
[
{"pool": "test_pool_1"},
{"pool": "test_pool_2"},
{"pool": "test_pool_3"},
],
True,
(
"/api/v1/dags/example_python_operator/dagRuns/"
"TEST_DAG_RUN_ID/taskInstances?pool=test_pool_1,test_pool_2"
),
2,
id="test pool filter",
),
pytest.param(
[
{"pool": "test_pool_1"},
{"pool": "test_pool_2"},
{"pool": "test_pool_3"},
],
True,
"/api/v1/dags/~/dagRuns/~/taskInstances?pool=test_pool_1,test_pool_2",
2,
id="test pool filter ~",
),
pytest.param(
[
{"queue": "test_queue_1"},
{"queue": "test_queue_2"},
{"queue": "test_queue_3"},
],
True,
(
"/api/v1/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID"
"/taskInstances?queue=test_queue_1,test_queue_2"
),
2,
id="test queue filter",
),
pytest.param(
[
{"queue": "test_queue_1"},
{"queue": "test_queue_2"},
{"queue": "test_queue_3"},
],
True,
"/api/v1/dags/~/dagRuns/~/taskInstances?queue=test_queue_1,test_queue_2",
2,
id="test queue filter ~",
),
],
)
def test_should_respond_200(self, task_instances, update_extras, url, expected_ti, session):
self.create_task_instances(
session,
update_extras=update_extras,
task_instances=task_instances,
)
response = self.client.get(url, environ_overrides={"REMOTE_USER": "test"})
assert response.status_code == 200
assert response.json["total_entries"] == expected_ti
assert len(response.json["task_instances"]) == expected_ti
@pytest.mark.parametrize(
"task_instances, user, expected_ti",
[
pytest.param(
{
"example_python_operator": 2,
"example_skip_dag": 1,
},
"test_read_only_one_dag",
2,
),
pytest.param(
{
"example_python_operator": 1,
"example_skip_dag": 2,
},
"test_read_only_one_dag",
1,
),
pytest.param(
{
"example_python_operator": 1,
"example_skip_dag": 2,
},
"test",
3,
),
],
)
def test_return_TI_only_from_readable_dags(self, task_instances, user, expected_ti, session):
for dag_id in task_instances:
self.create_task_instances(
session,
task_instances=[
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=i)}
for i in range(task_instances[dag_id])
],
dag_id=dag_id,
)
response = self.client.get(
"/api/v1/dags/~/dagRuns/~/taskInstances", environ_overrides={"REMOTE_USER": user}
)
assert response.status_code == 200
assert response.json["total_entries"] == expected_ti
assert len(response.json["task_instances"]) == expected_ti
def test_should_respond_200_for_dag_id_filter(self, session):
self.create_task_instances(session)
self.create_task_instances(session, dag_id="example_skip_dag")
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/~/taskInstances",
environ_overrides={"REMOTE_USER": "test"},
)
assert response.status_code == 200
count = session.query(TaskInstance).filter(TaskInstance.dag_id == "example_python_operator").count()
assert count == response.json["total_entries"]
assert count == len(response.json["task_instances"])
def test_should_raises_401_unauthenticated(self):
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/~/taskInstances",
)
assert_401(response)
def test_should_raise_403_forbidden(self):
response = self.client.get(
"/api/v1/dags/example_python_operator/dagRuns/~/taskInstances",
environ_overrides={"REMOTE_USER": "test_no_permissions"},
)
assert response.status_code == 403
class TestGetTaskInstancesBatch(TestTaskInstanceEndpoint):
@pytest.mark.parametrize(
"task_instances, update_extras, payload, expected_ti_count, username",
[
pytest.param(
[
{"queue": "test_queue_1"},
{"queue": "test_queue_2"},
{"queue": "test_queue_3"},
],
True,
{"queue": ["test_queue_1", "test_queue_2"]},
2,
"test",
id="test queue filter",
),
pytest.param(
[
{"pool": "test_pool_1"},
{"pool": "test_pool_2"},
{"pool": "test_pool_3"},
],
True,
{"pool": ["test_pool_1", "test_pool_2"]},
2,
"test_dag_read_only",
id="test pool filter",
),
pytest.param(
[
{"state": State.RUNNING},
{"state": State.QUEUED},
{"state": State.SUCCESS},
{"state": State.NONE},
],
False,
{"state": ["running", "queued", "none"]},
3,
"test_task_read_only",
id="test state filter",
),
pytest.param(
[
{"state": State.NONE},
{"state": State.NONE},
{"state": State.NONE},
{"state": State.NONE},
],
False,
{},
4,
"test_task_read_only",
id="test dag with null states",
),
pytest.param(
[
{"duration": 100},
{"duration": 150},
{"duration": 200},
],
True,
{"duration_gte": 100, "duration_lte": 200},
3,
"test",
id="test duration filter",
),
pytest.param(
[
{"end_date": DEFAULT_DATETIME_1},
{"end_date": DEFAULT_DATETIME_1 + dt.timedelta(days=1)},
{"end_date": DEFAULT_DATETIME_1 + dt.timedelta(days=2)},
],
True,
{
"end_date_gte": DEFAULT_DATETIME_STR_1,
"end_date_lte": DEFAULT_DATETIME_STR_2,
},
2,
"test_task_read_only",
id="test end date filter",
),
pytest.param(
[
{"start_date": DEFAULT_DATETIME_1},
{"start_date": DEFAULT_DATETIME_1 + dt.timedelta(days=1)},
{"start_date": DEFAULT_DATETIME_1 + dt.timedelta(days=2)},
],
True,
{
"start_date_gte": DEFAULT_DATETIME_STR_1,
"start_date_lte": DEFAULT_DATETIME_STR_2,
},
2,
"test_dag_read_only",
id="test start date filter",
),
pytest.param(
[
{"execution_date": DEFAULT_DATETIME_1},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=1)},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=2)},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=3)},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=4)},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=5)},
],
False,
{
"execution_date_gte": DEFAULT_DATETIME_1.isoformat(),
"execution_date_lte": (DEFAULT_DATETIME_1 + dt.timedelta(days=2)).isoformat(),
},
3,
"test",
id="with execution date filter",
),
pytest.param(
[
{"execution_date": DEFAULT_DATETIME_1},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=1)},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=2)},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=3)},
],
False,
{
"dag_run_ids": ["TEST_DAG_RUN_ID_0", "TEST_DAG_RUN_ID_1"],
},
2,
"test",
id="test dag run id filter",
),
pytest.param(
[
{"execution_date": DEFAULT_DATETIME_1},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=1)},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=2)},
{"execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=3)},
],
False,
{
"task_ids": ["print_the_context", "log_sql_query"],
},
2,
"test",
id="test task id filter",
),
],
)
def test_should_respond_200(
self, task_instances, update_extras, payload, expected_ti_count, username, session
):
self.create_task_instances(
session,
update_extras=update_extras,
task_instances=task_instances,
)
response = self.client.post(
"/api/v1/dags/~/dagRuns/~/taskInstances/list",
environ_overrides={"REMOTE_USER": username},
json=payload,
)
assert response.status_code == 200, response.json
assert expected_ti_count == response.json["total_entries"]
assert expected_ti_count == len(response.json["task_instances"])
@pytest.mark.parametrize(
"task_instances, payload, expected_ti_count",
[
pytest.param(
[
{"task": "test_1"},
{"task": "test_2"},
],
{"dag_ids": ["latest_only"]},
2,
id="task_instance properties",
),
],
)
@provide_session
def test_should_respond_200_when_task_instance_properties_are_none(
self, task_instances, payload, expected_ti_count, session
):
self.ti_extras.update(
{
"start_date": None,
"end_date": None,
"state": None,
}
)
self.create_task_instances(
session,
dag_id="latest_only",
task_instances=task_instances,
)
response = self.client.post(
"/api/v1/dags/~/dagRuns/~/taskInstances/list",
environ_overrides={"REMOTE_USER": "test"},
json=payload,
)
assert response.status_code == 200, response.json
assert expected_ti_count == response.json["total_entries"]
assert expected_ti_count == len(response.json["task_instances"])
@pytest.mark.parametrize(
"payload, expected_ti, total_ti",
[
pytest.param(
{"dag_ids": ["example_python_operator", "example_skip_dag"]},
17,
17,
id="with dag filter",
),
],
)
@provide_session
def test_should_respond_200_dag_ids_filter(self, payload, expected_ti, total_ti, session):
self.create_task_instances(session)
self.create_task_instances(session, dag_id="example_skip_dag")
response = self.client.post(
"/api/v1/dags/~/dagRuns/~/taskInstances/list",
environ_overrides={"REMOTE_USER": "test"},
json=payload,
)
assert response.status_code == 200
assert len(response.json["task_instances"]) == expected_ti
assert response.json["total_entries"] == total_ti
def test_should_raises_401_unauthenticated(self):
response = self.client.post(
"/api/v1/dags/~/dagRuns/~/taskInstances/list",
json={"dag_ids": ["example_python_operator", "example_skip_dag"]},
)
assert_401(response)
def test_should_raise_403_forbidden(self):
response = self.client.post(
"/api/v1/dags/~/dagRuns/~/taskInstances/list",
environ_overrides={"REMOTE_USER": "test_no_permissions"},
json={"dag_ids": ["example_python_operator", "example_skip_dag"]},
)
assert response.status_code == 403
def test_returns_403_forbidden_when_user_has_access_to_only_some_dags(self, session):
self.create_task_instances(session=session)
self.create_task_instances(session=session, dag_id="example_skip_dag")
payload = {"dag_ids": ["example_python_operator", "example_skip_dag"]}