voice-dictation/tests/unit/test_local_pipeline.py

164 lines
6.8 KiB
Python

"""Offline guarantees across routing, recovery and the full success path."""
from __future__ import annotations
import json
import socket
import httpx
import pytest
from tests.fakes.fake_components import FakeClipboard, FakeTranscriber
from tests.unit.test_orchestrator import _make_orchestrator
from voice_dictation.core.config import Config, ConfigStore
from voice_dictation.core.paths import AppPaths
from voice_dictation.core.transcription import RoutingTranscriber
from voice_dictation.infrastructure.env_loader import load_env
from voice_dictation.infrastructure.errors import TranscriptionError
def _wait(orchestrator):
if orchestrator._current_future:
orchestrator._current_future.result(timeout=5)
def _no_network(*args, **kwargs):
raise AssertionError("Offline scenario attempted network access")
def test_local_success_never_calls_network_or_postprocessing(tmp_paths, monkeypatch):
monkeypatch.setattr(socket, "create_connection", _no_network)
monkeypatch.setattr(httpx.Client, "send", _no_network)
clipboard = FakeClipboard()
config = Config(transcription_backend="local", active_preset="Тезисы", paste_delay_ms=0)
orchestrator = _make_orchestrator(tmp_paths, clipboard=clipboard, config=config)
monkeypatch.setattr(orchestrator, "_summarize", _no_network)
monkeypatch.setattr("voice_dictation.core.fx.get_rate", _no_network)
orchestrator.toggle()
orchestrator.toggle()
_wait(orchestrator)
assert clipboard.copy_calls == ["Тестовый текст"]
orchestrator.shutdown()
def test_local_recording_keeps_mode_when_settings_change(tmp_paths):
config = Config(transcription_backend="local", paste_delay_ms=0)
engine = FakeTranscriber()
orchestrator = _make_orchestrator(tmp_paths, transcriber=engine, config=config)
orchestrator.toggle()
# Simulate separate settings process returning a new config object.
orchestrator._config_provider = lambda: Config(transcription_backend="openai")
orchestrator.toggle()
_wait(orchestrator)
manifest = next(tmp_paths.sessions_dir.glob("*/manifest.json"))
saved = json.loads(manifest.read_text())
assert saved["transcription_identity"]["engine"] == "local"
assert saved["recording_config"]["transcription_backend"] == "local"
orchestrator.shutdown()
def test_recovery_uses_recording_config_not_current_cloud(tmp_paths, monkeypatch):
config = Config(transcription_backend="local", paste_delay_ms=0)
first = _make_orchestrator(tmp_paths, config=config)
first.toggle()
# Simulate interrupted process with an intact source WAV.
session = next(tmp_paths.sessions_dir.iterdir())
first._session_store.mark_recorded(session / "source.wav", 2.0)
second = _make_orchestrator(tmp_paths, config=Config(transcription_backend="openai"))
monkeypatch.setattr(second, "_summarize", _no_network)
assert second.resume_pending_sessions() == 1
_wait(second)
saved = second._session_store.read(session)
assert saved["transcription_identity"]["engine"] == "local"
first.shutdown()
second.shutdown()
def test_legacy_recording_never_automatically_uploaded(tmp_paths):
engine = FakeTranscriber()
orchestrator = _make_orchestrator(tmp_paths, transcriber=engine)
source = orchestrator._session_store.create()
source.write_bytes(b"audio")
orchestrator._session_store.mark_recorded(source, 2.0)
assert orchestrator.resume_pending_sessions() == 1
_wait(orchestrator)
assert not engine.calls
assert "автоматическое" in orchestrator._session_store.read(source.parent)["last_error"]
orchestrator.shutdown()
def test_local_missing_model_cannot_construct_cloud(tmp_path, monkeypatch):
monkeypatch.setattr("voice_dictation.core.transcriber.WhisperTranscriber", _no_network)
with pytest.raises(TranscriptionError):
RoutingTranscriber("", tmp_path).transcribe(
tmp_path / "audio.wav", model="local:whisper-base"
)
def test_cloud_missing_key_is_actionable(tmp_path):
with pytest.raises(TranscriptionError, match="OPENAI_API_KEY"):
RoutingTranscriber("", tmp_path).transcribe(tmp_path / "audio.wav", model="whisper-1")
def test_keyless_env_and_beta_paths_are_isolated(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.setenv("VOICE_DICTATION_HOME", str(tmp_path / "beta"))
assert load_env().api_key == ""
assert AppPaths.default().root == tmp_path / "beta"
def test_settings_file_changes_are_loaded_for_next_recording(tmp_path):
store = ConfigStore(tmp_path / "config.json")
store.save(Config(transcription_backend="openai"))
other = ConfigStore(store._path)
other.save(Config(transcription_backend="local"))
assert store.load().transcription_backend == "local"
def test_corrupt_local_config_never_switches_to_cloud(tmp_path):
path = tmp_path / "config.json"
store = ConfigStore(path)
store.save(Config(transcription_backend="local"))
path.write_text("{broken")
assert store.load().transcription_backend == "local"
assert ConfigStore(path).load().transcription_backend == "local"
path.write_text('{"transcription_backend": "server"}')
assert ConfigStore(path).load().transcription_backend == "local"
def test_local_long_wav_splits_without_ffmpeg(tmp_paths):
import wave
from voice_dictation.core.models import RecordingResult
config = Config(transcription_backend="local", chunk_duration_sec=60)
orchestrator = _make_orchestrator(tmp_paths, config=config)
source = orchestrator._session_store.create()
with wave.open(str(source), "wb") as audio:
audio.setparams((1, 2, 16000, 0, "NONE", "not compressed"))
audio.writeframes(b"\0\0" * 16000 * 125)
chunks = orchestrator._prepare_chunks(RecordingResult(source, 125), source, config)
assert len(chunks.chunks) == 3
assert chunks.mode == "local_pcm_fixed"
for chunk in chunks.chunks:
with wave.open(str(chunk.path), "rb") as audio:
assert audio.getnframes() / audio.getframerate() <= 60.001
orchestrator.shutdown()
def test_checkpoint_model_change_is_rejected(tmp_paths):
from voice_dictation.core.models import RecordingResult
engine = FakeTranscriber()
config = Config(transcription_backend="local", paste_delay_ms=0)
orchestrator = _make_orchestrator(tmp_paths, transcriber=engine, config=config)
source = orchestrator._session_store.create()
source.write_bytes(b"audio")
recording = RecordingResult(source, 2)
orchestrator._transcribe_session(recording, config)
with pytest.raises(TranscriptionError, match="изменились"):
orchestrator._transcribe_session(
recording, Config(transcription_backend="local", local_model="whisper-small")
)
orchestrator.shutdown()