def get_entry_type(hosts_entry=None): if hosts_entry and isinstance(hosts_entry, str): entry = hosts_entry.strip() if not entry or not entry[0] or entry[0] == "\n": return "blank" if entry[0] == "#": return "comment" entry_chunks = entry.split() if is_ipv6(entry_chunks[0]): return "ipv6" if is_ipv4(entry_chunks[0]): return "ipv4"
def str_to_hostentry(entry): line_parts = entry.strip().split() if is_ipv4(line_parts[0]) and valid_hostnames(line_parts[1:]): return HostsEntry( entry_type="ipv4", address=line_parts[0], names=line_parts[1:] ) elif is_ipv6(line_parts[0]) and valid_hostnames(line_parts[1:]): return HostsEntry( entry_type="ipv6", address=line_parts[0], names=line_parts[1:] ) else: return False
def __init__(self, entry_type=None, address=None, comment=None, names=None): if not entry_type or entry_type not in ("ipv4", "ipv6", "comment", "blank"): raise Exception("entry_type invalid or not specified") if entry_type == "comment" and not comment: raise Exception("entry_type comment supplied without value.") if entry_type == "ipv4": if not all((address, names)): raise Exception("Address and Name(s) must be specified.") if not is_ipv4(address): raise InvalidIPv4Address() if entry_type == "ipv6": if not all((address, names)): raise Exception("Address and Name(s) must be specified.") if not is_ipv6(address): raise InvalidIPv6Address() self.entry_type = entry_type self.address = address self.comment = comment self.names = names
def test_should_return_true_for_min_address(self): input = "0:0:0:0:0:0:0:0" output = is_ipv6(input) self.assertEqual(True, output)
def test_should_return_false_for_ipv4(self): input = "127.0.0.1" output = is_ipv6(input) self.assertEqual(False, output)
def test_should_return_false_for_7_segments(self): input = "0:0:0:0:0:0:0" output = is_ipv6(input) self.assertEqual(False, output)
def test_should_return_true_for_loopback(self): input = "::1" output = is_ipv6(input) self.assertEqual(True, output)
def test_should_return_true_for_max_address(self): input = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF" output = is_ipv6(input) self.assertEqual(True, output)