"""Audio tools run off the event loop, one at a time, and the dream errors reach the page unchanged.""" from __future__ import annotations import asyncio import io from collections import defaultdict import threading import time import numpy as np import pytest import soundfile as sf from fastapi import FastAPI, HTTPException from fastapi.testclient import TestClient from app.routes import dreams as dreams_module from app.routes.data_processing import router as process_router from app.routes.dreams import router as dreams_router from app.routes.remix import router as remix_router from app.services import tool_gate @pytest.fixture(autouse=True) def fresh_gate(monkeypatch): monkeypatch.setattr(tool_gate, "_semaphore", None) monkeypatch.setattr(tool_gate, "_semaphore_loop", None) monkeypatch.setattr(tool_gate, "_waiting", 0) def wav(seconds: float = 2.0, freq: float = 220.0, sr: int = 22050) -> bytes: t = np.arange(int(seconds * sr)) / sr buf = io.BytesIO() sf.write(buf, (0.3 * np.sin(2 * np.pi * freq * t)).astype(np.float32), sr, format="WAV") return buf.getvalue() # ── the gate ───────────────────────────────────────────────────────── def test_work_runs_in_a_worker_thread_not_on_the_loop() -> None: async def scenario(): loop_thread = threading.get_ident() return loop_thread, await tool_gate.run_blocking(threading.get_ident) loop_thread, worker_thread = asyncio.run(scenario()) assert worker_thread != loop_thread def test_the_loop_stays_responsive_while_a_job_runs() -> None: async def scenario(): ticks = 0 async def heartbeat(): nonlocal ticks while True: await asyncio.sleep(0.02) ticks += 1 beat = asyncio.create_task(heartbeat()) await tool_gate.run_blocking(time.sleep, 0.3) beat.cancel() return ticks assert asyncio.run(scenario()) >= 5 def test_one_job_at_a_time_by_default(monkeypatch) -> None: monkeypatch.setattr(tool_gate, "TOOL_SLOTS", 1) running = {"now": 0, "peak": 0} lock = threading.Lock() def job(): with lock: running["now"] += 1 running["peak"] = max(running["peak"], running["now"]) time.sleep(0.1) with lock: running["now"] -= 1 async def scenario(): await asyncio.gather(*(tool_gate.run_blocking(job) for _ in range(3))) asyncio.run(scenario()) assert running["peak"] == 1 def test_a_full_queue_says_busy_instead_of_piling_up(monkeypatch) -> None: monkeypatch.setattr(tool_gate, "MAX_WAITING", 2) async def scenario(): # One job holds the slot and two wait for it; a fourth has nowhere to go. jobs = [asyncio.create_task(tool_gate.run_blocking(time.sleep, 0.3)) for _ in range(3)] await asyncio.sleep(0.05) with pytest.raises(HTTPException) as busy: await tool_gate.run_blocking(time.sleep, 0) await asyncio.gather(*jobs) return busy.value err = asyncio.run(scenario()) assert err.status_code == 503 assert err.detail["code"] == "server_busy" assert err.headers["Retry-After"] == "30" # ── routes ─────────────────────────────────────────────────────────── @pytest.fixture def tools_client() -> TestClient: app = FastAPI() app.include_router(process_router) app.include_router(remix_router) return TestClient(app) def test_convert_returns_the_file_in_one_body(tools_client) -> None: response = tools_client.post( "/api/process/audio/convert", files={"file": ("tone.wav", wav(), "audio/wav")}, data={"options": '{"targetFormat": "flac"}'}, ) assert response.status_code == 200 assert response.headers["content-type"] == "audio/flac" assert int(response.headers["content-length"]) == len(response.content) > 1000 def test_organize_reads_the_clip(tools_client) -> None: response = tools_client.post("/api/process/audio/organize", files={"file": ("tone.wav", wav(), "audio/wav")}) assert response.status_code == 200 assert response.json()["durationSec"] == pytest.approx(2.0, abs=0.1) def test_blend_returns_audio_and_its_analysis_header(tools_client) -> None: response = tools_client.post( "/api/remix/blend", files={"track_a": ("a.wav", wav(freq=220), "audio/wav"), "track_b": ("b.wav", wav(freq=330), "audio/wav")}, data={"options": "{}"}, ) assert response.status_code == 200 assert response.content[:4] == b"RIFF" assert int(response.headers["content-length"]) == len(response.content) assert "outputDurationSec" in response.headers["x-remix-analysis"] def test_multitrack_needs_two_tracks(tools_client) -> None: response = tools_client.post("/api/remix/multitrack", files=[("tracks", ("a.wav", wav(), "audio/wav"))], data={"options": "{}"}) assert response.status_code == 400 # ── dreams ─────────────────────────────────────────────────────────── @pytest.fixture def dreams_client(monkeypatch) -> TestClient: monkeypatch.setattr(dreams_module, "_rate_store", defaultdict(list)) app = FastAPI() app.include_router(dreams_router) return TestClient(app) def post_dream(client: TestClient): return client.post("/api/dreams/analyze", json={"dreamText": "a dream that is long enough", "language": "English"}) @pytest.mark.parametrize("error,status,code", [ ("Dream analysis is not configured", 503, "service_not_configured"), ("Invalid API key", 503, "service_unavailable"), ("API quota exceeded", 503, "service_unavailable"), ("Analysis produced an unexpected response format.", 502, "analysis_failed"), ("Dream description is too short to analyze.", 400, "dream_too_short"), ]) def test_dream_errors_map_to_distinct_codes(dreams_client, monkeypatch, error, status, code) -> None: monkeypatch.setattr(dreams_module, "analyze_dream", lambda text, language: (None, error)) response = post_dream(dreams_client) assert response.status_code == status assert response.json()["detail"]["code"] == code def test_a_good_reading_comes_back(dreams_client, monkeypatch) -> None: reading = {"emotions": ["fear"], "themes": ["falling"], "symbols": ["moon"], "interpretation": "A reading.", "lucidityIndicator": False} monkeypatch.setattr(dreams_module, "analyze_dream", lambda text, language: (reading, None)) response = post_dream(dreams_client) assert response.status_code == 200 assert response.json()["interpretation"] == "A reading."