import asyncio import io from pathlib import Path from types import SimpleNamespace import httpx from PIL import Image import pytest import pytest_asyncio PASSWORD = "Sufficient-Password-194!" class BoundaryError(Exception): def __init__(self, message="network interrupted", retriable=True): self.code, self.message, self.retriable = "upstream_unavailable", message, retriable super().__init__(message) class FakeProvider: """External-service boundary only. DB, events, HTTP/auth and files are real.""" def __init__(self): self.remote = {} self.accepted = {} self.lost_response = False self.fail_download_once = False self.fail_download_at = None self.submitted_payloads = [] self.download_count = 0 self.cpu_wait = False self.cpu_runs = 0 self.reject_submission = False async def health(self): return True async def scheduler_status(self): return {"available": True, "state": "ready", "reason": None, "gpus": [], "updated_at": None} async def prepare_gpu_payload(self, task_type, inputs, parameters, assets, work_dir): resolved = dict(inputs) for source, target in (("image_asset_id", "image_path"), ("audio_asset_id", "audio_path"), ("asset_id", "audio_path")): if source in resolved: resolved[target] = str(assets[resolved.pop(source)]) return {"task_type": task_type, "input": resolved, "parameters": parameters, "timeout_seconds": 3600} async def submit(self, payload, idempotency_key): self.submitted_payloads.append((idempotency_key, payload)) if self.reject_submission: error = BoundaryError("unsupported upstream input", retriable=False) error.code = "upstream_rejected" raise error if idempotency_key not in self.accepted: remote_id = f"remote-{len(self.accepted) + 1}" self.accepted[idempotency_key] = remote_id self.remote[remote_id] = {"id": remote_id, "state": "queued", "attempt_count": 0, "preemptions": 0} remote_id = self.accepted[idempotency_key] if self.lost_response: self.lost_response = False raise BoundaryError() return dict(self.remote[remote_id]) async def query(self, upstream_id): return dict(self.remote[upstream_id]) async def cancel(self, upstream_id): self.remote[upstream_id].update(state="cancelled") return dict(self.remote[upstream_id]) async def download(self, upstream_id, index, destination): self.download_count += 1 if self.fail_download_once or self.fail_download_at == index: self.fail_download_once = False self.fail_download_at = None raise BoundaryError("download interrupted") destination.parent.mkdir(parents=True, exist_ok=True) Image.new("RGB", (12, 10), "blue").save(destination, format="PNG") async def run_cpu(self, task_type, inputs, parameters, assets, work_dir): self.cpu_runs += 1 if self.cpu_wait: await asyncio.sleep(60) work_dir.mkdir(parents=True, exist_ok=True) output = work_dir / "answer.txt" output.write_text("The answer is 5", encoding="utf-8") return SimpleNamespace(outputs=[output], result={"text": "The answer is 5"}, metadata={}) async def aclose(self): pass @pytest.fixture def png_bytes(): data = io.BytesIO() Image.new("RGB", (16, 12), "red").save(data, format="PNG") return data.getvalue() @pytest_asyncio.fixture async def system(tmp_path): from app.config import Settings from app.main import create_app settings = Settings(mode="test", database_url=f"sqlite+aiosqlite:///{tmp_path / 'test.sqlite3'}", workspace_root=tmp_path, admin_username="admin", admin_password=PASSWORD, run_coordinator=False, cookie_secure=False, event_heartbeat_seconds=.03) provider = FakeProvider() app = create_app(settings, provider=provider) async with app.router.lifespan_context(app): async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: response = await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD}) assert response.status_code == 200, response.text client.headers["X-CSRF-Token"] = response.json()["csrf_token"] yield SimpleNamespace(app=app, client=client, settings=settings, provider=provider) @pytest_asyncio.fixture async def other_client(system): response = await system.client.post("/api/auth/users", json={"username": "alice", "display_name": "Alice", "password": PASSWORD}) assert response.status_code == 201, response.text async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test") as client: login = await client.post("/api/auth/login", json={"username": "alice", "password": PASSWORD}) client.headers["X-CSRF-Token"] = login.json()["csrf_token"] yield client