Debian Codegraph @

test/with_dummyserver/test_connectionpool.py

raw
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 @pytest.mark.parametrize("chunked_via", ["kwarg", "header"])
542 def test_303_redirect_makes_request_lose_body_framing(
543 self, chunked_via: str
544 ) -> None:
545 # The body is dropped, so the redirected GET must not keep announcing
546 # a chunked body that it is never going to send.
547 request_headers: dict[str, str] = {}
548 kw: dict[str, typing.Any] = {}
549 if chunked_via == "kwarg":
550 kw["chunked"] = True
551 else:
552 request_headers["Transfer-Encoding"] = "chunked"
553 with HTTPConnectionPool(self.host, self.port) as pool:
554 response = pool.request(
555 "POST",
556 "/redirect?target=/headers_and_params",
557 body=iter([b"xxxxxxxx"]),
558 headers=request_headers,
559 **kw,
560 )
561 headers = HTTPHeaderDict(response.json()["headers"])
562 assert "Transfer-Encoding" not in headers
563 assert "Content-Length" not in headers
564
565 def test_bad_connect(self) -> None:
566 with HTTPConnectionPool("badhost.invalid", self.port) as pool:
567 with pytest.raises(MaxRetryError) as e:
568 pool.request("GET", "/", retries=5)
569 assert type(e.value.reason) is NameResolutionError
570
571 def test_keepalive(self) -> None:
572 with HTTPConnectionPool(self.host, self.port, block=True, maxsize=1) as pool:
573 r = pool.request("GET", "/keepalive?close=0")
574 r = pool.request("GET", "/keepalive?close=0")
575
576 assert r.status == 200
577 assert pool.num_connections == 1
578 assert pool.num_requests == 2
579
580 def test_keepalive_close(self) -> None:
581 with HTTPConnectionPool(
582 self.host, self.port, block=True, maxsize=1, timeout=2
583 ) as pool:
584 r = pool.request(
585 "GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"}
586 )
587
588 assert pool.num_connections == 1
589
590 # The dummyserver will have responded with Connection:close,
591 # and httplib will properly cleanup the socket.
592
593 # We grab the HTTPConnection object straight from the Queue,
594 # because _get_conn() is where the check & reset occurs
595 assert pool.pool is not None
596 conn = pool.pool.get()
597 assert conn.sock is None
598 pool._put_conn(conn)
599
600 # Now with keep-alive
601 r = pool.request(
602 "GET",
603 "/keepalive?close=0",
604 retries=0,
605 headers={"Connection": "keep-alive"},
606 )
607
608 # The dummyserver responded with Connection:keep-alive, the connection
609 # persists.
610 conn = pool.pool.get()
611 assert conn.sock is not None
612 pool._put_conn(conn)
613
614 # Another request asking the server to close the connection. This one
615 # should get cleaned up for the next request.
616 r = pool.request(
617 "GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"}
618 )
619
620 assert r.status == 200
621
622 conn = pool.pool.get()
623 assert conn.sock is None
624 pool._put_conn(conn)
625
626 # Next request
627 r = pool.request("GET", "/keepalive?close=0")
628
629 def test_post_with_urlencode(self) -> None:
630 with HTTPConnectionPool(self.host, self.port) as pool:
631 data = {"banana": "hammock", "lol": "cat"}
632 r = pool.request("POST", "/echo", fields=data, encode_multipart=False)
633 assert r.data.decode("utf-8") == urlencode(data)
634
635 def test_post_with_multipart(self) -> None:
636 with HTTPConnectionPool(self.host, self.port) as pool:
637 data = {"banana": "hammock", "lol": "cat"}
638 r = pool.request("POST", "/echo", fields=data, encode_multipart=True)
639 body = r.data.split(b"\r\n")
640
641 encoded_data = encode_multipart_formdata(data)[0]
642 expected_body = encoded_data.split(b"\r\n")
643
644 # TODO: Get rid of extra parsing stuff when you can specify
645 # a custom boundary to encode_multipart_formdata
646 """
647 We need to loop the return lines because a timestamp is attached
648 from within encode_multipart_formdata. When the server echos back
649 the data, it has the timestamp from when the data was encoded, which
650 is not equivalent to when we run encode_multipart_formdata on
651 the data again.
652 """
653 for i, line in enumerate(body):
654 if line.startswith(b"--"):
655 continue
656
657 assert body[i] == expected_body[i]
658
659 def test_post_with_multipart__iter__(self) -> None:
660 with HTTPConnectionPool(self.host, self.port) as pool:
661 data = {"hello": "world"}
662 r = pool.request(
663 "POST",
664 "/echo",
665 fields=data,
666 preload_content=False,
667 multipart_boundary="boundary",
668 encode_multipart=True,
669 )
670
671 chunks = [chunk for chunk in r]
672 assert chunks == [
673 b"--boundary\r\n",
674 b'Content-Disposition: form-data; name="hello"\r\n',
675 b"\r\n",
676 b"world\r\n",
677 b"--boundary--\r\n",
678 ]
679
680 def test_check_gzip(self) -> None:
681 with HTTPConnectionPool(self.host, self.port) as pool:
682 r = pool.request(
683 "GET", "/encodingrequest", headers={"accept-encoding": "gzip"}
684 )
685 assert r.headers.get("content-encoding") == "gzip"
686 assert r.data == b"hello, world!"
687
688 def test_check_deflate(self) -> None:
689 with HTTPConnectionPool(self.host, self.port) as pool:
690 r = pool.request(
691 "GET", "/encodingrequest", headers={"accept-encoding": "deflate"}
692 )
693 assert r.headers.get("content-encoding") == "deflate"
694 assert r.data == b"hello, world!"
695
696 def test_bad_decode(self) -> None:
697 with HTTPConnectionPool(self.host, self.port) as pool:
698 with pytest.raises(DecodeError):
699 pool.request(
700 "GET",
701 "/encodingrequest",
702 headers={"accept-encoding": "garbage-deflate"},
703 )
704
705 with pytest.raises(DecodeError):
706 pool.request(
707 "GET",
708 "/encodingrequest",
709 headers={"accept-encoding": "garbage-gzip"},
710 )
711
712 def test_connection_count(self) -> None:
713 with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool:
714 pool.request("GET", "/")
715 pool.request("GET", "/")
716 pool.request("GET", "/")
717
718 assert pool.num_connections == 1
719 assert pool.num_requests == 3
720
721 def test_connection_count_bigpool(self) -> None:
722 with HTTPConnectionPool(self.host, self.port, maxsize=16) as http_pool:
723 http_pool.request("GET", "/")
724 http_pool.request("GET", "/")
725 http_pool.request("GET", "/")
726
727 assert http_pool.num_connections == 1
728 assert http_pool.num_requests == 3
729
730 def test_partial_response(self) -> None:
731 with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool:
732 req_data = {"lol": "cat"}
733 resp_data = urlencode(req_data).encode("utf-8")
734
735 r = pool.request("GET", "/echo", fields=req_data, preload_content=False)
736
737 assert r.read(5) == resp_data[:5]
738 assert r.read() == resp_data[5:]
739
740 def test_lazy_load_twice(self) -> None:
741 # This test is sad and confusing. Need to figure out what's
742 # going on with partial reads and socket reuse.
743
744 with HTTPConnectionPool(
745 self.host, self.port, block=True, maxsize=1, timeout=2
746 ) as pool:
747 payload_size = 1024 * 2
748 first_chunk = 512
749
750 boundary = "foo"
751
752 req_data = {"count": "a" * payload_size}
753 resp_data = encode_multipart_formdata(req_data, boundary=boundary)[0]
754
755 req2_data = {"count": "b" * payload_size}
756 resp2_data = encode_multipart_formdata(req2_data, boundary=boundary)[0]
757
758 r1 = pool.request(
759 "POST",
760 "/echo",
761 fields=req_data,
762 multipart_boundary=boundary,
763 preload_content=False,
764 )
765
766 assert r1.read(first_chunk) == resp_data[:first_chunk]
767
768 try:
769 r2 = pool.request(
770 "POST",
771 "/echo",
772 fields=req2_data,
773 multipart_boundary=boundary,
774 preload_content=False,
775 pool_timeout=0.001,
776 )
777
778 # This branch should generally bail here, but maybe someday it will
779 # work? Perhaps by some sort of magic. Consider it a TODO.
780
781 assert r2.read(first_chunk) == resp2_data[:first_chunk]
782
783 assert r1.read() == resp_data[first_chunk:]
784 assert r2.read() == resp2_data[first_chunk:]
785 assert pool.num_requests == 2
786
787 except EmptyPoolError:
788 assert r1.read() == resp_data[first_chunk:]
789 assert pool.num_requests == 1
790
791 assert pool.num_connections == 1
792
793 def test_for_double_release(self) -> None:
794 MAXSIZE = 5
795
796 # Check default state
797 with HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE) as pool:
798 assert pool.num_connections == 0
799 assert pool.pool is not None
800 assert pool.pool.qsize() == MAXSIZE
801
802 # Make an empty slot for testing
803 pool.pool.get()
804 assert pool.pool.qsize() == MAXSIZE - 1
805
806 # Check state after simple request
807 pool.urlopen("GET", "/")
808 assert pool.pool.qsize() == MAXSIZE - 1
809
810 # Check state without release
811 pool.urlopen("GET", "/", preload_content=False)
812 assert pool.pool.qsize() == MAXSIZE - 2
813
814 pool.urlopen("GET", "/")
815 assert pool.pool.qsize() == MAXSIZE - 2
816
817 # Check state after read
818 pool.urlopen("GET", "/").data
819 assert pool.pool.qsize() == MAXSIZE - 2
820
821 pool.urlopen("GET", "/")
822 assert pool.pool.qsize() == MAXSIZE - 2
823
824 def test_release_conn_parameter(self) -> None:
825 MAXSIZE = 5
826 with HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE) as pool:
827 assert pool.pool is not None
828 assert pool.pool.qsize() == MAXSIZE
829
830 # Make request without releasing connection
831 pool.request("GET", "/", release_conn=False, preload_content=False)
832 assert pool.pool.qsize() == MAXSIZE - 1
833
834 def test_dns_error(self) -> None:
835 with HTTPConnectionPool(
836 "thishostdoesnotexist.invalid", self.port, timeout=0.001
837 ) as pool:
838 with pytest.raises(MaxRetryError):
839 pool.request("GET", "/test", retries=2)
840
841 @pytest.mark.parametrize("char", [" ", "\r", "\n", "\x00"])
842 def test_invalid_method_not_allowed(self, char: str) -> None:
843 with pytest.raises(ValueError):
844 with HTTPConnectionPool(self.host, self.port) as pool:
845 pool.request("GET" + char, "/")
846
847 def test_percent_encode_invalid_target_chars(self) -> None:
848 with HTTPConnectionPool(self.host, self.port) as pool:
849 r = pool.request("GET", "/echo_params?q=\r&k=\n \n")
850 assert r.data == b"[('k', '\\n \\n'), ('q', '\\r')]"
851
852 def test_source_address(self) -> None:
853 for addr, is_ipv6 in VALID_SOURCE_ADDRESSES:
854 if is_ipv6:
855 # TODO enable if HAS_IPV6_AND_DNS when this is fixed:
856 # https://github.com/pgjones/hypercorn/issues/160
857 warnings.warn("No IPv6 support: skipping.", NoIPv6Warning)
858 continue
859 with HTTPConnectionPool(
860 self.host, self.port, source_address=addr, retries=False
861 ) as pool:
862 r = pool.request("GET", "/source_address")
863 assert r.data == addr[0].encode()
864
865 @pytest.mark.parametrize(
866 "invalid_source_address, is_ipv6", INVALID_SOURCE_ADDRESSES
867 )
868 def test_source_address_error(
869 self, invalid_source_address: tuple[str, int], is_ipv6: bool
870 ) -> None:
871 with HTTPConnectionPool(
872 self.host, self.port, source_address=invalid_source_address, retries=False
873 ) as pool:
874 if is_ipv6:
875 # with pytest.raises(NameResolutionError):
876 with pytest.raises(NewConnectionError):
877 pool.request("GET", f"/source_address?{invalid_source_address}")
878 else:
879 with pytest.raises(NewConnectionError):
880 pool.request("GET", f"/source_address?{invalid_source_address}")
881
882 def test_stream_keepalive(self) -> None:
883 x = 2
884
885 with HTTPConnectionPool(self.host, self.port) as pool:
886 for _ in range(x):
887 response = pool.request(
888 "GET",
889 "/chunked",
890 headers={"Connection": "keep-alive"},
891 preload_content=False,
892 retries=False,
893 )
894 for chunk in response.stream():
895 assert chunk == b"123"
896
897 assert pool.num_connections == 1
898 assert pool.num_requests == x
899
900 def test_read_chunked_short_circuit(self) -> None:
901 with HTTPConnectionPool(self.host, self.port) as pool:
902 response = pool.request("GET", "/chunked", preload_content=False)
903 response.read()
904 with pytest.raises(StopIteration):
905 next(response.read_chunked())
906
907 def test_read_chunked_on_closed_response(self) -> None:
908 with HTTPConnectionPool(self.host, self.port) as pool:
909 response = pool.request("GET", "/chunked", preload_content=False)
910 response.close()
911 with pytest.raises(StopIteration):
912 next(response.read_chunked())
913
914 def test_chunked_gzip(self) -> None:
915 with HTTPConnectionPool(self.host, self.port) as pool:
916 response = pool.request(
917 "GET", "/chunked_gzip", preload_content=False, decode_content=True
918 )
919
920 assert b"123" * 4 == response.read()
921
922 def test_cleanup_on_connection_error(self) -> None:
923 """
924 Test that connections are recycled to the pool on
925 connection errors where no http response is received.
926 """
927 poolsize = 3
928 with HTTPConnectionPool(
929 self.host, self.port, maxsize=poolsize, block=True
930 ) as http:
931 assert http.pool is not None
932 assert http.pool.qsize() == poolsize
933
934 # force a connection error by supplying a non-existent
935 # url. We won't get a response for this and so the
936 # conn won't be implicitly returned to the pool.
937 with pytest.raises(MaxRetryError):
938 http.request(
939 "GET",
940 "/redirect",
941 fields={"target": "/"},
942 release_conn=False,
943 retries=0,
944 )
945
946 r = http.request(
947 "GET",
948 "/redirect",
949 fields={"target": "/"},
950 release_conn=False,
951 retries=1,
952 )
953 r.release_conn()
954
955 # the pool should still contain poolsize elements
956 assert http.pool.qsize() == http.pool.maxsize
957
958 def test_shutdown_on_connection_released_to_pool(self) -> None:
959 with HTTPConnectionPool(self.host, self.port) as pool:
960 resp = pool.urlopen("GET", "/", preload_content=False)
961 resp.drain_conn()
962 resp.release_conn()
963
964 with pytest.raises(
965 RuntimeError,
966 match="Cannot shutdown as connection has already been released to the pool",
967 ):
968 resp.shutdown()
969
970 def test_mixed_case_hostname(self) -> None:
971 with HTTPConnectionPool("LoCaLhOsT", self.port) as pool:
972 response = pool.request("GET", f"http://LoCaLhOsT:{self.port}/")
973 assert response.status == 200
974
975 def test_preserves_path_dot_segments(self) -> None:
976 """ConnectionPool preserves dot segments in the URI"""
977 with HTTPConnectionPool(self.host, self.port) as pool:
978 response = pool.request("GET", "/echo_uri/seg0/../seg2")
979 assert response.data == b"/echo_uri/seg0/../seg2?"
980
981 def test_default_user_agent_header(self) -> None:
982 """ConnectionPool has a default user agent"""
983 default_ua = _get_default_user_agent()
984 custom_ua = "I'm not a web scraper, what are you talking about?"
985 custom_ua2 = "Yet Another User Agent"
986 with HTTPConnectionPool(self.host, self.port) as pool:
987 # Use default user agent if no user agent was specified.
988 r = pool.request("GET", "/headers")
989 request_headers = r.json()
990 assert request_headers.get("User-Agent") == _get_default_user_agent()
991
992 # Prefer the request user agent over the default.
993 headers = {"UsEr-AGENt": custom_ua}
994 r = pool.request("GET", "/headers", headers=headers)
995 request_headers = r.json()
996 assert request_headers.get("User-Agent") == custom_ua
997
998 # Do not modify pool headers when using the default user agent.
999 pool_headers = {"foo": "bar"}
1000 pool.headers = pool_headers
1001 r = pool.request("GET", "/headers")
1002 request_headers = r.json()
1003 assert request_headers.get("User-Agent") == default_ua
1004 assert "User-Agent" not in pool_headers
1005
1006 pool.headers.update({"User-Agent": custom_ua2})
1007 r = pool.request("GET", "/headers")
1008 request_headers = r.json()
1009 assert request_headers.get("User-Agent") == custom_ua2
1010
1011 @pytest.mark.parametrize(
1012 "headers",
1013 [
1014 None,
1015 {},
1016 {"User-Agent": "key"},
1017 {"user-agent": "key"},
1018 {b"uSeR-AgEnT": b"key"},
1019 {b"user-agent": "key"},
1020 ],
1021 )
1022 @pytest.mark.parametrize("chunked", [True, False])
1023 def test_user_agent_header_not_sent_twice(
1024 self, headers: dict[str, str] | None, chunked: bool
1025 ) -> None:
1026 with HTTPConnectionPool(self.host, self.port) as pool:
1027 r = pool.request("GET", "/headers", headers=headers, chunked=chunked)
1028 request_headers = r.json()
1029
1030 if not headers:
1031 assert request_headers["User-Agent"].startswith("python-urllib3/")
1032 assert "key" not in request_headers["User-Agent"]
1033 else:
1034 assert request_headers["User-Agent"] == "key"
1035
1036 def test_no_user_agent_header(self) -> None:
1037 """ConnectionPool can suppress sending a user agent header"""
1038 custom_ua = "I'm not a web scraper, what are you talking about?"
1039 with HTTPConnectionPool(self.host, self.port) as pool:
1040 # Suppress user agent in the request headers.
1041 no_ua_headers = {"User-Agent": SKIP_HEADER}
1042 r = pool.request("GET", "/headers", headers=no_ua_headers)
1043 request_headers = r.json()
1044 assert "User-Agent" not in request_headers
1045 assert no_ua_headers["User-Agent"] == SKIP_HEADER
1046
1047 # Suppress user agent in the pool headers.
1048 pool.headers = no_ua_headers
1049 r = pool.request("GET", "/headers")
1050 request_headers = r.json()
1051 assert "User-Agent" not in request_headers
1052 assert no_ua_headers["User-Agent"] == SKIP_HEADER
1053
1054 # Request headers override pool headers.
1055 pool_headers = {"User-Agent": custom_ua}
1056 pool.headers = pool_headers
1057 r = pool.request("GET", "/headers", headers=no_ua_headers)
1058 request_headers = r.json()
1059 assert "User-Agent" not in request_headers
1060 assert no_ua_headers["User-Agent"] == SKIP_HEADER
1061 assert pool_headers.get("User-Agent") == custom_ua
1062
1063 @pytest.mark.parametrize("header", ["Content-Length", "content-length"])
1064 @pytest.mark.parametrize("chunked", [True, False])
1065 def test_skip_header_non_supported(self, header: str, chunked: bool) -> None:
1066 with HTTPConnectionPool(self.host, self.port) as pool:
1067 with pytest.raises(
1068 ValueError,
1069 match="urllib3.util.SKIP_HEADER only supports 'Accept-Encoding', 'Host', 'User-Agent'",
1070 ) as e:
1071 pool.request(
1072 "GET", "/headers", headers={header: SKIP_HEADER}, chunked=chunked
1073 )
1074 # Ensure that the error message stays up to date with 'SKIP_HEADER_SUPPORTED_HEADERS'
1075 assert all(
1076 ("'" + header.title() + "'") in str(e.value)
1077 for header in SKIPPABLE_HEADERS
1078 )
1079
1080 @pytest.mark.parametrize("chunked", [True, False])
1081 @pytest.mark.parametrize("pool_request", [True, False])
1082 @pytest.mark.parametrize("header_type", [dict, HTTPHeaderDict])
1083 def test_headers_not_modified_by_request(
1084 self,
1085 chunked: bool,
1086 pool_request: bool,
1087 header_type: type[dict[str, str] | HTTPHeaderDict],
1088 ) -> None:
1089 # Test that the .request*() methods of ConnectionPool and HTTPConnection
1090 # don't modify the given 'headers' structure, instead they should
1091 # make their own internal copies at request time.
1092 headers = header_type()
1093 headers["key"] = "val"
1094
1095 with HTTPConnectionPool(self.host, self.port) as pool:
1096 pool.headers = headers
1097 if pool_request:
1098 pool.request("GET", "/headers", chunked=chunked)
1099 else:
1100 conn = pool._get_conn()
1101 conn.request("GET", "/headers", chunked=chunked)
1102 conn.getresponse().close()
1103 conn.close()
1104
1105 assert pool.headers == {"key": "val"}
1106 assert type(pool.headers) is header_type
1107
1108 with HTTPConnectionPool(self.host, self.port) as pool:
1109 if pool_request:
1110 pool.request("GET", "/headers", headers=headers, chunked=chunked)
1111 else:
1112 conn = pool._get_conn()
1113 conn.request("GET", "/headers", headers=headers, chunked=chunked)
1114 conn.getresponse().close()
1115 conn.close()
1116
1117 assert headers == {"key": "val"}
1118
1119 def test_request_chunked_is_deprecated(
1120 self,
1121 ) -> None:
1122 with HTTPConnectionPool(self.host, self.port) as pool:
1123 conn = pool._get_conn()
1124
1125 with pytest.warns(FutureWarning) as w:
1126 conn.request_chunked("GET", "/headers") # type: ignore[attr-defined]
1127 assert len(w) == 1 and str(w[0].message) == (
1128 "HTTPConnection.request_chunked() is deprecated and will be removed in urllib3 v3.0. "
1129 "Instead use HTTPConnection.request(..., chunked=True)."
1130 )
1131
1132 resp = conn.getresponse()
1133 assert resp.status == 200
1134 assert resp.json()["Transfer-Encoding"] == "chunked"
1135 conn.close()
1136
1137 def test_bytes_header(self) -> None:
1138 with HTTPConnectionPool(self.host, self.port) as pool:
1139 headers = {"User-Agent": "test header"}
1140 r = pool.request("GET", "/headers", headers=headers)
1141 request_headers = r.json()
1142 assert "User-Agent" in request_headers
1143 assert request_headers["User-Agent"] == "test header"
1144
1145 @pytest.mark.parametrize(
1146 "user_agent", ["Schönefeld/1.18.0", "Schönefeld/1.18.0".encode("iso-8859-1")]
1147 )
1148 def test_user_agent_non_ascii_user_agent(self, user_agent: str) -> None:
1149 with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
1150 r = pool.urlopen(
1151 "GET",
1152 "/headers",
1153 headers={"User-Agent": user_agent},
1154 )
1155 request_headers = r.json()
1156 assert "User-Agent" in request_headers
1157 assert request_headers["User-Agent"] == "Schönefeld/1.18.0"
1158
1159
1160 class TestRetry(HypercornDummyServerTestCase):
1161 def test_max_retry(self) -> None:
1162 with HTTPConnectionPool(self.host, self.port) as pool:
1163 with pytest.raises(MaxRetryError):
1164 pool.request("GET", "/redirect", fields={"target": "/"}, retries=0)
1165
1166 def test_disabled_retry(self) -> None:
1167 """Disabled retries should disable redirect handling."""
1168 with HTTPConnectionPool(self.host, self.port) as pool:
1169 r = pool.request("GET", "/redirect", fields={"target": "/"}, retries=False)
1170 assert r.status == 303
1171
1172 r = pool.request(
1173 "GET",
1174 "/redirect",
1175 fields={"target": "/"},
1176 retries=Retry(redirect=False),
1177 )
1178 assert r.status == 303
1179
1180 with HTTPConnectionPool(
1181 "thishostdoesnotexist.invalid", self.port, timeout=0.001
1182 ) as pool:
1183 with pytest.raises(NameResolutionError):
1184 pool.request("GET", "/test", retries=False)
1185
1186 def test_read_retries(self) -> None:
1187 """Should retry for status codes in the forcelist"""
1188 with HTTPConnectionPool(self.host, self.port) as pool:
1189 retry = Retry(read=1, status_forcelist=[418])
1190 resp = pool.request(
1191 "GET",
1192 "/successful_retry",
1193 headers={"test-name": "test_read_retries"},
1194 retries=retry,
1195 )
1196 assert resp.status == 200
1197
1198 def test_read_total_retries(self) -> None:
1199 """HTTP response w/ status code in the forcelist should be retried"""
1200 with HTTPConnectionPool(self.host, self.port) as pool:
1201 headers = {"test-name": "test_read_total_retries"}
1202 retry = Retry(total=1, status_forcelist=[418])
1203 resp = pool.request(
1204 "GET", "/successful_retry", headers=headers, retries=retry
1205 )
1206 assert resp.status == 200
1207
1208 def test_retries_wrong_forcelist(self) -> None:
1209 """HTTP response w/ status code not in forcelist shouldn't be retried"""
1210 with HTTPConnectionPool(self.host, self.port) as pool:
1211 retry = Retry(total=1, status_forcelist=[202])
1212 resp = pool.request(
1213 "GET",
1214 "/successful_retry",
1215 headers={"test-name": "test_wrong_forcelist"},
1216 retries=retry,
1217 )
1218 assert resp.status == 418
1219
1220 def test_default_method_forcelist_retried(self) -> None:
1221 """urllib3 should retry methods in the default method forcelist"""
1222 with HTTPConnectionPool(self.host, self.port) as pool:
1223 retry = Retry(total=1, status_forcelist=[418])
1224 resp = pool.request(
1225 "OPTIONS",
1226 "/successful_retry",
1227 headers={"test-name": "test_default_forcelist"},
1228 retries=retry,
1229 )
1230 assert resp.status == 200
1231
1232 def test_retries_wrong_method_list(self) -> None:
1233 """Method not in our allowed list should not be retried, even if code matches"""
1234 with HTTPConnectionPool(self.host, self.port) as pool:
1235 headers = {"test-name": "test_wrong_allowed_method"}
1236 retry = Retry(total=1, status_forcelist=[418], allowed_methods=["POST"])
1237 resp = pool.request(
1238 "GET", "/successful_retry", headers=headers, retries=retry
1239 )
1240 assert resp.status == 418
1241
1242 def test_read_retries_unsuccessful(
1243 self,
1244 ) -> None:
1245 with HTTPConnectionPool(self.host, self.port) as pool:
1246 headers = {"test-name": "test_read_retries_unsuccessful"}
1247 resp = pool.request("GET", "/successful_retry", headers=headers, retries=1)
1248 assert resp.status == 418
1249
1250 def test_retry_reuse_safe(self) -> None:
1251 """It should be possible to reuse a Retry object across requests"""
1252 with HTTPConnectionPool(self.host, self.port) as pool:
1253 headers = {"test-name": "test_retry_safe"}
1254 retry = Retry(total=1, status_forcelist=[418])
1255 resp = pool.request(
1256 "GET", "/successful_retry", headers=headers, retries=retry
1257 )
1258 assert resp.status == 200
1259
1260 with HTTPConnectionPool(self.host, self.port) as pool:
1261 resp = pool.request(
1262 "GET", "/successful_retry", headers=headers, retries=retry
1263 )
1264 assert resp.status == 200
1265
1266 def test_retry_return_in_response(self) -> None:
1267 with HTTPConnectionPool(self.host, self.port) as pool:
1268 headers = {"test-name": "test_retry_return_in_response"}
1269 retry = Retry(total=2, status_forcelist=[418])
1270 resp = pool.request(
1271 "GET", "/successful_retry", headers=headers, retries=retry
1272 )
1273 assert resp.status == 200
1274 assert resp.retries is not None
1275 assert resp.retries.total == 1
1276 assert resp.retries.history == (
1277 RequestHistory("GET", "/successful_retry", None, 418, None),
1278 )
1279
1280 def test_retry_redirect_history(self) -> None:
1281 with HTTPConnectionPool(self.host, self.port) as pool:
1282 resp = pool.request("GET", "/redirect", fields={"target": "/"})
1283 assert resp.status == 200
1284 assert resp.retries is not None
1285 assert resp.retries.history == (
1286 RequestHistory("GET", "/redirect?target=%2F", None, 303, "/"),
1287 )
1288
1289 def test_multi_redirect_history(self) -> None:
1290 with HTTPConnectionPool(self.host, self.port) as pool:
1291 r = pool.request(
1292 "GET",
1293 "/multi_redirect",
1294 fields={"redirect_codes": "303,302,200"},
1295 redirect=False,
1296 )
1297 assert r.status == 303
1298 assert r.retries is not None
1299 assert r.retries.history == tuple()
1300
1301 with HTTPConnectionPool(self.host, self.port) as pool:
1302 r = pool.request(
1303 "GET",
1304 "/multi_redirect",
1305 retries=10,
1306 fields={"redirect_codes": "303,302,301,307,302,200"},
1307 )
1308 assert r.status == 200
1309 assert r.data == b"Done redirecting"
1310
1311 expected = [
1312 (303, "/multi_redirect?redirect_codes=302,301,307,302,200"),
1313 (302, "/multi_redirect?redirect_codes=301,307,302,200"),
1314 (301, "/multi_redirect?redirect_codes=307,302,200"),
1315 (307, "/multi_redirect?redirect_codes=302,200"),
1316 (302, "/multi_redirect?redirect_codes=200"),
1317 ]
1318 assert r.retries is not None
1319 actual = [
1320 (history.status, history.redirect_location)
1321 for history in r.retries.history
1322 ]
1323 assert actual == expected
1324
1325
1326 class TestRetryAfter(HypercornDummyServerTestCase):
1327 def test_retry_after(self) -> None:
1328 # Request twice in a second to get a 429 response.
1329 with HTTPConnectionPool(self.host, self.port) as pool:
1330 r = pool.request(
1331 "GET",
1332 "/retry_after",
1333 fields={"status": "429 Too Many Requests"},
1334 retries=False,
1335 )
1336 r = pool.request(
1337 "GET",
1338 "/retry_after",
1339 fields={"status": "429 Too Many Requests"},
1340 retries=False,
1341 )
1342 assert r.status == 429
1343
1344 r = pool.request(
1345 "GET",
1346 "/retry_after",
1347 fields={"status": "429 Too Many Requests"},
1348 retries=True,
1349 )
1350 assert r.status == 200
1351
1352 # Request twice in a second to get a 503 response.
1353 r = pool.request(
1354 "GET",
1355 "/retry_after",
1356 fields={"status": "503 Service Unavailable"},
1357 retries=False,
1358 )
1359 r = pool.request(
1360 "GET",
1361 "/retry_after",
1362 fields={"status": "503 Service Unavailable"},
1363 retries=False,
1364 )
1365 assert r.status == 503
1366
1367 r = pool.request(
1368 "GET",
1369 "/retry_after",
1370 fields={"status": "503 Service Unavailable"},
1371 retries=True,
1372 )
1373 assert r.status == 200
1374
1375 # Ignore Retry-After header on status which is not defined in
1376 # Retry.RETRY_AFTER_STATUS_CODES.
1377 r = pool.request(
1378 "GET",
1379 "/retry_after",
1380 fields={"status": "418 I'm a teapot"},
1381 retries=True,
1382 )
1383 assert r.status == 418
1384
1385 def test_redirect_after(self) -> None:
1386 with HTTPConnectionPool(self.host, self.port) as pool:
1387 r = pool.request("GET", "/redirect_after", retries=False)
1388 assert r.status == 303
1389
1390 # Real timestamps are needed for this test
1391 t = time.time()
1392 r = pool.request("GET", "/redirect_after")
1393 assert r.status == 200
1394 delta = time.time() - t
1395 assert delta >= 1
1396
1397 t = time.time()
1398 timestamp = t + 2
1399 r = pool.request("GET", "/redirect_after?date=" + str(timestamp))
1400 assert r.status == 200
1401 delta = time.time() - t
1402 assert delta >= 1
1403
1404 # Retry-After is past
1405 t = time.time()
1406 timestamp = t - 1
1407 r = pool.request("GET", "/redirect_after?date=" + str(timestamp))
1408 delta = time.time() - t
1409 assert r.status == 200
1410 assert delta < 1
1411
1412
1413 class TestFileBodiesOnRetryOrRedirect(HypercornDummyServerTestCase):
1414 def test_retries_put_filehandle(self) -> None:
1415 """HTTP PUT retry with a file-like object should not timeout"""
1416 with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool:
1417 retry = Retry(total=3, status_forcelist=[418])
1418 # httplib reads in 8k chunks; use a larger content length
1419 content_length = 65535
1420 data = b"A" * content_length
1421 uploaded_file = io.BytesIO(data)
1422 headers = {
1423 "test-name": "test_retries_put_filehandle",
1424 "Content-Length": str(content_length),
1425 }
1426 resp = pool.urlopen(
1427 "PUT",
1428 "/successful_retry",
1429 headers=headers,
1430 retries=retry,
1431 body=uploaded_file,
1432 assert_same_host=False,
1433 redirect=False,
1434 )
1435 assert resp.status == 200
1436
1437 def test_redirect_put_file(self) -> None:
1438 """PUT with file object should work with a redirection response"""
1439 with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool:
1440 retry = Retry(total=3, status_forcelist=[418])
1441 # httplib reads in 8k chunks; use a larger content length
1442 content_length = 65535
1443 data = b"A" * content_length
1444 uploaded_file = io.BytesIO(data)
1445 headers = {
1446 "test-name": "test_redirect_put_file",
1447 "Content-Length": str(content_length),
1448 }
1449 url = "/redirect?target=/echo&status=307"
1450 resp = pool.urlopen(
1451 "PUT",
1452 url,
1453 headers=headers,
1454 retries=retry,
1455 body=uploaded_file,
1456 assert_same_host=False,
1457 redirect=True,
1458 )
1459 assert resp.status == 200
1460 assert resp.data == data
1461
1462 def test_redirect_with_failed_tell(self) -> None:
1463 """Abort request if failed to get a position from tell()"""
1464
1465 class BadTellObject(io.BytesIO):
1466 def tell(self) -> typing.NoReturn:
1467 raise OSError
1468
1469 body = BadTellObject(b"the data")
1470 # A 307 keeps the body, so it has to be rewound for the redirect.
1471 url = "/redirect?target=/successful_retry&status=307"
1472 # httplib uses fileno if Content-Length isn't supplied,
1473 # which is unsupported by BytesIO.
1474 headers = {"Content-Length": "8"}
1475 with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool:
1476 with pytest.raises(
1477 UnrewindableBodyError, match="Unable to record file position for"
1478 ):
1479 pool.urlopen("PUT", url, headers=headers, body=body)
1480
1481 def test_303_redirect_with_failed_tell(self) -> None:
1482 """A 303 drops the body, so it never needs to be rewound"""
1483
1484 class BadTellObject(io.BytesIO):
1485 def tell(self) -> typing.NoReturn:
1486 raise OSError
1487
1488 body = BadTellObject(b"the data")
1489 url = "/redirect?target=/echo"
1490 # httplib uses fileno if Content-Length isn't supplied,
1491 # which is unsupported by BytesIO.
1492 headers = {"Content-Length": "8"}
1493 with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool:
1494 resp = pool.urlopen("PUT", url, headers=headers, body=body)
1495 assert resp.status == 200
1496 assert resp.data == b""
1497
1498
1499 class TestRetryPoolSize(HypercornDummyServerTestCase):
1500 def test_pool_size_retry(self) -> None:
1501 retries = Retry(total=1, raise_on_status=False, status_forcelist=[404])
1502 with HTTPConnectionPool(
1503 self.host, self.port, maxsize=10, retries=retries, block=True
1504 ) as pool:
1505 pool.urlopen("GET", "/not_found", preload_content=False)
1506 assert pool.num_connections == 1
1507
1508
1509 class TestRedirectPoolSize(HypercornDummyServerTestCase):
1510 def test_pool_size_redirect(self) -> None:
1511 retries = Retry(
1512 total=1, raise_on_status=False, status_forcelist=[404], redirect=True
1513 )
1514 with HTTPConnectionPool(
1515 self.host, self.port, maxsize=10, retries=retries, block=True
1516 ) as pool:
1517 pool.urlopen("GET", "/redirect", preload_content=False)
1518 assert pool.num_connections == 1