test_responses.py
This file
Path
tests/models/test_responses.py
328 lines · 9.2 KiB · Python
Last changed by
Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117
History of this fileTake it
1import datetime2import json3from unittest import mock45import pytest67import httpx8910def streaming_body():11 yield b"Hello, "12 yield b"world!"131415async def async_streaming_body():16 yield b"Hello, "17 yield b"world!"181920def test_response():21 response = httpx.Response(200, content=b"Hello, world!")22 assert response.status_code == 20023 assert response.reason_phrase == "OK"24 assert response.text == "Hello, world!"25 assert response.elapsed == datetime.timedelta(0)262728def test_response_repr():29 response = httpx.Response(200, content=b"Hello, world!")30 assert repr(response) == "<Response [200 OK]>"313233def test_response_content_type_encoding():34 """35 Use the charset encoding in the Content-Type header if possible.36 """37 headers = {"Content-Type": "text-plain; charset=latin-1"}38 content = "Latin 1: ÿ".encode("latin-1")39 response = httpx.Response(200, content=content, headers=headers)40 assert response.text == "Latin 1: ÿ"41 assert response.encoding == "latin-1"424344def test_response_autodetect_encoding():45 """46 Autodetect encoding if there is no charset info in a Content-Type header.47 """48 content = "おはようございます。".encode("EUC-JP")49 response = httpx.Response(200, content=content)50 assert response.text == "おはようございます。"51 assert response.encoding == "EUC-JP"525354def test_response_fallback_to_autodetect():55 """56 Fallback to autodetection if we get an invalid charset in the Content-Type header.57 """58 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}59 content = "おはようございます。".encode("EUC-JP")60 response = httpx.Response(200, content=content, headers=headers)61 assert response.text == "おはようございます。"62 assert response.encoding == "EUC-JP"636465def test_response_default_text_encoding():66 """67 A media type of 'text/*' with no charset should default to ISO-8859-1.68 See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.169 """70 content = b"Hello, world!"71 headers = {"Content-Type": "text/plain"}72 response = httpx.Response(200, content=content, headers=headers)73 assert response.status_code == 20074 assert response.encoding == "iso-8859-1"75 assert response.text == "Hello, world!"767778def test_response_default_encoding():79 """80 Default to utf-8 if all else fails.81 """82 response = httpx.Response(200, content=b"")83 assert response.text == ""84 assert response.encoding == "utf-8"858687def test_response_non_text_encoding():88 """89 Default to apparent encoding for non-text content-type headers.90 """91 headers = {"Content-Type": "image/png"}92 response = httpx.Response(200, content=b"xyz", headers=headers)93 assert response.text == "xyz"94 assert response.encoding == "ascii"959697def test_response_set_explicit_encoding():98 headers = {99 "Content-Type": "text-plain; charset=utf-8"100 } # Deliberately incorrect charset101 response = httpx.Response(102 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers103 )104 response.encoding = "latin-1"105 assert response.text == "Latin 1: ÿ"106 assert response.encoding == "latin-1"107108109def test_response_force_encoding():110 response = httpx.Response(200, content="Snowman: ☃".encode("utf-8"))111 response.encoding = "iso-8859-1"112 assert response.status_code == 200113 assert response.reason_phrase == "OK"114 assert response.text == "Snowman: â\x98\x83"115 assert response.encoding == "iso-8859-1"116117118def test_read_response():119 response = httpx.Response(200, content=b"Hello, world!")120121 assert response.status_code == 200122 assert response.text == "Hello, world!"123 assert response.encoding == "ascii"124 assert response.is_closed125126 content = response.read()127128 assert content == b"Hello, world!"129 assert response.content == b"Hello, world!"130 assert response.is_closed131132133def test_raw_interface():134 response = httpx.Response(200, content=b"Hello, world!")135136 raw = b""137 for part in response.raw():138 raw += part139 assert raw == b"Hello, world!"140141142def test_stream_interface():143 response = httpx.Response(200, content=b"Hello, world!")144145 content = b""146 for part in response.stream():147 content += part148 assert content == b"Hello, world!"149150151@pytest.mark.asyncio152async def test_async_stream_interface():153 response = httpx.AsyncResponse(200, content=b"Hello, world!")154155 content = b""156 async for part in response.stream():157 content += part158 assert content == b"Hello, world!"159160161def test_stream_interface_after_read():162 response = httpx.Response(200, content=b"Hello, world!")163164 response.read()165166 content = b""167 for part in response.stream():168 content += part169 assert content == b"Hello, world!"170171172@pytest.mark.asyncio173async def test_async_stream_interface_after_read():174 response = httpx.AsyncResponse(200, content=b"Hello, world!")175176 await response.read()177178 content = b""179 async for part in response.stream():180 content += part181 assert content == b"Hello, world!"182183184def test_streaming_response():185 response = httpx.Response(200, content=streaming_body())186187 assert response.status_code == 200188 assert not response.is_closed189190 content = response.read()191192 assert content == b"Hello, world!"193 assert response.content == b"Hello, world!"194 assert response.is_closed195196197@pytest.mark.asyncio198async def test_async_streaming_response():199 response = httpx.AsyncResponse(200, content=async_streaming_body())200201 assert response.status_code == 200202 assert not response.is_closed203204 content = await response.read()205206 assert content == b"Hello, world!"207 assert response.content == b"Hello, world!"208 assert response.is_closed209210211def test_cannot_read_after_stream_consumed():212 response = httpx.Response(200, content=streaming_body())213214 content = b""215 for part in response.stream():216 content += part217218 with pytest.raises(httpx.StreamConsumed):219 response.read()220221222@pytest.mark.asyncio223async def test_async_cannot_read_after_stream_consumed():224 response = httpx.AsyncResponse(200, content=async_streaming_body())225226 content = b""227 async for part in response.stream():228 content += part229230 with pytest.raises(httpx.StreamConsumed):231 await response.read()232233234def test_cannot_read_after_response_closed():235 response = httpx.Response(200, content=streaming_body())236237 response.close()238239 with pytest.raises(httpx.ResponseClosed):240 response.read()241242243@pytest.mark.asyncio244async def test_async_cannot_read_after_response_closed():245 response = httpx.AsyncResponse(200, content=async_streaming_body())246247 await response.close()248249 with pytest.raises(httpx.ResponseClosed):250 await response.read()251252253def test_unknown_status_code():254 response = httpx.Response(600)255 assert response.status_code == 600256 assert response.reason_phrase == ""257 assert response.text == ""258259260def test_json_with_specified_encoding():261 data = {"greeting": "hello", "recipient": "world"}262 content = json.dumps(data).encode("utf-16")263 headers = {"Content-Type": "application/json, charset=utf-16"}264 response = httpx.Response(200, content=content, headers=headers)265 assert response.json() == data266267268def test_json_with_options():269 data = {"greeting": "hello", "recipient": "world", "amount": 1}270 content = json.dumps(data).encode("utf-16")271 headers = {"Content-Type": "application/json, charset=utf-16"}272 response = httpx.Response(200, content=content, headers=headers)273 assert response.json(parse_int=str)["amount"] == "1"274275276def test_json_without_specified_encoding():277 data = {"greeting": "hello", "recipient": "world"}278 content = json.dumps(data).encode("utf-32-be")279 headers = {"Content-Type": "application/json"}280 response = httpx.Response(200, content=content, headers=headers)281 assert response.json() == data282283284def test_json_without_specified_encoding_decode_error():285 data = {"greeting": "hello", "recipient": "world"}286 content = json.dumps(data).encode("utf-32-be")287 headers = {"Content-Type": "application/json"}288 # force incorrect guess from `guess_json_utf` to trigger error289 with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):290 response = httpx.Response(200, content=content, headers=headers)291 with pytest.raises(json.JSONDecodeError):292 response.json()293294295@pytest.mark.parametrize(296 "headers, expected",297 [298 (299 {"Link": "<https://example.com>; rel='preload'"},300 {"preload": {"rel": "preload", "url": "https://example.com"}},301 ),302 (303 {"Link": '</hub>; rel="hub", </resource>; rel="self"'},304 {305 "hub": {"url": "/hub", "rel": "hub"},306 "self": {"url": "/resource", "rel": "self"},307 },308 ),309 ],310)311def test_link_headers(headers, expected):312 response = httpx.Response(200, content=None, headers=headers)313 assert response.links == expected314315316@pytest.mark.asyncio317async def test_stream_text():318 async def iterator():319 yield b"Hello, world!"320321 response = httpx.AsyncResponse(200, content=iterator().__aiter__())322323 await response.read()324325 content = ""326 async for part in response.stream_text():327 content += part328 assert content == "Hello, world!"