oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Validate the native test fixtures against the person API schema.
3
4Every pairing, device and error fixture under
5native/apple/Tests/EquipoKitTests/Fixtures is a response the person API could
6send: it must match its schema exactly, with no invented field. The
7conversation fixtures under Fixtures/thin are the server's own answers,
8captured and strictly decoded into internal/wire by Go
9(internal/thintest TestNativeFixtures) and checked against this document's
10device operations by internal/plan3test TestPersonAPIDeviceContract, so
11they are not checked here.
12Markdown fixtures are generated by Go from Render/RenderDraft and checked
13for freshness here. Requires Python and Go; Linux CI included."""
14import json, re, sys, os, subprocess
15from pathlib import Path
16
17root = Path(__file__).resolve().parents[2]
18spec = json.loads((root / 'docs/api/equipo-v1.openapi.json').read_text())
19fixtures = root / 'native/apple/Tests/EquipoKitTests/Fixtures'
20contracts = {
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
27def 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.
64RFC3339 = re.compile(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?(Z|[+-]\d\d:\d\d)$')
65
66failed = False
67for 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}')
72unlisted = {p.stem for p in fixtures.glob('*.json')} - set(contracts) - {'device-proof-vectors'}
73if unlisted: failed = True; print('fixtures without a contract:', sorted(unlisted))
74if failed: sys.exit(1)
75print(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).
79subprocess.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.
84subprocess.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)
87markdown = json.loads((fixtures / 'markdown/golden.json').read_text())
88assert markdown and len({case['name'] for case in markdown}) == len(markdown)
89print(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.
93differential = Path(os.environ.get('EQUIPO_MARKDOWN_DIFFERENTIAL', root / 'native/build/markdown-differential.json'))
94differential.parent.mkdir(parents=True, exist_ok=True)
95subprocess.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)
99generated = json.loads(differential.read_text())
100assert len(generated) >= 20_000 and len({case['name'] for case in generated}) == len(generated)
101assert len({case['source'] for case in generated}) == len(generated)
102print(f'{len(generated)} seeded differential cases generated from the web renderer')
103