Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding matches_re validator #552

Merged
merged 20 commits into from
Sep 9, 2019
Merged
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
1 change: 1 addition & 0 deletions changelog.d/552.change.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added ``attr.validators.matches_re``
18 changes: 18 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,24 @@ Validators
attr.exceptions.NotCallableError: 'x' must be callable (got 'not a callable' that is a <class 'str'>).


.. autofunction:: attr.validators.matches_re

For example:

.. doctest::

>>> @attr.s
... class User(object):
... email = attr.ib(validator=attr.validators.matches_re(
... "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"))
>>> User(email="[email protected]")
User(email='[email protected]')
>>> User(email="[email protected]@test.com")
Traceback (most recent call last):
...
ValueError: ("'email' must match regex '(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\.[a-zA-Z0-9-.]+$)' ('[email protected]@test.com' doesn't)", Attribute(name='email', default=NOTHING, validator=<matches_re validator for pattern re.compile('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)')>, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None, kw_only=False), re.compile('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)'), '[email protected]@test.com')


.. autofunction:: attr.validators.deep_iterable

For example:
Expand Down
73 changes: 73 additions & 0 deletions src/attr/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from __future__ import absolute_import, division, print_function

import re

from ._make import _AndValidator, and_, attrib, attrs
from .exceptions import NotCallableError

Expand All @@ -15,6 +17,7 @@
"in_",
"instance_of",
"is_callable",
"matches_re",
"optional",
"provides",
]
Expand Down Expand Up @@ -64,6 +67,76 @@ def instance_of(type):
return _InstanceOfValidator(type)


@attrs(repr=False, frozen=True)
class _MatchesReValidator(object):
regex = attrib()
flags = attrib()
match_func = attrib()

def __call__(self, inst, attr, value):
"""
We use a callable class to be able to change the ``__repr__``.
"""
if not self.match_func(value):
raise ValueError(
"'{name}' must match regex {regex!r}"
" ({value!r} doesn't)".format(
name=attr.name, regex=self.regex.pattern, value=value
),
attr,
self.regex,
value,
)

def __repr__(self):
return "<matches_re validator for pattern {regex!r}>".format(
regex=self.regex
)


def matches_re(regex, flags=0, func=None):
"""
A validator that raises :exc:`ValueError` if the initializer is called
with a string that doesn't match the given regex, and :exc:`TypeError`
if the initializer is called with a non-string.

:param regex: a regex string to match against
:param flags: flags that will be passed to the underlying re function
(default 0)
:param func: which underlying re function to call (options are
`re.fullmatch()`, `re.search()`, `re.match()`, default `re.fullmatch`)

.. versionadded:: 19.1.0
"""
fullmatch = getattr(re, "fullmatch", None)
valid_funcs = (fullmatch, None, re.search, re.match)
if func not in valid_funcs:
raise ValueError(
"'func' must be one of {}".format(
", ".join([repr(e) for e in set(valid_funcs)])
)
)
# non-int flags gives an okay error message in re, so rely on that
if func is None:
if fullmatch:
func = fullmatch
else:
# python 2 fullmatch emulation
if isinstance(regex, (type(u""), type(b""))):
# pylint flags references to basestring or unicode builtins
# avoid swallowing TypeError if regex is not basestring
regex = r"(?:{})\Z".format(regex)
func = re.match
regex = re.compile(regex, flags)
if func is re.match:
match_func = regex.match
elif func is re.search:
match_func = regex.search
elif func is re.fullmatch: # pragma: no branch
match_func = regex.fullmatch
return _MatchesReValidator(regex, flags, match_func)


@attrs(repr=False, slots=True, hash=True)
class _ProvidesValidator(object):
interface = attrib()
Expand Down
4 changes: 4 additions & 0 deletions src/attr/validators.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ from typing import (
Tuple,
Iterable,
Mapping,
Callable,
)
from . import _ValidatorType

Expand All @@ -27,6 +28,9 @@ def optional(
) -> _ValidatorType[Optional[_T]]: ...
def in_(options: Container[_T]) -> _ValidatorType[_T]: ...
def and_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ...
def matches_re(
regex: str, flags: int, func: Union[None, Callable[[str, str, int], ...]]
): ...
def deep_iterable(
member_validator: _ValidatorType[_T],
iterable_validator: Optional[_ValidatorType[_I]] = ...,
Expand Down
63 changes: 63 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from __future__ import absolute_import, division, print_function

import re

import pytest
import zope.interface

Expand All @@ -19,6 +21,7 @@
in_,
instance_of,
is_callable,
matches_re,
optional,
provides,
)
Expand Down Expand Up @@ -78,6 +81,66 @@ def test_repr(self):
) == repr(v)


class TestMatchesRe(object):
"""
Tests for `matches_re`.
"""

def test_in_all(self):
"""
validator is in ``__all__``.
"""
assert matches_re.__name__ in validator_module.__all__

def test_match(self):
"""
default re.match behavior
"""

@attr.s
class ReTester(object):
str_match = attr.ib(validator=matches_re("a"))

ReTester("a") # shouldn't raise exceptions
with pytest.raises(TypeError):
ReTester(1)
with pytest.raises(ValueError):
ReTester("1")
with pytest.raises(ValueError):
ReTester("a1")

def test_extra_args(self):
"""
flags and non-default match function behavior
"""

@attr.s
class MatchTester(object):
val = attr.ib(validator=matches_re("a", re.IGNORECASE, re.match))

MatchTester("A1") # test flags and using re.match

@attr.s
class SearchTester(object):
val = attr.ib(validator=matches_re("a", 0, re.search))

SearchTester("bab") # re.search will match

def test_bad_args_and_repr(self):
"""
miscellaneous behaviors: repr and
"""
with pytest.raises(TypeError):
matches_re(0)
with pytest.raises(TypeError):
matches_re("a", "a")
with pytest.raises(ValueError):
matches_re("a", 0, lambda: None)
for m in (None, getattr(re, "fullmatch", None), re.match, re.search):
matches_re("a", 0, m)
repr(matches_re("a"))


def always_pass(_, __, ___):
"""
Toy validator that always passses.
Expand Down