|
1 | 1 | from collections.abc import Mapping |
| 2 | +import copy |
2 | 3 | import json |
3 | 4 | from pathlib import Path |
4 | 5 | from typing import Any |
5 | 6 |
|
| 7 | +import jsonschema |
| 8 | + |
6 | 9 | from allotropy.allotrope.schema_parser.path_util import ( |
7 | 10 | get_full_schema_path, |
8 | 11 | get_schema_path_from_asm, |
9 | 12 | get_schema_path_from_manifest, |
10 | 13 | SHARED_SCHEMAS_DEFINITIONS_PATH, |
11 | 14 | ) |
12 | 15 | from allotropy.constants import DEFAULT_ENCODING |
| 16 | +from allotropy.exceptions import AllotropeSerializationError, AllotropeValidationError |
| 17 | + |
| 18 | +# Override format checker to remove "uri-reference" check, which ASM schemas fail against. |
| 19 | +FORMAT_CHECKER = copy.deepcopy( |
| 20 | + jsonschema.validators.Draft202012Validator.FORMAT_CHECKER |
| 21 | +) |
| 22 | +FORMAT_CHECKER.checkers.pop("uri-reference", None) |
13 | 23 |
|
14 | 24 |
|
15 | 25 | def get_shared_definitions() -> dict[str, Any]: |
@@ -63,3 +73,21 @@ def get_schema_from_model(model: Any) -> dict[str, Any]: |
63 | 73 | msg = f"No 'manifest' or 'field_asm_manifest' found in model: {type(model)}" |
64 | 74 | raise ValueError(msg) |
65 | 75 | return get_schema_from_manifest(manifest) |
| 76 | + |
| 77 | + |
| 78 | +def validate_asm_schema(asm_dict: dict[str, Any]) -> None: |
| 79 | + try: |
| 80 | + allotrope_schema = get_schema_from_asm(asm_dict) |
| 81 | + except Exception as e: |
| 82 | + msg = f"Failed to retrieve schema for model: {e}" |
| 83 | + raise AllotropeSerializationError(msg) from e |
| 84 | + |
| 85 | + try: |
| 86 | + jsonschema.validators.Draft202012Validator.check_schema( |
| 87 | + allotrope_schema, format_checker=FORMAT_CHECKER |
| 88 | + ) |
| 89 | + validator = jsonschema.validators.Draft202012Validator(allotrope_schema) |
| 90 | + validator.validate(asm_dict) |
| 91 | + except Exception as e: |
| 92 | + msg = f"Failed to validate allotrope model against schema: {e}" |
| 93 | + raise AllotropeValidationError(msg) from e |
0 commit comments