Add helper to format IP addresses appropriately
The ``format_addr`` helper will allow you to write IP version
agnostic code by encapsulating IPv6 addresses in brackets ('[]').
This commit is contained in:
@@ -30,3 +30,15 @@ class TestOpenStackBaseTest(unittest.TestCase):
|
||||
|
||||
MyTestClass.setUpClass('foo', 'bar')
|
||||
_setUpClass.assert_called_with('foo', 'bar')
|
||||
|
||||
|
||||
class TestUtils(unittest.TestCase):
|
||||
|
||||
def test_format_addr(self):
|
||||
self.assertEquals('1.2.3.4', test_utils.format_addr('1.2.3.4'))
|
||||
self.assertEquals(
|
||||
'[2001:db8::42]', test_utils.format_addr('2001:db8::42'))
|
||||
with self.assertRaises(ValueError):
|
||||
test_utils.format_addr('999.999.999.999')
|
||||
with self.assertRaises(ValueError):
|
||||
test_utils.format_addr('2001:db8::g')
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"""Module containing base class for implementing charm tests."""
|
||||
import contextlib
|
||||
import logging
|
||||
import ipaddress
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
@@ -431,3 +432,20 @@ class OpenStackBaseTest(BaseCharmTest):
|
||||
cls.keystone_session = openstack_utils.get_overcloud_keystone_session(
|
||||
model_name=cls.model_name)
|
||||
cls.cacert = openstack_utils.get_cacert()
|
||||
|
||||
|
||||
def format_addr(addr):
|
||||
"""Validate and format IP address.
|
||||
|
||||
:param addr: IPv6 or IPv4 address
|
||||
:type addr: str
|
||||
:returns: Address string, optionally encapsulated in brackets([])
|
||||
:rtype: str
|
||||
:raises: ValueError
|
||||
"""
|
||||
ipaddr = ipaddress.ip_address(addr)
|
||||
if isinstance(ipaddr, ipaddress.IPv6Address):
|
||||
fmt = '[{}]'
|
||||
else:
|
||||
fmt = '{}'
|
||||
return fmt.format(ipaddr)
|
||||
|
||||
Reference in New Issue
Block a user