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 SomeOf validator #314

Merged
merged 5 commits into from
Dec 7, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 10 additions & 0 deletions voluptuous/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,13 @@ class NotInInvalid(Invalid):

class ExactSequenceInvalid(Invalid):
pass


class NotEnoughValid(Invalid):
"""The value did not pass enough validations."""
pass


class TooManyValid(Invalid):
"""The value passed more than expected validations."""
pass
35 changes: 34 additions & 1 deletion voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
Url, MultipleInvalid, LiteralInvalid, TypeInvalid, NotIn, Match, Email,
Replace, Range, Coerce, All, Any, Length, FqdnUrl, ALLOW_EXTRA, PREVENT_EXTRA,
validate, ExactSequence, Equal, Unordered, Number, Maybe, Datetime, Date,
Contains, Marker, IsDir, IsFile, PathExists)
Contains, Marker, IsDir, IsFile, PathExists, SomeOf, TooManyValid, raises)
from voluptuous.humanize import humanize_error
from voluptuous.util import u

Expand Down Expand Up @@ -968,3 +968,36 @@ def test_description():

required = Required('key', description='Hello')
assert required.description == 'Hello'


def test_SomeOf_min_validation():
validator = All(Length(min=8), SomeOf(
min_valid=3,
validators=[Match(r'.*[A-Z]', 'no uppercase letters'),
Match(r'.*[a-z]', 'no lowercase letters'),
Match(r'.*[0-9]', 'no numbers'),
Match(r'.*[$@$!%*#?&^:;/<,>|{}()\-\'._+=]', 'no symbols')]))

validator('ffe532A1!')
with raises(MultipleInvalid, 'length of value must be at least 8'):
validator('a')

with raises(MultipleInvalid, 'no uppercase letters, no lowercase letters'):
validator('wqs2!#s111')

with raises(MultipleInvalid, 'no lowercase letters, no symbols'):
validator('3A34SDEF5')


def test_SomeOf_max_validation():
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add a test for checking the assert statement too using AssertionError

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

validator = SomeOf(
min_valid=0,
max_valid=2,
validators=[Match(r'.*[A-Z]', 'no uppercase letters'),
Match(r'.*[a-z]', 'no lowercase letters'),
Match(r'.*[0-9]', 'no numbers')],
msg='max validation test failed')

validator('Aa')
with raises(TooManyValid, 'max validation test failed'):
validator('Aa1')
49 changes: 48 additions & 1 deletion voluptuous/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
from voluptuous.error import (MultipleInvalid, CoerceInvalid, TrueInvalid, FalseInvalid, BooleanInvalid, Invalid,
AnyInvalid, AllInvalid, MatchInvalid, UrlInvalid, EmailInvalid, FileInvalid, DirInvalid,
RangeInvalid, PathInvalid, ExactSequenceInvalid, LengthInvalid, DatetimeInvalid,
DateInvalid, InInvalid, TypeInvalid, NotInInvalid, ContainsInvalid)
DateInvalid, InInvalid, TypeInvalid, NotInInvalid, ContainsInvalid, NotEnoughValid,
TooManyValid)

if sys.version_info >= (3,):
import urllib.parse as urlparse
Expand Down Expand Up @@ -933,3 +934,49 @@ def _get_precision_scale(self, number):
raise Invalid(self.msg or 'Value must be a number enclosed with string')

return (len(decimal_num.as_tuple().digits), -(decimal_num.as_tuple().exponent), decimal_num)


class SomeOf(object):
"""Value must pass at least some validations, determined by the given parameter

The output of each validator is passed as input to the next.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

description will be improved in the next update of this PR (I'm sure there will be so I'm waiting with pushing it 😄 )

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haha.. Let's not rely on it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will push it asap


>>> validate = Schema(SomeOf(min_valid=2, validators=[Range(1, 5), Any(float, int), 6.6]))
>>> validate(6.6)
6.6
>>> validate(3)
3
>>> with raises(MultipleInvalid, 'value must be at most 5, not a valid value'):
... validate(6.2)
"""

def __init__(self, min_valid, validators, max_valid=None, **kwargs):
self.min_valid = min_valid or 0
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why min_valid is not a default keyword argument while max_valid is?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Originally I only needed "minimum valid schemas" and just added "max valid" for completeness. So for me, min_valid was always needed. We can put them both as optional, and assert that either of them has a value (otherwise, what's the point of this validator).

Sounds good?

self.max_valid = max_valid or len(validators)
self.validators = validators
self.msg = kwargs.pop('msg', None)
self._schemas = [Schema(val, **kwargs) for val in validators]

def __call__(self, v):
errors = []
for schema in self._schemas:
try:
v = schema(v)
except Invalid as e:
errors.append(e)

passed_count = len(self._schemas) - len(errors)
if self.min_valid <= passed_count <= self.max_valid:
return v

msg = self.msg
if not msg:
msg = ', '.join(map(str, errors))

if passed_count > self.max_valid:
raise TooManyValid(msg)
raise NotEnoughValid(msg)

def __repr__(self):
return 'SomeOf(min_valid=%s, validators=[%s], max_valid=%s, msg=%r)' % (
self.min_valid, ", ".join(repr(v) for v in self.validators), self.max_valid, self.msg)