d3ro-voice/apps/desktop/sidecar/tests/test_transcribe_hygiene.py

87 lines
2.9 KiB
Python

"""Sidecar /transcribe & /shutdown hygiene regression tests."""
from __future__ import annotations
import sys
import threading
import unittest
from pathlib import Path
from unittest import mock
SIDECAR_DIR = Path(__file__).resolve().parent.parent
if str(SIDECAR_DIR) not in sys.path:
sys.path.insert(0, str(SIDECAR_DIR))
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
class _FakeModel:
pass
class TranscribeAndShutdownHygieneTest(unittest.TestCase):
def setUp(self) -> None:
self._orig_model = main._model
self._orig_model_id = main._model_id
self._orig_thread = main._download_thread
main._model = _FakeModel() # type: ignore[assignment]
main._model_id = "tiny"
self.client = TestClient(main.app)
def tearDown(self) -> None:
main._model = self._orig_model
main._model_id = self._orig_model_id
main._download_thread = self._orig_thread
main._download_cancel.clear()
def test_transcribe_single_byte_pcm_returns_400_without_frombuffer_crash(self) -> None:
res = self.client.post(
"/transcribe",
files={"audio": ("chunk.pcm", b"\x01", "application/octet-stream")},
)
self.assertEqual(res.status_code, 400)
self.assertEqual(res.json()["status"], "error")
def test_transcribe_odd_byte_pcm_truncates_trailing_byte_and_succeeds(self) -> None:
observed_samples: list[int] = []
def fake_transcribe(_model, audio_array, _kwargs, _resolved_id, _is_primary, _cancel):
observed_samples.append(len(audio_array))
return [{"text": "ok", "start": 0.0, "end": 0.1}], "ok", "ko"
with mock.patch.object(main, "_transcribe_blocking", side_effect=fake_transcribe):
res = self.client.post(
"/transcribe",
files={"audio": ("chunk.pcm", b"\x00\x01\x02\x03\x99", "application/octet-stream")},
)
self.assertEqual(res.status_code, 200)
self.assertEqual(observed_samples, [2])
self.assertEqual(res.json()["text"], "ok")
def test_shutdown_cancels_active_download_thread(self) -> None:
stopped = threading.Event()
def fake_worker() -> None:
main._download_cancel.wait(timeout=5.0)
stopped.set()
main._download_cancel.clear()
worker = threading.Thread(target=fake_worker, daemon=True)
main._download_thread = worker
worker.start()
with mock.patch.object(main, "_server", None):
res = self.client.post("/shutdown")
self.assertEqual(res.status_code, 200)
self.assertEqual(res.json()["status"], "shutting_down")
self.assertTrue(main._download_cancel.is_set())
self.assertTrue(stopped.is_set())
self.assertFalse(worker.is_alive())
if __name__ == "__main__":
unittest.main()