From 5c2af26b91e5d51ebdea2db5cc94aa324f6efb98 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 30 Oct 2024 15:43:10 -0500 Subject: [PATCH] Small cleanups to `encode_url` (#1405) --- tests/test_url.py | 22 ++++++++++++++++++++++ yarl/_url.py | 13 ++++++++----- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/tests/test_url.py b/tests/test_url.py index bd1579d0..a2d0cef7 100644 --- a/tests/test_url.py +++ b/tests/test_url.py @@ -2183,6 +2183,7 @@ def test_parsing_populates_cache(): assert url._cache["raw_query_string"] == "a=b" assert url._cache["raw_fragment"] == "frag" assert url._cache["scheme"] == "http" + assert url._cache["raw_path"] == "/path" assert url.raw_user == "user" assert url.raw_password == "password" assert url.raw_host == "example.com" @@ -2198,6 +2199,7 @@ def test_parsing_populates_cache(): assert url.raw_query_string == "a=b" assert url.raw_fragment == "frag" assert url.scheme == "http" + assert url.raw_path == "/path" assert url._cache["raw_user"] == "user" assert url._cache["raw_password"] == "password" assert url._cache["raw_host"] == "example.com" @@ -2205,6 +2207,26 @@ def test_parsing_populates_cache(): assert url._cache["raw_query_string"] == "a=b" assert url._cache["raw_fragment"] == "frag" assert url._cache["scheme"] == "http" + assert url._cache["raw_path"] == "/path" + + +def test_relative_url_populates_cache(): + """Test that parsing a relative URL populates the cache.""" + url = URL(".") + assert url._cache["raw_query_string"] == "" + assert url._cache["raw_fragment"] == "" + assert url._cache["scheme"] == "" + assert url._cache["raw_path"] == "." + + +def test_parsing_populates_cache_for_single_dot(): + """Test that parsing a URL populates the cache for a single dot path.""" + url = URL("http://example.com/.") + # raw_path should be normalized to "/" + assert url._cache["raw_path"] == "/" + assert url._cache["raw_host"] == "example.com" + assert url._cache["scheme"] == "http" + assert url.raw_path == "/" @pytest.mark.parametrize( diff --git a/yarl/_url.py b/yarl/_url.py index 988fcb81..b69149b9 100644 --- a/yarl/_url.py +++ b/yarl/_url.py @@ -182,15 +182,18 @@ def encode_url(url_str: str) -> "URL": if path: path = PATH_REQUOTER(path) - if netloc: - if "." in path: - path = normalize_path(path) + if netloc and "." in path: + path = normalize_path(path) + if query: + query = QUERY_REQUOTER(query) + if fragment: + fragment = FRAGMENT_REQUOTER(fragment) - query = QUERY_REQUOTER(query) if query else query - fragment = FRAGMENT_REQUOTER(fragment) if fragment else fragment cache["scheme"] = scheme + cache["raw_path"] = "/" if not path and netloc else path cache["raw_query_string"] = query cache["raw_fragment"] = fragment + self = object.__new__(URL) self._scheme = scheme self._netloc = netloc