Files
mtusi2026lab6/student-tests/pipeline_helpers.py
T

83 lines
2.9 KiB
Python

"""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):
compose('exec', '-T', 'api1', '/messenger', 'fault', 'arm', point)
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)