From 42c66863d0c2c65d9c43e81e76f9af4fad160e11 Mon Sep 17 00:00:00 2001 From: Tyler Wozniak Date: Fri, 4 Sep 2020 14:14:59 -0700 Subject: [PATCH] Raise a proper type error on invalid URL type (#1259) * Added test for expected URL class behavior * Updated URL class, tests pass * Updated to include type in error message --- httpx/_models.py | 6 +++++- tests/models/test_url.py | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/httpx/_models.py b/httpx/_models.py index 17ba955890..5b6a9b6571 100644 --- a/httpx/_models.py +++ b/httpx/_models.py @@ -71,8 +71,12 @@ def __init__(self, url: URLTypes = "", params: QueryParamTypes = None) -> None: # We don't want to normalize relative URLs, since doing so # removes any leading `../` portion. self._uri_reference = self._uri_reference.normalize() - else: + elif isinstance(url, URL): self._uri_reference = url._uri_reference + else: + raise TypeError( + f"Invalid type for url. Expected str or httpx.URL, got {type(url)}" + ) # Add any query parameters, merging with any in the URL if needed. if params: diff --git a/tests/models/test_url.py b/tests/models/test_url.py index fa75e556a6..8d34a75a79 100644 --- a/tests/models/test_url.py +++ b/tests/models/test_url.py @@ -204,3 +204,11 @@ def test_url_copywith_for_userinfo(): def test_url_invalid(): with pytest.raises(httpx.InvalidURL): httpx.URL("https://😇/") + + +def test_url_invalid_type(): + class ExternalURLClass: # representing external URL class + pass + + with pytest.raises(TypeError): + httpx.URL(ExternalURLClass()) # type: ignore