Exception hierarchy (#1095)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Exception heirachy * Exception heirarchy * Formatting tweaks * Update httpx/_exceptions.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update httpx/_exceptions.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update httpx/_exceptions.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update httpx/_exceptions.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
authored by Tom Christie · committed by GitHub · parent 2ba9c1e · Browse files · 11 files·+218 added−108 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: Florimond Manca <florimond.manca@gmail.com>
Diff stats
11 files+218 added−108 removed
- tests:+14 added−9 removed
- other:+204 added−99 removed
Provenance
- Commit
9409900- Tree
c807b68- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
2ba9c1e
11 files changed+218 added−108 removed
modified:httpx/__init__.py+4 added-2 removed
17 unmodified lines18 ProtocolError,19 ProxyError,20 ReadError,21 ReadTimeout,22- RedirectError,22 RequestBodyUnavailable,23+ RequestError,24 RequestNotRead,25 ResponseClosed,26 ResponseNotRead,27 StreamConsumed,28 StreamError,29 TimeoutException,30 TooManyRedirects,31+ TransportError,32 WriteError,33 WriteTimeout,34 )35 from ._models import URL, Cookies, Headers, QueryParams, Request, Response40 unmodified lines76 "PoolTimeout",77 "ProtocolError",78 "ReadError",79 "ReadTimeout",79- "RedirectError",80+ "RequestError",81 "RequestBodyUnavailable",82 "ResponseClosed",83 "ResponseNotRead",84 "RequestNotRead",2 unmodified lines87 "StreamError",88 "ProxyError",89 "TimeoutException",90 "TooManyRedirects",91+ "TransportError",92 "WriteError",93 "WriteTimeout",94 "URL",95 "URLLib3Transport",9 unmodified linesmodified:httpx/_auth.py+16 added-8 removed
114 unmodified lines115 # If the response is not a 401 WWW-Authenticate, then we don't116 # need to build an authenticated request.117 return118 119- header = response.headers["www-authenticate"]120- challenge = self._parse_challenge(header)119+ challenge = self._parse_challenge(request, response)120 request.headers["Authorization"] = self._build_auth_header(request, challenge)121 yield request122 124- def _parse_challenge(self, header: str) -> "_DigestAuthChallenge":123+ def _parse_challenge(124+ self, request: Request, response: Response125+ ) -> "_DigestAuthChallenge":126 """127 Returns a challenge from a Digest WWW-Authenticate header.128 These take the form of:129 `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`130 """131+ header = response.headers["www-authenticate"]132+133 scheme, _, fields = header.partition(" ")134 if scheme.lower() != "digest":132- raise ProtocolError("Header does not start with 'Digest'")135+ message = "Header does not start with 'Digest'"136+ raise ProtocolError(message, request=request)137 138 header_dict: typing.Dict[str, str] = {}139 for field in parse_http_list(fields):140 key, value = field.strip().split("=", 1)8 unmodified lines149 return _DigestAuthChallenge(150 realm=realm, nonce=nonce, qop=qop, opaque=opaque, algorithm=algorithm151 )152 except KeyError as exc:149- raise ProtocolError("Malformed Digest WWW-Authenticate header") from exc153+ message = "Malformed Digest WWW-Authenticate header"154+ raise ProtocolError(message, request=request) from exc155 156 def _build_auth_header(157 self, request: Request, challenge: "_DigestAuthChallenge"158 ) -> str:16 unmodified lines175 HA1 = digest(A1)176 if challenge.algorithm.lower().endswith("-sess"):177 HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))178 174- qop = self._resolve_qop(challenge.qop)179+ qop = self._resolve_qop(challenge.qop, request=request)180 if qop is None:181 digest_data = [HA1, challenge.nonce, HA2]182 else:183 digest_data = [challenge.nonce, nc_value, cnonce, qop, HA2]41 unmodified lines225 header_value += template.format(field, to_str(value))226 227 return header_value228 224- def _resolve_qop(self, qop: typing.Optional[bytes]) -> typing.Optional[bytes]:229+ def _resolve_qop(230+ self, qop: typing.Optional[bytes], request: Request231+ ) -> typing.Optional[bytes]:232 if qop is None:233 return None234 qops = re.split(b", ?", qop)235 if b"auth" in qops:1 unmodified line237 238 if qops == [b"auth-int"]:239 raise NotImplementedError("Digest auth-int support is not yet implemented")240 234- raise ProtocolError(f'Unexpected qop value "{qop!r}" in digest auth')241+ message = f'Unexpected qop value "{qop!r}" in digest auth'242+ raise ProtocolError(message, request=request)243 244 245 class _DigestAuthChallenge:246 def __init__(12 unmodified linesmodified:httpx/_client.py+12 added-8 removed
322 unmodified lines323 url = URL(location)324 325 # Check that we can handle the scheme326 if url.scheme and url.scheme not in ("http", "https"):327- raise InvalidURL(f'Scheme "{url.scheme}" not supported.')327+ message = f'Scheme "{url.scheme}" not supported.'328+ raise InvalidURL(message, request=request)329 330 # Handle malformed 'Location' headers that are "absolute" form, have no host.331 # See: https://github.com/encode/httpx/issues/771332 if url.scheme and not url.host:204 unmodified lines537 keepalive_expiry=KEEPALIVE_EXPIRY,538 http2=http2,539 )540 540- def _transport_for_url(self, url: URL) -> httpcore.SyncHTTPTransport:541+ def _transport_for_url(self, request: Request) -> httpcore.SyncHTTPTransport:542 """543 Returns the transport instance that should be used for a given URL.544 This will either be the standard connection pool, or a proxy.545 """546+ url = request.url545- enforce_http_url(url)547+ enforce_http_url(request)548 549 if self._proxies and not should_not_be_proxied(url):550 for matcher, transport in self._proxies.items():551 if matcher.matches(url):39 unmodified lines591 allow_redirects: bool = True,592 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,593 ) -> Response:594 if request.url.scheme not in ("http", "https"):593- raise InvalidURL('URL scheme must be "http" or "https".')595+ message = 'URL scheme must be "http" or "https".'596+ raise InvalidURL(message, request=request)597 598 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)599 600 auth = self._build_auth(request, auth)83 unmodified lines684 def _send_single_request(self, request: Request, timeout: Timeout) -> Response:685 """686 Sends a single request, without handling any redirections.687 """685- transport = self._transport_for_url(request.url)688+ transport = self._transport_for_url(request)689 690 with map_exceptions(HTTPCORE_EXC_MAP, request=request):691 (692 http_version,368 unmodified lines1061 keepalive_expiry=KEEPALIVE_EXPIRY,1062 http2=http2,1063 )1064 1062- def _transport_for_url(self, url: URL) -> httpcore.AsyncHTTPTransport:1065+ def _transport_for_url(self, request: Request) -> httpcore.AsyncHTTPTransport:1066 """1067 Returns the transport instance that should be used for a given URL.1068 This will either be the standard connection pool, or a proxy.1069 """1070+ url = request.url1067- enforce_http_url(url)1071+ enforce_http_url(request)1072 1073 if self._proxies and not should_not_be_proxied(url):1074 for matcher, transport in self._proxies.items():1075 if matcher.matches(url):131 unmodified lines1207 ) -> Response:1208 """1209 Sends a single request, without handling any redirections.1210 """1207- transport = self._transport_for_url(request.url)1211+ transport = self._transport_for_url(request)1212 1213 with map_exceptions(HTTPCORE_EXC_MAP, request=request):1214 (1215 http_version,276 unmodified linesmodified:httpx/_decoders.py+26 added-15 removed
14 unmodified lines15 import brotli16 except ImportError: # pragma: nocover17 brotli = None18 19+if typing.TYPE_CHECKING: # pragma: no cover20+ from ._models import Request21 22+23 class Decoder:24+ def __init__(self, request: "Request") -> None:25+ self.request = request26+27 def decode(self, data: bytes) -> bytes:28 raise NotImplementedError() # pragma: nocover29 30 def flush(self) -> bytes:18 unmodified lines49 50 See: https://stackoverflow.com/questions/183869951 """52 47- def __init__(self) -> None:53+ def __init__(self, request: "Request") -> None:54+ self.request = request55 self.first_attempt = True56 self.decompressor = zlib.decompressobj()57 58 def decode(self, data: bytes) -> bytes:4 unmodified lines63 except zlib.error as exc:64 if was_first_attempt:65 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)66 return self.decode(data)60- raise DecodingError from exc67+ raise DecodingError(message=str(exc), request=self.request)68 69 def flush(self) -> bytes:70 try:71 return self.decompressor.flush()72 except zlib.error as exc: # pragma: nocover66- raise DecodingError from exc73+ raise DecodingError(message=str(exc), request=self.request)74 75 76 class GZipDecoder(Decoder):77 """1 unmodified line79 80 See: https://stackoverflow.com/questions/183869981 """82 76- def __init__(self) -> None:83+ def __init__(self, request: "Request") -> None:84+ self.request = request85 self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)86 87 def decode(self, data: bytes) -> bytes:88 try:89 return self.decompressor.decompress(data)90 except zlib.error as exc:83- raise DecodingError from exc91+ raise DecodingError(message=str(exc), request=self.request)92 93 def flush(self) -> bytes:94 try:95 return self.decompressor.flush()96 except zlib.error as exc: # pragma: nocover89- raise DecodingError from exc97+ raise DecodingError(message=str(exc), request=self.request)98 99 100 class BrotliDecoder(Decoder):101 """4 unmodified lines106 Supports both 'brotlipy' and 'Brotli' packages since they share an import107 name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'108 """109 102- def __init__(self) -> None:110+ def __init__(self, request: "Request") -> None:111 assert (112 brotli is not None113 ), "The 'brotlipy' or 'brotli' library must be installed to use 'BrotliDecoder'"114+ self.request = request115 self.decompressor = brotli.Decompressor()116 self.seen_data = False117 if hasattr(self.decompressor, "decompress"):118 self._decompress = self.decompressor.decompress6 unmodified lines125 self.seen_data = True126 try:127 return self._decompress(data)128 except brotli.error as exc:120- raise DecodingError from exc129+ raise DecodingError(message=str(exc), request=self.request)130 131 def flush(self) -> bytes:132 if not self.seen_data:133 return b""1 unmodified line135 if hasattr(self.decompressor, "finish"):136 self.decompressor.finish()137 return b""138 except brotli.error as exc: # pragma: nocover130- raise DecodingError from exc139+ raise DecodingError(message=str(exc), request=self.request)140 141 142 class MultiDecoder(Decoder):143 """24 unmodified lines168 """169 Handles incrementally decoding bytes into text170 """171 163- def __init__(self, encoding: typing.Optional[str] = None):172+ def __init__(self, request: "Request", encoding: typing.Optional[str] = None):173+ self.request = request174 self.decoder: typing.Optional[codecs.IncrementalDecoder] = (175 None if encoding is None else codecs.getincrementaldecoder(encoding)()176 )177 self.detector = chardet.universaldetector.UniversalDetector()25 unmodified lines203 text = self.decoder.decode(bytes(self.buffer), False)204 self.buffer = None205 206 return text197- except UnicodeDecodeError: # pragma: nocover198- raise DecodingError() from None207+ except UnicodeDecodeError as exc: # pragma: nocover208+ raise DecodingError(message=str(exc), request=self.request)209 210 def flush(self) -> str:211 try:212 if self.decoder is None:3 unmodified lines216 return ""217 return bytes(self.buffer).decode(self._detector_result())218 219 return self.decoder.decode(b"", True)210- except UnicodeDecodeError: # pragma: nocover211- raise DecodingError() from None220+ except UnicodeDecodeError as exc: # pragma: nocover221+ raise DecodingError(message=str(exc), request=self.request)222 223 def _detector_result(self) -> str:224 self.detector.close()225 result = self.detector.result["encoding"]226 if not result: # pragma: nocover217- raise DecodingError("Unable to determine encoding of content")227+ message = "Unable to determine encoding of content"228+ raise DecodingError(message, request=self.request)229 230 return result231 232 77 unmodified linesmodified:httpx/_exceptions.py+120 added-52 removed
1+"""2+Our exception hierarchy:3+4+* RequestError5+ + TransportError6+ - TimeoutException7+ · ConnectTimeout8+ · ReadTimeout9+ · WriteTimeout10+ · PoolTimeout11+ - NetworkError12+ · ConnectError13+ · ReadError14+ · WriteError15+ · CloseError16+ - ProxyError17+ - ProtocolError18+ + DecodingError19+ + TooManyRedirects20+ + RequestBodyUnavailable21+ + InvalidURL22+* HTTPStatusError23+* NotRedirectResponse24+* CookieConflict25+* StreamError26+ + StreamConsumed27+ + ResponseNotRead28+ + RequestNotRead29+ + ResponseClosed30+"""31 import contextlib32 import typing33 34 import httpcore1 unmodified line36 if typing.TYPE_CHECKING:37 from ._models import Request, Response # pragma: nocover38 39 10-class HTTPError(Exception):40+class RequestError(Exception):41 """12- Base class for all HTTPX exceptions.42+ Base class for all exceptions that may occur when issuing a `.request()`.43 """44 15- def __init__(16- self, *args: typing.Any, request: "Request" = None, response: "Response" = None17- ) -> None:18- super().__init__(*args)19- self._request = request or (response.request if response is not None else None)20- self.response = response45+ def __init__(self, message: str, *, request: "Request") -> None:46+ super().__init__(message)47+ self.request = request48 22- @property23- def request(self) -> "Request":24- # NOTE: this property exists so that a `Request` is exposed to type25- # checkers, instead of `Optional[Request]`.26- assert self._request is not None # Populated by the client.27- return self._request49 50+class TransportError(RequestError):51+ """52+ Base class for all exceptions that are mapped from the httpcore API.53+ """54 55+56 # Timeout exceptions...57 58 33-class TimeoutException(HTTPError):59+class TimeoutException(TransportError):60 """61 The base class for timeout errors.62 63 An operation has timed out.26 unmodified lines90 91 # Core networking exceptions...92 93 68-class NetworkError(HTTPError):94+class NetworkError(TransportError):95 """96 The base class for network-related errors.97 98 An error occurred while interacting with the network.26 unmodified lines125 126 # Other transport exceptions...127 128 103-class ProxyError(HTTPError):129+class ProxyError(TransportError):130 """131 An error occurred while proxying a request.132 """133 134 109-class ProtocolError(HTTPError):135+class ProtocolError(TransportError):136 """137 A protocol was violated by the server.138 """139 140 115-# HTTP exceptions...141+# Other request exceptions...142 143 118-class DecodingError(HTTPError):144+class DecodingError(RequestError):145 """146 Decoding of the response failed.147 """148 149 124-class HTTPStatusError(HTTPError):150+class TooManyRedirects(RequestError):151 """126- Response sent an error HTTP status.152+ Too many redirects.153 """154 129- def __init__(self, *args: typing.Any, response: "Response") -> None:130- super().__init__(*args)131- self._request = response.request132- self.response = response155 156+class RequestBodyUnavailable(RequestError):157+ """158+ Had to send the request again, but the request body was streaming, and is159+ no longer available.160+ """161 135-# Redirect exceptions...162 137-138-class RedirectError(HTTPError):163+class InvalidURL(RequestError):164 """140- Base class for HTTP redirect errors.165+ URL was missing a hostname, or was not one of HTTP/HTTPS.166 """167 168 144-class TooManyRedirects(RedirectError):169+# Client errors170+171+172+class HTTPStatusError(Exception):173 """146- Too many redirects.174+ Response sent an error HTTP status.175+176+ May be raised when calling `response.raise_for_status()`177 """178 179+ def __init__(180+ self, message: str, *, request: "Request", response: "Response"181+ ) -> None:182+ super().__init__(message)183+ self.request = request184+ self.response = response185 186+150-class NotRedirectResponse(RedirectError):187+class NotRedirectResponse(Exception):188 """189 Response was not a redirect response.190+191+ May be raised if `response.next()` is called without first192+ properly checking `response.is_redirect`.193 """194 195+ def __init__(self, message: str) -> None:196+ super().__init__(message)197 198+199+class CookieConflict(Exception):200+ """201+ Attempted to lookup a cookie by name, but multiple cookies existed.202+203+ Can occur when calling `response.cookies.get(...)`.204+ """205+206+ def __init__(self, message: str) -> None:207+ super().__init__(message)208+209+210 # Stream exceptions...211 212+# These may occur as the result of a programming error, by accessing213+# the request/response stream in an invalid manner.214 215+159-class StreamError(HTTPError):216+class StreamError(Exception):217 """218 The base class for stream exceptions.219 220 The developer made an error in accessing the request stream in221 an invalid way.222 """223 224+ def __init__(self, message: str) -> None:225+ super().__init__(message)226 168-class RequestBodyUnavailable(StreamError):169- """170- Had to send the request again, but the request body was streaming, and is171- no longer available.172- """227 174-228 class StreamConsumed(StreamError):229 """230 Attempted to read or stream response content, but the content has already231 been streamed.232 """233 234+ def __init__(self) -> None:235+ message = (236+ "Attempted to read or stream response content, but the content has "237+ "already been streamed."238+ )239+ super().__init__(message)240 241+242 class ResponseNotRead(StreamError):243 """244 Attempted to access response content, without having called `read()`245 after a streaming response.246 """247 248+ def __init__(self) -> None:249+ message = (250+ "Attempted to access response content, without having called `read()` "251+ "after a streaming response."252+ )253+ super().__init__(message)254 255+256 class RequestNotRead(StreamError):257 """258 Attempted to access request content, without having called `read()`.259 """260 261+ def __init__(self) -> None:262+ message = "Attempted to access request content, without having called `read()`."263+ super().__init__(message)264 265+266 class ResponseClosed(StreamError):267 """268 Attempted to read or stream response content, but the request has been269 closed.270 """271 272+ def __init__(self) -> None:273+ message = (274+ "Attempted to read or stream response content, but the request has "275+ "been closed."276+ )277+ super().__init__(message)278 202-# Other cases...279 280+# We're continuing to expose this earlier naming at the moment.281+# It is due to be deprecated. Don't use it.282+HTTPError = RequestError283 205-class InvalidURL(HTTPError):206- """207- URL was missing a hostname, or was not one of HTTP/HTTPS.208- """284 210-211-class CookieConflict(HTTPError):212- """213- Attempted to lookup a cookie by name, but multiple cookies existed.214- """215-216-285 @contextlib.contextmanager286 def map_exceptions(287 mapping: typing.Mapping[typing.Type[Exception], typing.Type[Exception]],288 **kwargs: typing.Any,36 unmodified linesmodified:httpx/_models.py+16 added-9 removed
796 unmodified lines797 for value in values:798 value = value.strip().lower()799 try:800 decoder_cls = SUPPORTED_DECODERS[value]801- decoders.append(decoder_cls())801+ decoders.append(decoder_cls(request=self.request))802 except KeyError:803 continue804 805 if len(decoders) == 1:806 self._decoder = decoders[0]807 elif len(decoders) > 1:808- self._decoder = MultiDecoder(decoders)808+ self._decoder = MultiDecoder(children=decoders)809 else:810- self._decoder = IdentityDecoder()810+ self._decoder = IdentityDecoder(request=self.request)811 812 return self._decoder813 814 @property14 unmodified lines829 )830 831 if codes.is_client_error(self.status_code):832 message = message.format(self, error_type="Client Error")833- raise HTTPStatusError(message, response=self)833+ raise HTTPStatusError(message, request=self.request, response=self)834 elif codes.is_server_error(self.status_code):835 message = message.format(self, error_type="Server Error")836- raise HTTPStatusError(message, response=self)836+ raise HTTPStatusError(message, request=self.request, response=self)837 838 def json(self, **kwargs: typing.Any) -> typing.Any:839 if self.charset_encoding is None and self.content and len(self.content) > 3:840 encoding = guess_json_utf(self.content)53 unmodified lines894 A str-iterator over the decoded response content895 that handles both gzip, deflate, etc but also detects the content's896 string encoding.897 """898- decoder = TextDecoder(encoding=self.charset_encoding)898+ decoder = TextDecoder(request=self.request, encoding=self.charset_encoding)899 for chunk in self.iter_bytes():900 yield decoder.decode(chunk)901 yield decoder.flush()902 23 unmodified lines926 """927 Get the next response from a redirect response.928 """929 if not self.is_redirect:930+ message = (931+ "Called .next(), but the response was not a redirect. "932+ "Calling code should check `response.is_redirect` first."933+ )930- raise NotRedirectResponse()934+ raise NotRedirectResponse(message)935 assert self.call_next is not None936 return self.call_next()937 938 def close(self) -> None:32 unmodified lines971 A str-iterator over the decoded response content972 that handles both gzip, deflate, etc but also detects the content's973 string encoding.974 """971- decoder = TextDecoder(encoding=self.charset_encoding)975+ decoder = TextDecoder(request=self.request, encoding=self.charset_encoding)976 async for chunk in self.aiter_bytes():977 yield decoder.decode(chunk)978 yield decoder.flush()979 23 unmodified lines1003 """1004 Get the next response from a redirect response.1005 """1006 if not self.is_redirect:1003- raise NotRedirectResponse()1007+ raise NotRedirectResponse(1008+ "Called .anext(), but the response was not a redirect. "1009+ "Calling code should check `response.is_redirect` first."1010+ )1011 assert self.call_next is not None1012 return await self.call_next()1013 1014 async def aclose(self) -> None:183 unmodified linesmodified:httpx/_utils.py+10 added-5 removed
16 unmodified lines17 from ._exceptions import InvalidURL18 from ._types import PrimitiveData19 20 if typing.TYPE_CHECKING: # pragma: no cover21- from ._models import URL21+ from ._models import URL, Request22 23 24 _HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}25 _HTML5_FORM_ENCODING_REPLACEMENTS.update(238 unmodified lines264 265 return typing.cast(Logger, logger)266 267 268-def enforce_http_url(url: "URL") -> None:268+def enforce_http_url(request: "Request") -> None:269 """270 Raise an appropriate InvalidURL for any non-HTTP URLs.271 """272+ url = request.url273+274 if not url.scheme:273- raise InvalidURL("No scheme included in URL.")275+ message = "No scheme included in URL."276+ raise InvalidURL(message, request=request)277 if not url.host:275- raise InvalidURL("No host included in URL.")278+ message = "No host included in URL."279+ raise InvalidURL(message, request=request)280 if url.scheme not in ("http", "https"):277- raise InvalidURL('URL scheme must be "http" or "https".')281+ message = 'URL scheme must be "http" or "https".'282+ raise InvalidURL(message, request=request)283 284 285 def port_or_default(url: "URL") -> typing.Optional[int]:286 if url.port is not None:236 unmodified linesmodified:tests/client/test_proxies.py+4 added-2 removed
92 unmodified lines93 ],94 )95 def test_transport_for_request(url, proxies, expected):96 client = httpx.AsyncClient(proxies=proxies)97+ request = httpx.Request(method="GET", url=url)97- transport = client._transport_for_url(httpx.URL(url))98+ transport = client._transport_for_url(request)99 100 if expected is None:101 assert transport is client._transport102 else:38 unmodified lines141 for name, value in env.items():142 monkeypatch.setenv(name, value)143 144 client = client_class()145+ request = httpx.Request(method="GET", url=url)144- transport = client._transport_for_url(httpx.URL(url))146+ transport = client._transport_for_url(request)147 148 if expected is None:149 assert transport == client._transport150 else:1 unmodified linemodified:tests/test_asgi.py+2 added-2 removed
64 unmodified lines65 66 67 @pytest.mark.usefixtures("async_environment")68 async def test_asgi_http_error():69- client = httpx.AsyncClient(app=partial(raise_exc, exc=httpx.HTTPError))70- with pytest.raises(httpx.HTTPError):69+ client = httpx.AsyncClient(app=partial(raise_exc, exc=RuntimeError))70+ with pytest.raises(RuntimeError):71 await client.get("http://www.example.org/")72 73 74 @pytest.mark.usefixtures("async_environment")37 unmodified linesmodified:tests/test_decoders.py+6 added-3 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")138- instance = decoder()139+ instance = decoder(request)140 assert instance.decode(b"") == b""141 assert instance.flush() == b""142 143 62 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+209- decoder = TextDecoder()212+ decoder = TextDecoder(request=request)213 assert decoder.flush() == ""214 212- decoder = TextDecoder()215+ decoder = TextDecoder(request=request)216 assert decoder.decode(b"") == ""217 assert decoder.flush() == ""218 219 75 unmodified linesmodified:tests/test_wsgi.py+2 added-2 removed
95 unmodified lines96 client.get("http://www.example.org/")97 98 99 def test_wsgi_http_error():100- client = httpx.Client(app=partial(raise_exc, exc=httpx.HTTPError))101- with pytest.raises(httpx.HTTPError):100+ client = httpx.Client(app=partial(raise_exc, exc=RuntimeError))101+ with pytest.raises(RuntimeError):102 client.get("http://www.example.org/")103 104 105 def test_wsgi_generator():13 unmodified lines