Skip to content

Commit 255b5a3

Browse files
author
Sylvain MARIE
committed
new @as_failure_raiser decorator to create a failure raiser by decorating an existing validation function. Fixes #36
1 parent c0c6630 commit 255b5a3

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

valid8/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from valid8.utils_typing import Boolean, is_pep484_nonable
22

3-
from valid8.base import Failure, WrappingFailure, failure_raiser
3+
from valid8.base import Failure, ValidationFailed, failure_raiser, as_failure_raiser
44
from valid8.composition import CompositionFailure, AtLeastOneFailed, and_, DidNotFail, not_, AllValidatorsFailed, or_, \
55
XorTooManySuccess, xor_, not_all, fail_on_none, skip_on_none
66

@@ -33,7 +33,7 @@
3333
# -- utils_typing
3434
'Boolean', 'is_pep484_nonable',
3535
# -- base
36-
'Failure', 'ValidationFailed', 'failure_raiser',
36+
'Failure', 'ValidationFailed', 'failure_raiser', 'as_failure_raiser',
3737
# -- composition
3838
'CompositionFailure', 'AtLeastOneFailed', 'and_', 'DidNotFail', 'not_', 'AllValidatorsFailed', 'or_',
3939
'XorTooManySuccess', 'xor_', 'not_all', 'fail_on_none', 'skip_on_none',

valid8/base.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,39 @@ def raiser(x):
495495
return raiser
496496

497497

498+
def as_failure_raiser(failure_type=None, # type: Type[ValidationFailed]
499+
help_msg=None, # type: str
500+
**kw_context_args):
501+
"""
502+
A decorator to define a failure raiser. Same functionality then `failure_raiser`:
503+
504+
>>> import sys, pytest
505+
>>> if sys.version_info < (3, 0):
506+
... pytest.skip('doctest skipped in python 2 because exception namespace is different but details matter')
507+
508+
>>> @as_failure_raiser(help_msg="x should be smaller than 4")
509+
... def is_small_with_details(x):
510+
... return x < 4
511+
>>> is_small_with_details(2)
512+
>>> is_small_with_details(11)
513+
Traceback (most recent call last):
514+
...
515+
valid8.base.ValidationFailed: x should be smaller than 4. Function [is_small_with_details] returned [False] for
516+
value 11.
517+
518+
:param failure_type:
519+
:param help_msg:
520+
:param kw_context_args:
521+
:return:
522+
"""
523+
if failure_type is None and help_msg is None and len(kw_context_args) == 0:
524+
raise ValueError("at least one argument should be provided in @as_failure_raiser")
525+
526+
def apply_decorator(f):
527+
return failure_raiser(f, failure_type=failure_type, help_msg=help_msg, **kw_context_args)
528+
return apply_decorator
529+
530+
498531
class ValueIsNone(Failure, TypeError):
499532
help_msg = "The value must be non-None"
500533

0 commit comments

Comments
 (0)