Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

944 lines · 25.7 KiB · Python

Last changed by

is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17

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    # 1xx status codes are informational responses.94    response = httpx.Response(101, request=request)95    assert response.is_informational96    with pytest.raises(httpx.HTTPStatusError) as exc_info:97        response.raise_for_status()98    assert str(exc_info.value) == (99        "Informational response '101 Switching Protocols' for url 'https://example.org'\n"100        "For more information check: https://httpstatuses.com/101"101    )102103    # 3xx status codes are redirections.104    headers = {"location": "https://other.org"}105    response = httpx.Response(303, headers=headers, request=request)106    assert response.is_redirect107    with pytest.raises(httpx.HTTPStatusError) as exc_info:108        response.raise_for_status()109    assert str(exc_info.value) == (110        "Redirect response '303 See Other' for url 'https://example.org'\n"111        "Redirect location: 'https://other.org'\n"112        "For more information check: https://httpstatuses.com/303"113    )114115    # 4xx status codes are a client error.116    response = httpx.Response(403, request=request)117    assert response.is_client_error118    assert response.is_error119    with pytest.raises(httpx.HTTPStatusError) as exc_info:120        response.raise_for_status()121    assert str(exc_info.value) == (122        "Client error '403 Forbidden' for url 'https://example.org'\n"123        "For more information check: https://httpstatuses.com/403"124    )125126    # 5xx status codes are a server error.127    response = httpx.Response(500, request=request)128    assert response.is_server_error129    assert response.is_error130    with pytest.raises(httpx.HTTPStatusError) as exc_info:131        response.raise_for_status()132    assert str(exc_info.value) == (133        "Server error '500 Internal Server Error' for url 'https://example.org'\n"134        "For more information check: https://httpstatuses.com/500"135    )136137    # Calling .raise_for_status without setting a request instance is138    # not valid. Should raise a runtime error.139    response = httpx.Response(200)140    with pytest.raises(RuntimeError):141        response.raise_for_status()142143144def test_response_repr():145    response = httpx.Response(146        200,147        content=b"Hello, world!",148    )149    assert repr(response) == "<Response [200 OK]>"150151152def test_response_content_type_encoding():153    """154    Use the charset encoding in the Content-Type header if possible.155    """156    headers = {"Content-Type": "text-plain; charset=latin-1"}157    content = "Latin 1: ÿ".encode("latin-1")158    response = httpx.Response(159        200,160        content=content,161        headers=headers,162    )163    assert response.text == "Latin 1: ÿ"164    assert response.encoding == "latin-1"165166167def test_response_autodetect_encoding():168    """169    Autodetect encoding if there is no Content-Type header.170    """171    content = "おはようございます。".encode("utf-8")172    response = httpx.Response(173        200,174        content=content,175    )176    assert response.text == "おはようございます。"177    assert response.encoding is None178179180def test_response_fallback_to_autodetect():181    """182    Fallback to autodetection if we get an invalid charset in the Content-Type header.183    """184    headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}185    content = "おはようございます。".encode("utf-8")186    response = httpx.Response(187        200,188        content=content,189        headers=headers,190    )191    assert response.text == "おはようございます。"192    assert response.encoding is None193194195def test_response_no_charset_with_ascii_content():196    """197    A response with ascii encoded content should decode correctly,198    even with no charset specified.199    """200    content = b"Hello, world!"201    headers = {"Content-Type": "text/plain"}202    response = httpx.Response(203        200,204        content=content,205        headers=headers,206    )207    assert response.status_code == 200208    assert response.encoding is None209    assert response.text == "Hello, world!"210211212def test_response_no_charset_with_utf8_content():213    """214    A response with UTF-8 encoded content should decode correctly,215    even with no charset specified.216    """217    content = "Unicode Snowman: ☃".encode("utf-8")218    headers = {"Content-Type": "text/plain"}219    response = httpx.Response(220        200,221        content=content,222        headers=headers,223    )224    assert response.text == "Unicode Snowman: ☃"225    assert response.encoding is None226227228def test_response_no_charset_with_iso_8859_1_content():229    """230    A response with ISO 8859-1 encoded content should decode correctly,231    even with no charset specified.232    """233    content = "Accented: Österreich abcdefghijklmnopqrstuzwxyz".encode("iso-8859-1")234    headers = {"Content-Type": "text/plain"}235    response = httpx.Response(236        200,237        content=content,238        headers=headers,239    )240    assert response.text == "Accented: Österreich abcdefghijklmnopqrstuzwxyz"241    assert response.charset_encoding is None242    assert response.apparent_encoding is not None243244245def test_response_no_charset_with_cp_1252_content():246    """247    A response with Windows 1252 encoded content should decode correctly,248    even with no charset specified.249    """250    content = "Euro Currency: € abcdefghijklmnopqrstuzwxyz".encode("cp1252")251    headers = {"Content-Type": "text/plain"}252    response = httpx.Response(253        200,254        content=content,255        headers=headers,256    )257    assert response.text == "Euro Currency: € abcdefghijklmnopqrstuzwxyz"258    assert response.charset_encoding is None259    assert response.apparent_encoding is not None260261262def test_response_non_text_encoding():263    """264    Default to apparent encoding for non-text content-type headers.265    """266    headers = {"Content-Type": "image/png"}267    response = httpx.Response(268        200,269        content=b"xyz",270        headers=headers,271    )272    assert response.text == "xyz"273    assert response.encoding is None274275276def test_response_set_explicit_encoding():277    headers = {278        "Content-Type": "text-plain; charset=utf-8"279    }  # Deliberately incorrect charset280    response = httpx.Response(281        200,282        content="Latin 1: ÿ".encode("latin-1"),283        headers=headers,284    )285    response.encoding = "latin-1"286    assert response.text == "Latin 1: ÿ"287    assert response.encoding == "latin-1"288289290def test_response_force_encoding():291    response = httpx.Response(292        200,293        content="Snowman: ☃".encode("utf-8"),294    )295    response.encoding = "iso-8859-1"296    assert response.status_code == 200297    assert response.reason_phrase == "OK"298    assert response.text == "Snowman: â\x98\x83"299    assert response.encoding == "iso-8859-1"300301302def test_read():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 = response.read()314315    assert content == b"Hello, world!"316    assert response.content == b"Hello, world!"317    assert response.is_closed318319320def test_empty_read():321    response = httpx.Response(200)322323    assert response.status_code == 200324    assert response.text == ""325    assert response.encoding is None326    assert response.is_closed327328    content = response.read()329330    assert content == b""331    assert response.content == b""332    assert response.is_closed333334335@pytest.mark.asyncio336async def test_aread():337    response = httpx.Response(338        200,339        content=b"Hello, world!",340    )341342    assert response.status_code == 200343    assert response.text == "Hello, world!"344    assert response.encoding is None345    assert response.is_closed346347    content = await response.aread()348349    assert content == b"Hello, world!"350    assert response.content == b"Hello, world!"351    assert response.is_closed352353354@pytest.mark.asyncio355async def test_empty_aread():356    response = httpx.Response(200)357358    assert response.status_code == 200359    assert response.text == ""360    assert response.encoding is None361    assert response.is_closed362363    content = await response.aread()364365    assert content == b""366    assert response.content == b""367    assert response.is_closed368369370def test_iter_raw():371    response = httpx.Response(372        200,373        content=streaming_body(),374    )375376    raw = b""377    for part in response.iter_raw():378        raw += part379    assert raw == b"Hello, world!"380381382def test_iter_raw_with_chunksize():383    response = httpx.Response(200, content=streaming_body())384385    parts = [part for part in response.iter_raw(chunk_size=5)]386    assert parts == [b"Hello", b", wor", b"ld!"]387388    response = httpx.Response(200, content=streaming_body())389390    parts = [part for part in response.iter_raw(chunk_size=13)]391    assert parts == [b"Hello, world!"]392393    response = httpx.Response(200, content=streaming_body())394395    parts = [part for part in response.iter_raw(chunk_size=20)]396    assert parts == [b"Hello, world!"]397398399def test_iter_raw_on_iterable():400    response = httpx.Response(401        200,402        content=StreamingBody(),403    )404405    raw = b""406    for part in response.iter_raw():407        raw += part408    assert raw == b"Hello, world!"409410411def test_iter_raw_on_async():412    response = httpx.Response(413        200,414        content=async_streaming_body(),415    )416417    with pytest.raises(RuntimeError):418        [part for part in response.iter_raw()]419420421def test_close_on_async():422    response = httpx.Response(423        200,424        content=async_streaming_body(),425    )426427    with pytest.raises(RuntimeError):428        response.close()429430431def test_iter_raw_increments_updates_counter():432    response = httpx.Response(200, content=streaming_body())433434    num_downloaded = response.num_bytes_downloaded435    for part in response.iter_raw():436        assert len(part) == (response.num_bytes_downloaded - num_downloaded)437        num_downloaded = response.num_bytes_downloaded438439440@pytest.mark.asyncio441async def test_aiter_raw():442    response = httpx.Response(200, content=async_streaming_body())443444    raw = b""445    async for part in response.aiter_raw():446        raw += part447    assert raw == b"Hello, world!"448449450@pytest.mark.asyncio451async def test_aiter_raw_with_chunksize():452    response = httpx.Response(200, content=async_streaming_body())453454    parts = [part async for part in response.aiter_raw(chunk_size=5)]455    assert parts == [b"Hello", b", wor", b"ld!"]456457    response = httpx.Response(200, content=async_streaming_body())458459    parts = [part async for part in response.aiter_raw(chunk_size=13)]460    assert parts == [b"Hello, world!"]461462    response = httpx.Response(200, content=async_streaming_body())463464    parts = [part async for part in response.aiter_raw(chunk_size=20)]465    assert parts == [b"Hello, world!"]466467468@pytest.mark.asyncio469async def test_aiter_raw_on_sync():470    response = httpx.Response(471        200,472        content=streaming_body(),473    )474475    with pytest.raises(RuntimeError):476        [part async for part in response.aiter_raw()]477478479@pytest.mark.asyncio480async def test_aclose_on_sync():481    response = httpx.Response(482        200,483        content=streaming_body(),484    )485486    with pytest.raises(RuntimeError):487        await response.aclose()488489490@pytest.mark.asyncio491async def test_aiter_raw_increments_updates_counter():492    response = httpx.Response(200, content=async_streaming_body())493494    num_downloaded = response.num_bytes_downloaded495    async for part in response.aiter_raw():496        assert len(part) == (response.num_bytes_downloaded - num_downloaded)497        num_downloaded = response.num_bytes_downloaded498499500def test_iter_bytes():501    response = httpx.Response(200, content=b"Hello, world!")502503    content = b""504    for part in response.iter_bytes():505        content += part506    assert content == b"Hello, world!"507508509def test_iter_bytes_with_chunk_size():510    response = httpx.Response(200, content=streaming_body())511    parts = [part for part in response.iter_bytes(chunk_size=5)]512    assert parts == [b"Hello", b", wor", b"ld!"]513514    response = httpx.Response(200, content=streaming_body())515    parts = [part for part in response.iter_bytes(chunk_size=13)]516    assert parts == [b"Hello, world!"]517518    response = httpx.Response(200, content=streaming_body())519    parts = [part for part in response.iter_bytes(chunk_size=20)]520    assert parts == [b"Hello, world!"]521522523def test_iter_bytes_with_empty_response():524    response = httpx.Response(200, content=b"")525    parts = [part for part in response.iter_bytes()]526    assert parts == []527528529@pytest.mark.asyncio530async def test_aiter_bytes():531    response = httpx.Response(532        200,533        content=b"Hello, world!",534    )535536    content = b""537    async for part in response.aiter_bytes():538        content += part539    assert content == b"Hello, world!"540541542@pytest.mark.asyncio543async def test_aiter_bytes_with_chunk_size():544    response = httpx.Response(200, content=async_streaming_body())545    parts = [part async for part in response.aiter_bytes(chunk_size=5)]546    assert parts == [b"Hello", b", wor", b"ld!"]547548    response = httpx.Response(200, content=async_streaming_body())549    parts = [part async for part in response.aiter_bytes(chunk_size=13)]550    assert parts == [b"Hello, world!"]551552    response = httpx.Response(200, content=async_streaming_body())553    parts = [part async for part in response.aiter_bytes(chunk_size=20)]554    assert parts == [b"Hello, world!"]555556557def test_iter_text():558    response = httpx.Response(559        200,560        content=b"Hello, world!",561    )562563    content = ""564    for part in response.iter_text():565        content += part566    assert content == "Hello, world!"567568569def test_iter_text_with_chunk_size():570    response = httpx.Response(200, content=b"Hello, world!")571    parts = [part for part in response.iter_text(chunk_size=5)]572    assert parts == ["Hello", ", wor", "ld!"]573574    response = httpx.Response(200, content=b"Hello, world!")575    parts = [part for part in response.iter_text(chunk_size=13)]576    assert parts == ["Hello, world!"]577578    response = httpx.Response(200, content=b"Hello, world!")579    parts = [part for part in response.iter_text(chunk_size=20)]580    assert parts == ["Hello, world!"]581582583@pytest.mark.asyncio584async def test_aiter_text():585    response = httpx.Response(586        200,587        content=b"Hello, world!",588    )589590    content = ""591    async for part in response.aiter_text():592        content += part593    assert content == "Hello, world!"594595596@pytest.mark.asyncio597async def test_aiter_text_with_chunk_size():598    response = httpx.Response(200, content=b"Hello, world!")599    parts = [part async for part in response.aiter_text(chunk_size=5)]600    assert parts == ["Hello", ", wor", "ld!"]601602    response = httpx.Response(200, content=b"Hello, world!")603    parts = [part async for part in response.aiter_text(chunk_size=13)]604    assert parts == ["Hello, world!"]605606    response = httpx.Response(200, content=b"Hello, world!")607    parts = [part async for part in response.aiter_text(chunk_size=20)]608    assert parts == ["Hello, world!"]609610611def test_iter_lines():612    response = httpx.Response(613        200,614        content=b"Hello,\nworld!",615    )616    content = [line for line in response.iter_lines()]617    assert content == ["Hello,\n", "world!"]618619620@pytest.mark.asyncio621async def test_aiter_lines():622    response = httpx.Response(623        200,624        content=b"Hello,\nworld!",625    )626627    content = []628    async for line in response.aiter_lines():629        content.append(line)630    assert content == ["Hello,\n", "world!"]631632633def test_sync_streaming_response():634    response = httpx.Response(635        200,636        content=streaming_body(),637    )638639    assert response.status_code == 200640    assert not response.is_closed641642    content = response.read()643644    assert content == b"Hello, world!"645    assert response.content == b"Hello, world!"646    assert response.is_closed647648649@pytest.mark.asyncio650async def test_async_streaming_response():651    response = httpx.Response(652        200,653        content=async_streaming_body(),654    )655656    assert response.status_code == 200657    assert not response.is_closed658659    content = await response.aread()660661    assert content == b"Hello, world!"662    assert response.content == b"Hello, world!"663    assert response.is_closed664665666def test_cannot_read_after_stream_consumed():667    response = httpx.Response(668        200,669        content=streaming_body(),670    )671672    content = b""673    for part in response.iter_bytes():674        content += part675676    with pytest.raises(httpx.StreamConsumed):677        response.read()678679680@pytest.mark.asyncio681async def test_cannot_aread_after_stream_consumed():682    response = httpx.Response(683        200,684        content=async_streaming_body(),685    )686687    content = b""688    async for part in response.aiter_bytes():689        content += part690691    with pytest.raises(httpx.StreamConsumed):692        await response.aread()693694695def test_cannot_read_after_response_closed():696    response = httpx.Response(697        200,698        content=streaming_body(),699    )700701    response.close()702    with pytest.raises(httpx.StreamClosed):703        response.read()704705706@pytest.mark.asyncio707async def test_cannot_aread_after_response_closed():708    response = httpx.Response(709        200,710        content=async_streaming_body(),711    )712713    await response.aclose()714    with pytest.raises(httpx.StreamClosed):715        await response.aread()716717718@pytest.mark.asyncio719async def test_elapsed_not_available_until_closed():720    response = httpx.Response(721        200,722        content=async_streaming_body(),723    )724725    with pytest.raises(RuntimeError):726        response.elapsed727728729def test_unknown_status_code():730    response = httpx.Response(731        600,732    )733    assert response.status_code == 600734    assert response.reason_phrase == ""735    assert response.text == ""736737738def test_json_with_specified_encoding():739    data = {"greeting": "hello", "recipient": "world"}740    content = json.dumps(data).encode("utf-16")741    headers = {"Content-Type": "application/json, charset=utf-16"}742    response = httpx.Response(743        200,744        content=content,745        headers=headers,746    )747    assert response.json() == data748749750def test_json_with_options():751    data = {"greeting": "hello", "recipient": "world", "amount": 1}752    content = json.dumps(data).encode("utf-16")753    headers = {"Content-Type": "application/json, charset=utf-16"}754    response = httpx.Response(755        200,756        content=content,757        headers=headers,758    )759    assert response.json(parse_int=str)["amount"] == "1"760761762@pytest.mark.parametrize(763    "encoding",764    [765        "utf-8",766        "utf-8-sig",767        "utf-16",768        "utf-16-be",769        "utf-16-le",770        "utf-32",771        "utf-32-be",772        "utf-32-le",773    ],774)775def test_json_without_specified_charset(encoding):776    data = {"greeting": "hello", "recipient": "world"}777    content = json.dumps(data).encode(encoding)778    headers = {"Content-Type": "application/json"}779    response = httpx.Response(780        200,781        content=content,782        headers=headers,783    )784    assert response.json() == data785786787@pytest.mark.parametrize(788    "encoding",789    [790        "utf-8",791        "utf-8-sig",792        "utf-16",793        "utf-16-be",794        "utf-16-le",795        "utf-32",796        "utf-32-be",797        "utf-32-le",798    ],799)800def test_json_with_specified_charset(encoding):801    data = {"greeting": "hello", "recipient": "world"}802    content = json.dumps(data).encode(encoding)803    headers = {"Content-Type": f"application/json; charset={encoding}"}804    response = httpx.Response(805        200,806        content=content,807        headers=headers,808    )809    assert response.json() == data810811812@pytest.mark.parametrize(813    "headers, expected",814    [815        (816            {"Link": "<https://example.com>; rel='preload'"},817            {"preload": {"rel": "preload", "url": "https://example.com"}},818        ),819        (820            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},821            {822                "hub": {"url": "/hub", "rel": "hub"},823                "self": {"url": "/resource", "rel": "self"},824            },825        ),826    ],827)828def test_link_headers(headers, expected):829    response = httpx.Response(830        200,831        content=None,832        headers=headers,833    )834    assert response.links == expected835836837@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))838def test_decode_error_with_request(header_value):839    headers = [(b"Content-Encoding", header_value)]840    body = b"test 123"841    compressed_body = brotli.compress(body)[3:]842    with pytest.raises(httpx.DecodingError):843        httpx.Response(844            200,845            headers=headers,846            content=compressed_body,847        )848849    with pytest.raises(httpx.DecodingError):850        httpx.Response(851            200,852            headers=headers,853            content=compressed_body,854            request=httpx.Request("GET", "https://www.example.org/"),855        )856857858@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))859def test_value_error_without_request(header_value):860    headers = [(b"Content-Encoding", header_value)]861    body = b"test 123"862    compressed_body = brotli.compress(body)[3:]863    with pytest.raises(httpx.DecodingError):864        httpx.Response(200, headers=headers, content=compressed_body)865866867def test_response_with_unset_request():868    response = httpx.Response(200, content=b"Hello, world!")869870    assert response.status_code == 200871    assert response.reason_phrase == "OK"872    assert response.text == "Hello, world!"873    assert not response.is_error874875876def test_set_request_after_init():877    response = httpx.Response(200, content=b"Hello, world!")878879    response.request = httpx.Request("GET", "https://www.example.org")880881    assert response.request.method == "GET"882    assert response.request.url == "https://www.example.org"883884885def test_cannot_access_unset_request():886    response = httpx.Response(200, content=b"Hello, world!")887888    with pytest.raises(RuntimeError):889        response.request890891892def test_generator_with_transfer_encoding_header():893    def content():894        yield b"test 123"  # pragma: nocover895896    response = httpx.Response(200, content=content())897    assert response.headers == {"Transfer-Encoding": "chunked"}898899900def test_generator_with_content_length_header():901    def content():902        yield b"test 123"  # pragma: nocover903904    headers = {"Content-Length": "8"}905    response = httpx.Response(200, content=content(), headers=headers)906    assert response.headers == {"Content-Length": "8"}907908909def test_response_picklable():910    response = httpx.Response(911        200,912        content=b"Hello, world!",913        request=httpx.Request("GET", "https://example.org"),914    )915    pickle_response = pickle.loads(pickle.dumps(response))916    assert pickle_response.is_closed is True917    assert pickle_response.is_stream_consumed is True918    assert pickle_response.next_request is None919    assert pickle_response.stream is not None920    assert pickle_response.content == b"Hello, world!"921    assert pickle_response.status_code == 200922    assert pickle_response.request.url == response.request.url923    assert pickle_response.extensions == {}924    assert pickle_response.history == []925926927@pytest.mark.asyncio928async def test_response_async_streaming_picklable():929    response = httpx.Response(200, content=async_streaming_body())930    pickle_response = pickle.loads(pickle.dumps(response))931    with pytest.raises(httpx.ResponseNotRead):932        pickle_response.content933    with pytest.raises(httpx.StreamClosed):934        await pickle_response.aread()935    assert pickle_response.is_stream_consumed is False936    assert pickle_response.num_bytes_downloaded == 0937    assert pickle_response.headers == {"Transfer-Encoding": "chunked"}938939    response = httpx.Response(200, content=async_streaming_body())940    await response.aread()941    pickle_response = pickle.loads(pickle.dumps(response))942    assert pickle_response.is_stream_consumed is True943    assert pickle_response.content == b"Hello, world!"944    assert pickle_response.num_bytes_downloaded == 13