Map rfc3986 exceptions (#1163)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Map rfc3896 exceptions
authored by Joe · committed by GitHub · parent 7edfe64 · Browse files · 6 files·+46 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+46 added−13 removed
- tests:+20 added−2 removed
- other:+26 added−11 removed
Provenance
- Commit
45de714- Tree
9284f77- Author
Joe <nigelchiang@outlook.com>- Committer
GitHub <noreply@github.com>- Parent
7edfe64
6 files changed+46 added−13 removed
modified:httpx/_client.py+8 added-1 removed
17 unmodified lines18 )19 from ._content_streams import ContentStream20 from ._exceptions import (21 HTTPCORE_EXC_MAP,22+ InvalidURL,23+ RemoteProtocolError,24 RequestBodyUnavailable,25 TooManyRedirects,26 map_exceptions,27 )313 unmodified lines341 Return the URL for the redirect to follow.342 """343 location = response.headers["Location"]344 345+ try:343- url = URL(location)346+ url = URL(location)347+ except InvalidURL as exc:348+ raise RemoteProtocolError(349+ f"Invalid URL in location header: {exc}.", request=request350+ ) from None351 352 # Handle malformed 'Location' headers that are "absolute" form, have no host.353 # See: https://github.com/encode/httpx/issues/771354 if url.scheme and not url.host:1182 unmodified linesmodified:httpx/_exceptions.py+10 added-8 removed
21 unmodified lines22 + DecodingError23 + TooManyRedirects24 + RequestBodyUnavailable25 x HTTPStatusError26+* InvalidURL27 * NotRedirectResponse28 * CookieConflict29 * StreamError30 x StreamConsumed199 unmodified lines230 super().__init__(message, request=request)231 self.response = response232 233 234+class InvalidURL(Exception):235+ """236+ URL is improperly formed or cannot be parsed.237+ """238+239+ def __init__(self, message: str) -> None:240+ super().__init__(message)241+242+243 class NotRedirectResponse(Exception):244 """245 Response was not a redirect response.246 85 unmodified lines332 )333 super().__init__(message)334 335 326-# The `InvalidURL` class is no longer required. It was being used to enforce only327-# 'http'/'https' URLs being requested, but is now treated instead at the328-# transport layer using `UnsupportedProtocol()`.`329-330-# We are currently still exposing this class, but it will be removed in 1.0.331-InvalidURL = UnsupportedProtocol332-333-336 @contextlib.contextmanager337 def map_exceptions(338 mapping: typing.Mapping[typing.Type[Exception], typing.Type[Exception]],339 **kwargs: typing.Any,39 unmodified linesmodified:httpx/_models.py+8 added-2 removed
9 unmodified lines10 from urllib.parse import parse_qsl, urlencode11 12 import chardet13 import rfc398614+import rfc3986.exceptions15 16 from .__version__ import __version__17 from ._content_streams import ByteStream, ContentStream, encode18 from ._decoders import (6 unmodified lines25 )26 from ._exceptions import (27 CookieConflict,28 HTTPStatusError,29+ InvalidURL,30 NotRedirectResponse,31 RequestNotRead,32 ResponseClosed,33 ResponseNotRead,24 unmodified lines58 59 class URL:60 def __init__(self, url: URLTypes = "", params: QueryParamTypes = None) -> None:61 if isinstance(url, str):62+ try:60- self._uri_reference = rfc3986.iri_reference(url).encode()63+ self._uri_reference = rfc3986.iri_reference(url).encode()64+ except rfc3986.exceptions.InvalidAuthority as exc:65+ raise InvalidURL(message=str(exc)) from None66+67 if self.is_absolute_url:68 # We don't want to normalize relative URLs, since doing so69 # removes any leading `../` portion.70 self._uri_reference = self._uri_reference.normalize()117 unmodified lines188 authority = f"{userpass}@{authority}"189 190 kwargs["authority"] = authority191 186- return URL(self._uri_reference.copy_with(**kwargs).unsplit(),)192+ return URL(self._uri_reference.copy_with(**kwargs).unsplit())193 194 def join(self, url: URLTypes) -> "URL":195 """196 Return an absolute URL, using given this URL as the base.1014 unmodified linesmodified:tests/client/test_redirects.py+13 added
8 unmodified lines9 URL,10 AsyncClient,11 Client,12 NotRedirectResponse,13+ RemoteProtocolError,14 RequestBodyUnavailable,15 TooManyRedirects,16 UnsupportedProtocol,17 codes,57 unmodified lines75 status_code = codes.SEE_OTHER76 headers = [(b"location", b"https://:443/")]77 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")78 79+ elif path == b"/invalid_redirect":80+ status_code = codes.SEE_OTHER81+ headers = [(b"location", "https://😇/".encode("utf-8"))]82+ return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")83+84 elif path == b"/no_scheme_redirect":85 status_code = codes.SEE_OTHER86 headers = [(b"location", b"//example.org/")]87 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")167 unmodified lines255 assert len(response.history) == 1256 257 258 @pytest.mark.usefixtures("async_environment")259+async def test_invalid_redirect():260+ client = AsyncClient(transport=AsyncMockTransport())261+ with pytest.raises(RemoteProtocolError):262+ await client.get("http://example.org/invalid_redirect")263+264+265+@pytest.mark.usefixtures("async_environment")266 async def test_no_scheme_redirect():267 client = AsyncClient(transport=AsyncMockTransport())268 response = await client.get("https://example.org/no_scheme_redirect")269 assert response.status_code == codes.OK233 unmodified linesmodified:tests/models/test_url.py+6 added-1 removed
1 import pytest2 3-from httpx import URL3+from httpx import URL, InvalidURL4 5 6 @pytest.mark.parametrize(7 "given,idna,host,scheme,port",176 unmodified lines184 new = url.copy_with(**copy_with_kwargs)185 for k, v in copy_with_kwargs.items():186 assert getattr(new, k) == v187 assert str(new) == "https://username:password@example.net:444"188+189+190+def test_url_invalid():191+ with pytest.raises(InvalidURL):192+ URL("https://😇/")modified:tests/test_api.py+1 added-1 removed
67 unmodified lines68 assert response.http_version == "HTTP/1.1"69 70 71 def test_get_invalid_url():72- with pytest.raises(httpx.InvalidURL):72+ with pytest.raises(httpx.UnsupportedProtocol):73 httpx.get("invalid://example.org")