VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 6)
5afd2f7 verified
Raw History Blame Contribute Delete
3.44 kB
"""Validator for the explicitly used JSON Schema subset (standard library).
Unknown keywords fail; this is not a general JSON Schema implementation.
Used to validate real segment payloads and the generated Python/TS contract.
"""
import json
import math
from pathlib import Path
SCHEMA_PATH = Path(__file__).with_name('contract.schema.json')
def validate(value, schema=None, root=None, path='$'):
if schema is None:
root = schema = json.loads(SCHEMA_PATH.read_text())
root = root or schema
known = {'$schema', '$ref', '$defs', 'type', 'const', 'enum', 'properties', 'required',
'additionalProperties', 'items', 'minItems', 'maxItems', 'minimum', 'maximum',
'exclusiveMinimum', 'anyOf'}
# description 只是注释,不约束值;不放行它,带 description 的定义(如 ObserverSplit)一碰到真值就断言
assert set(schema) - {'description'} <= known, 'unsupported schema keywords'
if '$ref' in schema:
return validate(value, root['$defs'][schema['$ref'].split('/')[-1]], root, path)
if 'const' in schema and value != schema['const']:
raise ValueError(path + ': const mismatch')
if 'enum' in schema and value not in schema['enum']:
raise ValueError(path + ': enum mismatch')
if 'anyOf' in schema:
for candidate in schema['anyOf']:
try:
validate(value, candidate, root, path)
return
except ValueError:
pass
raise ValueError(path + ': anyOf mismatch')
if 'type' in schema:
kinds = schema['type'] if isinstance(schema['type'], list) else [schema['type']]
def matches(kind):
return {'object': isinstance(value, dict), 'array': isinstance(value, list),
'string': isinstance(value, str), 'boolean': type(value) is bool,
'null': value is None, 'integer': type(value) is int,
'number': type(value) in (int, float) and math.isfinite(value)}[kind]
if not any(matches(kind) for kind in kinds):
raise ValueError(path + ': wrong type')
if isinstance(value, dict):
for name in schema.get('required', []):
if name not in value:
raise ValueError(path + ': missing ' + name)
properties = schema.get('properties', {})
for name, item in value.items():
if name in properties:
validate(item, properties[name], root, path + '.' + name)
elif schema.get('additionalProperties') is False:
raise ValueError(path + ': unexpected ' + name)
elif isinstance(schema.get('additionalProperties'), dict):
validate(item, schema['additionalProperties'], root, path + '.' + name)
if isinstance(value, list):
if len(value) < schema.get('minItems', 0) or len(value) > schema.get('maxItems', math.inf):
raise ValueError(path + ': wrong array length')
for i, item in enumerate(value):
validate(item, schema.get('items', {}), root, path + '[' + str(i) + ']')
if type(value) in (int, float):
if value < schema.get('minimum', -math.inf) or value > schema.get('maximum', math.inf):
raise ValueError(path + ': out of bounds')
if 'exclusiveMinimum' in schema and value <= schema['exclusiveMinimum']:
raise ValueError(path + ': exclusive minimum')