Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

612 lines · 15.7 KiB · Python

Last changed by

Drop chardet (#1269)Tom Christiebefore adoptiond0fe113

History of this file

Take it

1import json2from unittest import mock34import brotli5import pytest67import httpx8910def streaming_body():11    yield b"Hello, "12    yield b"world!"131415async def async_streaming_body():16    yield b"Hello, "17    yield b"world!"181920def test_response():21    response = httpx.Response(22        200,23        content=b"Hello, world!",24        request=httpx.Request("GET", "https://example.org"),25    )2627    assert response.status_code == 20028    assert response.reason_phrase == "OK"29    assert response.text == "Hello, world!"30    assert response.request.method == "GET"31    assert response.request.url == "https://example.org"32    assert not response.is_error333435def test_raise_for_status():36    request = httpx.Request("GET", "https://example.org")3738    # 2xx status codes are not an error.39    response = httpx.Response(200, request=request)40    response.raise_for_status()4142    # 4xx status codes are a client error.43    response = httpx.Response(403, request=request)44    with pytest.raises(httpx.HTTPStatusError):45        response.raise_for_status()4647    # 5xx status codes are a server error.48    response = httpx.Response(500, request=request)49    with pytest.raises(httpx.HTTPStatusError):50        response.raise_for_status()5152    # Calling .raise_for_status without setting a request instance is53    # not valid. Should raise a runtime error.54    response = httpx.Response(200)55    with pytest.raises(RuntimeError):56        response.raise_for_status()575859def test_response_repr():60    response = httpx.Response(61        200,62        content=b"Hello, world!",63    )64    assert repr(response) == "<Response [200 OK]>"656667def test_response_content_type_encoding():68    """69    Use the charset encoding in the Content-Type header if possible.70    """71    headers = {"Content-Type": "text-plain; charset=latin-1"}72    content = "Latin 1: ÿ".encode("latin-1")73    response = httpx.Response(74        200,75        content=content,76        headers=headers,77    )78    assert response.text == "Latin 1: ÿ"79    assert response.encoding == "latin-1"808182def test_response_autodetect_encoding():83    """84    Autodetect encoding if there is no Content-Type header.85    """86    content = "おはようございます。".encode("utf-8")87    response = httpx.Response(88        200,89        content=content,90    )91    assert response.text == "おはようございます。"92    assert response.encoding is None939495def test_response_fallback_to_autodetect():96    """97    Fallback to autodetection if we get an invalid charset in the Content-Type header.98    """99    headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}100    content = "おはようございます。".encode("utf-8")101    response = httpx.Response(102        200,103        content=content,104        headers=headers,105    )106    assert response.text == "おはようございます。"107    assert response.encoding is None108109110def test_response_no_charset_with_ascii_content():111    """112    A response with ascii encoded content should decode correctly,113    even with no charset specified.114    """115    content = b"Hello, world!"116    headers = {"Content-Type": "text/plain"}117    response = httpx.Response(118        200,119        content=content,120        headers=headers,121    )122    assert response.status_code == 200123    assert response.encoding is None124    assert response.text == "Hello, world!"125126127def test_response_no_charset_with_utf8_content():128    """129    A response with UTF-8 encoded content should decode correctly,130    even with no charset specified.131    """132    content = "Unicode Snowman: ☃".encode("utf-8")133    headers = {"Content-Type": "text/plain"}134    response = httpx.Response(135        200,136        content=content,137        headers=headers,138    )139    assert response.text == "Unicode Snowman: ☃"140    assert response.encoding is None141142143def test_response_no_charset_with_iso_8859_1_content():144    """145    A response with ISO 8859-1 encoded content should decode correctly,146    even with no charset specified.147    """148    content = "Accented: Österreich".encode("iso-8859-1")149    headers = {"Content-Type": "text/plain"}150    response = httpx.Response(151        200,152        content=content,153        headers=headers,154    )155    assert response.text == "Accented: Österreich"156    assert response.encoding is None157158159def test_response_no_charset_with_cp_1252_content():160    """161    A response with Windows 1252 encoded content should decode correctly,162    even with no charset specified.163    """164    content = "Euro Currency: €".encode("cp1252")165    headers = {"Content-Type": "text/plain"}166    response = httpx.Response(167        200,168        content=content,169        headers=headers,170    )171    assert response.text == "Euro Currency: €"172    assert response.encoding is None173174175def test_response_non_text_encoding():176    """177    Default to apparent encoding for non-text content-type headers.178    """179    headers = {"Content-Type": "image/png"}180    response = httpx.Response(181        200,182        content=b"xyz",183        headers=headers,184    )185    assert response.text == "xyz"186    assert response.encoding is None187188189def test_response_set_explicit_encoding():190    headers = {191        "Content-Type": "text-plain; charset=utf-8"192    }  # Deliberately incorrect charset193    response = httpx.Response(194        200,195        content="Latin 1: ÿ".encode("latin-1"),196        headers=headers,197    )198    response.encoding = "latin-1"199    assert response.text == "Latin 1: ÿ"200    assert response.encoding == "latin-1"201202203def test_response_force_encoding():204    response = httpx.Response(205        200,206        content="Snowman: ☃".encode("utf-8"),207    )208    response.encoding = "iso-8859-1"209    assert response.status_code == 200210    assert response.reason_phrase == "OK"211    assert response.text == "Snowman: â\x98\x83"212    assert response.encoding == "iso-8859-1"213214215def test_read():216    response = httpx.Response(217        200,218        content=b"Hello, world!",219    )220221    assert response.status_code == 200222    assert response.text == "Hello, world!"223    assert response.encoding is None224    assert response.is_closed225226    content = response.read()227228    assert content == b"Hello, world!"229    assert response.content == b"Hello, world!"230    assert response.is_closed231232233@pytest.mark.asyncio234async def test_aread():235    response = httpx.Response(236        200,237        content=b"Hello, world!",238    )239240    assert response.status_code == 200241    assert response.text == "Hello, world!"242    assert response.encoding is None243    assert response.is_closed244245    content = await response.aread()246247    assert content == b"Hello, world!"248    assert response.content == b"Hello, world!"249    assert response.is_closed250251252def test_iter_raw():253    response = httpx.Response(254        200,255        content=streaming_body(),256    )257258    raw = b""259    for part in response.iter_raw():260        raw += part261    assert raw == b"Hello, world!"262263264def test_iter_raw_increments_updates_counter():265    response = httpx.Response(200, content=streaming_body())266267    num_downloaded = response.num_bytes_downloaded268    for part in response.iter_raw():269        assert len(part) == (response.num_bytes_downloaded - num_downloaded)270        num_downloaded = response.num_bytes_downloaded271272273@pytest.mark.asyncio274async def test_aiter_raw():275    response = httpx.Response(200, content=async_streaming_body())276277    raw = b""278    async for part in response.aiter_raw():279        raw += part280    assert raw == b"Hello, world!"281282283@pytest.mark.asyncio284async def test_aiter_raw_increments_updates_counter():285    response = httpx.Response(200, content=async_streaming_body())286287    num_downloaded = response.num_bytes_downloaded288    async for part in response.aiter_raw():289        assert len(part) == (response.num_bytes_downloaded - num_downloaded)290        num_downloaded = response.num_bytes_downloaded291292293def test_iter_bytes():294    response = httpx.Response(295        200,296        content=b"Hello, world!",297    )298299    content = b""300    for part in response.iter_bytes():301        content += part302    assert content == b"Hello, world!"303304305@pytest.mark.asyncio306async def test_aiter_bytes():307    response = httpx.Response(308        200,309        content=b"Hello, world!",310    )311312    content = b""313    async for part in response.aiter_bytes():314        content += part315    assert content == b"Hello, world!"316317318def test_iter_text():319    response = httpx.Response(320        200,321        content=b"Hello, world!",322    )323324    content = ""325    for part in response.iter_text():326        content += part327    assert content == "Hello, world!"328329330@pytest.mark.asyncio331async def test_aiter_text():332    response = httpx.Response(333        200,334        content=b"Hello, world!",335    )336337    content = ""338    async for part in response.aiter_text():339        content += part340    assert content == "Hello, world!"341342343def test_iter_lines():344    response = httpx.Response(345        200,346        content=b"Hello,\nworld!",347    )348349    content = []350    for line in response.iter_lines():351        content.append(line)352    assert content == ["Hello,\n", "world!"]353354355@pytest.mark.asyncio356async def test_aiter_lines():357    response = httpx.Response(358        200,359        content=b"Hello,\nworld!",360    )361362    content = []363    async for line in response.aiter_lines():364        content.append(line)365    assert content == ["Hello,\n", "world!"]366367368def test_sync_streaming_response():369    response = httpx.Response(370        200,371        content=streaming_body(),372    )373374    assert response.status_code == 200375    assert not response.is_closed376377    content = response.read()378379    assert content == b"Hello, world!"380    assert response.content == b"Hello, world!"381    assert response.is_closed382383384@pytest.mark.asyncio385async def test_async_streaming_response():386    response = httpx.Response(387        200,388        content=async_streaming_body(),389    )390391    assert response.status_code == 200392    assert not response.is_closed393394    content = await response.aread()395396    assert content == b"Hello, world!"397    assert response.content == b"Hello, world!"398    assert response.is_closed399400401def test_cannot_read_after_stream_consumed():402    response = httpx.Response(403        200,404        content=streaming_body(),405    )406407    content = b""408    for part in response.iter_bytes():409        content += part410411    with pytest.raises(httpx.StreamConsumed):412        response.read()413414415@pytest.mark.asyncio416async def test_cannot_aread_after_stream_consumed():417    response = httpx.Response(418        200,419        content=async_streaming_body(),420    )421422    content = b""423    async for part in response.aiter_bytes():424        content += part425426    with pytest.raises(httpx.StreamConsumed):427        await response.aread()428429430def test_cannot_read_after_response_closed():431    response = httpx.Response(432        200,433        content=streaming_body(),434    )435436    response.close()437    with pytest.raises(httpx.ResponseClosed):438        response.read()439440441@pytest.mark.asyncio442async def test_cannot_aread_after_response_closed():443    response = httpx.Response(444        200,445        content=async_streaming_body(),446    )447448    await response.aclose()449    with pytest.raises(httpx.ResponseClosed):450        await response.aread()451452453@pytest.mark.asyncio454async def test_elapsed_not_available_until_closed():455    response = httpx.Response(456        200,457        content=async_streaming_body(),458    )459460    with pytest.raises(RuntimeError):461        response.elapsed462463464def test_unknown_status_code():465    response = httpx.Response(466        600,467    )468    assert response.status_code == 600469    assert response.reason_phrase == ""470    assert response.text == ""471472473def test_json_with_specified_encoding():474    data = {"greeting": "hello", "recipient": "world"}475    content = json.dumps(data).encode("utf-16")476    headers = {"Content-Type": "application/json, charset=utf-16"}477    response = httpx.Response(478        200,479        content=content,480        headers=headers,481    )482    assert response.json() == data483484485def test_json_with_options():486    data = {"greeting": "hello", "recipient": "world", "amount": 1}487    content = json.dumps(data).encode("utf-16")488    headers = {"Content-Type": "application/json, charset=utf-16"}489    response = httpx.Response(490        200,491        content=content,492        headers=headers,493    )494    assert response.json(parse_int=str)["amount"] == "1"495496497def test_json_without_specified_encoding():498    data = {"greeting": "hello", "recipient": "world"}499    content = json.dumps(data).encode("utf-32-be")500    headers = {"Content-Type": "application/json"}501    response = httpx.Response(502        200,503        content=content,504        headers=headers,505    )506    assert response.json() == data507508509def test_json_without_specified_encoding_decode_error():510    data = {"greeting": "hello", "recipient": "world"}511    content = json.dumps(data).encode("utf-32-be")512    headers = {"Content-Type": "application/json"}513    # force incorrect guess from `guess_json_utf` to trigger error514    with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):515        response = httpx.Response(516            200,517            content=content,518            headers=headers,519        )520        with pytest.raises(json.decoder.JSONDecodeError):521            response.json()522523524def test_json_without_specified_encoding_value_error():525    data = {"greeting": "hello", "recipient": "world"}526    content = json.dumps(data).encode("utf-32-be")527    headers = {"Content-Type": "application/json"}528    # force incorrect guess from `guess_json_utf` to trigger error529    with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):530        response = httpx.Response(200, content=content, headers=headers)531        with pytest.raises(ValueError):532            response.json()533534535@pytest.mark.parametrize(536    "headers, expected",537    [538        (539            {"Link": "<https://example.com>; rel='preload'"},540            {"preload": {"rel": "preload", "url": "https://example.com"}},541        ),542        (543            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},544            {545                "hub": {"url": "/hub", "rel": "hub"},546                "self": {"url": "/resource", "rel": "self"},547            },548        ),549    ],550)551def test_link_headers(headers, expected):552    response = httpx.Response(553        200,554        content=None,555        headers=headers,556    )557    assert response.links == expected558559560@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))561def test_decode_error_with_request(header_value):562    headers = [(b"Content-Encoding", header_value)]563    body = b"test 123"564    compressed_body = brotli.compress(body)[3:]565    with pytest.raises(ValueError):566        httpx.Response(567            200,568            headers=headers,569            content=compressed_body,570        )571572    with pytest.raises(httpx.DecodingError):573        httpx.Response(574            200,575            headers=headers,576            content=compressed_body,577            request=httpx.Request("GET", "https://www.example.org/"),578        )579580581@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))582def test_value_error_without_request(header_value):583    headers = [(b"Content-Encoding", header_value)]584    body = b"test 123"585    compressed_body = brotli.compress(body)[3:]586    with pytest.raises(ValueError):587        httpx.Response(200, headers=headers, content=compressed_body)588589590def test_response_with_unset_request():591    response = httpx.Response(200, content=b"Hello, world!")592593    assert response.status_code == 200594    assert response.reason_phrase == "OK"595    assert response.text == "Hello, world!"596    assert not response.is_error597598599def test_set_request_after_init():600    response = httpx.Response(200, content=b"Hello, world!")601602    response.request = httpx.Request("GET", "https://www.example.org")603604    assert response.request.method == "GET"605    assert response.request.url == "https://www.example.org"606607608def test_cannot_access_unset_request():609    response = httpx.Response(200, content=b"Hello, world!")610611    with pytest.raises(RuntimeError):612        response.request