"""Тесты оркестратора — state-machine и DI.""" from __future__ import annotations import time from tests.fakes.fake_components import ( FakeAutoPaste, FakeClipboard, FakeNotifier, FakeRecorder, FakeSoundPlayer, FakeTranscriber, ) 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, ) -> 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, ) 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_long_text(tmp_paths: AppPaths) -> None: """Автовставка не выполняется если текст длиннее 10000 символов.""" long_text = "а" * 15000 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