test_decoders.py
This file
Path
tests/test_decoders.py
347 lines · 10.2 KiB · Python
Last changed by
replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
History of this fileTake it
1import typing2import zlib34import chardet5import pytest67import httpx8from httpx._compat import brotli9from httpx._decoders import ByteChunker, LineDecoder, TextChunker, TextDecoder101112def test_deflate():13 """14 Deflate encoding may use either 'zlib' or 'deflate' in the wild.1516 https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129717 """18 body = b"test 123"19 compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)20 compressed_body = compressor.compress(body) + compressor.flush()2122 headers = [(b"Content-Encoding", b"deflate")]23 response = httpx.Response(24 200,25 headers=headers,26 content=compressed_body,27 )28 assert response.content == body293031def test_zlib():32 """33 Deflate encoding may use either 'zlib' or 'deflate' in the wild.3435 https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129736 """37 body = b"test 123"38 compressed_body = zlib.compress(body)3940 headers = [(b"Content-Encoding", b"deflate")]41 response = httpx.Response(42 200,43 headers=headers,44 content=compressed_body,45 )46 assert response.content == body474849def test_gzip():50 body = b"test 123"51 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)52 compressed_body = compressor.compress(body) + compressor.flush()5354 headers = [(b"Content-Encoding", b"gzip")]55 response = httpx.Response(56 200,57 headers=headers,58 content=compressed_body,59 )60 assert response.content == body616263def test_brotli():64 body = b"test 123"65 compressed_body = brotli.compress(body)6667 headers = [(b"Content-Encoding", b"br")]68 response = httpx.Response(69 200,70 headers=headers,71 content=compressed_body,72 )73 assert response.content == body747576def test_multi():77 body = b"test 123"7879 deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)80 compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()8182 gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)83 compressed_body = (84 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()85 )8687 headers = [(b"Content-Encoding", b"deflate, gzip")]88 response = httpx.Response(89 200,90 headers=headers,91 content=compressed_body,92 )93 assert response.content == body949596def test_multi_with_identity():97 body = b"test 123"98 compressed_body = brotli.compress(body)99100 headers = [(b"Content-Encoding", b"br, identity")]101 response = httpx.Response(102 200,103 headers=headers,104 content=compressed_body,105 )106 assert response.content == body107108 headers = [(b"Content-Encoding", b"identity, br")]109 response = httpx.Response(110 200,111 headers=headers,112 content=compressed_body,113 )114 assert response.content == body115116117@pytest.mark.anyio118async def test_streaming():119 body = b"test 123"120 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)121122 async def compress(body: bytes) -> typing.AsyncIterator[bytes]:123 yield compressor.compress(body)124 yield compressor.flush()125126 headers = [(b"Content-Encoding", b"gzip")]127 response = httpx.Response(128 200,129 headers=headers,130 content=compress(body),131 )132 assert not hasattr(response, "body")133 assert await response.aread() == body134135136@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))137def test_empty_content(header_value):138 headers = [(b"Content-Encoding", header_value)]139 response = httpx.Response(140 200,141 headers=headers,142 content=b"",143 )144 assert response.content == b""145146147@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))148def test_decoders_empty_cases(header_value):149 headers = [(b"Content-Encoding", header_value)]150 response = httpx.Response(content=b"", status_code=200, headers=headers)151 assert response.read() == b""152153154@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))155def test_decoding_errors(header_value):156 headers = [(b"Content-Encoding", header_value)]157 body = b"test 123"158 compressed_body = brotli.compress(body)[3:]159 with pytest.raises(httpx.DecodingError):160 request = httpx.Request("GET", "https://example.org")161 httpx.Response(200, headers=headers, content=compressed_body, request=request)162163 with pytest.raises(httpx.DecodingError):164 httpx.Response(200, headers=headers, content=compressed_body)165166167@pytest.mark.parametrize(168 ["data", "encoding"],169 [170 ((b"Hello,", b" world!"), "ascii"),171 ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),172 ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),173 ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),174 ],175)176@pytest.mark.anyio177async def test_text_decoder_with_autodetect(data, encoding):178 async def iterator() -> typing.AsyncIterator[bytes]:179 nonlocal data180 for chunk in data:181 yield chunk182183 def autodetect(content):184 return chardet.detect(content).get("encoding")185186 # Accessing `.text` on a read response.187 response = httpx.Response(200, content=iterator(), default_encoding=autodetect)188 await response.aread()189 assert response.text == (b"".join(data)).decode(encoding)190191 # Streaming `.aiter_text` iteratively.192 # Note that if we streamed the text *without* having read it first, then193 # we won't get a `charset_normalizer` guess, and will instead always rely194 # on utf-8 if no charset is specified.195 text = "".join([part async for part in response.aiter_text()])196 assert text == (b"".join(data)).decode(encoding)197198199@pytest.mark.anyio200async def test_text_decoder_known_encoding():201 async def iterator() -> typing.AsyncIterator[bytes]:202 yield b"\x83g"203 yield b"\x83"204 yield b"\x89\x83x\x83\x8b"205206 response = httpx.Response(207 200,208 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],209 content=iterator(),210 )211212 await response.aread()213 assert "".join(response.text) == "トラベル"214215216def test_text_decoder_empty_cases():217 decoder = TextDecoder()218 assert decoder.flush() == ""219220 decoder = TextDecoder()221 assert decoder.decode(b"") == ""222 assert decoder.flush() == ""223224225def test_line_decoder_nl():226 decoder = LineDecoder()227 assert decoder.decode("") == []228 assert decoder.decode("a\n\nb\nc") == ["a\n", "\n", "b\n"]229 assert decoder.flush() == ["c"]230231 decoder = LineDecoder()232 assert decoder.decode("") == []233 assert decoder.decode("a\n\nb\nc\n") == ["a\n", "\n", "b\n", "c\n"]234 assert decoder.flush() == []235236 # Issue #1033237 decoder = LineDecoder()238 assert decoder.decode("") == []239 assert decoder.decode("12345\n") == ["12345\n"]240 assert decoder.decode("foo ") == []241 assert decoder.decode("bar ") == []242 assert decoder.decode("baz\n") == ["foo bar baz\n"]243 assert decoder.flush() == []244245246def test_line_decoder_cr():247 decoder = LineDecoder()248 assert decoder.decode("") == []249 assert decoder.decode("a\r\rb\rc") == ["a\n", "\n", "b\n"]250 assert decoder.flush() == ["c"]251252 decoder = LineDecoder()253 assert decoder.decode("") == []254 assert decoder.decode("a\r\rb\rc\r") == ["a\n", "\n", "b\n"]255 assert decoder.flush() == ["c\n"]256257 # Issue #1033258 decoder = LineDecoder()259 assert decoder.decode("") == []260 assert decoder.decode("12345\r") == []261 assert decoder.decode("foo ") == ["12345\n"]262 assert decoder.decode("bar ") == []263 assert decoder.decode("baz\r") == []264 assert decoder.flush() == ["foo bar baz\n"]265266267def test_line_decoder_crnl():268 decoder = LineDecoder()269 assert decoder.decode("") == []270 assert decoder.decode("a\r\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]271 assert decoder.flush() == ["c"]272273 decoder = LineDecoder()274 assert decoder.decode("") == []275 assert decoder.decode("a\r\n\r\nb\r\nc\r\n") == ["a\n", "\n", "b\n", "c\n"]276 assert decoder.flush() == []277278 decoder = LineDecoder()279 assert decoder.decode("") == []280 assert decoder.decode("a\r") == []281 assert decoder.decode("\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]282 assert decoder.flush() == ["c"]283284 # Issue #1033285 decoder = LineDecoder()286 assert decoder.decode("") == []287 assert decoder.decode("12345\r\n") == ["12345\n"]288 assert decoder.decode("foo ") == []289 assert decoder.decode("bar ") == []290 assert decoder.decode("baz\r\n") == ["foo bar baz\n"]291 assert decoder.flush() == []292293294def test_byte_chunker():295 decoder = ByteChunker()296 assert decoder.decode(b"1234567") == [b"1234567"]297 assert decoder.decode(b"89") == [b"89"]298 assert decoder.flush() == []299300 decoder = ByteChunker(chunk_size=3)301 assert decoder.decode(b"1234567") == [b"123", b"456"]302 assert decoder.decode(b"89") == [b"789"]303 assert decoder.flush() == []304305 decoder = ByteChunker(chunk_size=3)306 assert decoder.decode(b"123456") == [b"123", b"456"]307 assert decoder.decode(b"789") == [b"789"]308 assert decoder.flush() == []309310 decoder = ByteChunker(chunk_size=3)311 assert decoder.decode(b"123456") == [b"123", b"456"]312 assert decoder.decode(b"78") == []313 assert decoder.flush() == [b"78"]314315316def test_text_chunker():317 decoder = TextChunker()318 assert decoder.decode("1234567") == ["1234567"]319 assert decoder.decode("89") == ["89"]320 assert decoder.flush() == []321322 decoder = TextChunker(chunk_size=3)323 assert decoder.decode("1234567") == ["123", "456"]324 assert decoder.decode("89") == ["789"]325 assert decoder.flush() == []326327 decoder = TextChunker(chunk_size=3)328 assert decoder.decode("123456") == ["123", "456"]329 assert decoder.decode("789") == ["789"]330 assert decoder.flush() == []331332 decoder = TextChunker(chunk_size=3)333 assert decoder.decode("123456") == ["123", "456"]334 assert decoder.decode("78") == []335 assert decoder.flush() == ["78"]336337338def test_invalid_content_encoding_header():339 headers = [(b"Content-Encoding", b"invalid-header")]340 body = b"test 123"341342 response = httpx.Response(343 200,344 headers=headers,345 content=body,346 )347 assert response.content == body