File size: 1,019 Bytes
bc46b62 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | # -*- coding: utf-8 -*-
"""
validator_v2.py — 基于 jsonschema(draft2020-12) 的严格校验
validate_with_schema(ir, schema_path) -> (ok, issues, summary_msg)
"""
from __future__ import annotations
from typing import Any, List, Tuple
import json
from jsonschema import Draft202012Validator
from jsonschema.exceptions import best_match
def _format_path(err) -> str:
if not err.path: return ""
return "/".join(str(p) for p in err.path)
def validate_with_schema(ir: dict, schema_path: str) -> Tuple[bool, List[dict], str]:
schema = json.loads(open(schema_path, "r", encoding="utf-8").read())
validator = Draft202012Validator(schema)
errors = sorted(validator.iter_errors(ir), key=lambda e: list(e.path))
issues=[]
for e in errors:
issues.append({
"severity": "ERROR",
"path": _format_path(e),
"message": e.message
})
ok = len(issues)==0
msg = f"Schema: {'OK' if ok else 'FAIL'}; issues={len(issues)}"
return ok, issues, msg
|