Skip to content
Myr

test_decoders.py

This file

Path

tests/test_decoders.py

285 lines · 8.3 KiB · Python

Last changed by

Fixed `iter_text` adding an empty string (#2998)James Brazabefore adoption1e11096

History of this file

Take it

1import typing2import zlib34import chardet5import pytest67import httpx8910def test_deflate():11    """12    Deflate encoding may use either 'zlib' or 'deflate' in the wild.1314    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129715    """16    body = b"test 123"17    compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)18    compressed_body = compressor.compress(body) + compressor.flush()1920    headers = [(b"Content-Encoding", b"deflate")]21    response = httpx.Response(22        200,23        headers=headers,24        content=compressed_body,25    )26    assert response.content == body272829def test_zlib():30    """31    Deflate encoding may use either 'zlib' or 'deflate' in the wild.3233    https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-2231129734    """35    body = b"test 123"36    compressed_body = zlib.compress(body)3738    headers = [(b"Content-Encoding", b"deflate")]39    response = httpx.Response(40        200,41        headers=headers,42        content=compressed_body,43    )44    assert response.content == body454647def test_gzip():48    body = b"test 123"49    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)50    compressed_body = compressor.compress(body) + compressor.flush()5152    headers = [(b"Content-Encoding", b"gzip")]53    response = httpx.Response(54        200,55        headers=headers,56        content=compressed_body,57    )58    assert response.content == body596061def test_brotli():62    body = b"test 123"63    compressed_body = b"\x8b\x03\x80test 123\x03"6465    headers = [(b"Content-Encoding", b"br")]66    response = httpx.Response(67        200,68        headers=headers,69        content=compressed_body,70    )71    assert response.content == body727374def test_multi():75    body = b"test 123"7677    deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)78    compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()7980    gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)81    compressed_body = (82        gzip_compressor.compress(compressed_body) + gzip_compressor.flush()83    )8485    headers = [(b"Content-Encoding", b"deflate, gzip")]86    response = httpx.Response(87        200,88        headers=headers,89        content=compressed_body,90    )91    assert response.content == body929394def test_multi_with_identity():95    body = b"test 123"96    compressed_body = b"\x8b\x03\x80test 123\x03"9798    headers = [(b"Content-Encoding", b"br, identity")]99    response = httpx.Response(100        200,101        headers=headers,102        content=compressed_body,103    )104    assert response.content == body105106    headers = [(b"Content-Encoding", b"identity, br")]107    response = httpx.Response(108        200,109        headers=headers,110        content=compressed_body,111    )112    assert response.content == body113114115@pytest.mark.anyio116async def test_streaming():117    body = b"test 123"118    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)119120    async def compress(body: bytes) -> typing.AsyncIterator[bytes]:121        yield compressor.compress(body)122        yield compressor.flush()123124    headers = [(b"Content-Encoding", b"gzip")]125    response = httpx.Response(126        200,127        headers=headers,128        content=compress(body),129    )130    assert not hasattr(response, "body")131    assert await response.aread() == body132133134@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))135def test_empty_content(header_value):136    headers = [(b"Content-Encoding", header_value)]137    response = httpx.Response(138        200,139        headers=headers,140        content=b"",141    )142    assert response.content == b""143144145@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))146def test_decoders_empty_cases(header_value):147    headers = [(b"Content-Encoding", header_value)]148    response = httpx.Response(content=b"", status_code=200, headers=headers)149    assert response.read() == b""150151152@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))153def test_decoding_errors(header_value):154    headers = [(b"Content-Encoding", header_value)]155    compressed_body = b"invalid"156    with pytest.raises(httpx.DecodingError):157        request = httpx.Request("GET", "https://example.org")158        httpx.Response(200, headers=headers, content=compressed_body, request=request)159160    with pytest.raises(httpx.DecodingError):161        httpx.Response(200, headers=headers, content=compressed_body)162163164@pytest.mark.parametrize(165    ["data", "encoding"],166    [167        ((b"Hello,", b" world!"), "ascii"),168        ((b"\xe3\x83", b"\x88\xe3\x83\xa9", b"\xe3", b"\x83\x99\xe3\x83\xab"), "utf-8"),169        ((b"Euro character: \x88! abcdefghijklmnopqrstuvwxyz", b""), "cp1252"),170        ((b"Accented: \xd6sterreich abcdefghijklmnopqrstuvwxyz", b""), "iso-8859-1"),171    ],172)173@pytest.mark.anyio174async def test_text_decoder_with_autodetect(data, encoding):175    async def iterator() -> typing.AsyncIterator[bytes]:176        nonlocal data177        for chunk in data:178            yield chunk179180    def autodetect(content):181        return chardet.detect(content).get("encoding")182183    # Accessing `.text` on a read response.184    response = httpx.Response(200, content=iterator(), default_encoding=autodetect)185    await response.aread()186    assert response.text == (b"".join(data)).decode(encoding)187188    # Streaming `.aiter_text` iteratively.189    # Note that if we streamed the text *without* having read it first, then190    # we won't get a `charset_normalizer` guess, and will instead always rely191    # on utf-8 if no charset is specified.192    text = "".join([part async for part in response.aiter_text()])193    assert text == (b"".join(data)).decode(encoding)194195196@pytest.mark.anyio197async def test_text_decoder_known_encoding():198    async def iterator() -> typing.AsyncIterator[bytes]:199        yield b"\x83g"200        yield b"\x83"201        yield b"\x89\x83x\x83\x8b"202203    response = httpx.Response(204        200,205        headers=[(b"Content-Type", b"text/html; charset=shift-jis")],206        content=iterator(),207    )208209    await response.aread()210    assert "".join(response.text) == "トラベル"211212213def test_text_decoder_empty_cases():214    response = httpx.Response(200, content=b"")215    assert response.text == ""216217    response = httpx.Response(200, content=[b""])218    response.read()219    assert response.text == ""220221222@pytest.mark.parametrize(223    ["data", "expected"],224    [((b"Hello,", b" world!"), ["Hello,", " world!"])],225)226def test_streaming_text_decoder(227    data: typing.Iterable[bytes], expected: typing.List[str]228) -> None:229    response = httpx.Response(200, content=iter(data))230    assert list(response.iter_text()) == expected231232233def test_line_decoder_nl():234    response = httpx.Response(200, content=[b""])235    assert list(response.iter_lines()) == []236237    response = httpx.Response(200, content=[b"", b"a\n\nb\nc"])238    assert list(response.iter_lines()) == ["a", "", "b", "c"]239240    # Issue #1033241    response = httpx.Response(242        200, content=[b"", b"12345\n", b"foo ", b"bar ", b"baz\n"]243    )244    assert list(response.iter_lines()) == ["12345", "foo bar baz"]245246247def test_line_decoder_cr():248    response = httpx.Response(200, content=[b"", b"a\r\rb\rc"])249    assert list(response.iter_lines()) == ["a", "", "b", "c"]250251    response = httpx.Response(200, content=[b"", b"a\r\rb\rc\r"])252    assert list(response.iter_lines()) == ["a", "", "b", "c"]253254    # Issue #1033255    response = httpx.Response(256        200, content=[b"", b"12345\r", b"foo ", b"bar ", b"baz\r"]257    )258    assert list(response.iter_lines()) == ["12345", "foo bar baz"]259260261def test_line_decoder_crnl():262    response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc"])263    assert list(response.iter_lines()) == ["a", "", "b", "c"]264265    response = httpx.Response(200, content=[b"", b"a\r\n\r\nb\r\nc\r\n"])266    assert list(response.iter_lines()) == ["a", "", "b", "c"]267268    response = httpx.Response(200, content=[b"", b"a\r", b"\n\r\nb\r\nc"])269    assert list(response.iter_lines()) == ["a", "", "b", "c"]270271    # Issue #1033272    response = httpx.Response(200, content=[b"", b"12345\r\n", b"foo bar baz\r\n"])273    assert list(response.iter_lines()) == ["12345", "foo bar baz"]274275276def test_invalid_content_encoding_header():277    headers = [(b"Content-Encoding", b"invalid-header")]278    body = b"test 123"279280    response = httpx.Response(281        200,282        headers=headers,283        content=body,284    )285    assert response.content == body