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
|
from __future__ import annotations
import io
import logging
import platform
import socket
import time
import typing
import warnings
from test import LONG_TIMEOUT, SHORT_TIMEOUT
from threading import Event
from unittest import mock
from urllib.parse import urlencode
import pytest
from dummyserver.socketserver import NoIPv6Warning
from dummyserver.testcase import HypercornDummyServerTestCase, SocketDummyServerTestCase
from urllib3 import HTTPConnectionPool, encode_multipart_formdata
from urllib3._collections import HTTPHeaderDict
from urllib3.connection import _get_default_user_agent
from urllib3.exceptions import (
ConnectTimeoutError,
DecodeError,
EmptyPoolError,
MaxRetryError,
NameResolutionError,
NewConnectionError,
ReadTimeoutError,
UnrewindableBodyError,
)
from urllib3.fields import _TYPE_FIELD_VALUE_TUPLE
from urllib3.util import SKIP_HEADER, SKIPPABLE_HEADERS
from urllib3.util.retry import RequestHistory, Retry
from urllib3.util.timeout import _TYPE_TIMEOUT, Timeout
from .. import INVALID_SOURCE_ADDRESSES, TARPIT_HOST, VALID_SOURCE_ADDRESSES
from ..port_helpers import find_unused_port
def wait_for_socket(ready_event: Event) -> None:
ready_event.wait()
ready_event.clear()
class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
def test_timeout_float(self) -> None:
block_event = Event()
ready_event = self.start_basic_handler(block_send=block_event, num=2)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
wait_for_socket(ready_event)
with pytest.raises(ReadTimeoutError):
pool.request("GET", "/", timeout=SHORT_TIMEOUT)
block_event.set() # Release block
# Shouldn't raise this time
wait_for_socket(ready_event)
block_event.set() # Pre-release block
pool.request("GET", "/", timeout=LONG_TIMEOUT)
def test_conn_closed(self) -> None:
block_event = Event()
self.start_basic_handler(block_send=block_event, num=1)
with HTTPConnectionPool(
self.host, self.port, timeout=SHORT_TIMEOUT, retries=False
) as pool:
conn = pool._get_conn()
pool._put_conn(conn)
try:
with pytest.raises(ReadTimeoutError):
pool.urlopen("GET", "/")
if not conn.is_closed:
with pytest.raises(socket.error):
conn.sock.recv(1024) # type: ignore[attr-defined]
finally:
pool._put_conn(conn)
block_event.set()
def test_timeout(self) -> None:
# Requests should time out when expected
block_event = Event()
ready_event = self.start_basic_handler(block_send=block_event, num=3)
# Pool-global timeout
short_timeout = Timeout(read=SHORT_TIMEOUT)
with HTTPConnectionPool(
self.host, self.port, timeout=short_timeout, retries=False
) as pool:
wait_for_socket(ready_event)
block_event.clear()
with pytest.raises(ReadTimeoutError):
pool.request("GET", "/")
block_event.set() # Release request
# Request-specific timeouts should raise errors
with HTTPConnectionPool(
self.host, self.port, timeout=short_timeout, retries=False
) as pool:
wait_for_socket(ready_event)
now = time.perf_counter()
with pytest.raises(ReadTimeoutError):
pool.request("GET", "/", timeout=LONG_TIMEOUT)
delta = time.perf_counter() - now
message = "timeout was pool-level SHORT_TIMEOUT rather than request-level LONG_TIMEOUT"
if platform.system() == "Windows":
# Adjust tolerance for floating-point comparison on Windows to
# avoid flakiness in CI #3413
assert delta >= (LONG_TIMEOUT - 1e-3), message
else:
assert delta >= (LONG_TIMEOUT - 1e-5), message
block_event.set() # Release request
# Timeout passed directly to request should raise a request timeout
wait_for_socket(ready_event)
with pytest.raises(ReadTimeoutError):
pool.request("GET", "/", timeout=SHORT_TIMEOUT)
block_event.set() # Release request
def test_connect_timeout(self) -> None:
url = "/"
host, port = TARPIT_HOST, 80
timeout = Timeout(connect=SHORT_TIMEOUT)
# Pool-global timeout
with HTTPConnectionPool(host, port, timeout=timeout) as pool:
conn = pool._get_conn()
with pytest.raises(ConnectTimeoutError):
pool._make_request(conn, "GET", url)
# Retries
retries = Retry(connect=0)
with pytest.raises(MaxRetryError):
pool.request("GET", url, retries=retries)
# Request-specific connection timeouts
big_timeout = Timeout(read=LONG_TIMEOUT, connect=LONG_TIMEOUT)
with HTTPConnectionPool(host, port, timeout=big_timeout, retries=False) as pool:
conn = pool._get_conn()
with pytest.raises(ConnectTimeoutError):
pool._make_request(conn, "GET", url, timeout=timeout)
pool._put_conn(conn)
with pytest.raises(ConnectTimeoutError):
pool.request("GET", url, timeout=timeout)
def test_total_applies_connect(self) -> None:
host, port = TARPIT_HOST, 80
timeout = Timeout(total=None, connect=SHORT_TIMEOUT)
with HTTPConnectionPool(host, port, timeout=timeout) as pool:
conn = pool._get_conn()
try:
with pytest.raises(ConnectTimeoutError):
pool._make_request(conn, "GET", "/")
finally:
conn.close()
timeout = Timeout(connect=3, read=5, total=SHORT_TIMEOUT)
with HTTPConnectionPool(host, port, timeout=timeout) as pool:
conn = pool._get_conn()
try:
with pytest.raises(ConnectTimeoutError):
pool._make_request(conn, "GET", "/")
finally:
conn.close()
def test_total_timeout(self) -> None:
block_event = Event()
ready_event = self.start_basic_handler(block_send=block_event, num=2)
wait_for_socket(ready_event)
# This will get the socket to raise an EAGAIN on the read
timeout = Timeout(connect=3, read=SHORT_TIMEOUT)
with HTTPConnectionPool(
self.host, self.port, timeout=timeout, retries=False
) as pool:
with pytest.raises(ReadTimeoutError):
pool.request("GET", "/")
block_event.set()
wait_for_socket(ready_event)
block_event.clear()
# The connect should succeed and this should hit the read timeout
timeout = Timeout(connect=3, read=5, total=SHORT_TIMEOUT)
with HTTPConnectionPool(
self.host, self.port, timeout=timeout, retries=False
) as pool:
with pytest.raises(ReadTimeoutError):
pool.request("GET", "/")
def test_create_connection_timeout(self) -> None:
self.start_basic_handler(block_send=Event(), num=0) # needed for self.port
timeout = Timeout(connect=SHORT_TIMEOUT, total=LONG_TIMEOUT)
with HTTPConnectionPool(
TARPIT_HOST, self.port, timeout=timeout, retries=False
) as pool:
conn = pool._new_conn()
with pytest.raises(ConnectTimeoutError):
conn.connect()
class TestConnectionPool(HypercornDummyServerTestCase):
def test_http2_test_error(self, http_version: str) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
if http_version == "h2":
with pytest.raises(
ValueError, match="HTTP/2 support currently only applies to HTTPS.*"
):
r = pool.request("GET", "/")
else:
r = pool.request("GET", "/")
assert r.status == 200
def test_get(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/specific_method", fields={"method": "GET"})
assert r.status == 200, r.data
def test_debug_log(self, caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.DEBUG, logger="urllib3.connectionpool")
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.urlopen("GET", "/")
assert r.status == 200
logs = [record.getMessage() for record in caplog.records]
assert logs == [
f"Starting new HTTP connection (1): {self.host}:{self.port}",
f'http://{self.host}:{self.port} "GET / HTTP/1.1" 200 0',
]
def test_post_url(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("POST", "/specific_method", fields={"method": "POST"})
assert r.status == 200, r.data
def test_urlopen_put(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.urlopen("PUT", "/specific_method?method=PUT")
assert r.status == 200, r.data
def test_wrong_specific_method(self) -> None:
# To make sure the dummy server is actually returning failed responses
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/specific_method", fields={"method": "POST"})
assert r.status == 400, r.data
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("POST", "/specific_method", fields={"method": "GET"})
assert r.status == 400, r.data
def test_upload(self) -> None:
data = "I'm in ur multipart form-data, hazing a cheezburgr"
fields: dict[str, _TYPE_FIELD_VALUE_TUPLE] = {
"upload_param": "filefield",
"upload_filename": "lolcat.txt",
"filefield": ("lolcat.txt", data),
}
fields["upload_size"] = len(data) # type: ignore[assignment]
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("POST", "/upload", fields=fields)
assert r.status == 200, r.data
def test_one_name_multiple_values(self) -> None:
fields = [("foo", "a"), ("foo", "b")]
with HTTPConnectionPool(self.host, self.port) as pool:
# urlencode
r = pool.request("GET", "/echo", fields=fields)
assert r.data == b"foo=a&foo=b"
# multipart
r = pool.request("POST", "/echo", fields=fields)
assert r.data.count(b'name="foo"') == 2
def test_request_method_body(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
body = b"hi"
r = pool.request("POST", "/echo", body=body)
assert r.data == body
fields = [("hi", "hello")]
with pytest.raises(TypeError):
pool.request("POST", "/echo", body=body, fields=fields)
def test_unicode_upload(self) -> None:
fieldname = "myfile"
filename = "\xe2\x99\xa5.txt"
data = "\xe2\x99\xa5".encode()
size = len(data)
fields: dict[str, _TYPE_FIELD_VALUE_TUPLE] = {
"upload_param": fieldname,
"upload_filename": filename,
fieldname: (filename, data),
}
fields["upload_size"] = size # type: ignore[assignment]
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("POST", "/upload", fields=fields)
assert r.status == 200, r.data
def test_nagle(self) -> None:
"""Test that connections have TCP_NODELAY turned on"""
# This test needs to be here in order to be run. socket.create_connection actually tries
# to connect to the host provided so we need a dummyserver to be running.
with HTTPConnectionPool(self.host, self.port) as pool:
conn = pool._get_conn()
try:
pool._make_request(conn, "GET", "/")
tcp_nodelay_setting = conn.sock.getsockopt( # type: ignore[attr-defined]
socket.IPPROTO_TCP, socket.TCP_NODELAY
)
assert tcp_nodelay_setting
finally:
conn.close()
@pytest.mark.parametrize(
"socket_options",
[
[(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)],
((socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),),
],
)
def test_socket_options(self, socket_options: tuple[int, int, int]) -> None:
"""Test that connections accept socket options."""
# This test needs to be here in order to be run. socket.create_connection actually tries to
# connect to the host provided so we need a dummyserver to be running.
with HTTPConnectionPool(
self.host,
self.port,
socket_options=socket_options,
) as pool:
# Get the socket of a new connection.
s = pool._new_conn()._new_conn() # type: ignore[attr-defined]
try:
using_keepalive = (
s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0
)
assert using_keepalive
finally:
s.close()
@pytest.mark.parametrize("socket_options", [None, []])
def test_disable_default_socket_options(
self, socket_options: list[int] | None
) -> None:
"""Test that passing None or empty list disables all socket options."""
# This test needs to be here in order to be run. socket.create_connection actually tries
# to connect to the host provided so we need a dummyserver to be running.
with HTTPConnectionPool(
self.host, self.port, socket_options=socket_options
) as pool:
s = pool._new_conn()._new_conn() # type: ignore[attr-defined]
try:
using_nagle = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) == 0
assert using_nagle
finally:
s.close()
def test_defaults_are_applied(self) -> None:
"""Test that modifying the default socket options works."""
# This test needs to be here in order to be run. socket.create_connection actually tries
# to connect to the host provided so we need a dummyserver to be running.
with HTTPConnectionPool(self.host, self.port) as pool:
# Get the HTTPConnection instance
conn = pool._new_conn()
try:
# Update the default socket options
assert conn.socket_options is not None
conn.socket_options += [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
s = conn._new_conn() # type: ignore[attr-defined]
nagle_disabled = (
s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) > 0
)
using_keepalive = (
s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0
)
assert nagle_disabled
assert using_keepalive
finally:
conn.close()
s.close()
def test_connection_error_retries(self) -> None:
"""ECONNREFUSED error should raise a connection error, with retries"""
port = find_unused_port()
with HTTPConnectionPool(self.host, port) as pool:
with pytest.raises(MaxRetryError) as e:
pool.request("GET", "/", retries=Retry(connect=3))
assert type(e.value.reason) is NewConnectionError
def test_timeout_success(self) -> None:
timeout = Timeout(connect=3, read=5, total=None)
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool:
pool.request("GET", "/")
# This should not raise a "Timeout already started" error
pool.request("GET", "/")
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool:
# This should also not raise a "Timeout already started" error
pool.request("GET", "/")
timeout = Timeout(total=None)
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool:
pool.request("GET", "/")
socket_timeout_reuse_testdata = pytest.mark.parametrize(
["timeout", "expect_settimeout_calls"],
[
(1, (1, 1)),
(None, (None, None)),
(Timeout(read=4), (None, 4)),
(Timeout(read=4, connect=5), (5, 4)),
(Timeout(connect=6), (6, None)),
],
)
@socket_timeout_reuse_testdata
def test_socket_timeout_updated_on_reuse_constructor(
self,
timeout: _TYPE_TIMEOUT,
expect_settimeout_calls: typing.Sequence[float | None],
) -> None:
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool:
# Make a request to create a new connection.
pool.urlopen("GET", "/")
# Grab the connection and mock the inner socket.
assert pool.pool is not None
conn = pool.pool.get_nowait()
conn_sock = mock.Mock(wraps=conn.sock)
conn.sock = conn_sock
pool._put_conn(conn)
# Assert that sock.settimeout() is called with the new connect timeout, then the read timeout.
pool.urlopen("GET", "/", timeout=timeout)
conn_sock.settimeout.assert_has_calls(
[mock.call(x) for x in expect_settimeout_calls]
)
@socket_timeout_reuse_testdata
def test_socket_timeout_updated_on_reuse_parameter(
self,
timeout: _TYPE_TIMEOUT,
expect_settimeout_calls: typing.Sequence[float | None],
) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
# Make a request to create a new connection.
pool.urlopen("GET", "/", timeout=LONG_TIMEOUT)
# Grab the connection and mock the inner socket.
assert pool.pool is not None
conn = pool.pool.get_nowait()
conn_sock = mock.Mock(wraps=conn.sock)
conn.sock = conn_sock
pool._put_conn(conn)
# Assert that sock.settimeout() is called with the new connect timeout, then the read timeout.
pool.urlopen("GET", "/", timeout=timeout)
conn_sock.settimeout.assert_has_calls(
[mock.call(x) for x in expect_settimeout_calls]
)
def test_tunnel(self) -> None:
timeout = Timeout(total=None)
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool:
conn = pool._get_conn()
try:
conn.set_tunnel(self.host, self.port)
with mock.patch.object(
conn, "_tunnel", create=True, return_value=None
) as conn_tunnel:
pool._make_request(conn, "GET", "/")
conn_tunnel.assert_called_once_with()
finally:
conn.close()
# test that it's not called when tunnel is not set
timeout = Timeout(total=None)
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool:
conn = pool._get_conn()
try:
with mock.patch.object(
conn, "_tunnel", create=True, return_value=None
) as conn_tunnel:
pool._make_request(conn, "GET", "/")
assert not conn_tunnel.called
finally:
conn.close()
def test_redirect_relative_url_no_deprecation(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
pool.request("GET", "/redirect", fields={"target": "/"})
def test_redirect(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/redirect", fields={"target": "/"}, redirect=False)
assert r.status == 303
r = pool.request("GET", "/redirect", fields={"target": "/"})
assert r.status == 200
assert r.data == b"Dummy server!"
def test_303_redirect_makes_request_lose_body(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
response = pool.request(
"POST",
"/redirect",
fields={"target": "/headers_and_params", "status": "303 See Other"},
)
data = response.json()
assert data["params"] == {}
assert "Content-Type" not in HTTPHeaderDict(data["headers"])
def test_bad_connect(self) -> None:
with HTTPConnectionPool("badhost.invalid", self.port) as pool:
with pytest.raises(MaxRetryError) as e:
pool.request("GET", "/", retries=5)
assert type(e.value.reason) is NameResolutionError
def test_keepalive(self) -> None:
with HTTPConnectionPool(self.host, self.port, block=True, maxsize=1) as pool:
r = pool.request("GET", "/keepalive?close=0")
r = pool.request("GET", "/keepalive?close=0")
assert r.status == 200
assert pool.num_connections == 1
assert pool.num_requests == 2
def test_keepalive_close(self) -> None:
with HTTPConnectionPool(
self.host, self.port, block=True, maxsize=1, timeout=2
) as pool:
r = pool.request(
"GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"}
)
assert pool.num_connections == 1
# The dummyserver will have responded with Connection:close,
# and httplib will properly cleanup the socket.
# We grab the HTTPConnection object straight from the Queue,
# because _get_conn() is where the check & reset occurs
assert pool.pool is not None
conn = pool.pool.get()
assert conn.sock is None
pool._put_conn(conn)
# Now with keep-alive
r = pool.request(
"GET",
"/keepalive?close=0",
retries=0,
headers={"Connection": "keep-alive"},
)
# The dummyserver responded with Connection:keep-alive, the connection
# persists.
conn = pool.pool.get()
assert conn.sock is not None
pool._put_conn(conn)
# Another request asking the server to close the connection. This one
# should get cleaned up for the next request.
r = pool.request(
"GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"}
)
assert r.status == 200
conn = pool.pool.get()
assert conn.sock is None
pool._put_conn(conn)
# Next request
r = pool.request("GET", "/keepalive?close=0")
def test_post_with_urlencode(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
data = {"banana": "hammock", "lol": "cat"}
r = pool.request("POST", "/echo", fields=data, encode_multipart=False)
assert r.data.decode("utf-8") == urlencode(data)
def test_post_with_multipart(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
data = {"banana": "hammock", "lol": "cat"}
r = pool.request("POST", "/echo", fields=data, encode_multipart=True)
body = r.data.split(b"\r\n")
encoded_data = encode_multipart_formdata(data)[0]
expected_body = encoded_data.split(b"\r\n")
# TODO: Get rid of extra parsing stuff when you can specify
# a custom boundary to encode_multipart_formdata
"""
We need to loop the return lines because a timestamp is attached
from within encode_multipart_formdata. When the server echos back
the data, it has the timestamp from when the data was encoded, which
is not equivalent to when we run encode_multipart_formdata on
the data again.
"""
for i, line in enumerate(body):
if line.startswith(b"--"):
continue
assert body[i] == expected_body[i]
def test_post_with_multipart__iter__(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
data = {"hello": "world"}
r = pool.request(
"POST",
"/echo",
fields=data,
preload_content=False,
multipart_boundary="boundary",
encode_multipart=True,
)
chunks = [chunk for chunk in r]
assert chunks == [
b"--boundary\r\n",
b'Content-Disposition: form-data; name="hello"\r\n',
b"\r\n",
b"world\r\n",
b"--boundary--\r\n",
]
def test_check_gzip(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request(
"GET", "/encodingrequest", headers={"accept-encoding": "gzip"}
)
assert r.headers.get("content-encoding") == "gzip"
assert r.data == b"hello, world!"
def test_check_deflate(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request(
"GET", "/encodingrequest", headers={"accept-encoding": "deflate"}
)
assert r.headers.get("content-encoding") == "deflate"
assert r.data == b"hello, world!"
def test_bad_decode(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
with pytest.raises(DecodeError):
pool.request(
"GET",
"/encodingrequest",
headers={"accept-encoding": "garbage-deflate"},
)
with pytest.raises(DecodeError):
pool.request(
"GET",
"/encodingrequest",
headers={"accept-encoding": "garbage-gzip"},
)
def test_connection_count(self) -> None:
with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool:
pool.request("GET", "/")
pool.request("GET", "/")
pool.request("GET", "/")
assert pool.num_connections == 1
assert pool.num_requests == 3
def test_connection_count_bigpool(self) -> None:
with HTTPConnectionPool(self.host, self.port, maxsize=16) as http_pool:
http_pool.request("GET", "/")
http_pool.request("GET", "/")
http_pool.request("GET", "/")
assert http_pool.num_connections == 1
assert http_pool.num_requests == 3
def test_partial_response(self) -> None:
with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool:
req_data = {"lol": "cat"}
resp_data = urlencode(req_data).encode("utf-8")
r = pool.request("GET", "/echo", fields=req_data, preload_content=False)
assert r.read(5) == resp_data[:5]
assert r.read() == resp_data[5:]
def test_lazy_load_twice(self) -> None:
# This test is sad and confusing. Need to figure out what's
# going on with partial reads and socket reuse.
with HTTPConnectionPool(
self.host, self.port, block=True, maxsize=1, timeout=2
) as pool:
payload_size = 1024 * 2
first_chunk = 512
boundary = "foo"
req_data = {"count": "a" * payload_size}
resp_data = encode_multipart_formdata(req_data, boundary=boundary)[0]
req2_data = {"count": "b" * payload_size}
resp2_data = encode_multipart_formdata(req2_data, boundary=boundary)[0]
r1 = pool.request(
"POST",
"/echo",
fields=req_data,
multipart_boundary=boundary,
preload_content=False,
)
assert r1.read(first_chunk) == resp_data[:first_chunk]
try:
r2 = pool.request(
"POST",
"/echo",
fields=req2_data,
multipart_boundary=boundary,
preload_content=False,
pool_timeout=0.001,
)
# This branch should generally bail here, but maybe someday it will
# work? Perhaps by some sort of magic. Consider it a TODO.
assert r2.read(first_chunk) == resp2_data[:first_chunk]
assert r1.read() == resp_data[first_chunk:]
assert r2.read() == resp2_data[first_chunk:]
assert pool.num_requests == 2
except EmptyPoolError:
assert r1.read() == resp_data[first_chunk:]
assert pool.num_requests == 1
assert pool.num_connections == 1
def test_for_double_release(self) -> None:
MAXSIZE = 5
# Check default state
with HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE) as pool:
assert pool.num_connections == 0
assert pool.pool is not None
assert pool.pool.qsize() == MAXSIZE
# Make an empty slot for testing
pool.pool.get()
assert pool.pool.qsize() == MAXSIZE - 1
# Check state after simple request
pool.urlopen("GET", "/")
assert pool.pool.qsize() == MAXSIZE - 1
# Check state without release
pool.urlopen("GET", "/", preload_content=False)
assert pool.pool.qsize() == MAXSIZE - 2
pool.urlopen("GET", "/")
assert pool.pool.qsize() == MAXSIZE - 2
# Check state after read
pool.urlopen("GET", "/").data
assert pool.pool.qsize() == MAXSIZE - 2
pool.urlopen("GET", "/")
assert pool.pool.qsize() == MAXSIZE - 2
def test_release_conn_parameter(self) -> None:
MAXSIZE = 5
with HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE) as pool:
assert pool.pool is not None
assert pool.pool.qsize() == MAXSIZE
# Make request without releasing connection
pool.request("GET", "/", release_conn=False, preload_content=False)
assert pool.pool.qsize() == MAXSIZE - 1
def test_dns_error(self) -> None:
with HTTPConnectionPool(
"thishostdoesnotexist.invalid", self.port, timeout=0.001
) as pool:
with pytest.raises(MaxRetryError):
pool.request("GET", "/test", retries=2)
@pytest.mark.parametrize("char", [" ", "\r", "\n", "\x00"])
def test_invalid_method_not_allowed(self, char: str) -> None:
with pytest.raises(ValueError):
with HTTPConnectionPool(self.host, self.port) as pool:
pool.request("GET" + char, "/")
def test_percent_encode_invalid_target_chars(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/echo_params?q=\r&k=\n \n")
assert r.data == b"[('k', '\\n \\n'), ('q', '\\r')]"
def test_source_address(self) -> None:
for addr, is_ipv6 in VALID_SOURCE_ADDRESSES:
if is_ipv6:
# TODO enable if HAS_IPV6_AND_DNS when this is fixed:
# https://github.com/pgjones/hypercorn/issues/160
warnings.warn("No IPv6 support: skipping.", NoIPv6Warning)
continue
with HTTPConnectionPool(
self.host, self.port, source_address=addr, retries=False
) as pool:
r = pool.request("GET", "/source_address")
assert r.data == addr[0].encode()
@pytest.mark.parametrize(
"invalid_source_address, is_ipv6", INVALID_SOURCE_ADDRESSES
)
def test_source_address_error(
self, invalid_source_address: tuple[str, int], is_ipv6: bool
) -> None:
with HTTPConnectionPool(
self.host, self.port, source_address=invalid_source_address, retries=False
) as pool:
if is_ipv6:
# with pytest.raises(NameResolutionError):
with pytest.raises(NewConnectionError):
pool.request("GET", f"/source_address?{invalid_source_address}")
else:
with pytest.raises(NewConnectionError):
pool.request("GET", f"/source_address?{invalid_source_address}")
def test_stream_keepalive(self) -> None:
x = 2
with HTTPConnectionPool(self.host, self.port) as pool:
for _ in range(x):
response = pool.request(
"GET",
"/chunked",
headers={"Connection": "keep-alive"},
preload_content=False,
retries=False,
)
for chunk in response.stream():
assert chunk == b"123"
assert pool.num_connections == 1
assert pool.num_requests == x
def test_read_chunked_short_circuit(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
response = pool.request("GET", "/chunked", preload_content=False)
response.read()
with pytest.raises(StopIteration):
next(response.read_chunked())
def test_read_chunked_on_closed_response(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
response = pool.request("GET", "/chunked", preload_content=False)
response.close()
with pytest.raises(StopIteration):
next(response.read_chunked())
def test_chunked_gzip(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
response = pool.request(
"GET", "/chunked_gzip", preload_content=False, decode_content=True
)
assert b"123" * 4 == response.read()
def test_cleanup_on_connection_error(self) -> None:
"""
Test that connections are recycled to the pool on
connection errors where no http response is received.
"""
poolsize = 3
with HTTPConnectionPool(
self.host, self.port, maxsize=poolsize, block=True
) as http:
assert http.pool is not None
assert http.pool.qsize() == poolsize
# force a connection error by supplying a non-existent
# url. We won't get a response for this and so the
# conn won't be implicitly returned to the pool.
with pytest.raises(MaxRetryError):
http.request(
"GET",
"/redirect",
fields={"target": "/"},
release_conn=False,
retries=0,
)
r = http.request(
"GET",
"/redirect",
fields={"target": "/"},
release_conn=False,
retries=1,
)
r.release_conn()
# the pool should still contain poolsize elements
assert http.pool.qsize() == http.pool.maxsize
def test_shutdown_on_connection_released_to_pool(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
resp = pool.urlopen("GET", "/", preload_content=False)
resp.drain_conn()
resp.release_conn()
with pytest.raises(
RuntimeError,
match="Cannot shutdown as connection has already been released to the pool",
):
resp.shutdown()
def test_mixed_case_hostname(self) -> None:
with HTTPConnectionPool("LoCaLhOsT", self.port) as pool:
response = pool.request("GET", f"http://LoCaLhOsT:{self.port}/")
assert response.status == 200
def test_preserves_path_dot_segments(self) -> None:
"""ConnectionPool preserves dot segments in the URI"""
with HTTPConnectionPool(self.host, self.port) as pool:
response = pool.request("GET", "/echo_uri/seg0/../seg2")
assert response.data == b"/echo_uri/seg0/../seg2?"
def test_default_user_agent_header(self) -> None:
"""ConnectionPool has a default user agent"""
default_ua = _get_default_user_agent()
custom_ua = "I'm not a web scraper, what are you talking about?"
custom_ua2 = "Yet Another User Agent"
with HTTPConnectionPool(self.host, self.port) as pool:
# Use default user agent if no user agent was specified.
r = pool.request("GET", "/headers")
request_headers = r.json()
assert request_headers.get("User-Agent") == _get_default_user_agent()
# Prefer the request user agent over the default.
headers = {"UsEr-AGENt": custom_ua}
r = pool.request("GET", "/headers", headers=headers)
request_headers = r.json()
assert request_headers.get("User-Agent") == custom_ua
# Do not modify pool headers when using the default user agent.
pool_headers = {"foo": "bar"}
pool.headers = pool_headers
r = pool.request("GET", "/headers")
request_headers = r.json()
assert request_headers.get("User-Agent") == default_ua
assert "User-Agent" not in pool_headers
pool.headers.update({"User-Agent": custom_ua2})
r = pool.request("GET", "/headers")
request_headers = r.json()
assert request_headers.get("User-Agent") == custom_ua2
@pytest.mark.parametrize(
"headers",
[
None,
{},
{"User-Agent": "key"},
{"user-agent": "key"},
{b"uSeR-AgEnT": b"key"},
{b"user-agent": "key"},
],
)
@pytest.mark.parametrize("chunked", [True, False])
def test_user_agent_header_not_sent_twice(
self, headers: dict[str, str] | None, chunked: bool
) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/headers", headers=headers, chunked=chunked)
request_headers = r.json()
if not headers:
assert request_headers["User-Agent"].startswith("python-urllib3/")
assert "key" not in request_headers["User-Agent"]
else:
assert request_headers["User-Agent"] == "key"
def test_no_user_agent_header(self) -> None:
"""ConnectionPool can suppress sending a user agent header"""
custom_ua = "I'm not a web scraper, what are you talking about?"
with HTTPConnectionPool(self.host, self.port) as pool:
# Suppress user agent in the request headers.
no_ua_headers = {"User-Agent": SKIP_HEADER}
r = pool.request("GET", "/headers", headers=no_ua_headers)
request_headers = r.json()
assert "User-Agent" not in request_headers
assert no_ua_headers["User-Agent"] == SKIP_HEADER
# Suppress user agent in the pool headers.
pool.headers = no_ua_headers
r = pool.request("GET", "/headers")
request_headers = r.json()
assert "User-Agent" not in request_headers
assert no_ua_headers["User-Agent"] == SKIP_HEADER
# Request headers override pool headers.
pool_headers = {"User-Agent": custom_ua}
pool.headers = pool_headers
r = pool.request("GET", "/headers", headers=no_ua_headers)
request_headers = r.json()
assert "User-Agent" not in request_headers
assert no_ua_headers["User-Agent"] == SKIP_HEADER
assert pool_headers.get("User-Agent") == custom_ua
@pytest.mark.parametrize("header", ["Content-Length", "content-length"])
@pytest.mark.parametrize("chunked", [True, False])
def test_skip_header_non_supported(self, header: str, chunked: bool) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
with pytest.raises(
ValueError,
match="urllib3.util.SKIP_HEADER only supports 'Accept-Encoding', 'Host', 'User-Agent'",
) as e:
pool.request(
"GET", "/headers", headers={header: SKIP_HEADER}, chunked=chunked
)
# Ensure that the error message stays up to date with 'SKIP_HEADER_SUPPORTED_HEADERS'
assert all(
("'" + header.title() + "'") in str(e.value)
for header in SKIPPABLE_HEADERS
)
@pytest.mark.parametrize("chunked", [True, False])
@pytest.mark.parametrize("pool_request", [True, False])
@pytest.mark.parametrize("header_type", [dict, HTTPHeaderDict])
def test_headers_not_modified_by_request(
self,
chunked: bool,
pool_request: bool,
header_type: type[dict[str, str] | HTTPHeaderDict],
) -> None:
# Test that the .request*() methods of ConnectionPool and HTTPConnection
# don't modify the given 'headers' structure, instead they should
# make their own internal copies at request time.
headers = header_type()
headers["key"] = "val"
with HTTPConnectionPool(self.host, self.port) as pool:
pool.headers = headers
if pool_request:
pool.request("GET", "/headers", chunked=chunked)
else:
conn = pool._get_conn()
conn.request("GET", "/headers", chunked=chunked)
conn.getresponse().close()
conn.close()
assert pool.headers == {"key": "val"}
assert type(pool.headers) is header_type
with HTTPConnectionPool(self.host, self.port) as pool:
if pool_request:
pool.request("GET", "/headers", headers=headers, chunked=chunked)
else:
conn = pool._get_conn()
conn.request("GET", "/headers", headers=headers, chunked=chunked)
conn.getresponse().close()
conn.close()
assert headers == {"key": "val"}
def test_request_chunked_is_deprecated(
self,
) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
conn = pool._get_conn()
with pytest.warns(DeprecationWarning) as w:
conn.request_chunked("GET", "/headers") # type: ignore[attr-defined]
assert len(w) == 1 and str(w[0].message) == (
"HTTPConnection.request_chunked() is deprecated and will be removed in urllib3 v2.1.0. "
"Instead use HTTPConnection.request(..., chunked=True)."
)
resp = conn.getresponse()
assert resp.status == 200
assert resp.json()["Transfer-Encoding"] == "chunked"
conn.close()
def test_bytes_header(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
headers = {"User-Agent": "test header"}
r = pool.request("GET", "/headers", headers=headers)
request_headers = r.json()
assert "User-Agent" in request_headers
assert request_headers["User-Agent"] == "test header"
@pytest.mark.parametrize(
"user_agent", ["Schönefeld/1.18.0", "Schönefeld/1.18.0".encode("iso-8859-1")]
)
def test_user_agent_non_ascii_user_agent(self, user_agent: str) -> None:
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
r = pool.urlopen(
"GET",
"/headers",
headers={"User-Agent": user_agent},
)
request_headers = r.json()
assert "User-Agent" in request_headers
assert request_headers["User-Agent"] == "Schönefeld/1.18.0"
class TestRetry(HypercornDummyServerTestCase):
def test_max_retry(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
with pytest.raises(MaxRetryError):
pool.request("GET", "/redirect", fields={"target": "/"}, retries=0)
def test_disabled_retry(self) -> None:
"""Disabled retries should disable redirect handling."""
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/redirect", fields={"target": "/"}, retries=False)
assert r.status == 303
r = pool.request(
"GET",
"/redirect",
fields={"target": "/"},
retries=Retry(redirect=False),
)
assert r.status == 303
with HTTPConnectionPool(
"thishostdoesnotexist.invalid", self.port, timeout=0.001
) as pool:
with pytest.raises(NameResolutionError):
pool.request("GET", "/test", retries=False)
def test_read_retries(self) -> None:
"""Should retry for status codes in the forcelist"""
with HTTPConnectionPool(self.host, self.port) as pool:
retry = Retry(read=1, status_forcelist=[418])
resp = pool.request(
"GET",
"/successful_retry",
headers={"test-name": "test_read_retries"},
retries=retry,
)
assert resp.status == 200
def test_read_total_retries(self) -> None:
"""HTTP response w/ status code in the forcelist should be retried"""
with HTTPConnectionPool(self.host, self.port) as pool:
headers = {"test-name": "test_read_total_retries"}
retry = Retry(total=1, status_forcelist=[418])
resp = pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
assert resp.status == 200
def test_retries_wrong_forcelist(self) -> None:
"""HTTP response w/ status code not in forcelist shouldn't be retried"""
with HTTPConnectionPool(self.host, self.port) as pool:
retry = Retry(total=1, status_forcelist=[202])
resp = pool.request(
"GET",
"/successful_retry",
headers={"test-name": "test_wrong_forcelist"},
retries=retry,
)
assert resp.status == 418
def test_default_method_forcelist_retried(self) -> None:
"""urllib3 should retry methods in the default method forcelist"""
with HTTPConnectionPool(self.host, self.port) as pool:
retry = Retry(total=1, status_forcelist=[418])
resp = pool.request(
"OPTIONS",
"/successful_retry",
headers={"test-name": "test_default_forcelist"},
retries=retry,
)
assert resp.status == 200
def test_retries_wrong_method_list(self) -> None:
"""Method not in our allowed list should not be retried, even if code matches"""
with HTTPConnectionPool(self.host, self.port) as pool:
headers = {"test-name": "test_wrong_allowed_method"}
retry = Retry(total=1, status_forcelist=[418], allowed_methods=["POST"])
resp = pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
assert resp.status == 418
def test_read_retries_unsuccessful(
self,
) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
headers = {"test-name": "test_read_retries_unsuccessful"}
resp = pool.request("GET", "/successful_retry", headers=headers, retries=1)
assert resp.status == 418
def test_retry_reuse_safe(self) -> None:
"""It should be possible to reuse a Retry object across requests"""
with HTTPConnectionPool(self.host, self.port) as pool:
headers = {"test-name": "test_retry_safe"}
retry = Retry(total=1, status_forcelist=[418])
resp = pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
assert resp.status == 200
with HTTPConnectionPool(self.host, self.port) as pool:
resp = pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
assert resp.status == 200
def test_retry_return_in_response(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
headers = {"test-name": "test_retry_return_in_response"}
retry = Retry(total=2, status_forcelist=[418])
resp = pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
assert resp.status == 200
assert resp.retries is not None
assert resp.retries.total == 1
assert resp.retries.history == (
RequestHistory("GET", "/successful_retry", None, 418, None),
)
def test_retry_redirect_history(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
resp = pool.request("GET", "/redirect", fields={"target": "/"})
assert resp.status == 200
assert resp.retries is not None
assert resp.retries.history == (
RequestHistory("GET", "/redirect?target=%2F", None, 303, "/"),
)
def test_multi_redirect_history(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request(
"GET",
"/multi_redirect",
fields={"redirect_codes": "303,302,200"},
redirect=False,
)
assert r.status == 303
assert r.retries is not None
assert r.retries.history == tuple()
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request(
"GET",
"/multi_redirect",
retries=10,
fields={"redirect_codes": "303,302,301,307,302,200"},
)
assert r.status == 200
assert r.data == b"Done redirecting"
expected = [
(303, "/multi_redirect?redirect_codes=302,301,307,302,200"),
(302, "/multi_redirect?redirect_codes=301,307,302,200"),
(301, "/multi_redirect?redirect_codes=307,302,200"),
(307, "/multi_redirect?redirect_codes=302,200"),
(302, "/multi_redirect?redirect_codes=200"),
]
assert r.retries is not None
actual = [
(history.status, history.redirect_location)
for history in r.retries.history
]
assert actual == expected
class TestRetryAfter(HypercornDummyServerTestCase):
def test_retry_after(self) -> None:
# Request twice in a second to get a 429 response.
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request(
"GET",
"/retry_after",
fields={"status": "429 Too Many Requests"},
retries=False,
)
r = pool.request(
"GET",
"/retry_after",
fields={"status": "429 Too Many Requests"},
retries=False,
)
assert r.status == 429
r = pool.request(
"GET",
"/retry_after",
fields={"status": "429 Too Many Requests"},
retries=True,
)
assert r.status == 200
# Request twice in a second to get a 503 response.
r = pool.request(
"GET",
"/retry_after",
fields={"status": "503 Service Unavailable"},
retries=False,
)
r = pool.request(
"GET",
"/retry_after",
fields={"status": "503 Service Unavailable"},
retries=False,
)
assert r.status == 503
r = pool.request(
"GET",
"/retry_after",
fields={"status": "503 Service Unavailable"},
retries=True,
)
assert r.status == 200
# Ignore Retry-After header on status which is not defined in
# Retry.RETRY_AFTER_STATUS_CODES.
r = pool.request(
"GET",
"/retry_after",
fields={"status": "418 I'm a teapot"},
retries=True,
)
assert r.status == 418
def test_redirect_after(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/redirect_after", retries=False)
assert r.status == 303
# Real timestamps are needed for this test
t = time.time()
r = pool.request("GET", "/redirect_after")
assert r.status == 200
delta = time.time() - t
assert delta >= 1
t = time.time()
timestamp = t + 2
r = pool.request("GET", "/redirect_after?date=" + str(timestamp))
assert r.status == 200
delta = time.time() - t
assert delta >= 1
# Retry-After is past
t = time.time()
timestamp = t - 1
r = pool.request("GET", "/redirect_after?date=" + str(timestamp))
delta = time.time() - t
assert r.status == 200
assert delta < 1
class TestFileBodiesOnRetryOrRedirect(HypercornDummyServerTestCase):
def test_retries_put_filehandle(self) -> None:
"""HTTP PUT retry with a file-like object should not timeout"""
with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool:
retry = Retry(total=3, status_forcelist=[418])
# httplib reads in 8k chunks; use a larger content length
content_length = 65535
data = b"A" * content_length
uploaded_file = io.BytesIO(data)
headers = {
"test-name": "test_retries_put_filehandle",
"Content-Length": str(content_length),
}
resp = pool.urlopen(
"PUT",
"/successful_retry",
headers=headers,
retries=retry,
body=uploaded_file,
assert_same_host=False,
redirect=False,
)
assert resp.status == 200
def test_redirect_put_file(self) -> None:
"""PUT with file object should work with a redirection response"""
with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool:
retry = Retry(total=3, status_forcelist=[418])
# httplib reads in 8k chunks; use a larger content length
content_length = 65535
data = b"A" * content_length
uploaded_file = io.BytesIO(data)
headers = {
"test-name": "test_redirect_put_file",
"Content-Length": str(content_length),
}
url = "/redirect?target=/echo&status=307"
resp = pool.urlopen(
"PUT",
url,
headers=headers,
retries=retry,
body=uploaded_file,
assert_same_host=False,
redirect=True,
)
assert resp.status == 200
assert resp.data == data
def test_redirect_with_failed_tell(self) -> None:
"""Abort request if failed to get a position from tell()"""
class BadTellObject(io.BytesIO):
def tell(self) -> typing.NoReturn:
raise OSError
body = BadTellObject(b"the data")
url = "/redirect?target=/successful_retry"
# httplib uses fileno if Content-Length isn't supplied,
# which is unsupported by BytesIO.
headers = {"Content-Length": "8"}
with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool:
with pytest.raises(
UnrewindableBodyError, match="Unable to record file position for"
):
pool.urlopen("PUT", url, headers=headers, body=body)
class TestRetryPoolSize(HypercornDummyServerTestCase):
def test_pool_size_retry(self) -> None:
retries = Retry(total=1, raise_on_status=False, status_forcelist=[404])
with HTTPConnectionPool(
self.host, self.port, maxsize=10, retries=retries, block=True
) as pool:
pool.urlopen("GET", "/not_found", preload_content=False)
assert pool.num_connections == 1
class TestRedirectPoolSize(HypercornDummyServerTestCase):
def test_pool_size_redirect(self) -> None:
retries = Retry(
total=1, raise_on_status=False, status_forcelist=[404], redirect=True
)
with HTTPConnectionPool(
self.host, self.port, maxsize=10, retries=retries, block=True
) as pool:
pool.urlopen("GET", "/redirect", preload_content=False)
assert pool.num_connections == 1
|