test_responses.py
This file
Path
tests/models/test_responses.py
287 lines · 8.3 KiB · Python
Last changed by
Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04
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)26 assert not response.is_error272829def test_response_repr():30 response = httpx.Response(200, content=b"Hello, world!")31 assert repr(response) == "<Response [200 OK]>"323334def test_response_content_type_encoding():35 """36 Use the charset encoding in the Content-Type header if possible.37 """38 headers = {"Content-Type": "text-plain; charset=latin-1"}39 content = "Latin 1: ÿ".encode("latin-1")40 response = httpx.Response(200, content=content, headers=headers)41 assert response.text == "Latin 1: ÿ"42 assert response.encoding == "latin-1"434445def test_response_autodetect_encoding():46 """47 Autodetect encoding if there is no charset info in a Content-Type header.48 """49 content = "おはようございます。".encode("EUC-JP")50 response = httpx.Response(200, content=content)51 assert response.text == "おはようございます。"52 assert response.encoding == "EUC-JP"535455def test_response_fallback_to_autodetect():56 """57 Fallback to autodetection if we get an invalid charset in the Content-Type header.58 """59 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}60 content = "おはようございます。".encode("EUC-JP")61 response = httpx.Response(200, content=content, headers=headers)62 assert response.text == "おはようございます。"63 assert response.encoding == "EUC-JP"646566def test_response_default_text_encoding():67 """68 A media type of 'text/*' with no charset should default to ISO-8859-1.69 See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.170 """71 content = b"Hello, world!"72 headers = {"Content-Type": "text/plain"}73 response = httpx.Response(200, content=content, headers=headers)74 assert response.status_code == 20075 assert response.encoding == "iso-8859-1"76 assert response.text == "Hello, world!"777879def test_response_default_encoding():80 """81 Default to utf-8 if all else fails.82 """83 response = httpx.Response(200, content=b"")84 assert response.text == ""85 assert response.encoding == "utf-8"868788def test_response_non_text_encoding():89 """90 Default to apparent encoding for non-text content-type headers.91 """92 headers = {"Content-Type": "image/png"}93 response = httpx.Response(200, content=b"xyz", headers=headers)94 assert response.text == "xyz"95 assert response.encoding == "ascii"969798def test_response_set_explicit_encoding():99 headers = {100 "Content-Type": "text-plain; charset=utf-8"101 } # Deliberately incorrect charset102 response = httpx.Response(103 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers104 )105 response.encoding = "latin-1"106 assert response.text == "Latin 1: ÿ"107 assert response.encoding == "latin-1"108109110def test_response_force_encoding():111 response = httpx.Response(200, content="Snowman: ☃".encode("utf-8"))112 response.encoding = "iso-8859-1"113 assert response.status_code == 200114 assert response.reason_phrase == "OK"115 assert response.text == "Snowman: â\x98\x83"116 assert response.encoding == "iso-8859-1"117118119@pytest.mark.asyncio120async def test_read_response():121 response = httpx.Response(200, content=b"Hello, world!")122123 assert response.status_code == 200124 assert response.text == "Hello, world!"125 assert response.encoding == "ascii"126 assert response.is_closed127128 content = await response.read()129130 assert content == b"Hello, world!"131 assert response.content == b"Hello, world!"132 assert response.is_closed133134135@pytest.mark.asyncio136async def test_raw_interface():137 response = httpx.Response(200, content=b"Hello, world!")138139 raw = b""140 async for part in response.aiter_raw():141 raw += part142 assert raw == b"Hello, world!"143144145@pytest.mark.asyncio146async def test_bytes_interface():147 response = httpx.Response(200, content=b"Hello, world!")148149 content = b""150 async for part in response.aiter_bytes():151 content += part152 assert content == b"Hello, world!"153154155@pytest.mark.asyncio156async def test_text_interface():157 response = httpx.Response(200, content=b"Hello, world!")158159 await response.read()160161 content = ""162 async for part in response.aiter_text():163 content += part164 assert content == "Hello, world!"165166167@pytest.mark.asyncio168async def test_lines_interface():169 response = httpx.Response(200, content=b"Hello,\nworld!")170171 await response.read()172173 content = []174 async for line in response.aiter_lines():175 content.append(line)176 assert content == ["Hello,\n", "world!"]177178179@pytest.mark.asyncio180async def test_stream_interface_after_read():181 response = httpx.Response(200, content=b"Hello, world!")182183 await response.read()184185 content = b""186 async for part in response.aiter_bytes():187 content += part188 assert content == b"Hello, world!"189190191@pytest.mark.asyncio192async def test_streaming_response():193 response = httpx.Response(200, content=async_streaming_body())194195 assert response.status_code == 200196 assert not response.is_closed197198 content = await response.read()199200 assert content == b"Hello, world!"201 assert response.content == b"Hello, world!"202 assert response.is_closed203204205@pytest.mark.asyncio206async def test_cannot_read_after_stream_consumed():207 response = httpx.Response(200, content=async_streaming_body())208209 content = b""210 async for part in response.aiter_bytes():211 content += part212213 with pytest.raises(httpx.StreamConsumed):214 await response.read()215216217@pytest.mark.asyncio218async def test_cannot_read_after_response_closed():219 response = httpx.Response(200, content=async_streaming_body())220221 await response.close()222223 with pytest.raises(httpx.ResponseClosed):224 await response.read()225226227def test_unknown_status_code():228 response = httpx.Response(600)229 assert response.status_code == 600230 assert response.reason_phrase == ""231 assert response.text == ""232233234def test_json_with_specified_encoding():235 data = {"greeting": "hello", "recipient": "world"}236 content = json.dumps(data).encode("utf-16")237 headers = {"Content-Type": "application/json, charset=utf-16"}238 response = httpx.Response(200, content=content, headers=headers)239 assert response.json() == data240241242def test_json_with_options():243 data = {"greeting": "hello", "recipient": "world", "amount": 1}244 content = json.dumps(data).encode("utf-16")245 headers = {"Content-Type": "application/json, charset=utf-16"}246 response = httpx.Response(200, content=content, headers=headers)247 assert response.json(parse_int=str)["amount"] == "1"248249250def test_json_without_specified_encoding():251 data = {"greeting": "hello", "recipient": "world"}252 content = json.dumps(data).encode("utf-32-be")253 headers = {"Content-Type": "application/json"}254 response = httpx.Response(200, content=content, headers=headers)255 assert response.json() == data256257258def test_json_without_specified_encoding_decode_error():259 data = {"greeting": "hello", "recipient": "world"}260 content = json.dumps(data).encode("utf-32-be")261 headers = {"Content-Type": "application/json"}262 # force incorrect guess from `guess_json_utf` to trigger error263 with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):264 response = httpx.Response(200, content=content, headers=headers)265 with pytest.raises(json.JSONDecodeError):266 response.json()267268269@pytest.mark.parametrize(270 "headers, expected",271 [272 (273 {"Link": "<https://example.com>; rel='preload'"},274 {"preload": {"rel": "preload", "url": "https://example.com"}},275 ),276 (277 {"Link": '</hub>; rel="hub", </resource>; rel="self"'},278 {279 "hub": {"url": "/hub", "rel": "hub"},280 "self": {"url": "/resource", "rel": "self"},281 },282 ),283 ],284)285def test_link_headers(headers, expected):286 response = httpx.Response(200, content=None, headers=headers)287 assert response.links == expected