test_decoders.py
This file
Path
tests/test_decoders.py
336 lines · 9.6 KiB · Python
Last changed by
Add support for zstd decoding (#3139)Michiel W. Beijenbefore adoption392dbe4
History of this fileTake it
1from __future__ import annotations23import io4import typing5import zlib67import chardet8import pytest9import zstandard as zstd1011import httpx121314def test_deflate():15 """16 Deflate encoding may use either 'zlib' or 'deflate' in the wild.1718 https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129719 """20 body = b"test 123"21 compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)22 compressed_body = compressor.compress(body) + compressor.flush()2324 headers = [(b"Content-Encoding", b"deflate")]25 response = httpx.Response(26 200,27 headers=headers,28 content=compressed_body,29 )30 assert response.content == body313233def test_zlib():34 """35 Deflate encoding may use either 'zlib' or 'deflate' in the wild.3637 https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129738 """39 body = b"test 123"40 compressed_body = zlib.compress(body)4142 headers = [(b"Content-Encoding", b"deflate")]43 response = httpx.Response(44 200,45 headers=headers,46 content=compressed_body,47 )48 assert response.content == body495051def test_gzip():52 body = b"test 123"53 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)54 compressed_body = compressor.compress(body) + compressor.flush()5556 headers = [(b"Content-Encoding", b"gzip")]57 response = httpx.Response(58 200,59 headers=headers,60 content=compressed_body,61 )62 assert response.content == body636465def test_brotli():66 body = b"test 123"67 compressed_body = b"\x8b\x03\x80test 123\x03"6869 headers = [(b"Content-Encoding", b"br")]70 response = httpx.Response(71 200,72 headers=headers,73 content=compressed_body,74 )75 assert response.content == body767778def test_zstd():79 body = b"test 123"80 compressed_body = zstd.compress(body)8182 headers = [(b"Content-Encoding", b"zstd")]83 response = httpx.Response(84 200,85 headers=headers,86 content=compressed_body,87 )88 assert response.content == body899091def test_zstd_decoding_error():92 compressed_body = "this_is_not_zstd_compressed_data"9394 headers = [(b"Content-Encoding", b"zstd")]95 with pytest.raises(httpx.DecodingError):96 httpx.Response(97 200,98 headers=headers,99 content=compressed_body,100 )101102103def test_zstd_multiframe():104 # test inspired by urllib3 test suite105 data = (106 # Zstandard frame107 zstd.compress(b"foo")108 # skippable frame (must be ignored)109 + bytes.fromhex(110 "50 2A 4D 18" # Magic_Number (little-endian)111 "07 00 00 00" # Frame_Size (little-endian)112 "00 00 00 00 00 00 00" # User_Data113 )114 # Zstandard frame115 + zstd.compress(b"bar")116 )117 compressed_body = io.BytesIO(data)118119 headers = [(b"Content-Encoding", b"zstd")]120 response = httpx.Response(200, headers=headers, content=compressed_body)121 response.read()122 assert response.content == b"foobar"123124125def test_multi():126 body = b"test 123"127128 deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)129 compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()130131 gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)132 compressed_body = (133 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()134 )135136 headers = [(b"Content-Encoding", b"deflate, gzip")]137 response = httpx.Response(138 200,139 headers=headers,140 content=compressed_body,141 )142 assert response.content == body143144145def test_multi_with_identity():146 body = b"test 123"147 compressed_body = b"\x8b\x03\x80test 123\x03"148149 headers = [(b"Content-Encoding", b"br, identity")]150 response = httpx.Response(151 200,152 headers=headers,153 content=compressed_body,154 )155 assert response.content == body156157 headers = [(b"Content-Encoding", b"identity, br")]158 response = httpx.Response(159 200,160 headers=headers,161 content=compressed_body,162 )163 assert response.content == body164165166@pytest.mark.anyio167async def test_streaming():168 body = b"test 123"169 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)170171 async def compress(body: bytes) -> typing.AsyncIterator[bytes]:172 yield compressor.compress(body)173 yield compressor.flush()174175 headers = [(b"Content-Encoding", b"gzip")]176 response = httpx.Response(177 200,178 headers=headers,179 content=compress(body),180 )181 assert not hasattr(response, "body")182 assert await response.aread() == body183184185@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))186def test_empty_content(header_value):187 headers = [(b"Content-Encoding", header_value)]188 response = httpx.Response(189 200,190 headers=headers,191 content=b"",192 )193 assert response.content == b""194195196@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))197def test_decoders_empty_cases(header_value):198 headers = [(b"Content-Encoding", header_value)]199 response = httpx.Response(content=b"", status_code=200, headers=headers)200 assert response.read() == b""201202203@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))204def test_decoding_errors(header_value):205 headers = [(b"Content-Encoding", header_value)]206 compressed_body = b"invalid"207 with pytest.raises(httpx.DecodingError):208 request = httpx.Request("GET", "https://example.org")209 httpx.Response(200, headers=headers, content=compressed_body, request=request)210211 with pytest.raises(httpx.DecodingError):212 httpx.Response(200, headers=headers, content=compressed_body)213214215@pytest.mark.parametrize(216 ["data", "encoding"],217 [218 ((b"Hello,", b" world!"), "ascii"),219 ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),220 ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),221 ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),222 ],223)224@pytest.mark.anyio225async def test_text_decoder_with_autodetect(data, encoding):226 async def iterator() -> typing.AsyncIterator[bytes]:227 nonlocal data228 for chunk in data:229 yield chunk230231 def autodetect(content):232 return chardet.detect(content).get("encoding")233234 # Accessing `.text` on a read response.235 response = httpx.Response(200, content=iterator(), default_encoding=autodetect)236 await response.aread()237 assert response.text == (b"".join(data)).decode(encoding)238239 # Streaming `.aiter_text` iteratively.240 # Note that if we streamed the text *without* having read it first, then241 # we won't get a `charset_normalizer` guess, and will instead always rely242 # on utf-8 if no charset is specified.243 text = "".join([part async for part in response.aiter_text()])244 assert text == (b"".join(data)).decode(encoding)245246247@pytest.mark.anyio248async def test_text_decoder_known_encoding():249 async def iterator() -> typing.AsyncIterator[bytes]:250 yield b"\x83g"251 yield b"\x83"252 yield b"\x89\x83x\x83\x8b"253254 response = httpx.Response(255 200,256 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],257 content=iterator(),258 )259260 await response.aread()261 assert "".join(response.text) == "トラベル"262263264def test_text_decoder_empty_cases():265 response = httpx.Response(200, content=b"")266 assert response.text == ""267268 response = httpx.Response(200, content=[b""])269 response.read()270 assert response.text == ""271272273@pytest.mark.parametrize(274 ["data", "expected"],275 [((b"Hello,", b" world!"), ["Hello,", " world!"])],276)277def test_streaming_text_decoder(278 data: typing.Iterable[bytes], expected: list[str]279) -> None:280 response = httpx.Response(200, content=iter(data))281 assert list(response.iter_text()) == expected282283284def test_line_decoder_nl():285 response = httpx.Response(200, content=[b""])286 assert list(response.iter_lines()) == []287288 response = httpx.Response(200, content=[b"", b"a\n\nb\nc"])289 assert list(response.iter_lines()) == ["a", "", "b", "c"]290291 # Issue #1033292 response = httpx.Response(293 200, content=[b"", b"12345\n", b"foo ", b"bar ", b"baz\n"]294 )295 assert list(response.iter_lines()) == ["12345", "foo bar baz"]296297298def test_line_decoder_cr():299 response = httpx.Response(200, content=[b"", b"a\r\rb\rc"])300 assert list(response.iter_lines()) == ["a", "", "b", "c"]301302 response = httpx.Response(200, content=[b"", b"a\r\rb\rc\r"])303 assert list(response.iter_lines()) == ["a", "", "b", "c"]304305 # Issue #1033306 response = httpx.Response(307 200, content=[b"", b"12345\r", b"foo ", b"bar ", b"baz\r"]308 )309 assert list(response.iter_lines()) == ["12345", "foo bar baz"]310311312def test_line_decoder_crnl():313 response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc"])314 assert list(response.iter_lines()) == ["a", "", "b", "c"]315316 response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc\r\n"])317 assert list(response.iter_lines()) == ["a", "", "b", "c"]318319 response = httpx.Response(200, content=[b"", b"a\r", b"\n\r\nb\r\nc"])320 assert list(response.iter_lines()) == ["a", "", "b", "c"]321322 # Issue #1033323 response = httpx.Response(200, content=[b"", b"12345\r\n", b"foo bar baz\r\n"])324 assert list(response.iter_lines()) == ["12345", "foo bar baz"]325326327def test_invalid_content_encoding_header():328 headers = [(b"Content-Encoding", b"invalid-header")]329 body = b"test 123"330331 response = httpx.Response(332 200,333 headers=headers,334 content=body,335 )336 assert response.content == body