Skip to content
Myr

test_decoders.py

This file

Path

tests/test_decoders.py

287 lines · 8.3 KiB · Python

Last changed by

Use `__future__.annotations` (#3068)Kar Petrosyanbefore adoption371b6e9

History of this file

Take it

1from __future__ import annotations23import typing4import zlib56import chardet7import pytest89import httpx101112def test_deflate():13    """14    Deflate encoding may use either 'zlib' or 'deflate' in the wild.1516    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129717    """18    body = b"test 123"19    compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)20    compressed_body = compressor.compress(body) + compressor.flush()2122    headers = [(b"Content-Encoding", b"deflate")]23    response = httpx.Response(24        200,25        headers=headers,26        content=compressed_body,27    )28    assert response.content == body293031def test_zlib():32    """33    Deflate encoding may use either 'zlib' or 'deflate' in the wild.3435    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129736    """37    body = b"test 123"38    compressed_body = zlib.compress(body)3940    headers = [(b"Content-Encoding", b"deflate")]41    response = httpx.Response(42        200,43        headers=headers,44        content=compressed_body,45    )46    assert response.content == body474849def test_gzip():50    body = b"test 123"51    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)52    compressed_body = compressor.compress(body) + compressor.flush()5354    headers = [(b"Content-Encoding", b"gzip")]55    response = httpx.Response(56        200,57        headers=headers,58        content=compressed_body,59    )60    assert response.content == body616263def test_brotli():64    body = b"test 123"65    compressed_body = b"\x8b\x03\x80test 123\x03"6667    headers = [(b"Content-Encoding", b"br")]68    response = httpx.Response(69        200,70        headers=headers,71        content=compressed_body,72    )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,90        headers=headers,91        content=compressed_body,92    )93    assert response.content == body949596def test_multi_with_identity():97    body = b"test 123"98    compressed_body = b"\x8b\x03\x80test 123\x03"99100    headers = [(b"Content-Encoding", b"br, identity")]101    response = httpx.Response(102        200,103        headers=headers,104        content=compressed_body,105    )106    assert response.content == body107108    headers = [(b"Content-Encoding", b"identity, br")]109    response = httpx.Response(110        200,111        headers=headers,112        content=compressed_body,113    )114    assert response.content == body115116117@pytest.mark.anyio118async def test_streaming():119    body = b"test 123"120    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)121122    async def compress(body: bytes) -> typing.AsyncIterator[bytes]:123        yield compressor.compress(body)124        yield compressor.flush()125126    headers = [(b"Content-Encoding", b"gzip")]127    response = httpx.Response(128        200,129        headers=headers,130        content=compress(body),131    )132    assert not hasattr(response, "body")133    assert await response.aread() == body134135136@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))137def test_empty_content(header_value):138    headers = [(b"Content-Encoding", header_value)]139    response = httpx.Response(140        200,141        headers=headers,142        content=b"",143    )144    assert response.content == b""145146147@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))148def test_decoders_empty_cases(header_value):149    headers = [(b"Content-Encoding", header_value)]150    response = httpx.Response(content=b"", status_code=200, headers=headers)151    assert response.read() == b""152153154@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))155def test_decoding_errors(header_value):156    headers = [(b"Content-Encoding", header_value)]157    compressed_body = b"invalid"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 == ""222223224@pytest.mark.parametrize(225    ["data", "expected"],226    [((b"Hello,", b" world!"), ["Hello,", " world!"])],227)228def test_streaming_text_decoder(229    data: typing.Iterable[bytes], expected: list[str]230) -> None:231    response = httpx.Response(200, content=iter(data))232    assert list(response.iter_text()) == expected233234235def test_line_decoder_nl():236    response = httpx.Response(200, content=[b""])237    assert list(response.iter_lines()) == []238239    response = httpx.Response(200, content=[b"", b"a\n\nb\nc"])240    assert list(response.iter_lines()) == ["a", "", "b", "c"]241242    # Issue #1033243    response = httpx.Response(244        200, content=[b"", b"12345\n", b"foo ", b"bar ", b"baz\n"]245    )246    assert list(response.iter_lines()) == ["12345", "foo bar baz"]247248249def test_line_decoder_cr():250    response = httpx.Response(200, content=[b"", b"a\r\rb\rc"])251    assert list(response.iter_lines()) == ["a", "", "b", "c"]252253    response = httpx.Response(200, content=[b"", b"a\r\rb\rc\r"])254    assert list(response.iter_lines()) == ["a", "", "b", "c"]255256    # Issue #1033257    response = httpx.Response(258        200, content=[b"", b"12345\r", b"foo ", b"bar ", b"baz\r"]259    )260    assert list(response.iter_lines()) == ["12345", "foo bar baz"]261262263def test_line_decoder_crnl():264    response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc"])265    assert list(response.iter_lines()) == ["a", "", "b", "c"]266267    response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc\r\n"])268    assert list(response.iter_lines()) == ["a", "", "b", "c"]269270    response = httpx.Response(200, content=[b"", b"a\r", b"\n\r\nb\r\nc"])271    assert list(response.iter_lines()) == ["a", "", "b", "c"]272273    # Issue #1033274    response = httpx.Response(200, content=[b"", b"12345\r\n", b"foo bar baz\r\n"])275    assert list(response.iter_lines()) == ["12345", "foo bar baz"]276277278def test_invalid_content_encoding_header():279    headers = [(b"Content-Encoding", b"invalid-header")]280    body = b"test 123"281282    response = httpx.Response(283        200,284        headers=headers,285        content=body,286    )287    assert response.content == body