Files
collina-binaurals/backend/tests/test_api.py
T
Jorem Juárez 45da0f766e feat(api): endpoints FastAPI, export WAV en streaming y CLI typer
- /api/presets, /api/presets/{n} (+schedule), /api/noise/{pink|rain}.wav
  cacheado en disco, /api/export en streaming con Content-Length exacto,
  /api/health y estáticos de web/ en /
- 1 export concurrente por proceso (429 si hay otro en curso)
- sr 44100/48000, duration escala proporcional, errores 4xx en español
- CLI: binaural presets · binaural export
- tests criterios 5, 7 y 9 (37 en verde)
2026-08-30 05:51:27 -06:00

108 lines
3.5 KiB
Python

"""API completa con httpx/TestClient (criterios 7 y 9)."""
import io
import pytest
import soundfile as sf
from fastapi.testclient import TestClient
from binaural import api
NOMBRES = {"relajacion", "estudio", "foco", "foco_intenso", "descanso"}
@pytest.fixture()
def cliente(tmp_path, monkeypatch):
monkeypatch.setenv("BINAURAL_CACHE_DIR", str(tmp_path / "cache"))
with TestClient(api.app) as c:
yield c
def test_health(cliente):
r = cliente.get("/api/health")
assert r.status_code == 200
assert r.json()["status"] == "ok"
def test_listado_de_presets(cliente):
"""Criterio 7: /api/presets lista los 5 YAML."""
r = cliente.get("/api/presets")
assert r.status_code == 200
tarjetas = r.json()
assert {t["name"] for t in tarjetas} == NOMBRES
estudio = next(t for t in tarjetas if t["name"] == "estudio")
assert estudio["duracion_min"] == 30
assert (estudio["beat_min_hz"], estudio["beat_max_hz"]) == (10, 14)
def test_detalle_con_schedule(cliente):
r = cliente.get("/api/presets/estudio")
assert r.status_code == 200
sch = r.json()["schedule"]
assert [(p["t"], p["beat_hz"]) for p in sch["points"]] == [
(0, 10), (300, 10), (900, 14), (1800, 14),
]
assert sch["duration_s"] == 1800
assert sch["preroll_s"] == 1.5
def test_preset_inexistente(cliente):
r = cliente.get("/api/presets/zen")
assert r.status_code == 404
assert "no existe" in r.json()["detail"]
def test_loops_de_ruido(cliente, tmp_path):
for tipo in ("pink", "rain"):
r = cliente.get(f"/api/noise/{tipo}.wav")
assert r.status_code == 200
assert r.headers["content-type"].startswith("audio/wav")
datos, sr = sf.read(io.BytesIO(r.content))
assert sr == 44100
assert datos.ndim == 1 # mono
assert len(datos) == 20 * 44100
assert (tmp_path / "cache" / "pink-44100.wav").exists() # cacheado en disco
def test_export_wav_valido(cliente):
"""Criterio 9: cabecera WAV válida y Content-Length exacto."""
r = cliente.get("/api/export", params={"preset": "foco", "duration": 0.1})
assert r.status_code == 200
assert int(r.headers["content-length"]) == len(r.content)
assert r.content[:4] == b"RIFF" and r.content[8:12] == b"WAVE"
datos, sr = sf.read(io.BytesIO(r.content))
assert sr == 44100
assert datos.shape[1] == 2
assert abs(len(datos) / sr - (0.1 * 60 + 1.5)) <= 0.01
def test_export_errores(cliente):
assert cliente.get("/api/export", params={"preset": "zen"}).status_code == 404
assert (
cliente.get("/api/export", params={"preset": "foco", "duration": 61}).status_code == 422
)
r = cliente.get("/api/export", params={"preset": "foco", "format": "flac"})
assert r.status_code == 400
assert "fase 5" in r.json()["detail"]
assert (
cliente.get("/api/export", params={"preset": "foco", "sr": 22050}).status_code == 422
)
def test_export_concurrente_limitado(cliente):
"""Solo 1 export a la vez por proceso: el segundo recibe 429."""
assert api._export_ocupado.acquire(blocking=False)
try:
r = cliente.get("/api/export", params={"preset": "foco", "duration": 0.05})
assert r.status_code == 429
finally:
api._export_ocupado.release()
r = cliente.get("/api/export", params={"preset": "foco", "duration": 0.05})
assert r.status_code == 200 # el lock quedó libre tras el streaming
def test_frontend_estatico(cliente):
r = cliente.get("/")
assert r.status_code == 200
assert "text/html" in r.headers["content-type"]