Skip to content

Multiple anonymous schema validation #132

Description

@calve

Hi all,

I am looking for a schema that can validates multiples schema ;

document1 = {
   "this_field" : {"bar_field" : "value"},
   "common_field1" : 42,
   "common_field2" : "hello",
}
document2 = {
   "that_field" : "blop",
   "common_field1" : 42,
   "common_field2" : "hello",
}

(note the difference between this_field and that_field)

From what I understand from the documentation, it could be written using *-of :

schema = {
    "oneof_schema":[
        {"this_field" : {"type": "dict"}},
        {"that_field": {"type" : "string"}}
    ],
   "common_field1" : {"type" : "integer"},
   "common_field2" : {"type" : "string"}
}

When I try to validate, I get the following error

>>> Validator().validate(document1, schema) 
 File "/home/g/.virtualenvs/p/lib/python2.7/site-packages/cerberus/cerberus.py", line 231, in validate
    return self._validate(document, schema, update=update, context=context)
  File "/home/g/.virtualenvs/p/lib/python2.7/site-packages/cerberus/cerberus.py", line 249, in _validate
    self.validate_schema(schema)
  File "/home/g/.virtualenvs/p/lib/python2.7/site-packages/cerberus/cerberus.py", line 397, in validate_schema
    raise SchemaError(errors.ERROR_DEFINITION_FORMAT.format(field))

cerberus.cerberus.SchemaError: unknown rule 'oneof_schema' for field 'oneof_schema'

I need to "name" the field used by oneof to pass this error

schema = {
    "named" : {
        "type" : "dict",
        "oneof": [
            {"schema": {"this_field" : {"type": "dict"}}},
            {"schema": {"that_field": {"type" : "string"}}}
        ]
    },
   "common_field1" : {"type" : "integer"},
   "common_field2" : {"type" : "string"}
}

but this won't validate my original document1 and document2, which now needs to contains a named key

document3 = {
   "named" : {"this_field" : {"foo":42}},
   "common_field1" : 34
}

document4 = {
   "named" : {"that_field" : "test"},
   "common_field1" : 34
}

Correctly outputs

>>> Validator().validate(document3, schema)
True
>>> Validator().validate(document4, schema)
True

But this is not as good as what I need since it changes the structures of my documents (document1 != document3 and document2 != document4)

How can I write a schema that validates both document1 and document2, without using a specific named key ?

Please, let me know if I did not made myself clear, or if you need any extra more information.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions