Skip to content
Myr

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

6 files+46 added−13 removed

modified:httpx/_client.py+8 added-1 removed
17 unmodified lines
18)19from ._content_streams import ContentStream20from ._exceptions import (21 HTTPCORE_EXC_MAP,22 InvalidURL,23 RemoteProtocolError,24 RequestBodyUnavailable,25 TooManyRedirects,26 map_exceptions,27)
313 unmodified lines
341 Return the URL for the redirect to follow.342 """343 location = response.headers["Location"]344345 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 None351352 # 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 lines
modified:httpx/_exceptions.py+10 added-8 removed
21 unmodified lines
22 + DecodingError23 + TooManyRedirects24 + RequestBodyUnavailable25 x HTTPStatusError26* InvalidURL27* NotRedirectResponse28* CookieConflict29* StreamError30 x StreamConsumed
199 unmodified lines
230 super().__init__(message, request=request)231 self.response = response232233234class InvalidURL(Exception):235 """236 URL is improperly formed or cannot be parsed.237 """238239 def __init__(self, message: str) -> None:240 super().__init__(message)241242243class NotRedirectResponse(Exception):244 """245 Response was not a redirect response.246
85 unmodified lines
332 )333 super().__init__(message)334335326# 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()`.`329330# We are currently still exposing this class, but it will be removed in 1.0.331InvalidURL = UnsupportedProtocol332333336@contextlib.contextmanager337def map_exceptions(338 mapping: typing.Mapping[typing.Type[Exception], typing.Type[Exception]],339 **kwargs: typing.Any,
39 unmodified lines
modified:httpx/_models.py+8 added-2 removed
9 unmodified lines
10from urllib.parse import parse_qsl, urlencode1112import chardet13import rfc398614import rfc3986.exceptions1516from .__version__ import __version__17from ._content_streams import ByteStream, ContentStream, encode18from ._decoders import (
6 unmodified lines
25)26from ._exceptions import (27 CookieConflict,28 HTTPStatusError,29 InvalidURL,30 NotRedirectResponse,31 RequestNotRead,32 ResponseClosed,33 ResponseNotRead,
24 unmodified lines
5859class 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 None6667 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 lines
188 authority = f"{userpass}@{authority}"189190 kwargs["authority"] = authority191186 return URL(self._uri_reference.copy_with(**kwargs).unsplit(),)192 return URL(self._uri_reference.copy_with(**kwargs).unsplit())193194 def join(self, url: URLTypes) -> "URL":195 """196 Return an absolute URL, using given this URL as the base.
1014 unmodified lines
modified:tests/client/test_redirects.py+13 added
8 unmodified lines
9 URL,10 AsyncClient,11 Client,12 NotRedirectResponse,13 RemoteProtocolError,14 RequestBodyUnavailable,15 TooManyRedirects,16 UnsupportedProtocol,17 codes,
57 unmodified lines
75 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"")7879 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"")8384 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 lines
255 assert len(response.history) == 1256257258@pytest.mark.usefixtures("async_environment")259async def test_invalid_redirect():260 client = AsyncClient(transport=AsyncMockTransport())261 with pytest.raises(RemoteProtocolError):262 await client.get("http://example.org/invalid_redirect")263264265@pytest.mark.usefixtures("async_environment")266async 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.OK
233 unmodified lines
modified:tests/models/test_url.py+6 added-1 removed
1import pytest23from httpx import URL3from httpx import URL, InvalidURL456@pytest.mark.parametrize(7 "given,idna,host,scheme,port",
176 unmodified lines
184 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"188189190def test_url_invalid():191 with pytest.raises(InvalidURL):192 URL("https://😇/")
modified:tests/test_api.py+1 added-1 removed
67 unmodified lines
68 assert response.http_version == "HTTP/1.1"697071def test_get_invalid_url():72 with pytest.raises(httpx.InvalidURL):72 with pytest.raises(httpx.UnsupportedProtocol):73 httpx.get("invalid://example.org")