#!/usr/bin/env python3 """Validate the native test fixtures against the person API schema. Every pairing, device and error fixture under native/apple/Tests/EquipoKitTests/Fixtures is a response the person API could send: it must match its schema exactly, with no invented field. The conversation fixtures under Fixtures/thin are the server's own answers, captured and strictly decoded into internal/wire by Go (internal/thintest TestNativeFixtures) and checked against this document's device operations by internal/plan3test TestPersonAPIDeviceContract, so they are not checked here. Markdown fixtures are generated by Go from Render/RenderDraft and checked for freshness here. Requires Python and Go; Linux CI included.""" import json, re, sys, os, subprocess from pathlib import Path root = Path(__file__).resolve().parents[2] spec = json.loads((root / 'docs/api/equipo-v1.openapi.json').read_text()) fixtures = root / 'native/apple/Tests/EquipoKitTests/Fixtures' contracts = { 'project-typed-answer': 'Answered', 'project-list': 'ProjectList', 'project-card': 'Card', 'project-invalid': 'Error', 'me': 'PersonAPIMe', 'ack': 'Ack', 'device-challenge': 'PersonDeviceChallenge', 'device-credential': 'PersonCredential', 'devices': 'DevicePage', 'error-revision-conflict': 'Error', 'error-pending': 'Error', } def validate(value, schema, path='$'): if '$ref' in schema: return validate(value, spec['components']['schemas'][schema['$ref'].split('/')[-1]], path) for key in ('oneOf', 'anyOf'): if key in schema: matched = 0 for variant in schema[key]: try: validate(value, variant, path); matched += 1 except AssertionError: pass assert (matched == 1 if key == 'oneOf' else matched >= 1), f'{path}: {key} mismatch' if 'const' in schema: assert value == schema['const'], f'{path}: const mismatch' if 'enum' in schema: assert value in schema['enum'], f'{path}: enum mismatch' kind = schema.get('type') kinds = kind if isinstance(kind, list) else [kind] actual = ('null' if value is None else 'boolean' if isinstance(value, bool) else 'integer' if isinstance(value, int) else 'number' if isinstance(value, float) else 'string' if isinstance(value, str) else 'array' if isinstance(value, list) else 'object') if kind: assert actual in kinds or (actual == 'integer' and 'number' in kinds), f'{path}: {actual} is not {kinds}' if isinstance(value, dict): props = schema.get('properties', {}) missing = set(schema.get('required', [])) - value.keys() assert not missing, f'{path}: missing {sorted(missing)}' if schema.get('additionalProperties') is False: extra = value.keys() - props.keys() assert not extra, f'{path}: invented {sorted(extra)}' for name, item in value.items(): child = props.get(name, schema.get('additionalProperties', {})) if isinstance(child, dict): validate(item, child, f'{path}.{name}') elif isinstance(value, list) and 'items' in schema: for i, item in enumerate(value): validate(item, schema['items'], f'{path}[{i}]') elif isinstance(value, str): if 'pattern' in schema: assert re.search(schema['pattern'], value), f'{path}: pattern' if schema.get('format') == 'date-time': assert RFC3339.match(value), f'{path}: not RFC 3339' # Go's time.Time: RFC 3339 with up to nine fractional digits. RFC3339 = re.compile(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?(Z|[+-]\d\d:\d\d)$') failed = False for name, contract in contracts.items(): try: validate(json.loads((fixtures / f'{name}.json').read_text()), {'$ref': '#/components/schemas/' + contract}) except (AssertionError, ValueError) as e: failed = True; print(f'{name}.json: {e}') unlisted = {p.stem for p in fixtures.glob('*.json')} - set(contracts) - {'device-proof-vectors'} if unlisted: failed = True; print('fixtures without a contract:', sorted(unlisted)) if failed: sys.exit(1) print(f'{len(contracts)} native fixtures match the person API schema') # The Go fixture helper imports x/net directly. Keep the module graph honest # in the same gate that compiles that helper (including the native gate). subprocess.run(['go', 'mod', 'tidy', '-diff'], cwd=root, env={**os.environ, 'GOTOOLCHAIN': 'go1.26.11', 'CGO_ENABLED': '0'}, check=True) # The markdown tree is generated by the web's own Render/RenderDraft. Check # freshness on every run, including Linux CI; Swift compares every tree too. subprocess.run(['go', 'test', './internal/chatmarkdown', '-run', '^TestNativeMarkdownFixtures$', '-count=1'], cwd=root, env={**os.environ, 'GOTOOLCHAIN': 'go1.26.11', 'CGO_ENABLED': '0'}, check=True) markdown = json.loads((fixtures / 'markdown/golden.json').read_text()) assert markdown and len({case['name'] for case in markdown}) == len(markdown) print(f'{len(markdown)} markdown fixtures match the web renderer') # Fixed-seed, generated at check time. The native gate passes this same path to # Swift, which compares every tree and requires at least 20,000 cases. differential = Path(os.environ.get('EQUIPO_MARKDOWN_DIFFERENTIAL', root / 'native/build/markdown-differential.json')) differential.parent.mkdir(parents=True, exist_ok=True) subprocess.run(['go', 'test', './internal/chatmarkdown', '-run', '^TestNativeMarkdownDifferential$', '-count=1'], cwd=root, env={**os.environ, 'GOTOOLCHAIN': 'go1.26.11', 'CGO_ENABLED': '0', 'EQUIPO_MARKDOWN_DIFFERENTIAL': str(differential)}, check=True) generated = json.loads(differential.read_text()) assert len(generated) >= 20_000 and len({case['name'] for case in generated}) == len(generated) assert len({case['source'] for case in generated}) == len(generated) print(f'{len(generated)} seeded differential cases generated from the web renderer')