feat(model): Simplify logic
[csit.git] / resources / libraries / python / model / validate.py
1 # Copyright (c) 2023 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Module for validating JSON instances against schemas.
15
16 Short module currently, as we validate only testcase info outputs.
17 Structure will probably change when we start validation mode file types.
18 """
19
20 import json
21 import jsonschema
22 import yaml
23
24
25 def get_validators():
26     """Return mapping from file types to validator instances.
27
28     Uses hardcoded file types and paths to schemas on disk.
29
30     :returns: Validators, currently just for tc_info_output.
31     :rtype: Mapping[str, jsonschema.validators.Validator]
32     :raises RuntimeError: If schemas are not readable or not valid.
33     """
34     relative_path = "docs/model/current/schema/test_case.info.schema.yaml"
35     # Robot is always started when CWD is CSIT_DIR.
36     with open(relative_path, "rt", encoding="utf-8") as file_in:
37         schema = json.loads(
38             json.dumps(yaml.safe_load(file_in.read()), indent=2)
39         )
40     validator_class = jsonschema.validators.validator_for(schema)
41     validator_class.check_schema(schema)
42     fmt_checker = jsonschema.FormatChecker()
43     validator = validator_class(schema, format_checker=fmt_checker)
44
45     return dict(tc_info=validator)
46
47
48 def validate(file_path, validator):
49     """Load data from disk, use validator to validate it.
50
51     :param file_path: Local filesystem path including the file name to load.
52     :param validator: Validator instance to use for validation.
53     :type file_path: str
54     :type validator: jsonschema.validators.Validator
55     :raises RuntimeError: If schema validation fails.
56     """
57     with open(file_path, "rt", encoding="utf-8") as file_in:
58         instance = json.load(file_in)
59     error = jsonschema.exceptions.best_match(validator.iter_errors(instance))
60     if error is not None:
61         raise error