| 1 | #!/usr/bin/env python3 |
| 2 | """Validate the native test fixtures against the person API schema. |
| 3 | |
| 4 | Every pairing, device and error fixture under |
| 5 | native/apple/Tests/EquipoKitTests/Fixtures is a response the person API could |
| 6 | send: it must match its schema exactly, with no invented field. The |
| 7 | conversation fixtures under Fixtures/thin are the server's own answers, |
| 8 | captured and strictly decoded into internal/wire by Go |
| 9 | (internal/thintest TestNativeFixtures) and checked against this document's |
| 10 | device operations by internal/plan3test TestPersonAPIDeviceContract, so |
| 11 | they are not checked here. |
| 12 | Markdown fixtures are generated by Go from Render/RenderDraft and checked |
| 13 | for freshness here. Requires Python and Go; Linux CI included.""" |
| 14 | import json, re, sys, os, subprocess |
| 15 | from pathlib import Path |
| 16 | |
| 17 | root = Path(__file__).resolve().parents[2] |
| 18 | spec = json.loads((root / 'docs/api/equipo-v1.openapi.json').read_text()) |
| 19 | fixtures = root / 'native/apple/Tests/EquipoKitTests/Fixtures' |
| 20 | contracts = { |
| 21 | 'project-typed-answer': 'Answered', 'project-list': 'ProjectList', 'project-card': 'Card', 'project-invalid': 'Error', |
| 22 | 'me': 'PersonAPIMe', 'ack': 'Ack', 'device-challenge': 'PersonDeviceChallenge', |
| 23 | 'device-credential': 'PersonCredential', 'devices': 'DevicePage', |
| 24 | 'error-revision-conflict': 'Error', 'error-pending': 'Error', |
| 25 | } |
| 26 | |
| 27 | def validate(value, schema, path='$'): |
| 28 | if '$ref' in schema: |
| 29 | return validate(value, spec['components']['schemas'][schema['$ref'].split('/')[-1]], path) |
| 30 | for key in ('oneOf', 'anyOf'): |
| 31 | if key in schema: |
| 32 | matched = 0 |
| 33 | for variant in schema[key]: |
| 34 | try: |
| 35 | validate(value, variant, path); matched += 1 |
| 36 | except AssertionError: |
| 37 | pass |
| 38 | assert (matched == 1 if key == 'oneOf' else matched >= 1), f'{path}: {key} mismatch' |
| 39 | if 'const' in schema: assert value == schema['const'], f'{path}: const mismatch' |
| 40 | if 'enum' in schema: assert value in schema['enum'], f'{path}: enum mismatch' |
| 41 | kind = schema.get('type') |
| 42 | kinds = kind if isinstance(kind, list) else [kind] |
| 43 | actual = ('null' if value is None else 'boolean' if isinstance(value, bool) else |
| 44 | 'integer' if isinstance(value, int) else 'number' if isinstance(value, float) else |
| 45 | 'string' if isinstance(value, str) else 'array' if isinstance(value, list) else 'object') |
| 46 | if kind: assert actual in kinds or (actual == 'integer' and 'number' in kinds), f'{path}: {actual} is not {kinds}' |
| 47 | if isinstance(value, dict): |
| 48 | props = schema.get('properties', {}) |
| 49 | missing = set(schema.get('required', [])) - value.keys() |
| 50 | assert not missing, f'{path}: missing {sorted(missing)}' |
| 51 | if schema.get('additionalProperties') is False: |
| 52 | extra = value.keys() - props.keys() |
| 53 | assert not extra, f'{path}: invented {sorted(extra)}' |
| 54 | for name, item in value.items(): |
| 55 | child = props.get(name, schema.get('additionalProperties', {})) |
| 56 | if isinstance(child, dict): validate(item, child, f'{path}.{name}') |
| 57 | elif isinstance(value, list) and 'items' in schema: |
| 58 | for i, item in enumerate(value): validate(item, schema['items'], f'{path}[{i}]') |
| 59 | elif isinstance(value, str): |
| 60 | if 'pattern' in schema: assert re.search(schema['pattern'], value), f'{path}: pattern' |
| 61 | if schema.get('format') == 'date-time': assert RFC3339.match(value), f'{path}: not RFC 3339' |
| 62 | |
| 63 | # Go's time.Time: RFC 3339 with up to nine fractional digits. |
| 64 | RFC3339 = re.compile(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?(Z|[+-]\d\d:\d\d)$') |
| 65 | |
| 66 | failed = False |
| 67 | for name, contract in contracts.items(): |
| 68 | try: |
| 69 | validate(json.loads((fixtures / f'{name}.json').read_text()), {'$ref': '#/components/schemas/' + contract}) |
| 70 | except (AssertionError, ValueError) as e: |
| 71 | failed = True; print(f'{name}.json: {e}') |
| 72 | unlisted = {p.stem for p in fixtures.glob('*.json')} - set(contracts) - {'device-proof-vectors'} |
| 73 | if unlisted: failed = True; print('fixtures without a contract:', sorted(unlisted)) |
| 74 | if failed: sys.exit(1) |
| 75 | print(f'{len(contracts)} native fixtures match the person API schema') |
| 76 | |
| 77 | # The Go fixture helper imports x/net directly. Keep the module graph honest |
| 78 | # in the same gate that compiles that helper (including the native gate). |
| 79 | subprocess.run(['go', 'mod', 'tidy', '-diff'], cwd=root, |
| 80 | env={**os.environ, 'GOTOOLCHAIN': 'go1.26.11', 'CGO_ENABLED': '0'}, check=True) |
| 81 | |
| 82 | # The markdown tree is generated by the web's own Render/RenderDraft. Check |
| 83 | # freshness on every run, including Linux CI; Swift compares every tree too. |
| 84 | subprocess.run(['go', 'test', './internal/chatmarkdown', '-run', |
| 85 | '^TestNativeMarkdownFixtures$', '-count=1'], cwd=root, |
| 86 | env={**os.environ, 'GOTOOLCHAIN': 'go1.26.11', 'CGO_ENABLED': '0'}, check=True) |
| 87 | markdown = json.loads((fixtures / 'markdown/golden.json').read_text()) |
| 88 | assert markdown and len({case['name'] for case in markdown}) == len(markdown) |
| 89 | print(f'{len(markdown)} markdown fixtures match the web renderer') |
| 90 | |
| 91 | # Fixed-seed, generated at check time. The native gate passes this same path to |
| 92 | # Swift, which compares every tree and requires at least 20,000 cases. |
| 93 | differential = Path(os.environ.get('EQUIPO_MARKDOWN_DIFFERENTIAL', root / 'native/build/markdown-differential.json')) |
| 94 | differential.parent.mkdir(parents=True, exist_ok=True) |
| 95 | subprocess.run(['go', 'test', './internal/chatmarkdown', '-run', |
| 96 | '^TestNativeMarkdownDifferential$', '-count=1'], cwd=root, |
| 97 | env={**os.environ, 'GOTOOLCHAIN': 'go1.26.11', 'CGO_ENABLED': '0', |
| 98 | 'EQUIPO_MARKDOWN_DIFFERENTIAL': str(differential)}, check=True) |
| 99 | generated = json.loads(differential.read_text()) |
| 100 | assert len(generated) >= 20_000 and len({case['name'] for case in generated}) == len(generated) |
| 101 | assert len({case['source'] for case in generated}) == len(generated) |
| 102 | print(f'{len(generated)} seeded differential cases generated from the web renderer') |
| 103 | |