Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Predicate decorator #146

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,19 @@ If ``Schema(...)`` encounters a callable (function, class, or object with
...
SchemaError: <lambda>(-12) should evaluate to True

.. code:: python

>>> from schema import Predicate
>>> @Predicate(error="Zero or negative number")
... def positive(x):
... return x >= 0

>>> positive.validate(-12)
Traceback (most recent call last):
...
SchemaError: Zero or negative number


"Validatables"
~~~~~~~~~~~~~~

Expand Down Expand Up @@ -344,6 +357,7 @@ instead of a built-in one.
...
SchemaError: Invalid year


You can see all errors that occurred by accessing exception's ``exc.autos``
for auto-generated error messages, and ``exc.errors`` for errors
which had ``error`` text passed to them.
Expand Down
12 changes: 11 additions & 1 deletion schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

import re


__version__ = '0.6.7'
__all__ = ['Schema',
'And', 'Or', 'Regex', 'Optional', 'Use', 'Forbidden', 'Const',
'And', 'Or', 'Regex', 'Optional', 'Use', 'Forbidden', 'Const', 'Predicate',
'SchemaError',
'SchemaWrongKeyError',
'SchemaMissingKeyError',
Expand Down Expand Up @@ -378,6 +379,15 @@ def validate(self, data):
return data


def Predicate(error=None, ignore_extra_keys=False):
"""
Decorator to wrap function as Schema.
"""
def _Predicate(f):
return Schema(f, error=error, ignore_extra_keys=ignore_extra_keys)
return _Predicate


def _callable_str(callable_):
if hasattr(callable_, '__name__'):
return callable_.__name__
Expand Down
24 changes: 23 additions & 1 deletion test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from schema import (Schema, Use, And, Or, Regex, Optional, Const,
SchemaError, SchemaWrongKeyError,
SchemaMissingKeyError, SchemaUnexpectedTypeError,
SchemaForbiddenKeyError, Forbidden)
SchemaForbiddenKeyError, Forbidden, Predicate)

if sys.version_info[0] == 3:
basestring = str # Python 3 does not have basestring
Expand Down Expand Up @@ -592,3 +592,25 @@ def validate(self, data):
v = {'k': 1, 'd': {'k': 2, 'l': [{'l': [3, 4, 5]}]}}
d = MySchema(s).validate(v)
assert d['k'] == 2 and d['d']['k'] == 3 and d['d']['l'][0]['l'] == [4, 5, 6]


def test_predicate():
@Predicate()
def p1(x):
return x == 1
assert p1._error is None and not p1._ignore_extra_keys

@Predicate("ERROR2", ignore_extra_keys=True)
def p2(x):
return x == 2
assert p2._error is "ERROR2" and p2._ignore_extra_keys
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should use == to compare strings


p2.validate(2) # success

with SE:
try:
p2.validate(0) # failure
except SchemaError as e:
assert e.autos == ['p2(0) should evaluate to True']
assert e.errors == ["ERROR2"]
raise