Files
Jorem Juárez fc506ac7c6 feat(deploy): fase 6 — Dockerfile para Coolify, PWA y guía de despliegue
- Dockerfile: python:3.12-slim + uv --frozen, no root, HEALTHCHECK sobre
  /api/health, un worker con --proxy-headers para el Traefik de Coolify
- HEAD explícito en /api/health y /api/export (curl -I del criterio 12;
  export HEAD devuelve el Content-Length exacto sin generar audio)
- PWA: manifest, iconos generados con numpy+stdlib, apple-touch-icon
- docker-compose.dev.yml (solo local), .dockerignore
- deploy/coolify.md: recurso, deploy key, webhook Gitea, dominio, volumen
- versión 0.2.0 · smoke test del contenedor en local: healthy
2026-08-30 08:08:45 -06:00

117 lines
4.0 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"]
def test_head_health_y_export(cliente):
"""curl -I debe funcionar (criterio 12): HEAD con cabeceras exactas."""
assert cliente.head("/api/health").status_code == 200
r = cliente.head("/api/export", params={"preset": "foco", "duration": 25})
assert r.status_code == 200
assert r.content == b""
# mismo Content-Length que anunciaría el GET: (25*60+1.5)*44100 samples * 4 B + 44
assert int(r.headers["content-length"]) == round((25 * 60 + 1.5) * 44100) * 4 + 44