From 790f7eb84355c2c33c3f55834cf4624b9f678ddd Mon Sep 17 00:00:00 2001 From: MadhurBagdare <85842108+MadhurBagdare@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:40:25 +0530 Subject: [PATCH] Raise InvalidURL when a request URL has a scheme but no host --- httpx/_client.py | 2 ++ tests/client/test_async_client.py | 1 - tests/client/test_client.py | 21 ++++++++++++++++++++- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/httpx/_client.py b/httpx/_client.py index 13cd933673..5c54dd4f67 100644 --- a/httpx/_client.py +++ b/httpx/_client.py @@ -394,6 +394,8 @@ def _merge_url(self, url: URL | str) -> URL: to create the URL used for the outgoing request. """ merge_url = URL(url) + if merge_url.scheme and not merge_url.host: + raise InvalidURL(f"Invalid URL {str(merge_url)!r}: missing host") if merge_url.is_relative_url: # To merge URLs we always append to the base URL. To get this # behaviour correct we always ensure the base URL ends in a '/' diff --git a/tests/client/test_async_client.py b/tests/client/test_async_client.py index 8d7eaa3c58..2b2ee8ef33 100644 --- a/tests/client/test_async_client.py +++ b/tests/client/test_async_client.py @@ -26,7 +26,6 @@ async def test_get(server): [ pytest.param("invalid://example.org", id="scheme-not-http(s)"), pytest.param("://example.org", id="no-scheme"), - pytest.param("http://", id="no-host"), ], ) @pytest.mark.anyio diff --git a/tests/client/test_client.py b/tests/client/test_client.py index 657839018a..f588c8e872 100644 --- a/tests/client/test_client.py +++ b/tests/client/test_client.py @@ -35,7 +35,6 @@ def test_get(server): [ pytest.param("invalid://example.org", id="scheme-not-http(s)"), pytest.param("://example.org", id="no-scheme"), - pytest.param("http://", id="no-host"), ], ) def test_get_invalid_url(server, url): @@ -44,6 +43,26 @@ def test_get_invalid_url(server, url): client.get(url) +@pytest.mark.parametrize( + "url", + [ + pytest.param("http://", id="no-host"), + pytest.param("https:/google.com", id="scheme-single-slash"), + pytest.param("https:///google.com", id="scheme-empty-authority"), + ], +) +def test_get_url_with_scheme_and_no_host(url): + with httpx.Client() as client: + with pytest.raises(httpx.InvalidURL): + client.get(url) + + +def test_scheme_without_host_is_not_joined_onto_base_url(): + client = httpx.Client(base_url="https://example.org/sub") + with pytest.raises(httpx.InvalidURL): + client.build_request("GET", "https:/google.com") + + def test_build_request(server): url = server.url.copy_with(path="/echo_headers") headers = {"Custom-header": "value"}