Skip to content

Commit

Permalink
Fix with_scheme checks when passed scheme is not lowercase (#1189)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Oct 11, 2024
1 parent d5660f3 commit e342bcc
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGES/1189.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed validation with :py:meth:`~yarl.URL.with_scheme` when passed scheme is not lowercase -- by :user:`bdraco`.
21 changes: 18 additions & 3 deletions tests/test_url_update_netloc.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,27 @@ def test_with_scheme_uppercased():
assert str(url.with_scheme("HTTPS")) == "https://example.com"


def test_with_scheme_for_relative_url():
@pytest.mark.parametrize(
("scheme"),
[
("http"),
("https"),
("HTTP"),
],
)
def test_with_scheme_for_relative_url(scheme: str) -> None:
"""Test scheme can be set for relative URL."""
msg = "scheme replacement is not allowed for " "relative URLs for the http scheme"
lower_scheme = scheme.lower()
msg = (
"scheme replacement is not allowed for "
f"relative URLs for the {lower_scheme} scheme"
)
with pytest.raises(ValueError, match=msg):
assert URL("path/to").with_scheme("http")
assert URL("path/to").with_scheme(scheme)


def test_with_scheme_for_relative_file_url() -> None:
"""Test scheme can be set for relative file URL."""
expected = URL("file:///absolute/path")
assert expected.with_scheme("file") == expected

Expand Down
7 changes: 4 additions & 3 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -1124,13 +1124,14 @@ 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 and scheme in SCHEME_REQUIRES_HOST:
lower_scheme = scheme.lower()
if not self.absolute and lower_scheme in SCHEME_REQUIRES_HOST:
msg = (
"scheme replacement is not allowed for "
f"relative URLs for the {scheme} scheme"
f"relative URLs for the {lower_scheme} scheme"
)
raise ValueError(msg)
return URL(self._val._replace(scheme=scheme.lower()), encoded=True)
return URL(self._val._replace(scheme=lower_scheme), encoded=True)

def with_user(self, user: Union[str, None]) -> "URL":
"""Return a new URL with user replaced.
Expand Down

0 comments on commit e342bcc

Please sign in to comment.