From d7ddec93079828fb471b974668fe352fc3263598 Mon Sep 17 00:00:00 2001 From: Behnam Esfahbod Date: Thu, 12 Jul 2018 18:18:51 -0700 Subject: [PATCH] URL::build(): Accept host-only URLs Accept host-only URLs, which are buildable using the parsing method as `//host-name'. Also, add check for setting port without a host, along-side test case for it. --- tests/test_url_build.py | 20 ++++++++++++++++---- yarl/__init__.py | 6 +++--- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/tests/test_url_build.py b/tests/test_url_build.py index a5bbabf7..2b61ce60 100644 --- a/tests/test_url_build.py +++ b/tests/test_url_build.py @@ -16,15 +16,27 @@ def test_build_simple(): assert str(u) == 'http://127.0.0.1' -def test_build_scheme_and_host(): - with pytest.raises(ValueError): - URL.build(host='127.0.0.1') - +def test_build_with_scheme(): with pytest.raises(ValueError): URL.build(scheme='http') +def test_build_with_host(): + u = URL.build(host='127.0.0.1') + assert str(u) == '//127.0.0.1' + assert u == URL('//127.0.0.1') + + +def test_build_with_scheme_and_host(): + u = URL.build(scheme='http', host='127.0.0.1') + assert str(u) == 'http://127.0.0.1' + 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' diff --git a/yarl/__init__.py b/yarl/__init__.py index 74d03836..60093584 100644 --- a/yarl/__init__.py +++ b/yarl/__init__.py @@ -188,12 +188,12 @@ def build(cls, *, scheme='', user='', password='', host='', port=None, encoded=False): """Creates and returns a new URL""" - if host and not scheme: - raise ValueError( - 'Can\'t build URL with "host" but without "scheme".') if not host and scheme: raise ValueError( 'Can\'t build URL with "scheme" but without "host".') + if port and not host: + raise ValueError( + 'Can\'t build URL with "port" but without "host".') if query and query_string: raise ValueError( "Only one of \"query\" or \"query_string\" should be passed")