| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import http.client as httplib |
| 4 |
import queue |
| 5 |
import ssl |
| 6 |
import typing |
| 7 |
from http.client import HTTPException |
| 8 |
from queue import Empty |
| 9 |
from socket import error as SocketError |
| 10 |
from ssl import SSLError as BaseSSLError |
| 11 |
from test import SHORT_TIMEOUT |
| 12 |
from unittest.mock import Mock, patch |
| 13 |
|
| 14 |
import pytest |
| 15 |
|
| 16 |
from dummyserver.socketserver import DEFAULT_CA |
| 17 |
from urllib3 import Retry |
| 18 |
from urllib3.connection import HTTPConnection |
| 19 |
from urllib3.connectionpool import ( |
| 20 |
HTTPConnectionPool, |
| 21 |
HTTPSConnectionPool, |
| 22 |
_url_from_pool, |
| 23 |
connection_from_url, |
| 24 |
) |
| 25 |
from urllib3.exceptions import ( |
| 26 |
ClosedPoolError, |
| 27 |
EmptyPoolError, |
| 28 |
FullPoolError, |
| 29 |
HostChangedError, |
| 30 |
LocationParseError, |
| 31 |
LocationValueError, |
| 32 |
MaxRetryError, |
| 33 |
ProtocolError, |
| 34 |
ReadTimeoutError, |
| 35 |
SSLError, |
| 36 |
TimeoutError, |
| 37 |
UnrewindableBodyError, |
| 38 |
) |
| 39 |
from urllib3.response import HTTPResponse |
| 40 |
from urllib3.util.ssl_match_hostname import CertificateError |
| 41 |
from urllib3.util.timeout import _DEFAULT_TIMEOUT, Timeout |
| 42 |
|
| 43 |
from .test_response import MockChunkedEncodingResponse, MockSock |
| 44 |
|
| 45 |
|
| 46 |
class HTTPUnixConnection(HTTPConnection): |
| 47 |
def __init__(self, host: str, timeout: int = 60, **kwargs: typing.Any) -> None: |
| 48 |
super().__init__("localhost") |
| 49 |
self.unix_socket = host |
| 50 |
self.timeout = timeout |
| 51 |
self.sock = None |
| 52 |
|
| 53 |
|
| 54 |
class HTTPUnixConnectionPool(HTTPConnectionPool): |
| 55 |
scheme = "http+unix" |
| 56 |
ConnectionCls = HTTPUnixConnection |
| 57 |
|
| 58 |
|
| 59 |
class TestConnectionPool: |
| 60 |
""" |
| 61 |
Tests in this suite should exercise the ConnectionPool functionality |
| 62 |
without actually making any network requests or connections. |
| 63 |
""" |
| 64 |
|
| 65 |
@pytest.mark.parametrize( |
| 66 |
"a, b", |
| 67 |
[ |
| 68 |
("http://google.com/", "/"), |
| 69 |
("http://google.com/", "http://google.com/"), |
| 70 |
("http://google.com/", "http://google.com"), |
| 71 |
("http://google.com/", "http://google.com/abra/cadabra"), |
| 72 |
("http://google.com:42/", "http://google.com:42/abracadabra"), |
| 73 |
# Test comparison using default ports |
| 74 |
("http://google.com:80/", "http://google.com/abracadabra"), |
| 75 |
("http://google.com/", "http://google.com:80/abracadabra"), |
| 76 |
("https://google.com:443/", "https://google.com/abracadabra"), |
| 77 |
("https://google.com/", "https://google.com:443/abracadabra"), |
| 78 |
( |
| 79 |
"http://[2607:f8b0:4005:805::200e%25eth0]/", |
| 80 |
"http://[2607:f8b0:4005:805::200e%eth0]/", |
| 81 |
), |
| 82 |
( |
| 83 |
"https://[2607:f8b0:4005:805::200e%25eth0]:443/", |
| 84 |
"https://[2607:f8b0:4005:805::200e%eth0]:443/", |
| 85 |
), |
| 86 |
("http://[::1]/", "http://[::1]"), |
| 87 |
( |
| 88 |
"http://[2001:558:fc00:200:f816:3eff:fef9:b954%lo]/", |
| 89 |
"http://[2001:558:fc00:200:f816:3eff:fef9:b954%25lo]", |
| 90 |
), |
| 91 |
], |
| 92 |
) |
| 93 |
def test_same_host(self, a: str, b: str) -> None: |
| 94 |
with connection_from_url(a) as c: |
| 95 |
assert c.is_same_host(b) |
| 96 |
|
| 97 |
@pytest.mark.parametrize( |
| 98 |
"a, b", |
| 99 |
[ |
| 100 |
("https://google.com/", "http://google.com/"), |
| 101 |
("http://google.com/", "https://google.com/"), |
| 102 |
("http://yahoo.com/", "http://google.com/"), |
| 103 |
("http://google.com:42", "https://google.com/abracadabra"), |
| 104 |
("http://google.com", "https://google.net/"), |
| 105 |
# Test comparison with default ports |
| 106 |
("http://google.com:42", "http://google.com"), |
| 107 |
("https://google.com:42", "https://google.com"), |
| 108 |
("http://google.com:443", "http://google.com"), |
| 109 |
("https://google.com:80", "https://google.com"), |
| 110 |
("http://google.com:443", "https://google.com"), |
| 111 |
("https://google.com:80", "http://google.com"), |
| 112 |
("https://google.com:443", "http://google.com"), |
| 113 |
("http://google.com:80", "https://google.com"), |
| 114 |
# Zone identifiers are unique connection end points and should |
| 115 |
# never be equivalent. |
| 116 |
("http://[dead::beef]", "https://[dead::beef%en5]/"), |
| 117 |
], |
| 118 |
) |
| 119 |
def test_not_same_host(self, a: str, b: str) -> None: |
| 120 |
with connection_from_url(a) as c: |
| 121 |
assert not c.is_same_host(b) |
| 122 |
|
| 123 |
with connection_from_url(b) as c: |
| 124 |
assert not c.is_same_host(a) |
| 125 |
|
| 126 |
@pytest.mark.parametrize( |
| 127 |
"a, b", |
| 128 |
[ |
| 129 |
("google.com", "/"), |
| 130 |
("google.com", "http://google.com/"), |
| 131 |
("google.com", "http://google.com"), |
| 132 |
("google.com", "http://google.com/abra/cadabra"), |
| 133 |
# Test comparison using default ports |
| 134 |
("google.com", "http://google.com:80/abracadabra"), |
| 135 |
], |
| 136 |
) |
| 137 |
def test_same_host_no_port_http(self, a: str, b: str) -> None: |
| 138 |
# This test was introduced in #801 to deal with the fact that urllib3 |
| 139 |
# never initializes ConnectionPool objects with port=None. |
| 140 |
with HTTPConnectionPool(a) as c: |
| 141 |
assert c.is_same_host(b) |
| 142 |
|
| 143 |
@pytest.mark.parametrize( |
| 144 |
"a, b", |
| 145 |
[ |
| 146 |
("google.com", "/"), |
| 147 |
("google.com", "https://google.com/"), |
| 148 |
("google.com", "https://google.com"), |
| 149 |
("google.com", "https://google.com/abra/cadabra"), |
| 150 |
# Test comparison using default ports |
| 151 |
("google.com", "https://google.com:443/abracadabra"), |
| 152 |
], |
| 153 |
) |
| 154 |
def test_same_host_no_port_https(self, a: str, b: str) -> None: |
| 155 |
# This test was introduced in #801 to deal with the fact that urllib3 |
| 156 |
# never initializes ConnectionPool objects with port=None. |
| 157 |
with HTTPSConnectionPool(a) as c: |
| 158 |
assert c.is_same_host(b) |
| 159 |
|
| 160 |
@pytest.mark.parametrize( |
| 161 |
"host", |
| 162 |
[ |
| 163 |
"127.0.0.1\n", |
| 164 |
"127.0.0.1 ", |
| 165 |
"::1\n", |
| 166 |
"[::1]\n", |
| 167 |
], |
| 168 |
) |
| 169 |
def test_control_characters_in_host_raise(self, host: str) -> None: |
| 170 |
with pytest.raises(LocationParseError): |
| 171 |
HTTPConnectionPool(host) |
| 172 |
|
| 173 |
@pytest.mark.parametrize("host", ["foo%.example", "foo%zz.example"]) |
| 174 |
def test_malformed_percent_escapes_in_host_raise(self, host: str) -> None: |
| 175 |
with pytest.raises(LocationParseError): |
| 176 |
HTTPConnectionPool(host) |
| 177 |
|
| 178 |
@pytest.mark.parametrize( |
| 179 |
"host, expected_host, expected_tunnel_host", |
| 180 |
[ |
| 181 |
("EXAMPLE%2Ecom%2E", "example.com.", "example.com."), |
| 182 |
( |
| 183 |
"[2607:f8b0:4005:805::200e%25eth0]", |
| 184 |
"2607:f8b0:4005:805::200e%eth0", |
| 185 |
"[2607:f8b0:4005:805::200e%eth0]", |
| 186 |
), |
| 187 |
], |
| 188 |
) |
| 189 |
def test_host_and_tunnel_host_are_normalized( |
| 190 |
self, host: str, expected_host: str, expected_tunnel_host: str |
| 191 |
) -> None: |
| 192 |
with HTTPSConnectionPool(host) as pool: |
| 193 |
assert pool.host == expected_host |
| 194 |
assert pool._tunnel_host == expected_tunnel_host |
| 195 |
|
| 196 |
@pytest.mark.parametrize( |
| 197 |
"a, b", |
| 198 |
[ |
| 199 |
("google.com", "https://google.com/"), |
| 200 |
("yahoo.com", "http://google.com/"), |
| 201 |
("google.com", "https://google.net/"), |
| 202 |
("google.com", "http://google.com./"), |
| 203 |
], |
| 204 |
) |
| 205 |
def test_not_same_host_no_port_http(self, a: str, b: str) -> None: |
| 206 |
with HTTPConnectionPool(a) as c: |
| 207 |
assert not c.is_same_host(b) |
| 208 |
|
| 209 |
with HTTPConnectionPool(b) as c: |
| 210 |
assert not c.is_same_host(a) |
| 211 |
|
| 212 |
@pytest.mark.parametrize( |
| 213 |
"a, b", |
| 214 |
[ |
| 215 |
("google.com", "http://google.com/"), |
| 216 |
("yahoo.com", "https://google.com/"), |
| 217 |
("google.com", "https://google.net/"), |
| 218 |
("google.com", "https://google.com./"), |
| 219 |
], |
| 220 |
) |
| 221 |
def test_not_same_host_no_port_https(self, a: str, b: str) -> None: |
| 222 |
with HTTPSConnectionPool(a) as c: |
| 223 |
assert not c.is_same_host(b) |
| 224 |
|
| 225 |
with HTTPSConnectionPool(b) as c: |
| 226 |
assert not c.is_same_host(a) |
| 227 |
|
| 228 |
@pytest.mark.parametrize( |
| 229 |
"a, b", |
| 230 |
[ |
| 231 |
("%2Fvar%2Frun%2Fdocker.sock", "http+unix://%2Fvar%2Frun%2Fdocker.sock"), |
| 232 |
("%2Fvar%2Frun%2Fdocker.sock", "http+unix://%2Fvar%2Frun%2Fdocker.sock/"), |
| 233 |
( |
| 234 |
"%2Fvar%2Frun%2Fdocker.sock", |
| 235 |
"http+unix://%2Fvar%2Frun%2Fdocker.sock/abracadabra", |
| 236 |
), |
| 237 |
("%2Ftmp%2FTEST.sock", "http+unix://%2Ftmp%2FTEST.sock"), |
| 238 |
("%2Ftmp%2FTEST.sock", "http+unix://%2Ftmp%2FTEST.sock/"), |
| 239 |
("%2Ftmp%2FTEST.sock", "http+unix://%2Ftmp%2FTEST.sock/abracadabra"), |
| 240 |
], |
| 241 |
) |
| 242 |
def test_same_host_custom_protocol(self, a: str, b: str) -> None: |
| 243 |
with HTTPUnixConnectionPool(a) as c: |
| 244 |
assert c.is_same_host(b) |
| 245 |
|
| 246 |
@pytest.mark.parametrize( |
| 247 |
"a, b", |
| 248 |
[ |
| 249 |
("%2Ftmp%2Ftest.sock", "http+unix://%2Ftmp%2FTEST.sock"), |
| 250 |
("%2Ftmp%2Ftest.sock", "http+unix://%2Ftmp%2FTEST.sock/"), |
| 251 |
("%2Ftmp%2Ftest.sock", "http+unix://%2Ftmp%2FTEST.sock/abracadabra"), |
| 252 |
("%2Fvar%2Frun%2Fdocker.sock", "http+unix://%2Ftmp%2FTEST.sock"), |
| 253 |
], |
| 254 |
) |
| 255 |
def test_not_same_host_custom_protocol(self, a: str, b: str) -> None: |
| 256 |
with HTTPUnixConnectionPool(a) as c: |
| 257 |
assert not c.is_same_host(b) |
| 258 |
|
| 259 |
def test_same_host_port_zero(self) -> None: |
| 260 |
with HTTPConnectionPool("example.com", port=0) as c: |
| 261 |
assert c.is_same_host("http://example.com:0/") |
| 262 |
assert not c.is_same_host("http://example.com/") |
| 263 |
assert not c.is_same_host("https://example.com/") |
| 264 |
assert not c.is_same_host("http://example.com:80/") |
| 265 |
assert not c.is_same_host("https://example.com:443/") |
| 266 |
|
| 267 |
@pytest.mark.parametrize( |
| 268 |
"url, expected_port", |
| 269 |
[ |
| 270 |
("http://example.com:0/", 0), |
| 271 |
("https://example.com:0/", 0), |
| 272 |
("http://example.com/", 80), |
| 273 |
("https://example.com/", 443), |
| 274 |
("http://example.com:8080/", 8080), |
| 275 |
], |
| 276 |
) |
| 277 |
def test_connection_from_url_preserves_port_zero( |
| 278 |
self, url: str, expected_port: int |
| 279 |
) -> None: |
| 280 |
with connection_from_url(url) as c: |
| 281 |
assert c.port == expected_port |
| 282 |
|
| 283 |
def test_max_connections(self) -> None: |
| 284 |
with HTTPConnectionPool(host="localhost", maxsize=1, block=True) as pool: |
| 285 |
pool._get_conn(timeout=SHORT_TIMEOUT) |
| 286 |
|
| 287 |
with pytest.raises(EmptyPoolError): |
| 288 |
pool._get_conn(timeout=SHORT_TIMEOUT) |
| 289 |
|
| 290 |
with pytest.raises(EmptyPoolError): |
| 291 |
pool.request("GET", "/", pool_timeout=SHORT_TIMEOUT) |
| 292 |
|
| 293 |
assert pool.num_connections == 1 |
| 294 |
|
| 295 |
def test_put_conn_when_pool_is_full_nonblocking( |
| 296 |
self, caplog: pytest.LogCaptureFixture |
| 297 |
) -> None: |
| 298 |
""" |
| 299 |
If maxsize = n and we _put_conn n + 1 conns, the n + 1th conn will |
| 300 |
get closed and will not get added to the pool. |
| 301 |
""" |
| 302 |
with HTTPConnectionPool(host="localhost", maxsize=1, block=False) as pool: |
| 303 |
conn1 = pool._get_conn() |
| 304 |
# pool.pool is empty because we popped the one None that pool.pool was initialized with |
| 305 |
# but this pool._get_conn call will not raise EmptyPoolError because block is False |
| 306 |
conn2 = pool._get_conn() |
| 307 |
|
| 308 |
with patch.object(conn1, "close") as conn1_close: |
| 309 |
with patch.object(conn2, "close") as conn2_close: |
| 310 |
pool._put_conn(conn1) |
| 311 |
pool._put_conn(conn2) |
| 312 |
|
| 313 |
assert conn1_close.called is False |
| 314 |
assert conn2_close.called is True |
| 315 |
|
| 316 |
assert conn1 == pool._get_conn() |
| 317 |
assert conn2 != pool._get_conn() |
| 318 |
|
| 319 |
assert pool.num_connections == 3 |
| 320 |
assert "Connection pool is full, discarding connection" in caplog.text |
| 321 |
assert "Connection pool size: 1" in caplog.text |
| 322 |
|
| 323 |
def test_put_conn_when_pool_is_full_blocking(self) -> None: |
| 324 |
""" |
| 325 |
If maxsize = n and we _put_conn n + 1 conns, the n + 1th conn will |
| 326 |
cause a FullPoolError. |
| 327 |
""" |
| 328 |
with HTTPConnectionPool(host="localhost", maxsize=1, block=True) as pool: |
| 329 |
conn1 = pool._get_conn() |
| 330 |
conn2 = pool._new_conn() |
| 331 |
|
| 332 |
with patch.object(conn1, "close") as conn1_close: |
| 333 |
with patch.object(conn2, "close") as conn2_close: |
| 334 |
pool._put_conn(conn1) |
| 335 |
with pytest.raises(FullPoolError): |
| 336 |
pool._put_conn(conn2) |
| 337 |
|
| 338 |
assert conn1_close.called is False |
| 339 |
assert conn2_close.called is True |
| 340 |
|
| 341 |
assert conn1 == pool._get_conn() |
| 342 |
|
| 343 |
def test_urlopen_invalid_timeout_raises_value_error(self) -> None: |
| 344 |
with HTTPConnectionPool(host="localhost", maxsize=1, block=True) as pool: |
| 345 |
with pytest.raises( |
| 346 |
ValueError, |
| 347 |
match="Timeout value connect was 1, but it must be an int, float or None", |
| 348 |
): |
| 349 |
pool.urlopen("GET", "/", timeout="1") # type: ignore[arg-type] |
| 350 |
|
| 351 |
def test_put_conn_closed_pool(self) -> None: |
| 352 |
with HTTPConnectionPool(host="localhost", maxsize=1, block=True) as pool: |
| 353 |
conn1 = pool._get_conn() |
| 354 |
with patch.object(conn1, "close") as conn1_close: |
| 355 |
pool.close() |
| 356 |
|
| 357 |
assert pool.pool is None |
| 358 |
|
| 359 |
# Accessing pool.pool will raise AttributeError, which will get |
| 360 |
# caught and will close conn1 |
| 361 |
pool._put_conn(conn1) |
| 362 |
|
| 363 |
assert conn1_close.called is True |
| 364 |
|
| 365 |
def test_exception_str(self) -> None: |
| 366 |
assert ( |
| 367 |
str(EmptyPoolError(HTTPConnectionPool(host="localhost"), "Test.")) |
| 368 |
== "HTTPConnectionPool(host='localhost', port=None): Test." |
| 369 |
) |
| 370 |
|
| 371 |
def test_retry_exception_str(self) -> None: |
| 372 |
assert ( |
| 373 |
str(MaxRetryError(HTTPConnectionPool(host="localhost"), "Test.", None)) |
| 374 |
== "HTTPConnectionPool(host='localhost', port=None): " |
| 375 |
"Max retries exceeded with url: Test. (Caused by None)" |
| 376 |
) |
| 377 |
|
| 378 |
err = SocketError("Test") |
| 379 |
|
| 380 |
# using err.__class__ here, as socket.error is an alias for OSError |
| 381 |
# since Py3.3 and gets printed as this |
| 382 |
assert ( |
| 383 |
str(MaxRetryError(HTTPConnectionPool(host="localhost"), "Test.", err)) |
| 384 |
== "HTTPConnectionPool(host='localhost', port=None): " |
| 385 |
"Max retries exceeded with url: Test. " |
| 386 |
"(Caused by %r)" % err |
| 387 |
) |
| 388 |
|
| 389 |
def test_pool_size(self) -> None: |
| 390 |
POOL_SIZE = 1 |
| 391 |
with HTTPConnectionPool( |
| 392 |
host="localhost", maxsize=POOL_SIZE, block=True |
| 393 |
) as pool: |
| 394 |
|
| 395 |
def _test( |
| 396 |
exception: type[BaseException], |
| 397 |
expect: type[BaseException], |
| 398 |
reason: type[BaseException] | None = None, |
| 399 |
) -> None: |
| 400 |
with patch.object(pool, "_make_request", side_effect=exception()): |
| 401 |
with pytest.raises(expect) as excinfo: |
| 402 |
pool.request("GET", "/") |
| 403 |
if reason is not None: |
| 404 |
assert isinstance(excinfo.value.reason, reason) # type: ignore[attr-defined] |
| 405 |
assert pool.pool is not None |
| 406 |
assert pool.pool.qsize() == POOL_SIZE |
| 407 |
|
| 408 |
# Make sure that all of the exceptions return the connection |
| 409 |
# to the pool |
| 410 |
_test(BaseSSLError, MaxRetryError, SSLError) |
| 411 |
_test(CertificateError, MaxRetryError, SSLError) |
| 412 |
|
| 413 |
# The pool should never be empty, and with these two exceptions |
| 414 |
# being raised, a retry will be triggered, but that retry will |
| 415 |
# fail, eventually raising MaxRetryError, not EmptyPoolError |
| 416 |
# See: https://github.com/urllib3/urllib3/issues/76 |
| 417 |
with patch.object(pool, "_make_request", side_effect=HTTPException()): |
| 418 |
with pytest.raises(MaxRetryError): |
| 419 |
pool.request("GET", "/", retries=1, pool_timeout=SHORT_TIMEOUT) |
| 420 |
assert pool.pool is not None |
| 421 |
assert pool.pool.qsize() == POOL_SIZE |
| 422 |
|
| 423 |
def test_empty_does_not_put_conn(self) -> None: |
| 424 |
"""Do not put None back in the pool if the pool was empty""" |
| 425 |
|
| 426 |
with HTTPConnectionPool(host="localhost", maxsize=1, block=True) as pool: |
| 427 |
with patch.object( |
| 428 |
pool, "_get_conn", side_effect=EmptyPoolError(pool, "Pool is empty") |
| 429 |
): |
| 430 |
with patch.object( |
| 431 |
pool, |
| 432 |
"_put_conn", |
| 433 |
side_effect=AssertionError("Unexpected _put_conn"), |
| 434 |
): |
| 435 |
with pytest.raises(EmptyPoolError): |
| 436 |
pool.request("GET", "/") |
| 437 |
|
| 438 |
def test_assert_same_host(self) -> None: |
| 439 |
with connection_from_url("http://google.com:80") as c: |
| 440 |
with pytest.raises(HostChangedError): |
| 441 |
c.request("GET", "http://yahoo.com:80", assert_same_host=True) |
| 442 |
|
| 443 |
def test_pool_close(self) -> None: |
| 444 |
pool = connection_from_url("http://google.com:80") |
| 445 |
|
| 446 |
# Populate with some connections |
| 447 |
conn1 = pool._get_conn() |
| 448 |
conn2 = pool._get_conn() |
| 449 |
conn3 = pool._get_conn() |
| 450 |
pool._put_conn(conn1) |
| 451 |
pool._put_conn(conn2) |
| 452 |
|
| 453 |
old_pool_queue = pool.pool |
| 454 |
|
| 455 |
pool.close() |
| 456 |
assert pool.pool is None |
| 457 |
|
| 458 |
with pytest.raises(ClosedPoolError): |
| 459 |
pool._get_conn() |
| 460 |
|
| 461 |
pool._put_conn(conn3) |
| 462 |
|
| 463 |
with pytest.raises(ClosedPoolError): |
| 464 |
pool._get_conn() |
| 465 |
|
| 466 |
with pytest.raises(Empty): |
| 467 |
assert old_pool_queue is not None |
| 468 |
old_pool_queue.get(block=False) |
| 469 |
|
| 470 |
def test_pool_close_twice(self) -> None: |
| 471 |
pool = connection_from_url("http://google.com:80") |
| 472 |
|
| 473 |
# Populate with some connections |
| 474 |
conn1 = pool._get_conn() |
| 475 |
conn2 = pool._get_conn() |
| 476 |
pool._put_conn(conn1) |
| 477 |
pool._put_conn(conn2) |
| 478 |
|
| 479 |
pool.close() |
| 480 |
assert pool.pool is None |
| 481 |
|
| 482 |
try: |
| 483 |
pool.close() |
| 484 |
except AttributeError: |
| 485 |
pytest.fail("Pool of the ConnectionPool is None and has no attribute get.") |
| 486 |
|
| 487 |
def test_pool_timeouts(self) -> None: |
| 488 |
with HTTPConnectionPool(host="localhost") as pool: |
| 489 |
conn = pool._new_conn() |
| 490 |
assert conn.__class__ == HTTPConnection |
| 491 |
assert pool.timeout.__class__ == Timeout |
| 492 |
assert pool.timeout._read == _DEFAULT_TIMEOUT |
| 493 |
assert pool.timeout._connect == _DEFAULT_TIMEOUT |
| 494 |
assert pool.timeout.total is None |
| 495 |
|
| 496 |
pool = HTTPConnectionPool(host="localhost", timeout=SHORT_TIMEOUT) |
| 497 |
assert pool.timeout._read == SHORT_TIMEOUT |
| 498 |
assert pool.timeout._connect == SHORT_TIMEOUT |
| 499 |
assert pool.timeout.total is None |
| 500 |
|
| 501 |
def test_no_host(self) -> None: |
| 502 |
with pytest.raises(LocationValueError): |
| 503 |
HTTPConnectionPool(None) # type: ignore[arg-type] |
| 504 |
|
| 505 |
def test_contextmanager(self) -> None: |
| 506 |
with connection_from_url("http://google.com:80") as pool: |
| 507 |
# Populate with some connections |
| 508 |
conn1 = pool._get_conn() |
| 509 |
conn2 = pool._get_conn() |
| 510 |
conn3 = pool._get_conn() |
| 511 |
pool._put_conn(conn1) |
| 512 |
pool._put_conn(conn2) |
| 513 |
|
| 514 |
old_pool_queue = pool.pool |
| 515 |
|
| 516 |
assert pool.pool is None |
| 517 |
with pytest.raises(ClosedPoolError): |
| 518 |
pool._get_conn() |
| 519 |
|
| 520 |
pool._put_conn(conn3) |
| 521 |
with pytest.raises(ClosedPoolError): |
| 522 |
pool._get_conn() |
| 523 |
with pytest.raises(Empty): |
| 524 |
assert old_pool_queue is not None |
| 525 |
old_pool_queue.get(block=False) |
| 526 |
|
| 527 |
def test_url_from_pool(self) -> None: |
| 528 |
with connection_from_url("http://google.com:80") as pool: |
| 529 |
path = "path?query=foo" |
| 530 |
assert f"http://google.com:80/{path}" == _url_from_pool(pool, path) |
| 531 |
|
| 532 |
def test_ca_certs_default_cert_required(self) -> None: |
| 533 |
with connection_from_url("https://google.com:80", ca_certs=DEFAULT_CA) as pool: |
| 534 |
conn = pool._get_conn() |
| 535 |
assert conn.cert_reqs == ssl.CERT_REQUIRED # type: ignore[attr-defined] |
| 536 |
|
| 537 |
def test_cleanup_on_extreme_connection_error(self) -> None: |
| 538 |
""" |
| 539 |
This test validates that we clean up properly even on exceptions that |
| 540 |
we'd not otherwise catch, i.e. those that inherit from BaseException |
| 541 |
like KeyboardInterrupt or gevent.Timeout. See #805 for more details. |
| 542 |
""" |
| 543 |
|
| 544 |
class RealBad(BaseException): |
| 545 |
pass |
| 546 |
|
| 547 |
def kaboom(*args: typing.Any, **kwargs: typing.Any) -> None: |
| 548 |
raise RealBad() |
| 549 |
|
| 550 |
with connection_from_url("http://localhost:80") as c: |
| 551 |
with patch.object(c, "_make_request", kaboom): |
| 552 |
assert c.pool is not None |
| 553 |
initial_pool_size = c.pool.qsize() |
| 554 |
|
| 555 |
try: |
| 556 |
# We need to release_conn this way or we'd put it away |
| 557 |
# regardless. |
| 558 |
c.urlopen("GET", "/", release_conn=False) |
| 559 |
except RealBad: |
| 560 |
pass |
| 561 |
|
| 562 |
new_pool_size = c.pool.qsize() |
| 563 |
assert initial_pool_size == new_pool_size |
| 564 |
|
| 565 |
def test_release_conn_param_is_respected_after_http_error_retry(self) -> None: |
| 566 |
"""For successful ```urlopen(release_conn=False)```, |
| 567 |
the connection isn't released, even after a retry. |
| 568 |
|
| 569 |
This is a regression test for issue #651 [1], where the connection |
| 570 |
would be released if the initial request failed, even if a retry |
| 571 |
succeeded. |
| 572 |
|
| 573 |
[1] <https://github.com/urllib3/urllib3/issues/651> |
| 574 |
""" |
| 575 |
|
| 576 |
class _raise_once_make_request_function: |
| 577 |
"""Callable that can mimic `_make_request()`. |
| 578 |
|
| 579 |
Raises the given exception on its first call, but returns a |
| 580 |
successful response on subsequent calls. |
| 581 |
""" |
| 582 |
|
| 583 |
def __init__( |
| 584 |
self, ex: type[BaseException], pool: HTTPConnectionPool |
| 585 |
) -> None: |
| 586 |
super().__init__() |
| 587 |
self._ex: type[BaseException] | None = ex |
| 588 |
self._pool = pool |
| 589 |
|
| 590 |
def __call__( |
| 591 |
self, |
| 592 |
conn: HTTPConnection, |
| 593 |
method: str, |
| 594 |
url: str, |
| 595 |
*args: typing.Any, |
| 596 |
retries: Retry, |
| 597 |
**kwargs: typing.Any, |
| 598 |
) -> HTTPResponse: |
| 599 |
if self._ex: |
| 600 |
ex, self._ex = self._ex, None |
| 601 |
raise ex() |
| 602 |
httplib_response = httplib.HTTPResponse(MockSock) # type: ignore[arg-type] |
| 603 |
httplib_response.fp = MockChunkedEncodingResponse([b"f", b"o", b"o"]) # type: ignore[assignment] |
| 604 |
httplib_response.headers = httplib_response.msg = httplib.HTTPMessage() |
| 605 |
|
| 606 |
response_conn: HTTPConnection | None = kwargs.get("response_conn") |
| 607 |
|
| 608 |
response = HTTPResponse( |
| 609 |
body=httplib_response, |
| 610 |
headers=httplib_response.headers, # type: ignore[arg-type] |
| 611 |
status=httplib_response.status, |
| 612 |
version=httplib_response.version, |
| 613 |
reason=httplib_response.reason, |
| 614 |
original_response=httplib_response, |
| 615 |
retries=retries, |
| 616 |
request_method=method, |
| 617 |
request_url=url, |
| 618 |
preload_content=False, |
| 619 |
connection=response_conn, |
| 620 |
pool=self._pool, |
| 621 |
) |
| 622 |
return response |
| 623 |
|
| 624 |
def _test(exception: type[BaseException]) -> None: |
| 625 |
with HTTPConnectionPool(host="localhost", maxsize=1, block=True) as pool: |
| 626 |
# Verify that the request succeeds after two attempts, and that the |
| 627 |
# connection is left on the response object, instead of being |
| 628 |
# released back into the pool. |
| 629 |
with patch.object( |
| 630 |
pool, |
| 631 |
"_make_request", |
| 632 |
_raise_once_make_request_function(exception, pool), |
| 633 |
): |
| 634 |
response = pool.urlopen( |
| 635 |
"GET", |
| 636 |
"/", |
| 637 |
retries=1, |
| 638 |
release_conn=False, |
| 639 |
preload_content=False, |
| 640 |
chunked=True, |
| 641 |
) |
| 642 |
assert pool.pool is not None |
| 643 |
assert pool.pool.qsize() == 0 |
| 644 |
assert pool.num_connections == 2 |
| 645 |
assert response.connection is not None |
| 646 |
|
| 647 |
response.release_conn() |
| 648 |
assert pool.pool.qsize() == 1 |
| 649 |
assert response.connection is None |
| 650 |
|
| 651 |
# Run the test case for all the retriable exceptions. |
| 652 |
_test(TimeoutError) |
| 653 |
_test(HTTPException) |
| 654 |
_test(SocketError) |
| 655 |
_test(ProtocolError) |
| 656 |
|
| 657 |
def test_retry_with_body_that_has_tell_but_no_seek(self) -> None: |
| 658 |
""" |
| 659 |
This is a regression test for issue #3779 [1] where, if |
| 660 |
seek is missing from body and we retried, we previously raised |
| 661 |
a confusing error. |
| 662 |
|
| 663 |
[1] <https://github.com/urllib3/urllib3/issues/3779> |
| 664 |
""" |
| 665 |
|
| 666 |
class TellableStream: |
| 667 |
"""A stream-like object with tell() and read() but no seek().""" |
| 668 |
|
| 669 |
def __init__(self, data: bytes) -> None: |
| 670 |
self._data = data |
| 671 |
self._pos = 0 |
| 672 |
|
| 673 |
def read(self, n: int = -1) -> bytes: |
| 674 |
if n == -1: |
| 675 |
chunk = self._data[self._pos :] |
| 676 |
self._pos = len(self._data) |
| 677 |
else: |
| 678 |
chunk = self._data[self._pos : self._pos + n] |
| 679 |
self._pos += len(chunk) |
| 680 |
return chunk |
| 681 |
|
| 682 |
def tell(self) -> int: |
| 683 |
return self._pos |
| 684 |
|
| 685 |
body = TellableStream(b"hello world") |
| 686 |
|
| 687 |
with HTTPConnectionPool(host="localhost", maxsize=1) as pool: |
| 688 |
with patch.object( |
| 689 |
pool, |
| 690 |
"_make_request", |
| 691 |
side_effect=OSError("connection reset"), |
| 692 |
): |
| 693 |
with pytest.raises( |
| 694 |
UnrewindableBodyError, match="body does not implement seek" |
| 695 |
): |
| 696 |
pool.urlopen( |
| 697 |
"POST", |
| 698 |
"/", |
| 699 |
body=body, # type: ignore[arg-type] |
| 700 |
retries=Retry(total=2, allowed_methods=["POST"]), |
| 701 |
body_pos=None, |
| 702 |
) |
| 703 |
|
| 704 |
def test_read_timeout_0_does_not_raise_bad_status_line_error(self) -> None: |
| 705 |
with HTTPConnectionPool(host="localhost", maxsize=1) as pool: |
| 706 |
conn = Mock(spec=HTTPConnection) |
| 707 |
# Needed to tell the pool that the connection is alive. |
| 708 |
conn.is_closed = False |
| 709 |
with patch.object(Timeout, "read_timeout", 0): |
| 710 |
timeout = Timeout(1, 1, 1) |
| 711 |
with pytest.raises(ReadTimeoutError): |
| 712 |
pool._make_request(conn, "", "", timeout=timeout) |
| 713 |
|
| 714 |
def test_default_queuecls_uses_current_lifoqueue( |
| 715 |
self, monkeypatch: pytest.MonkeyPatch |
| 716 |
) -> None: |
| 717 |
original_queue_cls = HTTPConnectionPool.QueueCls |
| 718 |
|
| 719 |
class PatchedLifoQueue(queue.LifoQueue[typing.Any]): |
| 720 |
pass |
| 721 |
|
| 722 |
monkeypatch.setattr(queue, "LifoQueue", PatchedLifoQueue) |
| 723 |
|
| 724 |
assert HTTPConnectionPool.QueueCls is original_queue_cls |
| 725 |
|
| 726 |
with HTTPConnectionPool(host="localhost", maxsize=1) as pool: |
| 727 |
assert isinstance(pool.pool, PatchedLifoQueue) |
| 728 |
|
| 729 |
def test_queuecls_override_is_preserved( |
| 730 |
self, monkeypatch: pytest.MonkeyPatch |
| 731 |
) -> None: |
| 732 |
class CustomLifoQueue(queue.LifoQueue[typing.Any]): |
| 733 |
pass |
| 734 |
|
| 735 |
class PatchedLifoQueue(queue.LifoQueue[typing.Any]): |
| 736 |
pass |
| 737 |
|
| 738 |
class CustomQueueConnectionPool(HTTPConnectionPool): |
| 739 |
QueueCls = CustomLifoQueue |
| 740 |
|
| 741 |
monkeypatch.setattr(queue, "LifoQueue", PatchedLifoQueue) |
| 742 |
|
| 743 |
with CustomQueueConnectionPool(host="localhost", maxsize=1) as pool: |
| 744 |
assert isinstance(pool.pool, CustomLifoQueue) |
| 745 |
|
| 746 |
@pytest.mark.parametrize( |
| 747 |
"path", |
| 748 |
[ |
| 749 |
"//v:h", |
| 750 |
"//host:8080/path", |
| 751 |
"//host/path", |
| 752 |
"//v:h?key=val", |
| 753 |
"/", |
| 754 |
], |
| 755 |
) |
| 756 |
def test_paths_arent_parsed_as_urls(self, path: str) -> None: |
| 757 |
"""See https://github.com/urllib3/urllib3/issues/3352.""" |
| 758 |
with HTTPConnectionPool(host="localhost", port=80) as pool: |
| 759 |
with patch.object( |
| 760 |
pool, "_make_request", return_value=HTTPResponse(status=200) |
| 761 |
) as mock_request: |
| 762 |
pool.urlopen("GET", path) |
| 763 |
|
| 764 |
# Verify the URL isn't mangled |
| 765 |
actual_url = mock_request.call_args[0][2] |
| 766 |
assert actual_url == path |
| 767 |
|
| 768 |
@pytest.mark.parametrize( |
| 769 |
("target_url", "expected_url"), |
| 770 |
[ |
| 771 |
pytest.param( |
| 772 |
"http://localhost/path#marker=value", |
| 773 |
"http://localhost/path", |
| 774 |
id="fragment-after-path", |
| 775 |
), |
| 776 |
pytest.param( |
| 777 |
"http://localhost/path?x=1#marker=value", |
| 778 |
"http://localhost/path?x=1", |
| 779 |
id="fragment-after-query", |
| 780 |
), |
| 781 |
pytest.param( |
| 782 |
"http://localhost/#marker=value", |
| 783 |
"http://localhost/", |
| 784 |
id="root-path-with-fragment", |
| 785 |
), |
| 786 |
pytest.param( |
| 787 |
"http://localhost/path?x=1#", |
| 788 |
"http://localhost/path?x=1", |
| 789 |
id="empty-fragment", |
| 790 |
), |
| 791 |
], |
| 792 |
) |
| 793 |
def test_absolute_url_request_target_strips_fragment( |
| 794 |
self, target_url: str, expected_url: str |
| 795 |
) -> None: |
| 796 |
with HTTPConnectionPool(host="localhost", port=80) as pool: |
| 797 |
with patch.object( |
| 798 |
pool, "_make_request", return_value=HTTPResponse(status=200) |
| 799 |
) as mock_request: |
| 800 |
pool.urlopen("GET", target_url) |
| 801 |
|
| 802 |
actual_url = mock_request.call_args[0][2] |
| 803 |
assert actual_url == expected_url |
| 804 |
|
| 805 |
def test_absolute_redirect_request_target_strips_fragment(self) -> None: |
| 806 |
redirect_response = HTTPResponse( |
| 807 |
status=302, |
| 808 |
headers={"location": "http://localhost/next?x=1#marker=value"}, |
| 809 |
) |
| 810 |
final_response = HTTPResponse(status=200) |
| 811 |
|
| 812 |
with HTTPConnectionPool(host="localhost", port=80) as pool: |
| 813 |
with patch.object( |
| 814 |
pool, |
| 815 |
"_make_request", |
| 816 |
side_effect=[redirect_response, final_response], |
| 817 |
) as mock_request: |
| 818 |
response = pool.urlopen("GET", "/", retries=1) |
| 819 |
|
| 820 |
requested_urls = [call.args[2] for call in mock_request.call_args_list] |
| 821 |
|
| 822 |
assert response.status == 200 |
| 823 |
assert requested_urls == ["/", "http://localhost/next?x=1"] |