summaryrefslogtreecommitdiff
path: root/cloudinit/net
diff options
context:
space:
mode:
authorDaniel Watkins <oddbloke@ubuntu.com>2020-03-30 23:02:44 -0400
committerGitHub <noreply@github.com>2020-03-30 21:02:44 -0600
commit4f825b3e6d8fde5c239d29639b04d2bea6d95d0e (patch)
tree4d73682ac9118d057e1009aae02e18f3139e5244 /cloudinit/net
parentee0377924aa6bcd072dc5836dbf8ac51110bd87d (diff)
downloadvyos-cloud-init-4f825b3e6d8fde5c239d29639b04d2bea6d95d0e.tar.gz
vyos-cloud-init-4f825b3e6d8fde5c239d29639b04d2bea6d95d0e.zip
cloudinit: refactor util.is_ipv4 to net.is_ipv4_address (#292)
This also simplifies the implementation to rely on the stdlib, instead of our own NIH checking.
Diffstat (limited to 'cloudinit/net')
-rw-r--r--cloudinit/net/__init__.py16
-rw-r--r--cloudinit/net/tests/test_init.py22
2 files changed, 38 insertions, 0 deletions
diff --git a/cloudinit/net/__init__.py b/cloudinit/net/__init__.py
index 08eaf0a3..cb8c1601 100644
--- a/cloudinit/net/__init__.py
+++ b/cloudinit/net/__init__.py
@@ -978,6 +978,22 @@ def is_ip_address(s: str) -> bool:
return True
+def is_ipv4_address(s: str) -> bool:
+ """Returns a bool indicating if ``s`` is an IPv4 address.
+
+ :param s:
+ The string to test.
+
+ :return:
+ A bool indicating if the string contains an IPv4 address or not.
+ """
+ try:
+ ipaddress.IPv4Address(s)
+ except ValueError:
+ return False
+ return True
+
+
class EphemeralIPv4Network(object):
"""Context manager which sets up temporary static network configuration.
diff --git a/cloudinit/net/tests/test_init.py b/cloudinit/net/tests/test_init.py
index 909f43c8..32e70b4c 100644
--- a/cloudinit/net/tests/test_init.py
+++ b/cloudinit/net/tests/test_init.py
@@ -1316,4 +1316,26 @@ class TestIsIpAddress:
expected_call = mock.call(mock.sentinel.ip_address_in)
assert [expected_call] == m_ip_address.call_args_list
+
+class TestIsIpv4Address:
+ """Tests for net.is_ipv4_address.
+
+ Instead of testing with values we rely on the ipaddress stdlib module to
+ handle all values correctly, so simply test that is_ipv4_address defers to
+ the ipaddress module correctly.
+ """
+
+ @pytest.mark.parametrize('ipv4address_mock,expected_return', (
+ (mock.Mock(side_effect=ValueError), False),
+ (mock.Mock(return_value=ipaddress.IPv4Address('192.168.0.1')), True),
+ ))
+ def test_is_ip_address(self, ipv4address_mock, expected_return):
+ with mock.patch('cloudinit.net.ipaddress.IPv4Address',
+ ipv4address_mock) as m_ipv4address:
+ ret = net.is_ipv4_address(mock.sentinel.ip_address_in)
+ assert expected_return == ret
+ expected_call = mock.call(mock.sentinel.ip_address_in)
+ assert [expected_call] == m_ipv4address.call_args_list
+
+
# vi: ts=4 expandtab