Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

326 lines · 9.1 KiB · Python

Last changed by

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

History of this file

Take it

1import json2from unittest import mock34import pytest56import httpx789def streaming_body():10    yield b"Hello, "11    yield b"world!"121314async def async_streaming_body():15    yield b"Hello, "16    yield b"world!"171819def test_response():20    response = httpx.Response(200, content=b"Hello, world!")21    assert response.status_code == 20022    assert response.reason_phrase == "OK"23    assert response.text == "Hello, world!"242526def test_response_repr():27    response = httpx.Response(200, content=b"Hello, world!")28    assert repr(response) == "<Response [200 OK]>"293031def test_response_content_type_encoding():32    """33    Use the charset encoding in the Content-Type header if possible.34    """35    headers = {"Content-Type": "text-plain; charset=latin-1"}36    content = "Latin 1: ÿ".encode("latin-1")37    response = httpx.Response(200, content=content, headers=headers)38    assert response.text == "Latin 1: ÿ"39    assert response.encoding == "latin-1"404142def test_response_autodetect_encoding():43    """44    Autodetect encoding if there is no charset info in a Content-Type header.45    """46    content = "おはようございます。".encode("EUC-JP")47    response = httpx.Response(200, content=content)48    assert response.text == "おはようございます。"49    assert response.encoding == "EUC-JP"505152def test_response_fallback_to_autodetect():53    """54    Fallback to autodetection if we get an invalid charset in the Content-Type header.55    """56    headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}57    content = "おはようございます。".encode("EUC-JP")58    response = httpx.Response(200, content=content, headers=headers)59    assert response.text == "おはようございます。"60    assert response.encoding == "EUC-JP"616263def test_response_default_text_encoding():64    """65    A media type of 'text/*' with no charset should default to ISO-8859-1.66    See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.167    """68    content = b"Hello, world!"69    headers = {"Content-Type": "text/plain"}70    response = httpx.Response(200, content=content, headers=headers)71    assert response.status_code == 20072    assert response.encoding == "iso-8859-1"73    assert response.text == "Hello, world!"747576def test_response_default_encoding():77    """78    Default to utf-8 if all else fails.79    """80    response = httpx.Response(200, content=b"")81    assert response.text == ""82    assert response.encoding == "utf-8"838485def test_response_non_text_encoding():86    """87    Default to apparent encoding for non-text content-type headers.88    """89    headers = {"Content-Type": "image/png"}90    response = httpx.Response(200, content=b"xyz", headers=headers)91    assert response.text == "xyz"92    assert response.encoding == "ascii"939495def test_response_set_explicit_encoding():96    headers = {97        "Content-Type": "text-plain; charset=utf-8"98    }  # Deliberately incorrect charset99    response = httpx.Response(100        200, content="Latin 1: ÿ".encode("latin-1"), headers=headers101    )102    response.encoding = "latin-1"103    assert response.text == "Latin 1: ÿ"104    assert response.encoding == "latin-1"105106107def test_response_force_encoding():108    response = httpx.Response(200, content="Snowman: ☃".encode("utf-8"))109    response.encoding = "iso-8859-1"110    assert response.status_code == 200111    assert response.reason_phrase == "OK"112    assert response.text == "Snowman: â\x98\x83"113    assert response.encoding == "iso-8859-1"114115116def test_read_response():117    response = httpx.Response(200, content=b"Hello, world!")118119    assert response.status_code == 200120    assert response.text == "Hello, world!"121    assert response.encoding == "ascii"122    assert response.is_closed123124    content = response.read()125126    assert content == b"Hello, world!"127    assert response.content == b"Hello, world!"128    assert response.is_closed129130131def test_raw_interface():132    response = httpx.Response(200, content=b"Hello, world!")133134    raw = b""135    for part in response.raw():136        raw += part137    assert raw == b"Hello, world!"138139140def test_stream_interface():141    response = httpx.Response(200, content=b"Hello, world!")142143    content = b""144    for part in response.stream():145        content += part146    assert content == b"Hello, world!"147148149@pytest.mark.asyncio150async def test_async_stream_interface():151    response = httpx.AsyncResponse(200, content=b"Hello, world!")152153    content = b""154    async for part in response.stream():155        content += part156    assert content == b"Hello, world!"157158159def test_stream_interface_after_read():160    response = httpx.Response(200, content=b"Hello, world!")161162    response.read()163164    content = b""165    for part in response.stream():166        content += part167    assert content == b"Hello, world!"168169170@pytest.mark.asyncio171async def test_async_stream_interface_after_read():172    response = httpx.AsyncResponse(200, content=b"Hello, world!")173174    await response.read()175176    content = b""177    async for part in response.stream():178        content += part179    assert content == b"Hello, world!"180181182def test_streaming_response():183    response = httpx.Response(200, content=streaming_body())184185    assert response.status_code == 200186    assert not response.is_closed187188    content = response.read()189190    assert content == b"Hello, world!"191    assert response.content == b"Hello, world!"192    assert response.is_closed193194195@pytest.mark.asyncio196async def test_async_streaming_response():197    response = httpx.AsyncResponse(200, content=async_streaming_body())198199    assert response.status_code == 200200    assert not response.is_closed201202    content = await response.read()203204    assert content == b"Hello, world!"205    assert response.content == b"Hello, world!"206    assert response.is_closed207208209def test_cannot_read_after_stream_consumed():210    response = httpx.Response(200, content=streaming_body())211212    content = b""213    for part in response.stream():214        content += part215216    with pytest.raises(httpx.StreamConsumed):217        response.read()218219220@pytest.mark.asyncio221async def test_async_cannot_read_after_stream_consumed():222    response = httpx.AsyncResponse(200, content=async_streaming_body())223224    content = b""225    async for part in response.stream():226        content += part227228    with pytest.raises(httpx.StreamConsumed):229        await response.read()230231232def test_cannot_read_after_response_closed():233    response = httpx.Response(200, content=streaming_body())234235    response.close()236237    with pytest.raises(httpx.ResponseClosed):238        response.read()239240241@pytest.mark.asyncio242async def test_async_cannot_read_after_response_closed():243    response = httpx.AsyncResponse(200, content=async_streaming_body())244245    await response.close()246247    with pytest.raises(httpx.ResponseClosed):248        await response.read()249250251def test_unknown_status_code():252    response = httpx.Response(600)253    assert response.status_code == 600254    assert response.reason_phrase == ""255    assert response.text == ""256257258def test_json_with_specified_encoding():259    data = {"greeting": "hello", "recipient": "world"}260    content = json.dumps(data).encode("utf-16")261    headers = {"Content-Type": "application/json, charset=utf-16"}262    response = httpx.Response(200, content=content, headers=headers)263    assert response.json() == data264265266def test_json_with_options():267    data = {"greeting": "hello", "recipient": "world", "amount": 1}268    content = json.dumps(data).encode("utf-16")269    headers = {"Content-Type": "application/json, charset=utf-16"}270    response = httpx.Response(200, content=content, headers=headers)271    assert response.json(parse_int=str)["amount"] == "1"272273274def test_json_without_specified_encoding():275    data = {"greeting": "hello", "recipient": "world"}276    content = json.dumps(data).encode("utf-32-be")277    headers = {"Content-Type": "application/json"}278    response = httpx.Response(200, content=content, headers=headers)279    assert response.json() == data280281282def test_json_without_specified_encoding_decode_error():283    data = {"greeting": "hello", "recipient": "world"}284    content = json.dumps(data).encode("utf-32-be")285    headers = {"Content-Type": "application/json"}286    # force incorrect guess from `guess_json_utf` to trigger error287    with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):288        response = httpx.Response(200, content=content, headers=headers)289        with pytest.raises(json.JSONDecodeError):290            response.json()291292293@pytest.mark.parametrize(294    "headers, expected",295    [296        (297            {"Link": "<https://example.com>; rel='preload'"},298            {"preload": {"rel": "preload", "url": "https://example.com"}},299        ),300        (301            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},302            {303                "hub": {"url": "/hub", "rel": "hub"},304                "self": {"url": "/resource", "rel": "self"},305            },306        ),307    ],308)309def test_link_headers(headers, expected):310    response = httpx.Response(200, content=None, headers=headers)311    assert response.links == expected312313314@pytest.mark.asyncio315async def test_stream_text():316    async def iterator():317        yield b"Hello, world!"318319    response = httpx.AsyncResponse(200, content=iterator().__aiter__())320321    await response.read()322323    content = ""324    async for part in response.stream_text():325        content += part326    assert content == "Hello, world!"