Skip to content
Myr

test_decoders.py

This file

Path

tests/test_decoders.py

355 lines · 10.1 KiB · Python

Last changed by

Handle empty zstd responses (#3412)Tom Christiebefore adoption47f4a96

History of this file

Take it

1from __future__ import annotations23import io4import typing5import zlib67import chardet8import pytest9import zstandard as zstd1011import httpx121314def test_deflate():15    """16    Deflate encoding may use either 'zlib' or 'deflate' in the wild.1718    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129719    """20    body = b"test 123"21    compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)22    compressed_body = compressor.compress(body) + compressor.flush()2324    headers = [(b"Content-Encoding", b"deflate")]25    response = httpx.Response(26        200,27        headers=headers,28        content=compressed_body,29    )30    assert response.content == body313233def test_zlib():34    """35    Deflate encoding may use either 'zlib' or 'deflate' in the wild.3637    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129738    """39    body = b"test 123"40    compressed_body = zlib.compress(body)4142    headers = [(b"Content-Encoding", b"deflate")]43    response = httpx.Response(44        200,45        headers=headers,46        content=compressed_body,47    )48    assert response.content == body495051def test_gzip():52    body = b"test 123"53    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)54    compressed_body = compressor.compress(body) + compressor.flush()5556    headers = [(b"Content-Encoding", b"gzip")]57    response = httpx.Response(58        200,59        headers=headers,60        content=compressed_body,61    )62    assert response.content == body636465def test_brotli():66    body = b"test 123"67    compressed_body = b"\x8b\x03\x80test 123\x03"6869    headers = [(b"Content-Encoding", b"br")]70    response = httpx.Response(71        200,72        headers=headers,73        content=compressed_body,74    )75    assert response.content == body767778def test_zstd():79    body = b"test 123"80    compressed_body = zstd.compress(body)8182    headers = [(b"Content-Encoding", b"zstd")]83    response = httpx.Response(84        200,85        headers=headers,86        content=compressed_body,87    )88    assert response.content == body899091def test_zstd_decoding_error():92    compressed_body = "this_is_not_zstd_compressed_data"9394    headers = [(b"Content-Encoding", b"zstd")]95    with pytest.raises(httpx.DecodingError):96        httpx.Response(97            200,98            headers=headers,99            content=compressed_body,100        )101102103def test_zstd_empty():104    headers = [(b"Content-Encoding", b"zstd")]105    response = httpx.Response(200, headers=headers, content=b"")106    assert response.content == b""107108109def test_zstd_truncated():110    body = b"test 123"111    compressed_body = zstd.compress(body)112113    headers = [(b"Content-Encoding", b"zstd")]114    with pytest.raises(httpx.DecodingError):115        httpx.Response(116            200,117            headers=headers,118            content=compressed_body[1:3],119        )120121122def test_zstd_multiframe():123    # test inspired by urllib3 test suite124    data = (125        # Zstandard frame126        zstd.compress(b"foo")127        # skippable frame (must be ignored)128        + bytes.fromhex(129            "50 2A 4D 18"  # Magic_Number (little-endian)130            "07 00 00 00"  # Frame_Size (little-endian)131            "00 00 00 00 00 00 00"  # User_Data132        )133        # Zstandard frame134        + zstd.compress(b"bar")135    )136    compressed_body = io.BytesIO(data)137138    headers = [(b"Content-Encoding", b"zstd")]139    response = httpx.Response(200, headers=headers, content=compressed_body)140    response.read()141    assert response.content == b"foobar"142143144def test_multi():145    body = b"test 123"146147    deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)148    compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()149150    gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)151    compressed_body = (152        gzip_compressor.compress(compressed_body) + gzip_compressor.flush()153    )154155    headers = [(b"Content-Encoding", b"deflate, gzip")]156    response = httpx.Response(157        200,158        headers=headers,159        content=compressed_body,160    )161    assert response.content == body162163164def test_multi_with_identity():165    body = b"test 123"166    compressed_body = b"\x8b\x03\x80test 123\x03"167168    headers = [(b"Content-Encoding", b"br, identity")]169    response = httpx.Response(170        200,171        headers=headers,172        content=compressed_body,173    )174    assert response.content == body175176    headers = [(b"Content-Encoding", b"identity, br")]177    response = httpx.Response(178        200,179        headers=headers,180        content=compressed_body,181    )182    assert response.content == body183184185@pytest.mark.anyio186async def test_streaming():187    body = b"test 123"188    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)189190    async def compress(body: bytes) -> typing.AsyncIterator[bytes]:191        yield compressor.compress(body)192        yield compressor.flush()193194    headers = [(b"Content-Encoding", b"gzip")]195    response = httpx.Response(196        200,197        headers=headers,198        content=compress(body),199    )200    assert not hasattr(response, "body")201    assert await response.aread() == body202203204@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))205def test_empty_content(header_value):206    headers = [(b"Content-Encoding", header_value)]207    response = httpx.Response(208        200,209        headers=headers,210        content=b"",211    )212    assert response.content == b""213214215@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))216def test_decoders_empty_cases(header_value):217    headers = [(b"Content-Encoding", header_value)]218    response = httpx.Response(content=b"", status_code=200, headers=headers)219    assert response.read() == b""220221222@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))223def test_decoding_errors(header_value):224    headers = [(b"Content-Encoding", header_value)]225    compressed_body = b"invalid"226    with pytest.raises(httpx.DecodingError):227        request = httpx.Request("GET", "https://example.org")228        httpx.Response(200, headers=headers, content=compressed_body, request=request)229230    with pytest.raises(httpx.DecodingError):231        httpx.Response(200, headers=headers, content=compressed_body)232233234@pytest.mark.parametrize(235    ["data", "encoding"],236    [237        ((b"Hello,", b" world!"), "ascii"),238        ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),239        ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),240        ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),241    ],242)243@pytest.mark.anyio244async def test_text_decoder_with_autodetect(data, encoding):245    async def iterator() -> typing.AsyncIterator[bytes]:246        nonlocal data247        for chunk in data:248            yield chunk249250    def autodetect(content):251        return chardet.detect(content).get("encoding")252253    # Accessing `.text` on a read response.254    response = httpx.Response(200, content=iterator(), default_encoding=autodetect)255    await response.aread()256    assert response.text == (b"".join(data)).decode(encoding)257258    # Streaming `.aiter_text` iteratively.259    # Note that if we streamed the text *without* having read it first, then260    # we won't get a `charset_normalizer` guess, and will instead always rely261    # on utf-8 if no charset is specified.262    text = "".join([part async for part in response.aiter_text()])263    assert text == (b"".join(data)).decode(encoding)264265266@pytest.mark.anyio267async def test_text_decoder_known_encoding():268    async def iterator() -> typing.AsyncIterator[bytes]:269        yield b"\x83g"270        yield b"\x83"271        yield b"\x89\x83x\x83\x8b"272273    response = httpx.Response(274        200,275        headers=[(b"Content-Type", b"text/html; charset=shift-jis")],276        content=iterator(),277    )278279    await response.aread()280    assert "".join(response.text) == "トラベル"281282283def test_text_decoder_empty_cases():284    response = httpx.Response(200, content=b"")285    assert response.text == ""286287    response = httpx.Response(200, content=[b""])288    response.read()289    assert response.text == ""290291292@pytest.mark.parametrize(293    ["data", "expected"],294    [((b"Hello,", b" world!"), ["Hello,", " world!"])],295)296def test_streaming_text_decoder(297    data: typing.Iterable[bytes], expected: list[str]298) -> None:299    response = httpx.Response(200, content=iter(data))300    assert list(response.iter_text()) == expected301302303def test_line_decoder_nl():304    response = httpx.Response(200, content=[b""])305    assert list(response.iter_lines()) == []306307    response = httpx.Response(200, content=[b"", b"a\n\nb\nc"])308    assert list(response.iter_lines()) == ["a", "", "b", "c"]309310    # Issue #1033311    response = httpx.Response(312        200, content=[b"", b"12345\n", b"foo ", b"bar ", b"baz\n"]313    )314    assert list(response.iter_lines()) == ["12345", "foo bar baz"]315316317def test_line_decoder_cr():318    response = httpx.Response(200, content=[b"", b"a\r\rb\rc"])319    assert list(response.iter_lines()) == ["a", "", "b", "c"]320321    response = httpx.Response(200, content=[b"", b"a\r\rb\rc\r"])322    assert list(response.iter_lines()) == ["a", "", "b", "c"]323324    # Issue #1033325    response = httpx.Response(326        200, content=[b"", b"12345\r", b"foo ", b"bar ", b"baz\r"]327    )328    assert list(response.iter_lines()) == ["12345", "foo bar baz"]329330331def test_line_decoder_crnl():332    response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc"])333    assert list(response.iter_lines()) == ["a", "", "b", "c"]334335    response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc\r\n"])336    assert list(response.iter_lines()) == ["a", "", "b", "c"]337338    response = httpx.Response(200, content=[b"", b"a\r", b"\n\r\nb\r\nc"])339    assert list(response.iter_lines()) == ["a", "", "b", "c"]340341    # Issue #1033342    response = httpx.Response(200, content=[b"", b"12345\r\n", b"foo bar baz\r\n"])343    assert list(response.iter_lines()) == ["12345", "foo bar baz"]344345346def test_invalid_content_encoding_header():347    headers = [(b"Content-Encoding", b"invalid-header")]348    body = b"test 123"349350    response = httpx.Response(351        200,352        headers=headers,353        content=body,354    )355    assert response.content == body