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

thb/fix-283 #298

Merged
merged 2 commits into from
Nov 2, 2017
Merged
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
24 changes: 1 addition & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ contain anything, specify it as `list`:
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "not a valid value"
>>> str(exc) == "not a valid value @ data[1]"
True
>>> schema([])
[]
Expand Down Expand Up @@ -368,28 +368,6 @@ token `extra` as a key:

```

However, an empty dict (`{}`) is treated as is. If you want to specify a list that can
contain anything, specify it as `dict`:

```pycon
>>> schema = Schema({}, extra=ALLOW_EXTRA) # don't do this
>>> try:
... schema({'extra': 1})
... raise AssertionError('MultipleInvalid not raised')
... except MultipleInvalid as e:
... exc = e
>>> str(exc) == "not a valid value"
True
>>> schema({})
{}
>>> schema = Schema(dict) # do this instead
>>> schema({})
{}
>>> schema({'extra': 1})
{'extra': 1}

```

#### Required dictionary keys

By default, keys in the schema are not required to be in the data:
Expand Down
18 changes: 8 additions & 10 deletions voluptuous/schema_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,9 @@ def _compile(self, schema):
return lambda _, v: v
if isinstance(schema, Object):
return self._compile_object(schema)
if isinstance(schema, collections.Mapping) and len(schema):
if isinstance(schema, collections.Mapping):
return self._compile_dict(schema)
elif isinstance(schema, list) and len(schema):
elif isinstance(schema, list):
return self._compile_list(schema)
elif isinstance(schema, tuple):
return self._compile_tuple(schema)
Expand Down Expand Up @@ -408,7 +408,7 @@ def _compile_dict(self, schema):

A dictionary schema will only validate a dictionary:

>>> validate = Schema({'prop': str})
>>> validate = Schema({})
>>> with raises(er.MultipleInvalid, 'expected a dictionary'):
... validate([])

Expand All @@ -423,6 +423,7 @@ def _compile_dict(self, schema):
>>> with raises(er.MultipleInvalid, "extra keys not allowed @ data['two']"):
... validate({'two': 'three'})


Validation function, in this case the "int" type:

>>> validate = Schema({'one': 'two', 'three': 'four', int: str})
Expand All @@ -432,17 +433,10 @@ def _compile_dict(self, schema):
>>> validate({10: 'twenty'})
{10: 'twenty'}

An empty dictionary is matched as value:

>>> validate = Schema({})
>>> with raises(er.MultipleInvalid, 'not a valid value'):
... validate([])

By default, a "type" in the schema (in this case "int") will be used
purely to validate that the corresponding value is of that type. It
will not Coerce the value:

>>> validate = Schema({'one': 'two', 'three': 'four', int: str})
>>> with raises(er.MultipleInvalid, "extra keys not allowed @ data['10']"):
... validate({'10': 'twenty'})

Expand Down Expand Up @@ -557,6 +551,10 @@ def validate_sequence(path, data):

# Empty seq schema, allow any data.
if not schema:
if data:
raise er.MultipleInvalid([
er.ValueInvalid('not a valid value', [value]) for value in data
])
return data

out = []
Expand Down
34 changes: 0 additions & 34 deletions voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,40 +566,6 @@ def test_empty_list_as_exact():
s([])


def test_empty_dict_as_exact():
# {} always evaluates as {}
s = Schema({})
assert_raises(Invalid, s, {'extra': 1})
s = Schema({}, extra=ALLOW_EXTRA) # this should not be used
assert_raises(Invalid, s, {'extra': 1})

# {...} evaluates as Schema({...})
s = Schema({'foo': int})
assert_raises(Invalid, s, {'foo': 1, 'extra': 1})
s = Schema({'foo': int}, extra=ALLOW_EXTRA)
s({'foo': 1, 'extra': 1})

# dict matches {} or {...}
s = Schema(dict)
s({'extra': 1})
s({})
s = Schema(dict, extra=PREVENT_EXTRA)
s({'extra': 1})
s({})

# nested {} evaluate as {}
s = Schema({
'inner': {}
}, extra=ALLOW_EXTRA)
assert_raises(Invalid, s, {'inner': {'extra': 1}})
s({})
s = Schema({
'inner': Schema({}, extra=ALLOW_EXTRA)
})
assert_raises(Invalid, s, {'inner': {'extra': 1}})
s({})


def test_schema_decorator_match_with_args():
@validate(int)
def fn(arg):
Expand Down