blob: 2848edfc05bc035d8ce546a02ff9f314d29c519e [file] [log] [blame]
Jeremy Johnson77fc6142023-09-04 17:04:21 +01001# Copyright (c) 2023, ARM Limited.
2# SPDX-License-Identifier: Apache-2.0
3"""Validates desc.json against its JSON schema."""
4import json
5from pathlib import Path
6
7from jsonschema import validate
8from referencing import Registry
9from referencing import Resource
10
11TD_SCHEMA_FULL = "full"
12TD_SCHEMA_DATA_GEN = "data_gen"
13TD_SCHEMA_COMPLIANCE = "compliance"
14
15# Default file info
16SCRIPT = Path(__file__).absolute()
17TD_SCHEMAS = {
18 TD_SCHEMA_DATA_GEN: "datagen-config.schema.json",
19 TD_SCHEMA_COMPLIANCE: "compliance-config.schema.json",
20 TD_SCHEMA_FULL: "desc.schema.json",
21}
22
23
24class TestDescSchemaValidator:
25 def __init__(self):
26 """Initialize by loading all the schemas and setting up a registry."""
27 self.registry = Registry()
28 self.schemas = {}
29 for key, name in TD_SCHEMAS.items():
30 schema_path = SCRIPT.parent / name
31 with schema_path.open("r") as fd:
32 schema = json.load(fd)
33 self.schemas[key] = schema
34 if key != TD_SCHEMA_FULL:
35 resource = Resource.from_contents(schema)
36 self.registry = self.registry.with_resource(uri=name, resource=resource)
37
38 def validate_config(self, config, schema_type=TD_SCHEMA_FULL):
39 """Validate the whole (or partial) config versus the relevant schema."""
40 validate(config, self.schemas[schema_type], registry=self.registry)
41
42
43def main(argv=None):
44 """Command line interface for the schema validation."""
45 import argparse
46
47 parser = argparse.ArgumentParser()
48 parser.add_argument(
49 "path", type=Path, help="the path to the test directory to validate"
50 )
51 args = parser.parse_args(argv)
52 test_path = args.path
53
54 if not test_path.is_dir():
55 print(f"ERROR: Invalid directory - {test_path}")
56 return 2
57
58 test_desc_path = test_path / "desc.json"
59
60 if not test_desc_path.is_file():
61 print(f"ERROR: No test description found: {test_desc_path}")
62 return 2
63
64 # Load the JSON desc.json
65 try:
66 with test_desc_path.open("r") as fd:
67 test_desc = json.load(fd)
68 except Exception as e:
69 print(f"ERROR: Loading {test_desc_path} - {repr(e)}")
70 return 2
71
72 sv = TestDescSchemaValidator()
73 sv.validate_config(test_desc, TD_SCHEMA_FULL)
74
75 return 0
76
77
78if __name__ == "__main__":
79 exit(main())