Debian Codegraph @

test/test_poolmanager.py

raw
1 from __future__ import annotations
2
3 import gc
4 import socket
5 from test import resolvesLocalhostFQDN
6 from unittest import mock
7 from unittest.mock import MagicMock, patch
8
9 import pytest
10
11 from urllib3 import connection_from_url
12 from urllib3.connectionpool import HTTPSConnectionPool
13 from urllib3.exceptions import LocationValueError
14 from urllib3.poolmanager import (
15 _DEFAULT_BLOCKSIZE,
16 PoolKey,
17 PoolManager,
18 key_fn_by_scheme,
19 )
20 from urllib3.util import retry, timeout
21 from urllib3.util.url import Url
22
23
24 class TestPoolManager:
25 @resolvesLocalhostFQDN()
26 def test_same_url(self) -> None:
27 # Convince ourselves that normally we don't get the same object
28 conn1 = connection_from_url("http://localhost:8081/foo")
29 conn2 = connection_from_url("http://localhost:8081/bar")
30
31 assert conn1 != conn2
32
33 # Now try again using the PoolManager
34 p = PoolManager(1)
35
36 conn1 = p.connection_from_url("http://localhost:8081/foo")
37 conn2 = p.connection_from_url("http://localhost:8081/bar")
38
39 assert conn1 == conn2
40
41 # Ensure that FQDNs are handled separately from relative domains
42 p = PoolManager(2)
43
44 conn1 = p.connection_from_url("http://localhost.:8081/foo")
45 conn2 = p.connection_from_url("http://localhost:8081/bar")
46
47 assert conn1 != conn2
48
49 def test_many_urls(self) -> None:
50 urls = [
51 "http://localhost:8081/foo",
52 "http://www.google.com/mail",
53 "http://localhost:8081/bar",
54 "https://www.google.com/",
55 "https://www.google.com/mail",
56 "http://yahoo.com",
57 "http://bing.com",
58 "http://yahoo.com/",
59 ]
60
61 connections = set()
62
63 p = PoolManager(10)
64
65 for url in urls:
66 conn = p.connection_from_url(url)
67 connections.add(conn)
68
69 assert len(connections) == 5
70
71 def test_manager_clear(self) -> None:
72 p = PoolManager(5)
73
74 p.connection_from_url("http://google.com")
75 assert len(p.pools) == 1
76
77 p.clear()
78 assert len(p.pools) == 0
79
80 @pytest.mark.parametrize("url", ["http://@", None])
81 def test_nohost(self, url: str | None) -> None:
82 p = PoolManager(5)
83 with pytest.raises(LocationValueError):
84 p.connection_from_url(url=url) # type: ignore[arg-type]
85
86 def test_contextmanager(self) -> None:
87 with PoolManager(1) as p:
88 p.connection_from_url("http://google.com")
89 assert len(p.pools) == 1
90
91 assert len(p.pools) == 0
92
93 def test_http_pool_key_fields(self) -> None:
94 """Assert the HTTPPoolKey fields are honored when selecting a pool."""
95 connection_pool_kw = {
96 "timeout": timeout.Timeout(3.14),
97 "retries": retry.Retry(total=6, connect=2),
98 "block": True,
99 "source_address": "127.0.0.1",
100 "blocksize": _DEFAULT_BLOCKSIZE + 1,
101 }
102 p = PoolManager()
103 conn_pools = [
104 p.connection_from_url("http://example.com/"),
105 p.connection_from_url("http://example.com:8000/"),
106 p.connection_from_url("http://other.example.com/"),
107 ]
108
109 for key, value in connection_pool_kw.items():
110 p.connection_pool_kw[key] = value
111 conn_pools.append(p.connection_from_url("http://example.com/"))
112
113 assert all(
114 x is not y
115 for i, x in enumerate(conn_pools)
116 for j, y in enumerate(conn_pools)
117 if i != j
118 )
119 assert all(isinstance(key, PoolKey) for key in p.pools.keys())
120
121 def test_https_pool_key_fields(self) -> None:
122 """Assert the HTTPSPoolKey fields are honored when selecting a pool."""
123 connection_pool_kw = {
124 "timeout": timeout.Timeout(3.14),
125 "retries": retry.Retry(total=6, connect=2),
126 "block": True,
127 "source_address": "127.0.0.1",
128 "key_file": "/root/totally_legit.key",
129 "cert_file": "/root/totally_legit.crt",
130 "cert_reqs": "CERT_REQUIRED",
131 "ca_certs": "/root/path_to_pem",
132 "ssl_version": "SSLv23_METHOD",
133 "blocksize": _DEFAULT_BLOCKSIZE + 1,
134 }
135 p = PoolManager()
136 conn_pools = [
137 p.connection_from_url("https://example.com/"),
138 p.connection_from_url("https://example.com:4333/"),
139 p.connection_from_url("https://other.example.com/"),
140 ]
141 # Asking for a connection pool with the same key should give us an
142 # existing pool.
143 dup_pools = []
144
145 for key, value in connection_pool_kw.items():
146 p.connection_pool_kw[key] = value
147 conn_pools.append(p.connection_from_url("https://example.com/"))
148 dup_pools.append(p.connection_from_url("https://example.com/"))
149
150 assert all(
151 x is not y
152 for i, x in enumerate(conn_pools)
153 for j, y in enumerate(conn_pools)
154 if i != j
155 )
156 assert all(pool in conn_pools for pool in dup_pools)
157 assert all(isinstance(key, PoolKey) for key in p.pools.keys())
158
159 def test_default_pool_key_funcs_copy(self) -> None:
160 """Assert each PoolManager gets a copy of ``pool_keys_by_scheme``."""
161 p = PoolManager()
162 assert p.key_fn_by_scheme == p.key_fn_by_scheme
163 assert p.key_fn_by_scheme is not key_fn_by_scheme
164
165 def test_pools_keyed_with_from_host(self) -> None:
166 """Assert pools are still keyed correctly with connection_from_host."""
167 ssl_kw = {
168 "key_file": "/root/totally_legit.key",
169 "cert_file": "/root/totally_legit.crt",
170 "cert_reqs": "CERT_REQUIRED",
171 "ca_certs": "/root/path_to_pem",
172 "ssl_version": "SSLv23_METHOD",
173 }
174 p = PoolManager(5, **ssl_kw) # type: ignore[arg-type]
175 conns = [p.connection_from_host("example.com", 443, scheme="https")]
176
177 for k in ssl_kw:
178 p.connection_pool_kw[k] = "newval"
179 conns.append(p.connection_from_host("example.com", 443, scheme="https"))
180
181 assert all(
182 x is not y
183 for i, x in enumerate(conns)
184 for j, y in enumerate(conns)
185 if i != j
186 )
187
188 def test_https_connection_from_url_case_insensitive(self) -> None:
189 """Assert scheme case is ignored when pooling HTTPS connections."""
190 p = PoolManager()
191 pool = p.connection_from_url("https://example.com/")
192 other_pool = p.connection_from_url("HTTPS://EXAMPLE.COM/")
193
194 assert 1 == len(p.pools)
195 assert pool is other_pool
196 assert all(isinstance(key, PoolKey) for key in p.pools.keys())
197
198 def test_https_connection_from_host_case_insensitive(self) -> None:
199 """Assert scheme case is ignored when getting the https key class."""
200 p = PoolManager()
201 pool = p.connection_from_host("example.com", scheme="https")
202 other_pool = p.connection_from_host("EXAMPLE.COM", scheme="HTTPS")
203
204 assert 1 == len(p.pools)
205 assert pool is other_pool
206 assert all(isinstance(key, PoolKey) for key in p.pools.keys())
207
208 def test_https_connection_from_context_case_insensitive(self) -> None:
209 """Assert scheme case is ignored when getting the https key class."""
210 p = PoolManager()
211 context = {"scheme": "https", "host": "example.com", "port": "443"}
212 other_context = {"scheme": "HTTPS", "host": "EXAMPLE.COM", "port": "443"}
213 pool = p.connection_from_context(context)
214 other_pool = p.connection_from_context(other_context)
215
216 assert 1 == len(p.pools)
217 assert pool is other_pool
218 assert all(isinstance(key, PoolKey) for key in p.pools.keys())
219
220 def test_http_connection_from_url_case_insensitive(self) -> None:
221 """Assert scheme case is ignored when pooling HTTP connections."""
222 p = PoolManager()
223 pool = p.connection_from_url("http://example.com/")
224 other_pool = p.connection_from_url("HTTP://EXAMPLE.COM/")
225
226 assert 1 == len(p.pools)
227 assert pool is other_pool
228 assert all(isinstance(key, PoolKey) for key in p.pools.keys())
229
230 def test_http_connection_from_host_case_insensitive(self) -> None:
231 """Assert scheme case is ignored when getting the https key class."""
232 p = PoolManager()
233 pool = p.connection_from_host("example.com", scheme="http")
234 other_pool = p.connection_from_host("EXAMPLE.COM", scheme="HTTP")
235
236 assert 1 == len(p.pools)
237 assert pool is other_pool
238 assert all(isinstance(key, PoolKey) for key in p.pools.keys())
239
240 def test_assert_hostname_and_fingerprint_flag(self) -> None:
241 """Assert that pool manager can accept hostname and fingerprint flags."""
242 fingerprint = "92:81:FE:85:F7:0C:26:60:EC:D6:B3:BF:93:CF:F9:71:CC:07:7D:0A"
243 p = PoolManager(assert_hostname=True, assert_fingerprint=fingerprint)
244 pool = p.connection_from_url("https://example.com/")
245 assert 1 == len(p.pools)
246 assert isinstance(pool, HTTPSConnectionPool)
247 assert pool.assert_hostname
248 assert fingerprint == pool.assert_fingerprint
249
250 def test_http_connection_from_context_case_insensitive(self) -> None:
251 """Assert scheme case is ignored when getting the https key class."""
252 p = PoolManager()
253 context = {"scheme": "http", "host": "example.com", "port": "8080"}
254 other_context = {"scheme": "HTTP", "host": "EXAMPLE.COM", "port": "8080"}
255 pool = p.connection_from_context(context)
256 other_pool = p.connection_from_context(other_context)
257
258 assert 1 == len(p.pools)
259 assert pool is other_pool
260 assert all(isinstance(key, PoolKey) for key in p.pools.keys())
261
262 @patch("urllib3.poolmanager.PoolManager.connection_from_host")
263 def test_deprecated_no_scheme(self, connection_from_host: mock.MagicMock) -> None:
264 # Don't actually make a network connection, just verify the FutureWarning
265 connection_from_host.side_effect = ConnectionError("Not attempting connection")
266 p = PoolManager()
267
268 with pytest.warns(FutureWarning) as records:
269 with pytest.raises(ConnectionError):
270 p.request(method="GET", url="evil.com://good.com")
271
272 msg = (
273 "URLs without a scheme (ie 'https://') are deprecated and will raise an error "
274 "in urllib3 v3.0. To avoid this FutureWarning ensure all URLs "
275 "start with 'https://' or 'http://'. Read more in this issue: "
276 "https://github.com/urllib3/urllib3/issues/2920"
277 )
278
279 assert len(records) == 1
280 assert isinstance(records[0].message, FutureWarning)
281 assert records[0].message.args[0] == msg
282
283 @patch("urllib3.poolmanager.PoolManager.connection_from_pool_key")
284 def test_connection_from_context_strict_param(
285 self, connection_from_pool_key: mock.MagicMock
286 ) -> None:
287 p = PoolManager()
288 context = {
289 "scheme": "http",
290 "host": "example.com",
291 "port": 8080,
292 "strict": True,
293 }
294 with pytest.warns(FutureWarning) as records:
295 p.connection_from_context(context)
296
297 msg = (
298 "The 'strict' parameter is no longer needed on Python 3+. "
299 "This will raise an error in urllib3 v3.0."
300 )
301 record = records[0]
302 assert isinstance(record.message, Warning)
303 assert record.message.args[0] == msg
304
305 _, kwargs = connection_from_pool_key.call_args
306 assert kwargs["request_context"] == {
307 "scheme": "http",
308 "host": "example.com",
309 "port": 8080,
310 }
311
312 def test_custom_pool_key(self) -> None:
313 """Assert it is possible to define a custom key function."""
314 p = PoolManager(10)
315
316 p.key_fn_by_scheme["http"] = lambda x: tuple(x["key"]) # type: ignore[assignment]
317 pool1 = p.connection_from_url(
318 "http://example.com", pool_kwargs={"key": "value"}
319 )
320 pool2 = p.connection_from_url(
321 "http://example.com", pool_kwargs={"key": "other"}
322 )
323 pool3 = p.connection_from_url(
324 "http://example.com", pool_kwargs={"key": "value", "x": "y"}
325 )
326
327 assert 2 == len(p.pools)
328 assert pool1 is pool3
329 assert pool1 is not pool2
330
331 def test_override_pool_kwargs_url(self) -> None:
332 """Assert overriding pool kwargs works with connection_from_url."""
333 p = PoolManager()
334 pool_kwargs = {"retries": 100, "block": True}
335
336 default_pool = p.connection_from_url("http://example.com/")
337 override_pool = p.connection_from_url(
338 "http://example.com/", pool_kwargs=pool_kwargs
339 )
340
341 assert retry.Retry.DEFAULT == default_pool.retries
342 assert not default_pool.block
343
344 assert 100 == override_pool.retries
345 assert override_pool.block
346
347 def test_override_pool_kwargs_host(self) -> None:
348 """Assert overriding pool kwargs works with connection_from_host"""
349 p = PoolManager()
350 pool_kwargs = {"retries": 100, "block": True}
351
352 default_pool = p.connection_from_host("example.com", scheme="http")
353 override_pool = p.connection_from_host(
354 "example.com", scheme="http", pool_kwargs=pool_kwargs
355 )
356
357 assert retry.Retry.DEFAULT == default_pool.retries
358 assert not default_pool.block
359
360 assert 100 == override_pool.retries
361 assert override_pool.block
362
363 def test_pool_kwargs_socket_options(self) -> None:
364 """Assert passing socket options works with connection_from_host"""
365 p = PoolManager(socket_options=[])
366 override_opts = [
367 (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1),
368 (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),
369 ]
370 pool_kwargs = {"socket_options": override_opts}
371
372 default_pool = p.connection_from_host("example.com", scheme="http")
373 override_pool = p.connection_from_host(
374 "example.com", scheme="http", pool_kwargs=pool_kwargs
375 )
376
377 assert default_pool.conn_kw["socket_options"] == []
378 assert override_pool.conn_kw["socket_options"] == override_opts
379
380 def test_merge_pool_kwargs(self) -> None:
381 """Assert _merge_pool_kwargs works in the happy case"""
382 retries = retry.Retry(total=100)
383 p = PoolManager(retries=retries)
384 merged = p._merge_pool_kwargs({"new_key": "value"})
385 assert {"retries": retries, "new_key": "value"} == merged
386
387 def test_merge_pool_kwargs_none(self) -> None:
388 """Assert false-y values to _merge_pool_kwargs result in defaults"""
389 p = PoolManager(retries=100)
390 merged = p._merge_pool_kwargs({})
391 assert p.connection_pool_kw == merged
392 merged = p._merge_pool_kwargs(None)
393 assert p.connection_pool_kw == merged
394
395 def test_merge_pool_kwargs_remove_key(self) -> None:
396 """Assert keys can be removed with _merge_pool_kwargs"""
397 p = PoolManager(retries=100)
398 merged = p._merge_pool_kwargs({"retries": None})
399 assert "retries" not in merged
400
401 def test_merge_pool_kwargs_invalid_key(self) -> None:
402 """Assert removing invalid keys with _merge_pool_kwargs doesn't break"""
403 p = PoolManager(retries=100)
404 merged = p._merge_pool_kwargs({"invalid_key": None})
405 assert p.connection_pool_kw == merged
406
407 def test_pool_manager_no_url_absolute_form(self) -> None:
408 """Valides we won't send a request with absolute form without a proxy"""
409 p = PoolManager()
410 assert p._proxy_requires_url_absolute_form(Url("http://example.com")) is False
411 assert p._proxy_requires_url_absolute_form(Url("https://example.com")) is False
412
413 @pytest.mark.parametrize(
414 "input_blocksize,expected_blocksize",
415 [
416 (_DEFAULT_BLOCKSIZE, _DEFAULT_BLOCKSIZE),
417 (None, _DEFAULT_BLOCKSIZE),
418 (8192, 8192),
419 ],
420 )
421 def test_poolmanager_blocksize(
422 self, input_blocksize: int, expected_blocksize: int
423 ) -> None:
424 """Assert PoolManager sets blocksize properly"""
425 p = PoolManager()
426
427 pool_blocksize = p.connection_from_url(
428 "http://example.com", {"blocksize": input_blocksize}
429 )
430 assert pool_blocksize.conn_kw["blocksize"] == expected_blocksize
431 assert pool_blocksize._get_conn().blocksize == expected_blocksize
432
433 @pytest.mark.parametrize(
434 "url",
435 [
436 "[a::b%zone]",
437 "[a::b%25zone]",
438 "http://[a::b%zone]",
439 "http://[a::b%25zone]",
440 ],
441 )
442 @patch("urllib3.util.connection.create_connection")
443 def test_e2e_connect_to_ipv6_scoped(
444 self, create_connection: MagicMock, url: str
445 ) -> None:
446 """Checks that IPv6 scoped addresses are properly handled end-to-end.
447
448 This is not strictly speaking a pool manager unit test - this test
449 lives here in absence of a better code location for e2e/integration
450 tests.
451 """
452 p = PoolManager()
453 conn_pool = p.connection_from_url(url)
454 conn = conn_pool._get_conn()
455 conn.connect()
456
457 assert create_connection.call_args[0][0] == ("a::b%zone", 80)
458
459 @patch("urllib3.connection.ssl_wrap_socket")
460 @patch("urllib3.util.connection.create_connection")
461 def test_e2e_connect_to_ipv6_scoped_tls(
462 self, create_connection: MagicMock, ssl_wrap_socket: MagicMock
463 ) -> None:
464 p = PoolManager()
465 conn_pool = p.connection_from_url(
466 "https://[a::b%zone]", pool_kwargs={"assert_hostname": False}
467 )
468 conn = conn_pool._get_conn()
469 conn.connect()
470
471 assert ssl_wrap_socket.call_args[1]["server_hostname"] == "a::b"
472
473 def test_thread_safty(self) -> None:
474 pool_manager = PoolManager(num_pools=2)
475
476 # thread 1 gets a pool for host x
477 pool_1 = pool_manager.connection_from_url("http://host_x:80/")
478
479 # thread 2 gets a pool for host y
480 pool_2 = pool_manager.connection_from_url("http://host_y:80/")
481
482 # thread 3 gets a pool for host z
483 pool_3 = pool_manager.connection_from_url("http://host_z:80")
484
485 # None of the pools should be closed, since all of them are referenced.
486 assert pool_1.pool is not None
487 assert pool_2.pool is not None
488 assert pool_3.pool is not None
489
490 conn_queue = pool_1.pool
491 assert conn_queue.qsize() > 0
492
493 # thread 1 stops.
494 del pool_1
495 gc.collect()
496
497 # Connection should be closed, because reference to pool_1 is gone.
498 assert conn_queue.qsize() == 0