Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 5 additions & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
2.7.14
3.6.3
3.3.6
3.4.7
3.5.2

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this file was accidentally added because I was working with pyenv which proved to be very useful for testing locally with multiple python versions.

I was going to remove it, but then thought it would be a good to have such convention as repository users, to use pyenv. your call.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@alecthomas What do you think about adding this to the package?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Let's remove this for now and create an issue where we will continue this discussion.

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
Copy Markdown
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
Copy Markdown
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')
61 changes: 60 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,61 @@ 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.
Optionally, number of passed validations can be capped.

The output of each validator is passed as input to the next.

Copy link
Copy Markdown
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
Copy Markdown
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
Copy Markdown
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


:param min_valid: Minimum number of valid schemas.
:param validators: a list of schemas or validators to match input against
:param max_valid: Maximum number of valid schemas.
:param msg: Message to deliver to user if validation fails.
:param kwargs: All other keyword arguments are passed to the sub-Schema constructors.

:raises NotEnoughValid: if the minimum number of validations isn't met
:raises TooManyValid: if the more validations than the given amount is met

>>> 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, validators, min_valid=None, max_valid=None, **kwargs):
assert min_valid is not None or max_valid is not None, \
'when using "%s" you should specify at least one of min_valid and max_valid' % (type(self).__name__,)
self.min_valid = min_valid or 0

Copy link
Copy Markdown
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
Copy Markdown
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)