Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

1,020 lines · 29.1 KiB · Python

Last changed by

Drop private imports from test_decoders.py (#2570)Florimond Mancabefore adoptioncca6206

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://httpstatuses.com/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://httpstatuses.com/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://httpstatuses.com/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://httpstatuses.com/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_read():302    response = httpx.Response(303        200,304        content=b"Hello, world!",305    )306307    assert response.status_code == 200308    assert response.text == "Hello, world!"309    assert response.encoding == "utf-8"310    assert response.is_closed311312    content = response.read()313314    assert content == b"Hello, world!"315    assert response.content == b"Hello, world!"316    assert response.is_closed317318319def test_empty_read():320    response = httpx.Response(200)321322    assert response.status_code == 200323    assert response.text == ""324    assert response.encoding == "utf-8"325    assert response.is_closed326327    content = response.read()328329    assert content == b""330    assert response.content == b""331    assert response.is_closed332333334@pytest.mark.anyio335async def test_aread():336    response = httpx.Response(337        200,338        content=b"Hello, world!",339    )340341    assert response.status_code == 200342    assert response.text == "Hello, world!"343    assert response.encoding == "utf-8"344    assert response.is_closed345346    content = await response.aread()347348    assert content == b"Hello, world!"349    assert response.content == b"Hello, world!"350    assert response.is_closed351352353@pytest.mark.anyio354async def test_empty_aread():355    response = httpx.Response(200)356357    assert response.status_code == 200358    assert response.text == ""359    assert response.encoding == "utf-8"360    assert response.is_closed361362    content = await response.aread()363364    assert content == b""365    assert response.content == b""366    assert response.is_closed367368369def test_iter_raw():370    response = httpx.Response(371        200,372        content=streaming_body(),373    )374375    raw = b""376    for part in response.iter_raw():377        raw += part378    assert raw == b"Hello, world!"379380381def test_iter_raw_with_chunksize():382    response = httpx.Response(200, content=streaming_body())383    parts = [part for part in response.iter_raw(chunk_size=5)]384    assert parts == [b"Hello", b", wor", b"ld!"]385386    response = httpx.Response(200, content=streaming_body())387    parts = [part for part in response.iter_raw(chunk_size=7)]388    assert parts == [b"Hello, ", b"world!"]389390    response = httpx.Response(200, content=streaming_body())391    parts = [part for part in response.iter_raw(chunk_size=13)]392    assert parts == [b"Hello, world!"]393394    response = httpx.Response(200, content=streaming_body())395    parts = [part for part in response.iter_raw(chunk_size=20)]396    assert parts == [b"Hello, world!"]397398399def test_iter_raw_doesnt_return_empty_chunks():400    def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:401        yield b"Hello, "402        yield b""403        yield b"world!"404        yield b""405406    response = httpx.Response(200, content=streaming_body_with_empty_chunks())407408    parts = [part for part in response.iter_raw()]409    assert parts == [b"Hello, ", b"world!"]410411412def test_iter_raw_on_iterable():413    response = httpx.Response(414        200,415        content=StreamingBody(),416    )417418    raw = b""419    for part in response.iter_raw():420        raw += part421    assert raw == b"Hello, world!"422423424def test_iter_raw_on_async():425    response = httpx.Response(426        200,427        content=async_streaming_body(),428    )429430    with pytest.raises(RuntimeError):431        [part for part in response.iter_raw()]432433434def test_close_on_async():435    response = httpx.Response(436        200,437        content=async_streaming_body(),438    )439440    with pytest.raises(RuntimeError):441        response.close()442443444def test_iter_raw_increments_updates_counter():445    response = httpx.Response(200, content=streaming_body())446447    num_downloaded = response.num_bytes_downloaded448    for part in response.iter_raw():449        assert len(part) == (response.num_bytes_downloaded - num_downloaded)450        num_downloaded = response.num_bytes_downloaded451452453@pytest.mark.anyio454async def test_aiter_raw():455    response = httpx.Response(200, content=async_streaming_body())456457    raw = b""458    async for part in response.aiter_raw():459        raw += part460    assert raw == b"Hello, world!"461462463@pytest.mark.anyio464async def test_aiter_raw_with_chunksize():465    response = httpx.Response(200, content=async_streaming_body())466467    parts = [part async for part in response.aiter_raw(chunk_size=5)]468    assert parts == [b"Hello", b", wor", b"ld!"]469470    response = httpx.Response(200, content=async_streaming_body())471472    parts = [part async for part in response.aiter_raw(chunk_size=13)]473    assert parts == [b"Hello, world!"]474475    response = httpx.Response(200, content=async_streaming_body())476477    parts = [part async for part in response.aiter_raw(chunk_size=20)]478    assert parts == [b"Hello, world!"]479480481@pytest.mark.anyio482async def test_aiter_raw_on_sync():483    response = httpx.Response(484        200,485        content=streaming_body(),486    )487488    with pytest.raises(RuntimeError):489        [part async for part in response.aiter_raw()]490491492@pytest.mark.anyio493async def test_aclose_on_sync():494    response = httpx.Response(495        200,496        content=streaming_body(),497    )498499    with pytest.raises(RuntimeError):500        await response.aclose()501502503@pytest.mark.anyio504async def test_aiter_raw_increments_updates_counter():505    response = httpx.Response(200, content=async_streaming_body())506507    num_downloaded = response.num_bytes_downloaded508    async for part in response.aiter_raw():509        assert len(part) == (response.num_bytes_downloaded - num_downloaded)510        num_downloaded = response.num_bytes_downloaded511512513def test_iter_bytes():514    response = httpx.Response(200, content=b"Hello, world!")515516    content = b""517    for part in response.iter_bytes():518        content += part519    assert content == b"Hello, world!"520521522def test_iter_bytes_with_chunk_size():523    response = httpx.Response(200, content=streaming_body())524    parts = [part for part in response.iter_bytes(chunk_size=5)]525    assert parts == [b"Hello", b", wor", b"ld!"]526527    response = httpx.Response(200, content=streaming_body())528    parts = [part for part in response.iter_bytes(chunk_size=13)]529    assert parts == [b"Hello, world!"]530531    response = httpx.Response(200, content=streaming_body())532    parts = [part for part in response.iter_bytes(chunk_size=20)]533    assert parts == [b"Hello, world!"]534535536def test_iter_bytes_with_empty_response():537    response = httpx.Response(200, content=b"")538    parts = [part for part in response.iter_bytes()]539    assert parts == []540541542def test_iter_bytes_doesnt_return_empty_chunks():543    def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:544        yield b"Hello, "545        yield b""546        yield b"world!"547        yield b""548549    response = httpx.Response(200, content=streaming_body_with_empty_chunks())550551    parts = [part for part in response.iter_bytes()]552    assert parts == [b"Hello, ", b"world!"]553554555@pytest.mark.anyio556async def test_aiter_bytes():557    response = httpx.Response(558        200,559        content=b"Hello, world!",560    )561562    content = b""563    async for part in response.aiter_bytes():564        content += part565    assert content == b"Hello, world!"566567568@pytest.mark.anyio569async def test_aiter_bytes_with_chunk_size():570    response = httpx.Response(200, content=async_streaming_body())571    parts = [part async for part in response.aiter_bytes(chunk_size=5)]572    assert parts == [b"Hello", b", wor", b"ld!"]573574    response = httpx.Response(200, content=async_streaming_body())575    parts = [part async for part in response.aiter_bytes(chunk_size=13)]576    assert parts == [b"Hello, world!"]577578    response = httpx.Response(200, content=async_streaming_body())579    parts = [part async for part in response.aiter_bytes(chunk_size=20)]580    assert parts == [b"Hello, world!"]581582583def test_iter_text():584    response = httpx.Response(585        200,586        content=b"Hello, world!",587    )588589    content = ""590    for part in response.iter_text():591        content += part592    assert content == "Hello, world!"593594595def test_iter_text_with_chunk_size():596    response = httpx.Response(200, content=b"Hello, world!")597    parts = [part for part in response.iter_text(chunk_size=5)]598    assert parts == ["Hello", ", wor", "ld!"]599600    response = httpx.Response(200, content=b"Hello, world!!")601    parts = [part for part in response.iter_text(chunk_size=7)]602    assert parts == ["Hello, ", "world!!"]603604    response = httpx.Response(200, content=b"Hello, world!")605    parts = [part for part in response.iter_text(chunk_size=7)]606    assert parts == ["Hello, ", "world!"]607608    response = httpx.Response(200, content=b"Hello, world!")609    parts = [part for part in response.iter_text(chunk_size=13)]610    assert parts == ["Hello, world!"]611612    response = httpx.Response(200, content=b"Hello, world!")613    parts = [part for part in response.iter_text(chunk_size=20)]614    assert parts == ["Hello, world!"]615616617@pytest.mark.anyio618async def test_aiter_text():619    response = httpx.Response(620        200,621        content=b"Hello, world!",622    )623624    content = ""625    async for part in response.aiter_text():626        content += part627    assert content == "Hello, world!"628629630@pytest.mark.anyio631async def test_aiter_text_with_chunk_size():632    response = httpx.Response(200, content=b"Hello, world!")633    parts = [part async for part in response.aiter_text(chunk_size=5)]634    assert parts == ["Hello", ", wor", "ld!"]635636    response = httpx.Response(200, content=b"Hello, world!")637    parts = [part async for part in response.aiter_text(chunk_size=13)]638    assert parts == ["Hello, world!"]639640    response = httpx.Response(200, content=b"Hello, world!")641    parts = [part async for part in response.aiter_text(chunk_size=20)]642    assert parts == ["Hello, world!"]643644645def test_iter_lines():646    response = httpx.Response(647        200,648        content=b"Hello,\nworld!",649    )650    content = [line for line in response.iter_lines()]651    assert content == ["Hello,", "world!"]652653654@pytest.mark.anyio655async def test_aiter_lines():656    response = httpx.Response(657        200,658        content=b"Hello,\nworld!",659    )660661    content = []662    async for line in response.aiter_lines():663        content.append(line)664    assert content == ["Hello,", "world!"]665666667def test_sync_streaming_response():668    response = httpx.Response(669        200,670        content=streaming_body(),671    )672673    assert response.status_code == 200674    assert not response.is_closed675676    content = response.read()677678    assert content == b"Hello, world!"679    assert response.content == b"Hello, world!"680    assert response.is_closed681682683@pytest.mark.anyio684async def test_async_streaming_response():685    response = httpx.Response(686        200,687        content=async_streaming_body(),688    )689690    assert response.status_code == 200691    assert not response.is_closed692693    content = await response.aread()694695    assert content == b"Hello, world!"696    assert response.content == b"Hello, world!"697    assert response.is_closed698699700def test_cannot_read_after_stream_consumed():701    response = httpx.Response(702        200,703        content=streaming_body(),704    )705706    content = b""707    for part in response.iter_bytes():708        content += part709710    with pytest.raises(httpx.StreamConsumed):711        response.read()712713714@pytest.mark.anyio715async def test_cannot_aread_after_stream_consumed():716    response = httpx.Response(717        200,718        content=async_streaming_body(),719    )720721    content = b""722    async for part in response.aiter_bytes():723        content += part724725    with pytest.raises(httpx.StreamConsumed):726        await response.aread()727728729def test_cannot_read_after_response_closed():730    response = httpx.Response(731        200,732        content=streaming_body(),733    )734735    response.close()736    with pytest.raises(httpx.StreamClosed):737        response.read()738739740@pytest.mark.anyio741async def test_cannot_aread_after_response_closed():742    response = httpx.Response(743        200,744        content=async_streaming_body(),745    )746747    await response.aclose()748    with pytest.raises(httpx.StreamClosed):749        await response.aread()750751752@pytest.mark.anyio753async def test_elapsed_not_available_until_closed():754    response = httpx.Response(755        200,756        content=async_streaming_body(),757    )758759    with pytest.raises(RuntimeError):760        response.elapsed  # noqa: B018761762763def test_unknown_status_code():764    response = httpx.Response(765        600,766    )767    assert response.status_code == 600768    assert response.reason_phrase == ""769    assert response.text == ""770771772def test_json_with_specified_encoding():773    data = {"greeting": "hello", "recipient": "world"}774    content = json.dumps(data).encode("utf-16")775    headers = {"Content-Type": "application/json, charset=utf-16"}776    response = httpx.Response(777        200,778        content=content,779        headers=headers,780    )781    assert response.json() == data782783784def test_json_with_options():785    data = {"greeting": "hello", "recipient": "world", "amount": 1}786    content = json.dumps(data).encode("utf-16")787    headers = {"Content-Type": "application/json, charset=utf-16"}788    response = httpx.Response(789        200,790        content=content,791        headers=headers,792    )793    assert response.json(parse_int=str)["amount"] == "1"794795796@pytest.mark.parametrize(797    "encoding",798    [799        "utf-8",800        "utf-8-sig",801        "utf-16",802        "utf-16-be",803        "utf-16-le",804        "utf-32",805        "utf-32-be",806        "utf-32-le",807    ],808)809def test_json_without_specified_charset(encoding):810    data = {"greeting": "hello", "recipient": "world"}811    content = json.dumps(data).encode(encoding)812    headers = {"Content-Type": "application/json"}813    response = httpx.Response(814        200,815        content=content,816        headers=headers,817    )818    assert response.json() == data819820821@pytest.mark.parametrize(822    "encoding",823    [824        "utf-8",825        "utf-8-sig",826        "utf-16",827        "utf-16-be",828        "utf-16-le",829        "utf-32",830        "utf-32-be",831        "utf-32-le",832    ],833)834def test_json_with_specified_charset(encoding):835    data = {"greeting": "hello", "recipient": "world"}836    content = json.dumps(data).encode(encoding)837    headers = {"Content-Type": f"application/json; charset={encoding}"}838    response = httpx.Response(839        200,840        content=content,841        headers=headers,842    )843    assert response.json() == data844845846@pytest.mark.parametrize(847    "headers, expected",848    [849        (850            {"Link": "<https://example.com>; rel='preload'"},851            {"preload": {"rel": "preload", "url": "https://example.com"}},852        ),853        (854            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},855            {856                "hub": {"url": "/hub", "rel": "hub"},857                "self": {"url": "/resource", "rel": "self"},858            },859        ),860    ],861)862def test_link_headers(headers, expected):863    response = httpx.Response(864        200,865        content=None,866        headers=headers,867    )868    assert response.links == expected869870871@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))872def test_decode_error_with_request(header_value):873    headers = [(b"Content-Encoding", header_value)]874    broken_compressed_body = b"xxxxxxxxxxxxxx"875    with pytest.raises(httpx.DecodingError):876        httpx.Response(877            200,878            headers=headers,879            content=broken_compressed_body,880        )881882    with pytest.raises(httpx.DecodingError):883        httpx.Response(884            200,885            headers=headers,886            content=broken_compressed_body,887            request=httpx.Request("GET", "https://www.example.org/"),888        )889890891@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))892def test_value_error_without_request(header_value):893    headers = [(b"Content-Encoding", header_value)]894    broken_compressed_body = b"xxxxxxxxxxxxxx"895    with pytest.raises(httpx.DecodingError):896        httpx.Response(200, headers=headers, content=broken_compressed_body)897898899def test_response_with_unset_request():900    response = httpx.Response(200, content=b"Hello, world!")901902    assert response.status_code == 200903    assert response.reason_phrase == "OK"904    assert response.text == "Hello, world!"905    assert not response.is_error906907908def test_set_request_after_init():909    response = httpx.Response(200, content=b"Hello, world!")910911    response.request = httpx.Request("GET", "https://www.example.org")912913    assert response.request.method == "GET"914    assert response.request.url == "https://www.example.org"915916917def test_cannot_access_unset_request():918    response = httpx.Response(200, content=b"Hello, world!")919920    with pytest.raises(RuntimeError):921        response.request  # noqa: B018922923924def test_generator_with_transfer_encoding_header():925    def content() -> typing.Iterator[bytes]:926        yield b"test 123"  # pragma: no cover927928    response = httpx.Response(200, content=content())929    assert response.headers == {"Transfer-Encoding": "chunked"}930931932def test_generator_with_content_length_header():933    def content() -> typing.Iterator[bytes]:934        yield b"test 123"  # pragma: no cover935936    headers = {"Content-Length": "8"}937    response = httpx.Response(200, content=content(), headers=headers)938    assert response.headers == {"Content-Length": "8"}939940941def test_response_picklable():942    response = httpx.Response(943        200,944        content=b"Hello, world!",945        request=httpx.Request("GET", "https://example.org"),946    )947    pickle_response = pickle.loads(pickle.dumps(response))948    assert pickle_response.is_closed is True949    assert pickle_response.is_stream_consumed is True950    assert pickle_response.next_request is None951    assert pickle_response.stream is not None952    assert pickle_response.content == b"Hello, world!"953    assert pickle_response.status_code == 200954    assert pickle_response.request.url == response.request.url955    assert pickle_response.extensions == {}956    assert pickle_response.history == []957958959@pytest.mark.anyio960async def test_response_async_streaming_picklable():961    response = httpx.Response(200, content=async_streaming_body())962    pickle_response = pickle.loads(pickle.dumps(response))963    with pytest.raises(httpx.ResponseNotRead):964        pickle_response.content  # noqa: B018965    with pytest.raises(httpx.StreamClosed):966        await pickle_response.aread()967    assert pickle_response.is_stream_consumed is False968    assert pickle_response.num_bytes_downloaded == 0969    assert pickle_response.headers == {"Transfer-Encoding": "chunked"}970971    response = httpx.Response(200, content=async_streaming_body())972    await response.aread()973    pickle_response = pickle.loads(pickle.dumps(response))974    assert pickle_response.is_stream_consumed is True975    assert pickle_response.content == b"Hello, world!"976    assert pickle_response.num_bytes_downloaded == 13977978979def test_response_decode_text_using_autodetect():980    # Ensure that a 'default_encoding="autodetect"' on the response allows for981    # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."982    # info is present.983    #984    # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.985    text = (986        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "987        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "988        "l'esprit anglais par son séjour à Londres, c'est incontestablement "989        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "990        "plus complète le fond du génie français."991    )992    content = text.encode("ISO-8859-1")993    response = httpx.Response(200, content=content, default_encoding=autodetect)994995    assert response.status_code == 200996    assert response.reason_phrase == "OK"997    assert response.encoding == "ISO-8859-1"998    assert response.text == text99910001001def test_response_decode_text_using_explicit_encoding():1002    # Ensure that a 'default_encoding="..."' on the response is used for text decoding1003    # when no "Content-Type: text/plain; charset=..."" info is present.1004    #1005    # Here we have some french text encoded with Windows-1252, rather than UTF-8.1006    # https://en.wikipedia.org/wiki/Windows-12521007    text = (1008        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "1009        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "1010        "l'esprit anglais par son séjour à Londres, c'est incontestablement "1011        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "1012        "plus complète le fond du génie français."1013    )1014    content = text.encode("cp1252")1015    response = httpx.Response(200, content=content, default_encoding="cp1252")10161017    assert response.status_code == 2001018    assert response.reason_phrase == "OK"1019    assert response.encoding == "cp1252"1020    assert response.text == text