Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace isipv6 method with builtin package #1689

Merged
merged 4 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 46 additions & 16 deletions common/test/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import signal
import unittest
from unittest.mock import patch
import uuid
from copy import deepcopy
from tempfile import NamedTemporaryFile, TemporaryDirectory
from datetime import datetime
Expand All @@ -35,7 +34,6 @@

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import tools
import config
import configfile

# chroot jails used for building may have no UUID devices (because of tmpfs)
Expand Down Expand Up @@ -520,21 +518,53 @@ def test_splitCommands(self):
ret[0],
'echo start;echo foo;echo foo;echo foo;echo end')

def test_isIPv6Address(self):
self.assertTrue(tools.isIPv6Address('fd00:0::5'))
self.assertTrue(tools.isIPv6Address('2001:db8:0:8d3:0:8a2e:70:7344'))
self.assertFalse(tools.isIPv6Address('foo.bar'))
self.assertFalse(tools.isIPv6Address('192.168.1.1'))
self.assertFalse(tools.isIPv6Address('fd00'))

def test_excapeIPv6Address(self):
self.assertEqual(tools.escapeIPv6Address('fd00:0::5'), '[fd00:0::5]')
self.assertEqual(
tools.escapeIPv6Address('2001:db8:0:8d3:0:8a2e:70:7344'),
'[2001:db8:0:8d3:0:8a2e:70:7344]')
self.assertEqual(tools.escapeIPv6Address('foo.bar'), 'foo.bar')
self.assertEqual(tools.escapeIPv6Address('192.168.1.1'), '192.168.1.1')
self.assertEqual(tools.escapeIPv6Address('fd00'), 'fd00')
class TestEscapeIPv6(generic.TestCase):
def test_escaped(self):
values_and_expected = (
('fd00:0::5', '[fd00:0::5]'),
(
'2001:db8:0:8d3:0:8a2e:70:7344',
'[2001:db8:0:8d3:0:8a2e:70:7344]'
),
('::', '[::]'),
('::1', '[::1]'),
('::ffff:192.0.2.128', '[::ffff:192.0.2.128]'),
('fe80::1', '[fe80::1]'),
)

for val, exp in values_and_expected:
with self.subTest(val=val, exp=exp):
self.assertEqual(tools.escapeIPv6Address(val), exp)

def test_passed(self):
test_values = (
'192.168.1.1',
'172.17.1.133',
'255.255.255.255',
'169.254.0.1',
)

for val in test_values:
with self.subTest(val=val):
# IPv4 addresses are not escaped
self.assertEqual(tools.escapeIPv6Address(val), val)

def test_invalid(self):
"""Invalid IP addresses and hostnames"""
test_values = (
'foo.bar',
'fd00',
'2001:0db8:::0000:0000:8a2e:0370:7334',
':2001:0db8:85a3:0000:0000:8a2e:0370:7334',
'2001:0gb8:85a3:0000:0000:8a2e:0370:7334',
'2001:0db8:85a3:0000:0000:8a2e:0370:7334:abcd',
'localhost',
)

for val in test_values:
with self.subTest(val=val):
self.assertEqual(tools.escapeIPv6Address(val), val)


class TestToolsEnviron(generic.TestCase):
Expand Down
44 changes: 20 additions & 24 deletions common/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1803,15 +1803,17 @@ def writeCrontab(lines):
stderr = subprocess.PIPE,
universal_newlines = True)
out, err = proc.communicate()

if proc.returncode or err:
logger.error('Failed to write lines to crontab: %s, %s'
%(proc.returncode, err))
logger.error(
f'Failed to write lines to crontab: {proc.returncode}, {err}')
return False

else:
logger.debug('Wrote %s lines to user crontab'
%len(lines))
logger.debug(f'Wrote {len(lines)} lines to user crontab')
return True


def splitCommands(cmds, head = '', tail = '', maxLength = 0):
"""
Split a list of commands ``cmds`` into multiple commands with each length
Expand Down Expand Up @@ -1840,35 +1842,29 @@ def splitCommands(cmds, head = '', tail = '', maxLength = 0):
s += tail
yield s

def isIPv6Address(address):
"""
Check if ``address`` is a valid IPv6 address.

def escapeIPv6Address(address):
"""Escape IP addresses with square brackets ``[]`` if they are IPv6.

If it is an IPv4 address or a hostname (lettersonly) nothing is changed.

Args:
address (str): address that should get tested
address (str): IP-Address to escape if needed.

Returns:
bool: True if ``address`` is a valid IPv6 address
str: The address, escaped if it is IPv6.
"""
try:
return isinstance(ipaddress.IPv6Address(address), ipaddress.IPv6Address)
except:
return False
ip = ipaddress.ip_address(address)
except ValueError:
# invalid IP, e.g. a hostname
return address

def escapeIPv6Address(address):
"""
Escape IPv6 Addresses with square brackets ``[]``.
if ip.version == 6:
return f'[{address}]'

Args:
address (str): address that should be escaped
return address

Returns:
str: ``address`` in square brackets
"""
if isIPv6Address(address):
return '[{}]'.format(address)
else:
return address

def camelCase(s):
"""
Expand Down