Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

1,013 lines · 28.5 KiB · Python

Last changed by

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

History of this file

Take it

1import json2import pickle34import chardet5import pytest67import httpx8from httpx._compat import brotli91011class StreamingBody:12    def __iter__(self):13        yield b"Hello, "14        yield b"world!"151617def streaming_body():18    yield b"Hello, "19    yield b"world!"202122async def async_streaming_body():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.asyncio335async 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.asyncio354async 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())383384    parts = [part for part in response.iter_raw(chunk_size=5)]385    assert parts == [b"Hello", b", wor", b"ld!"]386387    response = httpx.Response(200, content=streaming_body())388389    parts = [part for part in response.iter_raw(chunk_size=13)]390    assert parts == [b"Hello, world!"]391392    response = httpx.Response(200, content=streaming_body())393394    parts = [part for part in response.iter_raw(chunk_size=20)]395    assert parts == [b"Hello, world!"]396397398def test_iter_raw_doesnt_return_empty_chunks():399    def streaming_body_with_empty_chunks():400        yield b"Hello, "401        yield b""402        yield b"world!"403        yield b""404405    response = httpx.Response(200, content=streaming_body_with_empty_chunks())406407    parts = [part for part in response.iter_raw()]408    assert parts == [b"Hello, ", b"world!"]409410411def test_iter_raw_on_iterable():412    response = httpx.Response(413        200,414        content=StreamingBody(),415    )416417    raw = b""418    for part in response.iter_raw():419        raw += part420    assert raw == b"Hello, world!"421422423def test_iter_raw_on_async():424    response = httpx.Response(425        200,426        content=async_streaming_body(),427    )428429    with pytest.raises(RuntimeError):430        [part for part in response.iter_raw()]431432433def test_close_on_async():434    response = httpx.Response(435        200,436        content=async_streaming_body(),437    )438439    with pytest.raises(RuntimeError):440        response.close()441442443def test_iter_raw_increments_updates_counter():444    response = httpx.Response(200, content=streaming_body())445446    num_downloaded = response.num_bytes_downloaded447    for part in response.iter_raw():448        assert len(part) == (response.num_bytes_downloaded - num_downloaded)449        num_downloaded = response.num_bytes_downloaded450451452@pytest.mark.asyncio453async def test_aiter_raw():454    response = httpx.Response(200, content=async_streaming_body())455456    raw = b""457    async for part in response.aiter_raw():458        raw += part459    assert raw == b"Hello, world!"460461462@pytest.mark.asyncio463async def test_aiter_raw_with_chunksize():464    response = httpx.Response(200, content=async_streaming_body())465466    parts = [part async for part in response.aiter_raw(chunk_size=5)]467    assert parts == [b"Hello", b", wor", b"ld!"]468469    response = httpx.Response(200, content=async_streaming_body())470471    parts = [part async for part in response.aiter_raw(chunk_size=13)]472    assert parts == [b"Hello, world!"]473474    response = httpx.Response(200, content=async_streaming_body())475476    parts = [part async for part in response.aiter_raw(chunk_size=20)]477    assert parts == [b"Hello, world!"]478479480@pytest.mark.asyncio481async def test_aiter_raw_on_sync():482    response = httpx.Response(483        200,484        content=streaming_body(),485    )486487    with pytest.raises(RuntimeError):488        [part async for part in response.aiter_raw()]489490491@pytest.mark.asyncio492async def test_aclose_on_sync():493    response = httpx.Response(494        200,495        content=streaming_body(),496    )497498    with pytest.raises(RuntimeError):499        await response.aclose()500501502@pytest.mark.asyncio503async def test_aiter_raw_increments_updates_counter():504    response = httpx.Response(200, content=async_streaming_body())505506    num_downloaded = response.num_bytes_downloaded507    async for part in response.aiter_raw():508        assert len(part) == (response.num_bytes_downloaded - num_downloaded)509        num_downloaded = response.num_bytes_downloaded510511512def test_iter_bytes():513    response = httpx.Response(200, content=b"Hello, world!")514515    content = b""516    for part in response.iter_bytes():517        content += part518    assert content == b"Hello, world!"519520521def test_iter_bytes_with_chunk_size():522    response = httpx.Response(200, content=streaming_body())523    parts = [part for part in response.iter_bytes(chunk_size=5)]524    assert parts == [b"Hello", b", wor", b"ld!"]525526    response = httpx.Response(200, content=streaming_body())527    parts = [part for part in response.iter_bytes(chunk_size=13)]528    assert parts == [b"Hello, world!"]529530    response = httpx.Response(200, content=streaming_body())531    parts = [part for part in response.iter_bytes(chunk_size=20)]532    assert parts == [b"Hello, world!"]533534535def test_iter_bytes_with_empty_response():536    response = httpx.Response(200, content=b"")537    parts = [part for part in response.iter_bytes()]538    assert parts == []539540541def test_iter_bytes_doesnt_return_empty_chunks():542    def streaming_body_with_empty_chunks():543        yield b"Hello, "544        yield b""545        yield b"world!"546        yield b""547548    response = httpx.Response(200, content=streaming_body_with_empty_chunks())549550    parts = [part for part in response.iter_bytes()]551    assert parts == [b"Hello, ", b"world!"]552553554@pytest.mark.asyncio555async def test_aiter_bytes():556    response = httpx.Response(557        200,558        content=b"Hello, world!",559    )560561    content = b""562    async for part in response.aiter_bytes():563        content += part564    assert content == b"Hello, world!"565566567@pytest.mark.asyncio568async def test_aiter_bytes_with_chunk_size():569    response = httpx.Response(200, content=async_streaming_body())570    parts = [part async for part in response.aiter_bytes(chunk_size=5)]571    assert parts == [b"Hello", b", wor", b"ld!"]572573    response = httpx.Response(200, content=async_streaming_body())574    parts = [part async for part in response.aiter_bytes(chunk_size=13)]575    assert parts == [b"Hello, world!"]576577    response = httpx.Response(200, content=async_streaming_body())578    parts = [part async for part in response.aiter_bytes(chunk_size=20)]579    assert parts == [b"Hello, world!"]580581582def test_iter_text():583    response = httpx.Response(584        200,585        content=b"Hello, world!",586    )587588    content = ""589    for part in response.iter_text():590        content += part591    assert content == "Hello, world!"592593594def test_iter_text_with_chunk_size():595    response = httpx.Response(200, content=b"Hello, world!")596    parts = [part for part in response.iter_text(chunk_size=5)]597    assert parts == ["Hello", ", wor", "ld!"]598599    response = httpx.Response(200, content=b"Hello, world!")600    parts = [part for part in response.iter_text(chunk_size=13)]601    assert parts == ["Hello, world!"]602603    response = httpx.Response(200, content=b"Hello, world!")604    parts = [part for part in response.iter_text(chunk_size=20)]605    assert parts == ["Hello, world!"]606607608@pytest.mark.asyncio609async def test_aiter_text():610    response = httpx.Response(611        200,612        content=b"Hello, world!",613    )614615    content = ""616    async for part in response.aiter_text():617        content += part618    assert content == "Hello, world!"619620621@pytest.mark.asyncio622async def test_aiter_text_with_chunk_size():623    response = httpx.Response(200, content=b"Hello, world!")624    parts = [part async for part in response.aiter_text(chunk_size=5)]625    assert parts == ["Hello", ", wor", "ld!"]626627    response = httpx.Response(200, content=b"Hello, world!")628    parts = [part async for part in response.aiter_text(chunk_size=13)]629    assert parts == ["Hello, world!"]630631    response = httpx.Response(200, content=b"Hello, world!")632    parts = [part async for part in response.aiter_text(chunk_size=20)]633    assert parts == ["Hello, world!"]634635636def test_iter_lines():637    response = httpx.Response(638        200,639        content=b"Hello,\nworld!",640    )641    content = [line for line in response.iter_lines()]642    assert content == ["Hello,\n", "world!"]643644645@pytest.mark.asyncio646async def test_aiter_lines():647    response = httpx.Response(648        200,649        content=b"Hello,\nworld!",650    )651652    content = []653    async for line in response.aiter_lines():654        content.append(line)655    assert content == ["Hello,\n", "world!"]656657658def test_sync_streaming_response():659    response = httpx.Response(660        200,661        content=streaming_body(),662    )663664    assert response.status_code == 200665    assert not response.is_closed666667    content = response.read()668669    assert content == b"Hello, world!"670    assert response.content == b"Hello, world!"671    assert response.is_closed672673674@pytest.mark.asyncio675async def test_async_streaming_response():676    response = httpx.Response(677        200,678        content=async_streaming_body(),679    )680681    assert response.status_code == 200682    assert not response.is_closed683684    content = await response.aread()685686    assert content == b"Hello, world!"687    assert response.content == b"Hello, world!"688    assert response.is_closed689690691def test_cannot_read_after_stream_consumed():692    response = httpx.Response(693        200,694        content=streaming_body(),695    )696697    content = b""698    for part in response.iter_bytes():699        content += part700701    with pytest.raises(httpx.StreamConsumed):702        response.read()703704705@pytest.mark.asyncio706async def test_cannot_aread_after_stream_consumed():707    response = httpx.Response(708        200,709        content=async_streaming_body(),710    )711712    content = b""713    async for part in response.aiter_bytes():714        content += part715716    with pytest.raises(httpx.StreamConsumed):717        await response.aread()718719720def test_cannot_read_after_response_closed():721    response = httpx.Response(722        200,723        content=streaming_body(),724    )725726    response.close()727    with pytest.raises(httpx.StreamClosed):728        response.read()729730731@pytest.mark.asyncio732async def test_cannot_aread_after_response_closed():733    response = httpx.Response(734        200,735        content=async_streaming_body(),736    )737738    await response.aclose()739    with pytest.raises(httpx.StreamClosed):740        await response.aread()741742743@pytest.mark.asyncio744async def test_elapsed_not_available_until_closed():745    response = httpx.Response(746        200,747        content=async_streaming_body(),748    )749750    with pytest.raises(RuntimeError):751        response.elapsed752753754def test_unknown_status_code():755    response = httpx.Response(756        600,757    )758    assert response.status_code == 600759    assert response.reason_phrase == ""760    assert response.text == ""761762763def test_json_with_specified_encoding():764    data = {"greeting": "hello", "recipient": "world"}765    content = json.dumps(data).encode("utf-16")766    headers = {"Content-Type": "application/json, charset=utf-16"}767    response = httpx.Response(768        200,769        content=content,770        headers=headers,771    )772    assert response.json() == data773774775def test_json_with_options():776    data = {"greeting": "hello", "recipient": "world", "amount": 1}777    content = json.dumps(data).encode("utf-16")778    headers = {"Content-Type": "application/json, charset=utf-16"}779    response = httpx.Response(780        200,781        content=content,782        headers=headers,783    )784    assert response.json(parse_int=str)["amount"] == "1"785786787@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_without_specified_charset(encoding):801    data = {"greeting": "hello", "recipient": "world"}802    content = json.dumps(data).encode(encoding)803    headers = {"Content-Type": "application/json"}804    response = httpx.Response(805        200,806        content=content,807        headers=headers,808    )809    assert response.json() == data810811812@pytest.mark.parametrize(813    "encoding",814    [815        "utf-8",816        "utf-8-sig",817        "utf-16",818        "utf-16-be",819        "utf-16-le",820        "utf-32",821        "utf-32-be",822        "utf-32-le",823    ],824)825def test_json_with_specified_charset(encoding):826    data = {"greeting": "hello", "recipient": "world"}827    content = json.dumps(data).encode(encoding)828    headers = {"Content-Type": f"application/json; charset={encoding}"}829    response = httpx.Response(830        200,831        content=content,832        headers=headers,833    )834    assert response.json() == data835836837@pytest.mark.parametrize(838    "headers, expected",839    [840        (841            {"Link": "<https://example.com>; rel='preload'"},842            {"preload": {"rel": "preload", "url": "https://example.com"}},843        ),844        (845            {"Link": '</hub>; rel="hub", </resource>; rel="self"'},846            {847                "hub": {"url": "/hub", "rel": "hub"},848                "self": {"url": "/resource", "rel": "self"},849            },850        ),851    ],852)853def test_link_headers(headers, expected):854    response = httpx.Response(855        200,856        content=None,857        headers=headers,858    )859    assert response.links == expected860861862@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))863def test_decode_error_with_request(header_value):864    headers = [(b"Content-Encoding", header_value)]865    body = b"test 123"866    compressed_body = brotli.compress(body)[3:]867    with pytest.raises(httpx.DecodingError):868        httpx.Response(869            200,870            headers=headers,871            content=compressed_body,872        )873874    with pytest.raises(httpx.DecodingError):875        httpx.Response(876            200,877            headers=headers,878            content=compressed_body,879            request=httpx.Request("GET", "https://www.example.org/"),880        )881882883@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))884def test_value_error_without_request(header_value):885    headers = [(b"Content-Encoding", header_value)]886    body = b"test 123"887    compressed_body = brotli.compress(body)[3:]888    with pytest.raises(httpx.DecodingError):889        httpx.Response(200, headers=headers, content=compressed_body)890891892def test_response_with_unset_request():893    response = httpx.Response(200, content=b"Hello, world!")894895    assert response.status_code == 200896    assert response.reason_phrase == "OK"897    assert response.text == "Hello, world!"898    assert not response.is_error899900901def test_set_request_after_init():902    response = httpx.Response(200, content=b"Hello, world!")903904    response.request = httpx.Request("GET", "https://www.example.org")905906    assert response.request.method == "GET"907    assert response.request.url == "https://www.example.org"908909910def test_cannot_access_unset_request():911    response = httpx.Response(200, content=b"Hello, world!")912913    with pytest.raises(RuntimeError):914        response.request915916917def test_generator_with_transfer_encoding_header():918    def content():919        yield b"test 123"  # pragma: nocover920921    response = httpx.Response(200, content=content())922    assert response.headers == {"Transfer-Encoding": "chunked"}923924925def test_generator_with_content_length_header():926    def content():927        yield b"test 123"  # pragma: nocover928929    headers = {"Content-Length": "8"}930    response = httpx.Response(200, content=content(), headers=headers)931    assert response.headers == {"Content-Length": "8"}932933934def test_response_picklable():935    response = httpx.Response(936        200,937        content=b"Hello, world!",938        request=httpx.Request("GET", "https://example.org"),939    )940    pickle_response = pickle.loads(pickle.dumps(response))941    assert pickle_response.is_closed is True942    assert pickle_response.is_stream_consumed is True943    assert pickle_response.next_request is None944    assert pickle_response.stream is not None945    assert pickle_response.content == b"Hello, world!"946    assert pickle_response.status_code == 200947    assert pickle_response.request.url == response.request.url948    assert pickle_response.extensions == {}949    assert pickle_response.history == []950951952@pytest.mark.asyncio953async def test_response_async_streaming_picklable():954    response = httpx.Response(200, content=async_streaming_body())955    pickle_response = pickle.loads(pickle.dumps(response))956    with pytest.raises(httpx.ResponseNotRead):957        pickle_response.content958    with pytest.raises(httpx.StreamClosed):959        await pickle_response.aread()960    assert pickle_response.is_stream_consumed is False961    assert pickle_response.num_bytes_downloaded == 0962    assert pickle_response.headers == {"Transfer-Encoding": "chunked"}963964    response = httpx.Response(200, content=async_streaming_body())965    await response.aread()966    pickle_response = pickle.loads(pickle.dumps(response))967    assert pickle_response.is_stream_consumed is True968    assert pickle_response.content == b"Hello, world!"969    assert pickle_response.num_bytes_downloaded == 13970971972def test_response_decode_text_using_autodetect():973    # Ensure that a 'default_encoding="autodetect"' on the response allows for974    # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."975    # info is present.976    #977    # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.978    text = (979        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "980        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "981        "l'esprit anglais par son séjour à Londres, c'est incontestablement "982        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "983        "plus complète le fond du génie français."984    )985    content = text.encode("ISO-8859-1")986    response = httpx.Response(200, content=content, default_encoding=autodetect)987988    assert response.status_code == 200989    assert response.reason_phrase == "OK"990    assert response.encoding == "ISO-8859-1"991    assert response.text == text992993994def test_response_decode_text_using_explicit_encoding():995    # Ensure that a 'default_encoding="..."' on the response is used for text decoding996    # when no "Content-Type: text/plain; charset=..."" info is present.997    #998    # Here we have some french text encoded with Windows-1252, rather than UTF-8.999    # https://en.wikipedia.org/wiki/Windows-12521000    text = (1001        "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "1002        "que la France a produits, sans excepter Voltaire lui-même, imprégné de "1003        "l'esprit anglais par son séjour à Londres, c'est incontestablement "1004        "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "1005        "plus complète le fond du génie français."1006    )1007    content = text.encode("cp1252")1008    response = httpx.Response(200, content=content, default_encoding="cp1252")10091010    assert response.status_code == 2001011    assert response.reason_phrase == "OK"1012    assert response.encoding == "cp1252"1013    assert response.text == text