Skip to content

Commit

Permalink
Fix #379: Regression with Any and required
Browse files Browse the repository at this point in the history
In 0.9.3, the `Schema`s associated to the `Any` validators where setup with the
`required` argument given to `Any`

https://github.com/alecthomas/voluptuous/blob/0.9.3/voluptuous/validators.py#L218

This allow us to write something like:

```
Schema(Any({'a': int}, {'b': str}, required=True))
```

In recent version, the `required` keyword is ignored.

This patch pass the required argument to the `Schema`s associated with the
`SubValidator`.
  • Loading branch information
Cédric Cabessa committed Jan 11, 2019
1 parent 7e18e1c commit 7b4efb4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
27 changes: 27 additions & 0 deletions voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1322,3 +1322,30 @@ def test_strip_util_handles_various_inputs():
assert Strip(u"3") == u"3"
assert Strip(b'\xe2\x98\x83'.decode("UTF-8")) == b'\xe2\x98\x83'.decode("UTF-8")
assert Strip(u" aaa ") == u"aaa"


def test_any_required():
schema = Schema(Any({'a': int}, {'b': str}, required=True))

try:
schema({})
except MultipleInvalid as e:
assert_equal(str(e),
"required key not provided @ data['a']")
else:
assert False, "Did not raise Invalid for MultipleInvalid"


def test_any_required_with_subschema():
schema = Schema(Any({'a': Any(float, int)},
{'b': int},
{'c': {'aa': int}},
required=True))

try:
schema({})
except MultipleInvalid as e:
assert_equal(str(e),
"required key not provided @ data['a']")
else:
assert False, "Did not raise Invalid for MultipleInvalid"
9 changes: 5 additions & 4 deletions voluptuous/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,12 +192,13 @@ class _WithSubValidators(object):
def __init__(self, *validators, **kwargs):
self.validators = validators
self.msg = kwargs.pop('msg', None)
self.required = kwargs.pop('required', False)

def __voluptuous_compile__(self, schema):
self._compiled = [
schema._compile(v)
for v in self.validators
]
self._compiled = []
for v in self.validators:
schema.required = self.required
self._compiled.append(schema._compile(v))
return self._run

def _run(self, path, value):
Expand Down

0 comments on commit 7b4efb4

Please sign in to comment.