"""JSON Draft3 Schema Validator Wrapper. A Wrapper for a JSON Draft3 schema validation library which allows us to transform the results into an internal Response() format. """ from jsonschema import Draft3Validator from oto import response from sales_goals.constants import error def _format_error(validator, validator_value, message): """Format error. Args: validator (string): type of validator that generated the error validator_value (any): type of value the validator expected message (string): a description of the error Returns: (dict): formatted error. """ return { 'validator': validator, 'validator_value': validator_value, 'message': message } def add_error_to_errors(errors, field, validator, validator_value, message): """Standardize validation error format. Args: errors (dict): errors to add error to field (string): field to add error for validator (string): type of validator that generated the error validator_value (any): type of value the validator expected message (string): a description of the error Returns: errors (dict): standartized errors. """ errors[field] = _format_error(validator, validator_value, message) return errors def validate(data, validator): """Generic JSON Draft3 Schema Validation. Args: data (dict): the JSON to be validated. validator (Draft3Validator): the JSON Draft3 Schema to validate against Returns: Response: the response of the create operation. """ errors = {} for e in sorted(validator.iter_errors(data), key=str): field = None if e.relative_path: field = e.relative_path.pop() elif e.absolute_schema_path: field = e.absolute_schema_path.pop() add_error_to_errors( errors, field, e.validator, e.validator_value, e.message) if len(errors) > 0: return response.create_error_response( code=error.VALIDATION_ERROR, message=errors, status=400) return response.Response(message={'status': 'ok'}, status=200) def json_validator(schema): """Make validator from schema json. Args: schema (dict): Loaded json file """ return Draft3Validator(schema)