I'm using Cerberus to validate payloads that have a type
and a data
field. Depending on the value of type
(test
or build
), I want to validate data
against different constraints.
So far, I hav this setup:
test_task = {"folder": {"required": True}}
build_task = {"environment": {"allowed": ["staging", "product"]}}
abstract_task = {'type': {'allowed': ['test', 'build']},
'data': {'type': 'dict',
'required': True,
'anyof': [{'schema': test_task},
{'schema': build_task}]}}
But when the intended subschema fails, also an error regarding the other will be reported:
>>> validator = cerberus.Validator(schemas.abstract_task)
>>> validator.validate({
... "type": "build",
... "data": {"environment": "staging"}})
>>> pp validator.errors
{'data': {'anyof': 'no definitions validated',
'definition 0': {'environment': 'unknown field',
'folder': 'required field'},
'definition 1': {'environment': 'unallowed value bad'}}}
Is there a way to conditionally use definition 1
when the sibling type
has the value build
?
This question is derived from this issue.