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