Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

590 lines · 14.8 KiB · Python

Last changed by

Drop Response(..., request=...) style in test cases. (#1243)Tom Christiebefore adoptionde502a4

History of this file

Take it

1import datetime2import json3from unittest import mock45import brotli6import pytest78import httpx9from httpx._content_streams import AsyncIteratorStream, IteratorStream101112def streaming_body():13    yield b"Hello, "14    yield b"world!"151617async def async_streaming_body():18    yield b"Hello, "19    yield b"world!"202122def test_response():23    response = httpx.Response(24        200,25        content=b"Hello, world!",26        request=httpx.Request("GET", "https://example.org"),27    )2829    assert response.status_code == 20030    assert response.reason_phrase == "OK"31    assert response.text == "Hello, world!"32    assert response.request.method == "GET"33    assert response.request.url == "https://example.org"34    assert response.elapsed >= datetime.timedelta(0)35    assert not response.is_error363738def test_raise_for_status():39    request = httpx.Request("GET", "https://example.org")4041    # 2xx status codes are not an error.42    response = httpx.Response(200, request=request)43    response.raise_for_status()4445    # 4xx status codes are a client error.46    response = httpx.Response(403, request=request)47    with pytest.raises(httpx.HTTPStatusError):48        response.raise_for_status()4950    # 5xx status codes are a server error.51    response = httpx.Response(500, request=request)52    with pytest.raises(httpx.HTTPStatusError):53        response.raise_for_status()5455    # Calling .raise_for_status without setting a request instance is56    # not valid. Should raise a runtime error.57    response = httpx.Response(200)58    with pytest.raises(RuntimeError):59        response.raise_for_status()606162def test_response_repr():63    response = httpx.Response(64        200,65        content=b"Hello, world!",66    )67    assert repr(response) == "<Response [200 OK]>"686970def test_response_content_type_encoding():71    """72    Use the charset encoding in the Content-Type header if possible.73    """74    headers = {"Content-Type": "text-plain; charset=latin-1"}75    content = "Latin 1: ÿ".encode("latin-1")76    response = httpx.Response(77        200,78        content=content,79        headers=headers,80    )81    assert response.text == "Latin 1: ÿ"82    assert response.encoding == "latin-1"838485def test_response_autodetect_encoding():86    """87    Autodetect encoding if there is no charset info in a Content-Type header.88    """89    content = "おはようございます。".encode("EUC-JP")90    response = httpx.Response(91        200,92        content=content,93    )94    assert response.text == "おはようございます。"95    assert response.encoding == "EUC-JP"969798def test_response_fallback_to_autodetect():99    """100    Fallback to autodetection if we get an invalid charset in the Content-Type header.101    """102    headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}103    content = "おはようございます。".encode("EUC-JP")104    response = httpx.Response(105        200,106        content=content,107        headers=headers,108    )109    assert response.text == "おはようございます。"110    assert response.encoding == "EUC-JP"111112113def test_response_default_text_encoding():114    """115    A media type of 'text/*' with no charset should default to ISO-8859-1.116    See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1117    """118    content = b"Hello, world!"119    headers = {"Content-Type": "text/plain"}120    response = httpx.Response(121        200,122        content=content,123        headers=headers,124    )125    assert response.status_code == 200126    assert response.encoding == "iso-8859-1"127    assert response.text == "Hello, world!"128129130def test_response_default_encoding():131    """132    Default to utf-8 if all else fails.133    """134    response = httpx.Response(135        200,136        content=b"",137    )138    assert response.text == ""139    assert response.encoding == "utf-8"140141142def test_response_non_text_encoding():143    """144    Default to apparent encoding for non-text content-type headers.145    """146    headers = {"Content-Type": "image/png"}147    response = httpx.Response(148        200,149        content=b"xyz",150        headers=headers,151    )152    assert response.text == "xyz"153    assert response.encoding == "ascii"154155156def test_response_set_explicit_encoding():157    headers = {158        "Content-Type": "text-plain; charset=utf-8"159    }  # Deliberately incorrect charset160    response = httpx.Response(161        200,162        content="Latin 1: ÿ".encode("latin-1"),163        headers=headers,164    )165    response.encoding = "latin-1"166    assert response.text == "Latin 1: ÿ"167    assert response.encoding == "latin-1"168169170def test_response_force_encoding():171    response = httpx.Response(172        200,173        content="Snowman: ☃".encode("utf-8"),174    )175    response.encoding = "iso-8859-1"176    assert response.status_code == 200177    assert response.reason_phrase == "OK"178    assert response.text == "Snowman: â\x98\x83"179    assert response.encoding == "iso-8859-1"180181182def test_read():183    response = httpx.Response(184        200,185        content=b"Hello, world!",186    )187188    assert response.status_code == 200189    assert response.text == "Hello, world!"190    assert response.encoding == "ascii"191    assert response.is_closed192193    content = response.read()194195    assert content == b"Hello, world!"196    assert response.content == b"Hello, world!"197    assert response.is_closed198199200@pytest.mark.asyncio201async def test_aread():202    response = httpx.Response(203        200,204        content=b"Hello, world!",205    )206207    assert response.status_code == 200208    assert response.text == "Hello, world!"209    assert response.encoding == "ascii"210    assert response.is_closed211212    content = await response.aread()213214    assert content == b"Hello, world!"215    assert response.content == b"Hello, world!"216    assert response.is_closed217218219def test_iter_raw():220    stream = IteratorStream(iterator=streaming_body())221    response = httpx.Response(222        200,223        stream=stream,224    )225226    raw = b""227    for part in response.iter_raw():228        raw += part229    assert raw == b"Hello, world!"230231232@pytest.mark.asyncio233async def test_aiter_raw():234    stream = AsyncIteratorStream(aiterator=async_streaming_body())235    response = httpx.Response(236        200,237        stream=stream,238    )239240    raw = b""241    async for part in response.aiter_raw():242        raw += part243    assert raw == b"Hello, world!"244245246def test_iter_bytes():247    response = httpx.Response(248        200,249        content=b"Hello, world!",250    )251252    content = b""253    for part in response.iter_bytes():254        content += part255    assert content == b"Hello, world!"256257258@pytest.mark.asyncio259async def test_aiter_bytes():260    response = httpx.Response(261        200,262        content=b"Hello, world!",263    )264265    content = b""266    async for part in response.aiter_bytes():267        content += part268    assert content == b"Hello, world!"269270271def test_iter_text():272    response = httpx.Response(273        200,274        content=b"Hello, world!",275    )276277    content = ""278    for part in response.iter_text():279        content += part280    assert content == "Hello, world!"281282283@pytest.mark.asyncio284async def test_aiter_text():285    response = httpx.Response(286        200,287        content=b"Hello, world!",288    )289290    content = ""291    async for part in response.aiter_text():292        content += part293    assert content == "Hello, world!"294295296def test_iter_lines():297    response = httpx.Response(298        200,299        content=b"Hello,\nworld!",300    )301302    content = []303    for line in response.iter_lines():304        content.append(line)305    assert content == ["Hello,\n", "world!"]306307308@pytest.mark.asyncio309async def test_aiter_lines():310    response = httpx.Response(311        200,312        content=b"Hello,\nworld!",313    )314315    content = []316    async for line in response.aiter_lines():317        content.append(line)318    assert content == ["Hello,\n", "world!"]319320321def test_sync_streaming_response():322    stream = IteratorStream(iterator=streaming_body())323    response = httpx.Response(324        200,325        stream=stream,326    )327328    assert response.status_code == 200329    assert not response.is_closed330331    content = response.read()332333    assert content == b"Hello, world!"334    assert response.content == b"Hello, world!"335    assert response.is_closed336337338@pytest.mark.asyncio339async def test_async_streaming_response():340    stream = AsyncIteratorStream(aiterator=async_streaming_body())341    response = httpx.Response(342        200,343        stream=stream,344    )345346    assert response.status_code == 200347    assert not response.is_closed348349    content = await response.aread()350351    assert content == b"Hello, world!"352    assert response.content == b"Hello, world!"353    assert response.is_closed354355356def test_cannot_read_after_stream_consumed():357    stream = IteratorStream(iterator=streaming_body())358    response = httpx.Response(359        200,360        stream=stream,361    )362363    content = b""364    for part in response.iter_bytes():365        content += part366367    with pytest.raises(httpx.StreamConsumed):368        response.read()369370371@pytest.mark.asyncio372async def test_cannot_aread_after_stream_consumed():373    stream = AsyncIteratorStream(aiterator=async_streaming_body())374    response = httpx.Response(375        200,376        stream=stream,377    )378379    content = b""380    async for part in response.aiter_bytes():381        content += part382383    with pytest.raises(httpx.StreamConsumed):384        await response.aread()385386387def test_cannot_read_after_response_closed():388    is_closed = False389390    def close_func():391        nonlocal is_closed392        is_closed = True393394    stream = IteratorStream(iterator=streaming_body(), close_func=close_func)395    response = httpx.Response(396        200,397        stream=stream,398    )399400    response.close()401    assert is_closed402403    with pytest.raises(httpx.ResponseClosed):404        response.read()405406407@pytest.mark.asyncio408async def test_cannot_aread_after_response_closed():409    is_closed = False410411    async def close_func():412        nonlocal is_closed413        is_closed = True414415    stream = AsyncIteratorStream(416        aiterator=async_streaming_body(), close_func=close_func417    )418    response = httpx.Response(419        200,420        stream=stream,421    )422423    await response.aclose()424    assert is_closed425426    with pytest.raises(httpx.ResponseClosed):427        await response.aread()428429430@pytest.mark.asyncio431async def test_elapsed_not_available_until_closed():432    stream = AsyncIteratorStream(aiterator=async_streaming_body())433    response = httpx.Response(434        200,435        stream=stream,436    )437438    with pytest.raises(RuntimeError):439        response.elapsed440441442def test_unknown_status_code():443    response = httpx.Response(444        600,445    )446    assert response.status_code == 600447    assert response.reason_phrase == ""448    assert response.text == ""449450451def test_json_with_specified_encoding():452    data = {"greeting": "hello", "recipient": "world"}453    content = json.dumps(data).encode("utf-16")454    headers = {"Content-Type": "application/json, charset=utf-16"}455    response = httpx.Response(456        200,457        content=content,458        headers=headers,459    )460    assert response.json() == data461462463def test_json_with_options():464    data = {"greeting": "hello", "recipient": "world", "amount": 1}465    content = json.dumps(data).encode("utf-16")466    headers = {"Content-Type": "application/json, charset=utf-16"}467    response = httpx.Response(468        200,469        content=content,470        headers=headers,471    )472    assert response.json(parse_int=str)["amount"] == "1"473474475def test_json_without_specified_encoding():476    data = {"greeting": "hello", "recipient": "world"}477    content = json.dumps(data).encode("utf-32-be")478    headers = {"Content-Type": "application/json"}479    response = httpx.Response(480        200,481        content=content,482        headers=headers,483    )484    assert response.json() == data485486487def test_json_without_specified_encoding_decode_error():488    data = {"greeting": "hello", "recipient": "world"}489    content = json.dumps(data).encode("utf-32-be")490    headers = {"Content-Type": "application/json"}491    # force incorrect guess from `guess_json_utf` to trigger error492    with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):493        response = httpx.Response(494            200,495            content=content,496            headers=headers,497        )498        with pytest.raises(json.decoder.JSONDecodeError):499            response.json()500501502def test_json_without_specified_encoding_value_error():503    data = {"greeting": "hello", "recipient": "world"}504    content = json.dumps(data).encode("utf-32-be")505    headers = {"Content-Type": "application/json"}506    # force incorrect guess from `guess_json_utf` to trigger error507    with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):508        response = httpx.Response(200, content=content, headers=headers)509        with pytest.raises(ValueError):510            response.json()511512513@pytest.mark.parametrize(514    "headers, expected",515    [516        (517            {"Link": "<https://example.com>; rel='preload'"},518            {"preload": {"rel": "preload", "url": "https://example.com"}},519        ),520        (521            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},522            {523                "hub": {"url": "/hub", "rel": "hub"},524                "self": {"url": "/resource", "rel": "self"},525            },526        ),527    ],528)529def test_link_headers(headers, expected):530    response = httpx.Response(531        200,532        content=None,533        headers=headers,534    )535    assert response.links == expected536537538@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))539def test_decode_error_with_request(header_value):540    headers = [(b"Content-Encoding", header_value)]541    body = b"test 123"542    compressed_body = brotli.compress(body)[3:]543    with pytest.raises(ValueError):544        httpx.Response(545            200,546            headers=headers,547            content=compressed_body,548        )549550    with pytest.raises(httpx.DecodingError):551        httpx.Response(552            200,553            headers=headers,554            content=compressed_body,555            request=httpx.Request("GET", "https://www.example.org/"),556        )557558559@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))560def test_value_error_without_request(header_value):561    headers = [(b"Content-Encoding", header_value)]562    body = b"test 123"563    compressed_body = brotli.compress(body)[3:]564    with pytest.raises(ValueError):565        httpx.Response(200, headers=headers, content=compressed_body)566567568def test_response_with_unset_request():569    response = httpx.Response(200, content=b"Hello, world!")570571    assert response.status_code == 200572    assert response.reason_phrase == "OK"573    assert response.text == "Hello, world!"574    assert not response.is_error575576577def test_set_request_after_init():578    response = httpx.Response(200, content=b"Hello, world!")579580    response.request = httpx.Request("GET", "https://www.example.org")581582    assert response.request.method == "GET"583    assert response.request.url == "https://www.example.org"584585586def test_cannot_access_unset_request():587    response = httpx.Response(200, content=b"Hello, world!")588589    with pytest.raises(RuntimeError):590        response.request