Skip to content
Open
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
6 changes: 4 additions & 2 deletions src/validators/ip_address.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
25 changes: 25 additions & 0 deletions tests/test_ip_address.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,37 @@
"""Test IP Address."""

# standard
from typing import Any, Optional

# external
import pytest

# local
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",),
[
Expand Down