Skip to content

Commit

Permalink
Allow scheme replacement for relative URLs if the target scheme does …
Browse files Browse the repository at this point in the history
…not require a host (#1138)
  • Loading branch information
bdraco committed Sep 9, 2024
1 parent 2340c72 commit 8048180
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGES/1138.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow scheme replacement for relative URLs if the scheme does not require a host -- by :user:`bdraco`.
1 change: 1 addition & 0 deletions CHANGES/280.bugfix.rst
9 changes: 7 additions & 2 deletions tests/test_url_update_netloc.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@ def test_with_scheme_uppercased():


def test_with_scheme_for_relative_url():
with pytest.raises(ValueError):
URL("path/to").with_scheme("http")
"""Test scheme can be set for relative URL."""
msg = "scheme replacement is not allowed for " "relative URLs for the http scheme"
with pytest.raises(ValueError, match=msg):
assert URL("path/to").with_scheme("http")

expected = URL("file:///absolute/path")
assert expected.with_scheme("file") == expected


def test_with_scheme_invalid_type():
Expand Down
8 changes: 6 additions & 2 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -1049,8 +1049,12 @@ def with_scheme(self, scheme: str) -> "URL":
# N.B. doesn't cleanup query/fragment
if not isinstance(scheme, str):
raise TypeError("Invalid scheme type")
if not self.absolute:
raise ValueError("scheme replacement is not allowed for relative URLs")
if not self.absolute and scheme in SCHEME_REQUIRES_HOST:
msg = (
"scheme replacement is not allowed for "
f"relative URLs for the {scheme} scheme"
)
raise ValueError(msg)
return URL(self._val._replace(scheme=scheme.lower()), encoded=True)

def with_user(self, user: Union[str, None]) -> "URL":
Expand Down

0 comments on commit 8048180

Please sign in to comment.