Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

1,037 lines · 29.4 KiB · Python

Last changed by

Enabling `ruff` C416 (#3001)James Brazabefore adoption2318fd8

History of this file

Take it

1import json2import pickle3import typing45import chardet6import pytest78import httpx91011class StreamingBody:12    def __iter__(self):13        yield b"Hello, "14        yield b"world!"151617def streaming_body() -> typing.Iterator[bytes]:18    yield b"Hello, "19    yield b"world!"202122async def async_streaming_body() -> typing.AsyncIterator[bytes]:23    yield b"Hello, "24    yield b"world!"252627def autodetect(content):28    return chardet.detect(content).get("encoding")293031def test_response():32    response = httpx.Response(33        200,34        content=b"Hello, world!",35        request=httpx.Request("GET", "https://example.org"),36    )3738    assert response.status_code == 20039    assert response.reason_phrase == "OK"40    assert response.text == "Hello, world!"41    assert response.request.method == "GET"42    assert response.request.url == "https://example.org"43    assert not response.is_error444546def test_response_content():47    response = httpx.Response(200, content="Hello, world!")4849    assert response.status_code == 20050    assert response.reason_phrase == "OK"51    assert response.text == "Hello, world!"52    assert response.headers == {"Content-Length": "13"}535455def test_response_text():56    response = httpx.Response(200, text="Hello, world!")5758    assert response.status_code == 20059    assert response.reason_phrase == "OK"60    assert response.text == "Hello, world!"61    assert response.headers == {62        "Content-Length": "13",63        "Content-Type": "text/plain; charset=utf-8",64    }656667def test_response_html():68    response = httpx.Response(200, html="<html><body>Hello, world!</html></body>")6970    assert response.status_code == 20071    assert response.reason_phrase == "OK"72    assert response.text == "<html><body>Hello, world!</html></body>"73    assert response.headers == {74        "Content-Length": "39",75        "Content-Type": "text/html; charset=utf-8",76    }777879def test_response_json():80    response = httpx.Response(200, json={"hello": "world"})8182    assert response.status_code == 20083    assert response.reason_phrase == "OK"84    assert response.json() == {"hello": "world"}85    assert response.headers == {86        "Content-Length": "18",87        "Content-Type": "application/json",88    }899091def test_raise_for_status():92    request = httpx.Request("GET", "https://example.org")9394    # 2xx status codes are not an error.95    response = httpx.Response(200, request=request)96    response.raise_for_status()9798    # 1xx status codes are informational responses.99    response = httpx.Response(101, request=request)100    assert response.is_informational101    with pytest.raises(httpx.HTTPStatusError) as exc_info:102        response.raise_for_status()103    assert str(exc_info.value) == (104        "Informational response '101 Switching Protocols' for url 'https://example.org'\n"105        "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/101"106    )107108    # 3xx status codes are redirections.109    headers = {"location": "https://other.org"}110    response = httpx.Response(303, headers=headers, request=request)111    assert response.is_redirect112    with pytest.raises(httpx.HTTPStatusError) as exc_info:113        response.raise_for_status()114    assert str(exc_info.value) == (115        "Redirect response '303 See Other' for url 'https://example.org'\n"116        "Redirect location: 'https://other.org'\n"117        "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303"118    )119120    # 4xx status codes are a client error.121    response = httpx.Response(403, request=request)122    assert response.is_client_error123    assert response.is_error124    with pytest.raises(httpx.HTTPStatusError) as exc_info:125        response.raise_for_status()126    assert str(exc_info.value) == (127        "Client error '403 Forbidden' for url 'https://example.org'\n"128        "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403"129    )130131    # 5xx status codes are a server error.132    response = httpx.Response(500, request=request)133    assert response.is_server_error134    assert response.is_error135    with pytest.raises(httpx.HTTPStatusError) as exc_info:136        response.raise_for_status()137    assert str(exc_info.value) == (138        "Server error '500 Internal Server Error' for url 'https://example.org'\n"139        "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500"140    )141142    # Calling .raise_for_status without setting a request instance is143    # not valid. Should raise a runtime error.144    response = httpx.Response(200)145    with pytest.raises(RuntimeError):146        response.raise_for_status()147148149def test_response_repr():150    response = httpx.Response(151        200,152        content=b"Hello, world!",153    )154    assert repr(response) == "<Response [200 OK]>"155156157def test_response_content_type_encoding():158    """159    Use the charset encoding in the Content-Type header if possible.160    """161    headers = {"Content-Type": "text-plain; charset=latin-1"}162    content = "Latin 1: ÿ".encode("latin-1")163    response = httpx.Response(164        200,165        content=content,166        headers=headers,167    )168    assert response.text == "Latin 1: ÿ"169    assert response.encoding == "latin-1"170171172def test_response_default_to_utf8_encoding():173    """174    Default to utf-8 encoding if there is no Content-Type header.175    """176    content = "おはようございます。".encode("utf-8")177    response = httpx.Response(178        200,179        content=content,180    )181    assert response.text == "おはようございます。"182    assert response.encoding == "utf-8"183184185def test_response_fallback_to_utf8_encoding():186    """187    Fallback to utf-8 if we get an invalid charset in the Content-Type header.188    """189    headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}190    content = "おはようございます。".encode("utf-8")191    response = httpx.Response(192        200,193        content=content,194        headers=headers,195    )196    assert response.text == "おはようございます。"197    assert response.encoding == "utf-8"198199200def test_response_no_charset_with_ascii_content():201    """202    A response with ascii encoded content should decode correctly,203    even with no charset specified.204    """205    content = b"Hello, world!"206    headers = {"Content-Type": "text/plain"}207    response = httpx.Response(208        200,209        content=content,210        headers=headers,211    )212    assert response.status_code == 200213    assert response.encoding == "utf-8"214    assert response.text == "Hello, world!"215216217def test_response_no_charset_with_utf8_content():218    """219    A response with UTF-8 encoded content should decode correctly,220    even with no charset specified.221    """222    content = "Unicode Snowman: ☃".encode("utf-8")223    headers = {"Content-Type": "text/plain"}224    response = httpx.Response(225        200,226        content=content,227        headers=headers,228    )229    assert response.text == "Unicode Snowman: ☃"230    assert response.encoding == "utf-8"231232233def test_response_no_charset_with_iso_8859_1_content():234    """235    A response with ISO 8859-1 encoded content should decode correctly,236    even with no charset specified, if autodetect is enabled.237    """238    content = "Accented: Österreich abcdefghijklmnopqrstuzwxyz".encode("iso-8859-1")239    headers = {"Content-Type": "text/plain"}240    response = httpx.Response(241        200, content=content, headers=headers, default_encoding=autodetect242    )243    assert response.text == "Accented: Österreich abcdefghijklmnopqrstuzwxyz"244    assert response.charset_encoding is None245246247def test_response_no_charset_with_cp_1252_content():248    """249    A response with Windows 1252 encoded content should decode correctly,250    even with no charset specified, if autodetect is enabled.251    """252    content = "Euro Currency: € abcdefghijklmnopqrstuzwxyz".encode("cp1252")253    headers = {"Content-Type": "text/plain"}254    response = httpx.Response(255        200, content=content, headers=headers, default_encoding=autodetect256    )257    assert response.text == "Euro Currency: € abcdefghijklmnopqrstuzwxyz"258    assert response.charset_encoding is None259260261def test_response_non_text_encoding():262    """263    Default to attempting utf-8 encoding for non-text content-type headers.264    """265    headers = {"Content-Type": "image/png"}266    response = httpx.Response(267        200,268        content=b"xyz",269        headers=headers,270    )271    assert response.text == "xyz"272    assert response.encoding == "utf-8"273274275def test_response_set_explicit_encoding():276    headers = {277        "Content-Type": "text-plain; charset=utf-8"278    }  # Deliberately incorrect charset279    response = httpx.Response(280        200,281        content="Latin 1: ÿ".encode("latin-1"),282        headers=headers,283    )284    response.encoding = "latin-1"285    assert response.text == "Latin 1: ÿ"286    assert response.encoding == "latin-1"287288289def test_response_force_encoding():290    response = httpx.Response(291        200,292        content="Snowman: ☃".encode("utf-8"),293    )294    response.encoding = "iso-8859-1"295    assert response.status_code == 200296    assert response.reason_phrase == "OK"297    assert response.text == "Snowman: â\x98\x83"298    assert response.encoding == "iso-8859-1"299300301def test_response_force_encoding_after_text_accessed():302    response = httpx.Response(303        200,304        content=b"Hello, world!",305    )306    assert response.status_code == 200307    assert response.reason_phrase == "OK"308    assert response.text == "Hello, world!"309    assert response.encoding == "utf-8"310311    with pytest.raises(ValueError):312        response.encoding = "UTF8"313314    with pytest.raises(ValueError):315        response.encoding = "iso-8859-1"316317318def test_read():319    response = httpx.Response(320        200,321        content=b"Hello, world!",322    )323324    assert response.status_code == 200325    assert response.text == "Hello, world!"326    assert response.encoding == "utf-8"327    assert response.is_closed328329    content = response.read()330331    assert content == b"Hello, world!"332    assert response.content == b"Hello, world!"333    assert response.is_closed334335336def test_empty_read():337    response = httpx.Response(200)338339    assert response.status_code == 200340    assert response.text == ""341    assert response.encoding == "utf-8"342    assert response.is_closed343344    content = response.read()345346    assert content == b""347    assert response.content == b""348    assert response.is_closed349350351@pytest.mark.anyio352async def test_aread():353    response = httpx.Response(354        200,355        content=b"Hello, world!",356    )357358    assert response.status_code == 200359    assert response.text == "Hello, world!"360    assert response.encoding == "utf-8"361    assert response.is_closed362363    content = await response.aread()364365    assert content == b"Hello, world!"366    assert response.content == b"Hello, world!"367    assert response.is_closed368369370@pytest.mark.anyio371async def test_empty_aread():372    response = httpx.Response(200)373374    assert response.status_code == 200375    assert response.text == ""376    assert response.encoding == "utf-8"377    assert response.is_closed378379    content = await response.aread()380381    assert content == b""382    assert response.content == b""383    assert response.is_closed384385386def test_iter_raw():387    response = httpx.Response(388        200,389        content=streaming_body(),390    )391392    raw = b""393    for part in response.iter_raw():394        raw += part395    assert raw == b"Hello, world!"396397398def test_iter_raw_with_chunksize():399    response = httpx.Response(200, content=streaming_body())400    parts = list(response.iter_raw(chunk_size=5))401    assert parts == [b"Hello", b", wor", b"ld!"]402403    response = httpx.Response(200, content=streaming_body())404    parts = list(response.iter_raw(chunk_size=7))405    assert parts == [b"Hello, ", b"world!"]406407    response = httpx.Response(200, content=streaming_body())408    parts = list(response.iter_raw(chunk_size=13))409    assert parts == [b"Hello, world!"]410411    response = httpx.Response(200, content=streaming_body())412    parts = list(response.iter_raw(chunk_size=20))413    assert parts == [b"Hello, world!"]414415416def test_iter_raw_doesnt_return_empty_chunks():417    def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:418        yield b"Hello, "419        yield b""420        yield b"world!"421        yield b""422423    response = httpx.Response(200, content=streaming_body_with_empty_chunks())424425    parts = list(response.iter_raw())426    assert parts == [b"Hello, ", b"world!"]427428429def test_iter_raw_on_iterable():430    response = httpx.Response(431        200,432        content=StreamingBody(),433    )434435    raw = b""436    for part in response.iter_raw():437        raw += part438    assert raw == b"Hello, world!"439440441def test_iter_raw_on_async():442    response = httpx.Response(443        200,444        content=async_streaming_body(),445    )446447    with pytest.raises(RuntimeError):448        list(response.iter_raw())449450451def test_close_on_async():452    response = httpx.Response(453        200,454        content=async_streaming_body(),455    )456457    with pytest.raises(RuntimeError):458        response.close()459460461def test_iter_raw_increments_updates_counter():462    response = httpx.Response(200, content=streaming_body())463464    num_downloaded = response.num_bytes_downloaded465    for part in response.iter_raw():466        assert len(part) == (response.num_bytes_downloaded - num_downloaded)467        num_downloaded = response.num_bytes_downloaded468469470@pytest.mark.anyio471async def test_aiter_raw():472    response = httpx.Response(200, content=async_streaming_body())473474    raw = b""475    async for part in response.aiter_raw():476        raw += part477    assert raw == b"Hello, world!"478479480@pytest.mark.anyio481async def test_aiter_raw_with_chunksize():482    response = httpx.Response(200, content=async_streaming_body())483484    parts = [part async for part in response.aiter_raw(chunk_size=5)]485    assert parts == [b"Hello", b", wor", b"ld!"]486487    response = httpx.Response(200, content=async_streaming_body())488489    parts = [part async for part in response.aiter_raw(chunk_size=13)]490    assert parts == [b"Hello, world!"]491492    response = httpx.Response(200, content=async_streaming_body())493494    parts = [part async for part in response.aiter_raw(chunk_size=20)]495    assert parts == [b"Hello, world!"]496497498@pytest.mark.anyio499async def test_aiter_raw_on_sync():500    response = httpx.Response(501        200,502        content=streaming_body(),503    )504505    with pytest.raises(RuntimeError):506        [part async for part in response.aiter_raw()]507508509@pytest.mark.anyio510async def test_aclose_on_sync():511    response = httpx.Response(512        200,513        content=streaming_body(),514    )515516    with pytest.raises(RuntimeError):517        await response.aclose()518519520@pytest.mark.anyio521async def test_aiter_raw_increments_updates_counter():522    response = httpx.Response(200, content=async_streaming_body())523524    num_downloaded = response.num_bytes_downloaded525    async for part in response.aiter_raw():526        assert len(part) == (response.num_bytes_downloaded - num_downloaded)527        num_downloaded = response.num_bytes_downloaded528529530def test_iter_bytes():531    response = httpx.Response(200, content=b"Hello, world!")532533    content = b""534    for part in response.iter_bytes():535        content += part536    assert content == b"Hello, world!"537538539def test_iter_bytes_with_chunk_size():540    response = httpx.Response(200, content=streaming_body())541    parts = list(response.iter_bytes(chunk_size=5))542    assert parts == [b"Hello", b", wor", b"ld!"]543544    response = httpx.Response(200, content=streaming_body())545    parts = list(response.iter_bytes(chunk_size=13))546    assert parts == [b"Hello, world!"]547548    response = httpx.Response(200, content=streaming_body())549    parts = list(response.iter_bytes(chunk_size=20))550    assert parts == [b"Hello, world!"]551552553def test_iter_bytes_with_empty_response():554    response = httpx.Response(200, content=b"")555    parts = list(response.iter_bytes())556    assert parts == []557558559def test_iter_bytes_doesnt_return_empty_chunks():560    def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:561        yield b"Hello, "562        yield b""563        yield b"world!"564        yield b""565566    response = httpx.Response(200, content=streaming_body_with_empty_chunks())567568    parts = list(response.iter_bytes())569    assert parts == [b"Hello, ", b"world!"]570571572@pytest.mark.anyio573async def test_aiter_bytes():574    response = httpx.Response(575        200,576        content=b"Hello, world!",577    )578579    content = b""580    async for part in response.aiter_bytes():581        content += part582    assert content == b"Hello, world!"583584585@pytest.mark.anyio586async def test_aiter_bytes_with_chunk_size():587    response = httpx.Response(200, content=async_streaming_body())588    parts = [part async for part in response.aiter_bytes(chunk_size=5)]589    assert parts == [b"Hello", b", wor", b"ld!"]590591    response = httpx.Response(200, content=async_streaming_body())592    parts = [part async for part in response.aiter_bytes(chunk_size=13)]593    assert parts == [b"Hello, world!"]594595    response = httpx.Response(200, content=async_streaming_body())596    parts = [part async for part in response.aiter_bytes(chunk_size=20)]597    assert parts == [b"Hello, world!"]598599600def test_iter_text():601    response = httpx.Response(602        200,603        content=b"Hello, world!",604    )605606    content = ""607    for part in response.iter_text():608        content += part609    assert content == "Hello, world!"610611612def test_iter_text_with_chunk_size():613    response = httpx.Response(200, content=b"Hello, world!")614    parts = list(response.iter_text(chunk_size=5))615    assert parts == ["Hello", ", wor", "ld!"]616617    response = httpx.Response(200, content=b"Hello, world!!")618    parts = list(response.iter_text(chunk_size=7))619    assert parts == ["Hello, ", "world!!"]620621    response = httpx.Response(200, content=b"Hello, world!")622    parts = list(response.iter_text(chunk_size=7))623    assert parts == ["Hello, ", "world!"]624625    response = httpx.Response(200, content=b"Hello, world!")626    parts = list(response.iter_text(chunk_size=13))627    assert parts == ["Hello, world!"]628629    response = httpx.Response(200, content=b"Hello, world!")630    parts = list(response.iter_text(chunk_size=20))631    assert parts == ["Hello, world!"]632633634@pytest.mark.anyio635async def test_aiter_text():636    response = httpx.Response(637        200,638        content=b"Hello, world!",639    )640641    content = ""642    async for part in response.aiter_text():643        content += part644    assert content == "Hello, world!"645646647@pytest.mark.anyio648async def test_aiter_text_with_chunk_size():649    response = httpx.Response(200, content=b"Hello, world!")650    parts = [part async for part in response.aiter_text(chunk_size=5)]651    assert parts == ["Hello", ", wor", "ld!"]652653    response = httpx.Response(200, content=b"Hello, world!")654    parts = [part async for part in response.aiter_text(chunk_size=13)]655    assert parts == ["Hello, world!"]656657    response = httpx.Response(200, content=b"Hello, world!")658    parts = [part async for part in response.aiter_text(chunk_size=20)]659    assert parts == ["Hello, world!"]660661662def test_iter_lines():663    response = httpx.Response(664        200,665        content=b"Hello,\nworld!",666    )667    content = list(response.iter_lines())668    assert content == ["Hello,", "world!"]669670671@pytest.mark.anyio672async def test_aiter_lines():673    response = httpx.Response(674        200,675        content=b"Hello,\nworld!",676    )677678    content = []679    async for line in response.aiter_lines():680        content.append(line)681    assert content == ["Hello,", "world!"]682683684def test_sync_streaming_response():685    response = httpx.Response(686        200,687        content=streaming_body(),688    )689690    assert response.status_code == 200691    assert not response.is_closed692693    content = response.read()694695    assert content == b"Hello, world!"696    assert response.content == b"Hello, world!"697    assert response.is_closed698699700@pytest.mark.anyio701async def test_async_streaming_response():702    response = httpx.Response(703        200,704        content=async_streaming_body(),705    )706707    assert response.status_code == 200708    assert not response.is_closed709710    content = await response.aread()711712    assert content == b"Hello, world!"713    assert response.content == b"Hello, world!"714    assert response.is_closed715716717def test_cannot_read_after_stream_consumed():718    response = httpx.Response(719        200,720        content=streaming_body(),721    )722723    content = b""724    for part in response.iter_bytes():725        content += part726727    with pytest.raises(httpx.StreamConsumed):728        response.read()729730731@pytest.mark.anyio732async def test_cannot_aread_after_stream_consumed():733    response = httpx.Response(734        200,735        content=async_streaming_body(),736    )737738    content = b""739    async for part in response.aiter_bytes():740        content += part741742    with pytest.raises(httpx.StreamConsumed):743        await response.aread()744745746def test_cannot_read_after_response_closed():747    response = httpx.Response(748        200,749        content=streaming_body(),750    )751752    response.close()753    with pytest.raises(httpx.StreamClosed):754        response.read()755756757@pytest.mark.anyio758async def test_cannot_aread_after_response_closed():759    response = httpx.Response(760        200,761        content=async_streaming_body(),762    )763764    await response.aclose()765    with pytest.raises(httpx.StreamClosed):766        await response.aread()767768769@pytest.mark.anyio770async def test_elapsed_not_available_until_closed():771    response = httpx.Response(772        200,773        content=async_streaming_body(),774    )775776    with pytest.raises(RuntimeError):777        response.elapsed  # noqa: B018778779780def test_unknown_status_code():781    response = httpx.Response(782        600,783    )784    assert response.status_code == 600785    assert response.reason_phrase == ""786    assert response.text == ""787788789def test_json_with_specified_encoding():790    data = {"greeting": "hello", "recipient": "world"}791    content = json.dumps(data).encode("utf-16")792    headers = {"Content-Type": "application/json, charset=utf-16"}793    response = httpx.Response(794        200,795        content=content,796        headers=headers,797    )798    assert response.json() == data799800801def test_json_with_options():802    data = {"greeting": "hello", "recipient": "world", "amount": 1}803    content = json.dumps(data).encode("utf-16")804    headers = {"Content-Type": "application/json, charset=utf-16"}805    response = httpx.Response(806        200,807        content=content,808        headers=headers,809    )810    assert response.json(parse_int=str)["amount"] == "1"811812813@pytest.mark.parametrize(814    "encoding",815    [816        "utf-8",817        "utf-8-sig",818        "utf-16",819        "utf-16-be",820        "utf-16-le",821        "utf-32",822        "utf-32-be",823        "utf-32-le",824    ],825)826def test_json_without_specified_charset(encoding):827    data = {"greeting": "hello", "recipient": "world"}828    content = json.dumps(data).encode(encoding)829    headers = {"Content-Type": "application/json"}830    response = httpx.Response(831        200,832        content=content,833        headers=headers,834    )835    assert response.json() == data836837838@pytest.mark.parametrize(839    "encoding",840    [841        "utf-8",842        "utf-8-sig",843        "utf-16",844        "utf-16-be",845        "utf-16-le",846        "utf-32",847        "utf-32-be",848        "utf-32-le",849    ],850)851def test_json_with_specified_charset(encoding):852    data = {"greeting": "hello", "recipient": "world"}853    content = json.dumps(data).encode(encoding)854    headers = {"Content-Type": f"application/json; charset={encoding}"}855    response = httpx.Response(856        200,857        content=content,858        headers=headers,859    )860    assert response.json() == data861862863@pytest.mark.parametrize(864    "headers, expected",865    [866        (867            {"Link": "<https://example.com>; rel='preload'"},868            {"preload": {"rel": "preload", "url": "https://example.com"}},869        ),870        (871            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},872            {873                "hub": {"url": "/hub", "rel": "hub"},874                "self": {"url": "/resource", "rel": "self"},875            },876        ),877    ],878)879def test_link_headers(headers, expected):880    response = httpx.Response(881        200,882        content=None,883        headers=headers,884    )885    assert response.links == expected886887888@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))889def test_decode_error_with_request(header_value):890    headers = [(b"Content-Encoding", header_value)]891    broken_compressed_body = b"xxxxxxxxxxxxxx"892    with pytest.raises(httpx.DecodingError):893        httpx.Response(894            200,895            headers=headers,896            content=broken_compressed_body,897        )898899    with pytest.raises(httpx.DecodingError):900        httpx.Response(901            200,902            headers=headers,903            content=broken_compressed_body,904            request=httpx.Request("GET", "https://www.example.org/"),905        )906907908@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))909def test_value_error_without_request(header_value):910    headers = [(b"Content-Encoding", header_value)]911    broken_compressed_body = b"xxxxxxxxxxxxxx"912    with pytest.raises(httpx.DecodingError):913        httpx.Response(200, headers=headers, content=broken_compressed_body)914915916def test_response_with_unset_request():917    response = httpx.Response(200, content=b"Hello, world!")918919    assert response.status_code == 200920    assert response.reason_phrase == "OK"921    assert response.text == "Hello, world!"922    assert not response.is_error923924925def test_set_request_after_init():926    response = httpx.Response(200, content=b"Hello, world!")927928    response.request = httpx.Request("GET", "https://www.example.org")929930    assert response.request.method == "GET"931    assert response.request.url == "https://www.example.org"932933934def test_cannot_access_unset_request():935    response = httpx.Response(200, content=b"Hello, world!")936937    with pytest.raises(RuntimeError):938        response.request  # noqa: B018939940941def test_generator_with_transfer_encoding_header():942    def content() -> typing.Iterator[bytes]:943        yield b"test 123"  # pragma: no cover944945    response = httpx.Response(200, content=content())946    assert response.headers == {"Transfer-Encoding": "chunked"}947948949def test_generator_with_content_length_header():950    def content() -> typing.Iterator[bytes]:951        yield b"test 123"  # pragma: no cover952953    headers = {"Content-Length": "8"}954    response = httpx.Response(200, content=content(), headers=headers)955    assert response.headers == {"Content-Length": "8"}956957958def test_response_picklable():959    response = httpx.Response(960        200,961        content=b"Hello, world!",962        request=httpx.Request("GET", "https://example.org"),963    )964    pickle_response = pickle.loads(pickle.dumps(response))965    assert pickle_response.is_closed is True966    assert pickle_response.is_stream_consumed is True967    assert pickle_response.next_request is None968    assert pickle_response.stream is not None969    assert pickle_response.content == b"Hello, world!"970    assert pickle_response.status_code == 200971    assert pickle_response.request.url == response.request.url972    assert pickle_response.extensions == {}973    assert pickle_response.history == []974975976@pytest.mark.anyio977async def test_response_async_streaming_picklable():978    response = httpx.Response(200, content=async_streaming_body())979    pickle_response = pickle.loads(pickle.dumps(response))980    with pytest.raises(httpx.ResponseNotRead):981        pickle_response.content  # noqa: B018982    with pytest.raises(httpx.StreamClosed):983        await pickle_response.aread()984    assert pickle_response.is_stream_consumed is False985    assert pickle_response.num_bytes_downloaded == 0986    assert pickle_response.headers == {"Transfer-Encoding": "chunked"}987988    response = httpx.Response(200, content=async_streaming_body())989    await response.aread()990    pickle_response = pickle.loads(pickle.dumps(response))991    assert pickle_response.is_stream_consumed is True992    assert pickle_response.content == b"Hello, world!"993    assert pickle_response.num_bytes_downloaded == 13994995996def test_response_decode_text_using_autodetect():997    # Ensure that a 'default_encoding="autodetect"' on the response allows for998    # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."999    # info is present.1000    #1001    # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.1002    text = (1003        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "1004        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "1005        "l'esprit anglais par son séjour à Londres, c'est incontestablement "1006        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "1007        "plus complète le fond du génie français."1008    )1009    content = text.encode("ISO-8859-1")1010    response = httpx.Response(200, content=content, default_encoding=autodetect)10111012    assert response.status_code == 2001013    assert response.reason_phrase == "OK"1014    assert response.encoding == "ISO-8859-1"1015    assert response.text == text101610171018def test_response_decode_text_using_explicit_encoding():1019    # Ensure that a 'default_encoding="..."' on the response is used for text decoding1020    # when no "Content-Type: text/plain; charset=..."" info is present.1021    #1022    # Here we have some french text encoded with Windows-1252, rather than UTF-8.1023    # https://en.wikipedia.org/wiki/Windows-12521024    text = (1025        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "1026        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "1027        "l'esprit anglais par son séjour à Londres, c'est incontestablement "1028        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "1029        "plus complète le fond du génie français."1030    )1031    content = text.encode("cp1252")1032    response = httpx.Response(200, content=content, default_encoding="cp1252")10331034    assert response.status_code == 2001035    assert response.reason_phrase == "OK"1036    assert response.encoding == "cp1252"1037    assert response.text == text