Skip to content
Myr

Make 'request' non-optional on responses (#666)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Make 'request' non-optional on Response * Lint * Remove remaining mention to null request

authored by Florimond Manca · committed by GitHub · parent 9e88f2e · Browse files · 5 files+64 added−44 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+64 added−44 removed

  • tests:+62 added−38 removed
  • other:+2 added−6 removed

5 files+64 added−44 removed

modified:httpx/models.py+2 added-6 removed
659 unmodified lines
660 def __init__(661 self,662 status_code: int,663 *,664 request: Request,665 http_version: str = None,666 headers: HeaderTypes = None,667 stream: ContentStream = None,668 content: bytes = None,668 request: Request = None,669 history: typing.List["Response"] = None,670 elapsed: datetime.timedelta = None,671 ):672 self.status_code = status_code
22 unmodified lines
695 @property696 def url(self) -> typing.Optional[URL]:697 """698 Returns the URL for which the request was made.699700 Requires that `request` was provided when instantiating the response.699 """702 return None if self.request is None else self.request.url700 return self.request.url701702 @property703 def content(self) -> bytes:704 if not hasattr(self, "_content"):
123 unmodified lines
828829 @property830 def cookies(self) -> "Cookies":831 if not hasattr(self, "_cookies"):834 assert self.request is not None832 self._cookies = Cookies()833 self._cookies.extract_cookies(self)834 return self._cookies835
127 unmodified lines
963 def extract_cookies(self, response: Response) -> None:964 """965 Loads any cookies based on the response `Set-Cookie` headers.966 """970 assert response.request is not None967 urlib_response = self._CookieCompatResponse(response)968 urllib_request = self._CookieCompatRequest(response.request)969970 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore
146 unmodified lines
modified:tests/dispatch/test_http2.py+1 added-1 removed
17 unmodified lines
18 content = json.dumps(19 {"method": method, "path": path, "body": body.decode()}20 ).encode()21 headers = {"Content-Length": str(len(content))}22 return Response(200, headers=headers, content=content)22 return Response(200, headers=headers, content=content, request=request)232425@pytest.mark.asyncio26async def test_http2_get_request():
123 unmodified lines
modified:tests/models/test_responses.py+32 added-25 removed
5 unmodified lines
67import httpx8from httpx.content_streams import AsyncIteratorStream910REQUEST = httpx.Request("GET", "https://example.org")111213def streaming_body():14 yield b"Hello, "15 yield b"world!"16
3 unmodified lines
20 yield b"world!"212223def test_response():22 response = httpx.Response(200, content=b"Hello, world!")24 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)25 assert response.status_code == 20026 assert response.reason_phrase == "OK"27 assert response.text == "Hello, world!"28 assert response.request is REQUEST29 assert response.elapsed == datetime.timedelta(0)30 assert not response.is_error313233def test_response_repr():31 response = httpx.Response(200, content=b"Hello, world!")34 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)35 assert repr(response) == "<Response [200 OK]>"363738def test_response_content_type_encoding():
1 unmodified line
40 Use the charset encoding in the Content-Type header if possible.41 """42 headers = {"Content-Type": "text-plain; charset=latin-1"}43 content = "Latin 1: ÿ".encode("latin-1")41 response = httpx.Response(200, content=content, headers=headers)44 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)45 assert response.text == "Latin 1: ÿ"46 assert response.encoding == "latin-1"4748
1 unmodified line
50 """51 Autodetect encoding if there is no charset info in a Content-Type header.52 """53 content = "おはようございます。".encode("EUC-JP")51 response = httpx.Response(200, content=content)54 response = httpx.Response(200, content=content, request=REQUEST)55 assert response.text == "おはようございます。"56 assert response.encoding == "EUC-JP"5758
2 unmodified lines
61 Fallback to autodetection if we get an invalid charset in the Content-Type header.62 """63 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}64 content = "おはようございます。".encode("EUC-JP")62 response = httpx.Response(200, content=content, headers=headers)65 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)66 assert response.text == "おはようございます。"67 assert response.encoding == "EUC-JP"6869
3 unmodified lines
73 See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.174 """75 content = b"Hello, world!"76 headers = {"Content-Type": "text/plain"}74 response = httpx.Response(200, content=content, headers=headers)77 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)78 assert response.status_code == 20079 assert response.encoding == "iso-8859-1"80 assert response.text == "Hello, world!"81
1 unmodified line
83def test_response_default_encoding():84 """85 Default to utf-8 if all else fails.86 """84 response = httpx.Response(200, content=b"")87 response = httpx.Response(200, content=b"", request=REQUEST)88 assert response.text == ""89 assert response.encoding == "utf-8"9091
1 unmodified line
93 """94 Default to apparent encoding for non-text content-type headers.95 """96 headers = {"Content-Type": "image/png"}94 response = httpx.Response(200, content=b"xyz", headers=headers)97 response = httpx.Response(200, content=b"xyz", headers=headers, request=REQUEST)98 assert response.text == "xyz"99 assert response.encoding == "ascii"100101
1 unmodified line
103 headers = {104 "Content-Type": "text-plain; charset=utf-8"105 } # Deliberately incorrect charset106 response = httpx.Response(104 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers107 200, content="Latin 1: ÿ".encode("latin-1"), headers=headers, request=REQUEST,108 )109 response.encoding = "latin-1"110 assert response.text == "Latin 1: ÿ"111 assert response.encoding == "latin-1"112113114def test_response_force_encoding():112 response = httpx.Response(200, content="Snowman: ☃".encode("utf-8"))115 response = httpx.Response(116 200, content="Snowman: ☃".encode("utf-8"), request=REQUEST117 )118 response.encoding = "iso-8859-1"119 assert response.status_code == 200120 assert response.reason_phrase == "OK"121 assert response.text == "Snowman: â\x98\x83"
1 unmodified line
123124125@pytest.mark.asyncio126async def test_read_response():122 response = httpx.Response(200, content=b"Hello, world!")127 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)128129 assert response.status_code == 200130 assert response.text == "Hello, world!"131 assert response.encoding == "ascii"
7 unmodified lines
139140141@pytest.mark.asyncio142async def test_raw_interface():138 response = httpx.Response(200, content=b"Hello, world!")143 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)144145 raw = b""146 async for part in response.aiter_raw():147 raw += part
1 unmodified line
149150151@pytest.mark.asyncio152async def test_bytes_interface():148 response = httpx.Response(200, content=b"Hello, world!")153 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)154155 content = b""156 async for part in response.aiter_bytes():157 content += part
1 unmodified line
159160161@pytest.mark.asyncio162async def test_text_interface():158 response = httpx.Response(200, content=b"Hello, world!")163 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)164165 await response.read()166167 content = ""
3 unmodified lines
171172173@pytest.mark.asyncio174async def test_lines_interface():170 response = httpx.Response(200, content=b"Hello,\nworld!")175 response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)176177 await response.read()178179 content = []
3 unmodified lines
183184185@pytest.mark.asyncio186async def test_stream_interface_after_read():182 response = httpx.Response(200, content=b"Hello, world!")187 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)188189 await response.read()190191 content = b""
4 unmodified lines
196197@pytest.mark.asyncio198async def test_streaming_response():199 stream = AsyncIteratorStream(aiterator=async_streaming_body())195 response = httpx.Response(200, stream=stream)200 response = httpx.Response(200, stream=stream, request=REQUEST)201202 assert response.status_code == 200203 assert not response.is_closed204
6 unmodified lines
211212@pytest.mark.asyncio213async def test_cannot_read_after_stream_consumed():214 stream = AsyncIteratorStream(aiterator=async_streaming_body())210 response = httpx.Response(200, stream=stream)215 response = httpx.Response(200, stream=stream, request=REQUEST)216217 content = b""218 async for part in response.aiter_bytes():219 content += part
4 unmodified lines
224225@pytest.mark.asyncio226async def test_cannot_read_after_response_closed():227 stream = AsyncIteratorStream(aiterator=async_streaming_body())223 response = httpx.Response(200, stream=stream)228 response = httpx.Response(200, stream=stream, request=REQUEST)229230 await response.close()231232 with pytest.raises(httpx.ResponseClosed):233 await response.read()234235236def test_unknown_status_code():232 response = httpx.Response(600)237 response = httpx.Response(600, request=REQUEST)238 assert response.status_code == 600239 assert response.reason_phrase == ""240 assert response.text == ""241
1 unmodified line
243def test_json_with_specified_encoding():244 data = {"greeting": "hello", "recipient": "world"}245 content = json.dumps(data).encode("utf-16")246 headers = {"Content-Type": "application/json, charset=utf-16"}242 response = httpx.Response(200, content=content, headers=headers)247 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)248 assert response.json() == data249250251def test_json_with_options():252 data = {"greeting": "hello", "recipient": "world", "amount": 1}253 content = json.dumps(data).encode("utf-16")254 headers = {"Content-Type": "application/json, charset=utf-16"}250 response = httpx.Response(200, content=content, headers=headers)255 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)256 assert response.json(parse_int=str)["amount"] == "1"257258259def test_json_without_specified_encoding():260 data = {"greeting": "hello", "recipient": "world"}261 content = json.dumps(data).encode("utf-32-be")262 headers = {"Content-Type": "application/json"}258 response = httpx.Response(200, content=content, headers=headers)263 response = httpx.Response(200, content=content, headers=headers, request=REQUEST)264 assert response.json() == data265266267def test_json_without_specified_encoding_decode_error():
1 unmodified line
269 content = json.dumps(data).encode("utf-32-be")270 headers = {"Content-Type": "application/json"}271 # force incorrect guess from `guess_json_utf` to trigger error272 with mock.patch("httpx.models.guess_json_utf", return_value="utf-32"):268 response = httpx.Response(200, content=content, headers=headers)273 response = httpx.Response(274 200, content=content, headers=headers, request=REQUEST275 )276 with pytest.raises(json.JSONDecodeError):277 response.json()278279
13 unmodified lines
293 ),294 ],295)296def test_link_headers(headers, expected):290 response = httpx.Response(200, content=None, headers=headers)297 response = httpx.Response(200, content=None, headers=headers, request=REQUEST)298 assert response.links == expected
modified:tests/test_decoders.py+28 added-11 removed
12 unmodified lines
13 LineDecoder,14 TextDecoder,15)1617REQUEST = httpx.Request("GET", "https://example.org")181920def test_deflate():21 body = b"test 123"22 compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)23 compressed_body = compressor.compress(body) + compressor.flush()2425 headers = [(b"Content-Encoding", b"deflate")]24 response = httpx.Response(200, headers=headers, content=compressed_body)26 response = httpx.Response(27 200, headers=headers, content=compressed_body, request=REQUEST28 )29 assert response.content == body303132def test_gzip():
1 unmodified line
34 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)35 compressed_body = compressor.compress(body) + compressor.flush()3637 headers = [(b"Content-Encoding", b"gzip")]34 response = httpx.Response(200, headers=headers, content=compressed_body)38 response = httpx.Response(39 200, headers=headers, content=compressed_body, request=REQUEST40 )41 assert response.content == body424344def test_brotli():45 body = b"test 123"46 compressed_body = brotli.compress(body)4748 headers = [(b"Content-Encoding", b"br")]43 response = httpx.Response(200, headers=headers, content=compressed_body)49 response = httpx.Response(50 200, headers=headers, content=compressed_body, request=REQUEST51 )52 assert response.content == body535455def test_multi():
7 unmodified lines
63 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()64 )6566 headers = [(b"Content-Encoding", b"deflate, gzip")]59 response = httpx.Response(200, headers=headers, content=compressed_body)67 response = httpx.Response(68 200, headers=headers, content=compressed_body, request=REQUEST69 )70 assert response.content == body717273def test_multi_with_identity():74 body = b"test 123"75 compressed_body = brotli.compress(body)7677 headers = [(b"Content-Encoding", b"br, identity")]68 response = httpx.Response(200, headers=headers, content=compressed_body)78 response = httpx.Response(79 200, headers=headers, content=compressed_body, request=REQUEST80 )81 assert response.content == body8283 headers = [(b"Content-Encoding", b"identity, br")]72 response = httpx.Response(200, headers=headers, content=compressed_body)84 response = httpx.Response(85 200, headers=headers, content=compressed_body, request=REQUEST86 )87 assert response.content == body888990@pytest.mark.asyncio
6 unmodified lines
97 yield compressor.flush()9899 headers = [(b"Content-Encoding", b"gzip")]100 stream = AsyncIteratorStream(aiterator=compress(body))87 response = httpx.Response(200, headers=headers, stream=stream)101 response = httpx.Response(200, headers=headers, stream=stream, request=REQUEST)102 assert not hasattr(response, "body")103 assert await response.read() == body104105106@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))107def test_empty_content(header_value):108 headers = [(b"Content-Encoding", header_value)]95 response = httpx.Response(200, headers=headers, content=b"")109 response = httpx.Response(200, headers=headers, content=b"", request=REQUEST)110 assert response.content == b""111112113@pytest.mark.parametrize(
10 unmodified lines
124 headers = [(b"Content-Encoding", header_value)]125 body = b"test 123"126 compressed_body = brotli.compress(body)[3:]127 with pytest.raises(httpx.DecodingError):114 response = httpx.Response(200, headers=headers, content=compressed_body)128 response = httpx.Response(129 200, headers=headers, content=compressed_body, request=REQUEST130 )131 response.content132133134@pytest.mark.parametrize(
20 unmodified lines
155 for chunk in data:156 yield chunk157158 stream = AsyncIteratorStream(aiterator=iterator())143 response = httpx.Response(200, stream=stream)159 response = httpx.Response(200, stream=stream, request=REQUEST)160 await response.read()161 assert response.text == (b"".join(data)).decode(encoding)162163
8 unmodified lines
172 response = httpx.Response(173 200,174 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],175 stream=stream,176 request=REQUEST,177 )178179 await response.read()180 assert "".join(response.text) == "トラベル"
53 unmodified lines
234def test_invalid_content_encoding_header():235 headers = [(b"Content-Encoding", b"invalid-header")]236 body = b"test 123"237221 response = httpx.Response(200, headers=headers, content=body)238 response = httpx.Response(200, headers=headers, content=body, request=REQUEST)239 assert response.content == body
modified:tests/test_multipart.py+1 added-1 removed
20 unmodified lines
21 cert: CertTypes = None,22 timeout: TimeoutTypes = None,23 ) -> httpx.Response:24 content = b"".join([part async for part in request.stream])25 return httpx.Response(200, content=content)25 return httpx.Response(200, content=content, request=request)262728@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))29@pytest.mark.asyncio
172 unmodified lines