Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than e64fcad point at it.

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 1why, one step back
1import datetime

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 2–24why, one step back
2import json
3from 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!"

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 25why, one step back
25 assert response.elapsed == datetime.timedelta(0)

Add Response.is_error (#574)Tom Christiebefore adoptionfdaa012

line 26why, one step back
26 assert not response.is_error

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 27–118why, one step back
27
2829def 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"117118

Drop sync (#544)Tom Christiebefore adoption206c537

lines 119–120why, one step back
119@pytest.mark.asyncio
120async def test_read_response():

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 121–127why, one step back
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_closed127

Drop sync (#544)Tom Christiebefore adoption206c537

line 128why, one step back
128 content = await response.read()

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 129–134why, one step back
129
130 assert content == b"Hello, world!"131 assert response.content == b"Hello, world!"132 assert response.is_closed133134

Drop sync (#544)Tom Christiebefore adoption206c537

lines 135–136why, one step back
135@pytest.mark.asyncio
136async def test_raw_interface():

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 137–139why, one step back
137 response = httpx.Response(200, content=b"Hello, world!")
138139 raw = b""

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 140why, one step back
140 async for part in response.aiter_raw():

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 141–144why, one step back
141 raw += part
142 assert raw == b"Hello, world!"143144

Drop sync (#544)Tom Christiebefore adoption206c537

line 145why, one step back
145@pytest.mark.asyncio

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 146why, one step back
146async def test_bytes_interface():

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 147–149why, one step back
147 response = httpx.Response(200, content=b"Hello, world!")
148149 content = b""

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 150why, one step back
150 async for part in response.aiter_bytes():

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 151–154why, one step back
151 content += part
152 assert content == b"Hello, world!"153154

Drop sync (#544)Tom Christiebefore adoption206c537

line 155why, one step back
155@pytest.mark.asyncio

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 156why, one step back
156async def test_text_interface():

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 157–158why, one step back
157 response = httpx.Response(200, content=b"Hello, world!")
158

Drop sync (#544)Tom Christiebefore adoption206c537

line 159why, one step back
159 await response.read()

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

line 160why, one step back
160

Drop sync (#544)Tom Christiebefore adoption206c537

line 161why, one step back
161 content = ""

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 162why, one step back
162 async for part in response.aiter_text():

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

line 163why, one step back
163 content += part

Drop sync (#544)Tom Christiebefore adoption206c537

line 164why, one step back
164 assert content == "Hello, world!"

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 165–167why, one step back
165
166167@pytest.mark.asyncio

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 168why, one step back
168async def test_lines_interface():

Add Response.stream_lines (#575)Tom Christiebefore adoption248aa58

lines 169–173why, one step back
169 response = httpx.Response(200, content=b"Hello,\nworld!")
170171 await response.read()172173 content = []

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 174why, one step back
174 async for line in response.aiter_lines():

Add Response.stream_lines (#575)Tom Christiebefore adoption248aa58

lines 175–179why, one step back
175 content.append(line)
176 assert content == ["Hello,\n", "world!"]177178179@pytest.mark.asyncio

Drop sync (#544)Tom Christiebefore adoption206c537

lines 180–181why, one step back
180async def test_stream_interface_after_read():
181 response = httpx.Response(200, content=b"Hello, world!")

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 182–185why, one step back
182
183 await response.read()184185 content = b""

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 186why, one step back
186 async for part in response.aiter_bytes():

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 187–191why, one step back
187 content += part
188 assert content == b"Hello, world!"189190191@pytest.mark.asyncio

Drop sync (#544)Tom Christiebefore adoption206c537

lines 192–193why, one step back
192async def test_streaming_response():
193 response = httpx.Response(200, content=async_streaming_body())

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 194–205why, one step back
194
195 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.asyncio

Drop sync (#544)Tom Christiebefore adoption206c537

lines 206–207why, one step back
206async def test_cannot_read_after_stream_consumed():
207 response = httpx.Response(200, content=async_streaming_body())

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 208–209why, one step back
208
209 content = b""

Add aiter methods on response (#610)Tom Christiebefore adoptionec40d04

line 210why, one step back
210 async for part in response.aiter_bytes():

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 211–217why, one step back
211 content += part
212213 with pytest.raises(httpx.StreamConsumed):214 await response.read()215216217@pytest.mark.asyncio

Drop sync (#544)Tom Christiebefore adoption206c537

lines 218–219why, one step back
218async def test_cannot_read_after_response_closed():
219 response = httpx.Response(200, content=async_streaming_body())

Add --diff flag to Black for easier debugging (#219)euri10before adoptione64fcad

lines 220–287why, one step back
220
221 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