Skip to content

Commit

Permalink
Maybe propagates error information (#369)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
monopolis committed Nov 29, 2019
1 parent 858ceee commit 1826566
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
20 changes: 18 additions & 2 deletions voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,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():
Expand Down Expand Up @@ -1437,9 +1437,25 @@ def test_any_with_discriminant():
schema({
'implementation': {
'type': 'C',
'c-value': None,}
'c-value': None,}
})
except MultipleInvalid as e:
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 UrlInvalid 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"
2 changes: 1 addition & 1 deletion voluptuous/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ def Maybe(validator, msg=None):
... s("string")
"""
return Any(None, validator, msg=msg)
return Any(validator, None, msg=msg)


class Range(object):
Expand Down

0 comments on commit 1826566

Please sign in to comment.