Debian Codegraph @

test/test_response.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import gzip
5 import http.client as httplib
6 import socket
7 import ssl
8 import sys
9 import typing
10 import zlib
11 from base64 import b64decode
12 from http.client import IncompleteRead as httplib_IncompleteRead
13 from io import BufferedReader, BytesIO, TextIOWrapper
14 from test import LONG_TIMEOUT, onlyBrotli, onlyZstd
15 from unittest import mock
16
17 import pytest
18
19 from urllib3.exceptions import (
20 BodyNotHttplibCompatible,
21 DecodeError,
22 IncompleteRead,
23 InvalidChunkLength,
24 InvalidHeader,
25 ProtocolError,
26 ResponseNotChunked,
27 SSLError,
28 )
29 from urllib3.response import ( # type: ignore[attr-defined]
30 _MAX_CHUNK_LINE_LENGTH,
31 BaseHTTPResponse,
32 BytesQueueBuffer,
33 HTTPResponse,
34 brotli,
35 )
36 from urllib3.util.response import is_fp_closed
37 from urllib3.util.retry import RequestHistory, Retry
38
39
40 def zstd_compress(data: bytes) -> bytes:
41 if sys.version_info >= (3, 14):
42 from compression import zstd
43 else:
44 from backports import zstd
45 return zstd.compress(data)
46
47
48 def deflate2_compress(data: bytes) -> bytes:
49 compressor = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS)
50 return compressor.compress(data) + compressor.flush()
51
52
53 if brotli:
54 try:
55 brotli.Decompressor().process(b"", output_buffer_limit=1024)
56 _brotli_gte_1_2_0_available = True
57 except (AttributeError, TypeError):
58 _brotli_gte_1_2_0_available = False
59 else:
60 _brotli_gte_1_2_0_available = False
61 try:
62 zstd_compress(b"")
63 _zstd_available = True
64 except ModuleNotFoundError:
65 _zstd_available = False
66
67
68 class TestBytesQueueBuffer:
69 def test_single_chunk(self) -> None:
70 buffer = BytesQueueBuffer()
71 assert len(buffer) == 0
72 with pytest.raises(RuntimeError, match="buffer is empty"):
73 assert buffer.get(10)
74
75 assert buffer.get(0) == b""
76
77 buffer.put(b"foo")
78 with pytest.raises(ValueError, match="n should be > 0"):
79 buffer.get(-1)
80
81 assert buffer.get(1) == b"f"
82 assert buffer.get(2) == b"oo"
83 with pytest.raises(RuntimeError, match="buffer is empty"):
84 assert buffer.get(10)
85
86 def test_read_too_much(self) -> None:
87 buffer = BytesQueueBuffer()
88 buffer.put(b"foo")
89 assert buffer.get(100) == b"foo"
90
91 def test_multiple_chunks(self) -> None:
92 buffer = BytesQueueBuffer()
93 buffer.put(b"foo")
94 buffer.put(b"bar")
95 buffer.put(b"baz")
96 assert len(buffer) == 9
97
98 assert buffer.get(1) == b"f"
99 assert len(buffer) == 8
100 assert buffer.get(4) == b"ooba"
101 assert len(buffer) == 4
102 assert buffer.get(4) == b"rbaz"
103 assert len(buffer) == 0
104
105 def test_get_all_empty(self) -> None:
106 q = BytesQueueBuffer()
107 assert q.get_all() == b""
108 assert len(q) == 0
109
110 def test_get_all_single(self) -> None:
111 q = BytesQueueBuffer()
112 q.put(b"a")
113 assert q.get_all() == b"a"
114 assert len(q) == 0
115
116 def test_get_all_many(self) -> None:
117 q = BytesQueueBuffer()
118 q.put(b"a")
119 q.put(b"b")
120 q.put(b"c")
121 assert q.get_all() == b"abc"
122 assert len(q) == 0
123
124 @pytest.mark.parametrize(
125 "get_func",
126 (lambda b: b.get(len(b)), lambda b: b.get_all()),
127 ids=("get", "get_all"),
128 )
129 # Doubling memory usage would take this past 20 MiB; the peak is 12.1 MiB.
130 # The margin is deliberately wide so that allocation noise cannot fail it.
131 @pytest.mark.limit_memory("15 MB", current_thread_only=True)
132 def test_memory_usage(
133 self, get_func: typing.Callable[[BytesQueueBuffer], bytes]
134 ) -> None:
135 # Allocate 10 1MiB chunks
136 buffer = BytesQueueBuffer()
137 for i in range(10):
138 # This allocates 2MiB, putting the max at around 12MiB. Not sure why.
139 buffer.put(bytes(2**20))
140
141 result = get_func(buffer)
142 assert type(result) is bytes
143 assert len(result) == 10 * 2**20
144
145 @pytest.mark.parametrize(
146 "get_func",
147 (lambda b: b.get(len(b)), lambda b: b.get_all()),
148 ids=("get", "get_all"),
149 )
150 # Copying the chunk instead of handing it back would take this to 20 MiB;
151 # the peak is 10 MiB and the identity assertion below is the real check.
152 # The margin is deliberately wide so that allocation noise cannot fail it.
153 @pytest.mark.limit_memory("12 MB", current_thread_only=True)
154 def test_memory_usage_single_chunk(
155 self, get_func: typing.Callable[[BytesQueueBuffer], bytes]
156 ) -> None:
157 buffer = BytesQueueBuffer()
158 chunk = bytes(10 * 2**20) # 10 MiB
159 buffer.put(chunk)
160 assert get_func(buffer) is chunk
161
162 @pytest.mark.parametrize(
163 "finish_with_get_all",
164 (True, False),
165 ids=("finish_with_get_all", "finish_with_get"),
166 )
167 # Duplicating the chunk while splitting it would take this to 20 MiB;
168 # the peak is 11 MiB.
169 # The margin is deliberately wide so that allocation noise cannot fail it.
170 @pytest.mark.limit_memory("13 MB", current_thread_only=True)
171 def test_memory_usage_splitting_chunk(self, finish_with_get_all: bool) -> None:
172 # Allocate a single 10MiB chunk, then read it in two parts.
173 # Verifies that splitting a chunk doesn't cause additional memory allocation.
174 buffer = BytesQueueBuffer()
175 chunk = bytes(10 * 2**20) # 10 MiB
176 buffer.put(chunk)
177 for i in range(10):
178 if finish_with_get_all and i == 9:
179 result = buffer.get_all()
180 else:
181 result = buffer.get(2**20)
182 assert type(result) is bytes
183 assert len(result) == 2**20
184 del result
185 assert len(buffer) == 0
186
187
188 # A known random (i.e, not-too-compressible) payload generated with:
189 # "".join(random.choice(string.printable) for i in range(512))
190 # .encode("zlib").encode("base64")
191 # Randomness in tests == bad, and fixing a seed may not be sufficient.
192 ZLIB_PAYLOAD = b64decode(
193 b"""\
194 eJwFweuaoQAAANDfineQhiKLUiaiCzvuTEmNNlJGiL5QhnGpZ99z8luQfe1AHoMioB+QSWHQu/L+
195 lzd7W5CipqYmeVTBjdgSATdg4l4Z2zhikbuF+EKn69Q0DTpdmNJz8S33odfJoVEexw/l2SS9nFdi
196 pis7KOwXzfSqarSo9uJYgbDGrs1VNnQpT9f8zAorhYCEZronZQF9DuDFfNK3Hecc+WHLnZLQptwk
197 nufw8S9I43sEwxsT71BiqedHo0QeIrFE01F/4atVFXuJs2yxIOak3bvtXjUKAA6OKnQJ/nNvDGKZ
198 Khe5TF36JbnKVjdcL1EUNpwrWVfQpFYJ/WWm2b74qNeSZeQv5/xBhRdOmKTJFYgO96PwrHBlsnLn
199 a3l0LwJsloWpMbzByU5WLbRE6X5INFqjQOtIwYz5BAlhkn+kVqJvWM5vBlfrwP42ifonM5yF4ciJ
200 auHVks62997mNGOsM7WXNG3P98dBHPo2NhbTvHleL0BI5dus2JY81MUOnK3SGWLH8HeWPa1t5KcW
201 S5moAj5HexY/g/F8TctpxwsvyZp38dXeLDjSQvEQIkF7XR3YXbeZgKk3V34KGCPOAeeuQDIgyVhV
202 nP4HF2uWHA==""",
203 )
204
205
206 @pytest.fixture
207 def sock() -> typing.Generator[socket.socket]:
208 s = socket.socket()
209 yield s
210 s.close()
211
212
213 class TestResponse:
214 def test_cache_content(self) -> None:
215 r = HTTPResponse(b"foo")
216 assert r._body == b"foo"
217 assert r.data == b"foo"
218 assert r._body == b"foo"
219
220 def test_cache_content_preload_false(self) -> None:
221 fp = BytesIO(b"foo")
222 r = HTTPResponse(fp, preload_content=False)
223
224 assert not r._body
225 assert r.data == b"foo"
226 assert r._body == b"foo" # type: ignore[comparison-overlap]
227 assert r.data == b"foo"
228
229 @pytest.mark.parametrize("read_args", ((), (None,), (-1,)))
230 def test_cache_content_with_explicit_read_call(
231 self, read_args: tuple[typing.Any, ...]
232 ) -> None:
233 fp = BytesIO(b"foo")
234 r = HTTPResponse(fp, preload_content=False)
235 assert r.read(*read_args, cache_content=True) == b"foo" # type: ignore[misc]
236 assert r._body == b"foo"
237 assert r.data == b"foo"
238
239 @pytest.mark.parametrize(
240 "initial_read_method", ("read", "read1", "read_chunked", "stream")
241 )
242 def test_cache_content_ignored_during_and_after_partial_read(
243 self, initial_read_method: str
244 ) -> None:
245 data = b"foo"
246 initial_limit = 1
247 if initial_read_method in ("read_chunked", "stream"):
248 httplib_r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
249 httplib_r.chunked = True
250 httplib_r.fp = MockChunkedEncodingResponse([data]) # type: ignore[assignment]
251 r = HTTPResponse(
252 httplib_r,
253 preload_content=False,
254 headers={"transfer-encoding": "chunked"},
255 )
256 # Partial read.
257 next(getattr(r, initial_read_method)(initial_limit))
258 httplib_r.chunk_left = len(data) - initial_limit
259 else:
260 fp = BytesIO(data)
261 r = HTTPResponse(fp, preload_content=False)
262 # Partial read.
263 if initial_read_method == "read":
264 r.read(initial_limit, cache_content=True)
265 else:
266 getattr(r, initial_read_method)(initial_limit)
267 assert r._body is None
268 # Full read (remaining content).
269 r.read(cache_content=True)
270 assert r._body is None
271 assert r.data == b""
272
273 def test_default(self) -> None:
274 r = HTTPResponse()
275 assert r.data is None
276
277 def test_none(self) -> None:
278 r = HTTPResponse(None) # type: ignore[arg-type]
279 assert r.data is None
280
281 def test_preload(self) -> None:
282 fp = BytesIO(b"foo")
283
284 r = HTTPResponse(fp, preload_content=True)
285
286 assert fp.tell() == len(b"foo")
287 assert r.data == b"foo"
288
289 def test_no_preload(self) -> None:
290 fp = BytesIO(b"foo")
291
292 r = HTTPResponse(fp, preload_content=False)
293
294 assert fp.tell() == 0
295 assert r.data == b"foo"
296 assert fp.tell() == len(b"foo")
297
298 def test_no_shutdown(self) -> None:
299 r = HTTPResponse()
300 with pytest.raises(
301 ValueError, match="Cannot shutdown socket as self._sock_shutdown is not set"
302 ):
303 r.shutdown()
304
305 def test_decode_bad_data(self) -> None:
306 fp = BytesIO(b"\x00" * 10)
307 with pytest.raises(DecodeError):
308 HTTPResponse(fp, headers={"content-encoding": "deflate"})
309
310 @pytest.mark.parametrize("content_encoding", (None, "gzip"))
311 def test_content_encoding_is_inspected_once(
312 self, content_encoding: str | None
313 ) -> None:
314 headers = {"content-encoding": content_encoding} if content_encoding else None
315 r = HTTPResponse(BytesIO(), headers=headers, preload_content=False)
316
317 with mock.patch.object(r.headers, "get", wraps=r.headers.get) as get_header:
318 r._init_decoder()
319 r._init_decoder()
320
321 assert get_header.call_count == 1
322 if content_encoding is None:
323 assert r._decoder is None
324 else:
325 assert r._decoder is not None
326
327 def test_decoder_initialization_is_retried_after_failure(self) -> None:
328 r = HTTPResponse(
329 BytesIO(), headers={"content-encoding": "gzip"}, preload_content=False
330 )
331 decoder = mock.Mock()
332
333 with mock.patch(
334 "urllib3.response._get_decoder", side_effect=(RuntimeError, decoder)
335 ) as get_decoder:
336 with pytest.raises(RuntimeError):
337 r._init_decoder()
338 r._init_decoder()
339 r._init_decoder()
340
341 assert r._decoder is decoder
342 assert get_decoder.call_count == 2
343
344 def test_reference_read(self) -> None:
345 fp = BytesIO(b"foo")
346 r = HTTPResponse(fp, preload_content=False)
347
348 assert r.read(0) == b""
349 assert r.read(1) == b"f"
350 assert r.read(2) == b"oo"
351 assert r.read() == b""
352 assert r.read() == b""
353
354 @pytest.mark.parametrize("read_args", ((), (None,), (-1,)))
355 def test_reference_read_until_eof(self, read_args: tuple[typing.Any, ...]) -> None:
356 fp = BytesIO(b"foo")
357 r = HTTPResponse(fp, preload_content=False)
358 assert r.read(*read_args) == b"foo"
359
360 def test_reference_read1(self) -> None:
361 fp = BytesIO(b"foobar")
362 r = HTTPResponse(fp, preload_content=False)
363
364 assert r.read1(0) == b""
365 assert r.read1(1) == b"f"
366 assert r.read1(2) == b"oo"
367 assert r.read1() == b"bar"
368 assert r.read1() == b""
369
370 @pytest.mark.parametrize("read1_args", ((), (None,), (-1,)))
371 def test_reference_read1_without_limit(
372 self, read1_args: tuple[typing.Any, ...]
373 ) -> None:
374 fp = BytesIO(b"foo")
375 r = HTTPResponse(fp, preload_content=False)
376 assert r.read1(*read1_args) == b"foo"
377
378 def test_reference_read1_nodecode(self) -> None:
379 fp = BytesIO(b"foobar")
380 r = HTTPResponse(fp, preload_content=False, decode_content=False)
381
382 assert r.read1(0) == b""
383 assert r.read1(1) == b"f"
384 assert r.read1(2) == b"oo"
385 assert r.read1() == b"bar"
386 assert r.read1() == b""
387
388 def test_decoding_read1(self) -> None:
389 data = zlib.compress(b"foobar")
390
391 fp = BytesIO(data)
392 r = HTTPResponse(
393 fp, headers={"content-encoding": "deflate"}, preload_content=False
394 )
395
396 assert r.read1(1) == b"f"
397 assert r.read1(2) == b"oo"
398 assert r.read1() == b"bar"
399 assert r.read1() == b""
400
401 def test_decode_deflate(self) -> None:
402 data = zlib.compress(b"foo")
403
404 fp = BytesIO(data)
405 r = HTTPResponse(fp, headers={"content-encoding": "deflate"})
406
407 assert r.data == b"foo"
408
409 def test_decode_deflate_case_insensitve(self) -> None:
410 data = zlib.compress(b"foo")
411
412 fp = BytesIO(data)
413 r = HTTPResponse(fp, headers={"content-encoding": "DeFlAtE"})
414
415 assert r.data == b"foo"
416
417 def test_chunked_decoding_deflate(self) -> None:
418 data = zlib.compress(b"foo")
419
420 fp = BytesIO(data)
421 r = HTTPResponse(
422 fp, headers={"content-encoding": "deflate"}, preload_content=False
423 )
424
425 assert r.read(1) == b"f"
426 assert r.read(2) == b"oo"
427 assert r.read() == b""
428 assert r.read() == b""
429
430 def test_chunked_decoding_deflate2(self) -> None:
431 compress = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS)
432 data = compress.compress(b"foo")
433 data += compress.flush()
434
435 fp = BytesIO(data)
436 r = HTTPResponse(
437 fp, headers={"content-encoding": "deflate"}, preload_content=False
438 )
439
440 assert r.read(1) == b"f"
441 assert r.read(2) == b"oo"
442 assert r.read() == b""
443 assert r.read() == b""
444
445 @pytest.mark.parametrize("content_encoding", ["gzip", "x-gzip"])
446 def test_chunked_decoding_gzip(self, content_encoding: str) -> None:
447 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
448 data = compress.compress(b"foo")
449 data += compress.flush()
450
451 fp = BytesIO(data)
452 r = HTTPResponse(
453 fp, headers={"content-encoding": content_encoding}, preload_content=False
454 )
455
456 assert r.read(1) == b"f"
457 assert r.read(2) == b"oo"
458 assert r.read() == b""
459 assert r.read() == b""
460
461 def test_decode_gzip_multi_member(self) -> None:
462 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
463 data = compress.compress(b"foo")
464 data += compress.flush()
465 data = data * 3
466
467 fp = BytesIO(data)
468 r = HTTPResponse(fp, headers={"content-encoding": "gzip"})
469
470 assert r.data == b"foofoofoo"
471
472 def test_decode_gzip_error(self) -> None:
473 fp = BytesIO(b"foo")
474 with pytest.raises(DecodeError):
475 HTTPResponse(fp, headers={"content-encoding": "gzip"})
476
477 def test_decode_gzip_swallow_garbage(self) -> None:
478 # When data comes from multiple calls to read(), data after
479 # the first zlib error (here triggered by garbage) should be
480 # ignored.
481 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
482 data = compress.compress(b"foo")
483 data += compress.flush()
484 data = data * 3 + b"foo"
485
486 fp = BytesIO(data)
487 r = HTTPResponse(
488 fp, headers={"content-encoding": "gzip"}, preload_content=False
489 )
490 ret = b""
491 for _ in range(100):
492 ret += r.read(1)
493 if r.closed:
494 break
495
496 assert ret == b"foofoofoo"
497
498 def test_chunked_decoding_gzip_swallow_garbage(self) -> None:
499 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
500 data = compress.compress(b"foo")
501 data += compress.flush()
502 data = data * 3 + b"foo"
503
504 fp = BytesIO(data)
505 r = HTTPResponse(fp, headers={"content-encoding": "gzip"})
506
507 assert r.data == b"foofoofoo"
508
509 @onlyBrotli()
510 def test_decode_brotli(self) -> None:
511 data = brotli.compress(b"foo")
512
513 fp = BytesIO(data)
514 r = HTTPResponse(fp, headers={"content-encoding": "br"})
515 assert r.data == b"foo"
516
517 @onlyBrotli()
518 def test_chunked_decoding_brotli(self) -> None:
519 data = brotli.compress(b"foobarbaz")
520
521 fp = BytesIO(data)
522 r = HTTPResponse(fp, headers={"content-encoding": "br"}, preload_content=False)
523
524 ret = b""
525 for _ in range(100):
526 ret += r.read(1)
527 if r.closed:
528 break
529 assert ret == b"foobarbaz"
530
531 @onlyBrotli()
532 def test_decode_brotli_error(self) -> None:
533 fp = BytesIO(b"foo")
534 with pytest.raises(DecodeError):
535 HTTPResponse(fp, headers={"content-encoding": "br"})
536
537 @onlyZstd()
538 def test_decode_zstd(self) -> None:
539 data = zstd_compress(b"foo")
540
541 fp = BytesIO(data)
542 r = HTTPResponse(fp, headers={"content-encoding": "zstd"})
543 assert r.data == b"foo"
544
545 @onlyZstd()
546 @pytest.mark.parametrize(
547 "read_amt",
548 (
549 # Read all data at once.
550 None,
551 # Read one byte at a time, data of frames will be returned
552 # separately.
553 1,
554 # Read two bytes at a time, the second read should return
555 # data from both frames.
556 2,
557 # Read three bytes at a time, the whole frames will be
558 # returned separately in two calls.
559 3,
560 # Read four bytes at a time, the first read should return
561 # data from the first frame and a part of the second frame.
562 4,
563 ),
564 )
565 def test_decode_multiframe_zstd(self, read_amt: int | None) -> None:
566 data = (
567 # Zstandard frame
568 zstd_compress(b"foo")
569 # skippable frame (must be ignored)
570 + bytes.fromhex(
571 "50 2A 4D 18" # Magic_Number (little-endian)
572 "07 00 00 00" # Frame_Size (little-endian)
573 "00 00 00 00 00 00 00" # User_Data
574 )
575 # Zstandard frame
576 + zstd_compress(b"bar")
577 )
578
579 fp = BytesIO(data)
580 result = bytearray()
581 r = HTTPResponse(
582 fp, headers={"content-encoding": "zstd"}, preload_content=False
583 )
584 total_length = 6
585 while len(result) < total_length:
586 chunk = r.read(read_amt, decode_content=True)
587 if read_amt is None:
588 assert len(chunk) == total_length
589 else:
590 assert len(chunk) == min(read_amt, total_length - len(result))
591 result += chunk
592 assert bytes(result) == b"foobar"
593
594 @onlyZstd()
595 def test_decode_multiframe_zstd_with_max_length_close_to_compressed_data_size(
596 self,
597 ) -> None:
598 """
599 Test decoding when the first read from the socket returns all
600 the compressed frames, but then it has to be decompressed in a
601 couple of read calls.
602 """
603 data = (
604 # Zstandard frame
605 zstd_compress(b"x" * 1024)
606 # skippable frame (must be ignored)
607 + bytes.fromhex(
608 "50 2A 4D 18" # Magic_Number (little-endian)
609 "07 00 00 00" # Frame_Size (little-endian)
610 "00 00 00 00 00 00 00" # User_Data
611 )
612 # Zstandard frame
613 + zstd_compress(b"y" * 1024)
614 )
615
616 fp = BytesIO(data)
617 r = HTTPResponse(
618 fp, headers={"content-encoding": "zstd"}, preload_content=False
619 )
620 # Read the whole first frame.
621 assert r.read(1024) == b"x" * 1024
622 assert len(r._decoded_buffer) == 0
623 # Read the whole second frame in two reads.
624 assert r.read(512) == b"y" * 512
625 assert len(r._decoded_buffer) == 0
626 assert r.read(512) == b"y" * 512
627 assert len(r._decoded_buffer) == 0
628 # Ensure no more data is left.
629 assert r.read() == b""
630 assert len(r._decoded_buffer) == 0
631
632 @onlyZstd()
633 def test_chunked_decoding_zstd(self) -> None:
634 data = zstd_compress(b"foobarbaz")
635
636 fp = BytesIO(data)
637 r = HTTPResponse(
638 fp, headers={"content-encoding": "zstd"}, preload_content=False
639 )
640
641 ret = b""
642
643 for _ in range(100):
644 ret += r.read(1)
645 if r.closed:
646 break
647 assert ret == b"foobarbaz"
648
649 decode_param_set = [
650 b"foo",
651 b"x" * 100,
652 ]
653
654 @onlyZstd()
655 @pytest.mark.parametrize("data", decode_param_set)
656 def test_decode_zstd_error(self, data: bytes) -> None:
657 fp = BytesIO(data)
658
659 with pytest.raises(DecodeError):
660 HTTPResponse(fp, headers={"content-encoding": "zstd"})
661
662 @onlyZstd()
663 @pytest.mark.parametrize("data", decode_param_set)
664 def test_decode_zstd_incomplete_preload_content(self, data: bytes) -> None:
665 data = zstd_compress(data)
666 fp = BytesIO(data[:-1])
667
668 with pytest.raises(DecodeError):
669 HTTPResponse(fp, headers={"content-encoding": "zstd"})
670
671 @onlyZstd()
672 @pytest.mark.parametrize("data", decode_param_set)
673 def test_decode_zstd_incomplete_read(self, data: bytes) -> None:
674 data = zstd_compress(data)
675 fp = BytesIO(data[:-1]) # shorten the data to trigger DecodeError
676
677 # create response object without(!) reading/decoding the content
678 r = HTTPResponse(
679 fp, headers={"content-encoding": "zstd"}, preload_content=False
680 )
681
682 # read/decode, expecting DecodeError
683 with pytest.raises(DecodeError):
684 r.read(decode_content=True)
685
686 @onlyZstd()
687 @pytest.mark.parametrize("data", decode_param_set)
688 def test_decode_zstd_incomplete_read1(self, data: bytes) -> None:
689 data = zstd_compress(data)
690 fp = BytesIO(data[:-1])
691
692 r = HTTPResponse(
693 fp, headers={"content-encoding": "zstd"}, preload_content=False
694 )
695
696 # read/decode via read1(!), expecting DecodeError
697 with pytest.raises(DecodeError):
698 amt_decoded = 0
699 # loop, as read1() may return just partial data
700 while amt_decoded < len(data):
701 part = r.read1(decode_content=True)
702 amt_decoded += len(part)
703
704 @onlyZstd()
705 @pytest.mark.parametrize("data", decode_param_set)
706 def test_decode_zstd_read1(self, data: bytes) -> None:
707 encoded_data = zstd_compress(data)
708 fp = BytesIO(encoded_data)
709
710 r = HTTPResponse(
711 fp, headers={"content-encoding": "zstd"}, preload_content=False
712 )
713
714 amt_decoded = 0
715 decoded_data = b""
716 # loop, as read1() may return just partial data
717 while amt_decoded < len(data):
718 part = r.read1(decode_content=True)
719 amt_decoded += len(part)
720 decoded_data += part
721 assert decoded_data == data
722
723 _test_compressor_params: list[
724 tuple[str, tuple[str, typing.Callable[[bytes], bytes]] | None]
725 ] = [
726 ("deflate1", ("deflate", zlib.compress)),
727 ("deflate2", ("deflate", deflate2_compress)),
728 ("gzip", ("gzip", gzip.compress)),
729 ]
730 if _brotli_gte_1_2_0_available:
731 _test_compressor_params.append(("brotli", ("br", brotli.compress)))
732 else:
733 _test_compressor_params.append(("brotli", None))
734 if _zstd_available:
735 _test_compressor_params.append(("zstd", ("zstd", zstd_compress)))
736 else:
737 _test_compressor_params.append(("zstd", None))
738
739 @pytest.mark.parametrize("read_method", ("read", "read1"))
740 @pytest.mark.parametrize(
741 "data",
742 [d[1] for d in _test_compressor_params],
743 ids=[d[0] for d in _test_compressor_params],
744 )
745 def test_read_with_all_data_already_in_decompressor(
746 self,
747 request: pytest.FixtureRequest,
748 read_method: str,
749 data: tuple[str, typing.Callable[[bytes], bytes]] | None,
750 ) -> None:
751 if data is None:
752 pytest.skip(f"Proper {request.node.callspec.id} decoder is not available")
753 original_data = b"bar" * 1000
754 name, compress_func = data
755 compressed_data = compress_func(original_data)
756 fp = mock.Mock(read=mock.Mock(return_value=b""))
757 r = HTTPResponse(fp, headers={"content-encoding": name}, preload_content=False)
758 # Put all data in the decompressor's buffer.
759 r._init_decoder()
760 assert r._decoder is not None # for mypy
761 decoded = r._decoder.decompress(compressed_data, max_length=0)
762 if name == "br":
763 # It's known that some Brotli libraries do not respect
764 # `max_length`.
765 r._decoded_buffer.put(decoded)
766 else:
767 assert decoded == b""
768 # Read the data via `HTTPResponse`.
769 read = getattr(r, read_method)
770 assert read(0) == b""
771 assert read(2500) == original_data[:2500]
772 assert read(500) == original_data[2500:]
773 assert read(0) == b""
774 assert read() == b""
775
776 @pytest.mark.parametrize("read_method", ("read_chunked", "stream"))
777 @pytest.mark.parametrize(
778 "data",
779 [d[1] for d in _test_compressor_params],
780 ids=[d[0] for d in _test_compressor_params],
781 )
782 def test_read_chunked_with_all_data_already_in_decompressor(
783 self,
784 request: pytest.FixtureRequest,
785 read_method: str,
786 data: tuple[str, typing.Callable[[bytes], bytes]] | None,
787 ) -> None:
788 if data is None:
789 pytest.skip(f"Proper {request.node.callspec.id} decoder is not available")
790 original_data = b"0" * 100_000 # 100 KB
791 name, compress_func = data
792 compressed_data = compress_func(original_data)
793 httplib_r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
794 httplib_r.fp = MockChunkedEncodingResponse([compressed_data]) # type: ignore[assignment]
795 r = HTTPResponse(
796 httplib_r,
797 preload_content=False,
798 headers={"transfer-encoding": "chunked", "content-encoding": name},
799 )
800 # Mark the current chunk as fully read.
801 r.chunk_left = 0
802 # Feed all compressed data to the decoder.
803 r._init_decoder()
804 assert r._decoder is not None # for mypy
805 initially_decoded = r._decoder.decompress(compressed_data, max_length=0)
806 result = list(getattr(r, read_method)(amt=10240, decode_content=True))
807 if name == "br":
808 # It's known that some Brotli libraries do not respect
809 # `max_length`.
810 result = [initially_decoded] + list(result)
811 else:
812 assert initially_decoded == b""
813 assert all(len(chunk) == 10240 for chunk in result[:-1])
814 assert len(result[-1]) == len(original_data) % 10240
815 assert b"".join(result) == original_data
816
817 @pytest.mark.timeout(LONG_TIMEOUT)
818 @pytest.mark.parametrize(
819 "data",
820 [d[1] for d in _test_compressor_params],
821 ids=[d[0] for d in _test_compressor_params],
822 )
823 def test_read_chunked_with_trailing_data_does_not_hang(
824 self,
825 request: pytest.FixtureRequest,
826 data: tuple[str, typing.Callable[[bytes], bytes]] | None,
827 ) -> None:
828 if data is None:
829 pytest.skip(f"Proper {request.node.callspec.id} decoder is not available")
830 # The decoded body must fill multiple bounded reads so EOF is reached
831 # while trailing data remains in the decoder's input buffer.
832 original_data = b"A" * 100
833 content_encoding, compress_func = data
834 if content_encoding == "br" and brotli.__name__ == "brotlicffi":
835 pytest.skip("This case is not supported by brotlicffi")
836 compressed_data = compress_func(original_data) + b"tail"
837 httplib_r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
838 httplib_r.fp = MockChunkedEncodingResponse([compressed_data]) # type: ignore[assignment]
839 r = HTTPResponse(
840 httplib_r,
841 preload_content=False,
842 headers={
843 "transfer-encoding": "chunked",
844 "content-encoding": content_encoding,
845 },
846 )
847
848 stream = r.stream(len(original_data) // 2, decode_content=True)
849 if content_encoding in ("br", "zstd"):
850 with pytest.raises(DecodeError):
851 list(stream)
852 else:
853 assert b"".join(stream) == original_data
854
855 @pytest.mark.parametrize(
856 "delta",
857 (
858 0, # First read from socket returns all compressed data.
859 -1, # First read from socket returns all but one byte of compressed data.
860 ),
861 )
862 @pytest.mark.parametrize("read_method", ("read", "read1"))
863 @pytest.mark.parametrize(
864 "data",
865 [d[1] for d in _test_compressor_params],
866 ids=[d[0] for d in _test_compressor_params],
867 )
868 def test_decode_with_max_length_close_to_compressed_data_size(
869 self,
870 request: pytest.FixtureRequest,
871 delta: int,
872 read_method: str,
873 data: tuple[str, typing.Callable[[bytes], bytes]] | None,
874 ) -> None:
875 """
876 Test decoding when the first read from the socket returns all or
877 almost all the compressed data, but then it has to be
878 decompressed in a couple of read calls.
879 """
880 if data is None:
881 pytest.skip(f"Proper {request.node.callspec.id} decoder is not available")
882
883 original_data = b"foo" * 1000
884 name, compress_func = data
885 compressed_data = compress_func(original_data)
886 fp = BytesIO(compressed_data)
887 r = HTTPResponse(fp, headers={"content-encoding": name}, preload_content=False)
888 initial_limit = len(compressed_data) + delta
889 read = getattr(r, read_method)
890 initial_chunk = read(amt=initial_limit, decode_content=True)
891 assert len(initial_chunk) == initial_limit
892 assert (
893 len(read(amt=len(original_data), decode_content=True))
894 == len(original_data) - initial_limit
895 )
896
897 # Prepare 50 MB of compressed data outside of the test measuring
898 # memory usage.
899 _test_memory_usage_decode_with_max_length_params: list[
900 tuple[str, tuple[str, bytes] | None]
901 ] = [
902 (
903 params[0],
904 (params[1][0], params[1][1](b"A" * (50 * 2**20))) if params[1] else None,
905 )
906 for params in _test_compressor_params
907 ]
908
909 @pytest.mark.parametrize(
910 "data",
911 [d[1] for d in _test_memory_usage_decode_with_max_length_params],
912 ids=[d[0] for d in _test_memory_usage_decode_with_max_length_params],
913 )
914 @pytest.mark.parametrize("read_method", ("read", "read1", "read_chunked", "stream"))
915 # Decoders consume different amounts of memory during decompression.
916 # We set the 10 MB limit to ensure that the whole decompressed data
917 # is not stored unnecessarily.
918 #
919 # FYI, the following consumption was observed for the test with
920 # `read` on CPython 3.14.0:
921 # - deflate: 2.3 MiB
922 # - deflate2: 2.1 MiB
923 # - gzip: 2.1 MiB
924 # - brotli:
925 # - brotli v1.2.0: 9 MiB
926 # - brotlicffi v1.2.0.0: 6 MiB
927 # - brotlipy v0.7.0: 105.8 MiB
928 # - zstd: 4.5 MiB
929 @pytest.mark.limit_memory("10 MB", current_thread_only=True)
930 def test_memory_usage_decode_with_max_length(
931 self,
932 request: pytest.FixtureRequest,
933 read_method: str,
934 data: tuple[str, bytes] | None,
935 ) -> None:
936 if data is None:
937 pytest.skip(f"Proper {request.node.callspec.id} decoder is not available")
938
939 name, compressed_data = data
940 limit1 = 1024 * 1024 # 1 MiB
941 # We test with two read calls because the second call may be
942 # able to use the internal buffer filled by the first call, and
943 # we want to ensure that full decompression is never triggered
944 # by the second call. The limit for the second call is lowered
945 # to make sure that the internal buffer is used for the Brotli
946 # case specifically https://github.com/google/brotli/issues/1396
947 limit2 = 1024 # 1 KiB
948 if read_method in ("read_chunked", "stream"):
949 httplib_r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
950 httplib_r.chunked = True
951 httplib_r.chunk_left = 1
952 httplib_r.fp = MockChunkedEncodingResponse([compressed_data]) # type: ignore[assignment]
953 r = HTTPResponse(
954 httplib_r,
955 preload_content=False,
956 headers={"transfer-encoding": "chunked", "content-encoding": name},
957 )
958 for limit in (limit1, limit2):
959 next(getattr(r, read_method)(amt=limit, decode_content=True))
960 else:
961 fp = BytesIO(compressed_data)
962 r = HTTPResponse(
963 fp, headers={"content-encoding": name}, preload_content=False
964 )
965 for limit in (limit1, limit2):
966 getattr(r, read_method)(amt=limit, decode_content=True)
967
968 # Check that the internal decoded buffer is empty unless brotli
969 # is used.
970 # Google's brotli library does not fully respect the output
971 # buffer limit: https://github.com/google/brotli/issues/1396
972 # And unmaintained brotlipy cannot limit the output buffer size.
973 if name != "br" or brotli.__name__ == "brotlicffi":
974 assert len(r._decoded_buffer) == 0
975
976 # Check that memory usage is still within the limit while the
977 # connection is being drained, meaning that the call does not
978 # decompress the whole content.
979 r.drain_conn()
980 assert r._decoder is None
981 assert len(r._decoded_buffer) == 0
982
983 def test_multi_decoding_deflate_deflate(self) -> None:
984 data = zlib.compress(zlib.compress(b"foo"))
985
986 fp = BytesIO(data)
987 r = HTTPResponse(fp, headers={"content-encoding": "deflate, deflate"})
988
989 assert r.data == b"foo"
990
991 def test_multi_decoding_deflate_gzip(self) -> None:
992 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
993 data = compress.compress(zlib.compress(b"foo"))
994 data += compress.flush()
995
996 fp = BytesIO(data)
997 r = HTTPResponse(fp, headers={"content-encoding": "deflate, gzip"})
998
999 assert r.data == b"foo"
1000
1001 def test_multi_decoding_gzip_gzip(self) -> None:
1002 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
1003 data = compress.compress(b"foo")
1004 data += compress.flush()
1005
1006 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
1007 data = compress.compress(data)
1008 data += compress.flush()
1009
1010 fp = BytesIO(data)
1011 r = HTTPResponse(fp, headers={"content-encoding": "gzip, gzip"})
1012
1013 assert r.data == b"foo"
1014
1015 def test_read_multi_decoding_deflate_deflate(self) -> None:
1016 msg = b"foobarbaz" * 42
1017 data = zlib.compress(zlib.compress(msg))
1018
1019 fp = BytesIO(data)
1020 r = HTTPResponse(
1021 fp, headers={"content-encoding": "deflate, deflate"}, preload_content=False
1022 )
1023
1024 assert r.read(3) == b"foo"
1025 assert r.read(3) == b"bar"
1026 assert r.read(3) == b"baz"
1027 assert r.read(9) == b"foobarbaz"
1028 assert r.read(9 * 3) == b"foobarbaz" * 3
1029 assert r.read(9 * 37) == b"foobarbaz" * 37
1030 assert r.read() == b""
1031
1032 def test_read_multi_decoding_too_many_links(self) -> None:
1033 fp = BytesIO(b"foo")
1034 with pytest.raises(
1035 DecodeError, match="Too many content encodings in the chain: 6 > 5"
1036 ):
1037 HTTPResponse(
1038 fp,
1039 headers={"content-encoding": "gzip, deflate, br, zstd, gzip, deflate"},
1040 )
1041
1042 def test_full_read_after_partial_read_with_buffered_decoded_data(self) -> None:
1043 data = zlib.compress(b"foobarbaz")
1044 fp = BytesIO(data)
1045 r = HTTPResponse(
1046 fp, headers={"content-encoding": "deflate"}, preload_content=False
1047 )
1048 assert r.read(3) == b"foo"
1049 # Force putting some decoded data in the buffer as the buffer
1050 # is normally empty unless decoder has issues like not
1051 # respecting `max_length` https://github.com/google/brotli/issues/1396
1052 middle_part = r._decode(
1053 r._raw_read(), decode_content=True, flush_decoder=False, max_length=3
1054 )
1055 assert middle_part == b"bar"
1056 r._decoded_buffer.put(middle_part)
1057 # Here we expect data from `_decoded_buffer` to be joined with
1058 # the remaining part.
1059 assert r.read() == b"barbaz"
1060
1061 def test_full_read_after_partial_read_without_buffered_decoded_data(self) -> None:
1062 data = zlib.compress(b"foobarbaz")
1063 fp = BytesIO(data)
1064 r = HTTPResponse(
1065 fp, headers={"content-encoding": "deflate"}, preload_content=False
1066 )
1067 assert r.read(3) == b"foo"
1068 assert len(r._decoded_buffer) == 0
1069 assert r.read() == b"barbaz"
1070
1071 def test_body_blob(self) -> None:
1072 resp = HTTPResponse(b"foo")
1073 assert resp.data == b"foo"
1074 assert resp.closed
1075
1076 @pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")
1077 def test_base_io(self) -> None:
1078 resp = BaseHTTPResponse(
1079 status=200,
1080 version=11,
1081 version_string="HTTP/1.1",
1082 reason=None,
1083 decode_content=False,
1084 request_url=None,
1085 )
1086
1087 assert not resp.closed
1088 assert not resp.readable()
1089 assert not resp.writable()
1090
1091 with pytest.raises(NotImplementedError):
1092 resp.read()
1093 with pytest.raises(NotImplementedError):
1094 resp.close()
1095
1096 def test_io(self, sock: socket.socket) -> None:
1097 fp = BytesIO(b"foo")
1098 resp = HTTPResponse(fp, preload_content=False)
1099
1100 assert not resp.closed
1101 assert resp.readable()
1102 assert not resp.writable()
1103 with pytest.raises(IOError):
1104 resp.fileno()
1105
1106 resp.close()
1107 assert resp.closed
1108
1109 # Try closing with an `httplib.HTTPResponse`, because it has an
1110 # `isclosed` method.
1111 try:
1112 hlr = httplib.HTTPResponse(sock)
1113 resp2 = HTTPResponse(hlr, preload_content=False)
1114 assert not resp2.closed
1115 resp2.close()
1116 assert resp2.closed
1117 finally:
1118 hlr.close()
1119
1120 # also try when only data is present.
1121 resp3 = HTTPResponse("foodata")
1122 with pytest.raises(IOError):
1123 resp3.fileno()
1124
1125 resp3._fp = 2
1126 # A corner case where _fp is present but doesn't have `closed`,
1127 # `isclosed`, or `fileno`. Unlikely, but possible.
1128 assert resp3.closed
1129 with pytest.raises(IOError):
1130 resp3.fileno()
1131
1132 def test_io_closed_consistently_by_read(self, sock: socket.socket) -> None:
1133 try:
1134 hlr = httplib.HTTPResponse(sock)
1135 hlr.fp = BytesIO(b"foo") # type: ignore[assignment]
1136 hlr.chunked = 0 # type: ignore[assignment]
1137 hlr.length = 3
1138 with HTTPResponse(hlr, preload_content=False) as resp:
1139 assert not resp.closed
1140 assert resp._fp is not None
1141 assert not resp._fp.isclosed()
1142 assert not is_fp_closed(resp._fp)
1143 assert not resp.isclosed()
1144 resp.read()
1145 assert resp.closed
1146 assert resp._fp.isclosed()
1147 assert is_fp_closed(resp._fp)
1148 assert resp.isclosed()
1149 finally:
1150 hlr.close()
1151
1152 @pytest.mark.parametrize("read_amt", (None, 3))
1153 @pytest.mark.parametrize("length_known", (True, False))
1154 def test_io_closed_consistently_by_read1(
1155 self, sock: socket.socket, length_known: bool, read_amt: int | None
1156 ) -> None:
1157 with httplib.HTTPResponse(sock) as hlr:
1158 hlr.fp = BytesIO(b"foo") # type: ignore[assignment]
1159 hlr.chunked = 0 # type: ignore[assignment]
1160 hlr.length = 3 if length_known else None
1161 with HTTPResponse(hlr, preload_content=False) as resp:
1162 if length_known:
1163 resp.length_remaining = 3
1164 assert not resp.closed
1165 assert resp._fp is not None
1166 assert not resp._fp.isclosed()
1167 assert not is_fp_closed(resp._fp)
1168 assert not resp.isclosed()
1169 resp.read1(read_amt)
1170 # If content length is unknown, IO is not closed until
1171 # the next read returning zero bytes.
1172 if not length_known:
1173 assert not resp.closed
1174 assert resp._fp is not None
1175 assert not resp._fp.isclosed()
1176 assert not is_fp_closed(resp._fp)
1177 assert not resp.isclosed()
1178 resp.read1(read_amt)
1179 assert resp.closed
1180 assert resp._fp.isclosed()
1181 assert is_fp_closed(resp._fp)
1182 assert resp.isclosed()
1183
1184 @pytest.mark.parametrize("length_known", (True, False))
1185 def test_io_not_closed_until_all_data_is_read(
1186 self, sock: socket.socket, length_known: bool
1187 ) -> None:
1188 with httplib.HTTPResponse(sock) as hlr:
1189 hlr.fp = BytesIO(b"foo") # type: ignore[assignment]
1190 hlr.chunked = 0 # type: ignore[assignment]
1191 length_remaining = 3
1192 hlr.length = length_remaining if length_known else None
1193 with HTTPResponse(hlr, preload_content=False) as resp:
1194 if length_known:
1195 resp.length_remaining = length_remaining
1196 while length_remaining:
1197 assert not resp.closed
1198 assert resp._fp is not None
1199 assert not resp._fp.isclosed()
1200 assert not is_fp_closed(resp._fp)
1201 assert not resp.isclosed()
1202 data = resp.read(1)
1203 assert len(data) == 1
1204 length_remaining -= 1
1205 # If content length is unknown, IO is not closed until
1206 # the next read returning zero bytes.
1207 if not length_known:
1208 assert not resp.closed
1209 assert resp._fp is not None
1210 assert not resp._fp.isclosed()
1211 assert not is_fp_closed(resp._fp)
1212 assert not resp.isclosed()
1213 data = resp.read(1)
1214 assert len(data) == 0
1215 assert resp.closed
1216 assert resp._fp.isclosed() # type: ignore[union-attr]
1217 assert is_fp_closed(resp._fp)
1218 assert resp.isclosed()
1219
1220 @pytest.mark.parametrize("length_known", (True, False))
1221 def test_io_not_closed_after_requesting_0_bytes(
1222 self, sock: socket.socket, length_known: bool
1223 ) -> None:
1224 with httplib.HTTPResponse(sock) as hlr:
1225 hlr.fp = BytesIO(b"foo") # type: ignore[assignment]
1226 hlr.chunked = 0 # type: ignore[assignment]
1227 length_remaining = 3
1228 hlr.length = length_remaining if length_known else None
1229 with HTTPResponse(hlr, preload_content=False) as resp:
1230 if length_known:
1231 resp.length_remaining = length_remaining
1232 assert not resp.closed
1233 assert resp._fp is not None
1234 assert not resp._fp.isclosed()
1235 assert not is_fp_closed(resp._fp)
1236 assert not resp.isclosed()
1237 data = resp.read(0)
1238 assert data == b""
1239 assert not resp.closed
1240 assert resp._fp is not None
1241 assert not resp._fp.isclosed()
1242 assert not is_fp_closed(resp._fp)
1243 assert not resp.isclosed()
1244
1245 def test_io_bufferedreader(self) -> None:
1246 fp = BytesIO(b"foo")
1247 resp = HTTPResponse(fp, preload_content=False)
1248 br = BufferedReader(resp)
1249
1250 assert br.read() == b"foo"
1251
1252 br.close()
1253 assert resp.closed
1254
1255 # HTTPResponse.read() by default closes the response
1256 # https://github.com/urllib3/urllib3/issues/1305
1257 fp = BytesIO(b"hello\nworld")
1258 resp = HTTPResponse(fp, preload_content=False)
1259 with pytest.raises(ValueError, match="readline of closed file"):
1260 list(BufferedReader(resp))
1261
1262 b = b"fooandahalf"
1263 fp = BytesIO(b)
1264 resp = HTTPResponse(fp, preload_content=False)
1265 br = BufferedReader(resp, 5)
1266
1267 br.read(1) # sets up the buffer, reading 5
1268 assert len(fp.read()) == (len(b) - 5)
1269
1270 # This is necessary to make sure the "no bytes left" part of `readinto`
1271 # gets tested.
1272 while not br.closed:
1273 br.read(5)
1274
1275 def test_readinto_with_memoryview(self) -> None:
1276 data = b"hello world"
1277 fp = BytesIO(data)
1278 resp = HTTPResponse(fp, preload_content=False)
1279
1280 buf = bytearray(5)
1281 mv = memoryview(buf)
1282 n = resp.readinto(mv)
1283 assert n == 5
1284 assert buf == b"hello"
1285
1286 # Also test readinto with a bytearray directly
1287 buf2 = bytearray(6)
1288 n2 = resp.readinto(buf2)
1289 assert n2 == 6
1290 assert buf2 == b" world"
1291
1292 # Test readinto when no bytes are left
1293 buf3 = bytearray(5)
1294 n3 = resp.readinto(buf3)
1295 assert n3 == 0
1296
1297 def test_io_not_autoclose_bufferedreader(self) -> None:
1298 fp = BytesIO(b"hello\nworld")
1299 resp = HTTPResponse(fp, preload_content=False, auto_close=False)
1300 reader = BufferedReader(resp)
1301 assert list(reader) == [b"hello\n", b"world"]
1302
1303 assert not reader.closed
1304 assert not resp.closed
1305 with pytest.raises(StopIteration):
1306 next(reader)
1307
1308 reader.close()
1309 assert reader.closed
1310 assert resp.closed
1311 with pytest.raises(ValueError, match="readline of closed file"):
1312 next(reader)
1313
1314 def test_io_textiowrapper(self) -> None:
1315 fp = BytesIO(b"\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f")
1316 resp = HTTPResponse(fp, preload_content=False)
1317 br = TextIOWrapper(resp, encoding="utf8") # type: ignore[type-var]
1318
1319 assert br.read() == "äöüß"
1320
1321 br.close()
1322 assert resp.closed
1323
1324 # HTTPResponse.read() by default closes the response
1325 # https://github.com/urllib3/urllib3/issues/1305
1326 fp = BytesIO(
1327 b"\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\n\xce\xb1\xce\xb2\xce\xb3\xce\xb4"
1328 )
1329 resp = HTTPResponse(fp, preload_content=False)
1330 with pytest.raises(ValueError, match="I/O operation on closed file.?"):
1331 list(TextIOWrapper(resp)) # type: ignore[type-var]
1332
1333 def test_io_not_autoclose_textiowrapper(self) -> None:
1334 fp = BytesIO(
1335 b"\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\n\xce\xb1\xce\xb2\xce\xb3\xce\xb4"
1336 )
1337 resp = HTTPResponse(fp, preload_content=False, auto_close=False)
1338 reader = TextIOWrapper(resp, encoding="utf8") # type: ignore[type-var]
1339 assert list(reader) == ["äöüß\n", "αβγδ"]
1340
1341 assert not reader.closed
1342 assert not resp.closed
1343 with pytest.raises(StopIteration):
1344 next(reader)
1345
1346 reader.close()
1347 assert reader.closed
1348 assert resp.closed
1349 with pytest.raises(ValueError, match="I/O operation on closed file.?"):
1350 next(reader)
1351
1352 def test_read_with_illegal_mix_decode_toggle(self) -> None:
1353 data = zlib.compress(b"foo")
1354
1355 fp = BytesIO(data)
1356
1357 resp = HTTPResponse(
1358 fp, headers={"content-encoding": "deflate"}, preload_content=False
1359 )
1360
1361 assert resp.read(1) == b"f"
1362
1363 with pytest.raises(
1364 RuntimeError,
1365 match=(
1366 r"Calling read\(decode_content=False\) is not supported after "
1367 r"read\(decode_content=True\) was called"
1368 ),
1369 ):
1370 resp.read(1, decode_content=False)
1371
1372 with pytest.raises(
1373 RuntimeError,
1374 match=(
1375 r"Calling read\(decode_content=False\) is not supported after "
1376 r"read\(decode_content=True\) was called"
1377 ),
1378 ):
1379 resp.read(decode_content=False)
1380
1381 def test_read1_with_illegal_mix_decode_toggle(self) -> None:
1382 data = zlib.compress(b"foo")
1383
1384 fp = BytesIO(data)
1385
1386 resp = HTTPResponse(
1387 fp, headers={"content-encoding": "deflate"}, preload_content=False
1388 )
1389
1390 assert resp.read1(1) == b"f"
1391
1392 with pytest.raises(
1393 RuntimeError,
1394 match=(
1395 r"Calling read1\(decode_content=False\) is not supported after "
1396 r"read1\(decode_content=True\) was called"
1397 ),
1398 ):
1399 resp.read1(1, decode_content=False)
1400
1401 with pytest.raises(
1402 RuntimeError,
1403 match=(
1404 r"Calling read1\(decode_content=False\) is not supported after "
1405 r"read1\(decode_content=True\) was called"
1406 ),
1407 ):
1408 resp.read1(decode_content=False)
1409
1410 def test_read_with_mix_decode_toggle(self) -> None:
1411 data = zlib.compress(b"foo")
1412
1413 fp = BytesIO(data)
1414
1415 resp = HTTPResponse(
1416 fp, headers={"content-encoding": "deflate"}, preload_content=False
1417 )
1418 assert resp.read(2, decode_content=False) is not None
1419 assert resp.read(1, decode_content=True) == b"f"
1420
1421 def test_streaming(self) -> None:
1422 fp = BytesIO(b"foo")
1423 resp = HTTPResponse(fp, preload_content=False)
1424 stream = resp.stream(2, decode_content=False)
1425
1426 assert next(stream) == b"fo"
1427 assert next(stream) == b"o"
1428 with pytest.raises(StopIteration):
1429 next(stream)
1430
1431 def test_streaming_tell(self) -> None:
1432 fp = BytesIO(b"foo")
1433 resp = HTTPResponse(fp, preload_content=False)
1434 stream = resp.stream(2, decode_content=False)
1435
1436 position = 0
1437
1438 position += len(next(stream))
1439 assert 2 == position
1440 assert position == resp.tell()
1441
1442 position += len(next(stream))
1443 assert 3 == position
1444 assert position == resp.tell()
1445
1446 with pytest.raises(StopIteration):
1447 next(stream)
1448
1449 def test_gzipped_streaming(self) -> None:
1450 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
1451 data = compress.compress(b"foo")
1452 data += compress.flush()
1453
1454 fp = BytesIO(data)
1455 resp = HTTPResponse(
1456 fp, headers={"content-encoding": "gzip"}, preload_content=False
1457 )
1458 stream = resp.stream(2)
1459
1460 assert next(stream) == b"fo"
1461 assert next(stream) == b"o"
1462 with pytest.raises(StopIteration):
1463 next(stream)
1464
1465 def test_gzipped_streaming_tell(self) -> None:
1466 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
1467 uncompressed_data = b"foo"
1468 data = compress.compress(uncompressed_data)
1469 data += compress.flush()
1470
1471 fp = BytesIO(data)
1472 resp = HTTPResponse(
1473 fp, headers={"content-encoding": "gzip"}, preload_content=False
1474 )
1475 stream = resp.stream()
1476
1477 # Read everything
1478 payload = next(stream)
1479 assert payload == uncompressed_data
1480
1481 assert len(data) == resp.tell()
1482
1483 with pytest.raises(StopIteration):
1484 next(stream)
1485
1486 def test_deflate_streaming_tell_intermediate_point(self) -> None:
1487 # Ensure that ``tell()`` returns the correct number of bytes when
1488 # part-way through streaming compressed content.
1489 NUMBER_OF_READS = 10
1490 PART_SIZE = 64
1491
1492 class MockCompressedDataReading(BytesIO):
1493 """
1494 A BytesIO-like reader returning ``payload`` in ``NUMBER_OF_READS``
1495 calls to ``read``.
1496 """
1497
1498 def __init__(self, payload: bytes, payload_part_size: int) -> None:
1499 self.payloads = [
1500 payload[i * payload_part_size : (i + 1) * payload_part_size]
1501 for i in range(NUMBER_OF_READS + 1)
1502 ]
1503
1504 assert b"".join(self.payloads) == payload
1505
1506 def read(self, _: int) -> bytes: # type: ignore[override]
1507 # Amount is unused.
1508 if len(self.payloads) > 0:
1509 return self.payloads.pop(0)
1510 return b""
1511
1512 def read1(self, amt: int) -> bytes: # type: ignore[override]
1513 return self.read(amt)
1514
1515 uncompressed_data = zlib.decompress(ZLIB_PAYLOAD)
1516
1517 payload_part_size = len(ZLIB_PAYLOAD) // NUMBER_OF_READS
1518 fp = MockCompressedDataReading(ZLIB_PAYLOAD, payload_part_size)
1519 resp = HTTPResponse(
1520 fp, headers={"content-encoding": "deflate"}, preload_content=False
1521 )
1522 stream = resp.stream(PART_SIZE)
1523
1524 parts_positions = [(part, resp.tell()) for part in stream]
1525 end_of_stream = resp.tell()
1526
1527 with pytest.raises(StopIteration):
1528 next(stream)
1529
1530 parts, positions = zip(*parts_positions)
1531
1532 # Check that the payload is equal to the uncompressed data
1533 payload = b"".join(parts)
1534 assert uncompressed_data == payload
1535
1536 # Check that the positions in the stream are correct
1537 # It is difficult to determine programmatically what the positions
1538 # returned by `tell` will be because the `HTTPResponse.read` method may
1539 # call socket `read` a couple of times if it doesn't have enough data
1540 # in the buffer or not call socket `read` at all if it has enough. All
1541 # this depends on the message, how it was compressed, what is
1542 # `PART_SIZE` and `payload_part_size`.
1543 # So for simplicity the expected values are hardcoded.
1544 expected = (92, 184, 230, 276, 322, 368, 414, 460)
1545 assert expected == positions
1546
1547 # Check that the end of the stream is in the correct place
1548 assert len(ZLIB_PAYLOAD) == end_of_stream
1549
1550 # Check that all parts have expected length
1551 expected_last_part_size = len(uncompressed_data) % PART_SIZE
1552 whole_parts = len(uncompressed_data) // PART_SIZE
1553 if expected_last_part_size == 0:
1554 expected_lengths = [PART_SIZE] * whole_parts
1555 else:
1556 expected_lengths = [PART_SIZE] * whole_parts + [expected_last_part_size]
1557 assert expected_lengths == [len(part) for part in parts]
1558
1559 def test_deflate_streaming(self) -> None:
1560 data = zlib.compress(b"foo")
1561
1562 fp = BytesIO(data)
1563 resp = HTTPResponse(
1564 fp, headers={"content-encoding": "deflate"}, preload_content=False
1565 )
1566 stream = resp.stream(2)
1567
1568 assert next(stream) == b"fo"
1569 assert next(stream) == b"o"
1570 with pytest.raises(StopIteration):
1571 next(stream)
1572
1573 def test_deflate2_streaming(self) -> None:
1574 compress = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS)
1575 data = compress.compress(b"foo")
1576 data += compress.flush()
1577
1578 fp = BytesIO(data)
1579 resp = HTTPResponse(
1580 fp, headers={"content-encoding": "deflate"}, preload_content=False
1581 )
1582 stream = resp.stream(2)
1583
1584 assert next(stream) == b"fo"
1585 assert next(stream) == b"o"
1586 with pytest.raises(StopIteration):
1587 next(stream)
1588
1589 def test_empty_stream(self) -> None:
1590 fp = BytesIO(b"")
1591 resp = HTTPResponse(fp, preload_content=False)
1592 stream = resp.stream(2, decode_content=False)
1593
1594 with pytest.raises(StopIteration):
1595 next(stream)
1596
1597 def test_stream_zero_amt(self) -> None:
1598 fp = BytesIO(b"hello")
1599 resp = HTTPResponse(fp, preload_content=False)
1600 data = list(resp.stream(0))
1601 assert data == []
1602
1603 def test_read_chunked_zero_amt(self) -> None:
1604 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1605 r.fp = MockChunkedEncodingResponse([b"hello"]) # type: ignore[assignment]
1606 r.chunked = True
1607 r.chunk_left = None
1608 resp = HTTPResponse(
1609 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1610 )
1611 assert len(list(resp.read_chunked(0))) == 0
1612
1613 @pytest.mark.parametrize(
1614 "preload_content, amt, read_meth",
1615 [
1616 (True, None, "read"),
1617 (False, None, "read"),
1618 (False, 10 * 2**20, "read"),
1619 (False, None, "read1"),
1620 (False, 10 * 2**20, "read1"),
1621 ],
1622 )
1623 @pytest.mark.limit_memory("25 MB", current_thread_only=True)
1624 def test_buffer_memory_usage_decode_one_chunk(
1625 self, preload_content: bool, amt: int, read_meth: str
1626 ) -> None:
1627 content_length = 10 * 2**20 # 10 MiB
1628 fp = BytesIO(zlib.compress(bytes(content_length)))
1629 resp = HTTPResponse(
1630 fp,
1631 preload_content=preload_content,
1632 headers={"content-encoding": "deflate"},
1633 )
1634 data = resp.data if preload_content else getattr(resp, read_meth)(amt)
1635 assert len(data) == content_length
1636
1637 @pytest.mark.parametrize(
1638 "preload_content, amt, read_meth",
1639 [
1640 (True, None, "read"),
1641 (False, None, "read"),
1642 (False, 10 * 2**20, "read"),
1643 (False, None, "read1"),
1644 (False, 10 * 2**20, "read1"),
1645 ],
1646 )
1647 # The body is 10 MiB and reading it must not buffer a second copy, which
1648 # would take the peak to 20 MiB.
1649 # The margin is deliberately wide so that allocation noise cannot fail it.
1650 @pytest.mark.limit_memory("13 MB", current_thread_only=True)
1651 def test_buffer_memory_usage_no_decoding(
1652 self, preload_content: bool, amt: int, read_meth: str
1653 ) -> None:
1654 content_length = 10 * 2**20 # 10 MiB
1655 fp = BytesIO(bytes(content_length))
1656 resp = HTTPResponse(fp, preload_content=preload_content, decode_content=False)
1657 data = resp.data if preload_content else getattr(resp, read_meth)(amt)
1658 assert len(data) == content_length
1659
1660 def test_length_no_header(self) -> None:
1661 fp = BytesIO(b"12345")
1662 resp = HTTPResponse(fp, preload_content=False)
1663 assert resp.length_remaining is None
1664
1665 def test_length_w_valid_header(self) -> None:
1666 headers = {"content-length": "5"}
1667 fp = BytesIO(b"12345")
1668
1669 resp = HTTPResponse(fp, headers=headers, preload_content=False)
1670 assert resp.length_remaining == 5
1671
1672 def test_length_w_bad_header(self) -> None:
1673 garbage = {"content-length": "foo"}
1674 fp = BytesIO(b"12345")
1675
1676 resp = HTTPResponse(fp, headers=garbage, preload_content=False)
1677 assert resp.length_remaining is None
1678
1679 garbage["content-length"] = "-10"
1680 resp = HTTPResponse(fp, headers=garbage, preload_content=False)
1681 assert resp.length_remaining is None
1682
1683 def test_length_when_chunked(self) -> None:
1684 # This is expressly forbidden in RFC 7230 sec 3.3.2
1685 # We fall back to chunked in this case and try to
1686 # handle response ignoring content length.
1687 headers = {"content-length": "5", "transfer-encoding": "chunked"}
1688 fp = BytesIO(b"12345")
1689
1690 resp = HTTPResponse(fp, headers=headers, preload_content=False)
1691 assert resp.length_remaining is None
1692
1693 def test_length_with_multiple_content_lengths(self) -> None:
1694 headers = {"content-length": "5, 5, 5"}
1695 garbage = {"content-length": "5, 42"}
1696 fp = BytesIO(b"abcde")
1697
1698 resp = HTTPResponse(fp, headers=headers, preload_content=False)
1699 assert resp.length_remaining == 5
1700
1701 with pytest.raises(InvalidHeader):
1702 HTTPResponse(fp, headers=garbage, preload_content=False)
1703
1704 def test_length_after_read(self) -> None:
1705 headers = {"content-length": "5"}
1706
1707 # Test no defined length
1708 fp = BytesIO(b"12345")
1709 resp = HTTPResponse(fp, preload_content=False)
1710 resp.read()
1711 assert resp.length_remaining is None
1712
1713 # Test our update from content-length
1714 fp = BytesIO(b"12345")
1715 resp = HTTPResponse(fp, headers=headers, preload_content=False)
1716 resp.read()
1717 assert resp.length_remaining == 0
1718
1719 # Test partial read
1720 fp = BytesIO(b"12345")
1721 resp = HTTPResponse(fp, headers=headers, preload_content=False)
1722 data = resp.stream(2)
1723 next(data)
1724 assert resp.length_remaining == 3
1725
1726 def test_mock_httpresponse_stream(self) -> None:
1727 # Mock out a HTTP Request that does enough to make it through urllib3's
1728 # read() and close() calls, and also exhausts and underlying file
1729 # object.
1730 class MockHTTPRequest:
1731 def __init__(self) -> None:
1732 self.fp: BytesIO | None = None
1733
1734 def read(self, amt: int) -> bytes:
1735 assert self.fp is not None
1736 data = self.fp.read(amt)
1737 if not data:
1738 self.fp = None
1739
1740 return data
1741
1742 def read1(self, amt: int) -> bytes:
1743 return self.read(1)
1744
1745 def close(self) -> None:
1746 self.fp = None
1747
1748 bio = BytesIO(b"foo")
1749 fp = MockHTTPRequest()
1750 fp.fp = bio
1751 resp = HTTPResponse(fp, preload_content=False) # type: ignore[arg-type]
1752 stream = resp.stream(2)
1753
1754 assert next(stream) == b"fo"
1755 assert next(stream) == b"o"
1756 with pytest.raises(StopIteration):
1757 next(stream)
1758
1759 def test_mock_transfer_encoding_chunked(self) -> None:
1760 stream = [b"fo", b"o", b"bar"]
1761 fp = MockChunkedEncodingResponse(stream)
1762 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1763 r.fp = fp # type: ignore[assignment]
1764 resp = HTTPResponse(
1765 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1766 )
1767
1768 for i, c in enumerate(resp.stream()):
1769 assert c == stream[i]
1770
1771 def test_mock_gzipped_transfer_encoding_chunked_decoded(self) -> None:
1772 """Show that we can decode the gzipped and chunked body."""
1773
1774 def stream() -> typing.Generator[bytes]:
1775 # Set up a generator to chunk the gzipped body
1776 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
1777 data = compress.compress(b"foobar")
1778 data += compress.flush()
1779 for i in range(0, len(data), 2):
1780 yield data[i : i + 2]
1781
1782 fp = MockChunkedEncodingResponse(list(stream()))
1783 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1784 r.fp = fp # type: ignore[assignment]
1785 headers = {"transfer-encoding": "chunked", "content-encoding": "gzip"}
1786 resp = HTTPResponse(r, preload_content=False, headers=headers)
1787
1788 data = b""
1789 for c in resp.stream(decode_content=True):
1790 data += c
1791
1792 assert b"foobar" == data
1793
1794 def test_mock_transfer_encoding_chunked_custom_read(self) -> None:
1795 stream = [b"foooo", b"bbbbaaaaar"]
1796 fp = MockChunkedEncodingResponse(stream)
1797 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1798 r.fp = fp # type: ignore[assignment]
1799 r.chunked = True
1800 r.chunk_left = None
1801 resp = HTTPResponse(
1802 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1803 )
1804 expected_response = [b"fo", b"oo", b"o", b"bb", b"bb", b"aa", b"aa", b"ar"]
1805 response = list(resp.read_chunked(2))
1806 assert expected_response == response
1807
1808 @pytest.mark.parametrize("read_chunked_args", ((), (None,), (-1,)))
1809 def test_mock_transfer_encoding_chunked_unlmtd_read(
1810 self, read_chunked_args: tuple[typing.Any, ...]
1811 ) -> None:
1812 stream = [b"foooo", b"bbbbaaaaar"]
1813 fp = MockChunkedEncodingResponse(stream)
1814 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1815 r.fp = fp # type: ignore[assignment]
1816 r.chunked = True
1817 r.chunk_left = None
1818 resp = HTTPResponse(
1819 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1820 )
1821 assert stream == list(resp.read_chunked(*read_chunked_args))
1822
1823 def test_read_not_chunked_response_as_chunks(self) -> None:
1824 fp = BytesIO(b"foo")
1825 resp = HTTPResponse(fp, preload_content=False)
1826 r = resp.read_chunked()
1827 with pytest.raises(ResponseNotChunked):
1828 next(r)
1829
1830 def test_read_chunked_not_supported(self) -> None:
1831 fp = BytesIO(b"foo")
1832 resp = HTTPResponse(
1833 fp, preload_content=False, headers={"transfer-encoding": "chunked"}
1834 )
1835 r = resp.read_chunked()
1836 with pytest.raises(BodyNotHttplibCompatible):
1837 next(r)
1838
1839 def test_buggy_incomplete_read(self) -> None:
1840 # Simulate buggy versions of Python (<2.7.4)
1841 # See http://bugs.python.org/issue16298
1842 content_length = 1337
1843 fp = BytesIO(b"")
1844 resp = HTTPResponse(
1845 fp,
1846 headers={"content-length": str(content_length)},
1847 preload_content=False,
1848 enforce_content_length=True,
1849 )
1850 with pytest.raises(ProtocolError) as ctx:
1851 resp.read(3)
1852
1853 orig_ex = ctx.value.args[1]
1854 assert isinstance(orig_ex, IncompleteRead)
1855 assert orig_ex.partial == 0
1856 assert orig_ex.expected == content_length
1857
1858 def test_incomplete_chunk(self) -> None:
1859 stream = [b"foooo", b"bbbbaaaaar"]
1860 fp = MockChunkedIncompleteRead(stream)
1861 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1862 r.fp = fp # type: ignore[assignment]
1863 r.chunked = True
1864 r.chunk_left = None
1865 resp = HTTPResponse(
1866 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1867 )
1868 with pytest.raises(ProtocolError) as ctx:
1869 next(resp.read_chunked())
1870
1871 orig_ex = ctx.value.args[1]
1872 assert isinstance(orig_ex, httplib_IncompleteRead)
1873
1874 def test_invalid_chunk_length(self) -> None:
1875 stream = [b"foooo", b"bbbbaaaaar"]
1876 fp = MockChunkedInvalidChunkLength(stream)
1877 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1878 r.fp = fp # type: ignore[assignment]
1879 r.chunked = True
1880 r.chunk_left = None
1881 resp = HTTPResponse(
1882 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1883 )
1884 with pytest.raises(ProtocolError) as ctx:
1885 next(resp.read_chunked())
1886
1887 orig_ex = ctx.value.args[1]
1888 msg = (
1889 "(\"Connection broken: InvalidChunkLength(got length b'ZZZ\\\\r\\\\n', 0 bytes read)\", "
1890 "InvalidChunkLength(got length b'ZZZ\\r\\n', 0 bytes read))"
1891 )
1892 assert str(ctx.value) == msg
1893 assert isinstance(orig_ex, InvalidChunkLength)
1894 assert orig_ex.length == fp.BAD_LENGTH_LINE.encode()
1895
1896 def test_chunk_size_line_too_long(self) -> None:
1897 # A malicious server can send a chunk-size line with no newline. urllib3's
1898 # streaming path must reject it with a bounded read rather than buffering
1899 # the whole line (memory exhaustion). See GHSA / CVE for chunked DoS.
1900 stream = [b"foooo"]
1901 fp = MockChunkedEncodingLongChunkSizeLine(stream)
1902 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1903 r.fp = fp # type: ignore[assignment]
1904 r.chunked = True
1905 r.chunk_left = None
1906 resp = HTTPResponse(
1907 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1908 )
1909 with pytest.raises(ProtocolError) as ctx:
1910 next(resp.read_chunked())
1911
1912 assert "chunk size line exceeded maximum allowed length" in str(ctx.value)
1913
1914 @pytest.mark.parametrize(
1915 "trailer_length",
1916 [
1917 _MAX_CHUNK_LINE_LENGTH - 1,
1918 _MAX_CHUNK_LINE_LENGTH,
1919 _MAX_CHUNK_LINE_LENGTH + 1,
1920 ],
1921 )
1922 @pytest.mark.parametrize("line_ending", [b"\r\n", b""])
1923 def test_chunk_trailer_line_length(
1924 self, trailer_length: int, line_ending: bytes
1925 ) -> None:
1926 # The line limit includes its CRLF, but not the final blank line.
1927 trailer = b"X:" + b"x" * (trailer_length - 2 - len(line_ending)) + line_ending
1928 fp = BytesIO(b"3\r\nfoo\r\n0\r\n" + trailer + (b"\r\n" if line_ending else b""))
1929 r = httplib.HTTPResponse(MockSock, method="GET") # type: ignore[arg-type]
1930 r.fp = fp # type: ignore[assignment]
1931 resp = HTTPResponse(
1932 r,
1933 preload_content=False,
1934 headers={"transfer-encoding": "chunked"},
1935 original_response=r,
1936 )
1937 chunks = resp.read_chunked()
1938 assert next(chunks) == b"foo"
1939
1940 if trailer_length > _MAX_CHUNK_LINE_LENGTH:
1941 with pytest.raises(
1942 ProtocolError,
1943 match="Response chunk trailer line exceeded maximum allowed length",
1944 ):
1945 next(chunks)
1946 else:
1947 assert list(chunks) == []
1948
1949 assert fp.closed
1950 assert r.isclosed()
1951 assert resp.closed
1952
1953 def test_truncated_before_chunk(self) -> None:
1954 stream = [b"foooo", b"bbbbaaaaar"]
1955 fp = MockChunkedNoChunks(stream)
1956 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1957 r.fp = fp # type: ignore[assignment]
1958 r.chunked = True
1959 r.chunk_left = None
1960 resp = HTTPResponse(
1961 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1962 )
1963 with pytest.raises(ProtocolError) as ctx:
1964 next(resp.read_chunked())
1965
1966 assert str(ctx.value) == "Response ended prematurely"
1967
1968 def test_chunked_response_without_crlf_on_end(self) -> None:
1969 stream = [b"foo", b"bar", b"baz"]
1970 fp = MockChunkedEncodingWithoutCRLFOnEnd(stream)
1971 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1972 r.fp = fp # type: ignore[assignment]
1973 r.chunked = True
1974 r.chunk_left = None
1975 resp = HTTPResponse(
1976 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1977 )
1978 assert stream == list(resp.stream())
1979
1980 def test_chunked_response_with_extensions(self) -> None:
1981 stream = [b"foo", b"bar"]
1982 fp = MockChunkedEncodingWithExtensions(stream)
1983 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
1984 r.fp = fp # type: ignore[assignment]
1985 r.chunked = True
1986 r.chunk_left = None
1987 resp = HTTPResponse(
1988 r, preload_content=False, headers={"transfer-encoding": "chunked"}
1989 )
1990 assert stream == list(resp.stream())
1991
1992 def test_chunked_head_response(self) -> None:
1993 r = httplib.HTTPResponse(MockSock, method="HEAD") # type: ignore[arg-type]
1994 r.chunked = True
1995 r.chunk_left = None
1996 resp = HTTPResponse(
1997 "",
1998 preload_content=False,
1999 headers={"transfer-encoding": "chunked"},
2000 original_response=r,
2001 )
2002 assert resp.chunked is True
2003
2004 setattr(resp, "supports_chunked_reads", lambda: True)
2005 setattr(resp, "release_conn", mock.Mock())
2006 for _ in resp.stream():
2007 continue
2008 resp.release_conn.assert_called_once_with() # type: ignore[attr-defined]
2009
2010 def test_getheaders(self) -> None:
2011 headers = {"host": "example.com"}
2012 r = HTTPResponse(headers=headers)
2013 assert r.getheaders() is r.headers
2014
2015 def test_get_case_insensitive_headers(self) -> None:
2016 headers = {"host": "example.com"}
2017 r = HTTPResponse(headers=headers)
2018 assert r.headers.get("host") == r.getheader("host") == "example.com"
2019 assert r.headers.get("Host") == r.getheader("Host") == "example.com"
2020
2021 def test_retries(self) -> None:
2022 fp = BytesIO(b"")
2023 resp = HTTPResponse(fp)
2024 assert resp.retries is None
2025 retry = Retry()
2026 resp = HTTPResponse(fp, retries=retry)
2027 assert resp.retries == retry
2028
2029 def test_geturl(self) -> None:
2030 fp = BytesIO(b"")
2031 request_url = "https://example.com"
2032 resp = HTTPResponse(fp, request_url=request_url)
2033 assert resp.geturl() == request_url
2034
2035 def test_url(self) -> None:
2036 fp = BytesIO(b"")
2037 request_url = "https://example.com"
2038 resp = HTTPResponse(fp, request_url=request_url)
2039 assert resp.url == request_url
2040 resp.url = "https://anotherurl.com"
2041 assert resp.url == "https://anotherurl.com"
2042
2043 def test_geturl_retries(self) -> None:
2044 fp = BytesIO(b"")
2045 resp = HTTPResponse(fp, request_url="http://example.com")
2046 request_histories = (
2047 RequestHistory(
2048 method="GET",
2049 url="http://example.com",
2050 error=None,
2051 status=301,
2052 redirect_location="https://example.com/",
2053 ),
2054 RequestHistory(
2055 method="GET",
2056 url="https://example.com/",
2057 error=None,
2058 status=301,
2059 redirect_location="https://www.example.com",
2060 ),
2061 )
2062 retry = Retry(history=request_histories)
2063 resp = HTTPResponse(fp, retries=retry)
2064 assert resp.geturl() == "https://www.example.com"
2065
2066 @pytest.mark.parametrize(
2067 ["payload", "expected_stream"],
2068 [
2069 (b"", []),
2070 (b"\n", [b"\n"]),
2071 (b"\n\n\n", [b"\n", b"\n", b"\n"]),
2072 (b"abc\ndef", [b"abc\n", b"def"]),
2073 (b"Hello\nworld\n\n\n!", [b"Hello\n", b"world\n", b"\n", b"\n", b"!"]),
2074 ],
2075 )
2076 def test__iter__(self, payload: bytes, expected_stream: list[bytes]) -> None:
2077 actual_stream = []
2078 for chunk in HTTPResponse(BytesIO(payload), preload_content=False):
2079 actual_stream.append(chunk)
2080
2081 assert actual_stream == expected_stream
2082
2083 def test__iter__decode_content(self) -> None:
2084 def stream() -> typing.Generator[bytes]:
2085 # Set up a generator to chunk the gzipped body
2086 compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
2087 data = compress.compress(b"foo\nbar")
2088 data += compress.flush()
2089 for i in range(0, len(data), 2):
2090 yield data[i : i + 2]
2091
2092 fp = MockChunkedEncodingResponse(list(stream()))
2093 r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
2094 r.fp = fp # type: ignore[assignment]
2095 headers = {"transfer-encoding": "chunked", "content-encoding": "gzip"}
2096 resp = HTTPResponse(r, preload_content=False, headers=headers)
2097
2098 data = b""
2099 for c in resp:
2100 data += c
2101
2102 assert b"foo\nbar" == data
2103
2104 def test_non_timeout_ssl_error_on_read(self) -> None:
2105 mac_error = ssl.SSLError(
2106 "SSL routines", "ssl3_get_record", "decryption failed or bad record mac"
2107 )
2108
2109 @contextlib.contextmanager
2110 def make_bad_mac_fp() -> typing.Generator[BytesIO]:
2111 fp = BytesIO(b"")
2112 with mock.patch.object(fp, "read") as fp_read:
2113 # mac/decryption error
2114 fp_read.side_effect = mac_error
2115 yield fp
2116
2117 with make_bad_mac_fp() as fp:
2118 with pytest.raises(SSLError) as e:
2119 HTTPResponse(fp)
2120 assert e.value.args[0] == mac_error
2121
2122 with make_bad_mac_fp() as fp:
2123 resp = HTTPResponse(fp, preload_content=False)
2124 with pytest.raises(SSLError) as e:
2125 resp.read()
2126 assert e.value.args[0] == mac_error
2127
2128 def test_unexpected_body(self) -> None:
2129 with pytest.raises(ProtocolError) as excinfo:
2130 fp = BytesIO(b"12345")
2131 headers = {"content-length": "5"}
2132 resp = HTTPResponse(fp, status=204, headers=headers)
2133 resp.read(16)
2134 assert "Response may not contain content" in str(excinfo.value)
2135
2136 with pytest.raises(ProtocolError):
2137 fp = BytesIO(b"12345")
2138 headers = {"content-length": "0"}
2139 resp = HTTPResponse(fp, status=204, headers=headers)
2140 resp.read(16)
2141 assert "Response may not contain content" in str(excinfo.value)
2142
2143 with pytest.raises(ProtocolError):
2144 fp = BytesIO(b"12345")
2145 resp = HTTPResponse(fp, status=204)
2146 resp.read(16)
2147 assert "Response may not contain content" in str(excinfo.value)
2148
2149
2150 class MockChunkedEncodingResponse:
2151 def __init__(self, content: list[bytes]) -> None:
2152 """
2153 content: collection of str, each str is a chunk in response
2154 """
2155 self.content = content
2156 self.index = 0 # This class iterates over self.content.
2157 self.closed = False
2158 self.cur_chunk = b""
2159 self.chunks_exhausted = False
2160
2161 def _encode_chunk(self, chunk: bytes) -> bytes:
2162 # In the general case, we can't decode the chunk to unicode
2163 length = f"{len(chunk):X}\r\n"
2164 return length.encode() + chunk + b"\r\n"
2165
2166 def _pop_new_chunk(self) -> bytes:
2167 if self.chunks_exhausted:
2168 return b""
2169 try:
2170 chunk = self.content[self.index]
2171 except IndexError:
2172 chunk = b""
2173 self.chunks_exhausted = True
2174 else:
2175 self.index += 1
2176 chunk = self._encode_chunk(chunk)
2177 if not isinstance(chunk, bytes):
2178 chunk = chunk.encode()
2179 assert isinstance(chunk, bytes)
2180 return chunk
2181
2182 def pop_current_chunk(self, amt: int = -1, till_crlf: bool = False) -> bytes:
2183 if amt > 0 and till_crlf:
2184 raise ValueError("Can't specify amt and till_crlf.")
2185 if len(self.cur_chunk) <= 0:
2186 self.cur_chunk = self._pop_new_chunk()
2187 if till_crlf:
2188 try:
2189 i = self.cur_chunk.index(b"\r\n")
2190 except ValueError:
2191 # No CRLF in current chunk -- probably caused by encoder.
2192 self.cur_chunk = b""
2193 return b""
2194 else:
2195 chunk_part = self.cur_chunk[: i + 2]
2196 self.cur_chunk = self.cur_chunk[i + 2 :]
2197 return chunk_part
2198 elif amt <= -1:
2199 chunk_part = self.cur_chunk
2200 self.cur_chunk = b""
2201 return chunk_part
2202 else:
2203 try:
2204 chunk_part = self.cur_chunk[:amt]
2205 except IndexError:
2206 chunk_part = self.cur_chunk
2207 self.cur_chunk = b""
2208 else:
2209 self.cur_chunk = self.cur_chunk[amt:]
2210 return chunk_part
2211
2212 def readline(self, amt: int = -1) -> bytes:
2213 # Emulate a real file object's readline(size): return bytes up to and
2214 # including the first newline, or at most ``amt`` bytes when ``amt >= 0``,
2215 # whichever comes first.
2216 if len(self.cur_chunk) <= 0:
2217 self.cur_chunk = self._pop_new_chunk()
2218 line = self.cur_chunk
2219 newline_index = line.find(b"\n")
2220 if newline_index != -1:
2221 line = line[: newline_index + 1]
2222 if 0 <= amt < len(line):
2223 line = line[:amt]
2224 self.cur_chunk = self.cur_chunk[len(line) :]
2225 return line
2226
2227 def read(self, amt: int = -1) -> bytes:
2228 return self.pop_current_chunk(amt)
2229
2230 def read1(self, amt: int = -1) -> bytes:
2231 return self.pop_current_chunk(amt)
2232
2233 def flush(self) -> None:
2234 # Python 3 wants this method.
2235 pass
2236
2237 def close(self) -> None:
2238 self.closed = True
2239
2240
2241 class MockChunkedIncompleteRead(MockChunkedEncodingResponse):
2242 def _encode_chunk(self, chunk: bytes) -> bytes:
2243 return f"9999\r\n{chunk.decode()}\r\n".encode()
2244
2245
2246 class MockChunkedInvalidChunkLength(MockChunkedEncodingResponse):
2247 BAD_LENGTH_LINE = "ZZZ\r\n"
2248
2249 def _encode_chunk(self, chunk: bytes) -> bytes:
2250 return f"{self.BAD_LENGTH_LINE}{chunk.decode()}\r\n".encode()
2251
2252
2253 class MockChunkedEncodingLongChunkSizeLine(MockChunkedEncodingResponse):
2254 def _encode_chunk(self, chunk: bytes) -> bytes:
2255 # A chunk-size line far longer than _MAX_CHUNK_LINE_LENGTH with no
2256 # newline, simulating a malicious server that never terminates the
2257 # size line (memory-exhaustion attack).
2258 return b"f" * (2**16 + 1024)
2259
2260
2261 class MockChunkedEncodingWithoutCRLFOnEnd(MockChunkedEncodingResponse):
2262 def _encode_chunk(self, chunk: bytes) -> bytes:
2263 return "{:X}\r\n{}{}".format(
2264 len(chunk),
2265 chunk.decode(),
2266 "\r\n" if len(chunk) > 0 else "",
2267 ).encode()
2268
2269
2270 class MockChunkedEncodingWithExtensions(MockChunkedEncodingResponse):
2271 def _encode_chunk(self, chunk: bytes) -> bytes:
2272 return f"{len(chunk):X};asd=qwe\r\n{chunk.decode()}\r\n".encode()
2273
2274
2275 class MockChunkedNoChunks(MockChunkedEncodingResponse):
2276 def _encode_chunk(self, chunk: bytes) -> bytes:
2277 return b""
2278
2279
2280 class MockSock:
2281 @classmethod
2282 def makefile(cls, *args: typing.Any, **kwargs: typing.Any) -> None:
2283 return