Skip to content

Commit cadc40d

Browse files
author
mvaught
committed
refactor: improve host parsing for IPv4/IPv6 and add tests
1 parent ec7d172 commit cadc40d

File tree

4 files changed

+18
-6
lines changed

4 files changed

+18
-6
lines changed

src/hyperlink/_url.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1667,11 +1667,16 @@ def to_uri(self):
16671667
new_path = _encode_path_parts(
16681668
self.path, has_scheme=bool(self.scheme), rooted=False, maximal=True
16691669
)
1670-
new_host = (
1671-
self.host
1672-
if not self.host
1673-
else idna_encode(self.host, uts46=True).decode("ascii")
1674-
)
1670+
family, host_text = parse_host(self.host)
1671+
if family is not None:
1672+
# IPv4 / IPv6 literal
1673+
new_host = host_text
1674+
else:
1675+
new_host = (
1676+
self.host
1677+
if not self.host
1678+
else idna_encode(self.host, uts46=True).decode("ascii")
1679+
)
16751680
return self.replace(
16761681
userinfo=new_userinfo,
16771682
host=new_host,

src/hyperlink/test/test_hypothesis.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
except ImportError:
1919
from mock import patch # type: ignore[misc]
2020

21-
from hypothesis import given, settings
21+
from hypothesis import given, settings, HealthCheck
2222
from hypothesis.strategies import SearchStrategy, data
2323

2424
from idna import IDNAError, check_label, encode as idna_encode
@@ -174,6 +174,7 @@ def test_hostnames_ascii(self, hostname):
174174
)
175175

176176
@given(hostnames(allow_leading_digit=False, allow_idn=False))
177+
@settings(suppress_health_check=[HealthCheck.filter_too_much])
177178
def test_hostnames_ascii_nolead(self, hostname):
178179
# type: (Text) -> None
179180
"""

src/hyperlink/test/test_parse.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,8 @@ def test_parse(self):
3535

3636
with self.assertRaises(UnicodeDecodeError):
3737
purl3.fragment
38+
39+
def test_ipv6_literal_not_idna_encoded(self) -> None:
40+
41+
url = EncodedURL.from_text("http://[::1]:8080/path")
42+
assert url.to_uri().to_text() == "http://[::1]:8080/path"

tox.ini

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ skip_install = True
9494

9595
deps =
9696
black==21.7b0
97+
click<8.0
9798

9899
setenv =
99100
BLACK_LINT_ARGS=--check

0 commit comments

Comments
 (0)