test_decoders.py
This file
Path
tests/test_decoders.py
276 lines · 8.0 KiB · Python
Last changed by
Drop private imports from test_decoders.py (#2570)Florimond Mancabefore adoptioncca6206
History of this fileTake it
1import typing2import zlib34import brotli5import chardet6import pytest78import httpx91011def test_deflate():12 """13 Deflate encoding may use either 'zlib' or 'deflate' in the wild.1415 https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129716 """17 body = b"test 123"18 compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)19 compressed_body = compressor.compress(body) + compressor.flush()2021 headers = [(b"Content-Encoding", b"deflate")]22 response = httpx.Response(23 200,24 headers=headers,25 content=compressed_body,26 )27 assert response.content == body282930def test_zlib():31 """32 Deflate encoding may use either 'zlib' or 'deflate' in the wild.3334 https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129735 """36 body = b"test 123"37 compressed_body = zlib.compress(body)3839 headers = [(b"Content-Encoding", b"deflate")]40 response = httpx.Response(41 200,42 headers=headers,43 content=compressed_body,44 )45 assert response.content == body464748def test_gzip():49 body = b"test 123"50 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)51 compressed_body = compressor.compress(body) + compressor.flush()5253 headers = [(b"Content-Encoding", b"gzip")]54 response = httpx.Response(55 200,56 headers=headers,57 content=compressed_body,58 )59 assert response.content == body606162def test_brotli():63 body = b"test 123"64 compressed_body = brotli.compress(body)6566 headers = [(b"Content-Encoding", b"br")]67 response = httpx.Response(68 200,69 headers=headers,70 content=compressed_body,71 )72 assert response.content == body737475def test_multi():76 body = b"test 123"7778 deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)79 compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()8081 gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)82 compressed_body = (83 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()84 )8586 headers = [(b"Content-Encoding", b"deflate, gzip")]87 response = httpx.Response(88 200,89 headers=headers,90 content=compressed_body,91 )92 assert response.content == body939495def test_multi_with_identity():96 body = b"test 123"97 compressed_body = brotli.compress(body)9899 headers = [(b"Content-Encoding", b"br, identity")]100 response = httpx.Response(101 200,102 headers=headers,103 content=compressed_body,104 )105 assert response.content == body106107 headers = [(b"Content-Encoding", b"identity, br")]108 response = httpx.Response(109 200,110 headers=headers,111 content=compressed_body,112 )113 assert response.content == body114115116@pytest.mark.anyio117async def test_streaming():118 body = b"test 123"119 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)120121 async def compress(body: bytes) -> typing.AsyncIterator[bytes]:122 yield compressor.compress(body)123 yield compressor.flush()124125 headers = [(b"Content-Encoding", b"gzip")]126 response = httpx.Response(127 200,128 headers=headers,129 content=compress(body),130 )131 assert not hasattr(response, "body")132 assert await response.aread() == body133134135@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))136def test_empty_content(header_value):137 headers = [(b"Content-Encoding", header_value)]138 response = httpx.Response(139 200,140 headers=headers,141 content=b"",142 )143 assert response.content == b""144145146@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))147def test_decoders_empty_cases(header_value):148 headers = [(b"Content-Encoding", header_value)]149 response = httpx.Response(content=b"", status_code=200, headers=headers)150 assert response.read() == b""151152153@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))154def test_decoding_errors(header_value):155 headers = [(b"Content-Encoding", header_value)]156 body = b"test 123"157 compressed_body = brotli.compress(body)[3:]158 with pytest.raises(httpx.DecodingError):159 request = httpx.Request("GET", "https://example.org")160 httpx.Response(200, headers=headers, content=compressed_body, request=request)161162 with pytest.raises(httpx.DecodingError):163 httpx.Response(200, headers=headers, content=compressed_body)164165166@pytest.mark.parametrize(167 ["data", "encoding"],168 [169 ((b"Hello,", b" world!"), "ascii"),170 ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),171 ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),172 ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),173 ],174)175@pytest.mark.anyio176async def test_text_decoder_with_autodetect(data, encoding):177 async def iterator() -> typing.AsyncIterator[bytes]:178 nonlocal data179 for chunk in data:180 yield chunk181182 def autodetect(content):183 return chardet.detect(content).get("encoding")184185 # Accessing `.text` on a read response.186 response = httpx.Response(200, content=iterator(), default_encoding=autodetect)187 await response.aread()188 assert response.text == (b"".join(data)).decode(encoding)189190 # Streaming `.aiter_text` iteratively.191 # Note that if we streamed the text *without* having read it first, then192 # we won't get a `charset_normalizer` guess, and will instead always rely193 # on utf-8 if no charset is specified.194 text = "".join([part async for part in response.aiter_text()])195 assert text == (b"".join(data)).decode(encoding)196197198@pytest.mark.anyio199async def test_text_decoder_known_encoding():200 async def iterator() -> typing.AsyncIterator[bytes]:201 yield b"\x83g"202 yield b"\x83"203 yield b"\x89\x83x\x83\x8b"204205 response = httpx.Response(206 200,207 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],208 content=iterator(),209 )210211 await response.aread()212 assert "".join(response.text) == "トラベル"213214215def test_text_decoder_empty_cases():216 response = httpx.Response(200, content=b"")217 assert response.text == ""218219 response = httpx.Response(200, content=[b""])220 response.read()221 assert response.text == ""222223224def test_line_decoder_nl():225 response = httpx.Response(200, content=[b""])226 assert list(response.iter_lines()) == []227228 response = httpx.Response(200, content=[b"", b"a\n\nb\nc"])229 assert list(response.iter_lines()) == ["a", "", "b", "c"]230231 # Issue #1033232 response = httpx.Response(233 200, content=[b"", b"12345\n", b"foo ", b"bar ", b"baz\n"]234 )235 assert list(response.iter_lines()) == ["12345", "foo bar baz"]236237238def test_line_decoder_cr():239 response = httpx.Response(200, content=[b"", b"a\r\rb\rc"])240 assert list(response.iter_lines()) == ["a", "", "b", "c"]241242 response = httpx.Response(200, content=[b"", b"a\r\rb\rc\r"])243 assert list(response.iter_lines()) == ["a", "", "b", "c"]244245 # Issue #1033246 response = httpx.Response(247 200, content=[b"", b"12345\r", b"foo ", b"bar ", b"baz\r"]248 )249 assert list(response.iter_lines()) == ["12345", "foo bar baz"]250251252def test_line_decoder_crnl():253 response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc"])254 assert list(response.iter_lines()) == ["a", "", "b", "c"]255256 response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc\r\n"])257 assert list(response.iter_lines()) == ["a", "", "b", "c"]258259 response = httpx.Response(200, content=[b"", b"a\r", b"\n\r\nb\r\nc"])260 assert list(response.iter_lines()) == ["a", "", "b", "c"]261262 # Issue #1033263 response = httpx.Response(200, content=[b"", b"12345\r\n", b"foo bar baz\r\n"])264 assert list(response.iter_lines()) == ["12345", "foo bar baz"]265266267def test_invalid_content_encoding_header():268 headers = [(b"Content-Encoding", b"invalid-header")]269 body = b"test 123"270271 response = httpx.Response(272 200,273 headers=headers,274 content=body,275 )276 assert response.content == body