Files
vibemake-pcb-studio/backend/tests/acceptance_live.py
T

102 lines
5.6 KiB
Python

"""Explicit live acceptance against a separate test API; uses real DeepSeek credit.
Never run by unittest discovery. All generated records remain in the selected
test API's external data directory. No previous user fixture is committed.
"""
import argparse
import hashlib
import io
import json
from pathlib import Path
import time
import uuid
import zipfile
import httpx
def run(args):
client = httpx.Client(base_url=args.api.rstrip('/') + '/api/v1', timeout=30,
headers={'Origin': 'http://127.0.0.1:5173'})
client.get('/session').raise_for_status()
task_id = None
def command(action, payload):
nonlocal task_id
rid = 'native-acceptance-' + uuid.uuid4().hex
response = client.post('/commands', json={'request_id': rid, 'action': action, 'payload': payload})
response.raise_for_status()
initial = response.json()
# HTTP replay must refer to the same durable operation identity.
replay = client.post('/commands', json={'request_id': rid, 'action': action, 'payload': payload})
replay.raise_for_status()
assert replay.json()['operation_id'] == initial['operation_id']
start, cursor = time.monotonic(), 0
while time.monotonic() - start < args.deadline:
result = client.get('/operations/' + initial['operation_id'])
result.raise_for_status()
operation = result.json()
if operation.get('task_id'):
task_id = operation['task_id']
if operation['state'] not in ['queued', 'running']:
print('OPERATION', action, operation['state'], (operation.get('result') or {}).get('state'), flush=True)
return operation
if int(time.monotonic() - start) % 10 == 0:
print('WAIT', action, task_id, round(time.monotonic() - start), flush=True)
time.sleep(1)
raise AssertionError('Acceptance exceeded its wall-clock deadline')
start = time.monotonic()
result = command('create', {'description': args.description, 'selection_policy': 'propose'})['result']
assert result['state'] == 'awaiting_selection', result
assert result['eda_engine'] == 'kicad'
result = command('select', {'task_id': task_id, 'proposal_hash': result['proposal_hash'], 'option_id': 'A'})['result']
generated_seconds = round(time.monotonic() - start, 2)
if result['state'] != 'delivery_ready':
path = Path(args.output)
path.mkdir(parents=True, exist_ok=True)
(path / 'failure.json').write_text(json.dumps(result, ensure_ascii=False, indent=2))
raise AssertionError({k: result.get(k) for k in ['task_id', 'state', 'error', 'manufacturing_blockers']})
assert result['download_ready'] is True and not result['manufacturing_blockers']
artifacts = client.get('/tasks/' + task_id + '/artifacts').json()['items']
assert not any(a['kind'] == 'manufacturing_package' for a in artifacts)
native = next(a for a in artifacts if a['kind'] == 'kicad_native')
response = client.get(native['download_url'].removeprefix('/api/v1'))
response.raise_for_status()
assert hashlib.sha256(response.content).hexdigest() == native['sha256']
with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
assert any(name.endswith('.kicad_pcb') for name in archive.namelist())
assert any(name.endswith('.kicad_sch') for name in archive.namelist())
assert not any(name.endswith('.epro2') for name in archive.namelist())
wrong = command('accept', {'task_id': task_id, 'manifest_sha256': '0' * 64, 'accepted': True})
assert wrong['state'] == 'failed', wrong
result = command('accept', {'task_id': task_id, 'manifest_sha256': result['delivery']['manifest_sha256'], 'accepted': True})['result']
assert result['state'] == 'completed', result
package = result['manufacturing_package']
response = client.get(package['download_url'].removeprefix('/api/v1'))
response.raise_for_status()
assert hashlib.sha256(response.content).hexdigest() == package['sha256']
with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
names = archive.namelist()
assert any(name.startswith('native/') and name.endswith('.kicad_pcb') for name in names)
assert any(name.startswith('native/') and name.endswith('.kicad_sch') for name in names)
assert len([name for name in names if name.startswith('manufacturing/') and name.endswith('.gbr')]) >= 7
assert any(name.endswith('.drl') for name in names)
output = Path(args.output)
output.mkdir(parents=True, exist_ok=True)
(output / 'pcb-download.zip').write_bytes(response.content)
report = {'passed': True, 'task_id': task_id, 'engine': 'kicad', 'generation_seconds': generated_seconds,
'metrics': result.get('metrics'), 'download_sha256': package['sha256'], 'download_bytes': len(response.content),
'validated': ['HTTP replay', 'real DeepSeek plan/circuit', 'native generation/routing/checks', 'draft fabrication gate',
'stale-manifest rejection', 'manifest-bound acceptance', 'download hashes', 'native files/Gerber/drill in ZIP']}
(output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(report, ensure_ascii=False), flush=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--api', required=True)
parser.add_argument('--description', required=True)
parser.add_argument('--output', required=True)
parser.add_argument('--deadline', type=int, default=900)
run(parser.parse_args())