Skip to content
This repository has been archived by the owner on Apr 10, 2023. It is now read-only.

Commit

Permalink
Add IpAddress field
Browse files Browse the repository at this point in the history
  • Loading branch information
rossmacarthur committed Feb 15, 2020
1 parent 5862375 commit 667ca96
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
3 changes: 3 additions & 0 deletions RELEASES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ Releases

*Unreleased*

- Add ``IpAddress`` field.
- Extended string types now subclass ``Text`` not ``Str``.
- Remove `fields.create()` method
- Completely rework error handling.
- Make ``Tag.lookup_tag`` default to module + qualname.

Expand Down
22 changes: 22 additions & 0 deletions src/serde/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1118,6 +1118,28 @@ def normalize(self, value):
return value


class IpAddress(Text):
"""
A text field that asserts the text is a valid IP address.
The validation is delegated to `validators.ip_address.ipv4` and
`validators.ip_address.ipv6`.
Args:
**kwargs: keyword arguments for the `Field` constructor.
"""

def __init__(self, **kwargs):
super(IpAddress, self).__init__(**kwargs)
self._validator_ipv4 = try_lookup('validators.ip_address.ipv4')
self._validator_ipv6 = try_lookup('validators.ip_address.ipv6')

def validate(self, value):
super(IpAddress, self).validate(value)
if not self._validator_ipv4(value) and not self._validator_ipv6(value):
raise ValidationError('invalid IP address', value=value)


def create_from(foreign, name=None, human=None):
"""
Create a new `Text` class from a `validators` function.
Expand Down
16 changes: 16 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
FrozenSet,
Instance,
Int,
IpAddress,
List,
Literal,
Nested,
Expand Down Expand Up @@ -1395,3 +1396,18 @@ def test_validate(self):
field.validate(uuid.UUID('2d7026c8-cc58-11e8-bd7a-784f4386978e'))
with raises(ValidationError):
field.validate('2d7026c8-cc58-11e8-bd7a-784f4386978e')


class TestIpAddress:
def test___init__(self):
# Construct a basic IpAddress and check values are set correctly.
field = IpAddress(validators=[None])
assert field.validators == [None]

def test_validate(self):
# An IpAddress simply validates that the text is an IP address.
field = IpAddress()
field.validate(u'123.0.0.7')
field.validate(u'::ffff:192.0.2.12')
with raises(ValidationError):
field.validate(u'900.80.70.11')

0 comments on commit 667ca96

Please sign in to comment.