forked from apache/airflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_task_command.py
More file actions
633 lines (558 loc) · 23.7 KB
/
Copy pathtest_task_command.py
File metadata and controls
633 lines (558 loc) · 23.7 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
# 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
import uuid
from unittest import mock
import httpx
import pytest
from airflowctl.api.datamodels.generated import (
TaskDependencyCollectionResponse,
TaskDependencyResponse,
TaskInstanceCollectionResponse,
TaskInstanceResponse,
TaskInstanceState,
)
from airflowctl.api.operations import ServerResponseError
from airflowctl.ctl import cli_parser
from airflowctl.ctl.commands import task_command
def _make_server_error(status_code: int) -> ServerResponseError:
request = httpx.Request("GET", "http://testserver/api/v2/dags/test_dag/dagRuns/test_run")
response = httpx.Response(status_code, request=request, json={"detail": "boom"})
return ServerResponseError(message="boom", request=request, response=response)
def _normalize_rich_output(text: str) -> str:
return " ".join(text.split())
class TestFailedDeps:
parser = cli_parser.get_parser()
dag_id = "test_dag"
run_id = "test_run"
task_id = "test_task"
logical_date = datetime.datetime(2025, 1, 1, tzinfo=datetime.timezone.utc)
def _make_task_instance(self, state: TaskInstanceState | None) -> TaskInstanceResponse:
return TaskInstanceResponse(
id=uuid.uuid4(),
task_id=self.task_id,
dag_id=self.dag_id,
dag_run_id=self.run_id,
map_index=-1,
logical_date=self.logical_date,
run_after=self.logical_date,
state=state,
start_date=None,
end_date=None,
try_number=1,
max_tries=0,
task_display_name=self.task_id,
dag_display_name=self.dag_id,
pool="default_pool",
pool_slots=1,
executor_config="{}",
duration=None,
hostname=None,
unixname=None,
queue=None,
priority_weight=None,
operator=None,
operator_name=None,
queued_when=None,
scheduled_when=None,
pid=None,
executor=None,
note=None,
rendered_map_index=None,
trigger=None,
triggerer_job=None,
dag_version=None,
)
def _make_api_client(
self,
dependencies: list[TaskDependencyResponse] | None = None,
state: TaskInstanceState | None = None,
) -> mock.MagicMock:
api_client = mock.MagicMock()
api_client.dag_runs.list.return_value.dag_runs = [mock.MagicMock(dag_run_id=self.run_id)]
api_client.task_instances.get_dependencies.return_value = TaskDependencyCollectionResponse(
dependencies=dependencies or [],
)
api_client.task_instances.get.return_value = self._make_task_instance(state=state)
return api_client
def test_failed_deps_not_met(self, capsys):
api_client = self._make_api_client(
dependencies=[
TaskDependencyResponse(
name="Dagrun Running", reason="Task instance's dagrun was not in the 'running' state"
),
TaskDependencyResponse(
name="Trigger Rule", reason="requires all upstream tasks to have succeeded"
),
]
)
task_command.failed_deps(
self.parser.parse_args(["tasks", "failed-deps", self.dag_id, self.task_id, self.run_id]),
api_client=api_client,
)
api_client.task_instances.get_dependencies.assert_called_once_with(
dag_id=self.dag_id,
dag_run_id=self.run_id,
task_id=self.task_id,
map_index=-1,
suppress_error_log=True,
)
api_client.task_instances.get.assert_not_called()
assert capsys.readouterr().out == (
"Task instance dependencies not met:\n"
"Dagrun Running: Task instance's dagrun was not in the 'running' state\n"
"Trigger Rule: requires all upstream tasks to have succeeded\n"
)
@pytest.mark.parametrize("state", [None, TaskInstanceState.SCHEDULED])
def test_failed_deps_all_met(self, state, capsys):
api_client = self._make_api_client(state=state)
task_command.failed_deps(
self.parser.parse_args(["tasks", "failed-deps", self.dag_id, self.task_id, self.run_id]),
api_client=api_client,
)
api_client.task_instances.get.assert_called_once_with(
dag_id=self.dag_id,
dag_run_id=self.run_id,
task_id=self.task_id,
map_index=-1,
suppress_error_log=True,
)
assert capsys.readouterr().out == "Task instance dependencies are all met.\n"
def test_failed_deps_not_evaluated_for_already_queued_task(self, capsys):
api_client = self._make_api_client(state=TaskInstanceState.SUCCESS)
task_command.failed_deps(
self.parser.parse_args(["tasks", "failed-deps", self.dag_id, self.task_id, self.run_id]),
api_client=api_client,
)
assert capsys.readouterr().out == (
"Task instance is in the 'success' state; scheduler dependencies are only evaluated "
"for task instances that have not yet been queued.\n"
)
def test_failed_deps_with_map_index(self, capsys):
api_client = self._make_api_client(
dependencies=[TaskDependencyResponse(name="Pool Slots Available", reason="pool is full")]
)
task_command.failed_deps(
self.parser.parse_args(
["tasks", "failed-deps", self.dag_id, self.task_id, self.run_id, "--map-index", "3"]
),
api_client=api_client,
)
api_client.task_instances.get_dependencies.assert_called_once_with(
dag_id=self.dag_id,
dag_run_id=self.run_id,
task_id=self.task_id,
map_index=3,
suppress_error_log=True,
)
assert capsys.readouterr().out == (
"Task instance dependencies not met:\nPool Slots Available: pool is full\n"
)
def test_failed_deps_by_logical_date(self, capsys):
api_client = self._make_api_client(
dependencies=[TaskDependencyResponse(name="Trigger Rule", reason="upstream tasks not done")]
)
task_command.failed_deps(
self.parser.parse_args(
[
"tasks",
"failed-deps",
self.dag_id,
self.task_id,
"--logical-date",
self.logical_date.isoformat(),
]
),
api_client=api_client,
)
api_client.dag_runs.list.assert_called_once_with(
dag_id=self.dag_id,
logical_date_gte=self.logical_date,
logical_date_lte=self.logical_date,
order_by="-id",
limit=1,
suppress_error_log=True,
)
api_client.task_instances.get_dependencies.assert_called_once_with(
dag_id=self.dag_id,
dag_run_id=self.run_id,
task_id=self.task_id,
map_index=-1,
suppress_error_log=True,
)
assert capsys.readouterr().out == (
"Task instance dependencies not met:\nTrigger Rule: upstream tasks not done\n"
)
@pytest.mark.parametrize(
"extra_args",
[
[],
["test_run", "--logical-date", "2025-01-01T00:00:00+00:00"],
],
ids=["neither", "both"],
)
def test_failed_deps_requires_exactly_one_of_run_id_and_logical_date(self, extra_args, capsys):
api_client = self._make_api_client()
with pytest.raises(SystemExit, match="1"):
task_command.failed_deps(
self.parser.parse_args(["tasks", "failed-deps", self.dag_id, self.task_id, *extra_args]),
api_client=api_client,
)
api_client.task_instances.get_dependencies.assert_not_called()
assert _normalize_rich_output(capsys.readouterr().out) == (
"Provide either run_id or --logical-date, but not both"
)
@pytest.mark.parametrize(
("logical_date", "expected_message"),
[
("not-a-date", "Invalid --logical-date: 'not-a-date'"),
("2025-01-01T00:00:00", "--logical-date must include a timezone offset"),
],
ids=["unparsable", "naive"],
)
def test_failed_deps_rejects_bad_logical_date(self, logical_date, expected_message, capsys):
api_client = self._make_api_client()
with pytest.raises(SystemExit, match="1"):
task_command.failed_deps(
self.parser.parse_args(
["tasks", "failed-deps", self.dag_id, self.task_id, "--logical-date", logical_date]
),
api_client=api_client,
)
api_client.dag_runs.list.assert_not_called()
assert _normalize_rich_output(capsys.readouterr().out) == expected_message
@pytest.mark.parametrize("list_failure", ["no_matching_run", "dag_not_found_404"])
def test_failed_deps_dag_run_not_found_by_logical_date(self, list_failure, capsys):
api_client = self._make_api_client()
if list_failure == "no_matching_run":
api_client.dag_runs.list.return_value.dag_runs = []
else:
api_client.dag_runs.list.side_effect = _make_server_error(404)
with pytest.raises(SystemExit, match="1"):
task_command.failed_deps(
self.parser.parse_args(
[
"tasks",
"failed-deps",
self.dag_id,
self.task_id,
"--logical-date",
self.logical_date.isoformat(),
]
),
api_client=api_client,
)
api_client.task_instances.get_dependencies.assert_not_called()
assert _normalize_rich_output(capsys.readouterr().out) == (
"Dag run for test_dag with logical date '2025-01-01T00:00:00+00:00' not found"
)
@pytest.mark.parametrize(
("extra_args", "expected_message"),
[
([], "Task instance for task 'test_task' in Dag run 'test_run' of Dag 'test_dag' not found"),
(
["--map-index", "3"],
"Task instance for task 'test_task' with map index 3 in Dag run 'test_run' "
"of Dag 'test_dag' not found",
),
],
)
def test_failed_deps_task_instance_not_found(self, extra_args, expected_message, capsys):
api_client = self._make_api_client()
api_client.task_instances.get_dependencies.side_effect = _make_server_error(404)
with pytest.raises(SystemExit, match="1"):
task_command.failed_deps(
self.parser.parse_args(
["tasks", "failed-deps", self.dag_id, self.task_id, self.run_id, *extra_args]
),
api_client=api_client,
)
assert _normalize_rich_output(capsys.readouterr().out) == expected_message
def test_failed_deps_task_instance_deleted_between_requests(self, capsys):
api_client = self._make_api_client()
api_client.task_instances.get.side_effect = _make_server_error(404)
with pytest.raises(SystemExit, match="1"):
task_command.failed_deps(
self.parser.parse_args(["tasks", "failed-deps", self.dag_id, self.task_id, self.run_id]),
api_client=api_client,
)
assert _normalize_rich_output(capsys.readouterr().out) == (
"Task instance for task 'test_task' in Dag run 'test_run' of Dag 'test_dag' not found"
)
def test_failed_deps_reraises_non_404_task_instance_get_error(self):
api_client = self._make_api_client()
api_client.task_instances.get.side_effect = _make_server_error(500)
with pytest.raises(ServerResponseError):
task_command.failed_deps(
self.parser.parse_args(["tasks", "failed-deps", self.dag_id, self.task_id, self.run_id]),
api_client=api_client,
)
def test_failed_deps_reraises_non_404_error(self):
api_client = self._make_api_client()
api_client.task_instances.get_dependencies.side_effect = _make_server_error(500)
with pytest.raises(ServerResponseError):
task_command.failed_deps(
self.parser.parse_args(["tasks", "failed-deps", self.dag_id, self.task_id, self.run_id]),
api_client=api_client,
)
def test_failed_deps_reraises_non_404_dag_run_list_error(self):
api_client = self._make_api_client()
api_client.dag_runs.list.side_effect = _make_server_error(500)
with pytest.raises(ServerResponseError):
task_command.failed_deps(
self.parser.parse_args(
[
"tasks",
"failed-deps",
self.dag_id,
self.task_id,
"--logical-date",
self.logical_date.isoformat(),
]
),
api_client=api_client,
)
class TestStatesForDagRun:
parser = cli_parser.get_parser()
dag_id = "test_dag"
run_id = "test_run"
logical_date = datetime.datetime(2025, 1, 1, tzinfo=datetime.timezone.utc)
def _make_task_instance(
self,
task_id: str,
*,
map_index: int = -1,
state: TaskInstanceState | None = TaskInstanceState.SUCCESS,
start_date: datetime.datetime | None = None,
end_date: datetime.datetime | None = None,
) -> TaskInstanceResponse:
return TaskInstanceResponse(
id=uuid.uuid4(),
task_id=task_id,
dag_id=self.dag_id,
dag_run_id=self.run_id,
map_index=map_index,
logical_date=self.logical_date,
run_after=self.logical_date,
state=state,
start_date=start_date,
end_date=end_date,
try_number=1,
max_tries=0,
task_display_name=task_id,
dag_display_name=self.dag_id,
pool="default_pool",
pool_slots=1,
executor_config="{}",
duration=None,
hostname=None,
unixname=None,
queue=None,
priority_weight=None,
operator=None,
operator_name=None,
queued_when=None,
scheduled_when=None,
pid=None,
executor=None,
note=None,
rendered_map_index=None,
trigger=None,
triggerer_job=None,
dag_version=None,
)
def _make_api_client(self, task_instances: list[TaskInstanceResponse]) -> mock.MagicMock:
api_client = mock.MagicMock()
api_client.dag_runs.list.return_value.dag_runs = [mock.MagicMock(dag_run_id=self.run_id)]
api_client.task_instances.list.return_value = TaskInstanceCollectionResponse(
task_instances=task_instances,
total_entries=len(task_instances),
)
return api_client
@mock.patch("airflowctl.ctl.commands.task_command.AirflowConsole")
def test_states_for_dag_run_by_run_id(self, mock_console_cls):
start_date = datetime.datetime(2025, 1, 1, 1, tzinfo=datetime.timezone.utc)
end_date = datetime.datetime(2025, 1, 1, 2, tzinfo=datetime.timezone.utc)
api_client = self._make_api_client(
[
self._make_task_instance("task_a", start_date=start_date, end_date=end_date),
self._make_task_instance("task_b", state=None),
]
)
task_command.states_for_dag_run(
self.parser.parse_args(["tasks", "states-for-dag-run", self.dag_id, self.run_id]),
api_client=api_client,
)
api_client.dag_runs.list.assert_not_called()
api_client.task_instances.list.assert_called_once_with(dag_id=self.dag_id, dag_run_id=self.run_id)
mock_console_cls.return_value.print_as.assert_called_once_with(
data=[
{
"dag_id": self.dag_id,
"logical_date": "2025-01-01T00:00:00+00:00",
"task_id": "task_a",
"state": "success",
"start_date": "2025-01-01T01:00:00+00:00",
"end_date": "2025-01-01T02:00:00+00:00",
},
{
"dag_id": self.dag_id,
"logical_date": "2025-01-01T00:00:00+00:00",
"task_id": "task_b",
"state": "",
"start_date": "",
"end_date": "",
},
],
output="json",
)
@mock.patch("airflowctl.ctl.commands.task_command.AirflowConsole")
def test_states_for_dag_run_by_logical_date(self, mock_console_cls):
api_client = self._make_api_client([self._make_task_instance("task_a")])
task_command.states_for_dag_run(
self.parser.parse_args(
["tasks", "states-for-dag-run", self.dag_id, "--logical-date", self.logical_date.isoformat()]
),
api_client=api_client,
)
api_client.dag_runs.list.assert_called_once_with(
dag_id=self.dag_id,
logical_date_gte=self.logical_date,
logical_date_lte=self.logical_date,
order_by="-id",
limit=1,
suppress_error_log=True,
)
api_client.task_instances.list.assert_called_once_with(dag_id=self.dag_id, dag_run_id=self.run_id)
mock_console_cls.return_value.print_as.assert_called_once_with(
data=[
{
"dag_id": self.dag_id,
"logical_date": "2025-01-01T00:00:00+00:00",
"task_id": "task_a",
"state": "success",
"start_date": "",
"end_date": "",
},
],
output="json",
)
@mock.patch("airflowctl.ctl.commands.task_command.AirflowConsole")
def test_states_for_dag_run_includes_map_index_for_mapped_instances(self, mock_console_cls):
api_client = self._make_api_client(
[
self._make_task_instance("plain_task"),
self._make_task_instance("mapped_task", map_index=0),
self._make_task_instance("mapped_task", map_index=1),
]
)
task_command.states_for_dag_run(
self.parser.parse_args(["tasks", "states-for-dag-run", self.dag_id, self.run_id]),
api_client=api_client,
)
rows = mock_console_cls.return_value.print_as.call_args.kwargs["data"]
assert [row["map_index"] for row in rows] == ["", "0", "1"]
@pytest.mark.parametrize(
"extra_args",
[
[],
["test_run", "--logical-date", "2025-01-01T00:00:00+00:00"],
],
ids=["neither", "both"],
)
def test_states_for_dag_run_requires_exactly_one_of_run_id_and_logical_date(self, extra_args, capsys):
api_client = mock.MagicMock()
with pytest.raises(SystemExit, match="1"):
task_command.states_for_dag_run(
self.parser.parse_args(["tasks", "states-for-dag-run", self.dag_id, *extra_args]),
api_client=api_client,
)
api_client.task_instances.list.assert_not_called()
assert _normalize_rich_output(capsys.readouterr().out) == (
"Provide either run_id or --logical-date, but not both"
)
@pytest.mark.parametrize(
("logical_date", "expected_message"),
[
("not-a-date", "Invalid --logical-date: 'not-a-date'"),
("2025-01-01T00:00:00", "--logical-date must include a timezone offset"),
],
ids=["unparsable", "naive"],
)
def test_states_for_dag_run_rejects_bad_logical_date(self, logical_date, expected_message, capsys):
api_client = mock.MagicMock()
with pytest.raises(SystemExit, match="1"):
task_command.states_for_dag_run(
self.parser.parse_args(
["tasks", "states-for-dag-run", self.dag_id, "--logical-date", logical_date]
),
api_client=api_client,
)
api_client.dag_runs.list.assert_not_called()
assert _normalize_rich_output(capsys.readouterr().out) == expected_message
@pytest.mark.parametrize("list_failure", ["no_matching_run", "dag_not_found_404"])
def test_states_for_dag_run_dag_run_not_found_by_logical_date(self, list_failure, capsys):
api_client = mock.MagicMock()
if list_failure == "no_matching_run":
api_client.dag_runs.list.return_value.dag_runs = []
else:
api_client.dag_runs.list.side_effect = _make_server_error(404)
with pytest.raises(SystemExit, match="1"):
task_command.states_for_dag_run(
self.parser.parse_args(
[
"tasks",
"states-for-dag-run",
self.dag_id,
"--logical-date",
self.logical_date.isoformat(),
]
),
api_client=api_client,
)
api_client.task_instances.list.assert_not_called()
assert _normalize_rich_output(capsys.readouterr().out) == (
"Dag run for test_dag with logical date '2025-01-01T00:00:00+00:00' not found"
)
def test_states_for_dag_run_dag_run_not_found(self, capsys):
api_client = mock.MagicMock()
api_client.task_instances.list.side_effect = _make_server_error(404)
with pytest.raises(SystemExit, match="1"):
task_command.states_for_dag_run(
self.parser.parse_args(["tasks", "states-for-dag-run", self.dag_id, self.run_id]),
api_client=api_client,
)
assert _normalize_rich_output(capsys.readouterr().out) == (
"Dag run 'test_run' of Dag 'test_dag' not found"
)
@pytest.mark.parametrize(
"failing_call",
["dag_runs_list", "task_instances_list"],
)
def test_states_for_dag_run_propagates_non_404_api_error(self, failing_call):
api_client = mock.MagicMock()
error = _make_server_error(500)
if failing_call == "dag_runs_list":
api_client.dag_runs.list.side_effect = error
argv = ["tasks", "states-for-dag-run", self.dag_id, "--logical-date", "2025-01-01T00:00:00+00:00"]
else:
api_client.task_instances.list.side_effect = error
argv = ["tasks", "states-for-dag-run", self.dag_id, self.run_id]
with pytest.raises(ServerResponseError) as ctx:
task_command.states_for_dag_run(self.parser.parse_args(argv), api_client=api_client)
assert ctx.value is error