-
Notifications
You must be signed in to change notification settings - Fork 531
Expand file tree
/
Copy pathtest_http_client.py
More file actions
2046 lines (1688 loc) · 63.2 KB
/
Copy pathtest_http_client.py
File metadata and controls
2046 lines (1688 loc) · 63.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import base64
import json
import sys
from typing import Any, Callable, Dict, List, Optional
from unittest.mock import MagicMock, Mock, call, patch
import pytest
from typing_extensions import Type
if sys.version_info >= (3, 8):
from unittest.mock import AsyncMock
else:
from mock import AsyncMock
from contextlib import contextmanager
import urllib3
import stripe
from stripe import APIConnectionError, _http_client
from stripe._encode import _api_encode
from stripe._http_client import (
AIOHTTPClient,
HTTPXClient,
NoImportFoundAsyncClient,
PycurlClient,
RequestsClient,
)
from stripe._http_client import (
UrlFetchClient as AppEngineClient,
)
from stripe._http_client import (
UrllibClient as BuiltinClient,
)
VALID_API_METHODS = ("get", "post", "delete")
@pytest.fixture
def mocked_request_lib():
return MagicMock()
SUPPORTED_LIBS = frozenset(
("google.appengine.api", "requests", "pycurl", "httpx", "aiohttp", "anyio")
)
@pytest.fixture
def mock_import():
"""
A pytest fixture that simulates a specific set of libraries being available. Right now it hardcodes information about our `SUPPORTED_LIBS`, but we could make it more general.
usage:
with patch("builtins.__import__") as mocked_import_fn:
mocked_import_fn.side_effect = mock_import(['a', 'b', 'c'])
# assuming SUPPORTED_LIBS is a,b,c
import a # works (MagicMock if `a` isn't installed for real)
import d # importError
import pytest # is a regular import, only works if pytest is actually installed
"""
orig_import = __import__
def create_mocked_import(available_libs: List[str]):
def _mocked_import(name, *args):
"""
emulate packages being missing by throwing early if they're not supposed to be here.
"""
if name in SUPPORTED_LIBS and name not in available_libs:
raise ImportError()
try:
# if it's not supposed to be missing, try and import it for real
return orig_import(name, *args)
except ImportError:
# we don't have some of our 3rd party options (like the GAE module) available, but the import needs to succeed
return MagicMock()
return _mocked_import
return create_mocked_import
class TestImports:
@pytest.mark.parametrize(
["available_libs", "expected"],
[
[["google.appengine.api"], AppEngineClient],
[["google.appengine.api", "requests"], AppEngineClient],
[["requests"], RequestsClient],
[["requests", "pycurl"], RequestsClient],
[["pycurl"], PycurlClient],
[[], BuiltinClient],
],
)
def test_default_httpclient_from_imports(
self, available_libs, expected, mock_import
):
with patch("builtins.__import__") as mocked_import_fn:
mocked_import_fn.side_effect = mock_import(available_libs)
resolved_class = _http_client._resolve_sync_client()
assert resolved_class is expected
@pytest.mark.parametrize(
["available_libs", "expected"],
[
# needs both httpx and anyio
[["httpx"], NoImportFoundAsyncClient],
[["anyio"], NoImportFoundAsyncClient],
[["httpx", "anyio"], HTTPXClient],
# having only one required lib means we proceed
[["anyio", "aiohttp"], AIOHTTPClient],
[["aiohttp"], AIOHTTPClient],
[[], NoImportFoundAsyncClient],
],
)
def test_default_async_httpclient_from_imports(
self, available_libs, expected, mock_import
):
with patch("builtins.__import__") as mocked_import_fn:
mocked_import_fn.side_effect = mock_import(available_libs)
resolved_class = _http_client._resolve_async_client()
assert resolved_class is expected
MakeReqFunc = Callable[[str, str, Dict[str, str], Optional[str]], Any]
class TestRetrySleepTimeDefaultHttpClient:
def assert_sleep_times(
self, client: _http_client.HTTPClient, expected: List[float]
):
# the sleep duration for a request after N retries
actual = [
client._sleep_time_seconds(i + 1) for i in range(len(expected))
]
assert expected == actual
@contextmanager
def mock_max_delay(self, new_value):
original_value = _http_client.HTTPClient.MAX_DELAY
_http_client.HTTPClient.MAX_DELAY = new_value
try:
yield self
finally:
_http_client.HTTPClient.MAX_DELAY = original_value
def test_sleep_time_exponential_back_off(self):
client = _http_client.new_default_http_client()
client._add_jitter_time = lambda sleep_seconds: sleep_seconds
with self.mock_max_delay(10):
self.assert_sleep_times(client, [])
def test_initial_delay_as_minimum(self):
client = _http_client.new_default_http_client()
client._add_jitter_time = lambda sleep_seconds: sleep_seconds * 0.001
initial_delay = _http_client.HTTPClient.INITIAL_DELAY
self.assert_sleep_times(client, [initial_delay] * 5)
def test_maximum_delay(self):
client = _http_client.new_default_http_client()
client._add_jitter_time = lambda sleep_seconds: sleep_seconds
max_delay = _http_client.HTTPClient.MAX_DELAY
expected = [0.5, 1.0, 2.0, 4.0, max_delay, max_delay, max_delay]
self.assert_sleep_times(client, expected)
def test_retry_after_header(self):
client = _http_client.new_default_http_client()
client._add_jitter_time = lambda sleep_seconds: sleep_seconds
# Prefer retry-after if it's bigger
assert 30 == client._sleep_time_seconds(
2, (None, 409, {"retry-after": "30"})
)
# Prefer default if it's bigger
assert 2 == client._sleep_time_seconds(
3, (None, 409, {"retry-after": "1"})
)
# Ignore crazy-big values
assert 1 == client._sleep_time_seconds(
2, (None, 409, {"retry-after": "300"})
)
def test_randomness_added(self):
client = _http_client.new_default_http_client()
random_value = 0.8
client._add_jitter_time = (
lambda sleep_seconds: sleep_seconds * random_value
)
base_value = _http_client.HTTPClient.INITIAL_DELAY * random_value
with self.mock_max_delay(10):
expected = [
_http_client.HTTPClient.INITIAL_DELAY,
base_value * 2,
base_value * 4,
base_value * 8,
base_value * 16,
]
self.assert_sleep_times(client, expected)
def test_jitter_has_randomness_but_within_range(self):
client = _http_client.new_default_http_client()
jittered_ones = set(
map(lambda _: client._add_jitter_time(1), list(range(100)))
)
assert len(jittered_ones) > 1
assert all(0.5 <= val <= 1 for val in jittered_ones)
class TestRetryConditionsDefaultHttpClient:
def test_should_retry_on_codes(self):
one_xx = list(range(100, 104))
two_xx = list(range(200, 209))
three_xx = list(range(300, 308))
four_xx = list(range(400, 431))
client = _http_client.new_default_http_client()
codes = one_xx + two_xx + three_xx + four_xx
codes.remove(409)
# These status codes should not be retried by default.
for code in codes:
assert (
client._should_retry(
(None, code, None), None, 0, max_network_retries=1
)
is False
)
# These status codes should be retried by default.
assert (
client._should_retry(
(None, 409, None), None, 0, max_network_retries=1
)
is True
)
assert (
client._should_retry(
(None, 500, None), None, 0, max_network_retries=1
)
is True
)
assert (
client._should_retry(
(None, 503, None), None, 0, max_network_retries=1
)
is True
)
def test_should_retry_on_error(self, mocker):
client = _http_client.new_default_http_client()
api_connection_error = Mock()
api_connection_error.should_retry = True
assert (
client._should_retry(
None, api_connection_error, 0, max_network_retries=1
)
is True
)
api_connection_error.should_retry = False
assert (
client._should_retry(
None, api_connection_error, 0, max_network_retries=1
)
is False
)
def test_should_retry_on_stripe_should_retry_true(self, mocker):
client = _http_client.new_default_http_client()
headers = {"stripe-should-retry": "true"}
# Ordinarily, we would not retry a 400, but with the header as true, we would.
assert (
client._should_retry(
(None, 400, {}), None, 0, max_network_retries=1
)
is False
)
assert (
client._should_retry(
(None, 400, headers), None, 0, max_network_retries=1
)
is True
)
def test_should_retry_on_stripe_should_retry_false(self, mocker):
client = _http_client.new_default_http_client()
headers = {"stripe-should-retry": "false"}
# Ordinarily, we would retry a 500, but with the header as false, we would not.
assert (
client._should_retry(
(None, 500, {}), None, 0, max_network_retries=1
)
is True
)
assert (
client._should_retry(
(None, 500, headers), None, 0, max_network_retries=1
)
is False
)
def test_should_retry_on_num_retries(self, mocker):
client = _http_client.new_default_http_client()
max_test_retries = 10
api_connection_error = Mock()
api_connection_error.should_retry = True
assert (
client._should_retry(
None,
api_connection_error,
max_test_retries + 1,
max_network_retries=max_test_retries,
)
is False
)
assert (
client._should_retry(
(None, 409, None),
None,
max_test_retries + 1,
max_network_retries=max_test_retries,
)
is False
)
class TestHTTPClient:
@pytest.fixture(autouse=True)
def setup_stripe(self):
orig_attrs = {"enable_telemetry": stripe.enable_telemetry}
stripe.enable_telemetry = False
yield
stripe.enable_telemetry = orig_attrs["enable_telemetry"]
def test_sends_telemetry_on_second_request(self, mocker):
class TestClient(_http_client.HTTPClient):
pass
stripe.enable_telemetry = True
url = "http://fake.url"
client = TestClient()
client.request = mocker.MagicMock(
return_value=["", 200, {"Request-Id": "req_123"}]
)
_, code, _ = client.request_with_retries("get", url, {}, None)
assert code == 200
client.request.assert_called_with("get", url, {}, None)
client.request = mocker.MagicMock(
return_value=["", 200, {"Request-Id": "req_234"}]
)
_, code, _ = client.request_with_retries("get", url, {}, None)
assert code == 200
args, _ = client.request.call_args
assert "X-Stripe-Client-Telemetry" in args[2]
telemetry = json.loads(args[2]["X-Stripe-Client-Telemetry"])
assert telemetry["last_request_metrics"]["request_id"] == "req_123"
class ClientTestBase:
REQUEST_CLIENT: Type[_http_client.HTTPClient]
valid_url = "https://api.stripe.com/foo"
# only some clients support proxies
PROXY = None
# certain test classes depend on re-initializing the client because they've modified the mocked lib before it goes in
ALWAYS_INIT_CLIENT = False
# allow customizing client creation
CLIENT_KWARGS = None
@pytest.fixture
def make_client(self, mocked_request_lib):
def _make_client(**kwargs):
client = self.REQUEST_CLIENT(
verify_ssl_certs=True,
proxy=self.PROXY,
_lib=mocked_request_lib,
**kwargs,
)
# speed up all retries
client._sleep_time_seconds = (
lambda num_retries, response=None: 0.0001
)
return client
return _make_client
@pytest.fixture
def client(self, make_client):
return make_client()
@pytest.fixture
def make_request(self, make_client, client) -> MakeReqFunc:
def _make_request(
method,
url,
headers,
post_data,
client_kwargs=None,
max_retries=None,
):
# reuse the fixture client, if possible
if client_kwargs or self.CLIENT_KWARGS or self.ALWAYS_INIT_CLIENT:
local_client = make_client(
**{
**(self.CLIENT_KWARGS or {}),
**(client_kwargs or {}),
}
)
else:
local_client = client
return local_client.request_with_retries(
method,
url,
headers,
post_data,
max_network_retries=max_retries,
)
return _make_request
@pytest.fixture
def make_streamed_request(self, make_client, client) -> MakeReqFunc:
def _make_request_stream(
method,
url,
headers,
post_data,
client_kwargs=None,
max_retries=None,
):
if client_kwargs or self.CLIENT_KWARGS or self.ALWAYS_INIT_CLIENT:
local_client = make_client(
**(client_kwargs or self.CLIENT_KWARGS or {})
)
else:
local_client = client
return local_client.request_stream_with_retries(
method,
url,
headers,
post_data,
max_network_retries=max_retries,
)
return _make_request_stream
@pytest.fixture
def make_async_request(self, make_client, client) -> MakeReqFunc:
def _make_request_async(
method,
url,
headers,
post_data,
client_kwargs=None,
max_retries=None,
):
if client_kwargs or self.CLIENT_KWARGS or self.ALWAYS_INIT_CLIENT:
local_client = make_client(
**(client_kwargs or {}),
**(self.CLIENT_KWARGS or {}),
)
else:
local_client = client
return local_client.request_with_retries_async(
method,
url,
headers,
post_data,
max_network_retries=max_retries,
)
return _make_request_async
@pytest.fixture
def make_async_stream_request(self, make_client, client) -> MakeReqFunc:
async def _make_request_stream_async(
method,
url,
headers,
post_data,
client_kwargs=None,
max_retries=None,
):
if client_kwargs or self.CLIENT_KWARGS or self.ALWAYS_INIT_CLIENT:
local_client = make_client(
**(client_kwargs or {}),
**(self.CLIENT_KWARGS or {}),
)
else:
local_client = client
return await local_client.request_stream_with_retries_async(
method,
url,
headers,
post_data,
max_network_retries=max_retries,
)
return _make_request_stream_async
@pytest.fixture
def mock_response(self):
def mock_response(mock, body, code):
raise NotImplementedError(
"You must implement this in your test subclass"
)
return mock_response
@pytest.fixture
def mock_error(self):
def mock_error(mock, error):
raise NotImplementedError(
"You must implement this in your test subclass"
)
return mock_error
@pytest.fixture
def check_call(self):
def check_call(
mock, method, abs_url, headers, params, is_streaming=False
):
raise NotImplementedError(
"You must implement this in your test subclass"
)
return check_call
def test_request(
self,
mocked_request_lib,
make_request: MakeReqFunc,
mock_response,
check_call,
):
mock_response(mocked_request_lib, '{"foo": "baz"}', 200)
for method in VALID_API_METHODS:
abs_url = self.valid_url
data = ""
if method != "post":
abs_url = f"{abs_url}?{data}"
data = None
headers = {"my-header": "header val"}
body, code, _ = make_request(method, abs_url, headers, data)
assert code == 200
assert body == '{"foo": "baz"}'
check_call(mocked_request_lib, method, abs_url, data, headers)
def test_request_stream(
self, mocked_request_lib, make_streamed_request, mock_response
):
for method in VALID_API_METHODS:
mock_response(mocked_request_lib, "some streamed content", 200)
abs_url = self.valid_url
data = ""
if method != "post":
abs_url = "%s?%s" % (abs_url, data)
data = None
headers = {"my-header": "header val"}
stream, code, _ = make_streamed_request(
method, abs_url, headers, data
)
assert code == 200
body_content = None
# Here we need to convert and align all content on one type (string)
# as some clients return a string stream others a byte stream.
if hasattr(stream, "read"):
body_content = stream.read()
if hasattr(body_content, "decode"):
body_content = body_content.decode("utf-8")
elif hasattr(stream, "__iter__"):
body_content = "".join(
[chunk.decode("utf-8") for chunk in stream]
)
assert body_content == "some streamed content"
def test_exception(self, mocked_request_lib, mock_error, make_request):
mock_error(mocked_request_lib)
with pytest.raises(APIConnectionError):
make_request("get", self.valid_url, {}, None, mocked_request_lib)
class RequestsVerify(object):
def __eq__(self, other):
return other and other.endswith("stripe/data/ca-certificates.crt")
class TestRequestsClient(ClientTestBase):
REQUEST_CLIENT: Type[_http_client.RequestsClient] = (
_http_client.RequestsClient
)
PROXY = "http://slap/"
@pytest.fixture
def session(self):
return MagicMock()
@pytest.fixture
def mock_response(self, session):
def _mock_response(mock, body, code):
result = Mock()
result.content = body
result.status_code = code
result.headers = {}
result.raw = urllib3.response.HTTPResponse(
body=io.BytesIO(str.encode(body)),
preload_content=False,
status=code,
)
session.request = MagicMock(return_value=result)
mock.Session = MagicMock(return_value=session)
return _mock_response
@pytest.fixture
def mock_error(self, session):
def _mock_error(mock):
# The first kind of request exceptions we catch
mock.exceptions.SSLError = Exception
session.request.side_effect = mock.exceptions.SSLError()
mock.Session = MagicMock(return_value=session)
return _mock_error
@pytest.fixture
def check_call(self, session):
def _check_call(
_,
method,
url,
post_data,
headers,
is_streaming=False,
timeout=80,
times=None,
):
times = times or 1
pargs = (method, url)
kwargs = {
"headers": headers,
"data": post_data,
"verify": RequestsVerify(),
"proxies": {"http": "http://slap/", "https": "http://slap/"},
"timeout": timeout,
}
if is_streaming:
kwargs["stream"] = True
calls = [call(*pargs, **kwargs) for _ in range(times)]
session.request.assert_has_calls(calls)
return _check_call
def test_timeout(
self, mocked_request_lib, mock_response, check_call, make_request
):
headers = {"my-header": "header val"}
data = ""
mock_response(mocked_request_lib, '{"foo": "baz"}', 200)
make_request(
"POST", self.valid_url, headers, data, client_kwargs={"timeout": 5}
)
check_call(None, "POST", self.valid_url, data, headers, timeout=5)
def test_request_stream_forwards_stream_param(
self,
mocked_request_lib,
mock_response,
check_call,
make_streamed_request: MakeReqFunc,
):
mock_response(mocked_request_lib, "some streamed content", 200)
make_streamed_request("GET", self.valid_url, {}, None)
check_call(None, "GET", self.valid_url, None, {}, is_streaming=True)
class TestRequestClientRetryBehavior(TestRequestsClient):
PROXY = "http://slap/"
max_retries = 3
@pytest.fixture
def response(self):
def response(code=200, headers=None):
result = Mock()
result.content = "{}"
result.status_code = code
result.headers = headers or {}
result.raw = urllib3.response.HTTPResponse(
body=io.BytesIO(str.encode(result.content)),
preload_content=False,
status=code,
)
return result
return response
@pytest.fixture
def mock_retry(self, session, mocked_request_lib):
def _mock_retry(
retry_error_num=0, no_retry_error_num=0, responses=None
):
if responses is None:
responses = []
# Mocking classes of exception we catch. Any group of exceptions
# with the same inheritance pattern will work
request_root_error_class = Exception
mocked_request_lib.exceptions.RequestException = (
request_root_error_class
)
no_retry_parent_class = LookupError
no_retry_child_class = KeyError
mocked_request_lib.exceptions.SSLError = no_retry_parent_class
no_retry_errors = [no_retry_child_class()] * no_retry_error_num
retry_parent_class = EnvironmentError
retry_child_class = IOError
mocked_request_lib.exceptions.Timeout = retry_parent_class
mocked_request_lib.exceptions.ConnectionError = retry_parent_class
retry_errors = [retry_child_class()] * retry_error_num
# Include mock responses as possible side-effects
# to simulate returning proper results after some exceptions
session.request.side_effect = (
retry_errors + no_retry_errors + responses
)
mocked_request_lib.Session = MagicMock(return_value=session)
return mocked_request_lib
return _mock_retry
@pytest.fixture
def check_call_numbers(self, check_call):
valid_url = self.valid_url
def _check_call_numbers(times, is_streaming=False):
check_call(
None,
"GET",
valid_url,
None,
{},
times=times,
is_streaming=is_streaming,
)
return _check_call_numbers
def test_retry_error_until_response(
self, mock_retry, response, check_call_numbers, make_request
):
mock_retry(retry_error_num=1, responses=[response(code=202)])
_, code, _ = make_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
assert code == 202
check_call_numbers(2)
def test_retry_error_until_exceeded(
self, mock_retry, check_call_numbers, make_request
):
mock_retry(retry_error_num=self.max_retries)
with pytest.raises(APIConnectionError):
make_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
check_call_numbers(self.max_retries)
def test_no_retry_error(
self, mock_retry, check_call_numbers, make_request
):
mock_retry(no_retry_error_num=self.max_retries)
with pytest.raises(APIConnectionError):
make_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
check_call_numbers(1)
def test_retry_codes(
self, mock_retry, response, check_call_numbers, make_request
):
mock_retry(responses=[response(code=409), response(code=202)])
_, code, _ = make_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
assert code == 202
check_call_numbers(2)
def test_retry_codes_until_exceeded(
self, mock_retry, response, check_call_numbers, make_request
):
mock_retry(responses=[response(code=409)] * (self.max_retries + 1))
_, code, _ = make_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
assert code == 409
check_call_numbers(self.max_retries + 1)
def test_retry_request_stream_error_until_response(
self,
mock_retry,
response,
check_call_numbers,
make_streamed_request,
):
mock_retry(retry_error_num=1, responses=[response(code=202)])
_, code, _ = make_streamed_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
assert code == 202
check_call_numbers(2, is_streaming=True)
def test_retry_request_stream_error_until_exceeded(
self,
mock_retry,
check_call_numbers,
make_streamed_request,
):
mock_retry(retry_error_num=self.max_retries)
with pytest.raises(APIConnectionError):
make_streamed_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
check_call_numbers(self.max_retries, is_streaming=True)
def test_no_retry_request_stream_error(
self,
mock_retry,
check_call_numbers,
make_streamed_request,
):
mock_retry(no_retry_error_num=self.max_retries)
with pytest.raises(APIConnectionError):
make_streamed_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
check_call_numbers(1, is_streaming=True)
def test_retry_request_stream_codes(
self,
mock_retry,
response,
check_call_numbers,
make_streamed_request,
):
mock_retry(responses=[response(code=409), response(code=202)])
_, code, _ = make_streamed_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
assert code == 202
check_call_numbers(2, is_streaming=True)
def test_retry_request_stream_codes_until_exceeded(
self,
mock_retry,
response,
check_call_numbers,
make_streamed_request,
):
mock_retry(responses=[response(code=409)] * (self.max_retries + 1))
_, code, _ = make_streamed_request(
"GET", self.valid_url, {}, None, max_retries=self.max_retries
)
assert code == 409
check_call_numbers(self.max_retries + 1, is_streaming=True)
@pytest.fixture
def connection_error(self, client):
def connection_error(given_exception):
with pytest.raises(APIConnectionError) as error:
client._handle_request_error(given_exception)
return error.value
return connection_error
def test_handle_request_error_should_retry(
self, connection_error, mock_retry
):
mocked_lib = mock_retry()
error = connection_error(mocked_lib.exceptions.Timeout())
assert error.should_retry
error = connection_error(mocked_lib.exceptions.ConnectionError())
assert error.should_retry
def test_handle_request_error_should_not_retry(
self, connection_error, mock_retry
):
request_mock = mock_retry()
error = connection_error(request_mock.exceptions.SSLError())
assert error.should_retry is False
assert "not verify Stripe's SSL certificate" in error.user_message
error = connection_error(request_mock.exceptions.RequestException())
assert error.should_retry is False
# Mimic non-requests exception as not being children of Exception,
# See mock_retry for the exceptions setup
error = connection_error(BaseException(""))
assert error.should_retry is False
assert "configuration issue locally" in error.user_message
# Skip inherited basic requests client tests
def test_request(self):
pass
def test_exception(self):
pass
def test_timeout(self):
pass
class TestUrlFetchClient(ClientTestBase):
REQUEST_CLIENT = _http_client.UrlFetchClient
@pytest.fixture
def mock_response(self):
def mock_response(mocked_lib, body, code):
result = Mock()
result.content = body
result.status_code = code
result.headers = {}
mocked_lib.fetch = Mock(return_value=result)
return result
return mock_response
@pytest.fixture
def mock_error(self):
def mock_error(mock):
mock.Error = mock.InvalidURLError = Exception
mock.fetch.side_effect = mock.InvalidURLError()
return mock_error
@pytest.fixture
def check_call(self):
def check_call(
mock, method, url, post_data, headers, is_streaming=False
):
mock.fetch.assert_called_with(
url=url,
method=method,
headers=headers,
validate_certificate=True,
deadline=55,
payload=post_data,
)
return check_call
class TestUrllibClient(ClientTestBase):
REQUEST_CLIENT: Type[_http_client.UrllibClient] = _http_client.UrllibClient