-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtest_http.py
1576 lines (1287 loc) · 56.4 KB
/
test_http.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
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import json
import logging
from http import HTTPStatus
from typing import Any, Callable, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Union
from unittest.mock import ANY, MagicMock, patch
import pytest
import requests
from requests.exceptions import InvalidURL
from airbyte_cdk.models import AirbyteLogMessage, AirbyteMessage, Level, SyncMode, Type
from airbyte_cdk.sources.streams import CheckpointMixin
from airbyte_cdk.sources.streams.checkpoint import ResumableFullRefreshCursor
from airbyte_cdk.sources.streams.checkpoint.substream_resumable_full_refresh_cursor import (
SubstreamResumableFullRefreshCursor,
)
from airbyte_cdk.sources.streams.core import StreamData
from airbyte_cdk.sources.streams.http import HttpStream, HttpSubStream
from airbyte_cdk.sources.streams.http.error_handlers import ErrorHandler, HttpStatusErrorHandler
from airbyte_cdk.sources.streams.http.error_handlers.response_models import (
FailureType,
ResponseAction,
)
from airbyte_cdk.sources.streams.http.exceptions import (
DefaultBackoffException,
RequestBodyException,
UserDefinedBackoffException,
)
from airbyte_cdk.sources.streams.http.http_client import MessageRepresentationAirbyteTracedErrors
from airbyte_cdk.sources.streams.http.requests_native_auth import TokenAuthenticator
from airbyte_cdk.utils.airbyte_secrets_utils import update_secrets
class StubBasicReadHttpStream(HttpStream):
url_base = "https://test_base_url.com"
primary_key = ""
def __init__(self, deduplicate_query_params: bool = False, **kwargs):
super().__init__(**kwargs)
self.resp_counter = 1
self._deduplicate_query_params = deduplicate_query_params
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
return None
def path(self, **kwargs) -> str:
return ""
def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:
stubResp = {"data": self.resp_counter}
self.resp_counter += 1
yield stubResp
def must_deduplicate_query_params(self) -> bool:
return self._deduplicate_query_params
@property
def cursor_field(self) -> Union[str, List[str]]:
return ["updated_at"]
def test_default_authenticator():
stream = StubBasicReadHttpStream()
assert stream._http_client._session.auth is None
def test_requests_native_token_authenticator():
stream = StubBasicReadHttpStream(authenticator=TokenAuthenticator("test-token"))
assert isinstance(stream._http_client._session.auth, TokenAuthenticator)
def test_request_kwargs_used(mocker, requests_mock):
stream = StubBasicReadHttpStream()
request_kwargs = {"cert": None, "proxies": "google.com"}
mocker.patch.object(stream, "request_kwargs", return_value=request_kwargs)
send_mock = mocker.patch.object(
stream._http_client._session, "send", wraps=stream._http_client._session.send
)
requests_mock.register_uri("GET", stream.url_base)
list(stream.read_records(sync_mode=SyncMode.full_refresh))
stream._http_client._session.send.assert_any_call(ANY, **request_kwargs)
assert send_mock.call_count == 1
def test_stub_basic_read_http_stream_read_records(mocker):
stream = StubBasicReadHttpStream()
blank_response = {} # Send a blank response is fine as we ignore the response in `parse_response anyway.
mocker.patch.object(stream._http_client, "send_request", return_value=(None, blank_response))
records = list(stream.read_records(SyncMode.full_refresh))
assert [{"data": 1}] == records
class StubNextPageTokenHttpStream(StubBasicReadHttpStream):
current_page = 0
def __init__(self, pages: int = 5):
super().__init__()
self._pages = pages
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
while self.current_page < self._pages:
page_token = {"page": self.current_page}
self.current_page += 1
return page_token
return None
def test_next_page_token_is_input_to_other_methods(mocker):
"""Validates that the return value from next_page_token is passed into other methods that need it like request_params, headers, body, etc.."""
pages = 5
stream = StubNextPageTokenHttpStream(pages=pages)
blank_response = {} # Send a blank response is fine as we ignore the response in `parse_response anyway.
mocker.patch.object(stream._http_client, "send_request", return_value=(None, blank_response))
methods = ["request_params", "request_headers", "request_body_json"]
for method in methods:
# Wrap all methods we're interested in testing with mocked objects so we can later spy on their input args and verify they were what we expect
mocker.patch.object(stream, method, wraps=getattr(stream, method))
records = list(stream.read_records(SyncMode.full_refresh))
# Since we have 5 pages, we expect 5 tokens which are {"page":1}, {"page":2}, etc...
expected_next_page_tokens = [{"page": i} for i in range(pages)]
for method in methods:
# First assert that they were called with no next_page_token. This is the first call in the pagination loop.
getattr(stream, method).assert_any_call(
next_page_token=None, stream_slice=None, stream_state={}
)
for token in expected_next_page_tokens:
# Then verify that each method
getattr(stream, method).assert_any_call(
next_page_token=token, stream_slice=None, stream_state={}
)
expected = [{"data": 1}, {"data": 2}, {"data": 3}, {"data": 4}, {"data": 5}, {"data": 6}]
assert records == expected
class StubBadUrlHttpStream(StubBasicReadHttpStream):
url_base = "bad_url"
def test_stub_bad_url_http_stream_read_records(mocker):
stream = StubBadUrlHttpStream()
with pytest.raises(requests.exceptions.RequestException):
list(stream.read_records(SyncMode.full_refresh))
class StubCustomBackoffHttpStream(StubBasicReadHttpStream):
def backoff_time(self, response: requests.Response) -> Optional[float]:
return 0.5
def test_stub_custom_backoff_http_stream(mocker):
mocker.patch("time.sleep", lambda x: None)
stream = StubCustomBackoffHttpStream()
req = requests.Response()
req.status_code = 429
send_mock = mocker.patch.object(requests.Session, "send", return_value=req)
with pytest.raises(UserDefinedBackoffException):
list(stream.read_records(SyncMode.full_refresh))
assert send_mock.call_count == stream.max_retries + 1
# TODO(davin): Figure out how to assert calls.
@pytest.mark.parametrize("retries", [-20, -1, 0, 1, 2, 10])
def test_stub_custom_backoff_http_stream_retries(mocker, retries):
mocker.patch("time.sleep", lambda x: None)
class StubCustomBackoffHttpStreamRetries(StubCustomBackoffHttpStream):
@property
def max_retries(self):
return retries
def get_error_handler(self) -> Optional[ErrorHandler]:
return HttpStatusErrorHandler(logging.Logger, max_retries=retries)
stream = StubCustomBackoffHttpStreamRetries()
req = requests.Response()
req.status_code = HTTPStatus.TOO_MANY_REQUESTS
send_mock = mocker.patch.object(requests.Session, "send", return_value=req)
with pytest.raises(UserDefinedBackoffException, match="Too many requests") as excinfo:
list(stream.read_records(SyncMode.full_refresh))
assert isinstance(excinfo.value.request, requests.PreparedRequest)
assert isinstance(excinfo.value.response, requests.Response)
if retries <= 0:
assert send_mock.call_count == 1
else:
assert send_mock.call_count == stream.max_retries + 1
def test_stub_custom_backoff_http_stream_endless_retries(mocker):
mocker.patch("time.sleep", lambda x: None)
class StubCustomBackoffHttpStreamRetries(StubCustomBackoffHttpStream):
def get_error_handler(self) -> Optional[ErrorHandler]:
return HttpStatusErrorHandler(logging.Logger, max_retries=99999)
infinite_number = 20
stream = StubCustomBackoffHttpStreamRetries()
req = requests.Response()
req.status_code = HTTPStatus.TOO_MANY_REQUESTS
send_mock = mocker.patch.object(requests.Session, "send", side_effect=[req] * infinite_number)
# Expecting mock object to raise a RuntimeError when the end of side_effect list parameter reached.
with pytest.raises(RuntimeError):
list(stream.read_records(SyncMode.full_refresh))
assert send_mock.call_count == infinite_number + 1
@pytest.mark.parametrize("http_code", [400, 401, 403])
def test_4xx_error_codes_http_stream(mocker, http_code):
stream = StubCustomBackoffHttpStream()
req = requests.Response()
req.status_code = http_code
mocker.patch.object(requests.Session, "send", return_value=req)
with pytest.raises(MessageRepresentationAirbyteTracedErrors):
list(stream.read_records(SyncMode.full_refresh))
@pytest.mark.parametrize("http_code", [400, 401, 403])
def test_error_codes_http_stream_error_resolution_with_response_secrets_filtered(mocker, http_code):
stream = StubCustomBackoffHttpStream()
# expected assertion values
expected_header_secret_replaced = "'authorisation_header': '__****__'"
expected_content_str_secret_replaced = "this str contains **** secret"
# mocking the response
res = requests.Response()
res.status_code = http_code
res._content = (
b'{"error": "test error message", "secret_info": "this str contains SECRET_VALUE secret"}'
)
res.headers = {
# simple non-secret header
"regular_header": "some_header_value",
# secret header
"authorisation_header": "__SECRET_X_VALUE__",
}
# updating secrets to be filtered
update_secrets(["SECRET_X_VALUE", "SECRET_VALUE"])
# patch the `send` > response
mocker.patch.object(requests.Session, "send", return_value=res)
# proceed
with pytest.raises(MessageRepresentationAirbyteTracedErrors) as err:
list(stream.read_records(SyncMode.full_refresh))
# we expect the header secrets are obscured
assert expected_header_secret_replaced in str(err._excinfo)
# we expect the response body values (any of them) are obscured
assert expected_content_str_secret_replaced in str(err._excinfo)
class AutoFailFalseHttpStream(StubBasicReadHttpStream):
raise_on_http_errors = False
max_retries = 3
def get_error_handler(self) -> Optional[ErrorHandler]:
return HttpStatusErrorHandler(logging.getLogger(), max_retries=3)
def test_raise_on_http_errors_off_429(mocker):
mocker.patch("time.sleep", lambda x: None)
stream = AutoFailFalseHttpStream()
req = requests.Response()
req.status_code = 429
mocker.patch.object(requests.Session, "send", return_value=req)
with pytest.raises(DefaultBackoffException, match="Too many requests"):
stream.exit_on_rate_limit = True
list(stream.read_records(SyncMode.full_refresh))
@pytest.mark.parametrize("status_code", [500, 501, 503, 504])
def test_raise_on_http_errors_off_5xx(mocker, status_code):
mocker.patch("time.sleep", lambda x: None)
stream = AutoFailFalseHttpStream()
req = requests.Response()
req.status_code = status_code
send_mock = mocker.patch.object(requests.Session, "send", return_value=req)
with pytest.raises(DefaultBackoffException):
list(stream.read_records(SyncMode.full_refresh))
assert send_mock.call_count == stream.max_retries + 1
@pytest.mark.parametrize("status_code", [400, 401, 402, 403, 416])
def test_raise_on_http_errors_off_non_retryable_4xx(mocker, status_code):
stream = AutoFailFalseHttpStream()
req = requests.PreparedRequest()
res = requests.Response()
res.status_code = status_code
mocker.patch.object(requests.Session, "send", return_value=res)
response = stream._http_client._session.send(req)
assert response.status_code == status_code
@pytest.mark.parametrize(
"error",
(
requests.exceptions.ConnectTimeout,
requests.exceptions.ConnectionError,
requests.exceptions.ChunkedEncodingError,
requests.exceptions.ReadTimeout,
),
)
def test_raise_on_http_errors(mocker, error):
mocker.patch("time.sleep", lambda x: None)
stream = AutoFailFalseHttpStream()
send_mock = mocker.patch.object(requests.Session, "send", side_effect=error())
with pytest.raises(DefaultBackoffException):
list(stream.read_records(SyncMode.full_refresh))
assert send_mock.call_count == stream.max_retries + 1
class StubHttpStreamWithErrorHandler(StubBasicReadHttpStream):
def get_error_handler(self) -> Optional[ErrorHandler]:
return HttpStatusErrorHandler(logging.getLogger())
def test_dns_resolution_error_retry():
"""Test that DNS resolution errors are retried"""
stream = StubHttpStreamWithErrorHandler()
error_handler = stream.get_error_handler()
resolution = error_handler.interpret_response(InvalidURL())
assert resolution.response_action == ResponseAction.RETRY
assert resolution.failure_type == FailureType.transient_error
class PostHttpStream(StubBasicReadHttpStream):
http_method = "POST"
def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:
"""Returns response data as is"""
yield response.json()
class TestRequestBody:
"""Suite of different tests for request bodies"""
json_body = {"key": "value"}
data_body = "key:value"
form_body = {"key1": "value1", "key2": 1234}
urlencoded_form_body = "key1=value1&key2=1234"
def request2response(self, request, context):
return json.dumps(
{"body": request.text, "content_type": request.headers.get("Content-Type")}
)
def test_json_body(self, mocker, requests_mock):
stream = PostHttpStream()
mocker.patch.object(stream, "request_body_json", return_value=self.json_body)
requests_mock.register_uri("POST", stream.url_base, text=self.request2response)
response = list(stream.read_records(sync_mode=SyncMode.full_refresh))[0]
assert response["content_type"] == "application/json"
assert json.loads(response["body"]) == self.json_body
def test_text_body(self, mocker, requests_mock):
stream = PostHttpStream()
mocker.patch.object(stream, "request_body_data", return_value=self.data_body)
requests_mock.register_uri("POST", stream.url_base, text=self.request2response)
response = list(stream.read_records(sync_mode=SyncMode.full_refresh))[0]
assert response["content_type"] is None
assert response["body"] == self.data_body
def test_form_body(self, mocker, requests_mock):
stream = PostHttpStream()
mocker.patch.object(stream, "request_body_data", return_value=self.form_body)
requests_mock.register_uri("POST", stream.url_base, text=self.request2response)
response = list(stream.read_records(sync_mode=SyncMode.full_refresh))[0]
assert response["content_type"] == "application/x-www-form-urlencoded"
assert response["body"] == self.urlencoded_form_body
def test_text_json_body(self, mocker, requests_mock):
"""checks a exception if both functions were overridden"""
stream = PostHttpStream()
mocker.patch.object(stream, "request_body_data", return_value=self.data_body)
mocker.patch.object(stream, "request_body_json", return_value=self.json_body)
requests_mock.register_uri("POST", stream.url_base, text=self.request2response)
with pytest.raises(RequestBodyException):
list(stream.read_records(sync_mode=SyncMode.full_refresh))
def test_body_for_all_methods(self, mocker, requests_mock):
"""Stream must send a body for GET/POST/PATCH/PUT methods only"""
stream = PostHttpStream()
methods = {
"POST": True,
"PUT": True,
"PATCH": True,
"GET": True,
"DELETE": False,
"OPTIONS": False,
}
for method, with_body in methods.items():
stream.http_method = method
mocker.patch.object(stream, "request_body_data", return_value=self.data_body)
requests_mock.register_uri(method, stream.url_base, text=self.request2response)
response = list(stream.read_records(sync_mode=SyncMode.full_refresh))[0]
if with_body:
assert response["body"] == self.data_body
else:
assert response["body"] is None
class CacheHttpStream(StubBasicReadHttpStream):
use_cache = True
def get_json_schema(self) -> Mapping[str, Any]:
return {}
class CacheHttpSubStream(HttpSubStream):
url_base = "https://example.com"
primary_key = ""
def __init__(self, parent):
super().__init__(parent=parent)
def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:
return []
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
return None
def path(self, **kwargs) -> str:
return ""
def test_caching_filename():
stream = CacheHttpStream()
assert stream.cache_filename == f"{stream.name}.sqlite"
def test_caching_sessions_are_different():
stream_1 = CacheHttpStream()
stream_2 = CacheHttpStream()
assert stream_1._http_client._session != stream_2._http_client._session
assert stream_1.cache_filename == stream_2.cache_filename
# def test_cached_streams_wortk_when_request_path_is_not_set(mocker, requests_mock):
# This test verifies that HttpStreams with a cached session work even if the path is not set
# For instance, when running in a unit test
# stream = CacheHttpStream()
# with mocker.patch.object(stream._session, "send", wraps=stream._session.send):
# requests_mock.register_uri("GET", stream.url_base)
# records = list(stream.read_records(sync_mode=SyncMode.full_refresh))
# assert records == [{"data": 1}]
# ""
def test_parent_attribute_exist():
parent_stream = CacheHttpStream()
child_stream = CacheHttpSubStream(parent=parent_stream)
assert child_stream.parent == parent_stream
def test_that_response_was_cached(mocker, requests_mock):
requests_mock.register_uri("GET", "https://google.com/", text="text")
stream = CacheHttpStream()
stream._http_client.clear_cache()
mocker.patch.object(stream, "url_base", "https://google.com/")
records = list(stream.read_records(sync_mode=SyncMode.full_refresh))
assert requests_mock.called
requests_mock.reset_mock()
new_records = list(stream.read_records(sync_mode=SyncMode.full_refresh))
assert len(records) == len(new_records)
assert not requests_mock.called
class CacheHttpStreamWithSlices(CacheHttpStream):
paths = ["", "search"]
def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:
return f'{stream_slice["path"]}' if stream_slice else ""
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, Any]]]:
for path in self.paths:
yield {"path": path}
def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:
yield {"value": len(response.text)}
@patch("airbyte_cdk.sources.streams.core.logging", MagicMock())
def test_using_cache(mocker, requests_mock):
requests_mock.register_uri("GET", "https://google.com/", text="text")
requests_mock.register_uri("GET", "https://google.com/search", text="text")
parent_stream = CacheHttpStreamWithSlices()
mocker.patch.object(parent_stream, "url_base", "https://google.com/")
parent_stream._http_client._session.cache.clear()
assert requests_mock.call_count == 0
assert len(parent_stream._http_client._session.cache.responses) == 0
for _slice in parent_stream.stream_slices():
list(parent_stream.read_records(sync_mode=SyncMode.full_refresh, stream_slice=_slice))
assert requests_mock.call_count == 2
assert len(parent_stream._http_client._session.cache.responses) == 2
child_stream = CacheHttpSubStream(parent=parent_stream)
for _slice in child_stream.stream_slices(sync_mode=SyncMode.full_refresh):
pass
assert requests_mock.call_count == 2
assert len(parent_stream._http_client._session.cache.responses) == 2
assert parent_stream._http_client._session.cache.contains(url="https://google.com/")
assert parent_stream._http_client._session.cache.contains(url="https://google.com/search")
class AutoFailTrueHttpStream(StubBasicReadHttpStream):
raise_on_http_errors = True
def should_retry(self, *args, **kwargs):
return True
@pytest.mark.parametrize(
"response_status_code,should_retry, raise_on_http_errors, expected_response_action",
[
(300, True, True, ResponseAction.RETRY),
(200, False, True, ResponseAction.SUCCESS),
(503, False, True, ResponseAction.FAIL),
(503, False, False, ResponseAction.IGNORE),
],
)
def test_http_stream_adapter_http_status_error_handler_should_retry_false_raise_on_http_errors(
mocker,
response_status_code: int,
should_retry: bool,
raise_on_http_errors: bool,
expected_response_action: ResponseAction,
):
stream = AutoFailTrueHttpStream()
mocker.patch.object(stream, "should_retry", return_value=should_retry)
mocker.patch.object(stream, "raise_on_http_errors", raise_on_http_errors)
res = requests.Response()
res.status_code = response_status_code
error_handler = stream.get_error_handler()
error_resolution = error_handler.interpret_response(res)
assert error_resolution.response_action == expected_response_action
@pytest.mark.parametrize("status_code", range(400, 600))
def test_send_raise_on_http_errors_logs(mocker, status_code):
mocker.patch("time.sleep", lambda x: None)
stream = AutoFailTrueHttpStream()
res = requests.Response()
res.status_code = status_code
mocker.patch.object(requests.Session, "send", return_value=res)
mocker.patch.object(stream._http_client, "_logger")
with pytest.raises(requests.exceptions.HTTPError):
response = stream._http_client.send_request("GET", "https://g", {}, exit_on_rate_limit=True)
stream._http_client.logger.error.assert_called_with(response.text)
assert response.status_code == status_code
@pytest.mark.parametrize(
"api_response, expected_message",
[
({"error": "something broke"}, "something broke"),
({"error": {"message": "something broke"}}, "something broke"),
({"error": "err-001", "message": "something broke"}, "something broke"),
({"failure": {"message": "something broke"}}, "something broke"),
(
{"error": {"errors": [{"message": "one"}, {"message": "two"}, {"message": "three"}]}},
"one, two, three",
),
({"errors": ["one", "two", "three"]}, "one, two, three"),
({"messages": ["one", "two", "three"]}, "one, two, three"),
(
{"errors": [{"message": "one"}, {"message": "two"}, {"message": "three"}]},
"one, two, three",
),
(
{"error": [{"message": "one"}, {"message": "two"}, {"message": "three"}]},
"one, two, three",
),
({"errors": [{"error": "one"}, {"error": "two"}, {"error": "three"}]}, "one, two, three"),
(
{"failures": [{"message": "one"}, {"message": "two"}, {"message": "three"}]},
"one, two, three",
),
(["one", "two", "three"], "one, two, three"),
([{"error": "one"}, {"error": "two"}, {"error": "three"}], "one, two, three"),
({"error": True}, None),
({"something_else": "hi"}, None),
({}, None),
],
)
def test_default_parse_response_error_message(api_response: dict, expected_message: Optional[str]):
stream = StubBasicReadHttpStream()
response = MagicMock()
response.json.return_value = api_response
message = stream.parse_response_error_message(response)
assert message == expected_message
def test_default_parse_response_error_message_not_json(requests_mock):
stream = StubBasicReadHttpStream()
requests_mock.register_uri("GET", "mock://test.com/not_json", text="this is not json")
response = requests.get("mock://test.com/not_json")
message = stream.parse_response_error_message(response)
assert message is None
def test_default_get_error_display_message_handles_http_error(mocker):
stream = StubBasicReadHttpStream()
mocker.patch.object(stream, "parse_response_error_message", return_value="my custom message")
non_http_err_msg = stream.get_error_display_message(RuntimeError("not me"))
assert non_http_err_msg is None
response = requests.Response()
http_exception = requests.HTTPError(response=response)
http_err_msg = stream.get_error_display_message(http_exception)
assert http_err_msg == "my custom message"
@pytest.mark.parametrize(
"test_name, base_url, path, expected_full_url",
[
("test_no_slashes", "https://airbyte.io", "my_endpoint", "https://airbyte.io/my_endpoint"),
(
"test_trailing_slash_on_base_url",
"https://airbyte.io/",
"my_endpoint",
"https://airbyte.io/my_endpoint",
),
(
"test_trailing_slash_on_base_url_and_leading_slash_on_path",
"https://airbyte.io/",
"/my_endpoint",
"https://airbyte.io/my_endpoint",
),
(
"test_leading_slash_on_path",
"https://airbyte.io",
"/my_endpoint",
"https://airbyte.io/my_endpoint",
),
(
"test_trailing_slash_on_path",
"https://airbyte.io",
"/my_endpoint/",
"https://airbyte.io/my_endpoint/",
),
(
"test_nested_path_no_leading_slash",
"https://airbyte.io",
"v1/my_endpoint",
"https://airbyte.io/v1/my_endpoint",
),
(
"test_nested_path_with_leading_slash",
"https://airbyte.io",
"/v1/my_endpoint",
"https://airbyte.io/v1/my_endpoint",
),
],
)
def test_join_url(test_name, base_url, path, expected_full_url):
actual_url = HttpStream._join_url(base_url, path)
assert actual_url == expected_full_url
@pytest.mark.parametrize(
"deduplicate_query_params, path, params, expected_url",
[
pytest.param(
True,
"v1/endpoint?param1=value1",
{},
"https://test_base_url.com/v1/endpoint?param1=value1",
id="test_params_only_in_path",
),
pytest.param(
True,
"v1/endpoint",
{"param1": "value1"},
"https://test_base_url.com/v1/endpoint?param1=value1",
id="test_params_only_in_path",
),
pytest.param(
True,
"v1/endpoint",
None,
"https://test_base_url.com/v1/endpoint",
id="test_params_is_none_and_no_params_in_path",
),
pytest.param(
True,
"v1/endpoint?param1=value1",
None,
"https://test_base_url.com/v1/endpoint?param1=value1",
id="test_params_is_none_and_no_params_in_path",
),
pytest.param(
True,
"v1/endpoint?param1=value1",
{"param2": "value2"},
"https://test_base_url.com/v1/endpoint?param1=value1¶m2=value2",
id="test_no_duplicate_params",
),
pytest.param(
True,
"v1/endpoint?param1=value1",
{"param1": "value1"},
"https://test_base_url.com/v1/endpoint?param1=value1",
id="test_duplicate_params_same_value",
),
pytest.param(
True,
"v1/endpoint?param1=1",
{"param1": 1},
"https://test_base_url.com/v1/endpoint?param1=1",
id="test_duplicate_params_same_value_not_string",
),
pytest.param(
True,
"v1/endpoint?param1=value1",
{"param1": "value2"},
"https://test_base_url.com/v1/endpoint?param1=value1¶m1=value2",
id="test_duplicate_params_different_value",
),
pytest.param(
False,
"v1/endpoint?param1=value1",
{"param1": "value2"},
"https://test_base_url.com/v1/endpoint?param1=value1¶m1=value2",
id="test_same_params_different_value_no_deduplication",
),
pytest.param(
False,
"v1/endpoint?param1=value1",
{"param1": "value1"},
"https://test_base_url.com/v1/endpoint?param1=value1¶m1=value1",
id="test_same_params_same_value_no_deduplication",
),
],
)
def test_duplicate_request_params_are_deduped(deduplicate_query_params, path, params, expected_url):
stream = StubBasicReadHttpStream(deduplicate_query_params)
if expected_url is None:
with pytest.raises(ValueError):
stream._http_client._create_prepared_request(
http_method=stream.http_method,
url=stream._join_url(stream.url_base, path),
params=params,
dedupe_query_params=deduplicate_query_params,
)
else:
prepared_request = stream._http_client._create_prepared_request(
http_method=stream.http_method,
url=stream._join_url(stream.url_base, path),
params=params,
dedupe_query_params=deduplicate_query_params,
)
assert prepared_request.url == expected_url
def test_connection_pool():
stream = StubBasicReadHttpStream(authenticator=TokenAuthenticator("test-token"))
assert stream._http_client._session.adapters["https://"]._pool_connections == 20
class StubParentHttpStream(HttpStream, CheckpointMixin):
primary_key = "primary_key"
counter = 0
def __init__(self, records: List[Mapping[str, Any]]):
super().__init__()
self._records = records
self._state: MutableMapping[str, Any] = {}
@property
def url_base(self) -> str:
return "https://airbyte.io/api/v1"
def path(
self,
*,
stream_state: Optional[Mapping[str, Any]] = None,
stream_slice: Optional[Mapping[str, Any]] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> str:
return "/stub"
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
return {"__ab_full_refresh_sync_complete": True}
def _read_single_page(
self,
records_generator_fn: Callable[
[
requests.PreparedRequest,
requests.Response,
Mapping[str, Any],
Optional[Mapping[str, Any]],
],
Iterable[StreamData],
],
stream_slice: Optional[Mapping[str, Any]] = None,
stream_state: Optional[Mapping[str, Any]] = None,
) -> Iterable[StreamData]:
yield from self._records
self.state = {"__ab_full_refresh_sync_complete": True}
def parse_response(
self,
response: requests.Response,
*,
stream_state: Mapping[str, Any],
stream_slice: Optional[Mapping[str, Any]] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> Iterable[Mapping[str, Any]]:
return []
def get_json_schema(self) -> Mapping[str, Any]:
return {}
class StubParentResumableFullRefreshStream(HttpStream, CheckpointMixin):
primary_key = "primary_key"
counter = 0
def __init__(self, record_pages: List[List[Mapping[str, Any]]]):
super().__init__()
self._record_pages = record_pages
self._state: MutableMapping[str, Any] = {}
@property
def url_base(self) -> str:
return "https://airbyte.io/api/v1"
def path(
self,
*,
stream_state: Optional[Mapping[str, Any]] = None,
stream_slice: Optional[Mapping[str, Any]] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> str:
return "/stub"
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
return {"__ab_full_refresh_sync_complete": True}
def read_records(
self,
sync_mode: SyncMode,
cursor_field: Optional[List[str]] = None,
stream_slice: Optional[Mapping[str, Any]] = None,
stream_state: Optional[Mapping[str, Any]] = None,
) -> Iterable[StreamData]:
page_number = self.state.get("page") or 1
yield from self._record_pages[page_number - 1]
if page_number < len(self._record_pages):
self.state = {"page": page_number + 1}
else:
self.state = {"__ab_full_refresh_sync_complete": True}
def parse_response(
self,
response: requests.Response,
*,
stream_state: Mapping[str, Any],
stream_slice: Optional[Mapping[str, Any]] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> Iterable[Mapping[str, Any]]:
return []
def get_json_schema(self) -> Mapping[str, Any]:
return {}
class StubHttpSubstream(HttpSubStream):
primary_key = "primary_key"
@property
def url_base(self) -> str:
return "https://airbyte.io/api/v1"
def path(
self,
*,
stream_state: Optional[Mapping[str, Any]] = None,
stream_slice: Optional[Mapping[str, Any]] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> str:
return "/stub"
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
return None
def _read_pages(
self,
records_generator_fn: Callable[
[
requests.PreparedRequest,
requests.Response,
Mapping[str, Any],
Optional[Mapping[str, Any]],
],
Iterable[StreamData],
],
stream_slice: Optional[Mapping[str, Any]] = None,
stream_state: Optional[Mapping[str, Any]] = None,
) -> Iterable[StreamData]:
return [
{"id": "abc", "parent": stream_slice.get("id")},
{"id", "def", "parent", stream_slice.get("id")},
]
def parse_response(
self,
response: requests.Response,
*,
stream_state: Mapping[str, Any],
stream_slice: Optional[Mapping[str, Any]] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> Iterable[Mapping[str, Any]]:
return []
def test_substream_with_incremental_parent():
expected_slices = [
{"parent": {"id": "abc"}},
{"parent": {"id": "def"}},
]
parent_records = [
{"id": "abc"},
{"id": "def"},
]
parent_stream = StubParentHttpStream(records=parent_records)
substream = StubHttpSubstream(parent=parent_stream)
actual_slices = [slice for slice in substream.stream_slices(sync_mode=SyncMode.full_refresh)]
assert actual_slices == expected_slices
def test_substream_with_resumable_full_refresh_parent():
parent_pages = [
[
{"id": "page_1_abc"},
{"id": "page_1_def"},
],
[
{"id": "page_2_abc"},
{"id": "page_2_def"},
],
[
{"id": "page_3_abc"},
{"id": "page_3_def"},
],