diff options
author | monopolis <anders@null-graph.eu> | 2020-12-06 21:28:35 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-12-06 21:28:35 +0100 |
commit | da3cc967f7b16f18bf8c1feacfeced8f10ce9e40 (patch) | |
tree | 7ffb18f734acdddc581fbf8c63ce3c48bf41692e | |
parent | de695d855949b44ec1cce41f243ad9c6a39034fd (diff) | |
download | voluptuous-da3cc967f7b16f18bf8c1feacfeced8f10ce9e40.tar.gz |
Ensure `Maybe` propagates error information (#411)
Due to Any evaluating all options, and raising the exception
from the first encountered error, Maybe would discard the
expected error raised by the provided validator and only
raise a invalid value error (due to values not being None).
This commit changes the order of the validators in Maybe so
that the first evaluated error, and thus returned is that of
the provided validator.
-rw-r--r-- | voluptuous/tests/tests.py | 18 | ||||
-rw-r--r-- | voluptuous/validators.py | 2 |
2 files changed, 18 insertions, 2 deletions
diff --git a/voluptuous/tests/tests.py b/voluptuous/tests/tests.py index 28598f7..428b157 100644 --- a/voluptuous/tests/tests.py +++ b/voluptuous/tests/tests.py @@ -516,7 +516,7 @@ def test_repr(): ) assert_equal(repr(coerce_), "Coerce(int, msg='moo')") assert_equal(repr(all_), "All('10', Coerce(int, msg=None), msg='all msg')") - assert_equal(repr(maybe_int), "Any(None, %s, msg=None)" % str(int)) + assert_equal(repr(maybe_int), "Any(%s, None, msg=None)" % str(int)) def test_list_validation_messages(): @@ -1530,3 +1530,19 @@ def test_any_with_discriminant(): assert_equal(str(e), 'expected bool for dictionary value @ data[\'implementation\'][\'c-value\']') else: assert False, "Did not raise correct Invalid" + +def test_maybe_returns_subvalidator_error(): + schema = Schema(Maybe(Range(1, 2))) + + # The following should be valid + schema(None) + schema(1) + schema(2) + + try: + # Should trigger a MultipleInvalid exception + schema(3) + except MultipleInvalid as e: + assert_equal(str(e), "value must be at most 2") + else: + assert False, "Did not raise correct Invalid" diff --git a/voluptuous/validators.py b/voluptuous/validators.py index 5e9a932..7b2536c 100644 --- a/voluptuous/validators.py +++ b/voluptuous/validators.py @@ -555,7 +555,7 @@ def Maybe(validator, msg=None): ... s("string") """ - return Any(None, validator, msg=msg) + return Any(validator, None, msg=msg) class Range(object): |