From 9d08f4faf21b0b4300f83424dfd7e4afd314cffe Mon Sep 17 00:00:00 2001 From: Christian Kellner Date: Wed, 29 Apr 2020 15:43:35 +0200 Subject: [PATCH] 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. --- osbuild/meta.py | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/osbuild/meta.py b/osbuild/meta.py index 792edc77..d96ad880 100644 --- a/osbuild/meta.py +++ b/osbuild/meta.py @@ -214,8 +214,31 @@ class Schema: def __init__(self, schema: str, name: Optional[str] = None): self.data = schema self.name = name - if schema: - self._validator = jsonschema.Draft7Validator(schema) + self._validator = None + + 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: """Validate the `target` against this schema @@ -224,10 +247,9 @@ class Schema: will return a `ValidationResult` in failed state, with 'missing schema information' as the reason. """ - res = ValidationResult(self.name) - - if not self.data: - return res.fail("missing schema information") + res = self.check() + if not res: + return res for error in self._validator.iter_errors(target): res += ValidationError.from_exception(error)