Skip to content

Commit

Permalink
Implement nested validations.
Browse files Browse the repository at this point in the history
This allows a list of validations to contain a dictionary of yet
more validations in order to accomodate writing validations
for nested dictionaries.
  • Loading branch information
= committed Jan 29, 2014
1 parent b64e291 commit 8f5a2eb
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
37 changes: 37 additions & 0 deletions tests/test_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,40 @@ def test_conditional_validator(self):
}
assert validate(passes, test_case)[0]
assert not validate(fails, test_case)[0]

def test_nested_validations(self):
passes = {
"foo": [Required, Equals(1)],
"bar": [
Required,
{
"baz": [Required, Equals(2)],
"qux": [Required, {
"quux": [Required, Equals(3)]
}]
}
]
}
fails = {
"foo": [Required, Equals(2)],
"bar": [
Required,
{
"baz": [Required, Equals(3)],
"qux": [Required, {
"quux": [Required, Equals(4)]
}]
}
]
}
test_case = {
"foo": 1,
"bar": {
"baz": 2,
"qux": {
"quux": 3
}
}
}
assert validate(passes, test_case)[0]
assert not validate(fails, test_case)[0]
11 changes: 10 additions & 1 deletion validator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,16 @@ def validate(validation, dictionary):
errors[key] = "must be present"
continue
for v in validation[key]:
# skip Required, since it was already
# Ok, need to deal with nested
# validations.
if isinstance(v, dict):
valid, nested_errors = validate(v, dictionary[key])
if nested_errors:
errors[key].append(nested_errors)
continue
# Done with that, on to the actual
# validating bit.
# Skip Required, since it was already
# handled before this point.
if not v == Required:
# special handling for the
Expand Down

0 comments on commit 8f5a2eb

Please sign in to comment.