338 lines
12 KiB
Python
338 lines
12 KiB
Python
"""Тесты оркестратора — state-machine и DI."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import time
|
||
from pathlib import Path
|
||
|
||
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] == "раз два три четыре пять шесть семь"
|