Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

398 lines · 11.6 KiB · Python

Last changed by

Sync streaming interface on responses (#695)Tom Christiebefore adoption11e7604

History of this file

Take it

1import datetime2import json3from unittest import mock45import pytest67import httpx8from httpx.content_streams import AsyncIteratorStream, IteratorStream910REQUEST = httpx.Request("GET", "https://example.org")111213def streaming_body():14    yield b"Hello, "15    yield b"world!"161718async def async_streaming_body():19    yield b"Hello, "20    yield b"world!"212223@pytest.mark.asyncio24async def test_response():25    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)2627    assert response.status_code == 20028    assert response.reason_phrase == "OK"29    assert response.text == "Hello, world!"30    assert response.request is REQUEST31    assert response.elapsed >= datetime.timedelta(0)32    assert not response.is_error333435def test_response_repr():36    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)37    assert repr(response) == "<Response [200 OK]>"383940def test_response_content_type_encoding():41    """42    Use the charset encoding in the Content-Type header if possible.43    """44    headers = {"Content-Type": "text-plain; charset=latin-1"}45    content = "Latin 1: ÿ".encode("latin-1")46    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)47    assert response.text == "Latin 1: ÿ"48    assert response.encoding == "latin-1"495051def test_response_autodetect_encoding():52    """53    Autodetect encoding if there is no charset info in a Content-Type header.54    """55    content = "おはようございます。".encode("EUC-JP")56    response = httpx.Response(200, content=content, request=REQUEST)57    assert response.text == "おはようございます。"58    assert response.encoding == "EUC-JP"596061def test_response_fallback_to_autodetect():62    """63    Fallback to autodetection if we get an invalid charset in the Content-Type header.64    """65    headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}66    content = "おはようございます。".encode("EUC-JP")67    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)68    assert response.text == "おはようございます。"69    assert response.encoding == "EUC-JP"707172def test_response_default_text_encoding():73    """74    A media type of 'text/*' with no charset should default to ISO-8859-1.75    See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.176    """77    content = b"Hello, world!"78    headers = {"Content-Type": "text/plain"}79    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)80    assert response.status_code == 20081    assert response.encoding == "iso-8859-1"82    assert response.text == "Hello, world!"838485def test_response_default_encoding():86    """87    Default to utf-8 if all else fails.88    """89    response = httpx.Response(200, content=b"", request=REQUEST)90    assert response.text == ""91    assert response.encoding == "utf-8"929394def test_response_non_text_encoding():95    """96    Default to apparent encoding for non-text content-type headers.97    """98    headers = {"Content-Type": "image/png"}99    response = httpx.Response(200, content=b"xyz", headers=headers, request=REQUEST)100    assert response.text == "xyz"101    assert response.encoding == "ascii"102103104def test_response_set_explicit_encoding():105    headers = {106        "Content-Type": "text-plain; charset=utf-8"107    }  # Deliberately incorrect charset108    response = httpx.Response(109        200, content="Latin 1: ÿ".encode("latin-1"), headers=headers, request=REQUEST,110    )111    response.encoding = "latin-1"112    assert response.text == "Latin 1: ÿ"113    assert response.encoding == "latin-1"114115116def test_response_force_encoding():117    response = httpx.Response(118        200, content="Snowman: ☃".encode("utf-8"), request=REQUEST119    )120    response.encoding = "iso-8859-1"121    assert response.status_code == 200122    assert response.reason_phrase == "OK"123    assert response.text == "Snowman: â\x98\x83"124    assert response.encoding == "iso-8859-1"125126127def test_read():128    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)129130    assert response.status_code == 200131    assert response.text == "Hello, world!"132    assert response.encoding == "ascii"133    assert response.is_closed134135    content = response.read()136137    assert content == b"Hello, world!"138    assert response.content == b"Hello, world!"139    assert response.is_closed140141142@pytest.mark.asyncio143async def test_aread():144    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)145146    assert response.status_code == 200147    assert response.text == "Hello, world!"148    assert response.encoding == "ascii"149    assert response.is_closed150151    content = await response.aread()152153    assert content == b"Hello, world!"154    assert response.content == b"Hello, world!"155    assert response.is_closed156157158def test_iter_raw():159    stream = IteratorStream(iterator=streaming_body())160    response = httpx.Response(200, stream=stream, request=REQUEST)161162    raw = b""163    for part in response.iter_raw():164        raw += part165    assert raw == b"Hello, world!"166167168@pytest.mark.asyncio169async def test_aiter_raw():170    stream = AsyncIteratorStream(aiterator=async_streaming_body())171    response = httpx.Response(200, stream=stream, request=REQUEST)172173    raw = b""174    async for part in response.aiter_raw():175        raw += part176    assert raw == b"Hello, world!"177178179def test_iter_bytes():180    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)181182    content = b""183    for part in response.iter_bytes():184        content += part185    assert content == b"Hello, world!"186187188@pytest.mark.asyncio189async def test_aiter_bytes():190    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)191192    content = b""193    async for part in response.aiter_bytes():194        content += part195    assert content == b"Hello, world!"196197198def test_iter_text():199    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)200201    content = ""202    for part in response.iter_text():203        content += part204    assert content == "Hello, world!"205206207@pytest.mark.asyncio208async def test_aiter_text():209    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)210211    content = ""212    async for part in response.aiter_text():213        content += part214    assert content == "Hello, world!"215216217def test_iter_lines():218    response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)219220    content = []221    for line in response.iter_lines():222        content.append(line)223    assert content == ["Hello,\n", "world!"]224225226@pytest.mark.asyncio227async def test_aiter_lines():228    response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)229230    content = []231    async for line in response.aiter_lines():232        content.append(line)233    assert content == ["Hello,\n", "world!"]234235236def test_sync_streaming_response():237    stream = IteratorStream(iterator=streaming_body())238    response = httpx.Response(200, stream=stream, request=REQUEST)239240    assert response.status_code == 200241    assert not response.is_closed242243    content = response.read()244245    assert content == b"Hello, world!"246    assert response.content == b"Hello, world!"247    assert response.is_closed248249250@pytest.mark.asyncio251async def test_async_streaming_response():252    stream = AsyncIteratorStream(aiterator=async_streaming_body())253    response = httpx.Response(200, stream=stream, request=REQUEST)254255    assert response.status_code == 200256    assert not response.is_closed257258    content = await response.aread()259260    assert content == b"Hello, world!"261    assert response.content == b"Hello, world!"262    assert response.is_closed263264265def test_cannot_read_after_stream_consumed():266    stream = IteratorStream(iterator=streaming_body())267    response = httpx.Response(200, stream=stream, request=REQUEST)268269    content = b""270    for part in response.iter_bytes():271        content += part272273    with pytest.raises(httpx.StreamConsumed):274        response.read()275276277@pytest.mark.asyncio278async def test_cannot_aread_after_stream_consumed():279    stream = AsyncIteratorStream(aiterator=async_streaming_body())280    response = httpx.Response(200, stream=stream, request=REQUEST)281282    content = b""283    async for part in response.aiter_bytes():284        content += part285286    with pytest.raises(httpx.StreamConsumed):287        await response.aread()288289290def test_cannot_read_after_response_closed():291    is_closed = False292293    def close_func():294        nonlocal is_closed295        is_closed = True296297    stream = IteratorStream(iterator=streaming_body(), close_func=close_func)298    response = httpx.Response(200, stream=stream, request=REQUEST)299300    response.close()301    assert is_closed302303    with pytest.raises(httpx.ResponseClosed):304        response.read()305306307@pytest.mark.asyncio308async def test_cannot_aread_after_response_closed():309    is_closed = False310311    async def close_func():312        nonlocal is_closed313        is_closed = True314315    stream = AsyncIteratorStream(316        aiterator=async_streaming_body(), close_func=close_func317    )318    response = httpx.Response(200, stream=stream, request=REQUEST)319320    await response.aclose()321    assert is_closed322323    with pytest.raises(httpx.ResponseClosed):324        await response.aread()325326327@pytest.mark.asyncio328async def test_elapsed_not_available_until_closed():329    stream = AsyncIteratorStream(aiterator=async_streaming_body())330    response = httpx.Response(200, stream=stream, request=REQUEST)331332    with pytest.raises(RuntimeError):333        response.elapsed334335336def test_unknown_status_code():337    response = httpx.Response(600, request=REQUEST)338    assert response.status_code == 600339    assert response.reason_phrase == ""340    assert response.text == ""341342343def test_json_with_specified_encoding():344    data = {"greeting": "hello", "recipient": "world"}345    content = json.dumps(data).encode("utf-16")346    headers = {"Content-Type": "application/json, charset=utf-16"}347    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)348    assert response.json() == data349350351def test_json_with_options():352    data = {"greeting": "hello", "recipient": "world", "amount": 1}353    content = json.dumps(data).encode("utf-16")354    headers = {"Content-Type": "application/json, charset=utf-16"}355    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)356    assert response.json(parse_int=str)["amount"] == "1"357358359def test_json_without_specified_encoding():360    data = {"greeting": "hello", "recipient": "world"}361    content = json.dumps(data).encode("utf-32-be")362    headers = {"Content-Type": "application/json"}363    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)364    assert response.json() == data365366367def test_json_without_specified_encoding_decode_error():368    data = {"greeting": "hello", "recipient": "world"}369    content = json.dumps(data).encode("utf-32-be")370    headers = {"Content-Type": "application/json"}371    # force incorrect guess from `guess_json_utf` to trigger error372    with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):373        response = httpx.Response(374            200, content=content, headers=headers, request=REQUEST375        )376        with pytest.raises(json.JSONDecodeError):377            response.json()378379380@pytest.mark.parametrize(381    "headers, expected",382    [383        (384            {"Link": "<https://example.com>; rel='preload'"},385            {"preload": {"rel": "preload", "url": "https://example.com"}},386        ),387        (388            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},389            {390                "hub": {"url": "/hub", "rel": "hub"},391                "self": {"url": "/resource", "rel": "self"},392            },393        ),394    ],395)396def test_link_headers(headers, expected):397    response = httpx.Response(200, content=None, headers=headers, request=REQUEST)398    assert response.links == expected