Skip to content

Commit

Permalink
Raise TypeError when a string is passed for port to URL.build()
Browse files Browse the repository at this point in the history
PR #959
Fixes #883

Co-authored-by: Sviatoslav Sydorenko <webknjaz@redhat.com>
  • Loading branch information
commonism and webknjaz authored Nov 28, 2023
1 parent e8cc8ab commit b3a5a71
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
4 changes: 4 additions & 0 deletions CHANGES/883.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Started raising :py:exc:`TypeError` when a string value is passed into
:py:meth:`~yarl.URL.build` as the ``port`` argument -- by :user:`commonism`.

Previously the empty string as port would create malformed URLs when rendered as string representations.
28 changes: 22 additions & 6 deletions tests/test_url_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,28 @@ def test_build_with_scheme_and_host():
assert u == URL("http://127.0.0.1")


def test_build_with_port():
with pytest.raises(ValueError):
URL.build(port=8000)

u = URL.build(scheme="http", host="127.0.0.1", port=8000)
assert str(u) == "http://127.0.0.1:8000"
@pytest.mark.parametrize(
("port", "exc", "match"),
[
pytest.param(
8000,
ValueError,
r"""(?x)
^
Can't\ build\ URL\ with\ "port"\ but\ without\ "host"\.
$
""",
id="port-only",
),
pytest.param(
"", TypeError, r"^The port is required to be int\.$", id="port-str"
),
],
)
def test_build_with_port(port, exc, match):
print(match)
with pytest.raises(exc, match=match):
URL.build(port=port)


def test_build_with_user():
Expand Down
2 changes: 2 additions & 0 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ def build(
raise ValueError(
'Can\'t mix "authority" with "user", "password", "host" or "port".'
)
if not isinstance(port, (int, type(None))):
raise TypeError("The port is required to be int.")
if port and not host:
raise ValueError('Can\'t build URL with "port" but without "host".')
if query and query_string:
Expand Down

0 comments on commit b3a5a71

Please sign in to comment.