Skip to content

Commit

Permalink
util.py: revert leading zeros logic, add is_valid_pfx
Browse files Browse the repository at this point in the history
the previously added check for leading zeros picks up private networks,
so it's not exactly what we want here. Instead, separate the format_pfx
and is_valid_pfx intents and add tests accordingly.
format_pfx checks whether the existing prefix can be coerced to a string
and returns it. is_valid_pfx simply checks whether it's a valid pfx
or not.
  • Loading branch information
jurraca committed Dec 30, 2024
1 parent 65fbed7 commit a542492
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 19 deletions.
23 changes: 17 additions & 6 deletions kartograf/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,22 +133,33 @@ def wait_for_launch(wait):

def format_pfx(pfx):
"""
We have seen some formatting issues like leading zeros in the prefix,
which can cause problems.
Attempt to format an IP network or address.
If invalid, return the input unchanged.
"""
try:
if "/" in pfx:
pattern = r"^0+"
match = re.search(pattern, pfx)
if match:
pfx = re.sub(pattern, "", pfx)
formatted_pfx = str(ipaddress.ip_network(pfx))
return f"{formatted_pfx}"
return str(ipaddress.ip_address(pfx))
except ValueError:
return pfx


def is_valid_pfx(pfx):
"""
Check whether the IP network or address provided is valid.
"""
try:
if "/" in pfx:
ipaddress.ip_network(pfx)
return True
else:
ipaddress.ip_address(pfx)
return True
except ValueError:
return False


def get_root_network(pfx):
"""
Extract the top-level network from an IPv4 or IPv6 address.
Expand Down
26 changes: 13 additions & 13 deletions tests/util_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from kartograf.util import format_pfx, get_root_network
from kartograf.util import format_pfx, is_valid_pfx, get_root_network

def test_valid_ipv4_network():
pfx = "192.144.11.0/21"
Expand All @@ -20,18 +20,6 @@ def test_valid_ipv6_addr():
assert format_pfx(pfx) == pfx


def test_ipv4_prefix_with_leading_zeros():
pfx = "010.10.00.00/16"
expected_output = "10.10.00.00/16"
assert format_pfx(pfx) == expected_output


def test_ipv6_prefix_with_leading_zeros():
pfx = "001:db8::0/24"
expected_output = "1:db8::0/24"
assert format_pfx(pfx) == expected_output


def test_invalid_ip_network():
pfx = "192.1/asdf"
assert format_pfx(pfx) == pfx
Expand All @@ -42,6 +30,18 @@ def test_invalid_input():
assert format_pfx(pfx) == pfx


def test_ipv4_prefix_with_leading_zeros():
pfx = "010.10.00.00/16"
assert format_pfx(pfx) == pfx
assert not is_valid_pfx(pfx)


def test_ipv6_prefix_with_leading_zeros():
pfx = "001:db8::0/24"
assert format_pfx(pfx) == pfx
assert not is_valid_pfx(pfx)


def test_get_root_network():
ipv4 = "192.144.11.0/24"
assert get_root_network(ipv4) == 192
Expand Down

0 comments on commit a542492

Please sign in to comment.