From 2b07f2be287ed8d1f9ee3af3646a3158af67186d Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Tue, 2 Jan 2018 00:07:06 +0330 Subject: [PATCH] Rewrite `parse_address` util and add one test --- gunicorn/util.py | 27 +++++++++++---------------- tests/test_util.py | 4 ++++ 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/gunicorn/util.py b/gunicorn/util.py index 899416ad..37e586a8 100644 --- a/gunicorn/util.py +++ b/gunicorn/util.py @@ -247,7 +247,7 @@ def is_ipv6(addr): return True -def parse_address(netloc, default_port=8000): +def parse_address(netloc, default_port='8000'): if re.match(r'unix:(//)?', netloc): return re.split(r'unix:(//)?', netloc)[-1] @@ -260,27 +260,22 @@ def parse_address(netloc, default_port=8000): if netloc.startswith("tcp://"): netloc = netloc.split("tcp://")[1] + host, port = netloc, default_port - # get host if '[' in netloc and ']' in netloc: - host = netloc.split(']')[0][1:].lower() + host = netloc.split(']')[0][1:] + port = (netloc.split(']:') + [default_port])[1] elif ':' in netloc: - host = netloc.split(':')[0].lower() + host, port = (netloc.split(':') + [default_port])[:2] elif netloc == "": - host = "0.0.0.0" - else: - host = netloc.lower() + host, port = "0.0.0.0", default_port - #get port - netloc = netloc.split(']')[-1] - if ":" in netloc: - port = netloc.split(':', 1)[1] - if not port.isdigit(): - raise RuntimeError("%r is not a valid port number." % port) + try: port = int(port) - else: - port = default_port - return (host, port) + except ValueError: + raise RuntimeError("%r is not a valid port number." % port) + + return host.lower(), port def close_on_exec(fd): diff --git a/tests/test_util.py b/tests/test_util.py index 3b8be0c3..3b8688a2 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -13,8 +13,12 @@ from urllib.parse import SplitResult @pytest.mark.parametrize('test_input, expected', [ ('unix://var/run/test.sock', 'var/run/test.sock'), ('unix:/var/run/test.sock', '/var/run/test.sock'), + ('tcp://localhost', ('localhost', 8000)), + ('tcp://localhost:5000', ('localhost', 5000)), ('', ('0.0.0.0', 8000)), ('[::1]:8000', ('::1', 8000)), + ('[::1]:5000', ('::1', 5000)), + ('[::1]', ('::1', 8000)), ('localhost:8000', ('localhost', 8000)), ('127.0.0.1:8000', ('127.0.0.1', 8000)), ('localhost', ('localhost', 8000)),