Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

298 lines · 9.0 KiB · Python

Last changed by

Rename 'read/close' to 'aread/aclose' on Response (#674)Florimond Mancabefore adoptionf9d18a8

History of this file

Take it

1import datetime2import json3from unittest import mock45import pytest67import httpx8from httpx.content_streams import AsyncIteratorStream910REQUEST = 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!"212223def test_response():24    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)25    assert response.status_code == 20026    assert response.reason_phrase == "OK"27    assert response.text == "Hello, world!"28    assert response.request is REQUEST29    assert response.elapsed == datetime.timedelta(0)30    assert not response.is_error313233def test_response_repr():34    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)35    assert repr(response) == "<Response [200 OK]>"363738def test_response_content_type_encoding():39    """40    Use the charset encoding in the Content-Type header if possible.41    """42    headers = {"Content-Type": "text-plain; charset=latin-1"}43    content = "Latin 1: ÿ".encode("latin-1")44    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)45    assert response.text == "Latin 1: ÿ"46    assert response.encoding == "latin-1"474849def test_response_autodetect_encoding():50    """51    Autodetect encoding if there is no charset info in a Content-Type header.52    """53    content = "おはようございます。".encode("EUC-JP")54    response = httpx.Response(200, content=content, request=REQUEST)55    assert response.text == "おはようございます。"56    assert response.encoding == "EUC-JP"575859def test_response_fallback_to_autodetect():60    """61    Fallback to autodetection if we get an invalid charset in the Content-Type header.62    """63    headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}64    content = "おはようございます。".encode("EUC-JP")65    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)66    assert response.text == "おはようございます。"67    assert response.encoding == "EUC-JP"686970def test_response_default_text_encoding():71    """72    A media type of 'text/*' with no charset should default to ISO-8859-1.73    See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.174    """75    content = b"Hello, world!"76    headers = {"Content-Type": "text/plain"}77    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)78    assert response.status_code == 20079    assert response.encoding == "iso-8859-1"80    assert response.text == "Hello, world!"818283def test_response_default_encoding():84    """85    Default to utf-8 if all else fails.86    """87    response = httpx.Response(200, content=b"", request=REQUEST)88    assert response.text == ""89    assert response.encoding == "utf-8"909192def test_response_non_text_encoding():93    """94    Default to apparent encoding for non-text content-type headers.95    """96    headers = {"Content-Type": "image/png"}97    response = httpx.Response(200, content=b"xyz", headers=headers, request=REQUEST)98    assert response.text == "xyz"99    assert response.encoding == "ascii"100101102def test_response_set_explicit_encoding():103    headers = {104        "Content-Type": "text-plain; charset=utf-8"105    }  # Deliberately incorrect charset106    response = httpx.Response(107        200, content="Latin 1: ÿ".encode("latin-1"), headers=headers, request=REQUEST,108    )109    response.encoding = "latin-1"110    assert response.text == "Latin 1: ÿ"111    assert response.encoding == "latin-1"112113114def test_response_force_encoding():115    response = httpx.Response(116        200, content="Snowman: ☃".encode("utf-8"), request=REQUEST117    )118    response.encoding = "iso-8859-1"119    assert response.status_code == 200120    assert response.reason_phrase == "OK"121    assert response.text == "Snowman: â\x98\x83"122    assert response.encoding == "iso-8859-1"123124125@pytest.mark.asyncio126async def test_read_response():127    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)128129    assert response.status_code == 200130    assert response.text == "Hello, world!"131    assert response.encoding == "ascii"132    assert response.is_closed133134    content = await response.aread()135136    assert content == b"Hello, world!"137    assert response.content == b"Hello, world!"138    assert response.is_closed139140141@pytest.mark.asyncio142async def test_raw_interface():143    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)144145    raw = b""146    async for part in response.aiter_raw():147        raw += part148    assert raw == b"Hello, world!"149150151@pytest.mark.asyncio152async def test_bytes_interface():153    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)154155    content = b""156    async for part in response.aiter_bytes():157        content += part158    assert content == b"Hello, world!"159160161@pytest.mark.asyncio162async def test_text_interface():163    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)164165    await response.aread()166167    content = ""168    async for part in response.aiter_text():169        content += part170    assert content == "Hello, world!"171172173@pytest.mark.asyncio174async def test_lines_interface():175    response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)176177    await response.aread()178179    content = []180    async for line in response.aiter_lines():181        content.append(line)182    assert content == ["Hello,\n", "world!"]183184185@pytest.mark.asyncio186async def test_stream_interface_after_read():187    response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)188189    await response.aread()190191    content = b""192    async for part in response.aiter_bytes():193        content += part194    assert content == b"Hello, world!"195196197@pytest.mark.asyncio198async def test_streaming_response():199    stream = AsyncIteratorStream(aiterator=async_streaming_body())200    response = httpx.Response(200, stream=stream, request=REQUEST)201202    assert response.status_code == 200203    assert not response.is_closed204205    content = await response.aread()206207    assert content == b"Hello, world!"208    assert response.content == b"Hello, world!"209    assert response.is_closed210211212@pytest.mark.asyncio213async def test_cannot_read_after_stream_consumed():214    stream = AsyncIteratorStream(aiterator=async_streaming_body())215    response = httpx.Response(200, stream=stream, request=REQUEST)216217    content = b""218    async for part in response.aiter_bytes():219        content += part220221    with pytest.raises(httpx.StreamConsumed):222        await response.aread()223224225@pytest.mark.asyncio226async def test_cannot_read_after_response_closed():227    stream = AsyncIteratorStream(aiterator=async_streaming_body())228    response = httpx.Response(200, stream=stream, request=REQUEST)229230    await response.aclose()231232    with pytest.raises(httpx.ResponseClosed):233        await response.aread()234235236def test_unknown_status_code():237    response = httpx.Response(600, request=REQUEST)238    assert response.status_code == 600239    assert response.reason_phrase == ""240    assert response.text == ""241242243def test_json_with_specified_encoding():244    data = {"greeting": "hello", "recipient": "world"}245    content = json.dumps(data).encode("utf-16")246    headers = {"Content-Type": "application/json, charset=utf-16"}247    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)248    assert response.json() == data249250251def test_json_with_options():252    data = {"greeting": "hello", "recipient": "world", "amount": 1}253    content = json.dumps(data).encode("utf-16")254    headers = {"Content-Type": "application/json, charset=utf-16"}255    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)256    assert response.json(parse_int=str)["amount"] == "1"257258259def test_json_without_specified_encoding():260    data = {"greeting": "hello", "recipient": "world"}261    content = json.dumps(data).encode("utf-32-be")262    headers = {"Content-Type": "application/json"}263    response = httpx.Response(200, content=content, headers=headers, request=REQUEST)264    assert response.json() == data265266267def test_json_without_specified_encoding_decode_error():268    data = {"greeting": "hello", "recipient": "world"}269    content = json.dumps(data).encode("utf-32-be")270    headers = {"Content-Type": "application/json"}271    # force incorrect guess from `guess_json_utf` to trigger error272    with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):273        response = httpx.Response(274            200, content=content, headers=headers, request=REQUEST275        )276        with pytest.raises(json.JSONDecodeError):277            response.json()278279280@pytest.mark.parametrize(281    "headers, expected",282    [283        (284            {"Link": "<https://example.com>; rel='preload'"},285            {"preload": {"rel": "preload", "url": "https://example.com"}},286        ),287        (288            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},289            {290                "hub": {"url": "/hub", "rel": "hub"},291                "self": {"url": "/resource", "rel": "self"},292            },293        ),294    ],295)296def test_link_headers(headers, expected):297    response = httpx.Response(200, content=None, headers=headers, request=REQUEST)298    assert response.links == expected