Skip to content
Myr

test_decoders.py

This file

Path

tests/test_decoders.py

357 lines · 10.1 KiB · Python

Last changed by

Use either brotli or brotlicffi. (#1618)Tom Christiebefore adoptiond514312

History of this file

Take it

1import zlib23import pytest45import httpx6from httpx._compat import brotli7from httpx._decoders import (8    BrotliDecoder,9    ByteChunker,10    DeflateDecoder,11    GZipDecoder,12    IdentityDecoder,13    LineDecoder,14    TextChunker,15    TextDecoder,16)171819def test_deflate():20    """21    Deflate encoding may use either 'zlib' or 'deflate' in the wild.2223    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129724    """25    body = b"test 123"26    compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)27    compressed_body = compressor.compress(body) + compressor.flush()2829    headers = [(b"Content-Encoding", b"deflate")]30    response = httpx.Response(31        200,32        headers=headers,33        content=compressed_body,34    )35    assert response.content == body363738def test_zlib():39    """40    Deflate encoding may use either 'zlib' or 'deflate' in the wild.4142    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129743    """44    body = b"test 123"45    compressed_body = zlib.compress(body)4647    headers = [(b"Content-Encoding", b"deflate")]48    response = httpx.Response(49        200,50        headers=headers,51        content=compressed_body,52    )53    assert response.content == body545556def test_gzip():57    body = b"test 123"58    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)59    compressed_body = compressor.compress(body) + compressor.flush()6061    headers = [(b"Content-Encoding", b"gzip")]62    response = httpx.Response(63        200,64        headers=headers,65        content=compressed_body,66    )67    assert response.content == body686970def test_brotli():71    body = b"test 123"72    compressed_body = brotli.compress(body)7374    headers = [(b"Content-Encoding", b"br")]75    response = httpx.Response(76        200,77        headers=headers,78        content=compressed_body,79    )80    assert response.content == body818283def test_multi():84    body = b"test 123"8586    deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)87    compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()8889    gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)90    compressed_body = (91        gzip_compressor.compress(compressed_body) + gzip_compressor.flush()92    )9394    headers = [(b"Content-Encoding", b"deflate, gzip")]95    response = httpx.Response(96        200,97        headers=headers,98        content=compressed_body,99    )100    assert response.content == body101102103def test_multi_with_identity():104    body = b"test 123"105    compressed_body = brotli.compress(body)106107    headers = [(b"Content-Encoding", b"br, identity")]108    response = httpx.Response(109        200,110        headers=headers,111        content=compressed_body,112    )113    assert response.content == body114115    headers = [(b"Content-Encoding", b"identity, br")]116    response = httpx.Response(117        200,118        headers=headers,119        content=compressed_body,120    )121    assert response.content == body122123124@pytest.mark.asyncio125async def test_streaming():126    body = b"test 123"127    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)128129    async def compress(body):130        yield compressor.compress(body)131        yield compressor.flush()132133    headers = [(b"Content-Encoding", b"gzip")]134    response = httpx.Response(135        200,136        headers=headers,137        content=compress(body),138    )139    assert not hasattr(response, "body")140    assert await response.aread() == body141142143@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))144def test_empty_content(header_value):145    headers = [(b"Content-Encoding", header_value)]146    response = httpx.Response(147        200,148        headers=headers,149        content=b"",150    )151    assert response.content == b""152153154@pytest.mark.parametrize(155    "decoder", (BrotliDecoder, DeflateDecoder, GZipDecoder, IdentityDecoder)156)157def test_decoders_empty_cases(decoder):158    response = httpx.Response(content=b"", status_code=200)159    instance = decoder()160    assert instance.decode(response.content) == b""161    assert instance.flush() == b""162163164@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))165def test_decoding_errors(header_value):166    headers = [(b"Content-Encoding", header_value)]167    body = b"test 123"168    compressed_body = brotli.compress(body)[3:]169    with pytest.raises(httpx.DecodingError):170        request = httpx.Request("GET", "https://example.org")171        httpx.Response(200, headers=headers, content=compressed_body, request=request)172173    with pytest.raises(httpx.DecodingError):174        httpx.Response(200, headers=headers, content=compressed_body)175176177@pytest.mark.parametrize(178    ["data", "encoding"],179    [180        ((b"Hello,", b" world!"), "ascii"),181        ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),182        ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),183        ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),184    ],185)186@pytest.mark.asyncio187async def test_text_decoder(data, encoding):188    async def iterator():189        nonlocal data190        for chunk in data:191            yield chunk192193    # Accessing `.text` on a read response.194    response = httpx.Response(195        200,196        content=iterator(),197    )198    await response.aread()199    assert response.text == (b"".join(data)).decode(encoding)200201    # Streaming `.aiter_text` iteratively.202    # Note that if we streamed the text *without* having read it first, then203    # we won't get a `charset_normalizer` guess, and will instead always rely204    # on utf-8 if no charset is specified.205    text = "".join([part async for part in response.aiter_text()])206    assert text == (b"".join(data)).decode(encoding)207208209@pytest.mark.asyncio210async def test_text_decoder_known_encoding():211    async def iterator():212        yield b"\x83g"213        yield b"\x83"214        yield b"\x89\x83x\x83\x8b"215216    response = httpx.Response(217        200,218        headers=[(b"Content-Type", b"text/html; charset=shift-jis")],219        content=iterator(),220    )221222    await response.aread()223    assert "".join(response.text) == "トラベル"224225226def test_text_decoder_empty_cases():227    decoder = TextDecoder()228    assert decoder.flush() == ""229230    decoder = TextDecoder()231    assert decoder.decode(b"") == ""232    assert decoder.flush() == ""233234235def test_line_decoder_nl():236    decoder = LineDecoder()237    assert decoder.decode("") == []238    assert decoder.decode("a\n\nb\nc") == ["a\n", "\n", "b\n"]239    assert decoder.flush() == ["c"]240241    decoder = LineDecoder()242    assert decoder.decode("") == []243    assert decoder.decode("a\n\nb\nc\n") == ["a\n", "\n", "b\n", "c\n"]244    assert decoder.flush() == []245246    # Issue #1033247    decoder = LineDecoder()248    assert decoder.decode("") == []249    assert decoder.decode("12345\n") == ["12345\n"]250    assert decoder.decode("foo ") == []251    assert decoder.decode("bar ") == []252    assert decoder.decode("baz\n") == ["foo bar baz\n"]253    assert decoder.flush() == []254255256def test_line_decoder_cr():257    decoder = LineDecoder()258    assert decoder.decode("") == []259    assert decoder.decode("a\r\rb\rc") == ["a\n", "\n", "b\n"]260    assert decoder.flush() == ["c"]261262    decoder = LineDecoder()263    assert decoder.decode("") == []264    assert decoder.decode("a\r\rb\rc\r") == ["a\n", "\n", "b\n"]265    assert decoder.flush() == ["c\n"]266267    # Issue #1033268    decoder = LineDecoder()269    assert decoder.decode("") == []270    assert decoder.decode("12345\r") == []271    assert decoder.decode("foo ") == ["12345\n"]272    assert decoder.decode("bar ") == []273    assert decoder.decode("baz\r") == []274    assert decoder.flush() == ["foo bar baz\n"]275276277def test_line_decoder_crnl():278    decoder = LineDecoder()279    assert decoder.decode("") == []280    assert decoder.decode("a\r\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]281    assert decoder.flush() == ["c"]282283    decoder = LineDecoder()284    assert decoder.decode("") == []285    assert decoder.decode("a\r\n\r\nb\r\nc\r\n") == ["a\n", "\n", "b\n", "c\n"]286    assert decoder.flush() == []287288    decoder = LineDecoder()289    assert decoder.decode("") == []290    assert decoder.decode("a\r") == []291    assert decoder.decode("\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]292    assert decoder.flush() == ["c"]293294    # Issue #1033295    decoder = LineDecoder()296    assert decoder.decode("") == []297    assert decoder.decode("12345\r\n") == ["12345\n"]298    assert decoder.decode("foo ") == []299    assert decoder.decode("bar ") == []300    assert decoder.decode("baz\r\n") == ["foo bar baz\n"]301    assert decoder.flush() == []302303304def test_byte_chunker():305    decoder = ByteChunker()306    assert decoder.decode(b"1234567") == [b"1234567"]307    assert decoder.decode(b"89") == [b"89"]308    assert decoder.flush() == []309310    decoder = ByteChunker(chunk_size=3)311    assert decoder.decode(b"1234567") == [b"123", b"456"]312    assert decoder.decode(b"89") == [b"789"]313    assert decoder.flush() == []314315    decoder = ByteChunker(chunk_size=3)316    assert decoder.decode(b"123456") == [b"123", b"456"]317    assert decoder.decode(b"789") == [b"789"]318    assert decoder.flush() == []319320    decoder = ByteChunker(chunk_size=3)321    assert decoder.decode(b"123456") == [b"123", b"456"]322    assert decoder.decode(b"78") == []323    assert decoder.flush() == [b"78"]324325326def test_text_chunker():327    decoder = TextChunker()328    assert decoder.decode("1234567") == ["1234567"]329    assert decoder.decode("89") == ["89"]330    assert decoder.flush() == []331332    decoder = TextChunker(chunk_size=3)333    assert decoder.decode("1234567") == ["123", "456"]334    assert decoder.decode("89") == ["789"]335    assert decoder.flush() == []336337    decoder = TextChunker(chunk_size=3)338    assert decoder.decode("123456") == ["123", "456"]339    assert decoder.decode("789") == ["789"]340    assert decoder.flush() == []341342    decoder = TextChunker(chunk_size=3)343    assert decoder.decode("123456") == ["123", "456"]344    assert decoder.decode("78") == []345    assert decoder.flush() == ["78"]346347348def test_invalid_content_encoding_header():349    headers = [(b"Content-Encoding", b"invalid-header")]350    body = b"test 123"351352    response = httpx.Response(353        200,354        headers=headers,355        content=body,356    )357    assert response.content == body