File: test_http_client.py

package info (click to toggle)
python-stripe 12.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 12,864 kB
  • sloc: python: 157,573; makefile: 13; sh: 9
file content (2004 lines) | stat: -rw-r--r-- 65,685 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
import base64
from typing import Any, List
from typing_extensions import Type
from unittest.mock import call
import pytest
import json
import sys

if sys.version_info >= (3, 8):
    from unittest.mock import AsyncMock
else:
    from mock import AsyncMock

import stripe
from stripe import _http_client
from stripe._encode import _api_encode
from stripe import APIConnectionError
import urllib3
from stripe import _util

VALID_API_METHODS = ("get", "post", "delete")


class StripeClientTestCase(object):
    REQUEST_LIBRARIES = [
        ("urlfetch", "stripe._http_client.urlfetch"),
        ("requests", "stripe._http_client.requests"),
        ("pycurl", "stripe._http_client.pycurl"),
        ("urllib.request", "stripe._http_client.urllibrequest"),
        ("httpx", "stripe._http_client.httpx"),
        ("aiohttp", "stripe._http_client.aiohttp"),
    ]

    @pytest.fixture
    def request_mocks(self, mocker):
        request_mocks = {}
        for lib, mockpath in self.REQUEST_LIBRARIES:
            request_mocks[lib] = mocker.patch(mockpath)
        return request_mocks


class TestNewDefaultHttpClient(StripeClientTestCase):
    def check_default(self, none_libs, expected):
        for lib in none_libs:
            setattr(_http_client, lib, None)

        inst = _http_client.new_default_http_client()

        assert isinstance(inst, expected)

    def test_new_default_http_client_urlfetch(self, request_mocks):
        self.check_default((), _http_client.UrlFetchClient)

    def test_new_default_http_client_requests(self, request_mocks):
        self.check_default(("urlfetch",), _http_client.RequestsClient)

    def test_new_default_http_client_pycurl(self, request_mocks):
        self.check_default(("urlfetch", "requests"), _http_client.PycurlClient)

    def test_new_default_http_client_urllib2(self, request_mocks):
        self.check_default(
            ("urlfetch", "requests", "pycurl"),
            _http_client.Urllib2Client,
        )


class TestNewHttpClientAsyncFallback(StripeClientTestCase):
    def check_default(self, none_libs, expected):
        for lib in none_libs:
            setattr(_http_client, lib, None)

        inst = _http_client.new_http_client_async_fallback()

        assert isinstance(inst, expected)

    def test_new_http_client_async_fallback_httpx(self, request_mocks):
        self.check_default((), _http_client.HTTPXClient)

    def test_new_http_client_async_fallback_aiohttp(self, request_mocks):
        self.check_default(
            (("httpx"),),
            _http_client.AIOHTTPClient,
        )

    def test_new_http_client_async_fallback_no_import_found(
        self, request_mocks
    ):
        self.check_default(
            (
                ("httpx"),
                ("aiohttp"),
            ),
            _http_client.NoImportFoundAsyncClient,
        )


class TestRetrySleepTimeDefaultHttpClient(StripeClientTestCase):
    from contextlib import contextmanager

    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(StripeClientTestCase):
    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 = mocker.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 = mocker.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(object):
    @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(object):
    REQUEST_CLIENT: Type[_http_client.HTTPClient]

    @pytest.fixture
    def request_mock(self, request_mocks):
        return request_mocks[self.REQUEST_CLIENT.name]

    @property
    def valid_url(self, path="/foo"):
        return "https://api.stripe.com%s" % (path,)

    def make_request(self, method, url, headers, post_data):
        client = self.REQUEST_CLIENT(verify_ssl_certs=True)
        return client.request_with_retries(method, url, headers, post_data)

    def make_request_stream(self, method, url, headers, post_data):
        client = self.REQUEST_CLIENT(verify_ssl_certs=True)
        return client.request_stream_with_retries(
            method, url, headers, post_data
        )

    def make_request_async(self, method, url, headers, post_data):
        client = self.REQUEST_CLIENT(verify_ssl_certs=True)
        return client.request_with_retries_async(
            method, url, headers, post_data
        )

    async def make_request_stream_async(self, method, url, headers, post_data):
        client = self.REQUEST_CLIENT(verify_ssl_certs=True)
        return await client.request_stream_with_retries_async(
            method, url, headers, post_data
        )

    @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, request_mock, mock_response, check_call):
        mock_response(request_mock, '{"foo": "baz"}', 200)

        for method in VALID_API_METHODS:
            abs_url = self.valid_url
            data = ""

            if method != "post":
                abs_url = "%s?%s" % (abs_url, data)
                data = None

            headers = {"my-header": "header val"}

            body, code, _ = self.make_request(method, abs_url, headers, data)

            assert code == 200
            assert body == '{"foo": "baz"}'

            check_call(request_mock, method, abs_url, data, headers)

    def test_request_stream(
        self, mocker, request_mock, mock_response, check_call
    ):
        for method in VALID_API_METHODS:
            mock_response(request_mock, "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, _ = self.make_request_stream(
                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"

            mocker.resetall()

    def test_exception(self, request_mock, mock_error):
        mock_error(request_mock)
        with pytest.raises(APIConnectionError):
            self.make_request("get", self.valid_url, {}, None)


class RequestsVerify(object):
    def __eq__(self, other):
        return other and other.endswith("stripe/data/ca-certificates.crt")


class TestRequestsClient(StripeClientTestCase, ClientTestBase):
    REQUEST_CLIENT: Type[_http_client.RequestsClient] = (
        _http_client.RequestsClient
    )

    @pytest.fixture
    def session(self, mocker, request_mocks):
        return mocker.MagicMock()

    @pytest.fixture
    def mock_response(self, mocker, session):
        def mock_response(mock, body, code):
            result = mocker.Mock()
            result.content = body
            result.status_code = code
            result.headers = {}
            result.raw = urllib3.response.HTTPResponse(
                body=_util.io.BytesIO(str.encode(body)),
                preload_content=False,
                status=code,
            )

            session.request = mocker.MagicMock(return_value=result)
            mock.Session = mocker.MagicMock(return_value=session)

        return mock_response

    @pytest.fixture
    def mock_error(self, mocker, 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 = mocker.MagicMock(return_value=session)

        return mock_error

    # Note that unlike other modules, we don't use the "mock" argument here
    # because we need to run the request call against the internal mock
    # session.
    @pytest.fixture
    def check_call(self, session):
        def check_call(
            mock,
            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 make_request(self, method, url, headers, post_data, timeout=80):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True, timeout=timeout, proxy="http://slap/"
        )
        return client.request_with_retries(method, url, headers, post_data)

    def make_request_stream(self, method, url, headers, post_data, timeout=80):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True, timeout=timeout, proxy="http://slap/"
        )
        return client.request_stream_with_retries(
            method, url, headers, post_data
        )

    def test_timeout(self, request_mock, mock_response, check_call):
        headers = {"my-header": "header val"}
        data = ""
        mock_response(request_mock, '{"foo": "baz"}', 200)
        self.make_request("POST", self.valid_url, headers, data, timeout=5)

        check_call(None, "POST", self.valid_url, data, headers, timeout=5)

    def test_request_stream_forwards_stream_param(
        self, mocker, request_mock, mock_response, check_call
    ):
        mock_response(request_mock, "some streamed content", 200)
        self.make_request_stream("GET", self.valid_url, {}, None)

        check_call(
            None,
            "GET",
            self.valid_url,
            None,
            {},
            is_streaming=True,
        )


class TestRequestClientRetryBehavior(TestRequestsClient):
    @pytest.fixture
    def response(self, mocker):
        def response(code=200, headers={}):
            result = mocker.Mock()
            result.content = "{}"
            result.status_code = code
            result.headers = headers
            result.raw = urllib3.response.HTTPResponse(
                body=_util.io.BytesIO(str.encode(result.content)),
                preload_content=False,
                status=code,
            )

            return result

        return response

    @pytest.fixture
    def mock_retry(self, mocker, session, request_mock):
        def mock_retry(retry_error_num=0, no_retry_error_num=0, responses=[]):
            # Mocking classes of exception we catch. Any group of exceptions
            # with the same inheritance pattern will work
            request_root_error_class = Exception
            request_mock.exceptions.RequestException = request_root_error_class

            no_retry_parent_class = LookupError
            no_retry_child_class = KeyError
            request_mock.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
            request_mock.exceptions.Timeout = retry_parent_class
            request_mock.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
            )

            request_mock.Session = mocker.MagicMock(return_value=session)
            return request_mock

        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 max_retries(self):
        return 3

    def make_client(self):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True, timeout=80, proxy="http://slap/"
        )
        # Override sleep time to speed up tests
        client._sleep_time_seconds = lambda num_retries, response=None: 0.0001
        # Override configured max retries
        return client

    def make_request(self, *args, **kwargs):
        client = self.make_client()
        return client.request_with_retries(
            "GET", self.valid_url, {}, None, self.max_retries()
        )

    def make_request_stream(self, *args, **kwargs):
        client = self.make_client()
        return client.request_stream_with_retries(
            "GET", self.valid_url, {}, None, self.max_retries()
        )

    def test_retry_error_until_response(
        self, mock_retry, response, check_call_numbers
    ):
        mock_retry(retry_error_num=1, responses=[response(code=202)])
        _, code, _ = self.make_request()
        assert code == 202
        check_call_numbers(2)

    def test_retry_error_until_exceeded(
        self, mock_retry, response, check_call_numbers
    ):
        mock_retry(retry_error_num=self.max_retries())
        with pytest.raises(APIConnectionError):
            self.make_request()

        check_call_numbers(self.max_retries())

    def test_no_retry_error(self, mock_retry, response, check_call_numbers):
        mock_retry(no_retry_error_num=self.max_retries())
        with pytest.raises(APIConnectionError):
            self.make_request()
        check_call_numbers(1)

    def test_retry_codes(self, mock_retry, response, check_call_numbers):
        mock_retry(responses=[response(code=409), response(code=202)])
        _, code, _ = self.make_request()
        assert code == 202
        check_call_numbers(2)

    def test_retry_codes_until_exceeded(
        self, mock_retry, response, check_call_numbers
    ):
        mock_retry(responses=[response(code=409)] * (self.max_retries() + 1))
        _, code, _ = self.make_request()
        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
    ):
        mock_retry(retry_error_num=1, responses=[response(code=202)])
        _, code, _ = self.make_request_stream()
        assert code == 202
        check_call_numbers(2, is_streaming=True)

    def test_retry_request_stream_error_until_exceeded(
        self, mock_retry, response, check_call_numbers
    ):
        mock_retry(retry_error_num=self.max_retries())
        with pytest.raises(APIConnectionError):
            self.make_request_stream()

        check_call_numbers(self.max_retries(), is_streaming=True)

    def test_no_retry_request_stream_error(
        self, mock_retry, response, check_call_numbers
    ):
        mock_retry(no_retry_error_num=self.max_retries())
        with pytest.raises(APIConnectionError):
            self.make_request_stream()
        check_call_numbers(1, is_streaming=True)

    def test_retry_request_stream_codes(
        self, mock_retry, response, check_call_numbers
    ):
        mock_retry(responses=[response(code=409), response(code=202)])
        _, code, _ = self.make_request_stream()
        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
    ):
        mock_retry(responses=[response(code=409)] * (self.max_retries() + 1))
        _, code, _ = self.make_request_stream()
        assert code == 409
        check_call_numbers(self.max_retries() + 1, is_streaming=True)

    @pytest.fixture
    def connection_error(self, session):
        client = self.REQUEST_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
    ):
        request_mock = mock_retry()

        error = connection_error(request_mock.exceptions.Timeout())
        assert error.should_retry

        error = connection_error(request_mock.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, request_mock, mock_response, check_call):
        pass

    def test_exception(self, request_mock, mock_error):
        pass

    def test_timeout(self, request_mock, mock_response, check_call):
        pass


class TestUrlFetchClient(StripeClientTestCase, ClientTestBase):
    REQUEST_CLIENT = _http_client.UrlFetchClient

    @pytest.fixture
    def mock_response(self, mocker):
        def mock_response(mock, body, code):
            result = mocker.Mock()
            result.content = body
            result.status_code = code
            result.headers = {}

            mock.fetch = mocker.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 TestUrllib2Client(StripeClientTestCase, ClientTestBase):
    REQUEST_CLIENT: Type[_http_client.Urllib2Client] = (
        _http_client.Urllib2Client
    )

    request_object: Any

    def make_client(self, proxy):
        self.client = self.REQUEST_CLIENT(verify_ssl_certs=True, proxy=proxy)
        self.proxy = proxy

    def make_request(self, method, url, headers, post_data, proxy=None):
        self.make_client(proxy)
        return self.client.request_with_retries(
            method, url, headers, post_data
        )

    def make_request_stream(self, method, url, headers, post_data, proxy=None):
        self.make_client(proxy)
        return self.client.request_stream_with_retries(
            method, url, headers, post_data
        )

    @pytest.fixture
    def mock_response(self, mocker):
        def mock_response(mock, body, code):
            response = mocker.Mock()
            response.read = mocker.MagicMock(return_value=body)
            response.code = code
            response.info = mocker.Mock(return_value={})

            self.request_object = mocker.Mock()
            mock.Request = mocker.Mock(return_value=self.request_object)

            mock.urlopen = mocker.Mock(return_value=response)

            opener = mocker.Mock()
            opener.open = mocker.Mock(return_value=response)
            mock.build_opener = mocker.Mock(return_value=opener)
            mock.build_opener.open = opener.open
            mock.ProxyHandler = mocker.Mock(return_value=opener)

            mock.urlopen = mocker.Mock(return_value=response)

        return mock_response

    @pytest.fixture
    def mock_error(self):
        def mock_error(mock):
            mock.urlopen.side_effect = ValueError
            mock.build_opener().open.side_effect = ValueError
            mock.build_opener.reset_mock()

        return mock_error

    @pytest.fixture
    def check_call(self):
        def check_call(
            mock, method, url, post_data, headers, is_streaming=False
        ):
            if isinstance(post_data, str):
                post_data = post_data.encode("utf-8")

            mock.Request.assert_called_with(url, post_data, headers)

            if self.client._proxy:
                assert isinstance(self.client._proxy, dict)
                mock.ProxyHandler.assert_called_with(self.client._proxy)
                mock.build_opener.open.assert_called_with(self.request_object)
                assert not mock.urlopen.called

            if not self.client._proxy:
                mock.urlopen.assert_called_with(self.request_object)
                assert not mock.build_opener.called
                assert not mock.build_opener.open.called

        return check_call


class TestUrllib2ClientHttpsProxy(TestUrllib2Client):
    def make_request(self, method, url, headers, post_data, proxy=None):
        return super(TestUrllib2ClientHttpsProxy, self).make_request(
            method,
            url,
            headers,
            post_data,
            {"http": "http://slap/", "https": "http://slap/"},
        )

    def make_request_stream(self, method, url, headers, post_data, proxy=None):
        return super(TestUrllib2ClientHttpsProxy, self).make_request_stream(
            method,
            url,
            headers,
            post_data,
            {"http": "http://slap/", "https": "http://slap/"},
        )


class TestUrllib2ClientHttpProxy(TestUrllib2Client):
    def make_request(self, method, url, headers, post_data, proxy=None):
        return super(TestUrllib2ClientHttpProxy, self).make_request(
            method, url, headers, post_data, "http://slap/"
        )

    def make_request_stream(self, method, url, headers, post_data, proxy=None):
        return super(TestUrllib2ClientHttpProxy, self).make_request_stream(
            method, url, headers, post_data, "http://slap/"
        )


class TestPycurlClient(StripeClientTestCase, ClientTestBase):
    REQUEST_CLIENT: Type[_http_client.PycurlClient] = _http_client.PycurlClient

    def make_client(self, proxy):
        self.client = self.REQUEST_CLIENT(verify_ssl_certs=True, proxy=proxy)
        self.proxy = proxy

    def make_request(self, method, url, headers, post_data, proxy=None):
        self.make_client(proxy)
        return self.client.request_with_retries(
            method, url, headers, post_data
        )

    def make_request_stream(self, method, url, headers, post_data, proxy=None):
        self.make_client(proxy)
        return self.client.request_stream_with_retries(
            method, url, headers, post_data
        )

    @pytest.fixture
    def curl_mock(self, mocker):
        return mocker.Mock()

    @pytest.fixture
    def request_mock(self, mocker, request_mocks, curl_mock):
        lib_mock = request_mocks[self.REQUEST_CLIENT.name]
        lib_mock.Curl = mocker.Mock(return_value=curl_mock)
        return curl_mock

    @pytest.fixture
    def bio_mock(self, mocker):
        bio_patcher = mocker.patch("stripe.util.io.BytesIO")
        bio_mock = mocker.Mock()
        bio_patcher.return_value = bio_mock
        return bio_mock

    @pytest.fixture
    def mock_response(self, mocker, bio_mock):
        def mock_response(mock, body, code):
            bio_mock.getvalue = mocker.MagicMock(
                return_value=body.encode("utf-8")
            )
            bio_mock.read = mocker.MagicMock(return_value=body.encode("utf-8"))
            mock.getinfo.return_value = code

        return mock_response

    @pytest.fixture
    def mock_error(self):
        def mock_error(mock):
            class FakeException(BaseException):
                @property
                def args(self):
                    return ("foo", "bar")

            _http_client.pycurl.error = FakeException
            mock.perform.side_effect = _http_client.pycurl.error

        return mock_error

    @pytest.fixture
    def check_call(self, request_mocks):
        def check_call(
            mock, method, url, post_data, headers, is_streaming=False
        ):
            lib_mock = request_mocks[self.REQUEST_CLIENT.name]

            if self.client._proxy:
                proxy = self.client._get_proxy(url)
                assert proxy is not None
                if proxy.hostname:
                    mock.setopt.assert_any_call(lib_mock.PROXY, proxy.hostname)
                if proxy.port:
                    mock.setopt.assert_any_call(lib_mock.PROXYPORT, proxy.port)
                if proxy.username or proxy.password:
                    mock.setopt.assert_any_call(
                        lib_mock.PROXYUSERPWD,
                        "%s:%s" % (proxy.username, proxy.password),
                    )

            # A note on methodology here: we don't necessarily need to verify
            # _every_ call to setopt, but check a few of them to make sure the
            # right thing is happening. Keep an eye specifically on conditional
            # statements where things are more likely to go wrong.

            mock.setopt.assert_any_call(lib_mock.NOSIGNAL, 1)
            mock.setopt.assert_any_call(lib_mock.URL, url)

            if method == "get":
                mock.setopt.assert_any_call(lib_mock.HTTPGET, 1)
            elif method == "post":
                mock.setopt.assert_any_call(lib_mock.POST, 1)
            else:
                mock.setopt.assert_any_call(
                    lib_mock.CUSTOMREQUEST, method.upper()
                )

            mock.perform.assert_any_call()

        return check_call


class TestPycurlClientHttpProxy(TestPycurlClient):
    def make_request(self, method, url, headers, post_data, proxy=None):
        return super(TestPycurlClientHttpProxy, self).make_request(
            method,
            url,
            headers,
            post_data,
            "http://user:withPwd@slap:8888/",
        )

    def make_request_stream(self, method, url, headers, post_data, proxy=None):
        return super(TestPycurlClientHttpProxy, self).make_request_stream(
            method,
            url,
            headers,
            post_data,
            "http://user:withPwd@slap:8888/",
        )


class TestPycurlClientHttpsProxy(TestPycurlClient):
    def make_request(self, method, url, headers, post_data, proxy=None):
        return super(TestPycurlClientHttpsProxy, self).make_request(
            method,
            url,
            headers,
            post_data,
            {"http": "http://slap:8888/", "https": "http://slap2:444/"},
        )

    def make_request_stream(self, method, url, headers, post_data, proxy=None):
        return super(TestPycurlClientHttpsProxy, self).make_request_stream(
            method,
            url,
            headers,
            post_data,
            {"http": "http://slap:8888/", "https": "http://slap2:444/"},
        )


class TestAPIEncode(StripeClientTestCase):
    def test_encode_dict(self):
        body = {"foo": {"dob": {"month": 1}, "name": "bat"}}

        values = [t for t in _api_encode(body, "V1")]

        assert ("foo[dob][month]", 1) in values
        assert ("foo[name]", "bat") in values

    def test_encode_array(self):
        body = {"foo": [{"dob": {"month": 1}, "name": "bat"}]}

        values = [t for t in _api_encode(body, "V1")]

        assert ("foo[0][dob][month]", 1) in values
        assert ("foo[0][name]", "bat") in values

    def test_encode_v2_array(self):
        body = {"foo": [{"dob": {"month": 1}, "name": "bat"}]}

        values = [t for t in _api_encode(body, "V2")]

        assert ("foo[dob][month]", 1) in values
        assert ("foo[name]", "bat") in values


class TestHTTPXClient(StripeClientTestCase, ClientTestBase):
    REQUEST_CLIENT: Type[_http_client.HTTPXClient] = _http_client.HTTPXClient

    @pytest.fixture
    def mock_response(self, mocker, request_mock):
        def mock_response(mock, body={}, code=200):
            result = mocker.Mock()
            result.content = body

            async def aiter_bytes():
                yield bytes(body, "utf-8")

            def iter_bytes():
                yield bytes(body, "utf-8")

            result.aiter_bytes = aiter_bytes
            result.iter_bytes = iter_bytes
            result.status_code = code
            result.headers = {}

            async def do_buffered(*args, **kwargs):
                return result

            async def do_stream(*args, **kwargs):
                return result

            async_mock = AsyncMock(side_effect=do_buffered)
            async_mock_stream = AsyncMock(side_effect=do_stream)

            request_mock.Client().send = mocker.Mock(return_value=result)
            request_mock.Client().request = mocker.Mock(return_value=result)
            request_mock.AsyncClient().send = async_mock_stream
            request_mock.AsyncClient().request = async_mock
            return result

        return mock_response

    @pytest.fixture
    def mock_error(self, mocker, request_mock):
        def mock_error(mock):
            # The first kind of request exceptions we catch
            mock.exceptions.SSLError = Exception
            request_mock.AsyncClient().request.side_effect = (
                mock.exceptions.SSLError()
            )

        return mock_error

    @pytest.fixture
    def check_call(self, request_mock, mocker):
        def check_call(
            mock,
            method,
            url,
            post_data,
            headers,
            is_streaming=False,
            timeout=80,
            times=None,
        ):
            times = times or 1
            args = (method, url)
            kwargs = {
                "headers": headers,
                "data": post_data or {},
                "timeout": timeout,
                "proxies": {"http": "http://slap/", "https": "http://slap/"},
            }

            if is_streaming:
                kwargs["stream"] = True

            calls = [mocker.call(*args, **kwargs) for _ in range(times)]
            request_mock.Client().request.assert_has_calls(calls)

        return check_call

    @pytest.fixture
    def check_call_async(self, request_mock, mocker):
        def check_call_async(
            mock,
            method,
            url,
            post_data,
            headers,
            is_streaming=False,
            timeout=80,
            times=None,
        ):
            times = times or 1
            args = (method, url)
            kwargs = {
                "headers": headers,
                "data": post_data,
                "timeout": timeout,
                "proxies": {"http": "http://slap/", "https": "http://slap/"},
            }

            if is_streaming:
                kwargs["stream"] = True

            calls = [mocker.call(*args, **kwargs) for _ in range(times)]
            request_mock.AsyncClient().request.assert_has_calls(calls)

        return check_call_async

    def make_request(self, method, url, headers, post_data, timeout=80):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True,
            proxy="http://slap/",
            timeout=timeout,
            allow_sync_methods=True,
        )
        return client.request_with_retries(method, url, headers, post_data)

    def make_request_stream(self, method, url, headers, post_data, timeout=80):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True,
            proxy="http://slap/",
            timeout=timeout,
            allow_sync_methods=True,
        )
        return client.request_stream_with_retries(
            method, url, headers, post_data
        )

    async def make_request_async(
        self, method, url, headers, post_data, timeout=80
    ):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True, proxy="http://slap/", timeout=timeout
        )
        return await client.request_with_retries_async(
            method, url, headers, post_data
        )

    async def make_request_stream_async(
        self, method, url, headers, post_data, timeout=80
    ):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True, proxy="http://slap/"
        )
        return await client.request_stream_with_retries_async(
            method, url, headers, post_data
        )

    @pytest.mark.anyio
    async def test_request_async(
        self, request_mock, mock_response, check_call_async
    ):
        mock_response(request_mock, '{"foo": "baz"}', 200)

        for method in VALID_API_METHODS:
            abs_url = self.valid_url
            data = {}

            if method != "post":
                abs_url = "%s?%s" % (abs_url, data)
                data = {}

            headers = {"my-header": "header val"}
            body, code, _ = await self.make_request_async(
                method, abs_url, headers, data
            )
            assert code == 200
            assert body == '{"foo": "baz"}'

            check_call_async(request_mock, method, abs_url, data, headers)

    @pytest.mark.anyio
    async def test_request_stream_async(
        self, mocker, request_mock, mock_response, check_call
    ):
        for method in VALID_API_METHODS:
            mock_response(request_mock, "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, _ = await self.make_request_stream_async(
                method, abs_url, headers, data
            )

            assert code == 200

            # Here we need to convert and align all content on one type (string)
            # as some clients return a string stream others a byte stream.
            body_content = b"".join([x async for x in stream])
            if hasattr(body_content, "decode"):
                body_content = body_content.decode("utf-8")

            assert body_content == "some streamed content"

            mocker.resetall()

    @pytest.mark.anyio
    async def test_exception(self, request_mock, mock_error):
        mock_error(request_mock)
        with pytest.raises(stripe.APIConnectionError):
            await self.make_request_async("get", self.valid_url, {}, None)

    @pytest.mark.anyio
    def test_timeout(self, request_mock, mock_response, check_call):
        headers = {"my-header": "header val"}
        data = {}
        mock_response(request_mock, '{"foo": "baz"}', 200)
        self.make_request("POST", self.valid_url, headers, data, timeout=5)

        check_call(
            request_mock, "POST", self.valid_url, data, headers, timeout=5
        )

    @pytest.mark.anyio
    async def test_timeout_async(
        self, request_mock, mock_response, check_call_async
    ):
        headers = {"my-header": "header val"}
        data = {}
        mock_response(request_mock, '{"foo": "baz"}', 200)
        await self.make_request_async(
            "POST", self.valid_url, headers, data, timeout=5
        )

        check_call_async(
            request_mock, "POST", self.valid_url, data, headers, timeout=5
        )

    @pytest.mark.anyio
    async def test_request_stream_forwards_stream_param(
        self, mocker, request_mock, mock_response, check_call
    ):
        # TODO
        pass

    def test_allow_sync_methods(self, request_mock, mock_response):
        client = self.REQUEST_CLIENT()
        assert client._client is None
        with pytest.raises(RuntimeError):
            client.request("GET", "http://foo", {})
        with pytest.raises(RuntimeError):
            client.request_stream("GET", "http://foo", {})
        client = self.REQUEST_CLIENT(allow_sync_methods=True)
        assert client._client is not None
        mock_response(request_mock, '{"foo": "baz"}', 200)
        client.request("GET", "http://foo", {})
        mock_response(request_mock, '{"foo": "baz"}', 200)
        client.request_stream("GET", "http://foo", {})


class TestHTTPXClientRetryBehavior(TestHTTPXClient):
    responses = None

    @pytest.fixture
    def mock_retry(self, mocker, request_mock):
        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
            request_mock.exceptions.RequestException = request_root_error_class

            no_retry_parent_class = LookupError
            no_retry_child_class = KeyError
            request_mock.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
            request_mock.exceptions.Timeout = retry_parent_class
            request_mock.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

            results = retry_errors + no_retry_errors + responses

            request_mock.AsyncClient().request = AsyncMock(side_effect=results)
            self.responses = results

            return request_mock

        return mock_retry

    @pytest.fixture
    def check_call_numbers(self, check_call_async):
        valid_url = self.valid_url

        def check_call_numbers(times, is_streaming=False):
            check_call_async(
                None,
                "GET",
                valid_url,
                {},
                {},
                times=times,
                is_streaming=is_streaming,
            )

        return check_call_numbers

    def max_retries(self):
        return 3

    def make_client(self, **kwargs):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True, timeout=80, proxy="http://slap/", **kwargs
        )
        # Override sleep time to speed up tests
        client._sleep_time_seconds = lambda num_retries, response=None: 0.0001
        # Override configured max retries
        return client

    def make_request(self, *args, **kwargs):
        client = self.make_client(allow_sync_methods=True)
        return client.request_with_retries(
            "GET", self.valid_url, {}, None, self.max_retries()
        )

    def make_request_stream(self, *args, **kwargs):
        client = self.make_client(allow_sync_methods=True)
        return client.request_stream_with_retries(
            "GET", self.valid_url, {}, None, self.max_retries()
        )

    async def make_request_async(self, *args, **kwargs):
        client = self.make_client()
        return await client.request_with_retries_async(
            "GET", self.valid_url, {}, None, self.max_retries()
        )

    async def make_request_stream_async(self, *args, **kwargs):
        client = self.make_client()
        return await client.request_stream_with_retries_async(
            "GET", self.valid_url, {}, None, self.max_retries()
        )

    @pytest.mark.anyio
    async def test_retry_error_until_response(
        self,
        mock_retry,
        mock_response,
        check_call_numbers,
        request_mock,
        mocker,
    ):
        mock_retry(
            retry_error_num=1,
            responses=[mock_response(request_mock, code=202)],
        )
        _, code, _ = await self.make_request_async()
        assert code == 202
        check_call_numbers(2)

    @pytest.mark.anyio
    async def test_retry_error_until_exceeded(
        self, mock_retry, mock_response, check_call_numbers
    ):
        mock_retry(retry_error_num=self.max_retries())
        with pytest.raises(stripe.APIConnectionError):
            await self.make_request_async()

        check_call_numbers(self.max_retries())

    @pytest.mark.anyio
    async def test_no_retry_error(
        self, mock_retry, mock_response, check_call_numbers
    ):
        mock_retry(no_retry_error_num=self.max_retries())
        with pytest.raises(stripe.APIConnectionError):
            await self.make_request_async()
        check_call_numbers(1)

    @pytest.mark.anyio
    async def test_retry_codes(
        self, mock_retry, mock_response, request_mock, check_call_numbers
    ):
        mock_retry(
            responses=[
                mock_response(request_mock, code=409),
                mock_response(request_mock, code=202),
            ]
        )
        _, code, _ = await self.make_request_async()
        assert code == 202
        check_call_numbers(2)

    @pytest.mark.anyio
    async def test_retry_codes_until_exceeded(
        self, mock_retry, mock_response, request_mock, check_call_numbers
    ):
        mock_retry(
            responses=[mock_response(request_mock, code=409)]
            * (self.max_retries() + 1)
        )
        _, code, _ = await self.make_request_async()
        assert code == 409
        check_call_numbers(self.max_retries() + 1)

    @pytest.fixture
    def connection_error(self):
        client = self.REQUEST_CLIENT()

        def connection_error(given_exception):
            with pytest.raises(stripe.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
    ):
        request_mock = mock_retry()

        error = connection_error(request_mock.exceptions.Timeout())
        assert error.should_retry

        error = connection_error(request_mock.exceptions.ConnectionError())
        assert error.should_retry

    # Skip inherited basic client tests
    def test_request(self):
        pass

    def test_request_async(self):
        pass

    def test_timeout(self):
        pass

    def test_timeout_async(self):
        pass


class TestAIOHTTPClient(StripeClientTestCase, ClientTestBase):
    REQUEST_CLIENT: Type[_http_client.AIOHTTPClient] = (
        _http_client.AIOHTTPClient
    )

    @pytest.fixture
    def mock_response(self, mocker, request_mock):
        def mock_response(mock, body={}, code=200):
            class Content:
                def __aiter__(self):
                    async def chunk():
                        yield (
                            bytes(body, "utf-8")
                            if isinstance(body, str)
                            else body
                        )

                    return chunk()

                async def read(self):
                    return body

            class Result:
                def __init__(self):
                    self.content = Content()
                    self.status = code
                    self.headers = {}

            result = Result()

            request_mock.ClientSession().request = AsyncMock(
                return_value=result
            )
            return result

        return mock_response

    @pytest.fixture
    def mock_error(self, mocker, request_mock):
        def mock_error(mock):
            # The first kind of request exceptions we catch
            mock.exceptions.SSLError = Exception
            request_mock.ClientSession().request.side_effect = (
                mock.exceptions.SSLError()
            )

        return mock_error

    @pytest.fixture
    def check_call(self, request_mock, mocker):
        def check_call(
            mock,
            method,
            url,
            post_data,
            headers,
            is_streaming=False,
            timeout=80,
            times=None,
        ):
            times = times or 1
            args = (method, url)
            kwargs = {
                "headers": headers,
                "data": post_data or {},
                "timeout": timeout,
                "proxies": {"http": "http://slap/", "https": "http://slap/"},
            }

            if is_streaming:
                kwargs["stream"] = True

            calls = [mocker.call(*args, **kwargs) for _ in range(times)]
            request_mock.ClientSession().request.assert_has_calls(calls)

        return check_call

    @pytest.fixture
    def check_call_async(self, request_mock, mocker):
        def check_call_async(
            mock,
            method,
            url,
            post_data,
            headers,
            is_streaming=False,
            timeout=80,
            times=None,
        ):
            times = times or 1
            args = (method, url)
            kwargs = {
                "headers": headers,
                "data": post_data,
                "timeout": timeout,
                "proxy": "http://slap/",
            }

            calls = [mocker.call(*args, **kwargs) for _ in range(times)]
            request_mock.ClientSession().request.assert_has_calls(calls)

        return check_call_async

    def make_request(self, method, url, headers, post_data, timeout=80):
        pass

    async def make_request_async(
        self, method, url, headers, post_data, timeout=80
    ):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True, proxy="http://slap/", timeout=timeout
        )
        return await client.request_with_retries_async(
            method, url, headers, post_data
        )

    async def make_request_stream_async(
        self, method, url, headers, post_data, timeout=80
    ):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True, proxy="http://slap/"
        )
        return await client.request_stream_with_retries_async(
            method, url, headers, post_data
        )

    def test_request(self):
        pass

    def test_request_stream(self):
        pass

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_request_async(
        self, request_mock, mock_response, check_call_async
    ):
        mock_response(request_mock, '{"foo": "baz"}', 200)

        for method in VALID_API_METHODS:
            abs_url = self.valid_url
            data = {}

            if method != "post":
                abs_url = "%s?%s" % (abs_url, data)
                data = {}

            headers = {"my-header": "header val"}
            body, code, _ = await self.make_request_async(
                method, abs_url, headers, data
            )
            assert code == 200
            assert body == '{"foo": "baz"}'

            check_call_async(request_mock, method, abs_url, data, headers)

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_request_stream_async(
        self, mocker, request_mock, mock_response, check_call
    ):
        for method in VALID_API_METHODS:
            mock_response(request_mock, "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, _ = await self.make_request_stream_async(
                method, abs_url, headers, data
            )

            assert code == 200

            # Here we need to convert and align all content on one type (string)
            # as some clients return a string stream others a byte stream.
            body_content = b"".join([x async for x in stream])
            if hasattr(body_content, "decode"):
                body_content = body_content.decode("utf-8")

            assert body_content == "some streamed content"

            mocker.resetall()

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_exception(self, request_mock, mock_error):
        mock_error(request_mock)
        with pytest.raises(stripe.APIConnectionError):
            await self.make_request_async("get", self.valid_url, {}, None)

    def test_timeout(
        self, request_mock, mock_response, check_call, anyio_backend
    ):
        pass

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_timeout_async(
        self, request_mock, mock_response, check_call_async
    ):
        headers = {"my-header": "header val"}
        data = {}
        mock_response(request_mock, '{"foo": "baz"}', 200)
        await self.make_request_async(
            "POST", self.valid_url, headers, data, timeout=5
        )

        check_call_async(
            request_mock, "POST", self.valid_url, data, headers, timeout=5
        )

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_request_stream_forwards_stream_param(
        self, mocker, request_mock, mock_response, check_call
    ):
        # TODO
        pass


class TestAIOHTTPClientRetryBehavior(TestAIOHTTPClient):
    responses = None

    @pytest.fixture
    def mock_retry(self, mocker, request_mock):
        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
            request_mock.exceptions.RequestException = request_root_error_class

            no_retry_parent_class = LookupError
            no_retry_child_class = KeyError
            request_mock.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
            request_mock.exceptions.Timeout = retry_parent_class
            request_mock.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

            results = retry_errors + no_retry_errors + responses

            request_mock.ClientSession().request = AsyncMock(
                side_effect=results
            )
            self.responses = results

            return request_mock

        return mock_retry

    @pytest.fixture
    def check_call_numbers(self, check_call_async):
        valid_url = self.valid_url

        def check_call_numbers(times, is_streaming=False):
            check_call_async(
                None,
                "GET",
                valid_url,
                None,
                {},
                times=times,
                is_streaming=is_streaming,
            )

        return check_call_numbers

    def max_retries(self):
        return 3

    def make_client(self):
        client = self.REQUEST_CLIENT(
            verify_ssl_certs=True, timeout=80, proxy="http://slap/"
        )
        # Override sleep time to speed up tests
        client._sleep_time_seconds = lambda num_retries, response=None: 0.0001
        # Override configured max retries
        return client

    def make_request(self, *args, **kwargs):
        pass

    def make_request_stream(self, *args, **kwargs):
        pass

    async def make_request_async(self, *args, **kwargs):
        client = self.make_client()
        return await client.request_with_retries_async(
            "GET", self.valid_url, {}, None, self.max_retries()
        )

    async def make_request_stream_async(self, *args, **kwargs):
        client = self.make_client()
        return await client.request_stream_with_retries_async(
            "GET", self.valid_url, {}, None, self.max_retries()
        )

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_retry_error_until_response(
        self,
        mock_retry,
        mock_response,
        check_call_numbers,
        request_mock,
        mocker,
    ):
        mock_retry(
            retry_error_num=1,
            responses=[mock_response(request_mock, code=202)],
        )
        _, code, _ = await self.make_request_async()
        assert code == 202
        check_call_numbers(2)

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_retry_error_until_exceeded(
        self, mock_retry, mock_response, check_call_numbers
    ):
        mock_retry(retry_error_num=self.max_retries())
        with pytest.raises(stripe.APIConnectionError):
            await self.make_request_async()

        check_call_numbers(self.max_retries())

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_no_retry_error(
        self, mock_retry, mock_response, check_call_numbers
    ):
        mock_retry(no_retry_error_num=self.max_retries())
        with pytest.raises(stripe.APIConnectionError):
            await self.make_request_async()
        check_call_numbers(1)

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_retry_codes(
        self, mock_retry, mock_response, request_mock, check_call_numbers
    ):
        mock_retry(
            responses=[
                mock_response(request_mock, code=409),
                mock_response(request_mock, code=202),
            ]
        )
        _, code, _ = await self.make_request_async()
        assert code == 202
        check_call_numbers(2)

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_retry_codes_until_exceeded(
        self, mock_retry, mock_response, request_mock, check_call_numbers
    ):
        mock_retry(
            responses=[mock_response(request_mock, code=409)]
            * (self.max_retries() + 1)
        )
        _, code, _ = await self.make_request_async()
        assert code == 409
        check_call_numbers(self.max_retries() + 1)

    def connection_error(self, client, given_exception):
        with pytest.raises(stripe.APIConnectionError) as error:
            client._handle_request_error(given_exception)
        return error.value

    @pytest.mark.parametrize("anyio_backend", ["asyncio"])
    @pytest.mark.anyio
    async def test_handle_request_error_should_retry(
        self, mock_retry, anyio_backend
    ):
        client = self.REQUEST_CLIENT()
        request_mock = mock_retry()

        error = self.connection_error(
            client, request_mock.exceptions.Timeout()
        )
        assert error.should_retry

        error = self.connection_error(
            client, request_mock.exceptions.ConnectionError()
        )
        assert error.should_retry

    # Skip inherited basic client tests
    def test_request(self):
        pass

    def test_request_async(self):
        pass

    def test_timeout(self):
        pass

    def test_timeout_async(self):
        pass


class TestLiveHTTPClients:
    """
    Tests that actually make HTTP requests in order to test functionality (like https)
    end to end.
    """

    @pytest.mark.anyio
    async def test_httpx_request_async_https(self):
        """
        Test to ensure that httpx https calls succeed by making a live test call
        to the public stripe API.
        """
        method = "get"
        abs_url = "https://api.stripe.com/v1/balance"
        data = {}

        client = _http_client.HTTPXClient(verify_ssl_certs=True)
        # the public test secret key, as found on https://docs.stripe.com/keys#obtain-api-keys
        test_api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"
        basic_auth = base64.b64encode(
            (test_api_key + ":").encode("utf-8")
        ).decode("utf-8")
        headers = {"Authorization": "Basic " + basic_auth}

        _, code, _ = await client.request_with_retries_async(
            method, abs_url, headers, data
        )
        assert code >= 200 and code < 400