Skip to content
Myr

test_decoders.py

This file

Path

tests/test_decoders.py

358 lines · 10.2 KiB · Python

Last changed by

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

History of this file

Take it

1import zlib23import chardet4import pytest56import httpx7from httpx._compat import brotli8from httpx._decoders import (9    BrotliDecoder,10    ByteChunker,11    DeflateDecoder,12    GZipDecoder,13    IdentityDecoder,14    LineDecoder,15    TextChunker,16    TextDecoder,17)181920def test_deflate():21    """22    Deflate encoding may use either 'zlib' or 'deflate' in the wild.2324    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129725    """26    body = b"test 123"27    compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)28    compressed_body = compressor.compress(body) + compressor.flush()2930    headers = [(b"Content-Encoding", b"deflate")]31    response = httpx.Response(32        200,33        headers=headers,34        content=compressed_body,35    )36    assert response.content == body373839def test_zlib():40    """41    Deflate encoding may use either 'zlib' or 'deflate' in the wild.4243    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129744    """45    body = b"test 123"46    compressed_body = zlib.compress(body)4748    headers = [(b"Content-Encoding", b"deflate")]49    response = httpx.Response(50        200,51        headers=headers,52        content=compressed_body,53    )54    assert response.content == body555657def test_gzip():58    body = b"test 123"59    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)60    compressed_body = compressor.compress(body) + compressor.flush()6162    headers = [(b"Content-Encoding", b"gzip")]63    response = httpx.Response(64        200,65        headers=headers,66        content=compressed_body,67    )68    assert response.content == body697071def test_brotli():72    body = b"test 123"73    compressed_body = brotli.compress(body)7475    headers = [(b"Content-Encoding", b"br")]76    response = httpx.Response(77        200,78        headers=headers,79        content=compressed_body,80    )81    assert response.content == body828384def test_multi():85    body = b"test 123"8687    deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)88    compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()8990    gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)91    compressed_body = (92        gzip_compressor.compress(compressed_body) + gzip_compressor.flush()93    )9495    headers = [(b"Content-Encoding", b"deflate, gzip")]96    response = httpx.Response(97        200,98        headers=headers,99        content=compressed_body,100    )101    assert response.content == body102103104def test_multi_with_identity():105    body = b"test 123"106    compressed_body = brotli.compress(body)107108    headers = [(b"Content-Encoding", b"br, identity")]109    response = httpx.Response(110        200,111        headers=headers,112        content=compressed_body,113    )114    assert response.content == body115116    headers = [(b"Content-Encoding", b"identity, br")]117    response = httpx.Response(118        200,119        headers=headers,120        content=compressed_body,121    )122    assert response.content == body123124125@pytest.mark.asyncio126async def test_streaming():127    body = b"test 123"128    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)129130    async def compress(body):131        yield compressor.compress(body)132        yield compressor.flush()133134    headers = [(b"Content-Encoding", b"gzip")]135    response = httpx.Response(136        200,137        headers=headers,138        content=compress(body),139    )140    assert not hasattr(response, "body")141    assert await response.aread() == body142143144@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))145def test_empty_content(header_value):146    headers = [(b"Content-Encoding", header_value)]147    response = httpx.Response(148        200,149        headers=headers,150        content=b"",151    )152    assert response.content == b""153154155@pytest.mark.parametrize(156    "decoder", (BrotliDecoder, DeflateDecoder, GZipDecoder, IdentityDecoder)157)158def test_decoders_empty_cases(decoder):159    response = httpx.Response(content=b"", status_code=200)160    instance = decoder()161    assert instance.decode(response.content) == b""162    assert instance.flush() == b""163164165@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))166def test_decoding_errors(header_value):167    headers = [(b"Content-Encoding", header_value)]168    body = b"test 123"169    compressed_body = brotli.compress(body)[3:]170    with pytest.raises(httpx.DecodingError):171        request = httpx.Request("GET", "https://example.org")172        httpx.Response(200, headers=headers, content=compressed_body, request=request)173174    with pytest.raises(httpx.DecodingError):175        httpx.Response(200, headers=headers, content=compressed_body)176177178@pytest.mark.parametrize(179    ["data", "encoding"],180    [181        ((b"Hello,", b" world!"), "ascii"),182        ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),183        ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),184        ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),185    ],186)187@pytest.mark.asyncio188async def test_text_decoder_with_autodetect(data, encoding):189    async def iterator():190        nonlocal data191        for chunk in data:192            yield chunk193194    def autodetect(content):195        return chardet.detect(content).get("encoding")196197    # Accessing `.text` on a read response.198    response = httpx.Response(200, content=iterator(), default_encoding=autodetect)199    await response.aread()200    assert response.text == (b"".join(data)).decode(encoding)201202    # Streaming `.aiter_text` iteratively.203    # Note that if we streamed the text *without* having read it first, then204    # we won't get a `charset_normalizer` guess, and will instead always rely205    # on utf-8 if no charset is specified.206    text = "".join([part async for part in response.aiter_text()])207    assert text == (b"".join(data)).decode(encoding)208209210@pytest.mark.asyncio211async def test_text_decoder_known_encoding():212    async def iterator():213        yield b"\x83g"214        yield b"\x83"215        yield b"\x89\x83x\x83\x8b"216217    response = httpx.Response(218        200,219        headers=[(b"Content-Type", b"text/html; charset=shift-jis")],220        content=iterator(),221    )222223    await response.aread()224    assert "".join(response.text) == "トラベル"225226227def test_text_decoder_empty_cases():228    decoder = TextDecoder()229    assert decoder.flush() == ""230231    decoder = TextDecoder()232    assert decoder.decode(b"") == ""233    assert decoder.flush() == ""234235236def test_line_decoder_nl():237    decoder = LineDecoder()238    assert decoder.decode("") == []239    assert decoder.decode("a\n\nb\nc") == ["a\n", "\n", "b\n"]240    assert decoder.flush() == ["c"]241242    decoder = LineDecoder()243    assert decoder.decode("") == []244    assert decoder.decode("a\n\nb\nc\n") == ["a\n", "\n", "b\n", "c\n"]245    assert decoder.flush() == []246247    # Issue #1033248    decoder = LineDecoder()249    assert decoder.decode("") == []250    assert decoder.decode("12345\n") == ["12345\n"]251    assert decoder.decode("foo ") == []252    assert decoder.decode("bar ") == []253    assert decoder.decode("baz\n") == ["foo bar baz\n"]254    assert decoder.flush() == []255256257def test_line_decoder_cr():258    decoder = LineDecoder()259    assert decoder.decode("") == []260    assert decoder.decode("a\r\rb\rc") == ["a\n", "\n", "b\n"]261    assert decoder.flush() == ["c"]262263    decoder = LineDecoder()264    assert decoder.decode("") == []265    assert decoder.decode("a\r\rb\rc\r") == ["a\n", "\n", "b\n"]266    assert decoder.flush() == ["c\n"]267268    # Issue #1033269    decoder = LineDecoder()270    assert decoder.decode("") == []271    assert decoder.decode("12345\r") == []272    assert decoder.decode("foo ") == ["12345\n"]273    assert decoder.decode("bar ") == []274    assert decoder.decode("baz\r") == []275    assert decoder.flush() == ["foo bar baz\n"]276277278def test_line_decoder_crnl():279    decoder = LineDecoder()280    assert decoder.decode("") == []281    assert decoder.decode("a\r\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]282    assert decoder.flush() == ["c"]283284    decoder = LineDecoder()285    assert decoder.decode("") == []286    assert decoder.decode("a\r\n\r\nb\r\nc\r\n") == ["a\n", "\n", "b\n", "c\n"]287    assert decoder.flush() == []288289    decoder = LineDecoder()290    assert decoder.decode("") == []291    assert decoder.decode("a\r") == []292    assert decoder.decode("\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]293    assert decoder.flush() == ["c"]294295    # Issue #1033296    decoder = LineDecoder()297    assert decoder.decode("") == []298    assert decoder.decode("12345\r\n") == ["12345\n"]299    assert decoder.decode("foo ") == []300    assert decoder.decode("bar ") == []301    assert decoder.decode("baz\r\n") == ["foo bar baz\n"]302    assert decoder.flush() == []303304305def test_byte_chunker():306    decoder = ByteChunker()307    assert decoder.decode(b"1234567") == [b"1234567"]308    assert decoder.decode(b"89") == [b"89"]309    assert decoder.flush() == []310311    decoder = ByteChunker(chunk_size=3)312    assert decoder.decode(b"1234567") == [b"123", b"456"]313    assert decoder.decode(b"89") == [b"789"]314    assert decoder.flush() == []315316    decoder = ByteChunker(chunk_size=3)317    assert decoder.decode(b"123456") == [b"123", b"456"]318    assert decoder.decode(b"789") == [b"789"]319    assert decoder.flush() == []320321    decoder = ByteChunker(chunk_size=3)322    assert decoder.decode(b"123456") == [b"123", b"456"]323    assert decoder.decode(b"78") == []324    assert decoder.flush() == [b"78"]325326327def test_text_chunker():328    decoder = TextChunker()329    assert decoder.decode("1234567") == ["1234567"]330    assert decoder.decode("89") == ["89"]331    assert decoder.flush() == []332333    decoder = TextChunker(chunk_size=3)334    assert decoder.decode("1234567") == ["123", "456"]335    assert decoder.decode("89") == ["789"]336    assert decoder.flush() == []337338    decoder = TextChunker(chunk_size=3)339    assert decoder.decode("123456") == ["123", "456"]340    assert decoder.decode("789") == ["789"]341    assert decoder.flush() == []342343    decoder = TextChunker(chunk_size=3)344    assert decoder.decode("123456") == ["123", "456"]345    assert decoder.decode("78") == []346    assert decoder.flush() == ["78"]347348349def test_invalid_content_encoding_header():350    headers = [(b"Content-Encoding", b"invalid-header")]351    body = b"test 123"352353    response = httpx.Response(354        200,355        headers=headers,356        content=body,357    )358    assert response.content == body