Files
whisper-remote/backend/tests/test_server.py
T
space 7830ee9355
CI / CLI (pull_request) Successful in 45s
CI / Backend (pull_request) Successful in 46s
Add cleanup and artifact test coverage
2026-06-04 16:58:21 +02:00

100 lines
3.0 KiB
Python

from pathlib import Path
import shutil
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from fastapi.testclient import TestClient
import server
client = TestClient(server.app)
class FakeTemporaryDirectory:
def __init__(self, root: Path, prefix: str, created_paths: list[Path]) -> None:
self.path = root / f"{prefix}{len(created_paths)}"
self.created_paths = created_paths
def __enter__(self) -> str:
self.path.mkdir(parents=True, exist_ok=False)
self.created_paths.append(self.path)
return str(self.path)
def __exit__(self, exc_type, exc, tb) -> None:
shutil.rmtree(self.path, ignore_errors=True)
def test_validate_output_format_rejects_unknown() -> None:
try:
server.validate_output_format("docx")
except Exception as exc: # pragma: no cover - structure assertion below
assert getattr(exc, "status_code", None) == 400
else: # pragma: no cover
raise AssertionError("Expected HTTPException")
def test_transcriptions_returns_generated_artifact(monkeypatch, tmp_path: Path) -> None:
created_paths: list[Path] = []
monkeypatch.setattr(
server,
"TemporaryDirectory",
lambda prefix="": FakeTemporaryDirectory(tmp_path, prefix, created_paths),
)
def fake_run(command: list[str], check: bool, capture_output: bool, text: bool):
output_dir = Path(command[command.index("--output_dir") + 1])
(output_dir / "clip.txt").write_text("hello world", encoding="utf-8")
class Result:
returncode = 0
stdout = ""
stderr = ""
return Result()
monkeypatch.setattr(server.subprocess, "run", fake_run)
response = client.post(
"/transcriptions",
data={"model": "base", "language": "en", "output_format": "txt"},
files={"file": ("clip.wav", b"audio", "audio/wav")},
)
assert response.status_code == 200
assert response.text == "hello world"
assert response.headers["x-whisper-output-format"] == "txt"
assert created_paths
assert all(not path.exists() for path in created_paths)
def test_transcriptions_maps_subprocess_failure(monkeypatch, tmp_path: Path) -> None:
created_paths: list[Path] = []
monkeypatch.setattr(
server,
"TemporaryDirectory",
lambda prefix="": FakeTemporaryDirectory(tmp_path, prefix, created_paths),
)
def fake_run(command: list[str], check: bool, capture_output: bool, text: bool):
class Result:
returncode = 1
stdout = ""
stderr = "bad whisper day"
return Result()
monkeypatch.setattr(server.subprocess, "run", fake_run)
response = client.post(
"/transcriptions",
data={"model": "base", "output_format": "txt"},
files={"file": ("clip.wav", b"audio", "audio/wav")},
)
assert response.status_code == 502
assert response.json()["detail"] == "bad whisper day"
assert created_paths
assert all(not path.exists() for path in created_paths)