diff --git a/voluptuous/tests/tests.py b/voluptuous/tests/tests.py index 8759b13..f47b75a 100644 --- a/voluptuous/tests/tests.py +++ b/voluptuous/tests/tests.py @@ -5,7 +5,7 @@ Schema, Required, Optional, Extra, Invalid, In, Remove, Literal, Url, MultipleInvalid, LiteralInvalid, NotIn, Match, Email, Replace, Range, Coerce, All, Any, Length, FqdnUrl, ALLOW_EXTRA, PREVENT_EXTRA, - validate, ExactSequence, Equal, Unordered, Number + validate, ExactSequence, Equal, Unordered, Number, Maybe ) from voluptuous.humanize import humanize_error from voluptuous.util import to_utf8_py2, u @@ -544,6 +544,19 @@ def fn(arg): fn(1) +def test_schema_decorator_no_args(): + @validate(int, __return__=Maybe(int)) + def fn(arg): + if arg == 0: + return None + else: + return arg + + fn(1) + fn(0) + + + def test_schema_decorator_unmatch_return_with_args(): @validate(int, __return__=int) def fn(arg): diff --git a/voluptuous/validators.py b/voluptuous/validators.py index 51e247f..8ee1aa9 100644 --- a/voluptuous/validators.py +++ b/voluptuous/validators.py @@ -459,6 +459,14 @@ def PathExists(v): raise PathInvalid("Not a Path") +class Maybe(object): + def __init__(self, kind): + self.kind = kind + + def __call__(self, v): + return v is None or isinstance(v, self.kind) + + class Range(object): """Limit a value to a range.