voice-dictation/tests/unit/test_orchestrator.py
2026-10-20 11:45:49 +03:00

440 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Тесты оркестратора — state-machine и DI."""
from __future__ import annotations
import time
from pathlib import Path
import pytest
from tests.fakes.fake_components import (
FakeAutoPaste,
FakeClipboard,
FakeNotifier,
FakeRecorder,
FakeSoundPlayer,
FakeTranscriber,
)
from voice_dictation.core.compressor import AudioChunk, ChunkingResult
from voice_dictation.core.config import Config
from voice_dictation.core.dictionary import Dictionary
from voice_dictation.core.enums import RecordingState, SoundKind
from voice_dictation.core.orchestrator import DictationOrchestrator
from voice_dictation.core.paths import AppPaths
def _make_orchestrator(
tmp_paths: AppPaths,
recorder: FakeRecorder | None = None,
transcriber: FakeTranscriber | None = None,
clipboard: FakeClipboard | None = None,
auto_paste: FakeAutoPaste | None = None,
sound_player: FakeSoundPlayer | None = None,
notifier: FakeNotifier | None = None,
config: Config | None = None,
compressor=None,
) -> DictationOrchestrator:
"""Вспомогательная функция — создаёт оркестратор с фейками."""
cfg = config or Config()
return DictationOrchestrator(
recorder=recorder or FakeRecorder(),
transcriber=transcriber or FakeTranscriber(),
dictionary=Dictionary(tmp_paths.dictionary_file),
clipboard=clipboard or FakeClipboard(),
auto_paste=auto_paste or FakeAutoPaste(),
sound_player=sound_player or FakeSoundPlayer(),
notifier=notifier or FakeNotifier(),
config_provider=lambda: cfg,
paths=tmp_paths,
compressor=compressor,
)
class _FakeChunkCompressor:
def is_available(self) -> bool:
return True
def compress(self, src: Path, dst: Path) -> Path:
dst.write_bytes(src.read_bytes())
return dst
def split(
self,
src: Path,
output_dir: Path,
total_duration_sec: float,
chunk_duration_sec: float,
overlap_sec: float,
**kwargs: object,
) -> ChunkingResult:
del src
del kwargs
output_dir.mkdir(parents=True, exist_ok=True)
chunks: list[AudioChunk] = []
start = 0.0
step = chunk_duration_sec - overlap_sec
index = 0
while start < total_duration_sec:
duration = min(chunk_duration_sec, total_duration_sec - start)
path = output_dir / f"chunk_{index:04d}.ogg"
path.write_bytes(b"chunk")
chunks.append(AudioChunk(index, path, start, duration))
if start + duration >= total_duration_sec:
break
start += step
index += 1
return ChunkingResult(tuple(chunks), "fake", 0, 0)
def test_initial_state_is_idle(tmp_paths: AppPaths) -> None:
"""Начальное состояние — IDLE."""
o = _make_orchestrator(tmp_paths)
assert o.state == RecordingState.IDLE
def test_toggle_idle_to_recording(tmp_paths: AppPaths) -> None:
"""toggle() в IDLE переводит в RECORDING."""
o = _make_orchestrator(tmp_paths)
o.toggle()
assert o.state == RecordingState.RECORDING
def test_toggle_recording_to_processing(tmp_paths: AppPaths) -> None:
"""toggle() в RECORDING переводит в PROCESSING."""
o = _make_orchestrator(tmp_paths)
o.toggle() # → RECORDING
o.toggle() # → PROCESSING
assert o.state == RecordingState.PROCESSING
def test_toggle_processing_ignored(tmp_paths: AppPaths) -> None:
"""toggle() в PROCESSING игнорируется."""
o = _make_orchestrator(tmp_paths)
o.toggle() # → RECORDING
o.toggle() # → PROCESSING
o.toggle() # должен быть проигнорирован
assert o.state == RecordingState.PROCESSING
def test_full_cycle_idle_after_transcription(tmp_paths: AppPaths) -> None:
"""После успешной транскрипции возвращается в IDLE."""
clipboard = FakeClipboard()
o = _make_orchestrator(tmp_paths, clipboard=clipboard)
o.toggle() # → RECORDING
o.toggle() # → PROCESSING (запускает worker)
# Даём worker-потоку завершиться
deadline = time.time() + 5
while o.state != RecordingState.IDLE and time.time() < deadline:
time.sleep(0.05)
assert o.state == RecordingState.IDLE
assert len(clipboard.copy_calls) == 1
assert clipboard.copy_calls[0] == "Тестовый текст"
def test_autopaste_called_after_transcription(tmp_paths: AppPaths) -> None:
"""AutoPaste.paste() вызывается после успешной транскрипции."""
auto_paste = FakeAutoPaste()
o = _make_orchestrator(tmp_paths, auto_paste=auto_paste, config=Config(paste_delay_ms=0))
o.toggle()
o.toggle()
deadline = time.time() + 5
while o.state != RecordingState.IDLE and time.time() < deadline:
time.sleep(0.05)
assert auto_paste.paste_count == 1
def test_start_sound_played_on_record(tmp_paths: AppPaths) -> None:
"""START-звук воспроизводится при начале записи."""
sound_player = FakeSoundPlayer()
o = _make_orchestrator(tmp_paths, sound_player=sound_player)
o.toggle()
assert SoundKind.START in sound_player.plays
def test_stop_sound_played_on_stop(tmp_paths: AppPaths) -> None:
"""STOP-звук воспроизводится при остановке записи."""
sound_player = FakeSoundPlayer()
o = _make_orchestrator(tmp_paths, sound_player=sound_player)
o.toggle()
o.toggle()
assert SoundKind.STOP in sound_player.plays
def test_error_on_recorder_start_failure(tmp_paths: AppPaths) -> None:
"""Ошибка recorder.start() → остаёмся в IDLE."""
recorder = FakeRecorder(fail_start=True)
o = _make_orchestrator(tmp_paths, recorder=recorder)
o.toggle()
assert o.state == RecordingState.IDLE
def test_error_sound_on_recorder_start_failure(tmp_paths: AppPaths) -> None:
"""При ошибке recorder.start() воспроизводится ERROR-звук."""
recorder = FakeRecorder(fail_start=True)
sound_player = FakeSoundPlayer()
o = _make_orchestrator(tmp_paths, recorder=recorder, sound_player=sound_player)
o.toggle()
assert SoundKind.ERROR in sound_player.plays
def test_transcription_error_returns_to_idle(tmp_paths: AppPaths) -> None:
"""Ошибка транскрипции → возврат в IDLE."""
transcriber = FakeTranscriber(fail=True)
o = _make_orchestrator(tmp_paths, transcriber=transcriber)
o.toggle()
o.toggle()
deadline = time.time() + 5
while o.state != RecordingState.IDLE and time.time() < deadline:
time.sleep(0.05)
assert o.state == RecordingState.IDLE
def test_transcription_error_shows_notification(tmp_paths: AppPaths) -> None:
"""Ошибка транскрипции → показывается уведомление."""
transcriber = FakeTranscriber(fail=True)
notifier = FakeNotifier()
o = _make_orchestrator(tmp_paths, transcriber=transcriber, notifier=notifier)
o.toggle()
o.toggle()
deadline = time.time() + 5
while o.state != RecordingState.IDLE and time.time() < deadline:
time.sleep(0.05)
assert len(notifier.notifications) > 0
titles = [n[0] for n in notifier.notifications]
assert any("ошибк" in t.lower() for t in titles)
def test_state_listener_called_on_transitions(tmp_paths: AppPaths) -> None:
"""state_listener вызывается при каждой смене состояния."""
states: list[RecordingState] = []
o = DictationOrchestrator(
recorder=FakeRecorder(),
transcriber=FakeTranscriber(),
dictionary=Dictionary(tmp_paths.dictionary_file),
clipboard=FakeClipboard(),
auto_paste=FakeAutoPaste(),
sound_player=FakeSoundPlayer(),
notifier=FakeNotifier(),
config_provider=lambda: Config(paste_delay_ms=0),
paths=tmp_paths,
state_listener=states.append,
)
o.toggle() # IDLE → RECORDING
o.toggle() # RECORDING → PROCESSING
deadline = time.time() + 5
while RecordingState.IDLE not in states[2:] and time.time() < deadline:
time.sleep(0.05)
assert RecordingState.RECORDING in states
assert RecordingState.PROCESSING in states
assert RecordingState.IDLE in states
def test_cancel_stops_recording(tmp_paths: AppPaths) -> None:
"""cancel() в RECORDING переводит в IDLE."""
o = _make_orchestrator(tmp_paths)
o.toggle()
assert o.state == RecordingState.RECORDING
o.cancel()
assert o.state == RecordingState.IDLE
def test_autopaste_skipped_for_very_long_text(tmp_paths: AppPaths) -> None:
"""Текст >10000 символов автоматически НЕ вставляется (только буфер).
После merge с веткой Жени: при превышении MAX_AUTOPASTE_CHARS показываем
notify «вставьте вручную ⌘V», autopaste не вызываем.
"""
long_text = "а" * 50_000
transcriber = FakeTranscriber(text=long_text)
auto_paste = FakeAutoPaste()
o = _make_orchestrator(tmp_paths, transcriber=transcriber, auto_paste=auto_paste)
o.toggle()
o.toggle()
deadline = time.time() + 5
while o.state != RecordingState.IDLE and time.time() < deadline:
time.sleep(0.05)
assert auto_paste.paste_count == 0
def test_long_recording_is_chunked_stitched_and_archived(tmp_paths: AppPaths) -> None:
clipboard = FakeClipboard()
transcriber = FakeTranscriber(
texts=[
"раз два три четыре",
"три четыре пять шесть",
"пять шесть семь",
]
)
config = Config(chunk_duration_sec=3.0, chunk_overlap_sec=1.0, paste_delay_ms=0)
o = _make_orchestrator(
tmp_paths,
recorder=FakeRecorder(duration_sec=7.0),
transcriber=transcriber,
clipboard=clipboard,
config=config,
compressor=_FakeChunkCompressor(),
)
o.toggle()
o.toggle()
deadline = time.time() + 5
while o.state != RecordingState.IDLE and time.time() < deadline:
time.sleep(0.05)
assert len(transcriber.calls) == 3
assert clipboard.copy_calls == ["раз два три четыре пять шесть семь"]
session_dir = next(tmp_paths.sessions_dir.iterdir())
assert (session_dir / "source.ogg").exists()
assert not (session_dir / "source.wav").exists()
assert not (session_dir / "chunks").exists()
assert (session_dir / "transcript.txt").read_text(encoding="utf-8") == clipboard.copy_calls[0]
def test_restart_resumes_from_saved_chunk_checkpoint(tmp_paths: AppPaths) -> None:
config = Config(chunk_duration_sec=3.0, chunk_overlap_sec=1.0, paste_delay_ms=0)
failing = FakeTranscriber(texts=["раз два три четыре"], fail_on_call=2)
first = _make_orchestrator(
tmp_paths,
recorder=FakeRecorder(duration_sec=7.0),
transcriber=failing,
config=config,
compressor=_FakeChunkCompressor(),
)
first.toggle()
first.toggle()
deadline = time.time() + 5
while first.state != RecordingState.IDLE and time.time() < deadline:
time.sleep(0.05)
session_dir = next(tmp_paths.sessions_dir.iterdir())
assert (session_dir / "transcripts" / "chunk_0000.json").exists()
assert (session_dir / "source.wav").exists()
clipboard = FakeClipboard()
resumed_transcriber = FakeTranscriber(texts=["три четыре пять шесть", "пять шесть семь"])
resumed = _make_orchestrator(
tmp_paths,
transcriber=resumed_transcriber,
clipboard=clipboard,
config=config,
compressor=_FakeChunkCompressor(),
)
assert resumed.resume_pending_sessions() == 1
deadline = time.time() + 5
while resumed.state != RecordingState.IDLE and time.time() < deadline:
time.sleep(0.05)
assert len(resumed_transcriber.calls) == 2
assert clipboard.copy_calls[-1] == "раз два три четыре пять шесть семь"
def test_history_measures_stop_to_final_including_postprocess(tmp_paths, monkeypatch):
from datetime import UTC, datetime
from decimal import Decimal
from voice_dictation.core.config import SummaryPreset
from voice_dictation.core.models import TranscriptionResult
from voice_dictation.core.usage_db import UsageDB
config = Config(
notifications_enabled=False,
summary_presets=[SummaryPreset("test", "synthetic", "format")],
active_preset="test",
)
orchestrator = _make_orchestrator(tmp_paths, config=config)
db = UsageDB(tmp_paths.usage_db)
orchestrator._usage_db = db
session = tmp_paths.sessions_dir / "synthetic"
session.mkdir()
(session / "source.ogg").write_bytes(b"synthetic")
result = TranscriptionResult("raw", 3.0, "fake", "ru", None, datetime.now(UTC), Decimal("0"))
clock = [10.0]
def postprocess(text, preset):
clock[0] = 15.25
return "Final text " * 100
monkeypatch.setattr(orchestrator, "_summarize", postprocess)
monkeypatch.setattr("voice_dictation.core.orchestrator.time.monotonic", lambda: clock[0])
orchestrator._on_transcription_success(
result, config, processing_started=10.0, session_dir=session
)
record = db.recent()[0]
assert record.full_text == "Final text " * 100
assert record.processing_sec == 5.25
assert record.audio_path == str((session / "source.ogg").resolve())
assert (session / "final.txt").read_text() == record.full_text
orchestrator.shutdown()
def test_new_recording_uses_configured_storage(tmp_paths, tmp_path):
custom = tmp_path / "custom-audio"
orchestrator = _make_orchestrator(tmp_paths, config=Config(audio_storage_dir=str(custom)))
orchestrator.toggle()
assert list(custom.glob("*/manifest.json"))
assert not list(tmp_paths.sessions_dir.glob("*/manifest.json"))
orchestrator.cancel()
orchestrator.shutdown()
def test_unavailable_audio_directory_does_not_start_or_fallback(tmp_paths, tmp_path):
blocked = tmp_path / "not-a-directory"
blocked.write_text("synthetic")
recorder = FakeRecorder()
orchestrator = _make_orchestrator(
tmp_paths, recorder=recorder, config=Config(audio_storage_dir=str(blocked))
)
orchestrator.toggle()
assert orchestrator.state == RecordingState.IDLE
assert not list(tmp_paths.sessions_dir.glob("*/source.wav"))
orchestrator.shutdown()
@pytest.mark.parametrize(
("model", "languages", "expected"),
[
("gpt-transcribe", ["ru", "ru", "ru"], "ru"),
("gpt-transcribe", ["ru", None, "ru"], None),
("gpt-transcribe", ["ru", "en", "ru"], None),
("gpt-transcribe", [None, None, None], None),
("gpt-4o-mini-transcribe", [None, None, None], "ru"),
("gpt-4o-mini-transcribe", [None, "en", "ru"], "en"),
],
)
def test_chunk_language_aggregation_preserves_unknown_and_legacy(
tmp_paths, monkeypatch, model, languages, expected
):
from dataclasses import replace
from voice_dictation.core.models import RecordingResult
transcriber = FakeTranscriber()
original = transcriber.transcribe
detected = iter(languages)
def respond(*args, **kwargs):
return replace(original(*args, **kwargs), language=next(detected))
monkeypatch.setattr(transcriber, "transcribe", respond)
config = Config(model=model, language="ru", chunk_duration_sec=3, chunk_overlap_sec=1)
orchestrator = _make_orchestrator(
tmp_paths, transcriber=transcriber, config=config, compressor=_FakeChunkCompressor()
)
audio = orchestrator._session_store.create()
audio.write_bytes(b"synthetic")
result = orchestrator._transcribe_session(RecordingResult(audio, 7), config)
assert result.language == expected
assert len(transcriber.calls) == 3
orchestrator.shutdown()