meta: add Schema.check method to check the schema
The _validator member of `Schema` is used as an indicator whether the provided schema is valid. The `check` method will, in case that _validator is not set attempt to validate the schema data, if present and set the _validator member if schema data is set and validation has passed. On failure, i.e. missing schema information or invalid schema data, the ValidationResult will contain the respective error.
This commit is contained in:
parent
cb0db496dc
commit
9d08f4faf2
1 changed files with 28 additions and 6 deletions
|
|
@ -214,8 +214,31 @@ class Schema:
|
||||||
def __init__(self, schema: str, name: Optional[str] = None):
|
def __init__(self, schema: str, name: Optional[str] = None):
|
||||||
self.data = schema
|
self.data = schema
|
||||||
self.name = name
|
self.name = name
|
||||||
if schema:
|
self._validator = None
|
||||||
self._validator = jsonschema.Draft7Validator(schema)
|
|
||||||
|
def check(self) -> ValidationResult:
|
||||||
|
"""Validate the `schema` data itself"""
|
||||||
|
res = ValidationResult(self.name)
|
||||||
|
|
||||||
|
# validator is assigned if and only if the schema
|
||||||
|
# itself passes validation (see below). Therefore
|
||||||
|
# this can be taken as an indicator for a valid
|
||||||
|
# schema and thus we can and should short-circuit
|
||||||
|
if self._validator:
|
||||||
|
return res
|
||||||
|
|
||||||
|
if not self.data:
|
||||||
|
res.fail("missing schema information")
|
||||||
|
return res
|
||||||
|
|
||||||
|
try:
|
||||||
|
Validator = jsonschema.Draft7Validator
|
||||||
|
Validator.check_schema(self.data)
|
||||||
|
self._validator = Validator(self.data)
|
||||||
|
except jsonschema.exceptions.SchemaError as err:
|
||||||
|
res += ValidationError.from_exception(err)
|
||||||
|
|
||||||
|
return res
|
||||||
|
|
||||||
def validate(self, target) -> ValidationResult:
|
def validate(self, target) -> ValidationResult:
|
||||||
"""Validate the `target` against this schema
|
"""Validate the `target` against this schema
|
||||||
|
|
@ -224,10 +247,9 @@ class Schema:
|
||||||
will return a `ValidationResult` in failed state,
|
will return a `ValidationResult` in failed state,
|
||||||
with 'missing schema information' as the reason.
|
with 'missing schema information' as the reason.
|
||||||
"""
|
"""
|
||||||
res = ValidationResult(self.name)
|
res = self.check()
|
||||||
|
if not res:
|
||||||
if not self.data:
|
return res
|
||||||
return res.fail("missing schema information")
|
|
||||||
|
|
||||||
for error in self._validator.iter_errors(target):
|
for error in self._validator.iter_errors(target):
|
||||||
res += ValidationError.from_exception(error)
|
res += ValidationError.from_exception(error)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue