test_responses.py
This file
Path
tests/models/test_responses.py
309 lines · 9.3 KiB · Python
Last changed by
Bump coverage (#705)Tom Christiebefore adoptionb8394f1
History of this fileTake it
1import datetime2import json3from unittest import mock45import pytest67import httpx8from httpx.content_streams import AsyncIteratorStream910REQUEST = httpx.Request("GET", "https://example.org")111213def streaming_body():14 yield b"Hello, "15 yield b"world!"161718async def async_streaming_body():19 yield b"Hello, "20 yield b"world!"212223@pytest.mark.asyncio24async def test_response():25 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)2627 assert response.status_code == 20028 assert response.reason_phrase == "OK"29 assert response.text == "Hello, world!"30 assert response.request is REQUEST31 assert response.elapsed >= datetime.timedelta(0)32 assert not response.is_error333435def test_response_repr():36 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)37 assert repr(response) == "<Response [200 OK]>"383940def test_response_content_type_encoding():41 """42 Use the charset encoding in the Content-Type header if possible.43 """44 headers = {"Content-Type": "text-plain; charset=latin-1"}45 content = "Latin 1: ÿ".encode("latin-1")46 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)47 assert response.text == "Latin 1: ÿ"48 assert response.encoding == "latin-1"495051def test_response_autodetect_encoding():52 """53 Autodetect encoding if there is no charset info in a Content-Type header.54 """55 content = "おはようございます。".encode("EUC-JP")56 response = httpx.Response(200, content=content, request=REQUEST)57 assert response.text == "おはようございます。"58 assert response.encoding == "EUC-JP"596061def test_response_fallback_to_autodetect():62 """63 Fallback to autodetection if we get an invalid charset in the Content-Type header.64 """65 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}66 content = "おはようございます。".encode("EUC-JP")67 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)68 assert response.text == "おはようございます。"69 assert response.encoding == "EUC-JP"707172def test_response_default_text_encoding():73 """74 A media type of 'text/*' with no charset should default to ISO-8859-1.75 See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.176 """77 content = b"Hello, world!"78 headers = {"Content-Type": "text/plain"}79 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)80 assert response.status_code == 20081 assert response.encoding == "iso-8859-1"82 assert response.text == "Hello, world!"838485def test_response_default_encoding():86 """87 Default to utf-8 if all else fails.88 """89 response = httpx.Response(200, content=b"", request=REQUEST)90 assert response.text == ""91 assert response.encoding == "utf-8"929394def test_response_non_text_encoding():95 """96 Default to apparent encoding for non-text content-type headers.97 """98 headers = {"Content-Type": "image/png"}99 response = httpx.Response(200, content=b"xyz", headers=headers, request=REQUEST)100 assert response.text == "xyz"101 assert response.encoding == "ascii"102103104def test_response_set_explicit_encoding():105 headers = {106 "Content-Type": "text-plain; charset=utf-8"107 } # Deliberately incorrect charset108 response = httpx.Response(109 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers, request=REQUEST,110 )111 response.encoding = "latin-1"112 assert response.text == "Latin 1: ÿ"113 assert response.encoding == "latin-1"114115116def test_response_force_encoding():117 response = httpx.Response(118 200, content="Snowman: ☃".encode("utf-8"), request=REQUEST119 )120 response.encoding = "iso-8859-1"121 assert response.status_code == 200122 assert response.reason_phrase == "OK"123 assert response.text == "Snowman: â\x98\x83"124 assert response.encoding == "iso-8859-1"125126127@pytest.mark.asyncio128async def test_read_response():129 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)130131 assert response.status_code == 200132 assert response.text == "Hello, world!"133 assert response.encoding == "ascii"134 assert response.is_closed135136 content = await response.aread()137138 assert content == b"Hello, world!"139 assert response.content == b"Hello, world!"140 assert response.is_closed141142143@pytest.mark.asyncio144async def test_raw_interface():145 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)146147 raw = b""148 async for part in response.aiter_raw():149 raw += part150 assert raw == b"Hello, world!"151152153@pytest.mark.asyncio154async def test_bytes_interface():155 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)156157 content = b""158 async for part in response.aiter_bytes():159 content += part160 assert content == b"Hello, world!"161162163@pytest.mark.asyncio164async def test_text_interface():165 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)166167 await response.aread()168169 content = ""170 async for part in response.aiter_text():171 content += part172 assert content == "Hello, world!"173174175@pytest.mark.asyncio176async def test_lines_interface():177 response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)178179 await response.aread()180181 content = []182 async for line in response.aiter_lines():183 content.append(line)184 assert content == ["Hello,\n", "world!"]185186187@pytest.mark.asyncio188async def test_stream_interface_after_read():189 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)190191 await response.aread()192193 content = b""194 async for part in response.aiter_bytes():195 content += part196 assert content == b"Hello, world!"197198199@pytest.mark.asyncio200async def test_streaming_response():201 stream = AsyncIteratorStream(aiterator=async_streaming_body())202 response = httpx.Response(200, stream=stream, request=REQUEST)203204 assert response.status_code == 200205 assert not response.is_closed206207 content = await response.aread()208209 assert content == b"Hello, world!"210 assert response.content == b"Hello, world!"211 assert response.is_closed212213214@pytest.mark.asyncio215async def test_cannot_read_after_stream_consumed():216 stream = AsyncIteratorStream(aiterator=async_streaming_body())217 response = httpx.Response(200, stream=stream, request=REQUEST)218219 content = b""220 async for part in response.aiter_bytes():221 content += part222223 with pytest.raises(httpx.StreamConsumed):224 await response.aread()225226227@pytest.mark.asyncio228async def test_cannot_read_after_response_closed():229 stream = AsyncIteratorStream(aiterator=async_streaming_body())230 response = httpx.Response(200, stream=stream, request=REQUEST)231232 await response.aclose()233234 with pytest.raises(httpx.ResponseClosed):235 await response.aread()236237238@pytest.mark.asyncio239async def test_elapsed_not_available_until_closed():240 stream = AsyncIteratorStream(aiterator=async_streaming_body())241 response = httpx.Response(200, stream=stream, request=REQUEST)242243 with pytest.raises(RuntimeError):244 response.elapsed245246247def test_unknown_status_code():248 response = httpx.Response(600, request=REQUEST)249 assert response.status_code == 600250 assert response.reason_phrase == ""251 assert response.text == ""252253254def test_json_with_specified_encoding():255 data = {"greeting": "hello", "recipient": "world"}256 content = json.dumps(data).encode("utf-16")257 headers = {"Content-Type": "application/json, charset=utf-16"}258 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)259 assert response.json() == data260261262def test_json_with_options():263 data = {"greeting": "hello", "recipient": "world", "amount": 1}264 content = json.dumps(data).encode("utf-16")265 headers = {"Content-Type": "application/json, charset=utf-16"}266 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)267 assert response.json(parse_int=str)["amount"] == "1"268269270def test_json_without_specified_encoding():271 data = {"greeting": "hello", "recipient": "world"}272 content = json.dumps(data).encode("utf-32-be")273 headers = {"Content-Type": "application/json"}274 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)275 assert response.json() == data276277278def test_json_without_specified_encoding_decode_error():279 data = {"greeting": "hello", "recipient": "world"}280 content = json.dumps(data).encode("utf-32-be")281 headers = {"Content-Type": "application/json"}282 # force incorrect guess from `guess_json_utf` to trigger error283 with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):284 response = httpx.Response(285 200, content=content, headers=headers, request=REQUEST286 )287 with pytest.raises(json.JSONDecodeError):288 response.json()289290291@pytest.mark.parametrize(292 "headers, expected",293 [294 (295 {"Link": "<https://example.com>; rel='preload'"},296 {"preload": {"rel": "preload", "url": "https://example.com"}},297 ),298 (299 {"Link": '</hub>; rel="hub", </resource>; rel="self"'},300 {301 "hub": {"url": "/hub", "rel": "hub"},302 "self": {"url": "/resource", "rel": "self"},303 },304 ),305 ],306)307def test_link_headers(headers, expected):308 response = httpx.Response(200, content=None, headers=headers, request=REQUEST)309 assert response.links == expected