Make the response's request parameter optional (#1238)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Make the response's request parameter optional * Fix _models coverage * Move DecodingError in _models * Update httpx/_models.py * Update _models.py * Update test_responses.py * Update test_responses.py
authored by tbascoul · committed by GitHub · parent 33d339a · Browse files · 4 files·+171 added−66 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Tom Christie <tom@tomchristie.com>
Diff stats
4 files+171 added−66 removed
- tests:+82 added−8 removed
- other:+89 added−58 removed
Provenance
- Commit
e0b4528- Tree
9ce0de7- Author
tbascoul <tbascoul+github@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
33d339a
4 files changed+171 added−66 removed
modified:httpx/_decoders.py+13 added-26 removed
7 unmodified lines8 import zlib9 10 import chardet11 12-from ._exceptions import DecodingError13-12 try:13 import brotli14 except ImportError: # pragma: nocover15 brotli = None16 19-if typing.TYPE_CHECKING: # pragma: no cover20- from ._models import Request17 22-18 class Decoder:24- def __init__(self, request: "Request") -> None:25- self.request = request26-19 def decode(self, data: bytes) -> bytes:20 raise NotImplementedError() # pragma: nocover21 22 def flush(self) -> bytes:18 unmodified lines41 42 See: https://stackoverflow.com/questions/183869943 """44 53- def __init__(self, request: "Request") -> None:54- self.request = request45+ def __init__(self) -> None:46 self.first_attempt = True47 self.decompressor = zlib.decompressobj()48 49 def decode(self, data: bytes) -> bytes:4 unmodified lines54 except zlib.error as exc:55 if was_first_attempt:56 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)57 return self.decode(data)67- raise DecodingError(message=str(exc), request=self.request)58+ raise ValueError(str(exc))59 60 def flush(self) -> bytes:61 try:62 return self.decompressor.flush()63 except zlib.error as exc: # pragma: nocover73- raise DecodingError(message=str(exc), request=self.request)64+ raise ValueError(str(exc))65 66 67 class GZipDecoder(Decoder):68 """1 unmodified line70 71 See: https://stackoverflow.com/questions/183869972 """73 83- def __init__(self, request: "Request") -> None:84- self.request = request74+ def __init__(self) -> None:75 self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)76 77 def decode(self, data: bytes) -> bytes:78 try:79 return self.decompressor.decompress(data)80 except zlib.error as exc:91- raise DecodingError(message=str(exc), request=self.request)81+ raise ValueError(str(exc))82 83 def flush(self) -> bytes:84 try:85 return self.decompressor.flush()86 except zlib.error as exc: # pragma: nocover97- raise DecodingError(message=str(exc), request=self.request)87+ raise ValueError(str(exc))88 89 90 class BrotliDecoder(Decoder):91 """4 unmodified lines96 Supports both 'brotlipy' and 'Brotli' packages since they share an import97 name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'98 """99 110- def __init__(self, request: "Request") -> None:100+ def __init__(self) -> None:101 if brotli is None: # pragma: nocover102 raise ImportError(103 "Using 'BrotliDecoder', but the 'brotlipy' or 'brotli' library "104 "is not installed."105 "Make sure to install httpx using `pip install httpx[brotli]`."106 ) from None107 118- self.request = request108 self.decompressor = brotli.Decompressor()109 self.seen_data = False110 if hasattr(self.decompressor, "decompress"):111 self._decompress = self.decompressor.decompress6 unmodified lines118 self.seen_data = True119 try:120 return self._decompress(data)121 except brotli.error as exc:133- raise DecodingError(message=str(exc), request=self.request)122+ raise ValueError(str(exc))123 124 def flush(self) -> bytes:125 if not self.seen_data:126 return b""1 unmodified line128 if hasattr(self.decompressor, "finish"):129 self.decompressor.finish()130 return b""131 except brotli.error as exc: # pragma: nocover143- raise DecodingError(message=str(exc), request=self.request)132+ raise ValueError(str(exc))133 134 135 class MultiDecoder(Decoder):136 """24 unmodified lines161 """162 Handles incrementally decoding bytes into text163 """164 176- def __init__(self, request: "Request", encoding: typing.Optional[str] = None):177- self.request = request165+ def __init__(self, encoding: typing.Optional[str] = None):166 self.decoder: typing.Optional[codecs.IncrementalDecoder] = (167 None if encoding is None else codecs.getincrementaldecoder(encoding)()168 )169 self.detector = chardet.universaldetector.UniversalDetector()26 unmodified lines196 self.buffer = None197 198 return text199 except UnicodeDecodeError as exc: # pragma: nocover212- raise DecodingError(message=str(exc), request=self.request)200+ raise ValueError(str(exc))201 202 def flush(self) -> str:203 try:204 if self.decoder is None:4 unmodified lines209 return bytes(self.buffer).decode(self._detector_result())210 211 return self.decoder.decode(b"", True)212 except UnicodeDecodeError as exc: # pragma: nocover225- raise DecodingError(message=str(exc), request=self.request)213+ raise ValueError(str(exc))214 215 def _detector_result(self) -> str:216 self.detector.close()217 result = self.detector.result["encoding"]218 if not result: # pragma: nocover231- message = "Unable to determine encoding of content"232- raise DecodingError(message, request=self.request)219+ raise ValueError("Unable to determine encoding of content")220 221 return result222 223 77 unmodified linesmodified:httpx/_models.py+76 added-32 removed
1 import cgi2+import contextlib3 import datetime4 import email.message5 import json as jsonlib6 import typing19 unmodified lines26 )27 from ._exceptions import (28 HTTPCORE_EXC_MAP,29 CookieConflict,30+ DecodingError,31 HTTPStatusError,32 InvalidURL,33 NotRedirectResponse,34 RequestNotRead,655 unmodified lines690 def __init__(691 self,692 status_code: int,693 *,692- request: Request,694+ request: Request = None,695 http_version: str = None,696 headers: HeaderTypes = None,697 stream: ContentStream = None,698 content: bytes = None,2 unmodified lines701 self.status_code = status_code702 self.http_version = http_version703 self.headers = Headers(headers)704 703- self.request = request705+ self._request: typing.Optional[Request] = request706+707 self.call_next: typing.Optional[typing.Callable] = None708 709 self.history = [] if history is None else list(history)710 18 unmodified lines729 )730 return self._elapsed731 732 @property733+ def request(self) -> Request:734+ """735+ Returns the request instance associated to the current response.736+ """737+ if self._request is None:738+ raise RuntimeError(739+ "The request instance has not been set on this response."740+ )741+ return self._request742+743+ @request.setter744+ def request(self, value: Request) -> None:745+ self._request = value746+747+ @property748 def reason_phrase(self) -> str:749 return codes.get_reason_phrase(self.status_code)750 751 @property76 unmodified lines828 for value in values:829 value = value.strip().lower()830 try:831 decoder_cls = SUPPORTED_DECODERS[value]814- decoders.append(decoder_cls(request=self.request))832+ decoders.append(decoder_cls())833 except KeyError:834 continue835 836 if len(decoders) == 1:837 self._decoder = decoders[0]838 elif len(decoders) > 1:839 self._decoder = MultiDecoder(children=decoders)840 else:823- self._decoder = IdentityDecoder(request=self.request)841+ self._decoder = IdentityDecoder()842 843 return self._decoder844 845 @property12 unmodified lines858 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"859 "For more information check: https://httpstatuses.com/{0.status_code}"860 )861 862+ request = self._request863+ if request is None:864+ raise RuntimeError(865+ "Cannot call `raise_for_status` as the request "866+ "instance has not been set on this response."867+ )868+869 if codes.is_client_error(self.status_code):870 message = message.format(self, error_type="Client Error")846- raise HTTPStatusError(message, request=self.request, response=self)871+ raise HTTPStatusError(message, request=request, response=self)872 elif codes.is_server_error(self.status_code):873 message = message.format(self, error_type="Server Error")849- raise HTTPStatusError(message, request=self.request, response=self)874+ raise HTTPStatusError(message, request=request, response=self)875 876 def json(self, **kwargs: typing.Any) -> typing.Any:877 if self.charset_encoding is None and self.content and len(self.content) > 3:878 encoding = guess_json_utf(self.content)27 unmodified lines906 907 def __repr__(self) -> str:908 return f"<Response [{self.status_code} {self.reason_phrase}]>"909 910+ @contextlib.contextmanager911+ def _wrap_decoder_errors(self) -> typing.Iterator[None]:912+ # If the response has an associated request instance, we want decoding913+ # errors to be raised as proper `httpx.DecodingError` exceptions.914+ try:915+ yield916+ except ValueError as exc:917+ if self._request is None:918+ raise exc919+ raise DecodingError(message=str(exc), request=self.request) from exc920+921 def read(self) -> bytes:922 """923 Read and return the response content.924 """8 unmodified lines933 """934 if hasattr(self, "_content"):935 yield self._content936 else:937+ with self._wrap_decoder_errors():901- for chunk in self.iter_raw():902- yield self.decoder.decode(chunk)903- yield self.decoder.flush()938+ for chunk in self.iter_raw():939+ yield self.decoder.decode(chunk)940+ yield self.decoder.flush()941 942 def iter_text(self) -> typing.Iterator[str]:943 """944 A str-iterator over the decoded response content945 that handles both gzip, deflate, etc but also detects the content's946 string encoding.947 """911- decoder = TextDecoder(request=self.request, encoding=self.charset_encoding)912- for chunk in self.iter_bytes():913- yield decoder.decode(chunk)914- yield decoder.flush()948+ decoder = TextDecoder(encoding=self.charset_encoding)949+ with self._wrap_decoder_errors():950+ for chunk in self.iter_bytes():951+ yield decoder.decode(chunk)952+ yield decoder.flush()953 954 def iter_lines(self) -> typing.Iterator[str]:955 decoder = LineDecoder()956+ with self._wrap_decoder_errors():918- for text in self.iter_text():919- for line in decoder.decode(text):957+ for text in self.iter_text():958+ for line in decoder.decode(text):959+ yield line960+ for line in decoder.flush():961 yield line921- for line in decoder.flush():922- yield line962 963 def iter_raw(self) -> typing.Iterator[bytes]:964 """965 A byte-iterator over the raw response content.3 unmodified lines969 if self.is_closed:970 raise ResponseClosed()971 972 self.is_stream_consumed = True934- with map_exceptions(HTTPCORE_EXC_MAP, request=self.request):973+ with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):974 for part in self._raw_stream:975 yield part976 self.close()977 16 unmodified lines994 Automatically called if the response body is read to completion.995 """996 if not self.is_closed:997 self.is_closed = True998+ if self._request is not None:959- self._elapsed = self.request.timer.elapsed999+ self._elapsed = self.request.timer.elapsed1000 self._raw_stream.close()1001 1002 async def aread(self) -> bytes:1003 """10 unmodified lines1014 """1015 if hasattr(self, "_content"):1016 yield self._content1017 else:1018+ with self._wrap_decoder_errors():978- async for chunk in self.aiter_raw():979- yield self.decoder.decode(chunk)980- yield self.decoder.flush()1019+ async for chunk in self.aiter_raw():1020+ yield self.decoder.decode(chunk)1021+ yield self.decoder.flush()1022 1023 async def aiter_text(self) -> typing.AsyncIterator[str]:1024 """1025 A str-iterator over the decoded response content1026 that handles both gzip, deflate, etc but also detects the content's1027 string encoding.1028 """988- decoder = TextDecoder(request=self.request, encoding=self.charset_encoding)989- async for chunk in self.aiter_bytes():990- yield decoder.decode(chunk)991- yield decoder.flush()1029+ decoder = TextDecoder(encoding=self.charset_encoding)1030+ with self._wrap_decoder_errors():1031+ async for chunk in self.aiter_bytes():1032+ yield decoder.decode(chunk)1033+ yield decoder.flush()1034 1035 async def aiter_lines(self) -> typing.AsyncIterator[str]:1036 decoder = LineDecoder()1037+ with self._wrap_decoder_errors():995- async for text in self.aiter_text():996- for line in decoder.decode(text):1038+ async for text in self.aiter_text():1039+ for line in decoder.decode(text):1040+ yield line1041+ for line in decoder.flush():1042 yield line998- for line in decoder.flush():999- yield line1043 1044 async def aiter_raw(self) -> typing.AsyncIterator[bytes]:1045 """1046 A byte-iterator over the raw response content.3 unmodified lines1050 if self.is_closed:1051 raise ResponseClosed()1052 1053 self.is_stream_consumed = True1011- with map_exceptions(HTTPCORE_EXC_MAP, request=self.request):1054+ with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1055 async for part in self._raw_stream:1056 yield part1057 await self.aclose()1058 15 unmodified lines1074 Automatically called if the response body is read to completion.1075 """1076 if not self.is_closed:1077 self.is_closed = True1078+ if self._request is not None:1035- self._elapsed = self.request.timer.elapsed1079+ self._elapsed = self.request.timer.elapsed1080 await self._raw_stream.aclose()1081 1082 1083 class Cookies(MutableMapping):178 unmodified linesmodified:tests/models/test_responses.py+77 added-1 removed
1 import datetime2 import json3 from unittest import mock4 5+import brotli6 import pytest7 8 import httpx9 from httpx._content_streams import AsyncIteratorStream, IteratorStream21 unmodified lines31 assert response.elapsed >= datetime.timedelta(0)32 assert not response.is_error33 34 35+def test_raise_for_status():36+ # 2xx status codes are not an error.37+ response = httpx.Response(200, request=REQUEST)38+ response.raise_for_status()39+40+ # 4xx status codes are a client error.41+ response = httpx.Response(403, request=REQUEST)42+ with pytest.raises(httpx.HTTPStatusError):43+ response.raise_for_status()44+45+ # 5xx status codes are a server error.46+ response = httpx.Response(500, request=REQUEST)47+ with pytest.raises(httpx.HTTPStatusError):48+ response.raise_for_status()49+50+ # Calling .raise_for_status without setting a request instance is51+ # not valid. Should raise a runtime error.52+ response = httpx.Response(200)53+ with pytest.raises(RuntimeError):54+ response.raise_for_status()55+56+57 def test_response_repr():58 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)59 assert repr(response) == "<Response [200 OK]>"60 333 unmodified lines394 with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):395 response = httpx.Response(396 200, content=content, headers=headers, request=REQUEST397 )375- with pytest.raises(json.JSONDecodeError):398+ with pytest.raises(json.decoder.JSONDecodeError):399 response.json()400 401 402+def test_json_without_specified_encoding_value_error():403+ data = {"greeting": "hello", "recipient": "world"}404+ content = json.dumps(data).encode("utf-32-be")405+ headers = {"Content-Type": "application/json"}406+ # force incorrect guess from `guess_json_utf` to trigger error407+ with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):408+ response = httpx.Response(200, content=content, headers=headers)409+ with pytest.raises(ValueError):410+ response.json()411+412+413 @pytest.mark.parametrize(414 "headers, expected",415 [416 (11 unmodified lines428 )429 def test_link_headers(headers, expected):430 response = httpx.Response(200, content=None, headers=headers, request=REQUEST)431 assert response.links == expected432+433+434+@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))435+def test_decode_error_with_request(header_value):436+ headers = [(b"Content-Encoding", header_value)]437+ body = b"test 123"438+ compressed_body = brotli.compress(body)[3:]439+ with pytest.raises(httpx.DecodingError):440+ httpx.Response(200, headers=headers, content=compressed_body, request=REQUEST)441+442+443+@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))444+def test_value_error_without_request(header_value):445+ headers = [(b"Content-Encoding", header_value)]446+ body = b"test 123"447+ compressed_body = brotli.compress(body)[3:]448+ with pytest.raises(ValueError):449+ httpx.Response(200, headers=headers, content=compressed_body)450+451+452+def test_response_with_unset_request():453+ response = httpx.Response(200, content=b"Hello, world!")454+455+ assert response.status_code == 200456+ assert response.reason_phrase == "OK"457+ assert response.text == "Hello, world!"458+ assert not response.is_error459+460+461+def test_set_request_after_init():462+ response = httpx.Response(200, content=b"Hello, world!")463+464+ response.request = REQUEST465+466+ assert response.request == REQUEST467+468+469+def test_cannot_access_unset_request():470+ response = httpx.Response(200, content=b"Hello, world!")471+472+ with pytest.raises(RuntimeError):473+ assert response.request is not Nonemodified:tests/test_decoders.py+5 added-7 removed
133 unmodified lines134 @pytest.mark.parametrize(135 "decoder", (BrotliDecoder, DeflateDecoder, GZipDecoder, IdentityDecoder)136 )137 def test_decoders_empty_cases(decoder):138- request = httpx.Request(method="GET", url="https://www.example.com")139- instance = decoder(request)140- assert instance.decode(b"") == b""138+ response = httpx.Response(content=b"", status_code=200)139+ instance = decoder()140+ assert instance.decode(response.content) == b""141 assert instance.flush() == b""142 143 144 @pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))61 unmodified lines206 assert "".join(response.text) == "トラベル"207 208 209 def test_text_decoder_empty_cases():210- request = httpx.Request(method="GET", url="https://www.example.com")211-212- decoder = TextDecoder(request=request)210+ decoder = TextDecoder()211 assert decoder.flush() == ""212 215- decoder = TextDecoder(request=request)213+ decoder = TextDecoder()214 assert decoder.decode(b"") == ""215 assert decoder.flush() == ""216 217 75 unmodified lines