"""Compare documented routes and validate the JSON POST examples. Only /scanner/validate is called: no device operation, calibration or edit is sent. Use --source to refresh the non-secret contract fixture after an intentional supplier specification update. Normal runs use the checked-in data. """ import argparse import hashlib import json from pathlib import Path import re from verify_cmvr_native import Client, require ROOT = Path(__file__).resolve().parents[1] FIXTURE = ROOT / 'scripts/fixtures/scanner-supplier-contract.json' REGISTRY = ROOT / 'am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerOperation.java' def registry(): return {name: dict(method=method, path=path) for name, method, path in re.findall( r'^ (\w+)\("(GET|POST)", "([^"]+)"', REGISTRY.read_text(encoding='utf-8'), re.M)} def extract(source): raw = source.read_bytes() routes = registry() names = {(row['method'], row['path']): name for name, row in routes.items()} operations = [] for block in re.split(r'(?m)(?=^## (?:GET|POST) )', raw.decode('utf-8-sig')): match = re.search(r'(?m)^(GET|POST) (/[^\s]*)\s*$', block) if not match: continue method, path = match.groups() path = re.sub(r'^/api/v1/tasks/[a-fA-F0-9]{32}$', '/api/v1/tasks/{taskId}', path) require((method, path) in names, 'Documented route is missing from registry: ' + path) upload = path == '/api/v1/framework/files' # Detailed documents may show result JSON before the request example. # Only extract the explicitly marked request body, never a success result. request_section = block.split('> Body 请求参数',1)[1].split('> 返回示例',1)[0] if '> Body 请求参数' in block else '' sample = re.search(r'```json\s*(.*?)```', request_section, re.S) if method == 'POST' and not upload else None operations.append(dict(operation=names[(method, path)], method=method, path=path, request=json.loads(sample[1]) if sample else ({} if method == 'POST' and not upload else None), upload=upload)) if not any(row['path']=='/' for row in operations) and '公开GET /' in raw.decode('utf-8-sig'): operations.append(dict(operation=names[('GET','/')],method='GET',path='/',request=None,upload=False)) require(len(operations) == len(routes) and len({row['operation'] for row in operations}) == len(routes), 'Supplier route inventory is incomplete or duplicated') fingerprint = dict(document=source.name, sha256=hashlib.sha256(raw).hexdigest()) history = [] if FIXTURE.exists(): previous = json.loads(FIXTURE.read_text(encoding='utf-8')) history = previous.get('sourceHistory', []) original = {key: previous[key] for key in ('document', 'sha256')} if original != fingerprint and original not in history: history = [*history, original] FIXTURE.parent.mkdir(parents=True, exist_ok=True) FIXTURE.write_text(json.dumps(dict(**fingerprint, sourceHistory=history, operations=operations), ensure_ascii=False, indent=2), encoding='utf-8') def run(): specification = json.loads(FIXTURE.read_text(encoding='utf-8')) routes = registry() client = Client().login() checks = [] for item in specification['operations']: name = item['operation'] checks.append(dict(name=name + ' documented method/path', passed=routes.get(name) == dict(method=item['method'], path=item['path']))) if item['method'] != 'POST' or item.get('upload'): continue for label, body, expected in ( ('documented example', item['request'], 200), ('unknown field rejection', dict(item['request'], __qa_unknown_field=True), 400), ): result = client.native('POST', '/scanner/validate', dict(operation=name, requestJson=json.dumps(body, ensure_ascii=False)), expected=None) checks.append(dict(name=name + ' ' + label, passed=result.get('code') == expected, code=result.get('code'), expected=expected)) checks.append(dict(name='complete documented operation inventory', passed= set(routes) == {row['operation'] for row in specification['operations']})) posts=sum(row['method']=='POST' and not row.get('upload') for row in specification['operations']) report = dict(passed=all(row['passed'] for row in checks), checks=checks, failures=[row for row in checks if not row['passed']], supplierRoutes=len(routes), documentedPostExamples=posts, unknownFieldChecks=posts, hardwareRequests=0, businessWrites=0, documentSha256=specification['sha256']) (ROOT / '.local/scanner-contract-verification.json').write_text( json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') print(json.dumps(dict(passed=report['passed'], checks=len(checks), failures=report['failures']), ensure_ascii=False), flush=True) return report['passed'] if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', type=Path, help='Explicit supplier Markdown used to refresh fixture') options = parser.parse_args() if options.source: extract(options.source) raise SystemExit(0 if run() else 1)