diff --git a/src/validators/ip_address.py b/src/validators/ip_address.py index 94a42c62..8761486e 100644 --- a/src/validators/ip_address.py +++ b/src/validators/ip_address.py @@ -82,7 +82,8 @@ def ipv4( (Literal[True]): If `value` is a valid IPv4 address. (ValidationError): If `value` is an invalid IPv4 address. """ - if not value: + # Validate untyped callers too, even though the public annotation is str. + if not isinstance(value, str) or not value: # pyright: ignore[reportUnnecessaryIsInstance] return False try: if cidr: @@ -127,7 +128,8 @@ def ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bo (Literal[True]): If `value` is a valid IPv6 address. (ValidationError): If `value` is an invalid IPv6 address. """ - if not value: + # Validate untyped callers too, even though the public annotation is str. + if not isinstance(value, str) or not value: # pyright: ignore[reportUnnecessaryIsInstance] return False try: if cidr: diff --git a/tests/test_ip_address.py b/tests/test_ip_address.py index ed6fd7d4..745aea79 100644 --- a/tests/test_ip_address.py +++ b/tests/test_ip_address.py @@ -1,5 +1,8 @@ """Test IP Address.""" +# standard +from typing import Any, Optional + # external import pytest @@ -7,6 +10,28 @@ from validators import ValidationError, ipv4, ipv6 +@pytest.mark.parametrize("address", [True, 3232235777, b"\x7f\x00\x00\x01", ("10.0.0.0", 8)]) +@pytest.mark.parametrize("cidr", [True, False]) +@pytest.mark.parametrize("private", [None, True, False]) +def test_rejects_non_string_ipv4_address(address: Any, cidr: bool, private: Optional[bool]): + """Reject non-string inputs even when ipaddress accepts their representation.""" + assert isinstance(ipv4(address, cidr=cidr, private=private), ValidationError) + + +@pytest.mark.parametrize("address", [True, 1, bytes(16), ("::", 0)]) +@pytest.mark.parametrize("cidr", [True, False]) +@pytest.mark.parametrize("strict", [True, False]) +def test_rejects_non_string_ipv6_address(address: Any, cidr: bool, strict: bool): + """Reject non-string addresses and avoid errors from CIDR string operations.""" + assert isinstance(ipv6(address, cidr=cidr, strict=strict), ValidationError) + + +@pytest.mark.parametrize("address", [True, 3232235777, b"\x7f\x00\x00\x01", ("10.0.0.0", 8)]) +def test_rejects_non_string_strict_ipv4_address(address: Any): + """Strict CIDR validation must reject non-string input without an AttributeError.""" + assert isinstance(ipv4(address, strict=True), ValidationError) + + @pytest.mark.parametrize( ("address",), [