"""Local synthetic tests; credentials stay in memory and never enter evidence.""" import json import os from pathlib import Path import subprocess import sys import time ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) from client import Client, Failure, check, run def compose(*args, data=None): result = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT, input=data, capture_output=True, text=True) check(result.returncode == 0, 'compose command failed: ' + ' '.join(args[:3])) return result.stdout.strip() def psql(sql): return compose('exec', '-T', 'postgres', 'psql', '-XAtq', '-v', 'ON_ERROR_STOP=1', '-U', 'messenger', '-d', 'messenger', data=sql) def wait_for(test, message, timeout=100): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: value = test() if value: return value except Failure: pass time.sleep(.3) raise Failure(message) def ready(client): wait_for(lambda: client.call('GET', '/health/ready', schema='Health'), 'API not ready') def upload(client, actor, chat, raw=None): if raw is None: raw = (ROOT / 'tests/fixtures/sample.png').read_bytes() result = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=test.png', 202, actor=actor, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json'] check(result['status'] == 'queued', '202 must contain queued snapshot') return result def state(client, actor, attachment): return client.call('GET', '/api/v1/attachments/' + attachment['id'], actor=actor, schema='Attachment')['json'] def wait_state(client, actor, attachment, wanted='ready', timeout=100): def poll(): result = state(client, actor, attachment) if wanted == 'ready': check(result['status'] != 'failed', 'job unexpectedly failed') return result if result['status'] == wanted else None return wait_for(poll, 'attachment did not become ' + wanted, timeout) def fault(point): check(point in ('dispatcher_before_publish','dispatcher_after_publish','worker_after_claim','worker_after_objects','worker_before_ack'),'unknown fault point') psql("INSERT INTO pipeline_faults(point) VALUES('"+point+"') ON CONFLICT(point) DO UPDATE SET armed=true,hit_at=NULL;") def hit(point): wait_for(lambda: psql("SELECT hit_at IS NOT NULL FROM pipeline_faults WHERE point='" + point + "';") == 't', 'fault not reached: ' + point) def dump_evidence(name, value): (ROOT / 'evidence').mkdir(exist_ok=True) (ROOT / 'evidence' / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n') def start_only(service): # Compose start can also start dependencies; fault tests need exactly this container. container = compose('ps', '--all', '-q', service) result = subprocess.run(['docker', 'start', container], capture_output=True, text=True) check(result.returncode == 0, 'cannot start container ' + service)