Rewrite parse_address util and add one test

This commit is contained in:
Hasan Ramezani 2018-01-02 00:07:06 +03:30 committed by Randall Leeds
parent a8963ef1a5
commit 2b07f2be28
2 changed files with 15 additions and 16 deletions

View File

@ -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):

View File

@ -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)),