Skip to content

Commit c02979c

Browse files
author
rodrigo.nogueira
committed
Fix inconsistent invalid URL handling (#1832)
1 parent ae1b9f6 commit c02979c

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

httpx/_client.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,8 @@ def _merge_url(self, url: URL | str) -> URL:
394394
to create the URL used for the outgoing request.
395395
"""
396396
merge_url = URL(url)
397+
if merge_url.scheme and not merge_url.host:
398+
raise InvalidURL(f"Invalid URL '{url}': has scheme but missing host")
397399
if merge_url.is_relative_url:
398400
# To merge URLs we always append to the base URL. To get this
399401
# behaviour correct we always ensure the base URL ends in a '/'

tests/client/test_async_client.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@ async def test_get(server):
3232
@pytest.mark.anyio
3333
async def test_get_invalid_url(server, url):
3434
async with httpx.AsyncClient() as client:
35-
with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):
35+
with pytest.raises(
36+
(httpx.UnsupportedProtocol, httpx.LocalProtocolError, httpx.InvalidURL)
37+
):
3638
await client.get(url)
3739

3840

tests/client/test_client.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,27 @@ def test_get(server):
4040
)
4141
def test_get_invalid_url(server, url):
4242
with httpx.Client() as client:
43-
with pytest.raises((httpx.UnsupportedProtocol, httpx.LocalProtocolError)):
43+
with pytest.raises(
44+
(httpx.UnsupportedProtocol, httpx.LocalProtocolError, httpx.InvalidURL)
45+
):
4446
client.get(url)
4547

4648

49+
def test_get_invalid_url_with_scheme_no_host():
50+
"""
51+
Regression test for: https://github.com/encode/httpx/issues/1832
52+
URLs with scheme but no host should raise InvalidURL.
53+
"""
54+
with httpx.Client() as client:
55+
with pytest.raises(httpx.InvalidURL) as exc:
56+
client.get("https:/google.com")
57+
assert "has scheme but missing host" in str(exc.value)
58+
59+
with pytest.raises(httpx.InvalidURL) as exc:
60+
client.get("https:///google.com")
61+
assert "has scheme but missing host" in str(exc.value)
62+
63+
4764
def test_build_request(server):
4865
url = server.url.copy_with(path="/echo_headers")
4966
headers = {"Custom-header": "value"}

0 commit comments

Comments
 (0)