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
Provenance
- Commit
56c8eda- Tree
d39393d- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
9e88f2e
5 files changed+64 added−44 removed
modified:httpx/models.py+2 added-6 removed
659 unmodified lines660 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_code22 unmodified lines695 @property696 def url(self) -> typing.Optional[URL]:697 """698 Returns the URL for which the request was made.699-700- 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.url701 702 @property703 def content(self) -> bytes:704 if not hasattr(self, "_content"):123 unmodified lines828 829 @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 lines963 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)969 970 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore146 unmodified linesmodified:tests/dispatch/test_http2.py+1 added-1 removed
17 unmodified lines18 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)23 24 25 @pytest.mark.asyncio26 async def test_http2_get_request():123 unmodified linesmodified:tests/models/test_responses.py+32 added-25 removed
5 unmodified lines6 7 import httpx8 from httpx.content_streams import AsyncIteratorStream9 10+REQUEST = httpx.Request("GET", "https://example.org")11 12+13 def streaming_body():14 yield b"Hello, "15 yield b"world!"16 3 unmodified lines20 yield b"world!"21 22 23 def 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_error31 32 33 def 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]>"36 37 38 def test_response_content_type_encoding():1 unmodified line40 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"47 48 1 unmodified line50 """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"57 58 2 unmodified lines61 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"68 69 3 unmodified lines73 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 line83 def 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"90 91 1 unmodified line93 """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"100 101 1 unmodified line103 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"112 113 114 def 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 line123 124 125 @pytest.mark.asyncio126 async def test_read_response():122- response = httpx.Response(200, content=b"Hello, world!")127+ response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)128 129 assert response.status_code == 200130 assert response.text == "Hello, world!"131 assert response.encoding == "ascii"7 unmodified lines139 140 141 @pytest.mark.asyncio142 async def test_raw_interface():138- response = httpx.Response(200, content=b"Hello, world!")143+ response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)144 145 raw = b""146 async for part in response.aiter_raw():147 raw += part1 unmodified line149 150 151 @pytest.mark.asyncio152 async def test_bytes_interface():148- response = httpx.Response(200, content=b"Hello, world!")153+ response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)154 155 content = b""156 async for part in response.aiter_bytes():157 content += part1 unmodified line159 160 161 @pytest.mark.asyncio162 async def test_text_interface():158- response = httpx.Response(200, content=b"Hello, world!")163+ response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)164 165 await response.read()166 167 content = ""3 unmodified lines171 172 173 @pytest.mark.asyncio174 async def test_lines_interface():170- response = httpx.Response(200, content=b"Hello,\nworld!")175+ response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)176 177 await response.read()178 179 content = []3 unmodified lines183 184 185 @pytest.mark.asyncio186 async 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)188 189 await response.read()190 191 content = b""4 unmodified lines196 197 @pytest.mark.asyncio198 async 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)201 202 assert response.status_code == 200203 assert not response.is_closed204 6 unmodified lines211 212 @pytest.mark.asyncio213 async 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)216 217 content = b""218 async for part in response.aiter_bytes():219 content += part4 unmodified lines224 225 @pytest.mark.asyncio226 async 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)229 230 await response.close()231 232 with pytest.raises(httpx.ResponseClosed):233 await response.read()234 235 236 def 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 line243 def 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() == data249 250 251 def 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"257 258 259 def 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() == data265 266 267 def test_json_without_specified_encoding_decode_error():1 unmodified line269 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()278 279 13 unmodified lines293 ),294 ],295 )296 def 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 == expectedmodified:tests/test_decoders.py+28 added-11 removed
12 unmodified lines13 LineDecoder,14 TextDecoder,15 )16 17+REQUEST = httpx.Request("GET", "https://example.org")18 19+20 def 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()24 25 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 == body30 31 32 def test_gzip():1 unmodified line34 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)35 compressed_body = compressor.compress(body) + compressor.flush()36 37 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 == body42 43 44 def test_brotli():45 body = b"test 123"46 compressed_body = brotli.compress(body)47 48 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 == body53 54 55 def test_multi():7 unmodified lines63 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()64 )65 66 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 == body71 72 73 def test_multi_with_identity():74 body = b"test 123"75 compressed_body = brotli.compress(body)76 77 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 == body82 83 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 == body88 89 90 @pytest.mark.asyncio6 unmodified lines97 yield compressor.flush()98 99 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() == body104 105 106 @pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))107 def 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""111 112 113 @pytest.mark.parametrize(10 unmodified lines124 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.content132 133 134 @pytest.mark.parametrize(20 unmodified lines155 for chunk in data:156 yield chunk157 158 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)162 163 8 unmodified lines172 response = httpx.Response(173 200,174 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],175 stream=stream,176+ request=REQUEST,177 )178 179 await response.read()180 assert "".join(response.text) == "トラベル"53 unmodified lines234 def test_invalid_content_encoding_header():235 headers = [(b"Content-Encoding", b"invalid-header")]236 body = b"test 123"237 221- response = httpx.Response(200, headers=headers, content=body)238+ response = httpx.Response(200, headers=headers, content=body, request=REQUEST)239 assert response.content == bodymodified:tests/test_multipart.py+1 added-1 removed
20 unmodified lines21 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)26 27 28 @pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))29 @pytest.mark.asyncio172 unmodified lines