Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

910 lines · 24.2 KiB · Python

Last changed by

Fix iter_bytes with empty content (#1827)Tom Christiebefore adoption10b60d4

History of this file

Take it

1import json2import pickle34import pytest56import httpx7from httpx._compat import brotli8910class StreamingBody:11    def __iter__(self):12        yield b"Hello, "13        yield b"world!"141516def streaming_body():17    yield b"Hello, "18    yield b"world!"192021async def async_streaming_body():22    yield b"Hello, "23    yield b"world!"242526def test_response():27    response = httpx.Response(28        200,29        content=b"Hello, world!",30        request=httpx.Request("GET", "https://example.org"),31    )3233    assert response.status_code == 20034    assert response.reason_phrase == "OK"35    assert response.text == "Hello, world!"36    assert response.request.method == "GET"37    assert response.request.url == "https://example.org"38    assert not response.is_error394041def test_response_content():42    response = httpx.Response(200, content="Hello, world!")4344    assert response.status_code == 20045    assert response.reason_phrase == "OK"46    assert response.text == "Hello, world!"47    assert response.headers == {"Content-Length": "13"}484950def test_response_text():51    response = httpx.Response(200, text="Hello, world!")5253    assert response.status_code == 20054    assert response.reason_phrase == "OK"55    assert response.text == "Hello, world!"56    assert response.headers == {57        "Content-Length": "13",58        "Content-Type": "text/plain; charset=utf-8",59    }606162def test_response_html():63    response = httpx.Response(200, html="<html><body>Hello, world!</html></body>")6465    assert response.status_code == 20066    assert response.reason_phrase == "OK"67    assert response.text == "<html><body>Hello, world!</html></body>"68    assert response.headers == {69        "Content-Length": "39",70        "Content-Type": "text/html; charset=utf-8",71    }727374def test_response_json():75    response = httpx.Response(200, json={"hello": "world"})7677    assert response.status_code == 20078    assert response.reason_phrase == "OK"79    assert response.json() == {"hello": "world"}80    assert response.headers == {81        "Content-Length": "18",82        "Content-Type": "application/json",83    }848586def test_raise_for_status():87    request = httpx.Request("GET", "https://example.org")8889    # 2xx status codes are not an error.90    response = httpx.Response(200, request=request)91    response.raise_for_status()9293    # 4xx status codes are a client error.94    response = httpx.Response(403, request=request)95    with pytest.raises(httpx.HTTPStatusError):96        response.raise_for_status()9798    # 5xx status codes are a server error.99    response = httpx.Response(500, request=request)100    with pytest.raises(httpx.HTTPStatusError):101        response.raise_for_status()102103    # Calling .raise_for_status without setting a request instance is104    # not valid. Should raise a runtime error.105    response = httpx.Response(200)106    with pytest.raises(RuntimeError):107        response.raise_for_status()108109110def test_response_repr():111    response = httpx.Response(112        200,113        content=b"Hello, world!",114    )115    assert repr(response) == "<Response [200 OK]>"116117118def test_response_content_type_encoding():119    """120    Use the charset encoding in the Content-Type header if possible.121    """122    headers = {"Content-Type": "text-plain; charset=latin-1"}123    content = "Latin 1: ÿ".encode("latin-1")124    response = httpx.Response(125        200,126        content=content,127        headers=headers,128    )129    assert response.text == "Latin 1: ÿ"130    assert response.encoding == "latin-1"131132133def test_response_autodetect_encoding():134    """135    Autodetect encoding if there is no Content-Type header.136    """137    content = "おはようございます。".encode("utf-8")138    response = httpx.Response(139        200,140        content=content,141    )142    assert response.text == "おはようございます。"143    assert response.encoding is None144145146def test_response_fallback_to_autodetect():147    """148    Fallback to autodetection if we get an invalid charset in the Content-Type header.149    """150    headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}151    content = "おはようございます。".encode("utf-8")152    response = httpx.Response(153        200,154        content=content,155        headers=headers,156    )157    assert response.text == "おはようございます。"158    assert response.encoding is None159160161def test_response_no_charset_with_ascii_content():162    """163    A response with ascii encoded content should decode correctly,164    even with no charset specified.165    """166    content = b"Hello, world!"167    headers = {"Content-Type": "text/plain"}168    response = httpx.Response(169        200,170        content=content,171        headers=headers,172    )173    assert response.status_code == 200174    assert response.encoding is None175    assert response.text == "Hello, world!"176177178def test_response_no_charset_with_utf8_content():179    """180    A response with UTF-8 encoded content should decode correctly,181    even with no charset specified.182    """183    content = "Unicode Snowman: ☃".encode("utf-8")184    headers = {"Content-Type": "text/plain"}185    response = httpx.Response(186        200,187        content=content,188        headers=headers,189    )190    assert response.text == "Unicode Snowman: ☃"191    assert response.encoding is None192193194def test_response_no_charset_with_iso_8859_1_content():195    """196    A response with ISO 8859-1 encoded content should decode correctly,197    even with no charset specified.198    """199    content = "Accented: Österreich abcdefghijklmnopqrstuzwxyz".encode("iso-8859-1")200    headers = {"Content-Type": "text/plain"}201    response = httpx.Response(202        200,203        content=content,204        headers=headers,205    )206    assert response.text == "Accented: Österreich abcdefghijklmnopqrstuzwxyz"207    assert response.charset_encoding is None208    assert response.apparent_encoding is not None209210211def test_response_no_charset_with_cp_1252_content():212    """213    A response with Windows 1252 encoded content should decode correctly,214    even with no charset specified.215    """216    content = "Euro Currency: € abcdefghijklmnopqrstuzwxyz".encode("cp1252")217    headers = {"Content-Type": "text/plain"}218    response = httpx.Response(219        200,220        content=content,221        headers=headers,222    )223    assert response.text == "Euro Currency: € abcdefghijklmnopqrstuzwxyz"224    assert response.charset_encoding is None225    assert response.apparent_encoding is not None226227228def test_response_non_text_encoding():229    """230    Default to apparent encoding for non-text content-type headers.231    """232    headers = {"Content-Type": "image/png"}233    response = httpx.Response(234        200,235        content=b"xyz",236        headers=headers,237    )238    assert response.text == "xyz"239    assert response.encoding is None240241242def test_response_set_explicit_encoding():243    headers = {244        "Content-Type": "text-plain; charset=utf-8"245    }  # Deliberately incorrect charset246    response = httpx.Response(247        200,248        content="Latin 1: ÿ".encode("latin-1"),249        headers=headers,250    )251    response.encoding = "latin-1"252    assert response.text == "Latin 1: ÿ"253    assert response.encoding == "latin-1"254255256def test_response_force_encoding():257    response = httpx.Response(258        200,259        content="Snowman: ☃".encode("utf-8"),260    )261    response.encoding = "iso-8859-1"262    assert response.status_code == 200263    assert response.reason_phrase == "OK"264    assert response.text == "Snowman: â\x98\x83"265    assert response.encoding == "iso-8859-1"266267268def test_read():269    response = httpx.Response(270        200,271        content=b"Hello, world!",272    )273274    assert response.status_code == 200275    assert response.text == "Hello, world!"276    assert response.encoding is None277    assert response.is_closed278279    content = response.read()280281    assert content == b"Hello, world!"282    assert response.content == b"Hello, world!"283    assert response.is_closed284285286def test_empty_read():287    response = httpx.Response(200)288289    assert response.status_code == 200290    assert response.text == ""291    assert response.encoding is None292    assert response.is_closed293294    content = response.read()295296    assert content == b""297    assert response.content == b""298    assert response.is_closed299300301@pytest.mark.asyncio302async def test_aread():303    response = httpx.Response(304        200,305        content=b"Hello, world!",306    )307308    assert response.status_code == 200309    assert response.text == "Hello, world!"310    assert response.encoding is None311    assert response.is_closed312313    content = await response.aread()314315    assert content == b"Hello, world!"316    assert response.content == b"Hello, world!"317    assert response.is_closed318319320@pytest.mark.asyncio321async def test_empty_aread():322    response = httpx.Response(200)323324    assert response.status_code == 200325    assert response.text == ""326    assert response.encoding is None327    assert response.is_closed328329    content = await response.aread()330331    assert content == b""332    assert response.content == b""333    assert response.is_closed334335336def test_iter_raw():337    response = httpx.Response(338        200,339        content=streaming_body(),340    )341342    raw = b""343    for part in response.iter_raw():344        raw += part345    assert raw == b"Hello, world!"346347348def test_iter_raw_with_chunksize():349    response = httpx.Response(200, content=streaming_body())350351    parts = [part for part in response.iter_raw(chunk_size=5)]352    assert parts == [b"Hello", b", wor", b"ld!"]353354    response = httpx.Response(200, content=streaming_body())355356    parts = [part for part in response.iter_raw(chunk_size=13)]357    assert parts == [b"Hello, world!"]358359    response = httpx.Response(200, content=streaming_body())360361    parts = [part for part in response.iter_raw(chunk_size=20)]362    assert parts == [b"Hello, world!"]363364365def test_iter_raw_on_iterable():366    response = httpx.Response(367        200,368        content=StreamingBody(),369    )370371    raw = b""372    for part in response.iter_raw():373        raw += part374    assert raw == b"Hello, world!"375376377def test_iter_raw_on_async():378    response = httpx.Response(379        200,380        content=async_streaming_body(),381    )382383    with pytest.raises(RuntimeError):384        [part for part in response.iter_raw()]385386387def test_close_on_async():388    response = httpx.Response(389        200,390        content=async_streaming_body(),391    )392393    with pytest.raises(RuntimeError):394        response.close()395396397def test_iter_raw_increments_updates_counter():398    response = httpx.Response(200, content=streaming_body())399400    num_downloaded = response.num_bytes_downloaded401    for part in response.iter_raw():402        assert len(part) == (response.num_bytes_downloaded - num_downloaded)403        num_downloaded = response.num_bytes_downloaded404405406@pytest.mark.asyncio407async def test_aiter_raw():408    response = httpx.Response(200, content=async_streaming_body())409410    raw = b""411    async for part in response.aiter_raw():412        raw += part413    assert raw == b"Hello, world!"414415416@pytest.mark.asyncio417async def test_aiter_raw_with_chunksize():418    response = httpx.Response(200, content=async_streaming_body())419420    parts = [part async for part in response.aiter_raw(chunk_size=5)]421    assert parts == [b"Hello", b", wor", b"ld!"]422423    response = httpx.Response(200, content=async_streaming_body())424425    parts = [part async for part in response.aiter_raw(chunk_size=13)]426    assert parts == [b"Hello, world!"]427428    response = httpx.Response(200, content=async_streaming_body())429430    parts = [part async for part in response.aiter_raw(chunk_size=20)]431    assert parts == [b"Hello, world!"]432433434@pytest.mark.asyncio435async def test_aiter_raw_on_sync():436    response = httpx.Response(437        200,438        content=streaming_body(),439    )440441    with pytest.raises(RuntimeError):442        [part async for part in response.aiter_raw()]443444445@pytest.mark.asyncio446async def test_aclose_on_sync():447    response = httpx.Response(448        200,449        content=streaming_body(),450    )451452    with pytest.raises(RuntimeError):453        await response.aclose()454455456@pytest.mark.asyncio457async def test_aiter_raw_increments_updates_counter():458    response = httpx.Response(200, content=async_streaming_body())459460    num_downloaded = response.num_bytes_downloaded461    async for part in response.aiter_raw():462        assert len(part) == (response.num_bytes_downloaded - num_downloaded)463        num_downloaded = response.num_bytes_downloaded464465466def test_iter_bytes():467    response = httpx.Response(200, content=b"Hello, world!")468469    content = b""470    for part in response.iter_bytes():471        content += part472    assert content == b"Hello, world!"473474475def test_iter_bytes_with_chunk_size():476    response = httpx.Response(200, content=streaming_body())477    parts = [part for part in response.iter_bytes(chunk_size=5)]478    assert parts == [b"Hello", b", wor", b"ld!"]479480    response = httpx.Response(200, content=streaming_body())481    parts = [part for part in response.iter_bytes(chunk_size=13)]482    assert parts == [b"Hello, world!"]483484    response = httpx.Response(200, content=streaming_body())485    parts = [part for part in response.iter_bytes(chunk_size=20)]486    assert parts == [b"Hello, world!"]487488489def test_iter_bytes_with_empty_response():490    response = httpx.Response(200, content=b"")491    parts = [part for part in response.iter_bytes()]492    assert parts == []493494495@pytest.mark.asyncio496async def test_aiter_bytes():497    response = httpx.Response(498        200,499        content=b"Hello, world!",500    )501502    content = b""503    async for part in response.aiter_bytes():504        content += part505    assert content == b"Hello, world!"506507508@pytest.mark.asyncio509async def test_aiter_bytes_with_chunk_size():510    response = httpx.Response(200, content=async_streaming_body())511    parts = [part async for part in response.aiter_bytes(chunk_size=5)]512    assert parts == [b"Hello", b", wor", b"ld!"]513514    response = httpx.Response(200, content=async_streaming_body())515    parts = [part async for part in response.aiter_bytes(chunk_size=13)]516    assert parts == [b"Hello, world!"]517518    response = httpx.Response(200, content=async_streaming_body())519    parts = [part async for part in response.aiter_bytes(chunk_size=20)]520    assert parts == [b"Hello, world!"]521522523def test_iter_text():524    response = httpx.Response(525        200,526        content=b"Hello, world!",527    )528529    content = ""530    for part in response.iter_text():531        content += part532    assert content == "Hello, world!"533534535def test_iter_text_with_chunk_size():536    response = httpx.Response(200, content=b"Hello, world!")537    parts = [part for part in response.iter_text(chunk_size=5)]538    assert parts == ["Hello", ", wor", "ld!"]539540    response = httpx.Response(200, content=b"Hello, world!")541    parts = [part for part in response.iter_text(chunk_size=13)]542    assert parts == ["Hello, world!"]543544    response = httpx.Response(200, content=b"Hello, world!")545    parts = [part for part in response.iter_text(chunk_size=20)]546    assert parts == ["Hello, world!"]547548549@pytest.mark.asyncio550async def test_aiter_text():551    response = httpx.Response(552        200,553        content=b"Hello, world!",554    )555556    content = ""557    async for part in response.aiter_text():558        content += part559    assert content == "Hello, world!"560561562@pytest.mark.asyncio563async def test_aiter_text_with_chunk_size():564    response = httpx.Response(200, content=b"Hello, world!")565    parts = [part async for part in response.aiter_text(chunk_size=5)]566    assert parts == ["Hello", ", wor", "ld!"]567568    response = httpx.Response(200, content=b"Hello, world!")569    parts = [part async for part in response.aiter_text(chunk_size=13)]570    assert parts == ["Hello, world!"]571572    response = httpx.Response(200, content=b"Hello, world!")573    parts = [part async for part in response.aiter_text(chunk_size=20)]574    assert parts == ["Hello, world!"]575576577def test_iter_lines():578    response = httpx.Response(579        200,580        content=b"Hello,\nworld!",581    )582    content = [line for line in response.iter_lines()]583    assert content == ["Hello,\n", "world!"]584585586@pytest.mark.asyncio587async def test_aiter_lines():588    response = httpx.Response(589        200,590        content=b"Hello,\nworld!",591    )592593    content = []594    async for line in response.aiter_lines():595        content.append(line)596    assert content == ["Hello,\n", "world!"]597598599def test_sync_streaming_response():600    response = httpx.Response(601        200,602        content=streaming_body(),603    )604605    assert response.status_code == 200606    assert not response.is_closed607608    content = response.read()609610    assert content == b"Hello, world!"611    assert response.content == b"Hello, world!"612    assert response.is_closed613614615@pytest.mark.asyncio616async def test_async_streaming_response():617    response = httpx.Response(618        200,619        content=async_streaming_body(),620    )621622    assert response.status_code == 200623    assert not response.is_closed624625    content = await response.aread()626627    assert content == b"Hello, world!"628    assert response.content == b"Hello, world!"629    assert response.is_closed630631632def test_cannot_read_after_stream_consumed():633    response = httpx.Response(634        200,635        content=streaming_body(),636    )637638    content = b""639    for part in response.iter_bytes():640        content += part641642    with pytest.raises(httpx.StreamConsumed):643        response.read()644645646@pytest.mark.asyncio647async def test_cannot_aread_after_stream_consumed():648    response = httpx.Response(649        200,650        content=async_streaming_body(),651    )652653    content = b""654    async for part in response.aiter_bytes():655        content += part656657    with pytest.raises(httpx.StreamConsumed):658        await response.aread()659660661def test_cannot_read_after_response_closed():662    response = httpx.Response(663        200,664        content=streaming_body(),665    )666667    response.close()668    with pytest.raises(httpx.StreamClosed):669        response.read()670671672@pytest.mark.asyncio673async def test_cannot_aread_after_response_closed():674    response = httpx.Response(675        200,676        content=async_streaming_body(),677    )678679    await response.aclose()680    with pytest.raises(httpx.StreamClosed):681        await response.aread()682683684@pytest.mark.asyncio685async def test_elapsed_not_available_until_closed():686    response = httpx.Response(687        200,688        content=async_streaming_body(),689    )690691    with pytest.raises(RuntimeError):692        response.elapsed693694695def test_unknown_status_code():696    response = httpx.Response(697        600,698    )699    assert response.status_code == 600700    assert response.reason_phrase == ""701    assert response.text == ""702703704def test_json_with_specified_encoding():705    data = {"greeting": "hello", "recipient": "world"}706    content = json.dumps(data).encode("utf-16")707    headers = {"Content-Type": "application/json, charset=utf-16"}708    response = httpx.Response(709        200,710        content=content,711        headers=headers,712    )713    assert response.json() == data714715716def test_json_with_options():717    data = {"greeting": "hello", "recipient": "world", "amount": 1}718    content = json.dumps(data).encode("utf-16")719    headers = {"Content-Type": "application/json, charset=utf-16"}720    response = httpx.Response(721        200,722        content=content,723        headers=headers,724    )725    assert response.json(parse_int=str)["amount"] == "1"726727728@pytest.mark.parametrize(729    "encoding",730    [731        "utf-8",732        "utf-8-sig",733        "utf-16",734        "utf-16-be",735        "utf-16-le",736        "utf-32",737        "utf-32-be",738        "utf-32-le",739    ],740)741def test_json_without_specified_charset(encoding):742    data = {"greeting": "hello", "recipient": "world"}743    content = json.dumps(data).encode(encoding)744    headers = {"Content-Type": "application/json"}745    response = httpx.Response(746        200,747        content=content,748        headers=headers,749    )750    assert response.json() == data751752753@pytest.mark.parametrize(754    "encoding",755    [756        "utf-8",757        "utf-8-sig",758        "utf-16",759        "utf-16-be",760        "utf-16-le",761        "utf-32",762        "utf-32-be",763        "utf-32-le",764    ],765)766def test_json_with_specified_charset(encoding):767    data = {"greeting": "hello", "recipient": "world"}768    content = json.dumps(data).encode(encoding)769    headers = {"Content-Type": f"application/json; charset={encoding}"}770    response = httpx.Response(771        200,772        content=content,773        headers=headers,774    )775    assert response.json() == data776777778@pytest.mark.parametrize(779    "headers, expected",780    [781        (782            {"Link": "<https://example.com>; rel='preload'"},783            {"preload": {"rel": "preload", "url": "https://example.com"}},784        ),785        (786            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},787            {788                "hub": {"url": "/hub", "rel": "hub"},789                "self": {"url": "/resource", "rel": "self"},790            },791        ),792    ],793)794def test_link_headers(headers, expected):795    response = httpx.Response(796        200,797        content=None,798        headers=headers,799    )800    assert response.links == expected801802803@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))804def test_decode_error_with_request(header_value):805    headers = [(b"Content-Encoding", header_value)]806    body = b"test 123"807    compressed_body = brotli.compress(body)[3:]808    with pytest.raises(httpx.DecodingError):809        httpx.Response(810            200,811            headers=headers,812            content=compressed_body,813        )814815    with pytest.raises(httpx.DecodingError):816        httpx.Response(817            200,818            headers=headers,819            content=compressed_body,820            request=httpx.Request("GET", "https://www.example.org/"),821        )822823824@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))825def test_value_error_without_request(header_value):826    headers = [(b"Content-Encoding", header_value)]827    body = b"test 123"828    compressed_body = brotli.compress(body)[3:]829    with pytest.raises(httpx.DecodingError):830        httpx.Response(200, headers=headers, content=compressed_body)831832833def test_response_with_unset_request():834    response = httpx.Response(200, content=b"Hello, world!")835836    assert response.status_code == 200837    assert response.reason_phrase == "OK"838    assert response.text == "Hello, world!"839    assert not response.is_error840841842def test_set_request_after_init():843    response = httpx.Response(200, content=b"Hello, world!")844845    response.request = httpx.Request("GET", "https://www.example.org")846847    assert response.request.method == "GET"848    assert response.request.url == "https://www.example.org"849850851def test_cannot_access_unset_request():852    response = httpx.Response(200, content=b"Hello, world!")853854    with pytest.raises(RuntimeError):855        response.request856857858def test_generator_with_transfer_encoding_header():859    def content():860        yield b"test 123"  # pragma: nocover861862    response = httpx.Response(200, content=content())863    assert response.headers == {"Transfer-Encoding": "chunked"}864865866def test_generator_with_content_length_header():867    def content():868        yield b"test 123"  # pragma: nocover869870    headers = {"Content-Length": "8"}871    response = httpx.Response(200, content=content(), headers=headers)872    assert response.headers == {"Content-Length": "8"}873874875def test_response_picklable():876    response = httpx.Response(877        200,878        content=b"Hello, world!",879        request=httpx.Request("GET", "https://example.org"),880    )881    pickle_response = pickle.loads(pickle.dumps(response))882    assert pickle_response.is_closed is True883    assert pickle_response.is_stream_consumed is True884    assert pickle_response.next_request is None885    assert pickle_response.stream is not None886    assert pickle_response.content == b"Hello, world!"887    assert pickle_response.status_code == 200888    assert pickle_response.request.url == response.request.url889    assert pickle_response.extensions == {}890    assert pickle_response.history == []891892893@pytest.mark.asyncio894async def test_response_async_streaming_picklable():895    response = httpx.Response(200, content=async_streaming_body())896    pickle_response = pickle.loads(pickle.dumps(response))897    with pytest.raises(httpx.ResponseNotRead):898        pickle_response.content899    with pytest.raises(httpx.StreamClosed):900        await pickle_response.aread()901    assert pickle_response.is_stream_consumed is False902    assert pickle_response.num_bytes_downloaded == 0903    assert pickle_response.headers == {"Transfer-Encoding": "chunked"}904905    response = httpx.Response(200, content=async_streaming_body())906    await response.aread()907    pickle_response = pickle.loads(pickle.dumps(response))908    assert pickle_response.is_stream_consumed is True909    assert pickle_response.content == b"Hello, world!"910    assert pickle_response.num_bytes_downloaded == 13