Skip to content

Commit

Permalink
refactor(tests): fix few tests, use pytest.raises, extend raises help…
Browse files Browse the repository at this point in the history
…er (#500)
  • Loading branch information
antoni-szych-rtbhouse authored Dec 13, 2023
1 parent 264b7e4 commit dec0fcb
Show file tree
Hide file tree
Showing 3 changed files with 235 additions and 425 deletions.
59 changes: 21 additions & 38 deletions voluptuous/schema_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,6 @@
import typing
from voluptuous.error import Error

if sys.version_info >= (3,):
long = int
unicode = str
basestring = str
ifilter = filter

def iteritems(d):
return d.items()
else:
from itertools import ifilter

def iteritems(d):
return d.iteritems()

if sys.version_info >= (3, 3):
_Mapping = collections.abc.Mapping
else:
_Mapping = collections.Mapping

"""Schema validation for Python data structures.
Given eg. a nested data structure like this:
Expand Down Expand Up @@ -151,6 +132,8 @@ def raises(exc, msg: typing.Optional[str] = None, regex: typing.Optional[re.Patt
assert str(e) == msg, '%r != %r' % (str(e), msg)
if regex is not None:
assert re.search(regex, str(e)), '%r does not match %r' % (str(e), regex)
else:
raise AssertionError(f"Did not raise exception {exc.__name__}")


def Extra(_) -> None:
Expand All @@ -162,13 +145,13 @@ def Extra(_) -> None:
# deprecated object, so we just leave an alias here instead.
extra = Extra

primitive_types = (bool, bytes, int, long, str, unicode, float, complex)
primitive_types = (bool, bytes, int, str, float, complex)

Schemable = typing.Union[
'Schema', 'Object',
_Mapping,
collections.abc.Mapping,
list, tuple, frozenset, set,
bool, bytes, int, long, str, unicode, float, complex,
bool, bytes, int, str, float, complex,
type, object, dict, None, typing.Callable
]

Expand All @@ -187,9 +170,9 @@ class Schema(object):
For Example:
>>> v = Schema({Required('a'): unicode})
>>> v1 = Schema({Required('a'): unicode})
>>> v2 = Schema({Required('b'): unicode})
>>> v = Schema({Required('a'): str})
>>> v1 = Schema({Required('a'): str})
>>> v2 = Schema({Required('b'): str})
>>> assert v == v1
>>> assert v != v2
Expand Down Expand Up @@ -254,7 +237,7 @@ def value_to_schema_type(value):
if len(value) == 0:
return dict
return {k: value_to_schema_type(v)
for k, v in iteritems(value)}
for k, v in value.items()}
if isinstance(value, list):
if len(value) == 0:
return list
Expand Down Expand Up @@ -300,7 +283,7 @@ def _compile(self, schema):
return schema.__voluptuous_compile__(self)
if isinstance(schema, Object):
return self._compile_object(schema)
if isinstance(schema, _Mapping):
if isinstance(schema, collections.abc.Mapping):
return self._compile_dict(schema)
elif isinstance(schema, list):
return self._compile_list(schema)
Expand Down Expand Up @@ -333,7 +316,7 @@ def _compile_mapping(self, schema, invalid_msg=None):
or isinstance(key, Optional))

_compiled_schema = {}
for skey, svalue in iteritems(schema):
for skey, svalue in schema.items():
new_key = self._compile(skey)
new_value = self._compile(svalue)
_compiled_schema[skey] = (new_key, new_value)
Expand Down Expand Up @@ -477,7 +460,7 @@ def validate_object(path, data):
if schema.cls is not UNDEFINED and not isinstance(data, schema.cls):
raise er.ObjectInvalid('expected a {0!r}'.format(schema.cls), path)
iterable = _iterate_object(data)
iterable = ifilter(lambda item: item[1] is not None, iterable)
iterable = filter(lambda item: item[1] is not None, iterable)
out = base_validate(path, iterable, {})
return type(data)(**out)

Expand Down Expand Up @@ -608,7 +591,7 @@ def validate_dict(path, data):
raise er.MultipleInvalid(errors)

out = data.__class__()
return base_validate(path, iteritems(data), out)
return base_validate(path, data.items(), out)

return validate_dict

Expand Down Expand Up @@ -767,7 +750,7 @@ def key_literal(key):

# for each item in the extension schema, replace duplicates
# or add new keys
for key, value in iteritems(schema):
for key, value in schema.items():

# if the key is already in the dictionary, we need to replace it
# transform key to literal before checking presence
Expand Down Expand Up @@ -896,7 +879,7 @@ def _iterate_mapping_candidates(schema):
# Without this, Extra might appear first in the iterator, and fail to
# validate a key even though it's a Required that has its own validation,
# generating a false positive.
return sorted(iteritems(schema), key=_sort_item)
return sorted(schema.items(), key=_sort_item)


def _iterate_object(obj):
Expand All @@ -911,7 +894,7 @@ def _iterate_object(obj):
# maybe we have named tuple here?
if hasattr(obj, '_asdict'):
d = obj._asdict()
for item in iteritems(d):
for item in d.items():
yield item
try:
slots = obj.__slots__
Expand Down Expand Up @@ -1076,15 +1059,15 @@ class Exclusive(Optional):
>>> msg = 'Please, use only one type of authentication at the same time.'
>>> schema = Schema({
... Exclusive('classic', 'auth', msg=msg):{
... Required('email'): basestring,
... Required('password'): basestring
... Required('email'): str,
... Required('password'): str
... },
... Exclusive('internal', 'auth', msg=msg):{
... Required('secret_key'): basestring
... Required('secret_key'): str
... },
... Exclusive('social', 'auth', msg=msg):{
... Required('social_network'): basestring,
... Required('token'): basestring
... Required('social_network'): str,
... Required('token'): str
... }
... })
Expand Down
Loading

0 comments on commit dec0fcb

Please sign in to comment.