From ebf326ff6e4687992170f1b97b9576d1e34a8033 Mon Sep 17 00:00:00 2001 From: Martijn Pieters Date: Tue, 25 Apr 2023 16:40:45 +0100 Subject: [PATCH] Fix truediv joining against absolute URL with no path When joining path elements against an absolute URL, ensure that the resulting path starts with a slash. --- CHANGES/854.bugfix.rst | 1 + tests/test_url.py | 20 ++++++++++++-------- yarl/_url.py | 4 ++++ 3 files changed, 17 insertions(+), 8 deletions(-) create mode 100644 CHANGES/854.bugfix.rst diff --git a/CHANGES/854.bugfix.rst b/CHANGES/854.bugfix.rst new file mode 100644 index 000000000..55a671086 --- /dev/null +++ b/CHANGES/854.bugfix.rst @@ -0,0 +1 @@ +Fix regression with truediv and absolute URLs with empty paths causing the raw path to lack the leading ``/``. diff --git a/tests/test_url.py b/tests/test_url.py index 2003298f0..261bb562b 100644 --- a/tests/test_url.py +++ b/tests/test_url.py @@ -690,23 +690,27 @@ def test_clear_query_on_getting_parent_toplevel(): def test_div_root(): - url = URL("http://example.com") - assert str(url / "path" / "to") == "http://example.com/path/to" + url = URL("http://example.com") / "path" / "to" + assert str(url) == "http://example.com/path/to" + assert url.raw_path == "/path/to" def test_div_root_with_slash(): - url = URL("http://example.com/") - assert str(url / "path" / "to") == "http://example.com/path/to" + url = URL("http://example.com/") / "path" / "to" + assert str(url) == "http://example.com/path/to" + assert url.raw_path == "/path/to" def test_div(): - url = URL("http://example.com/path") - assert str(url / "to") == "http://example.com/path/to" + url = URL("http://example.com/path") / "to" + assert str(url) == "http://example.com/path/to" + assert url.raw_path == "/path/to" def test_div_with_slash(): - url = URL("http://example.com/path/") - assert str(url / "to") == "http://example.com/path/to" + url = URL("http://example.com/path/") / "to" + assert str(url) == "http://example.com/path/to" + assert url.raw_path == "/path/to" def test_div_path_starting_from_slash_is_forbidden(): diff --git a/yarl/_url.py b/yarl/_url.py index d23c46d54..3e1c1a7f5 100644 --- a/yarl/_url.py +++ b/yarl/_url.py @@ -734,6 +734,10 @@ def _make_child(self, segments, encoded=False): parsed = [*old_path.rstrip("/").split("/"), *parsed] if self.is_absolute(): parsed = _normalize_path_segments(parsed) + if parsed and parsed[0] != "": + # inject a leading slash when adding a path to an absolute URL + # where there was none before + parsed = ["", *parsed] new_path = "/".join(parsed) return URL( self._val._replace(path=new_path, query="", fragment=""), encoded=True