Skip to content

Commit

Permalink
Merge pull request #374 from grleblanc/fix-ipv4-private
Browse files Browse the repository at this point in the history
fix(ip_address): properly handle private is false
  • Loading branch information
yozachar committed May 17, 2024
2 parents d46cd58 + 0623b4a commit bcb1342
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/validators/ip_address.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
def _check_private_ip(value: str, is_private: Optional[bool]):
if is_private is None:
return True
if is_private and (
if (
any(
value.startswith(l_bit)
for l_bit in {
Expand All @@ -33,8 +33,9 @@ def _check_private_ip(value: str, is_private: Optional[bool]):
or re.match(r"^172\.(?:1[6-9]|2\d|3[0-1])\.", value) # private
or re.match(r"^(?:22[4-9]|23[0-9]|24[0-9]|25[0-5])\.", value) # broadcast
):
return True
return False
return is_private

return not is_private


@validator
Expand Down
56 changes: 56 additions & 0 deletions tests/test_ip_address.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,59 @@ def test_returns_failed_validation_on_invalid_ipv6_cidr_address(
):
"""Test returns failed validation on invalid ipv6 CIDR address."""
assert isinstance(ipv6(address, cidr=cidr, strict=strict, host_bit=host_bit), ValidationError)


@pytest.mark.parametrize(
("address", "private"),
[
("10.1.1.1", True),
("192.168.1.1", True),
("169.254.1.1", True),
("127.0.0.1", True),
("0.0.0.0", True),
],
)
def test_returns_true_on_valid_private_ipv4_address(address: str, private: bool):
"""Test returns true on private ipv4 address."""
assert ipv4(address, private=private)


@pytest.mark.parametrize(
("address", "private"),
[
("1.1.1.1", True),
("192.169.1.1", True),
("7.53.12.1", True),
],
)
def test_returns_failed_validation_on_invalid_private_ipv4_address(address: str, private: bool):
"""Test returns failed validation on invalid private ipv4 address."""
assert isinstance(ipv4(address, private=private), ValidationError)


@pytest.mark.parametrize(
("address", "private"),
[
("1.1.1.1", False),
("192.169.1.1", False),
("7.53.12.1", False),
],
)
def test_returns_true_on_valid_public_ipv4_address(address: str, private: bool):
"""Test returns true on valid public ipv4 address."""
assert ipv4(address, private=private)


@pytest.mark.parametrize(
("address", "private"),
[
("10.1.1.1", False),
("192.168.1.1", False),
("169.254.1.1", False),
("127.0.0.1", False),
("0.0.0.0", False),
],
)
def test_returns_failed_validation_on_invalid_public_ipv4_address(address: str, private: bool):
"""Test returns failed validation on private ipv4 address."""
assert isinstance(ipv4(address, private=private), ValidationError)

0 comments on commit bcb1342

Please sign in to comment.