Skip to content
Myr

test_decoders.py

This file

Path

tests/test_decoders.py

264 lines · 7.9 KiB · Python

Last changed by

Switch to private module names (#785)Florimond Mancabefore adoption82dc6f3

History of this file

Take it

1import zlib23import brotli4import pytest56import httpx7from httpx._content_streams import AsyncIteratorStream8from httpx._decoders import (9    BrotliDecoder,10    DeflateDecoder,11    GZipDecoder,12    IdentityDecoder,13    LineDecoder,14    TextDecoder,15)1617REQUEST = httpx.Request("GET", "https://example.org")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, headers=headers, content=compressed_body, request=REQUEST33    )34    assert response.content == body353637def test_zlib():38    """39    Deflate encoding may use either 'zlib' or 'deflate' in the wild.4041    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129742    """43    body = b"test 123"44    compressed_body = zlib.compress(body)4546    headers = [(b"Content-Encoding", b"deflate")]47    response = httpx.Response(48        200, headers=headers, content=compressed_body, request=REQUEST49    )50    assert response.content == body515253def test_gzip():54    body = b"test 123"55    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)56    compressed_body = compressor.compress(body) + compressor.flush()5758    headers = [(b"Content-Encoding", b"gzip")]59    response = httpx.Response(60        200, headers=headers, content=compressed_body, request=REQUEST61    )62    assert response.content == body636465def test_brotli():66    body = b"test 123"67    compressed_body = brotli.compress(body)6869    headers = [(b"Content-Encoding", b"br")]70    response = httpx.Response(71        200, headers=headers, content=compressed_body, request=REQUEST72    )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, headers=headers, content=compressed_body, request=REQUEST90    )91    assert response.content == body929394def test_multi_with_identity():95    body = b"test 123"96    compressed_body = brotli.compress(body)9798    headers = [(b"Content-Encoding", b"br, identity")]99    response = httpx.Response(100        200, headers=headers, content=compressed_body, request=REQUEST101    )102    assert response.content == body103104    headers = [(b"Content-Encoding", b"identity, br")]105    response = httpx.Response(106        200, headers=headers, content=compressed_body, request=REQUEST107    )108    assert response.content == body109110111@pytest.mark.asyncio112async def test_streaming():113    body = b"test 123"114    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)115116    async def compress(body):117        yield compressor.compress(body)118        yield compressor.flush()119120    headers = [(b"Content-Encoding", b"gzip")]121    stream = AsyncIteratorStream(aiterator=compress(body))122    response = httpx.Response(200, headers=headers, stream=stream, request=REQUEST)123    assert not hasattr(response, "body")124    assert await response.aread() == body125126127@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))128def test_empty_content(header_value):129    headers = [(b"Content-Encoding", header_value)]130    response = httpx.Response(200, headers=headers, content=b"", request=REQUEST)131    assert response.content == b""132133134@pytest.mark.parametrize(135    "decoder", (BrotliDecoder, DeflateDecoder, GZipDecoder, IdentityDecoder)136)137def test_decoders_empty_cases(decoder):138    instance = decoder()139    assert instance.decode(b"") == b""140    assert instance.flush() == b""141142143@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))144def test_decoding_errors(header_value):145    headers = [(b"Content-Encoding", header_value)]146    body = b"test 123"147    compressed_body = brotli.compress(body)[3:]148    with pytest.raises(httpx.DecodingError):149        httpx.Response(200, headers=headers, content=compressed_body, request=REQUEST)150151152@pytest.mark.parametrize(153    ["data", "encoding"],154    [155        ((b"Hello,", b" world!"), "ascii"),156        ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),157        ((b"\x83g\x83\x89\x83x\x83\x8b",) * 64, "shift-jis"),158        ((b"\x83g\x83\x89\x83x\x83\x8b",) * 600, "shift-jis"),159        (160            (b"\xcb\xee\xf0\xe5\xec \xe8\xef\xf1\xf3\xec \xe4\xee\xeb\xee\xf0",) * 64,161            "MacCyrillic",162        ),163        (164            (b"\xa5\xa6\xa5\xa7\xa5\xd6\xa4\xce\xb9\xf1\xba\xdd\xb2\xbd",) * 512,165            "euc-jp",166        ),167    ],168)169@pytest.mark.asyncio170async def test_text_decoder(data, encoding):171    async def iterator():172        nonlocal data173        for chunk in data:174            yield chunk175176    # Accessing `.text` on a read response.177    stream = AsyncIteratorStream(aiterator=iterator())178    response = httpx.Response(200, stream=stream, request=REQUEST)179    await response.aread()180    assert response.text == (b"".join(data)).decode(encoding)181182    # Streaming `.aiter_text` iteratively.183    stream = AsyncIteratorStream(aiterator=iterator())184    response = httpx.Response(200, stream=stream, request=REQUEST)185    text = "".join([part async for part in response.aiter_text()])186    assert text == (b"".join(data)).decode(encoding)187188189@pytest.mark.asyncio190async def test_text_decoder_known_encoding():191    async def iterator():192        yield b"\x83g"193        yield b"\x83"194        yield b"\x89\x83x\x83\x8b"195196    stream = AsyncIteratorStream(aiterator=iterator())197    response = httpx.Response(198        200,199        headers=[(b"Content-Type", b"text/html; charset=shift-jis")],200        stream=stream,201        request=REQUEST,202    )203204    await response.aread()205    assert "".join(response.text) == "トラベル"206207208def test_text_decoder_empty_cases():209    decoder = TextDecoder()210    assert decoder.flush() == ""211212    decoder = TextDecoder()213    assert decoder.decode(b"") == ""214    assert decoder.flush() == ""215216217def test_line_decoder_nl():218    decoder = LineDecoder()219    assert decoder.decode("") == []220    assert decoder.decode("a\n\nb\nc") == ["a\n", "\n", "b\n"]221    assert decoder.flush() == ["c"]222223    decoder = LineDecoder()224    assert decoder.decode("") == []225    assert decoder.decode("a\n\nb\nc\n") == ["a\n", "\n", "b\n", "c\n"]226    assert decoder.flush() == []227228229def test_line_decoder_cr():230    decoder = LineDecoder()231    assert decoder.decode("") == []232    assert decoder.decode("a\r\rb\rc") == ["a\n", "\n", "b\n"]233    assert decoder.flush() == ["c"]234235    decoder = LineDecoder()236    assert decoder.decode("") == []237    assert decoder.decode("a\r\rb\rc\r") == ["a\n", "\n", "b\n"]238    assert decoder.flush() == ["c\n"]239240241def test_line_decoder_crnl():242    decoder = LineDecoder()243    assert decoder.decode("") == []244    assert decoder.decode("a\r\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]245    assert decoder.flush() == ["c"]246247    decoder = LineDecoder()248    assert decoder.decode("") == []249    assert decoder.decode("a\r\n\r\nb\r\nc\r\n") == ["a\n", "\n", "b\n", "c\n"]250    assert decoder.flush() == []251252    decoder = LineDecoder()253    assert decoder.decode("") == []254    assert decoder.decode("a\r") == []255    assert decoder.decode("\n\r\nb\r\nc") == ["a\n", "\n", "b\n"]256    assert decoder.flush() == ["c"]257258259def test_invalid_content_encoding_header():260    headers = [(b"Content-Encoding", b"invalid-header")]261    body = b"test 123"262263    response = httpx.Response(200, headers=headers, content=body, request=REQUEST)264    assert response.content == body