def _get_validator(cls): if cls.__validator__ is None and cls.__validator__ != _sentinal: cls.__validator__ = _sentinal if "requestBody" in cls.__config__: requestBody = cls.__config__["requestBody"] try: schema = requestBody["content"]["application/json"][ "schema"] except KeyError: return cls.__schema__, cls.__validator__ if "$ref" in schema: try: ref = schema["$ref"] schema_name = ref.split("/")[-1] cls.__schema__ = app_settings[ "json_schema_definitions"][schema_name] cls.__validator__ = get_schema_validator(schema_name) except KeyError: # pragma: no cover logger.warning("Invalid jsonschema", exc_info=True) elif schema is not None: try: cls.__schema__ = schema jsonschema_validator = jsonschema.validators.validator_for( cls.__schema__) cls.__validator__ = jsonschema_validator( cls.__schema__) except jsonschema.exceptions.ValidationError: # pragma: no cover logger.warning("Could not validate schema", exc_info=True) else: pass # can be used for query, path or header parameters return cls.__schema__, cls.__validator__
def test_get_json_schema_validator(dummy_guillotina): validator = get_schema_validator('PrincipalRole') validator.validate({ 'principal': 'foobar', 'role': 'foobar', 'setting': 'Allow' }) with pytest.raises(jsonschema.ValidationError): validator.validate({ 'principal': 'foobar', 'role': 'foobar', 'setting': 'Foobar' })
def test_get_json_schema_validator(dummy_guillotina): validator = get_schema_validator("PrincipalRole") validator.validate({ "principal": "foobar", "role": "foobar", "setting": "Allow" }) with pytest.raises(jsonschema.ValidationError): validator.validate({ "principal": "foobar", "role": "foobar", "setting": "Foobar" })
def test_get_json_schema_validator_caches(dummy_guillotina): validator = get_schema_validator('PrincipalRole') assert id(validator) == id(get_schema_validator('PrincipalRole'))