| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import io |
| 4 |
import logging |
| 5 |
import platform |
| 6 |
import socket |
| 7 |
import time |
| 8 |
import typing |
| 9 |
import warnings |
| 10 |
from test import LONG_TIMEOUT, SHORT_TIMEOUT |
| 11 |
from threading import Event |
| 12 |
from unittest import mock |
| 13 |
from urllib.parse import urlencode |
| 14 |
|
| 15 |
import pytest |
| 16 |
|
| 17 |
from dummyserver.socketserver import NoIPv6Warning |
| 18 |
from dummyserver.testcase import HypercornDummyServerTestCase, SocketDummyServerTestCase |
| 19 |
from urllib3 import HTTPConnectionPool, encode_multipart_formdata |
| 20 |
from urllib3._collections import HTTPHeaderDict |
| 21 |
from urllib3.connection import _get_default_user_agent |
| 22 |
from urllib3.exceptions import ( |
| 23 |
ConnectTimeoutError, |
| 24 |
DecodeError, |
| 25 |
EmptyPoolError, |
| 26 |
MaxRetryError, |
| 27 |
NameResolutionError, |
| 28 |
NewConnectionError, |
| 29 |
ReadTimeoutError, |
| 30 |
UnrewindableBodyError, |
| 31 |
) |
| 32 |
from urllib3.fields import _TYPE_FIELD_VALUE_TUPLE |
| 33 |
from urllib3.util import SKIP_HEADER, SKIPPABLE_HEADERS |
| 34 |
from urllib3.util.retry import RequestHistory, Retry |
| 35 |
from urllib3.util.timeout import _TYPE_TIMEOUT, Timeout |
| 36 |
|
| 37 |
from .. import INVALID_SOURCE_ADDRESSES, TARPIT_HOST, VALID_SOURCE_ADDRESSES |
| 38 |
from ..port_helpers import find_unused_port |
| 39 |
|
| 40 |
|
| 41 |
def wait_for_socket(ready_event: Event) -> None: |
| 42 |
ready_event.wait() |
| 43 |
ready_event.clear() |
| 44 |
|
| 45 |
|
| 46 |
class TestConnectionPoolTimeouts(SocketDummyServerTestCase): |
| 47 |
def test_timeout_float(self) -> None: |
| 48 |
block_event = Event() |
| 49 |
ready_event = self.start_basic_handler(block_send=block_event, num=2) |
| 50 |
|
| 51 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 52 |
wait_for_socket(ready_event) |
| 53 |
with pytest.raises(ReadTimeoutError): |
| 54 |
pool.request("GET", "/", timeout=SHORT_TIMEOUT) |
| 55 |
block_event.set() # Release block |
| 56 |
|
| 57 |
# Shouldn't raise this time |
| 58 |
wait_for_socket(ready_event) |
| 59 |
block_event.set() # Pre-release block |
| 60 |
pool.request("GET", "/", timeout=LONG_TIMEOUT) |
| 61 |
|
| 62 |
def test_conn_closed(self) -> None: |
| 63 |
block_event = Event() |
| 64 |
self.start_basic_handler(block_send=block_event, num=1) |
| 65 |
|
| 66 |
with HTTPConnectionPool( |
| 67 |
self.host, self.port, timeout=SHORT_TIMEOUT, retries=False |
| 68 |
) as pool: |
| 69 |
conn = pool._get_conn() |
| 70 |
pool._put_conn(conn) |
| 71 |
try: |
| 72 |
with pytest.raises(ReadTimeoutError): |
| 73 |
pool.urlopen("GET", "/") |
| 74 |
if not conn.is_closed: |
| 75 |
with pytest.raises(socket.error): |
| 76 |
conn.sock.recv(1024) # type: ignore[attr-defined] |
| 77 |
finally: |
| 78 |
pool._put_conn(conn) |
| 79 |
|
| 80 |
block_event.set() |
| 81 |
|
| 82 |
def test_timeout(self) -> None: |
| 83 |
# Requests should time out when expected |
| 84 |
block_event = Event() |
| 85 |
ready_event = self.start_basic_handler(block_send=block_event, num=3) |
| 86 |
|
| 87 |
# Pool-global timeout |
| 88 |
short_timeout = Timeout(read=SHORT_TIMEOUT) |
| 89 |
with HTTPConnectionPool( |
| 90 |
self.host, self.port, timeout=short_timeout, retries=False |
| 91 |
) as pool: |
| 92 |
wait_for_socket(ready_event) |
| 93 |
block_event.clear() |
| 94 |
with pytest.raises(ReadTimeoutError): |
| 95 |
pool.request("GET", "/") |
| 96 |
block_event.set() # Release request |
| 97 |
|
| 98 |
# Request-specific timeouts should raise errors |
| 99 |
with HTTPConnectionPool( |
| 100 |
self.host, self.port, timeout=short_timeout, retries=False |
| 101 |
) as pool: |
| 102 |
wait_for_socket(ready_event) |
| 103 |
now = time.perf_counter() |
| 104 |
with pytest.raises(ReadTimeoutError): |
| 105 |
pool.request("GET", "/", timeout=LONG_TIMEOUT) |
| 106 |
delta = time.perf_counter() - now |
| 107 |
|
| 108 |
message = "timeout was pool-level SHORT_TIMEOUT rather than request-level LONG_TIMEOUT" |
| 109 |
if platform.system() == "Windows": |
| 110 |
# Adjust tolerance for floating-point comparison on Windows to |
| 111 |
# avoid flakiness in CI #3413 |
| 112 |
assert delta >= (LONG_TIMEOUT - 1e-3), message |
| 113 |
else: |
| 114 |
assert delta >= (LONG_TIMEOUT - 1e-5), message |
| 115 |
block_event.set() # Release request |
| 116 |
|
| 117 |
# Timeout passed directly to request should raise a request timeout |
| 118 |
wait_for_socket(ready_event) |
| 119 |
with pytest.raises(ReadTimeoutError): |
| 120 |
pool.request("GET", "/", timeout=SHORT_TIMEOUT) |
| 121 |
block_event.set() # Release request |
| 122 |
|
| 123 |
def test_connect_timeout(self) -> None: |
| 124 |
url = "/" |
| 125 |
host, port = TARPIT_HOST, 80 |
| 126 |
timeout = Timeout(connect=SHORT_TIMEOUT) |
| 127 |
|
| 128 |
# Pool-global timeout |
| 129 |
with HTTPConnectionPool(host, port, timeout=timeout) as pool: |
| 130 |
conn = pool._get_conn() |
| 131 |
with pytest.raises(ConnectTimeoutError): |
| 132 |
pool._make_request(conn, "GET", url) |
| 133 |
|
| 134 |
# Retries |
| 135 |
retries = Retry(connect=0) |
| 136 |
with pytest.raises(MaxRetryError): |
| 137 |
pool.request("GET", url, retries=retries) |
| 138 |
|
| 139 |
# Request-specific connection timeouts |
| 140 |
big_timeout = Timeout(read=LONG_TIMEOUT, connect=LONG_TIMEOUT) |
| 141 |
with HTTPConnectionPool(host, port, timeout=big_timeout, retries=False) as pool: |
| 142 |
conn = pool._get_conn() |
| 143 |
with pytest.raises(ConnectTimeoutError): |
| 144 |
pool._make_request(conn, "GET", url, timeout=timeout) |
| 145 |
|
| 146 |
pool._put_conn(conn) |
| 147 |
with pytest.raises(ConnectTimeoutError): |
| 148 |
pool.request("GET", url, timeout=timeout) |
| 149 |
|
| 150 |
def test_total_applies_connect(self) -> None: |
| 151 |
host, port = TARPIT_HOST, 80 |
| 152 |
|
| 153 |
timeout = Timeout(total=None, connect=SHORT_TIMEOUT) |
| 154 |
with HTTPConnectionPool(host, port, timeout=timeout) as pool: |
| 155 |
conn = pool._get_conn() |
| 156 |
try: |
| 157 |
with pytest.raises(ConnectTimeoutError): |
| 158 |
pool._make_request(conn, "GET", "/") |
| 159 |
finally: |
| 160 |
conn.close() |
| 161 |
|
| 162 |
timeout = Timeout(connect=3, read=5, total=SHORT_TIMEOUT) |
| 163 |
with HTTPConnectionPool(host, port, timeout=timeout) as pool: |
| 164 |
conn = pool._get_conn() |
| 165 |
try: |
| 166 |
with pytest.raises(ConnectTimeoutError): |
| 167 |
pool._make_request(conn, "GET", "/") |
| 168 |
finally: |
| 169 |
conn.close() |
| 170 |
|
| 171 |
def test_total_timeout(self) -> None: |
| 172 |
block_event = Event() |
| 173 |
ready_event = self.start_basic_handler(block_send=block_event, num=2) |
| 174 |
|
| 175 |
wait_for_socket(ready_event) |
| 176 |
# This will get the socket to raise an EAGAIN on the read |
| 177 |
timeout = Timeout(connect=3, read=SHORT_TIMEOUT) |
| 178 |
with HTTPConnectionPool( |
| 179 |
self.host, self.port, timeout=timeout, retries=False |
| 180 |
) as pool: |
| 181 |
with pytest.raises(ReadTimeoutError): |
| 182 |
pool.request("GET", "/") |
| 183 |
|
| 184 |
block_event.set() |
| 185 |
wait_for_socket(ready_event) |
| 186 |
block_event.clear() |
| 187 |
|
| 188 |
# The connect should succeed and this should hit the read timeout |
| 189 |
timeout = Timeout(connect=3, read=5, total=SHORT_TIMEOUT) |
| 190 |
with HTTPConnectionPool( |
| 191 |
self.host, self.port, timeout=timeout, retries=False |
| 192 |
) as pool: |
| 193 |
with pytest.raises(ReadTimeoutError): |
| 194 |
pool.request("GET", "/") |
| 195 |
|
| 196 |
def test_create_connection_timeout(self) -> None: |
| 197 |
self.start_basic_handler(block_send=Event(), num=0) # needed for self.port |
| 198 |
|
| 199 |
timeout = Timeout(connect=SHORT_TIMEOUT, total=LONG_TIMEOUT) |
| 200 |
with HTTPConnectionPool( |
| 201 |
TARPIT_HOST, self.port, timeout=timeout, retries=False |
| 202 |
) as pool: |
| 203 |
conn = pool._new_conn() |
| 204 |
with pytest.raises(ConnectTimeoutError): |
| 205 |
conn.connect() |
| 206 |
|
| 207 |
|
| 208 |
class TestConnectionPool(HypercornDummyServerTestCase): |
| 209 |
def test_http2_test_error(self, http_version: str) -> None: |
| 210 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 211 |
if http_version == "h2": |
| 212 |
with pytest.raises( |
| 213 |
ValueError, match="HTTP/2 support currently only applies to HTTPS.*" |
| 214 |
): |
| 215 |
r = pool.request("GET", "/") |
| 216 |
else: |
| 217 |
r = pool.request("GET", "/") |
| 218 |
assert r.status == 200 |
| 219 |
|
| 220 |
def test_get(self) -> None: |
| 221 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 222 |
r = pool.request("GET", "/specific_method", fields={"method": "GET"}) |
| 223 |
assert r.status == 200, r.data |
| 224 |
|
| 225 |
def test_debug_log(self, caplog: pytest.LogCaptureFixture) -> None: |
| 226 |
caplog.set_level(logging.DEBUG, logger="urllib3.connectionpool") |
| 227 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 228 |
r = pool.urlopen("GET", "/") |
| 229 |
assert r.status == 200 |
| 230 |
logs = [record.getMessage() for record in caplog.records] |
| 231 |
assert logs == [ |
| 232 |
f"Starting new HTTP connection (1): {self.host}:{self.port}", |
| 233 |
f'http://{self.host}:{self.port} "GET / HTTP/1.1" 200 0', |
| 234 |
] |
| 235 |
|
| 236 |
def test_post_url(self) -> None: |
| 237 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 238 |
r = pool.request("POST", "/specific_method", fields={"method": "POST"}) |
| 239 |
assert r.status == 200, r.data |
| 240 |
|
| 241 |
def test_urlopen_put(self) -> None: |
| 242 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 243 |
r = pool.urlopen("PUT", "/specific_method?method=PUT") |
| 244 |
assert r.status == 200, r.data |
| 245 |
|
| 246 |
def test_wrong_specific_method(self) -> None: |
| 247 |
# To make sure the dummy server is actually returning failed responses |
| 248 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 249 |
r = pool.request("GET", "/specific_method", fields={"method": "POST"}) |
| 250 |
assert r.status == 400, r.data |
| 251 |
|
| 252 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 253 |
r = pool.request("POST", "/specific_method", fields={"method": "GET"}) |
| 254 |
assert r.status == 400, r.data |
| 255 |
|
| 256 |
def test_upload(self) -> None: |
| 257 |
data = "I'm in ur multipart form-data, hazing a cheezburgr" |
| 258 |
fields: dict[str, _TYPE_FIELD_VALUE_TUPLE] = { |
| 259 |
"upload_param": "filefield", |
| 260 |
"upload_filename": "lolcat.txt", |
| 261 |
"filefield": ("lolcat.txt", data), |
| 262 |
} |
| 263 |
fields["upload_size"] = len(data) # type: ignore[assignment] |
| 264 |
|
| 265 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 266 |
r = pool.request("POST", "/upload", fields=fields) |
| 267 |
assert r.status == 200, r.data |
| 268 |
|
| 269 |
def test_one_name_multiple_values(self) -> None: |
| 270 |
fields = [("foo", "a"), ("foo", "b")] |
| 271 |
|
| 272 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 273 |
# urlencode |
| 274 |
r = pool.request("GET", "/echo", fields=fields) |
| 275 |
assert r.data == b"foo=a&foo=b" |
| 276 |
|
| 277 |
# multipart |
| 278 |
r = pool.request("POST", "/echo", fields=fields) |
| 279 |
assert r.data.count(b'name="foo"') == 2 |
| 280 |
|
| 281 |
def test_request_method_body(self) -> None: |
| 282 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 283 |
body = b"hi" |
| 284 |
r = pool.request("POST", "/echo", body=body) |
| 285 |
assert r.data == body |
| 286 |
|
| 287 |
fields = [("hi", "hello")] |
| 288 |
with pytest.raises(TypeError): |
| 289 |
pool.request("POST", "/echo", body=body, fields=fields) |
| 290 |
|
| 291 |
def test_unicode_upload(self) -> None: |
| 292 |
fieldname = "myfile" |
| 293 |
filename = "\xe2\x99\xa5.txt" |
| 294 |
data = "\xe2\x99\xa5".encode() |
| 295 |
size = len(data) |
| 296 |
|
| 297 |
fields: dict[str, _TYPE_FIELD_VALUE_TUPLE] = { |
| 298 |
"upload_param": fieldname, |
| 299 |
"upload_filename": filename, |
| 300 |
fieldname: (filename, data), |
| 301 |
} |
| 302 |
fields["upload_size"] = size # type: ignore[assignment] |
| 303 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 304 |
r = pool.request("POST", "/upload", fields=fields) |
| 305 |
assert r.status == 200, r.data |
| 306 |
|
| 307 |
def test_nagle(self) -> None: |
| 308 |
"""Test that connections have TCP_NODELAY turned on""" |
| 309 |
# This test needs to be here in order to be run. socket.create_connection actually tries |
| 310 |
# to connect to the host provided so we need a dummyserver to be running. |
| 311 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 312 |
conn = pool._get_conn() |
| 313 |
try: |
| 314 |
pool._make_request(conn, "GET", "/") |
| 315 |
tcp_nodelay_setting = conn.sock.getsockopt( # type: ignore[attr-defined] |
| 316 |
socket.IPPROTO_TCP, socket.TCP_NODELAY |
| 317 |
) |
| 318 |
assert tcp_nodelay_setting |
| 319 |
finally: |
| 320 |
conn.close() |
| 321 |
|
| 322 |
@pytest.mark.parametrize( |
| 323 |
"socket_options", |
| 324 |
[ |
| 325 |
[(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)], |
| 326 |
((socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),), |
| 327 |
], |
| 328 |
) |
| 329 |
def test_socket_options(self, socket_options: tuple[int, int, int]) -> None: |
| 330 |
"""Test that connections accept socket options.""" |
| 331 |
# This test needs to be here in order to be run. socket.create_connection actually tries to |
| 332 |
# connect to the host provided so we need a dummyserver to be running. |
| 333 |
with HTTPConnectionPool( |
| 334 |
self.host, |
| 335 |
self.port, |
| 336 |
socket_options=socket_options, |
| 337 |
) as pool: |
| 338 |
# Get the socket of a new connection. |
| 339 |
s = pool._new_conn()._new_conn() # type: ignore[attr-defined] |
| 340 |
try: |
| 341 |
using_keepalive = ( |
| 342 |
s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0 |
| 343 |
) |
| 344 |
assert using_keepalive |
| 345 |
finally: |
| 346 |
s.close() |
| 347 |
|
| 348 |
@pytest.mark.parametrize("socket_options", [None, []]) |
| 349 |
def test_disable_default_socket_options( |
| 350 |
self, socket_options: list[int] | None |
| 351 |
) -> None: |
| 352 |
"""Test that passing None or empty list disables all socket options.""" |
| 353 |
# This test needs to be here in order to be run. socket.create_connection actually tries |
| 354 |
# to connect to the host provided so we need a dummyserver to be running. |
| 355 |
with HTTPConnectionPool( |
| 356 |
self.host, self.port, socket_options=socket_options |
| 357 |
) as pool: |
| 358 |
s = pool._new_conn()._new_conn() # type: ignore[attr-defined] |
| 359 |
try: |
| 360 |
using_nagle = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) == 0 |
| 361 |
assert using_nagle |
| 362 |
finally: |
| 363 |
s.close() |
| 364 |
|
| 365 |
def test_defaults_are_applied(self) -> None: |
| 366 |
"""Test that modifying the default socket options works.""" |
| 367 |
# This test needs to be here in order to be run. socket.create_connection actually tries |
| 368 |
# to connect to the host provided so we need a dummyserver to be running. |
| 369 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 370 |
# Get the HTTPConnection instance |
| 371 |
conn = pool._new_conn() |
| 372 |
try: |
| 373 |
# Update the default socket options |
| 374 |
assert conn.socket_options is not None |
| 375 |
conn.socket_options += [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] |
| 376 |
s = conn._new_conn() # type: ignore[attr-defined] |
| 377 |
nagle_disabled = ( |
| 378 |
s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) > 0 |
| 379 |
) |
| 380 |
using_keepalive = ( |
| 381 |
s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0 |
| 382 |
) |
| 383 |
assert nagle_disabled |
| 384 |
assert using_keepalive |
| 385 |
finally: |
| 386 |
conn.close() |
| 387 |
s.close() |
| 388 |
|
| 389 |
def test_connection_error_retries(self) -> None: |
| 390 |
"""ECONNREFUSED error should raise a connection error, with retries""" |
| 391 |
port = find_unused_port() |
| 392 |
with HTTPConnectionPool(self.host, port) as pool: |
| 393 |
with pytest.raises(MaxRetryError) as e: |
| 394 |
pool.request("GET", "/", retries=Retry(connect=3)) |
| 395 |
assert type(e.value.reason) is NewConnectionError |
| 396 |
|
| 397 |
def test_timeout_success(self) -> None: |
| 398 |
timeout = Timeout(connect=3, read=5, total=None) |
| 399 |
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: |
| 400 |
pool.request("GET", "/") |
| 401 |
# This should not raise a "Timeout already started" error |
| 402 |
pool.request("GET", "/") |
| 403 |
|
| 404 |
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: |
| 405 |
# This should also not raise a "Timeout already started" error |
| 406 |
pool.request("GET", "/") |
| 407 |
|
| 408 |
timeout = Timeout(total=None) |
| 409 |
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: |
| 410 |
pool.request("GET", "/") |
| 411 |
|
| 412 |
socket_timeout_reuse_testdata = pytest.mark.parametrize( |
| 413 |
["timeout", "expect_settimeout_calls"], |
| 414 |
[ |
| 415 |
(1, (1, 1)), |
| 416 |
(None, (None, None)), |
| 417 |
(Timeout(read=4), (None, 4)), |
| 418 |
(Timeout(read=4, connect=5), (5, 4)), |
| 419 |
(Timeout(connect=6), (6, None)), |
| 420 |
], |
| 421 |
) |
| 422 |
|
| 423 |
@socket_timeout_reuse_testdata |
| 424 |
def test_socket_timeout_updated_on_reuse_constructor( |
| 425 |
self, |
| 426 |
timeout: _TYPE_TIMEOUT, |
| 427 |
expect_settimeout_calls: typing.Sequence[float | None], |
| 428 |
) -> None: |
| 429 |
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: |
| 430 |
# Make a request to create a new connection. |
| 431 |
pool.urlopen("GET", "/") |
| 432 |
|
| 433 |
# Grab the connection and mock the inner socket. |
| 434 |
assert pool.pool is not None |
| 435 |
conn = pool.pool.get_nowait() |
| 436 |
conn_sock = mock.Mock(wraps=conn.sock) |
| 437 |
conn.sock = conn_sock |
| 438 |
pool._put_conn(conn) |
| 439 |
|
| 440 |
# Assert that sock.settimeout() is called with the new connect timeout, then the read timeout. |
| 441 |
pool.urlopen("GET", "/", timeout=timeout) |
| 442 |
conn_sock.settimeout.assert_has_calls( |
| 443 |
[mock.call(x) for x in expect_settimeout_calls] |
| 444 |
) |
| 445 |
|
| 446 |
@socket_timeout_reuse_testdata |
| 447 |
def test_socket_timeout_updated_on_reuse_parameter( |
| 448 |
self, |
| 449 |
timeout: _TYPE_TIMEOUT, |
| 450 |
expect_settimeout_calls: typing.Sequence[float | None], |
| 451 |
) -> None: |
| 452 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 453 |
# Make a request to create a new connection. |
| 454 |
pool.urlopen("GET", "/", timeout=LONG_TIMEOUT) |
| 455 |
|
| 456 |
# Grab the connection and mock the inner socket. |
| 457 |
assert pool.pool is not None |
| 458 |
conn = pool.pool.get_nowait() |
| 459 |
conn_sock = mock.Mock(wraps=conn.sock) |
| 460 |
conn.sock = conn_sock |
| 461 |
pool._put_conn(conn) |
| 462 |
|
| 463 |
# Assert that sock.settimeout() is called with the new connect timeout, then the read timeout. |
| 464 |
pool.urlopen("GET", "/", timeout=timeout) |
| 465 |
conn_sock.settimeout.assert_has_calls( |
| 466 |
[mock.call(x) for x in expect_settimeout_calls] |
| 467 |
) |
| 468 |
|
| 469 |
def test_tunnel(self) -> None: |
| 470 |
timeout = Timeout(total=None) |
| 471 |
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: |
| 472 |
conn = pool._get_conn() |
| 473 |
try: |
| 474 |
conn.set_tunnel(self.host, self.port) |
| 475 |
with mock.patch.object( |
| 476 |
conn, "_tunnel", create=True, return_value=None |
| 477 |
) as conn_tunnel: |
| 478 |
pool._make_request(conn, "GET", "/") |
| 479 |
conn_tunnel.assert_called_once_with() |
| 480 |
finally: |
| 481 |
conn.close() |
| 482 |
|
| 483 |
# test that it's not called when tunnel is not set |
| 484 |
timeout = Timeout(total=None) |
| 485 |
with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: |
| 486 |
conn = pool._get_conn() |
| 487 |
try: |
| 488 |
with mock.patch.object( |
| 489 |
conn, "_tunnel", create=True, return_value=None |
| 490 |
) as conn_tunnel: |
| 491 |
pool._make_request(conn, "GET", "/") |
| 492 |
assert not conn_tunnel.called |
| 493 |
finally: |
| 494 |
conn.close() |
| 495 |
|
| 496 |
def test_redirect_relative_url_no_deprecation(self) -> None: |
| 497 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 498 |
with warnings.catch_warnings(): |
| 499 |
warnings.simplefilter("error", FutureWarning) |
| 500 |
pool.request("GET", "/redirect", fields={"target": "/"}) |
| 501 |
|
| 502 |
def test_redirect(self) -> None: |
| 503 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 504 |
r = pool.request("GET", "/redirect", fields={"target": "/"}, redirect=False) |
| 505 |
assert r.status == 303 |
| 506 |
|
| 507 |
r = pool.request("GET", "/redirect", fields={"target": "/"}) |
| 508 |
assert r.status == 200 |
| 509 |
assert r.data == b"Dummy server!" |
| 510 |
|
| 511 |
@mock.patch("urllib3.response.GzipDecoder.decompress") |
| 512 |
def test_no_decoding_with_redirect_when_preload_disabled( |
| 513 |
self, gzip_decompress: mock.MagicMock |
| 514 |
) -> None: |
| 515 |
""" |
| 516 |
Test that urllib3 does not attempt to decode a gzipped redirect |
| 517 |
response when `preload_content` is set to `False`. |
| 518 |
""" |
| 519 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 520 |
# Three requests are expected: two redirects and one final / 200 OK. |
| 521 |
response = pool.request( |
| 522 |
"GET", |
| 523 |
"/redirect", |
| 524 |
fields={"target": "/redirect?compressed=true", "compressed": "true"}, |
| 525 |
preload_content=False, |
| 526 |
) |
| 527 |
assert response.status == 200 |
| 528 |
gzip_decompress.assert_not_called() |
| 529 |
|
| 530 |
def test_303_redirect_makes_request_lose_body(self) -> None: |
| 531 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 532 |
response = pool.request( |
| 533 |
"POST", |
| 534 |
"/redirect", |
| 535 |
fields={"target": "/headers_and_params", "status": "303 See Other"}, |
| 536 |
) |
| 537 |
data = response.json() |
| 538 |
assert data["params"] == {} |
| 539 |
assert "Content-Type" not in HTTPHeaderDict(data["headers"]) |
| 540 |
|
| 541 |
def test_bad_connect(self) -> None: |
| 542 |
with HTTPConnectionPool("badhost.invalid", self.port) as pool: |
| 543 |
with pytest.raises(MaxRetryError) as e: |
| 544 |
pool.request("GET", "/", retries=5) |
| 545 |
assert type(e.value.reason) is NameResolutionError |
| 546 |
|
| 547 |
def test_keepalive(self) -> None: |
| 548 |
with HTTPConnectionPool(self.host, self.port, block=True, maxsize=1) as pool: |
| 549 |
r = pool.request("GET", "/keepalive?close=0") |
| 550 |
r = pool.request("GET", "/keepalive?close=0") |
| 551 |
|
| 552 |
assert r.status == 200 |
| 553 |
assert pool.num_connections == 1 |
| 554 |
assert pool.num_requests == 2 |
| 555 |
|
| 556 |
def test_keepalive_close(self) -> None: |
| 557 |
with HTTPConnectionPool( |
| 558 |
self.host, self.port, block=True, maxsize=1, timeout=2 |
| 559 |
) as pool: |
| 560 |
r = pool.request( |
| 561 |
"GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"} |
| 562 |
) |
| 563 |
|
| 564 |
assert pool.num_connections == 1 |
| 565 |
|
| 566 |
# The dummyserver will have responded with Connection:close, |
| 567 |
# and httplib will properly cleanup the socket. |
| 568 |
|
| 569 |
# We grab the HTTPConnection object straight from the Queue, |
| 570 |
# because _get_conn() is where the check & reset occurs |
| 571 |
assert pool.pool is not None |
| 572 |
conn = pool.pool.get() |
| 573 |
assert conn.sock is None |
| 574 |
pool._put_conn(conn) |
| 575 |
|
| 576 |
# Now with keep-alive |
| 577 |
r = pool.request( |
| 578 |
"GET", |
| 579 |
"/keepalive?close=0", |
| 580 |
retries=0, |
| 581 |
headers={"Connection": "keep-alive"}, |
| 582 |
) |
| 583 |
|
| 584 |
# The dummyserver responded with Connection:keep-alive, the connection |
| 585 |
# persists. |
| 586 |
conn = pool.pool.get() |
| 587 |
assert conn.sock is not None |
| 588 |
pool._put_conn(conn) |
| 589 |
|
| 590 |
# Another request asking the server to close the connection. This one |
| 591 |
# should get cleaned up for the next request. |
| 592 |
r = pool.request( |
| 593 |
"GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"} |
| 594 |
) |
| 595 |
|
| 596 |
assert r.status == 200 |
| 597 |
|
| 598 |
conn = pool.pool.get() |
| 599 |
assert conn.sock is None |
| 600 |
pool._put_conn(conn) |
| 601 |
|
| 602 |
# Next request |
| 603 |
r = pool.request("GET", "/keepalive?close=0") |
| 604 |
|
| 605 |
def test_post_with_urlencode(self) -> None: |
| 606 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 607 |
data = {"banana": "hammock", "lol": "cat"} |
| 608 |
r = pool.request("POST", "/echo", fields=data, encode_multipart=False) |
| 609 |
assert r.data.decode("utf-8") == urlencode(data) |
| 610 |
|
| 611 |
def test_post_with_multipart(self) -> None: |
| 612 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 613 |
data = {"banana": "hammock", "lol": "cat"} |
| 614 |
r = pool.request("POST", "/echo", fields=data, encode_multipart=True) |
| 615 |
body = r.data.split(b"\r\n") |
| 616 |
|
| 617 |
encoded_data = encode_multipart_formdata(data)[0] |
| 618 |
expected_body = encoded_data.split(b"\r\n") |
| 619 |
|
| 620 |
# TODO: Get rid of extra parsing stuff when you can specify |
| 621 |
# a custom boundary to encode_multipart_formdata |
| 622 |
""" |
| 623 |
We need to loop the return lines because a timestamp is attached |
| 624 |
from within encode_multipart_formdata. When the server echos back |
| 625 |
the data, it has the timestamp from when the data was encoded, which |
| 626 |
is not equivalent to when we run encode_multipart_formdata on |
| 627 |
the data again. |
| 628 |
""" |
| 629 |
for i, line in enumerate(body): |
| 630 |
if line.startswith(b"--"): |
| 631 |
continue |
| 632 |
|
| 633 |
assert body[i] == expected_body[i] |
| 634 |
|
| 635 |
def test_post_with_multipart__iter__(self) -> None: |
| 636 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 637 |
data = {"hello": "world"} |
| 638 |
r = pool.request( |
| 639 |
"POST", |
| 640 |
"/echo", |
| 641 |
fields=data, |
| 642 |
preload_content=False, |
| 643 |
multipart_boundary="boundary", |
| 644 |
encode_multipart=True, |
| 645 |
) |
| 646 |
|
| 647 |
chunks = [chunk for chunk in r] |
| 648 |
assert chunks == [ |
| 649 |
b"--boundary\r\n", |
| 650 |
b'Content-Disposition: form-data; name="hello"\r\n', |
| 651 |
b"\r\n", |
| 652 |
b"world\r\n", |
| 653 |
b"--boundary--\r\n", |
| 654 |
] |
| 655 |
|
| 656 |
def test_check_gzip(self) -> None: |
| 657 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 658 |
r = pool.request( |
| 659 |
"GET", "/encodingrequest", headers={"accept-encoding": "gzip"} |
| 660 |
) |
| 661 |
assert r.headers.get("content-encoding") == "gzip" |
| 662 |
assert r.data == b"hello, world!" |
| 663 |
|
| 664 |
def test_check_deflate(self) -> None: |
| 665 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 666 |
r = pool.request( |
| 667 |
"GET", "/encodingrequest", headers={"accept-encoding": "deflate"} |
| 668 |
) |
| 669 |
assert r.headers.get("content-encoding") == "deflate" |
| 670 |
assert r.data == b"hello, world!" |
| 671 |
|
| 672 |
def test_bad_decode(self) -> None: |
| 673 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 674 |
with pytest.raises(DecodeError): |
| 675 |
pool.request( |
| 676 |
"GET", |
| 677 |
"/encodingrequest", |
| 678 |
headers={"accept-encoding": "garbage-deflate"}, |
| 679 |
) |
| 680 |
|
| 681 |
with pytest.raises(DecodeError): |
| 682 |
pool.request( |
| 683 |
"GET", |
| 684 |
"/encodingrequest", |
| 685 |
headers={"accept-encoding": "garbage-gzip"}, |
| 686 |
) |
| 687 |
|
| 688 |
def test_connection_count(self) -> None: |
| 689 |
with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool: |
| 690 |
pool.request("GET", "/") |
| 691 |
pool.request("GET", "/") |
| 692 |
pool.request("GET", "/") |
| 693 |
|
| 694 |
assert pool.num_connections == 1 |
| 695 |
assert pool.num_requests == 3 |
| 696 |
|
| 697 |
def test_connection_count_bigpool(self) -> None: |
| 698 |
with HTTPConnectionPool(self.host, self.port, maxsize=16) as http_pool: |
| 699 |
http_pool.request("GET", "/") |
| 700 |
http_pool.request("GET", "/") |
| 701 |
http_pool.request("GET", "/") |
| 702 |
|
| 703 |
assert http_pool.num_connections == 1 |
| 704 |
assert http_pool.num_requests == 3 |
| 705 |
|
| 706 |
def test_partial_response(self) -> None: |
| 707 |
with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool: |
| 708 |
req_data = {"lol": "cat"} |
| 709 |
resp_data = urlencode(req_data).encode("utf-8") |
| 710 |
|
| 711 |
r = pool.request("GET", "/echo", fields=req_data, preload_content=False) |
| 712 |
|
| 713 |
assert r.read(5) == resp_data[:5] |
| 714 |
assert r.read() == resp_data[5:] |
| 715 |
|
| 716 |
def test_lazy_load_twice(self) -> None: |
| 717 |
# This test is sad and confusing. Need to figure out what's |
| 718 |
# going on with partial reads and socket reuse. |
| 719 |
|
| 720 |
with HTTPConnectionPool( |
| 721 |
self.host, self.port, block=True, maxsize=1, timeout=2 |
| 722 |
) as pool: |
| 723 |
payload_size = 1024 * 2 |
| 724 |
first_chunk = 512 |
| 725 |
|
| 726 |
boundary = "foo" |
| 727 |
|
| 728 |
req_data = {"count": "a" * payload_size} |
| 729 |
resp_data = encode_multipart_formdata(req_data, boundary=boundary)[0] |
| 730 |
|
| 731 |
req2_data = {"count": "b" * payload_size} |
| 732 |
resp2_data = encode_multipart_formdata(req2_data, boundary=boundary)[0] |
| 733 |
|
| 734 |
r1 = pool.request( |
| 735 |
"POST", |
| 736 |
"/echo", |
| 737 |
fields=req_data, |
| 738 |
multipart_boundary=boundary, |
| 739 |
preload_content=False, |
| 740 |
) |
| 741 |
|
| 742 |
assert r1.read(first_chunk) == resp_data[:first_chunk] |
| 743 |
|
| 744 |
try: |
| 745 |
r2 = pool.request( |
| 746 |
"POST", |
| 747 |
"/echo", |
| 748 |
fields=req2_data, |
| 749 |
multipart_boundary=boundary, |
| 750 |
preload_content=False, |
| 751 |
pool_timeout=0.001, |
| 752 |
) |
| 753 |
|
| 754 |
# This branch should generally bail here, but maybe someday it will |
| 755 |
# work? Perhaps by some sort of magic. Consider it a TODO. |
| 756 |
|
| 757 |
assert r2.read(first_chunk) == resp2_data[:first_chunk] |
| 758 |
|
| 759 |
assert r1.read() == resp_data[first_chunk:] |
| 760 |
assert r2.read() == resp2_data[first_chunk:] |
| 761 |
assert pool.num_requests == 2 |
| 762 |
|
| 763 |
except EmptyPoolError: |
| 764 |
assert r1.read() == resp_data[first_chunk:] |
| 765 |
assert pool.num_requests == 1 |
| 766 |
|
| 767 |
assert pool.num_connections == 1 |
| 768 |
|
| 769 |
def test_for_double_release(self) -> None: |
| 770 |
MAXSIZE = 5 |
| 771 |
|
| 772 |
# Check default state |
| 773 |
with HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE) as pool: |
| 774 |
assert pool.num_connections == 0 |
| 775 |
assert pool.pool is not None |
| 776 |
assert pool.pool.qsize() == MAXSIZE |
| 777 |
|
| 778 |
# Make an empty slot for testing |
| 779 |
pool.pool.get() |
| 780 |
assert pool.pool.qsize() == MAXSIZE - 1 |
| 781 |
|
| 782 |
# Check state after simple request |
| 783 |
pool.urlopen("GET", "/") |
| 784 |
assert pool.pool.qsize() == MAXSIZE - 1 |
| 785 |
|
| 786 |
# Check state without release |
| 787 |
pool.urlopen("GET", "/", preload_content=False) |
| 788 |
assert pool.pool.qsize() == MAXSIZE - 2 |
| 789 |
|
| 790 |
pool.urlopen("GET", "/") |
| 791 |
assert pool.pool.qsize() == MAXSIZE - 2 |
| 792 |
|
| 793 |
# Check state after read |
| 794 |
pool.urlopen("GET", "/").data |
| 795 |
assert pool.pool.qsize() == MAXSIZE - 2 |
| 796 |
|
| 797 |
pool.urlopen("GET", "/") |
| 798 |
assert pool.pool.qsize() == MAXSIZE - 2 |
| 799 |
|
| 800 |
def test_release_conn_parameter(self) -> None: |
| 801 |
MAXSIZE = 5 |
| 802 |
with HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE) as pool: |
| 803 |
assert pool.pool is not None |
| 804 |
assert pool.pool.qsize() == MAXSIZE |
| 805 |
|
| 806 |
# Make request without releasing connection |
| 807 |
pool.request("GET", "/", release_conn=False, preload_content=False) |
| 808 |
assert pool.pool.qsize() == MAXSIZE - 1 |
| 809 |
|
| 810 |
def test_dns_error(self) -> None: |
| 811 |
with HTTPConnectionPool( |
| 812 |
"thishostdoesnotexist.invalid", self.port, timeout=0.001 |
| 813 |
) as pool: |
| 814 |
with pytest.raises(MaxRetryError): |
| 815 |
pool.request("GET", "/test", retries=2) |
| 816 |
|
| 817 |
@pytest.mark.parametrize("char", [" ", "\r", "\n", "\x00"]) |
| 818 |
def test_invalid_method_not_allowed(self, char: str) -> None: |
| 819 |
with pytest.raises(ValueError): |
| 820 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 821 |
pool.request("GET" + char, "/") |
| 822 |
|
| 823 |
def test_percent_encode_invalid_target_chars(self) -> None: |
| 824 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 825 |
r = pool.request("GET", "/echo_params?q=\r&k=\n \n") |
| 826 |
assert r.data == b"[('k', '\\n \\n'), ('q', '\\r')]" |
| 827 |
|
| 828 |
def test_source_address(self) -> None: |
| 829 |
for addr, is_ipv6 in VALID_SOURCE_ADDRESSES: |
| 830 |
if is_ipv6: |
| 831 |
# TODO enable if HAS_IPV6_AND_DNS when this is fixed: |
| 832 |
# https://github.com/pgjones/hypercorn/issues/160 |
| 833 |
warnings.warn("No IPv6 support: skipping.", NoIPv6Warning) |
| 834 |
continue |
| 835 |
with HTTPConnectionPool( |
| 836 |
self.host, self.port, source_address=addr, retries=False |
| 837 |
) as pool: |
| 838 |
r = pool.request("GET", "/source_address") |
| 839 |
assert r.data == addr[0].encode() |
| 840 |
|
| 841 |
@pytest.mark.parametrize( |
| 842 |
"invalid_source_address, is_ipv6", INVALID_SOURCE_ADDRESSES |
| 843 |
) |
| 844 |
def test_source_address_error( |
| 845 |
self, invalid_source_address: tuple[str, int], is_ipv6: bool |
| 846 |
) -> None: |
| 847 |
with HTTPConnectionPool( |
| 848 |
self.host, self.port, source_address=invalid_source_address, retries=False |
| 849 |
) as pool: |
| 850 |
if is_ipv6: |
| 851 |
# with pytest.raises(NameResolutionError): |
| 852 |
with pytest.raises(NewConnectionError): |
| 853 |
pool.request("GET", f"/source_address?{invalid_source_address}") |
| 854 |
else: |
| 855 |
with pytest.raises(NewConnectionError): |
| 856 |
pool.request("GET", f"/source_address?{invalid_source_address}") |
| 857 |
|
| 858 |
def test_stream_keepalive(self) -> None: |
| 859 |
x = 2 |
| 860 |
|
| 861 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 862 |
for _ in range(x): |
| 863 |
response = pool.request( |
| 864 |
"GET", |
| 865 |
"/chunked", |
| 866 |
headers={"Connection": "keep-alive"}, |
| 867 |
preload_content=False, |
| 868 |
retries=False, |
| 869 |
) |
| 870 |
for chunk in response.stream(): |
| 871 |
assert chunk == b"123" |
| 872 |
|
| 873 |
assert pool.num_connections == 1 |
| 874 |
assert pool.num_requests == x |
| 875 |
|
| 876 |
def test_read_chunked_short_circuit(self) -> None: |
| 877 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 878 |
response = pool.request("GET", "/chunked", preload_content=False) |
| 879 |
response.read() |
| 880 |
with pytest.raises(StopIteration): |
| 881 |
next(response.read_chunked()) |
| 882 |
|
| 883 |
def test_read_chunked_on_closed_response(self) -> None: |
| 884 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 885 |
response = pool.request("GET", "/chunked", preload_content=False) |
| 886 |
response.close() |
| 887 |
with pytest.raises(StopIteration): |
| 888 |
next(response.read_chunked()) |
| 889 |
|
| 890 |
def test_chunked_gzip(self) -> None: |
| 891 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 892 |
response = pool.request( |
| 893 |
"GET", "/chunked_gzip", preload_content=False, decode_content=True |
| 894 |
) |
| 895 |
|
| 896 |
assert b"123" * 4 == response.read() |
| 897 |
|
| 898 |
def test_cleanup_on_connection_error(self) -> None: |
| 899 |
""" |
| 900 |
Test that connections are recycled to the pool on |
| 901 |
connection errors where no http response is received. |
| 902 |
""" |
| 903 |
poolsize = 3 |
| 904 |
with HTTPConnectionPool( |
| 905 |
self.host, self.port, maxsize=poolsize, block=True |
| 906 |
) as http: |
| 907 |
assert http.pool is not None |
| 908 |
assert http.pool.qsize() == poolsize |
| 909 |
|
| 910 |
# force a connection error by supplying a non-existent |
| 911 |
# url. We won't get a response for this and so the |
| 912 |
# conn won't be implicitly returned to the pool. |
| 913 |
with pytest.raises(MaxRetryError): |
| 914 |
http.request( |
| 915 |
"GET", |
| 916 |
"/redirect", |
| 917 |
fields={"target": "/"}, |
| 918 |
release_conn=False, |
| 919 |
retries=0, |
| 920 |
) |
| 921 |
|
| 922 |
r = http.request( |
| 923 |
"GET", |
| 924 |
"/redirect", |
| 925 |
fields={"target": "/"}, |
| 926 |
release_conn=False, |
| 927 |
retries=1, |
| 928 |
) |
| 929 |
r.release_conn() |
| 930 |
|
| 931 |
# the pool should still contain poolsize elements |
| 932 |
assert http.pool.qsize() == http.pool.maxsize |
| 933 |
|
| 934 |
def test_shutdown_on_connection_released_to_pool(self) -> None: |
| 935 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 936 |
resp = pool.urlopen("GET", "/", preload_content=False) |
| 937 |
resp.drain_conn() |
| 938 |
resp.release_conn() |
| 939 |
|
| 940 |
with pytest.raises( |
| 941 |
RuntimeError, |
| 942 |
match="Cannot shutdown as connection has already been released to the pool", |
| 943 |
): |
| 944 |
resp.shutdown() |
| 945 |
|
| 946 |
def test_mixed_case_hostname(self) -> None: |
| 947 |
with HTTPConnectionPool("LoCaLhOsT", self.port) as pool: |
| 948 |
response = pool.request("GET", f"http://LoCaLhOsT:{self.port}/") |
| 949 |
assert response.status == 200 |
| 950 |
|
| 951 |
def test_preserves_path_dot_segments(self) -> None: |
| 952 |
"""ConnectionPool preserves dot segments in the URI""" |
| 953 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 954 |
response = pool.request("GET", "/echo_uri/seg0/../seg2") |
| 955 |
assert response.data == b"/echo_uri/seg0/../seg2?" |
| 956 |
|
| 957 |
def test_default_user_agent_header(self) -> None: |
| 958 |
"""ConnectionPool has a default user agent""" |
| 959 |
default_ua = _get_default_user_agent() |
| 960 |
custom_ua = "I'm not a web scraper, what are you talking about?" |
| 961 |
custom_ua2 = "Yet Another User Agent" |
| 962 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 963 |
# Use default user agent if no user agent was specified. |
| 964 |
r = pool.request("GET", "/headers") |
| 965 |
request_headers = r.json() |
| 966 |
assert request_headers.get("User-Agent") == _get_default_user_agent() |
| 967 |
|
| 968 |
# Prefer the request user agent over the default. |
| 969 |
headers = {"UsEr-AGENt": custom_ua} |
| 970 |
r = pool.request("GET", "/headers", headers=headers) |
| 971 |
request_headers = r.json() |
| 972 |
assert request_headers.get("User-Agent") == custom_ua |
| 973 |
|
| 974 |
# Do not modify pool headers when using the default user agent. |
| 975 |
pool_headers = {"foo": "bar"} |
| 976 |
pool.headers = pool_headers |
| 977 |
r = pool.request("GET", "/headers") |
| 978 |
request_headers = r.json() |
| 979 |
assert request_headers.get("User-Agent") == default_ua |
| 980 |
assert "User-Agent" not in pool_headers |
| 981 |
|
| 982 |
pool.headers.update({"User-Agent": custom_ua2}) |
| 983 |
r = pool.request("GET", "/headers") |
| 984 |
request_headers = r.json() |
| 985 |
assert request_headers.get("User-Agent") == custom_ua2 |
| 986 |
|
| 987 |
@pytest.mark.parametrize( |
| 988 |
"headers", |
| 989 |
[ |
| 990 |
None, |
| 991 |
{}, |
| 992 |
{"User-Agent": "key"}, |
| 993 |
{"user-agent": "key"}, |
| 994 |
{b"uSeR-AgEnT": b"key"}, |
| 995 |
{b"user-agent": "key"}, |
| 996 |
], |
| 997 |
) |
| 998 |
@pytest.mark.parametrize("chunked", [True, False]) |
| 999 |
def test_user_agent_header_not_sent_twice( |
| 1000 |
self, headers: dict[str, str] | None, chunked: bool |
| 1001 |
) -> None: |
| 1002 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1003 |
r = pool.request("GET", "/headers", headers=headers, chunked=chunked) |
| 1004 |
request_headers = r.json() |
| 1005 |
|
| 1006 |
if not headers: |
| 1007 |
assert request_headers["User-Agent"].startswith("python-urllib3/") |
| 1008 |
assert "key" not in request_headers["User-Agent"] |
| 1009 |
else: |
| 1010 |
assert request_headers["User-Agent"] == "key" |
| 1011 |
|
| 1012 |
def test_no_user_agent_header(self) -> None: |
| 1013 |
"""ConnectionPool can suppress sending a user agent header""" |
| 1014 |
custom_ua = "I'm not a web scraper, what are you talking about?" |
| 1015 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1016 |
# Suppress user agent in the request headers. |
| 1017 |
no_ua_headers = {"User-Agent": SKIP_HEADER} |
| 1018 |
r = pool.request("GET", "/headers", headers=no_ua_headers) |
| 1019 |
request_headers = r.json() |
| 1020 |
assert "User-Agent" not in request_headers |
| 1021 |
assert no_ua_headers["User-Agent"] == SKIP_HEADER |
| 1022 |
|
| 1023 |
# Suppress user agent in the pool headers. |
| 1024 |
pool.headers = no_ua_headers |
| 1025 |
r = pool.request("GET", "/headers") |
| 1026 |
request_headers = r.json() |
| 1027 |
assert "User-Agent" not in request_headers |
| 1028 |
assert no_ua_headers["User-Agent"] == SKIP_HEADER |
| 1029 |
|
| 1030 |
# Request headers override pool headers. |
| 1031 |
pool_headers = {"User-Agent": custom_ua} |
| 1032 |
pool.headers = pool_headers |
| 1033 |
r = pool.request("GET", "/headers", headers=no_ua_headers) |
| 1034 |
request_headers = r.json() |
| 1035 |
assert "User-Agent" not in request_headers |
| 1036 |
assert no_ua_headers["User-Agent"] == SKIP_HEADER |
| 1037 |
assert pool_headers.get("User-Agent") == custom_ua |
| 1038 |
|
| 1039 |
@pytest.mark.parametrize("header", ["Content-Length", "content-length"]) |
| 1040 |
@pytest.mark.parametrize("chunked", [True, False]) |
| 1041 |
def test_skip_header_non_supported(self, header: str, chunked: bool) -> None: |
| 1042 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1043 |
with pytest.raises( |
| 1044 |
ValueError, |
| 1045 |
match="urllib3.util.SKIP_HEADER only supports 'Accept-Encoding', 'Host', 'User-Agent'", |
| 1046 |
) as e: |
| 1047 |
pool.request( |
| 1048 |
"GET", "/headers", headers={header: SKIP_HEADER}, chunked=chunked |
| 1049 |
) |
| 1050 |
# Ensure that the error message stays up to date with 'SKIP_HEADER_SUPPORTED_HEADERS' |
| 1051 |
assert all( |
| 1052 |
("'" + header.title() + "'") in str(e.value) |
| 1053 |
for header in SKIPPABLE_HEADERS |
| 1054 |
) |
| 1055 |
|
| 1056 |
@pytest.mark.parametrize("chunked", [True, False]) |
| 1057 |
@pytest.mark.parametrize("pool_request", [True, False]) |
| 1058 |
@pytest.mark.parametrize("header_type", [dict, HTTPHeaderDict]) |
| 1059 |
def test_headers_not_modified_by_request( |
| 1060 |
self, |
| 1061 |
chunked: bool, |
| 1062 |
pool_request: bool, |
| 1063 |
header_type: type[dict[str, str] | HTTPHeaderDict], |
| 1064 |
) -> None: |
| 1065 |
# Test that the .request*() methods of ConnectionPool and HTTPConnection |
| 1066 |
# don't modify the given 'headers' structure, instead they should |
| 1067 |
# make their own internal copies at request time. |
| 1068 |
headers = header_type() |
| 1069 |
headers["key"] = "val" |
| 1070 |
|
| 1071 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1072 |
pool.headers = headers |
| 1073 |
if pool_request: |
| 1074 |
pool.request("GET", "/headers", chunked=chunked) |
| 1075 |
else: |
| 1076 |
conn = pool._get_conn() |
| 1077 |
conn.request("GET", "/headers", chunked=chunked) |
| 1078 |
conn.getresponse().close() |
| 1079 |
conn.close() |
| 1080 |
|
| 1081 |
assert pool.headers == {"key": "val"} |
| 1082 |
assert type(pool.headers) is header_type |
| 1083 |
|
| 1084 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1085 |
if pool_request: |
| 1086 |
pool.request("GET", "/headers", headers=headers, chunked=chunked) |
| 1087 |
else: |
| 1088 |
conn = pool._get_conn() |
| 1089 |
conn.request("GET", "/headers", headers=headers, chunked=chunked) |
| 1090 |
conn.getresponse().close() |
| 1091 |
conn.close() |
| 1092 |
|
| 1093 |
assert headers == {"key": "val"} |
| 1094 |
|
| 1095 |
def test_request_chunked_is_deprecated( |
| 1096 |
self, |
| 1097 |
) -> None: |
| 1098 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1099 |
conn = pool._get_conn() |
| 1100 |
|
| 1101 |
with pytest.warns(FutureWarning) as w: |
| 1102 |
conn.request_chunked("GET", "/headers") # type: ignore[attr-defined] |
| 1103 |
assert len(w) == 1 and str(w[0].message) == ( |
| 1104 |
"HTTPConnection.request_chunked() is deprecated and will be removed in urllib3 v3.0. " |
| 1105 |
"Instead use HTTPConnection.request(..., chunked=True)." |
| 1106 |
) |
| 1107 |
|
| 1108 |
resp = conn.getresponse() |
| 1109 |
assert resp.status == 200 |
| 1110 |
assert resp.json()["Transfer-Encoding"] == "chunked" |
| 1111 |
conn.close() |
| 1112 |
|
| 1113 |
def test_bytes_header(self) -> None: |
| 1114 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1115 |
headers = {"User-Agent": "test header"} |
| 1116 |
r = pool.request("GET", "/headers", headers=headers) |
| 1117 |
request_headers = r.json() |
| 1118 |
assert "User-Agent" in request_headers |
| 1119 |
assert request_headers["User-Agent"] == "test header" |
| 1120 |
|
| 1121 |
@pytest.mark.parametrize( |
| 1122 |
"user_agent", ["Schönefeld/1.18.0", "Schönefeld/1.18.0".encode("iso-8859-1")] |
| 1123 |
) |
| 1124 |
def test_user_agent_non_ascii_user_agent(self, user_agent: str) -> None: |
| 1125 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 1126 |
r = pool.urlopen( |
| 1127 |
"GET", |
| 1128 |
"/headers", |
| 1129 |
headers={"User-Agent": user_agent}, |
| 1130 |
) |
| 1131 |
request_headers = r.json() |
| 1132 |
assert "User-Agent" in request_headers |
| 1133 |
assert request_headers["User-Agent"] == "Schönefeld/1.18.0" |
| 1134 |
|
| 1135 |
|
| 1136 |
class TestRetry(HypercornDummyServerTestCase): |
| 1137 |
def test_max_retry(self) -> None: |
| 1138 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1139 |
with pytest.raises(MaxRetryError): |
| 1140 |
pool.request("GET", "/redirect", fields={"target": "/"}, retries=0) |
| 1141 |
|
| 1142 |
def test_disabled_retry(self) -> None: |
| 1143 |
"""Disabled retries should disable redirect handling.""" |
| 1144 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1145 |
r = pool.request("GET", "/redirect", fields={"target": "/"}, retries=False) |
| 1146 |
assert r.status == 303 |
| 1147 |
|
| 1148 |
r = pool.request( |
| 1149 |
"GET", |
| 1150 |
"/redirect", |
| 1151 |
fields={"target": "/"}, |
| 1152 |
retries=Retry(redirect=False), |
| 1153 |
) |
| 1154 |
assert r.status == 303 |
| 1155 |
|
| 1156 |
with HTTPConnectionPool( |
| 1157 |
"thishostdoesnotexist.invalid", self.port, timeout=0.001 |
| 1158 |
) as pool: |
| 1159 |
with pytest.raises(NameResolutionError): |
| 1160 |
pool.request("GET", "/test", retries=False) |
| 1161 |
|
| 1162 |
def test_read_retries(self) -> None: |
| 1163 |
"""Should retry for status codes in the forcelist""" |
| 1164 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1165 |
retry = Retry(read=1, status_forcelist=[418]) |
| 1166 |
resp = pool.request( |
| 1167 |
"GET", |
| 1168 |
"/successful_retry", |
| 1169 |
headers={"test-name": "test_read_retries"}, |
| 1170 |
retries=retry, |
| 1171 |
) |
| 1172 |
assert resp.status == 200 |
| 1173 |
|
| 1174 |
def test_read_total_retries(self) -> None: |
| 1175 |
"""HTTP response w/ status code in the forcelist should be retried""" |
| 1176 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1177 |
headers = {"test-name": "test_read_total_retries"} |
| 1178 |
retry = Retry(total=1, status_forcelist=[418]) |
| 1179 |
resp = pool.request( |
| 1180 |
"GET", "/successful_retry", headers=headers, retries=retry |
| 1181 |
) |
| 1182 |
assert resp.status == 200 |
| 1183 |
|
| 1184 |
def test_retries_wrong_forcelist(self) -> None: |
| 1185 |
"""HTTP response w/ status code not in forcelist shouldn't be retried""" |
| 1186 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1187 |
retry = Retry(total=1, status_forcelist=[202]) |
| 1188 |
resp = pool.request( |
| 1189 |
"GET", |
| 1190 |
"/successful_retry", |
| 1191 |
headers={"test-name": "test_wrong_forcelist"}, |
| 1192 |
retries=retry, |
| 1193 |
) |
| 1194 |
assert resp.status == 418 |
| 1195 |
|
| 1196 |
def test_default_method_forcelist_retried(self) -> None: |
| 1197 |
"""urllib3 should retry methods in the default method forcelist""" |
| 1198 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1199 |
retry = Retry(total=1, status_forcelist=[418]) |
| 1200 |
resp = pool.request( |
| 1201 |
"OPTIONS", |
| 1202 |
"/successful_retry", |
| 1203 |
headers={"test-name": "test_default_forcelist"}, |
| 1204 |
retries=retry, |
| 1205 |
) |
| 1206 |
assert resp.status == 200 |
| 1207 |
|
| 1208 |
def test_retries_wrong_method_list(self) -> None: |
| 1209 |
"""Method not in our allowed list should not be retried, even if code matches""" |
| 1210 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1211 |
headers = {"test-name": "test_wrong_allowed_method"} |
| 1212 |
retry = Retry(total=1, status_forcelist=[418], allowed_methods=["POST"]) |
| 1213 |
resp = pool.request( |
| 1214 |
"GET", "/successful_retry", headers=headers, retries=retry |
| 1215 |
) |
| 1216 |
assert resp.status == 418 |
| 1217 |
|
| 1218 |
def test_read_retries_unsuccessful( |
| 1219 |
self, |
| 1220 |
) -> None: |
| 1221 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1222 |
headers = {"test-name": "test_read_retries_unsuccessful"} |
| 1223 |
resp = pool.request("GET", "/successful_retry", headers=headers, retries=1) |
| 1224 |
assert resp.status == 418 |
| 1225 |
|
| 1226 |
def test_retry_reuse_safe(self) -> None: |
| 1227 |
"""It should be possible to reuse a Retry object across requests""" |
| 1228 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1229 |
headers = {"test-name": "test_retry_safe"} |
| 1230 |
retry = Retry(total=1, status_forcelist=[418]) |
| 1231 |
resp = pool.request( |
| 1232 |
"GET", "/successful_retry", headers=headers, retries=retry |
| 1233 |
) |
| 1234 |
assert resp.status == 200 |
| 1235 |
|
| 1236 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1237 |
resp = pool.request( |
| 1238 |
"GET", "/successful_retry", headers=headers, retries=retry |
| 1239 |
) |
| 1240 |
assert resp.status == 200 |
| 1241 |
|
| 1242 |
def test_retry_return_in_response(self) -> None: |
| 1243 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1244 |
headers = {"test-name": "test_retry_return_in_response"} |
| 1245 |
retry = Retry(total=2, status_forcelist=[418]) |
| 1246 |
resp = pool.request( |
| 1247 |
"GET", "/successful_retry", headers=headers, retries=retry |
| 1248 |
) |
| 1249 |
assert resp.status == 200 |
| 1250 |
assert resp.retries is not None |
| 1251 |
assert resp.retries.total == 1 |
| 1252 |
assert resp.retries.history == ( |
| 1253 |
RequestHistory("GET", "/successful_retry", None, 418, None), |
| 1254 |
) |
| 1255 |
|
| 1256 |
def test_retry_redirect_history(self) -> None: |
| 1257 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1258 |
resp = pool.request("GET", "/redirect", fields={"target": "/"}) |
| 1259 |
assert resp.status == 200 |
| 1260 |
assert resp.retries is not None |
| 1261 |
assert resp.retries.history == ( |
| 1262 |
RequestHistory("GET", "/redirect?target=%2F", None, 303, "/"), |
| 1263 |
) |
| 1264 |
|
| 1265 |
def test_multi_redirect_history(self) -> None: |
| 1266 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1267 |
r = pool.request( |
| 1268 |
"GET", |
| 1269 |
"/multi_redirect", |
| 1270 |
fields={"redirect_codes": "303,302,200"}, |
| 1271 |
redirect=False, |
| 1272 |
) |
| 1273 |
assert r.status == 303 |
| 1274 |
assert r.retries is not None |
| 1275 |
assert r.retries.history == tuple() |
| 1276 |
|
| 1277 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1278 |
r = pool.request( |
| 1279 |
"GET", |
| 1280 |
"/multi_redirect", |
| 1281 |
retries=10, |
| 1282 |
fields={"redirect_codes": "303,302,301,307,302,200"}, |
| 1283 |
) |
| 1284 |
assert r.status == 200 |
| 1285 |
assert r.data == b"Done redirecting" |
| 1286 |
|
| 1287 |
expected = [ |
| 1288 |
(303, "/multi_redirect?redirect_codes=302,301,307,302,200"), |
| 1289 |
(302, "/multi_redirect?redirect_codes=301,307,302,200"), |
| 1290 |
(301, "/multi_redirect?redirect_codes=307,302,200"), |
| 1291 |
(307, "/multi_redirect?redirect_codes=302,200"), |
| 1292 |
(302, "/multi_redirect?redirect_codes=200"), |
| 1293 |
] |
| 1294 |
assert r.retries is not None |
| 1295 |
actual = [ |
| 1296 |
(history.status, history.redirect_location) |
| 1297 |
for history in r.retries.history |
| 1298 |
] |
| 1299 |
assert actual == expected |
| 1300 |
|
| 1301 |
|
| 1302 |
class TestRetryAfter(HypercornDummyServerTestCase): |
| 1303 |
def test_retry_after(self) -> None: |
| 1304 |
# Request twice in a second to get a 429 response. |
| 1305 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1306 |
r = pool.request( |
| 1307 |
"GET", |
| 1308 |
"/retry_after", |
| 1309 |
fields={"status": "429 Too Many Requests"}, |
| 1310 |
retries=False, |
| 1311 |
) |
| 1312 |
r = pool.request( |
| 1313 |
"GET", |
| 1314 |
"/retry_after", |
| 1315 |
fields={"status": "429 Too Many Requests"}, |
| 1316 |
retries=False, |
| 1317 |
) |
| 1318 |
assert r.status == 429 |
| 1319 |
|
| 1320 |
r = pool.request( |
| 1321 |
"GET", |
| 1322 |
"/retry_after", |
| 1323 |
fields={"status": "429 Too Many Requests"}, |
| 1324 |
retries=True, |
| 1325 |
) |
| 1326 |
assert r.status == 200 |
| 1327 |
|
| 1328 |
# Request twice in a second to get a 503 response. |
| 1329 |
r = pool.request( |
| 1330 |
"GET", |
| 1331 |
"/retry_after", |
| 1332 |
fields={"status": "503 Service Unavailable"}, |
| 1333 |
retries=False, |
| 1334 |
) |
| 1335 |
r = pool.request( |
| 1336 |
"GET", |
| 1337 |
"/retry_after", |
| 1338 |
fields={"status": "503 Service Unavailable"}, |
| 1339 |
retries=False, |
| 1340 |
) |
| 1341 |
assert r.status == 503 |
| 1342 |
|
| 1343 |
r = pool.request( |
| 1344 |
"GET", |
| 1345 |
"/retry_after", |
| 1346 |
fields={"status": "503 Service Unavailable"}, |
| 1347 |
retries=True, |
| 1348 |
) |
| 1349 |
assert r.status == 200 |
| 1350 |
|
| 1351 |
# Ignore Retry-After header on status which is not defined in |
| 1352 |
# Retry.RETRY_AFTER_STATUS_CODES. |
| 1353 |
r = pool.request( |
| 1354 |
"GET", |
| 1355 |
"/retry_after", |
| 1356 |
fields={"status": "418 I'm a teapot"}, |
| 1357 |
retries=True, |
| 1358 |
) |
| 1359 |
assert r.status == 418 |
| 1360 |
|
| 1361 |
def test_redirect_after(self) -> None: |
| 1362 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 1363 |
r = pool.request("GET", "/redirect_after", retries=False) |
| 1364 |
assert r.status == 303 |
| 1365 |
|
| 1366 |
# Real timestamps are needed for this test |
| 1367 |
t = time.time() |
| 1368 |
r = pool.request("GET", "/redirect_after") |
| 1369 |
assert r.status == 200 |
| 1370 |
delta = time.time() - t |
| 1371 |
assert delta >= 1 |
| 1372 |
|
| 1373 |
t = time.time() |
| 1374 |
timestamp = t + 2 |
| 1375 |
r = pool.request("GET", "/redirect_after?date=" + str(timestamp)) |
| 1376 |
assert r.status == 200 |
| 1377 |
delta = time.time() - t |
| 1378 |
assert delta >= 1 |
| 1379 |
|
| 1380 |
# Retry-After is past |
| 1381 |
t = time.time() |
| 1382 |
timestamp = t - 1 |
| 1383 |
r = pool.request("GET", "/redirect_after?date=" + str(timestamp)) |
| 1384 |
delta = time.time() - t |
| 1385 |
assert r.status == 200 |
| 1386 |
assert delta < 1 |
| 1387 |
|
| 1388 |
|
| 1389 |
class TestFileBodiesOnRetryOrRedirect(HypercornDummyServerTestCase): |
| 1390 |
def test_retries_put_filehandle(self) -> None: |
| 1391 |
"""HTTP PUT retry with a file-like object should not timeout""" |
| 1392 |
with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool: |
| 1393 |
retry = Retry(total=3, status_forcelist=[418]) |
| 1394 |
# httplib reads in 8k chunks; use a larger content length |
| 1395 |
content_length = 65535 |
| 1396 |
data = b"A" * content_length |
| 1397 |
uploaded_file = io.BytesIO(data) |
| 1398 |
headers = { |
| 1399 |
"test-name": "test_retries_put_filehandle", |
| 1400 |
"Content-Length": str(content_length), |
| 1401 |
} |
| 1402 |
resp = pool.urlopen( |
| 1403 |
"PUT", |
| 1404 |
"/successful_retry", |
| 1405 |
headers=headers, |
| 1406 |
retries=retry, |
| 1407 |
body=uploaded_file, |
| 1408 |
assert_same_host=False, |
| 1409 |
redirect=False, |
| 1410 |
) |
| 1411 |
assert resp.status == 200 |
| 1412 |
|
| 1413 |
def test_redirect_put_file(self) -> None: |
| 1414 |
"""PUT with file object should work with a redirection response""" |
| 1415 |
with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool: |
| 1416 |
retry = Retry(total=3, status_forcelist=[418]) |
| 1417 |
# httplib reads in 8k chunks; use a larger content length |
| 1418 |
content_length = 65535 |
| 1419 |
data = b"A" * content_length |
| 1420 |
uploaded_file = io.BytesIO(data) |
| 1421 |
headers = { |
| 1422 |
"test-name": "test_redirect_put_file", |
| 1423 |
"Content-Length": str(content_length), |
| 1424 |
} |
| 1425 |
url = "/redirect?target=/echo&status=307" |
| 1426 |
resp = pool.urlopen( |
| 1427 |
"PUT", |
| 1428 |
url, |
| 1429 |
headers=headers, |
| 1430 |
retries=retry, |
| 1431 |
body=uploaded_file, |
| 1432 |
assert_same_host=False, |
| 1433 |
redirect=True, |
| 1434 |
) |
| 1435 |
assert resp.status == 200 |
| 1436 |
assert resp.data == data |
| 1437 |
|
| 1438 |
def test_redirect_with_failed_tell(self) -> None: |
| 1439 |
"""Abort request if failed to get a position from tell()""" |
| 1440 |
|
| 1441 |
class BadTellObject(io.BytesIO): |
| 1442 |
def tell(self) -> typing.NoReturn: |
| 1443 |
raise OSError |
| 1444 |
|
| 1445 |
body = BadTellObject(b"the data") |
| 1446 |
url = "/redirect?target=/successful_retry" |
| 1447 |
# httplib uses fileno if Content-Length isn't supplied, |
| 1448 |
# which is unsupported by BytesIO. |
| 1449 |
headers = {"Content-Length": "8"} |
| 1450 |
with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool: |
| 1451 |
with pytest.raises( |
| 1452 |
UnrewindableBodyError, match="Unable to record file position for" |
| 1453 |
): |
| 1454 |
pool.urlopen("PUT", url, headers=headers, body=body) |
| 1455 |
|
| 1456 |
|
| 1457 |
class TestRetryPoolSize(HypercornDummyServerTestCase): |
| 1458 |
def test_pool_size_retry(self) -> None: |
| 1459 |
retries = Retry(total=1, raise_on_status=False, status_forcelist=[404]) |
| 1460 |
with HTTPConnectionPool( |
| 1461 |
self.host, self.port, maxsize=10, retries=retries, block=True |
| 1462 |
) as pool: |
| 1463 |
pool.urlopen("GET", "/not_found", preload_content=False) |
| 1464 |
assert pool.num_connections == 1 |
| 1465 |
|
| 1466 |
|
| 1467 |
class TestRedirectPoolSize(HypercornDummyServerTestCase): |
| 1468 |
def test_pool_size_redirect(self) -> None: |
| 1469 |
retries = Retry( |
| 1470 |
total=1, raise_on_status=False, status_forcelist=[404], redirect=True |
| 1471 |
) |
| 1472 |
with HTTPConnectionPool( |
| 1473 |
self.host, self.port, maxsize=10, retries=retries, block=True |
| 1474 |
) as pool: |
| 1475 |
pool.urlopen("GET", "/redirect", preload_content=False) |
| 1476 |
assert pool.num_connections == 1 |