-
Notifications
You must be signed in to change notification settings - Fork 17.1k
Expand file tree
/
Copy pathtest_client.py
More file actions
1402 lines (1198 loc) · 58.1 KB
/
test_client.py
File metadata and controls
1402 lines (1198 loc) · 58.1 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
# 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 json
import pickle
from datetime import datetime
from typing import TYPE_CHECKING
from unittest import mock
import certifi
import httpx
import pytest
import uuid6
from task_sdk import make_client, make_client_w_dry_run, make_client_w_responses
from uuid6 import uuid7
from airflow.sdk import timezone
from airflow.sdk.api.client import Client, RemoteValidationError, ServerResponseError
from airflow.sdk.api.datamodels._generated import (
AssetEventsResponse,
AssetResponse,
ConnectionResponse,
DagRunState,
DagRunStateResponse,
HITLDetailRequest,
HITLDetailResponse,
HITLUser,
VariableResponse,
XComResponse,
)
from airflow.sdk.exceptions import ErrorType
from airflow.sdk.execution_time.comms import (
DeferTask,
ErrorResponse,
OKResponse,
PreviousDagRunResult,
RescheduleTask,
TaskRescheduleStartDate,
)
from airflow.utils.state import TerminalTIState
if TYPE_CHECKING:
from time_machine import TimeMachineFixture
class TestClient:
@pytest.mark.parametrize(
["path", "json_response"],
[
(
"/task-instances/1/run",
{
"dag_run": {
"dag_id": "test_dag",
"run_id": "test_run",
"logical_date": "2021-01-01T00:00:00Z",
"start_date": "2021-01-01T00:00:00Z",
"run_type": "manual",
"run_after": "2021-01-01T00:00:00Z",
"consumed_asset_events": [],
},
"max_tries": 0,
"should_retry": False,
},
),
],
)
def test_dry_run(self, path, json_response):
client = make_client_w_dry_run()
assert client.base_url == "dry-run://server"
resp = client.get(path)
assert resp.status_code == 200
assert resp.json() == json_response
@mock.patch("airflow.sdk.api.client.API_SSL_CERT_PATH", "/capath/does/not/exist/")
def test_add_capath(self):
def handle_request(request: httpx.Request) -> httpx.Response:
return httpx.Response(status_code=200)
with pytest.raises(FileNotFoundError) as err:
make_client(httpx.MockTransport(handle_request))
assert isinstance(err.value, FileNotFoundError)
@mock.patch("airflow.sdk.api.client.API_TIMEOUT", 60.0)
def test_timeout_configuration(self):
def handle_request(request: httpx.Request) -> httpx.Response:
return httpx.Response(status_code=200)
client = make_client(httpx.MockTransport(handle_request))
assert client.timeout == httpx.Timeout(60.0)
def test_timeout_can_be_overridden(self):
def handle_request(request: httpx.Request) -> httpx.Response:
return httpx.Response(status_code=200)
client = Client(
base_url="test://server", token="", transport=httpx.MockTransport(handle_request), timeout=120.0
)
assert client.timeout == httpx.Timeout(120.0)
def test_error_parsing(self):
responses = [
httpx.Response(422, json={"detail": [{"loc": ["#0"], "msg": "err", "type": "required"}]})
]
client = make_client_w_responses(responses)
with pytest.raises(ServerResponseError) as err:
client.get("http://error")
assert isinstance(err.value, ServerResponseError)
assert isinstance(err.value.detail, list)
assert err.value.detail == [
RemoteValidationError(loc=["#0"], msg="err", type="required"),
]
def test_error_parsing_plain_text(self):
responses = [httpx.Response(422, content=b"Internal Server Error")]
client = make_client_w_responses(responses)
with pytest.raises(httpx.HTTPStatusError) as err:
client.get("http://error")
assert not isinstance(err.value, ServerResponseError)
def test_error_parsing_other_json(self):
responses = [httpx.Response(404, json={"detail": "Not found"})]
client = make_client_w_responses(responses)
with pytest.raises(ServerResponseError) as err:
client.get("http://error")
assert err.value.args == ("Not found",)
assert err.value.detail is None
def test_server_response_error_pickling(self):
responses = [httpx.Response(404, json={"detail": {"message": "Invalid input"}})]
client = make_client_w_responses(responses)
with pytest.raises(ServerResponseError) as exc_info:
client.get("http://error")
err = exc_info.value
assert err.args == ("Server returned error",)
assert err.detail == {"detail": {"message": "Invalid input"}}
# Check that the error is picklable
pickled = pickle.dumps(err)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, ServerResponseError)
# Test that unpickled error has the same attributes as the original
assert unpickled.response.json() == {"detail": {"message": "Invalid input"}}
assert unpickled.detail == {"detail": {"message": "Invalid input"}}
assert unpickled.response.status_code == 404
assert unpickled.request.url == "http://error"
@mock.patch("time.sleep", return_value=None)
def test_retry_handling_unrecoverable_error(self, mock_sleep):
responses: list[httpx.Response] = [
*[httpx.Response(500, text="Internal Server Error")] * 6,
httpx.Response(200, json={"detail": "Recovered from error - but will fail before"}),
httpx.Response(400, json={"detail": "Should not get here"}),
]
client = make_client_w_responses(responses)
with pytest.raises(httpx.HTTPStatusError) as err:
client.get("http://error")
assert not isinstance(err.value, ServerResponseError)
assert len(responses) == 3
assert mock_sleep.call_count == 4
@mock.patch("time.sleep", return_value=None)
def test_retry_handling_recovered(self, mock_sleep):
responses: list[httpx.Response] = [
*[httpx.Response(500, text="Internal Server Error")] * 2,
httpx.Response(200, json={"detail": "Recovered from error"}),
httpx.Response(400, json={"detail": "Should not get here"}),
]
client = make_client_w_responses(responses)
response = client.get("http://error")
assert response.status_code == 200
assert len(responses) == 1
assert mock_sleep.call_count == 2
@mock.patch("time.sleep", return_value=None)
def test_retry_handling_overload(self, mock_sleep):
responses: list[httpx.Response] = [
httpx.Response(429, text="I am really busy atm, please back-off", headers={"Retry-After": "37"}),
httpx.Response(200, json={"detail": "Recovered from error"}),
httpx.Response(400, json={"detail": "Should not get here"}),
]
client = make_client_w_responses(responses)
response = client.get("http://error")
assert response.status_code == 200
assert len(responses) == 1
assert mock_sleep.call_count == 1
assert mock_sleep.call_args[0][0] == 37
@mock.patch("time.sleep", return_value=None)
def test_retry_handling_non_retry_error(self, mock_sleep):
responses: list[httpx.Response] = [
httpx.Response(422, json={"detail": "Somehow this is a bad request"}),
httpx.Response(400, json={"detail": "Should not get here"}),
]
client = make_client_w_responses(responses)
with pytest.raises(ServerResponseError) as err:
client.get("http://error")
assert len(responses) == 1
assert mock_sleep.call_count == 0
assert err.value.args == ("Somehow this is a bad request",)
@mock.patch("time.sleep", return_value=None)
def test_retry_handling_ok(self, mock_sleep):
responses: list[httpx.Response] = [
httpx.Response(200, json={"detail": "Recovered from error"}),
httpx.Response(400, json={"detail": "Should not get here"}),
]
client = make_client_w_responses(responses)
response = client.get("http://error")
assert response.status_code == 200
assert len(responses) == 1
assert mock_sleep.call_count == 0
def test_token_renewal(self):
responses: list[httpx.Response] = [
httpx.Response(200, json={"ok": "1"}),
httpx.Response(404, json={"var": "not_found"}, headers={"Refreshed-API-Token": "abc"}),
httpx.Response(200, json={"ok": "3"}),
]
client = make_client_w_responses(responses)
response = client.get("/")
assert response.status_code == 200
assert client.auth is not None
assert not client.auth.token
with pytest.raises(ServerResponseError):
response = client.get("/")
# Even thought it was Not Found, we should still respect the header
assert client.auth is not None
assert client.auth.token == "abc"
# Test that the next request is made with that new auth token
response = client.get("/")
assert response.status_code == 200
assert response.request.headers["Authorization"] == "Bearer abc"
@pytest.mark.parametrize(
["status_code", "description"],
[
(399, "status code < 400"),
(301, "3xx redirect status code"),
(600, "status code >= 600"),
],
)
def test_server_response_error_invalid_status_codes(self, status_code, description):
"""Test that ServerResponseError.from_response returns None for invalid status codes."""
response = httpx.Response(status_code, json={"detail": f"Test {description}"})
assert ServerResponseError.from_response(response) is None
class TestTaskInstanceOperations:
"""
Test that the TestVariableOperations class works as expected. While the operations are simple, it
still catches the basic functionality of the client for task instances including endpoint and
response parsing.
"""
@mock.patch("time.sleep", return_value=None) # To have retries not slowing down tests
def test_task_instance_start(self, mock_sleep, make_ti_context):
# Simulate a successful response from the server that starts a task
ti_id = uuid6.uuid7()
start_date = "2024-10-31T12:00:00Z"
ti_context = make_ti_context(
start_date=start_date,
logical_date="2024-10-31T12:00:00Z",
run_type="manual",
)
# ...including a validation that retry really works
call_count = 0
def handle_request(request: httpx.Request) -> httpx.Response:
nonlocal call_count
call_count += 1
if call_count < 3:
return httpx.Response(status_code=500, json={"detail": "Internal Server Error"})
if request.url.path == f"/task-instances/{ti_id}/run":
actual_body = json.loads(request.read())
assert actual_body["pid"] == 100
assert actual_body["start_date"] == start_date
assert actual_body["state"] == "running"
return httpx.Response(
status_code=200,
json=ti_context.model_dump(mode="json"),
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
resp = client.task_instances.start(ti_id, 100, start_date)
assert resp == ti_context
assert call_count == 3
@pytest.mark.parametrize(
"state", [state for state in TerminalTIState if state != TerminalTIState.SUCCESS]
)
def test_task_instance_finish(self, state):
# Simulate a successful response from the server that finishes (moved to terminal state) a task
ti_id = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/state":
actual_body = json.loads(request.read())
assert actual_body["end_date"] == "2024-10-31T12:00:00Z"
assert actual_body["state"] == state
assert actual_body["rendered_map_index"] == "test"
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
client.task_instances.finish(
ti_id, state=state, when="2024-10-31T12:00:00Z", rendered_map_index="test"
)
def test_task_instance_heartbeat(self):
# Simulate a successful response from the server that sends a heartbeat for a ti
ti_id = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/heartbeat":
actual_body = json.loads(request.read())
assert actual_body["pid"] == 100
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
client.task_instances.heartbeat(ti_id, 100)
def test_task_instance_defer(self):
# Simulate a successful response from the server that defers a task
ti_id = uuid6.uuid7()
msg = DeferTask(
classpath="airflow.providers.standard.triggers.temporal.DateTimeTrigger",
next_method="execute_complete",
trigger_kwargs={
"__type": "dict",
"__var": {
"moment": {"__type": "datetime", "__var": 1730982899.0},
"end_from_trigger": False,
},
},
next_kwargs={"__type": "dict", "__var": {}},
)
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/state":
actual_body = json.loads(request.read())
assert actual_body["state"] == "deferred"
assert actual_body["trigger_kwargs"] == msg.trigger_kwargs
assert (
actual_body["classpath"] == "airflow.providers.standard.triggers.temporal.DateTimeTrigger"
)
assert actual_body["next_method"] == "execute_complete"
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
client.task_instances.defer(ti_id, msg)
def test_task_instance_reschedule(self):
# Simulate a successful response from the server that reschedules a task
ti_id = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/state":
actual_body = json.loads(request.read())
assert actual_body["state"] == "up_for_reschedule"
assert actual_body["reschedule_date"] == "2024-10-31T12:00:00Z"
assert actual_body["end_date"] == "2024-10-31T12:00:00Z"
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
msg = RescheduleTask(
reschedule_date=timezone.parse("2024-10-31T12:00:00Z"),
end_date=timezone.parse("2024-10-31T12:00:00Z"),
)
client.task_instances.reschedule(ti_id, msg)
def test_task_instance_up_for_retry(self):
ti_id = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/state":
actual_body = json.loads(request.read())
assert actual_body["state"] == "up_for_retry"
assert actual_body["end_date"] == "2024-10-31T12:00:00Z"
assert actual_body["rendered_map_index"] == "test"
return httpx.Response(
status_code=204,
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
client.task_instances.retry(
ti_id, end_date=timezone.parse("2024-10-31T12:00:00Z"), rendered_map_index="test"
)
@pytest.mark.parametrize(
"rendered_fields",
[
pytest.param({"field1": "rendered_value1", "field2": "rendered_value2"}, id="simple-rendering"),
pytest.param(
{
"field1": "ClassWithCustomAttributes({'nested1': ClassWithCustomAttributes("
"{'att1': 'test', 'att2': 'test2'), "
"'nested2': ClassWithCustomAttributes("
"{'att3': 'test3', 'att4': 'test4')"
},
id="complex-rendering",
),
],
)
def test_taskinstance_set_rtif_success(self, rendered_fields):
TI_ID = uuid6.uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{TI_ID}/rtif":
return httpx.Response(
status_code=201,
json={"message": "Rendered task instance fields successfully set"},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.set_rtif(id=TI_ID, body=rendered_fields)
assert result == OKResponse(ok=True)
def test_get_count_basic(self):
"""Test basic get_count functionality with just dag_id."""
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/task-instances/count"
assert request.url.params.get("dag_id") == "test_dag"
return httpx.Response(200, json=5)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_count(dag_id="test_dag")
assert result.count == 5
def test_get_count_with_all_params(self):
"""Test get_count with all optional parameters."""
logical_dates_str = ["2024-01-01T00:00:00+00:00", "2024-01-02T00:00:00+00:00"]
logical_dates = [timezone.parse(d) for d in logical_dates_str]
task_ids = ["task1", "task2"]
states = ["success", "failed"]
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/task-instances/count"
assert request.method == "GET"
params = request.url.params
assert params["dag_id"] == "test_dag"
assert params.get_list("task_ids") == task_ids
assert params["task_group_id"] == "group1"
assert params.get_list("logical_dates") == logical_dates_str
assert params.get_list("run_ids") == []
assert params.get_list("states") == states
assert params["map_index"] == "0"
return httpx.Response(200, json=10)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_count(
dag_id="test_dag",
map_index=0,
task_ids=task_ids,
task_group_id="group1",
logical_dates=logical_dates,
states=states,
)
assert result.count == 10
def test_get_task_states_basic(self):
"""Test basic get_task_states functionality with just dag_id."""
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/task-instances/states"
assert request.url.params.get("dag_id") == "test_dag"
assert request.url.params.get("task_group_id") == "group1"
return httpx.Response(
200, json={"task_states": {"run_id": {"group1.task1": "success", "group1.task2": "failed"}}}
)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_task_states(dag_id="test_dag", task_group_id="group1")
assert result.task_states == {"run_id": {"group1.task1": "success", "group1.task2": "failed"}}
def test_get_task_states_with_all_params(self):
"""Test get_task_states with all optional parameters."""
logical_dates_str = ["2024-01-01T00:00:00+00:00", "2024-01-02T00:00:00+00:00"]
logical_dates = [timezone.parse(d) for d in logical_dates_str]
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/task-instances/states"
assert request.method == "GET"
params = request.url.params
assert params["dag_id"] == "test_dag"
assert params["task_group_id"] == "group1"
assert params.get_list("logical_dates") == logical_dates_str
assert params.get_list("task_ids") == []
assert params.get_list("run_ids") == []
assert params.get("map_index") == "0"
return httpx.Response(
200, json={"task_states": {"run_id": {"group1.task1": "success", "group1.task2": "failed"}}}
)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_task_states(
dag_id="test_dag",
map_index=0,
task_group_id="group1",
logical_dates=logical_dates,
)
assert result.task_states == {"run_id": {"group1.task1": "success", "group1.task2": "failed"}}
class TestVariableOperations:
"""
Test that the VariableOperations class works as expected. While the operations are simple, it
still catches the basic functionality of the client for variables including endpoint and
response parsing.
"""
@mock.patch("time.sleep", return_value=None) # To have retries not slowing down tests
def test_variable_get_success(self, mock_sleep):
# Simulate a successful response from the server with a variable
# ...including a validation that retry really works
call_count = 0
def handle_request(request: httpx.Request) -> httpx.Response:
nonlocal call_count
call_count += 1
if call_count < 2:
return httpx.Response(status_code=500, json={"detail": "Internal Server Error"})
if request.url.path == "/variables/test_key":
return httpx.Response(
status_code=200,
json={"key": "test_key", "value": "test_value"},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.variables.get(key="test_key")
assert isinstance(result, VariableResponse)
assert result.key == "test_key"
assert result.value == "test_value"
assert call_count == 2
def test_variable_not_found(self):
# Simulate a 404 response from the server
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/variables/non_existent_var":
return httpx.Response(
status_code=404,
json={
"detail": {
"message": "Variable with key 'non_existent_var' not found",
"reason": "not_found",
}
},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
resp = client.variables.get(key="non_existent_var")
assert isinstance(resp, ErrorResponse)
assert resp.error == ErrorType.VARIABLE_NOT_FOUND
assert resp.detail == {"key": "non_existent_var"}
@mock.patch("time.sleep", return_value=None)
def test_variable_get_500_error(self, mock_sleep):
# Simulate a response from the server returning a 500 error
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/variables/test_key":
return httpx.Response(
status_code=500,
headers=[("content-Type", "application/json")],
json={
"reason": "internal_server_error",
"message": "Internal Server Error",
},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
with pytest.raises(ServerResponseError):
client.variables.get(
key="test_key",
)
def test_variable_set_success(self):
# Simulate a successful response from the server when putting a variable
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/variables/test_key":
return httpx.Response(
status_code=201,
json={"message": "Variable successfully set"},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.variables.set(key="test_key", value="test_value", description="test_description")
assert result == OKResponse(ok=True)
def test_variable_delete_success(self):
# Simulate a successful response from the server when deleting a variable
def handle_request(request: httpx.Request) -> httpx.Response:
if request.method == "DELETE" and request.url.path == "/variables/test_key":
return httpx.Response(
status_code=200,
json={"count": 1},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.variables.delete(key="test_key")
assert result == OKResponse(ok=True)
class TestXCOMOperations:
"""
Test that the XComOperations class works as expected. While the operations are simple, it
still catches the basic functionality of the client for xcoms including endpoint and
response parsing.
"""
@pytest.mark.parametrize(
"value",
[
pytest.param("value1", id="string-value"),
pytest.param({"key1": "value1"}, id="dict-value"),
pytest.param('{"key1": "value1"}', id="dict-str-value"),
pytest.param(["value1", "value2"], id="list-value"),
pytest.param({"key": "test_key", "value": {"key2": "value2"}}, id="nested-dict-value"),
],
)
@mock.patch("time.sleep", return_value=None) # To have retries not slowing down tests
def test_xcom_get_success(self, mock_sleep, value):
# Simulate a successful response from the server when getting an xcom
# ...including a validation that retry really works
call_count = 0
def handle_request(request: httpx.Request) -> httpx.Response:
nonlocal call_count
call_count += 1
if call_count < 3:
return httpx.Response(status_code=500, json={"detail": "Internal Server Error"})
if request.url.path == "/xcoms/dag_id/run_id/task_id/key":
return httpx.Response(
status_code=201,
json={"key": "test_key", "value": value},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.xcoms.get(
dag_id="dag_id",
run_id="run_id",
task_id="task_id",
key="key",
)
assert isinstance(result, XComResponse)
assert result.key == "test_key"
assert result.value == value
assert call_count == 3
def test_xcom_get_success_with_map_index(self):
# Simulate a successful response from the server when getting an xcom with map_index passed
def handle_request(request: httpx.Request) -> httpx.Response:
if (
request.url.path == "/xcoms/dag_id/run_id/task_id/key"
and request.url.params.get("map_index") == "2"
):
return httpx.Response(
status_code=201,
json={"key": "test_key", "value": "test_value"},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.xcoms.get(
dag_id="dag_id",
run_id="run_id",
task_id="task_id",
key="key",
map_index=2,
)
assert isinstance(result, XComResponse)
assert result.key == "test_key"
assert result.value == "test_value"
def test_xcom_get_success_with_include_prior_dates(self):
# Simulate a successful response from the server when getting an xcom with include_prior_dates passed
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/xcoms/dag_id/run_id/task_id/key" and request.url.params.get(
"include_prior_dates"
):
return httpx.Response(
status_code=201,
json={"key": "test_key", "value": "test_value"},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.xcoms.get(
dag_id="dag_id",
run_id="run_id",
task_id="task_id",
key="key",
include_prior_dates=True,
)
assert isinstance(result, XComResponse)
assert result.key == "test_key"
assert result.value == "test_value"
@mock.patch("time.sleep", return_value=None)
def test_xcom_get_500_error(self, mock_sleep):
# Simulate a successful response from the server returning a 500 error
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/xcoms/dag_id/run_id/task_id/key":
return httpx.Response(
status_code=500,
headers=[("content-Type", "application/json")],
json={
"reason": "invalid_format",
"message": "XCom value is not a valid JSON",
},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
with pytest.raises(ServerResponseError):
client.xcoms.get(
dag_id="dag_id",
run_id="run_id",
task_id="task_id",
key="key",
)
@pytest.mark.parametrize(
"values",
[
pytest.param("value1", id="string-value"),
pytest.param({"key1": "value1"}, id="dict-value"),
pytest.param(["value1", "value2"], id="list-value"),
pytest.param({"key": "test_key", "value": {"key2": "value2"}}, id="nested-dict-value"),
],
)
def test_xcom_set_success(self, values):
# Simulate a successful response from the server when setting an xcom
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/xcoms/dag_id/run_id/task_id/key":
assert json.loads(request.read()) == values
return httpx.Response(
status_code=201,
json={"message": "XCom successfully set"},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.xcoms.set(
dag_id="dag_id",
run_id="run_id",
task_id="task_id",
key="key",
value=values,
)
assert result == OKResponse(ok=True)
def test_xcom_set_with_map_index(self):
# Simulate a successful response from the server when setting an xcom with map_index passed
def handle_request(request: httpx.Request) -> httpx.Response:
if (
request.url.path == "/xcoms/dag_id/run_id/task_id/key"
and request.url.params.get("map_index") == "2"
):
assert json.loads(request.read()) == "value1"
return httpx.Response(
status_code=201,
json={"message": "XCom successfully set"},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.xcoms.set(
dag_id="dag_id",
run_id="run_id",
task_id="task_id",
key="key",
value="value1",
map_index=2,
)
assert result == OKResponse(ok=True)
def test_xcom_set_with_mapped_length(self):
# Simulate a successful response from the server when setting an xcom with mapped_length
def handle_request(request: httpx.Request) -> httpx.Response:
if (
request.url.path == "/xcoms/dag_id/run_id/task_id/key"
and request.url.params.get("map_index") == "2"
and request.url.params.get("mapped_length") == "3"
):
assert json.loads(request.read()) == "value1"
return httpx.Response(
status_code=201,
json={"message": "XCom successfully set"},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.xcoms.set(
dag_id="dag_id",
run_id="run_id",
task_id="task_id",
key="key",
value="value1",
map_index=2,
mapped_length=3,
)
assert result == OKResponse(ok=True)
class TestConnectionOperations:
"""
Test that the TestConnectionOperations class works as expected. While the operations are simple, it
still catches the basic functionality of the client for connections including endpoint and
response parsing.
"""
def test_connection_get_success(self):
# Simulate a successful response from the server with a connection
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/connections/test_conn":
return httpx.Response(
status_code=200,
json={
"conn_id": "test_conn",
"conn_type": "mysql",
},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.connections.get(conn_id="test_conn")
assert isinstance(result, ConnectionResponse)
assert result.conn_id == "test_conn"
assert result.conn_type == "mysql"
def test_connection_get_404_not_found(self):
# Simulate a successful response from the server with a connection
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == "/connections/test_conn":
return httpx.Response(
status_code=404,
json={
"reason": "not_found",
"message": "Connection with ID test_conn not found",
},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.connections.get(conn_id="test_conn")
assert isinstance(result, ErrorResponse)
assert result.error == ErrorType.CONNECTION_NOT_FOUND
class TestAssetEventOperations:
@pytest.mark.parametrize(
"request_params",
[
({"name": "this_asset", "uri": "s3://bucket/key"}),
({"alias_name": "this_asset_alias"}),
],
)
def test_by_name_get_success(self, request_params):
def handle_request(request: httpx.Request) -> httpx.Response:
params = request.url.params
if request.url.path == "/asset-events/by-asset":
assert params.get("name") == request_params.get("name")
assert params.get("uri") == request_params.get("uri")
elif request.url.path == "/asset-events/by-asset-alias":
assert params.get("name") == request_params.get("alias_name")
else:
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
return httpx.Response(
status_code=200,
json={
"asset_events": [
{
"id": 1,
"asset": {
"name": "this_asset",
"uri": "s3://bucket/key",
"group": "asset",
},
"created_dagruns": [],
"timestamp": "2023-01-01T00:00:00Z",
}
]
},
)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.asset_events.get(**request_params)
assert isinstance(result, AssetEventsResponse)
assert len(result.asset_events) == 1
assert result.asset_events[0].asset.name == "this_asset"
assert result.asset_events[0].asset.uri == "s3://bucket/key"
class TestAssetOperations:
@pytest.mark.parametrize(
"request_params",
[
({"name": "this_asset"}),
({"uri": "s3://bucket/key"}),
],
)
def test_by_name_get_success(self, request_params):
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path in ("/assets/by-name", "/assets/by-uri"):
return httpx.Response(
status_code=200,
json={
"name": "this_asset",
"uri": "s3://bucket/key",
"group": "asset",
"extra": {"foo": "bar"},
},
)
return httpx.Response(status_code=400, json={"detail": "Bad Request"})
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.assets.get(**request_params)
assert isinstance(result, AssetResponse)
assert result.name == "this_asset"
assert result.uri == "s3://bucket/key"
@pytest.mark.parametrize(
"request_params",
[
({"name": "this_asset"}),
({"uri": "s3://bucket/key"}),
],
)
def test_by_name_get_404_not_found(self, request_params):
def handle_request(request: httpx.Request) -> httpx.Response: