diff --git a/CHANGES/1157.bugfix.rst b/CHANGES/1157.bugfix.rst new file mode 120000 index 000000000..0082490cd --- /dev/null +++ b/CHANGES/1157.bugfix.rst @@ -0,0 +1 @@ +1158.bugfix.rst \ No newline at end of file diff --git a/CHANGES/1158.bugfix.rst b/CHANGES/1158.bugfix.rst new file mode 100644 index 000000000..d6f8330e2 --- /dev/null +++ b/CHANGES/1158.bugfix.rst @@ -0,0 +1 @@ +Fixed IPv6 addresses missing brackets when the :class:`~yarl.URL` was converted to a string -- by :user:`bdraco`. diff --git a/tests/test_url_build.py b/tests/test_url_build.py index 1d5c4d09c..b6675c294 100644 --- a/tests/test_url_build.py +++ b/tests/test_url_build.py @@ -17,17 +17,22 @@ def test_build_simple(): def test_url_build_ipv6(): u = URL.build(scheme="http", host="::1") - assert str(u) == "http://::1" + assert str(u) == "http://[::1]" -def test_url_build_ipv6_brackets(): - u = URL.build(scheme="http", host="[::1]") - assert str(u) == "http://::1" +def test_url_build_ipv6_brackets_encoded(): + u = URL.build(scheme="http", host="[::1]", encoded=True) + assert str(u) == "http://[::1]" + + +def test_url_build_ipv6_brackets_not_encoded(): + u = URL.build(scheme="http", host="::1", encoded=False) + assert str(u) == "http://[::1]" def test_url_ipv4_in_ipv6(): u = URL.build(scheme="http", host="2001:db8:122:344::192.0.2.33") - assert str(u) == "http://2001:db8:122:344::c000:221" + assert str(u) == "http://[2001:db8:122:344::c000:221]" def test_build_with_scheme(): diff --git a/tests/test_url_parsing.py b/tests/test_url_parsing.py index 4fe95185e..0d58c9d09 100644 --- a/tests/test_url_parsing.py +++ b/tests/test_url_parsing.py @@ -604,3 +604,28 @@ def test_schemes_that_require_host(scheme: str) -> None: ) with pytest.raises(ValueError, match=expect): URL(f"{scheme}://:1") + + +@pytest.mark.parametrize( + ("url", "hostname", "hostname_without_brackets"), + [ + ("http://[::1]", "[::1]", "::1"), + ("http://[::1]:8080", "[::1]", "::1"), + ("http://127.0.0.1:8080", "127.0.0.1", "127.0.0.1"), + ( + "http://xn--jxagkqfkduily1i.eu", + "xn--jxagkqfkduily1i.eu", + "xn--jxagkqfkduily1i.eu", + ), + ], +) +def test_url_round_trips( + url: str, hostname: str, hostname_without_brackets: str +) -> None: + """Verify that URLs round-trip correctly.""" + parsed = URL(url) + assert parsed._val.hostname == hostname_without_brackets + assert parsed.raw_host == hostname_without_brackets + assert parsed.host_subcomponent == hostname + assert str(parsed) == url + assert str(URL(str(parsed))) == url diff --git a/yarl/_url.py b/yarl/_url.py index a61a7f1d2..37e4739fa 100644 --- a/yarl/_url.py +++ b/yarl/_url.py @@ -395,7 +395,7 @@ def __str__(self) -> str: netloc=self._make_netloc( self.raw_user, self.raw_password, - self.raw_host, + self.host_subcomponent, port, encode_host=False, )