Skip to content

Commit 8048180

Browse files
authored
Allow scheme replacement for relative URLs if the target scheme does not require a host (#1138)
1 parent 2340c72 commit 8048180

File tree

4 files changed

+15
-4
lines changed

4 files changed

+15
-4
lines changed

CHANGES/1138.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Allow scheme replacement for relative URLs if the scheme does not require a host -- by :user:`bdraco`.

CHANGES/280.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
1138.bugfix.rst

tests/test_url_update_netloc.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,13 @@ def test_with_scheme_uppercased():
1616

1717

1818
def test_with_scheme_for_relative_url():
19-
with pytest.raises(ValueError):
20-
URL("path/to").with_scheme("http")
19+
"""Test scheme can be set for relative URL."""
20+
msg = "scheme replacement is not allowed for " "relative URLs for the http scheme"
21+
with pytest.raises(ValueError, match=msg):
22+
assert URL("path/to").with_scheme("http")
23+
24+
expected = URL("file:///absolute/path")
25+
assert expected.with_scheme("file") == expected
2126

2227

2328
def test_with_scheme_invalid_type():

yarl/_url.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,8 +1049,12 @@ def with_scheme(self, scheme: str) -> "URL":
10491049
# N.B. doesn't cleanup query/fragment
10501050
if not isinstance(scheme, str):
10511051
raise TypeError("Invalid scheme type")
1052-
if not self.absolute:
1053-
raise ValueError("scheme replacement is not allowed for relative URLs")
1052+
if not self.absolute and scheme in SCHEME_REQUIRES_HOST:
1053+
msg = (
1054+
"scheme replacement is not allowed for "
1055+
f"relative URLs for the {scheme} scheme"
1056+
)
1057+
raise ValueError(msg)
10541058
return URL(self._val._replace(scheme=scheme.lower()), encoded=True)
10551059

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

0 commit comments

Comments
 (0)