test_responses.py
This file
Path
tests/models/test_responses.py
894 lines · 24.1 KiB · Python
Last changed by
Make Request and Response picklable (#1579)Hannes Ljungbergbefore adoption2d57104
History of this fileTake it
1import json2import pickle3from unittest import mock45import brotli6import pytest78import httpx91011class 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 test_response():28 response = httpx.Response(29 200,30 content=b"Hello, world!",31 request=httpx.Request("GET", "https://example.org"),32 )3334 assert response.status_code == 20035 assert response.reason_phrase == "OK"36 assert response.text == "Hello, world!"37 assert response.request.method == "GET"38 assert response.request.url == "https://example.org"39 assert not response.is_error404142def test_response_content():43 response = httpx.Response(200, content="Hello, world!")4445 assert response.status_code == 20046 assert response.reason_phrase == "OK"47 assert response.text == "Hello, world!"48 assert response.headers == {"Content-Length": "13"}495051def test_response_text():52 response = httpx.Response(200, text="Hello, world!")5354 assert response.status_code == 20055 assert response.reason_phrase == "OK"56 assert response.text == "Hello, world!"57 assert response.headers == {58 "Content-Length": "13",59 "Content-Type": "text/plain; charset=utf-8",60 }616263def test_response_html():64 response = httpx.Response(200, html="<html><body>Hello, world!</html></body>")6566 assert response.status_code == 20067 assert response.reason_phrase == "OK"68 assert response.text == "<html><body>Hello, world!</html></body>"69 assert response.headers == {70 "Content-Length": "39",71 "Content-Type": "text/html; charset=utf-8",72 }737475def test_response_json():76 response = httpx.Response(200, json={"hello": "world"})7778 assert response.status_code == 20079 assert response.reason_phrase == "OK"80 assert response.json() == {"hello": "world"}81 assert response.headers == {82 "Content-Length": "18",83 "Content-Type": "application/json",84 }858687def test_raise_for_status():88 request = httpx.Request("GET", "https://example.org")8990 # 2xx status codes are not an error.91 response = httpx.Response(200, request=request)92 response.raise_for_status()9394 # 4xx status codes are a client error.95 response = httpx.Response(403, request=request)96 with pytest.raises(httpx.HTTPStatusError):97 response.raise_for_status()9899 # 5xx status codes are a server error.100 response = httpx.Response(500, request=request)101 with pytest.raises(httpx.HTTPStatusError):102 response.raise_for_status()103104 # Calling .raise_for_status without setting a request instance is105 # not valid. Should raise a runtime error.106 response = httpx.Response(200)107 with pytest.raises(RuntimeError):108 response.raise_for_status()109110111def test_response_repr():112 response = httpx.Response(113 200,114 content=b"Hello, world!",115 )116 assert repr(response) == "<Response [200 OK]>"117118119def test_response_content_type_encoding():120 """121 Use the charset encoding in the Content-Type header if possible.122 """123 headers = {"Content-Type": "text-plain; charset=latin-1"}124 content = "Latin 1: ÿ".encode("latin-1")125 response = httpx.Response(126 200,127 content=content,128 headers=headers,129 )130 assert response.text == "Latin 1: ÿ"131 assert response.encoding == "latin-1"132133134def test_response_autodetect_encoding():135 """136 Autodetect encoding if there is no Content-Type header.137 """138 content = "おはようございます。".encode("utf-8")139 response = httpx.Response(140 200,141 content=content,142 )143 assert response.text == "おはようございます。"144 assert response.encoding is None145146147def test_response_fallback_to_autodetect():148 """149 Fallback to autodetection if we get an invalid charset in the Content-Type header.150 """151 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}152 content = "おはようございます。".encode("utf-8")153 response = httpx.Response(154 200,155 content=content,156 headers=headers,157 )158 assert response.text == "おはようございます。"159 assert response.encoding is None160161162def test_response_no_charset_with_ascii_content():163 """164 A response with ascii encoded content should decode correctly,165 even with no charset specified.166 """167 content = b"Hello, world!"168 headers = {"Content-Type": "text/plain"}169 response = httpx.Response(170 200,171 content=content,172 headers=headers,173 )174 assert response.status_code == 200175 assert response.encoding is None176 assert response.text == "Hello, world!"177178179def test_response_no_charset_with_utf8_content():180 """181 A response with UTF-8 encoded content should decode correctly,182 even with no charset specified.183 """184 content = "Unicode Snowman: ☃".encode("utf-8")185 headers = {"Content-Type": "text/plain"}186 response = httpx.Response(187 200,188 content=content,189 headers=headers,190 )191 assert response.text == "Unicode Snowman: ☃"192 assert response.encoding is None193194195def test_response_no_charset_with_iso_8859_1_content():196 """197 A response with ISO 8859-1 encoded content should decode correctly,198 even with no charset specified.199 """200 content = "Accented: Österreich".encode("iso-8859-1")201 headers = {"Content-Type": "text/plain"}202 response = httpx.Response(203 200,204 content=content,205 headers=headers,206 )207 assert response.text == "Accented: Österreich"208 assert response.encoding is None209210211def test_response_no_charset_with_cp_1252_content():212 """213 A response with Windows 1252 encoded content should decode correctly,214 even with no charset specified.215 """216 content = "Euro Currency: €".encode("cp1252")217 headers = {"Content-Type": "text/plain"}218 response = httpx.Response(219 200,220 content=content,221 headers=headers,222 )223 assert response.text == "Euro Currency: €"224 assert response.encoding is None225226227def test_response_non_text_encoding():228 """229 Default to apparent encoding for non-text content-type headers.230 """231 headers = {"Content-Type": "image/png"}232 response = httpx.Response(233 200,234 content=b"xyz",235 headers=headers,236 )237 assert response.text == "xyz"238 assert response.encoding is None239240241def test_response_set_explicit_encoding():242 headers = {243 "Content-Type": "text-plain; charset=utf-8"244 } # Deliberately incorrect charset245 response = httpx.Response(246 200,247 content="Latin 1: ÿ".encode("latin-1"),248 headers=headers,249 )250 response.encoding = "latin-1"251 assert response.text == "Latin 1: ÿ"252 assert response.encoding == "latin-1"253254255def test_response_force_encoding():256 response = httpx.Response(257 200,258 content="Snowman: ☃".encode("utf-8"),259 )260 response.encoding = "iso-8859-1"261 assert response.status_code == 200262 assert response.reason_phrase == "OK"263 assert response.text == "Snowman: â\x98\x83"264 assert response.encoding == "iso-8859-1"265266267def test_read():268 response = httpx.Response(269 200,270 content=b"Hello, world!",271 )272273 assert response.status_code == 200274 assert response.text == "Hello, world!"275 assert response.encoding is None276 assert response.is_closed277278 content = response.read()279280 assert content == b"Hello, world!"281 assert response.content == b"Hello, world!"282 assert response.is_closed283284285def test_empty_read():286 response = httpx.Response(200)287288 assert response.status_code == 200289 assert response.text == ""290 assert response.encoding is None291 assert response.is_closed292293 content = response.read()294295 assert content == b""296 assert response.content == b""297 assert response.is_closed298299300@pytest.mark.asyncio301async def test_aread():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 is None310 assert response.is_closed311312 content = await response.aread()313314 assert content == b"Hello, world!"315 assert response.content == b"Hello, world!"316 assert response.is_closed317318319@pytest.mark.asyncio320async def test_empty_aread():321 response = httpx.Response(200)322323 assert response.status_code == 200324 assert response.text == ""325 assert response.encoding is None326 assert response.is_closed327328 content = await response.aread()329330 assert content == b""331 assert response.content == b""332 assert response.is_closed333334335def test_iter_raw():336 response = httpx.Response(337 200,338 content=streaming_body(),339 )340341 raw = b""342 for part in response.iter_raw():343 raw += part344 assert raw == b"Hello, world!"345346347def test_iter_raw_with_chunksize():348 response = httpx.Response(200, content=streaming_body())349350 parts = [part for part in response.iter_raw(chunk_size=5)]351 assert parts == [b"Hello", b", wor", b"ld!"]352353 response = httpx.Response(200, content=streaming_body())354355 parts = [part for part in response.iter_raw(chunk_size=13)]356 assert parts == [b"Hello, world!"]357358 response = httpx.Response(200, content=streaming_body())359360 parts = [part for part in response.iter_raw(chunk_size=20)]361 assert parts == [b"Hello, world!"]362363364def test_iter_raw_on_iterable():365 response = httpx.Response(366 200,367 content=StreamingBody(),368 )369370 raw = b""371 for part in response.iter_raw():372 raw += part373 assert raw == b"Hello, world!"374375376def test_iter_raw_on_async():377 response = httpx.Response(378 200,379 content=async_streaming_body(),380 )381382 with pytest.raises(RuntimeError):383 [part for part in response.iter_raw()]384385386def test_close_on_async():387 response = httpx.Response(388 200,389 content=async_streaming_body(),390 )391392 with pytest.raises(RuntimeError):393 response.close()394395396def test_iter_raw_increments_updates_counter():397 response = httpx.Response(200, content=streaming_body())398399 num_downloaded = response.num_bytes_downloaded400 for part in response.iter_raw():401 assert len(part) == (response.num_bytes_downloaded - num_downloaded)402 num_downloaded = response.num_bytes_downloaded403404405@pytest.mark.asyncio406async def test_aiter_raw():407 response = httpx.Response(200, content=async_streaming_body())408409 raw = b""410 async for part in response.aiter_raw():411 raw += part412 assert raw == b"Hello, world!"413414415@pytest.mark.asyncio416async def test_aiter_raw_with_chunksize():417 response = httpx.Response(200, content=async_streaming_body())418419 parts = [part async for part in response.aiter_raw(chunk_size=5)]420 assert parts == [b"Hello", b", wor", b"ld!"]421422 response = httpx.Response(200, content=async_streaming_body())423424 parts = [part async for part in response.aiter_raw(chunk_size=13)]425 assert parts == [b"Hello, world!"]426427 response = httpx.Response(200, content=async_streaming_body())428429 parts = [part async for part in response.aiter_raw(chunk_size=20)]430 assert parts == [b"Hello, world!"]431432433@pytest.mark.asyncio434async def test_aiter_raw_on_sync():435 response = httpx.Response(436 200,437 content=streaming_body(),438 )439440 with pytest.raises(RuntimeError):441 [part async for part in response.aiter_raw()]442443444@pytest.mark.asyncio445async def test_aclose_on_sync():446 response = httpx.Response(447 200,448 content=streaming_body(),449 )450451 with pytest.raises(RuntimeError):452 await response.aclose()453454455@pytest.mark.asyncio456async def test_aiter_raw_increments_updates_counter():457 response = httpx.Response(200, content=async_streaming_body())458459 num_downloaded = response.num_bytes_downloaded460 async for part in response.aiter_raw():461 assert len(part) == (response.num_bytes_downloaded - num_downloaded)462 num_downloaded = response.num_bytes_downloaded463464465def test_iter_bytes():466 response = httpx.Response(200, content=b"Hello, world!")467468 content = b""469 for part in response.iter_bytes():470 content += part471 assert content == b"Hello, world!"472473474def test_iter_bytes_with_chunk_size():475 response = httpx.Response(200, content=streaming_body())476 parts = [part for part in response.iter_bytes(chunk_size=5)]477 assert parts == [b"Hello", b", wor", b"ld!"]478479 response = httpx.Response(200, content=streaming_body())480 parts = [part for part in response.iter_bytes(chunk_size=13)]481 assert parts == [b"Hello, world!"]482483 response = httpx.Response(200, content=streaming_body())484 parts = [part for part in response.iter_bytes(chunk_size=20)]485 assert parts == [b"Hello, world!"]486487488@pytest.mark.asyncio489async def test_aiter_bytes():490 response = httpx.Response(491 200,492 content=b"Hello, world!",493 )494495 content = b""496 async for part in response.aiter_bytes():497 content += part498 assert content == b"Hello, world!"499500501@pytest.mark.asyncio502async def test_aiter_bytes_with_chunk_size():503 response = httpx.Response(200, content=async_streaming_body())504 parts = [part async for part in response.aiter_bytes(chunk_size=5)]505 assert parts == [b"Hello", b", wor", b"ld!"]506507 response = httpx.Response(200, content=async_streaming_body())508 parts = [part async for part in response.aiter_bytes(chunk_size=13)]509 assert parts == [b"Hello, world!"]510511 response = httpx.Response(200, content=async_streaming_body())512 parts = [part async for part in response.aiter_bytes(chunk_size=20)]513 assert parts == [b"Hello, world!"]514515516def test_iter_text():517 response = httpx.Response(518 200,519 content=b"Hello, world!",520 )521522 content = ""523 for part in response.iter_text():524 content += part525 assert content == "Hello, world!"526527528def test_iter_text_with_chunk_size():529 response = httpx.Response(200, content=b"Hello, world!")530 parts = [part for part in response.iter_text(chunk_size=5)]531 assert parts == ["Hello", ", wor", "ld!"]532533 response = httpx.Response(200, content=b"Hello, world!")534 parts = [part for part in response.iter_text(chunk_size=13)]535 assert parts == ["Hello, world!"]536537 response = httpx.Response(200, content=b"Hello, world!")538 parts = [part for part in response.iter_text(chunk_size=20)]539 assert parts == ["Hello, world!"]540541542@pytest.mark.asyncio543async def test_aiter_text():544 response = httpx.Response(545 200,546 content=b"Hello, world!",547 )548549 content = ""550 async for part in response.aiter_text():551 content += part552 assert content == "Hello, world!"553554555@pytest.mark.asyncio556async def test_aiter_text_with_chunk_size():557 response = httpx.Response(200, content=b"Hello, world!")558 parts = [part async for part in response.aiter_text(chunk_size=5)]559 assert parts == ["Hello", ", wor", "ld!"]560561 response = httpx.Response(200, content=b"Hello, world!")562 parts = [part async for part in response.aiter_text(chunk_size=13)]563 assert parts == ["Hello, world!"]564565 response = httpx.Response(200, content=b"Hello, world!")566 parts = [part async for part in response.aiter_text(chunk_size=20)]567 assert parts == ["Hello, world!"]568569570def test_iter_lines():571 response = httpx.Response(572 200,573 content=b"Hello,\nworld!",574 )575576 content = []577 for line in response.iter_lines():578 content.append(line)579 assert content == ["Hello,\n", "world!"]580581582@pytest.mark.asyncio583async def test_aiter_lines():584 response = httpx.Response(585 200,586 content=b"Hello,\nworld!",587 )588589 content = []590 async for line in response.aiter_lines():591 content.append(line)592 assert content == ["Hello,\n", "world!"]593594595def test_sync_streaming_response():596 response = httpx.Response(597 200,598 content=streaming_body(),599 )600601 assert response.status_code == 200602 assert not response.is_closed603604 content = response.read()605606 assert content == b"Hello, world!"607 assert response.content == b"Hello, world!"608 assert response.is_closed609610611@pytest.mark.asyncio612async def test_async_streaming_response():613 response = httpx.Response(614 200,615 content=async_streaming_body(),616 )617618 assert response.status_code == 200619 assert not response.is_closed620621 content = await response.aread()622623 assert content == b"Hello, world!"624 assert response.content == b"Hello, world!"625 assert response.is_closed626627628def test_cannot_read_after_stream_consumed():629 response = httpx.Response(630 200,631 content=streaming_body(),632 )633634 content = b""635 for part in response.iter_bytes():636 content += part637638 with pytest.raises(httpx.StreamConsumed):639 response.read()640641642@pytest.mark.asyncio643async def test_cannot_aread_after_stream_consumed():644 response = httpx.Response(645 200,646 content=async_streaming_body(),647 )648649 content = b""650 async for part in response.aiter_bytes():651 content += part652653 with pytest.raises(httpx.StreamConsumed):654 await response.aread()655656657def test_cannot_read_after_response_closed():658 response = httpx.Response(659 200,660 content=streaming_body(),661 )662663 response.close()664 with pytest.raises(httpx.StreamClosed):665 response.read()666667668@pytest.mark.asyncio669async def test_cannot_aread_after_response_closed():670 response = httpx.Response(671 200,672 content=async_streaming_body(),673 )674675 await response.aclose()676 with pytest.raises(httpx.StreamClosed):677 await response.aread()678679680@pytest.mark.asyncio681async def test_elapsed_not_available_until_closed():682 response = httpx.Response(683 200,684 content=async_streaming_body(),685 )686687 with pytest.raises(RuntimeError):688 response.elapsed689690691def test_unknown_status_code():692 response = httpx.Response(693 600,694 )695 assert response.status_code == 600696 assert response.reason_phrase == ""697 assert response.text == ""698699700def test_json_with_specified_encoding():701 data = {"greeting": "hello", "recipient": "world"}702 content = json.dumps(data).encode("utf-16")703 headers = {"Content-Type": "application/json, charset=utf-16"}704 response = httpx.Response(705 200,706 content=content,707 headers=headers,708 )709 assert response.json() == data710711712def test_json_with_options():713 data = {"greeting": "hello", "recipient": "world", "amount": 1}714 content = json.dumps(data).encode("utf-16")715 headers = {"Content-Type": "application/json, charset=utf-16"}716 response = httpx.Response(717 200,718 content=content,719 headers=headers,720 )721 assert response.json(parse_int=str)["amount"] == "1"722723724def test_json_without_specified_encoding():725 data = {"greeting": "hello", "recipient": "world"}726 content = json.dumps(data).encode("utf-32-be")727 headers = {"Content-Type": "application/json"}728 response = httpx.Response(729 200,730 content=content,731 headers=headers,732 )733 assert response.json() == data734735736def test_json_without_specified_encoding_decode_error():737 data = {"greeting": "hello", "recipient": "world"}738 content = json.dumps(data).encode("utf-32-be")739 headers = {"Content-Type": "application/json"}740 # force incorrect guess from `guess_json_utf` to trigger error741 with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):742 response = httpx.Response(743 200,744 content=content,745 headers=headers,746 )747 with pytest.raises(json.decoder.JSONDecodeError):748 response.json()749750751def test_json_without_specified_encoding_value_error():752 data = {"greeting": "hello", "recipient": "world"}753 content = json.dumps(data).encode("utf-32-be")754 headers = {"Content-Type": "application/json"}755 # force incorrect guess from `guess_json_utf` to trigger error756 with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):757 response = httpx.Response(200, content=content, headers=headers)758 with pytest.raises(json.decoder.JSONDecodeError):759 response.json()760761762@pytest.mark.parametrize(763 "headers, expected",764 [765 (766 {"Link": "<https://example.com>; rel='preload'"},767 {"preload": {"rel": "preload", "url": "https://example.com"}},768 ),769 (770 {"Link": '</hub>; rel="hub", </resource>; rel="self"'},771 {772 "hub": {"url": "/hub", "rel": "hub"},773 "self": {"url": "/resource", "rel": "self"},774 },775 ),776 ],777)778def test_link_headers(headers, expected):779 response = httpx.Response(780 200,781 content=None,782 headers=headers,783 )784 assert response.links == expected785786787@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))788def test_decode_error_with_request(header_value):789 headers = [(b"Content-Encoding", header_value)]790 body = b"test 123"791 compressed_body = brotli.compress(body)[3:]792 with pytest.raises(httpx.DecodingError):793 httpx.Response(794 200,795 headers=headers,796 content=compressed_body,797 )798799 with pytest.raises(httpx.DecodingError):800 httpx.Response(801 200,802 headers=headers,803 content=compressed_body,804 request=httpx.Request("GET", "https://www.example.org/"),805 )806807808@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))809def test_value_error_without_request(header_value):810 headers = [(b"Content-Encoding", header_value)]811 body = b"test 123"812 compressed_body = brotli.compress(body)[3:]813 with pytest.raises(httpx.DecodingError):814 httpx.Response(200, headers=headers, content=compressed_body)815816817def test_response_with_unset_request():818 response = httpx.Response(200, content=b"Hello, world!")819820 assert response.status_code == 200821 assert response.reason_phrase == "OK"822 assert response.text == "Hello, world!"823 assert not response.is_error824825826def test_set_request_after_init():827 response = httpx.Response(200, content=b"Hello, world!")828829 response.request = httpx.Request("GET", "https://www.example.org")830831 assert response.request.method == "GET"832 assert response.request.url == "https://www.example.org"833834835def test_cannot_access_unset_request():836 response = httpx.Response(200, content=b"Hello, world!")837838 with pytest.raises(RuntimeError):839 response.request840841842def test_generator_with_transfer_encoding_header():843 def content():844 yield b"test 123" # pragma: nocover845846 response = httpx.Response(200, content=content())847 assert response.headers == {"Transfer-Encoding": "chunked"}848849850def test_generator_with_content_length_header():851 def content():852 yield b"test 123" # pragma: nocover853854 headers = {"Content-Length": "8"}855 response = httpx.Response(200, content=content(), headers=headers)856 assert response.headers == {"Content-Length": "8"}857858859def test_response_picklable():860 response = httpx.Response(861 200,862 content=b"Hello, world!",863 request=httpx.Request("GET", "https://example.org"),864 )865 pickle_response = pickle.loads(pickle.dumps(response))866 assert pickle_response.is_closed is True867 assert pickle_response.is_stream_consumed is True868 assert pickle_response.next_request is None869 assert pickle_response.stream is not None870 assert pickle_response.content == b"Hello, world!"871 assert pickle_response.status_code == 200872 assert pickle_response.request.url == response.request.url873 assert pickle_response.extensions == {}874 assert pickle_response.history == []875876877@pytest.mark.asyncio878async def test_response_async_streaming_picklable():879 response = httpx.Response(200, content=async_streaming_body())880 pickle_response = pickle.loads(pickle.dumps(response))881 with pytest.raises(httpx.ResponseNotRead):882 pickle_response.content883 with pytest.raises(httpx.StreamClosed):884 await pickle_response.aread()885 assert pickle_response.is_stream_consumed is False886 assert pickle_response.num_bytes_downloaded == 0887 assert pickle_response.headers == {"Transfer-Encoding": "chunked"}888889 response = httpx.Response(200, content=async_streaming_body())890 await response.aread()891 pickle_response = pickle.loads(pickle.dumps(response))892 assert pickle_response.is_stream_consumed is True893 assert pickle_response.content == b"Hello, world!"894 assert pickle_response.num_bytes_downloaded == 13