Add method is_valid_port in netutils

Glance[1] and Neutron[2] need to check if a value is a valid port,
so we place the common code in oslo.utils.

[1] https://git.openstack.org/cgit/openstack/glance/tree/glance/common/utils.py#n550
[2] https://git.openstack.org/cgit/openstack/neutron/tree/neutron/extensions/securitygroup.py#n142

Change-Id: I156035396b4f686589b6f7ddfbdb0c922b8d90a0
This commit is contained in:
ChangBo Guo(gcb) 2014-12-23 16:04:04 +08:00
parent 058ee53a69
commit 44f36e35ec
2 changed files with 22 additions and 0 deletions

View File

@ -114,6 +114,16 @@ def is_valid_ip(address):
return is_valid_ipv4(address) or is_valid_ipv6(address)
def is_valid_port(port):
"""Verify that port represents a valid port number."""
try:
val = int(port)
except (ValueError, TypeError):
return False
return (val > 0 and val <= 65535)
def get_my_ipv4():
"""Returns the actual ipv4 of the local machine.

View File

@ -178,6 +178,18 @@ class NetworkUtilsTest(test_base.BaseTestCase):
self.assertFalse(netutils.is_valid_ip(''))
def test_valid_port(self):
valid_inputs = [1, '1', 2, '3', '5', 8, 13, 21,
'80', '3246', '65535']
for input_str in valid_inputs:
self.assertTrue(netutils.is_valid_port(input_str))
def test_valid_port_fail(self):
invalid_inputs = ['-32768', '0', 0, '65536', 528491, '528491',
'528.491', 'thirty-seven', None]
for input_str in invalid_inputs:
self.assertFalse(netutils.is_valid_port(input_str))
def test_get_my_ip(self):
sock_attrs = {
'return_value.getsockname.return_value': ['1.2.3.4', '']}