I'm trying to validate the headers of a flask request and its failing. I'm trying to use the below code to simulate the same and can see that its failing to validate the headers properly even if I miss some of the mandatory headers.
The below code is expected to fail but its passing.
import validictory
from werkzeug.datastructures import EnvironHeaders
obj = EnvironHeaders(environ={})
validictory.validate(obj,{'type': 'object', 'properties': {'test':{'required': True, 'type': 'any'}}})
If I convert the EnvironHeaders as dict then validation is happening properly.
import validictory
from werkzeug.datastructures import EnvironHeaders
obj = EnvironHeaders(environ={})
validictory.validate(dict(obj),{'type': 'object', 'properties': {'test':{'required': True, 'type': 'any'}}})
This properly raises the below error during validation. Any idea on the reason for improper validation happened in the first case?
validictory.validator.RequiredFieldValidationError: Required field 'test' is missing
I was able to find out the reason for this issue by going through the source code of validictory.
It was passing the type validation since EnvironHeaders has both the attributes 'keys' and 'values'.
def validate_type_object(self, val):
return isinstance(val, Mapping) or (hasattr(val, 'keys') and hasattr(val, 'items'))
Property validation is happening only for dict types and the validation is passing since the code doesn't raise any error if the input type is not a dictionary.
def validate_properties(self, x, fieldname, schema, path, properties=None):
''' Validates properties of a JSON object by processing the object's schema recursively '''
value = x.get(fieldname)
if value is not None:
if isinstance(value, dict):
if isinstance(properties, dict):
if self.disallow_unknown_properties or self.remove_unknown_properties:
self._validate_unknown_properties(properties, value, fieldname,
schema.get('patternProperties'))
for property in properties:
self.__validate(property, value, properties.get(property),
path + '.' + property)
else:
raise SchemaError("Properties definition of field '{0}' is not an object"
.format(fieldname))
Note: Validictory has stopped support and hence not going to raise any issue in git repo. Will try using jsonschema package as suggested.