"""Тесты конфигурации.""" from __future__ import annotations import json from pathlib import Path import pytest from voice_dictation.core.config import Config, ConfigStore from voice_dictation.core.paths import AppPaths def test_default_config_values() -> None: """Дефолтный конфиг имеет правильные значения.""" config = Config() assert config.hotkey == "cmd+alt+d" assert config.model == "gpt-4o-mini-transcribe" assert config.language == "ru" assert config.auto_paste is True assert config.paste_delay_ms == 80 assert config.volume == 0.6 assert config.chunk_duration_sec == 180.0 assert config.chunk_overlap_sec == 4.0 assert config.vad_enabled is True assert config.vad_search_window_sec == 12.0 assert config.vad_min_silence_sec == 0.35 assert config.vad_noise_db == -35.0 assert config.audio_retention_days == 30 def test_load_missing_file_returns_defaults(tmp_paths: AppPaths) -> None: """Загрузка несуществующего файла возвращает дефолтный конфиг.""" store = ConfigStore(tmp_paths.config_file) config = store.load() assert config.hotkey == "cmd+alt+d" assert config.model == "gpt-4o-mini-transcribe" def test_save_and_load_roundtrip(tmp_paths: AppPaths) -> None: """Сохранение и загрузка конфига — round-trip.""" original = Config( hotkey="ctrl+shift+r", model="whisper-1", language="en", auto_paste=False, paste_delay_ms=150, chunk_duration_sec=240.0, chunk_overlap_sec=5.0, vad_enabled=False, vad_search_window_sec=15.0, vad_min_silence_sec=0.5, vad_noise_db=-32.0, audio_retention_days=60, ) store = ConfigStore(tmp_paths.config_file) store.save(original) store2 = ConfigStore(tmp_paths.config_file) loaded = store2.load() assert loaded.hotkey == "ctrl+shift+r" assert loaded.model == "whisper-1" assert loaded.language == "en" assert loaded.auto_paste is False assert loaded.paste_delay_ms == 150 assert loaded.chunk_duration_sec == 240.0 assert loaded.chunk_overlap_sec == 5.0 assert loaded.vad_enabled is False assert loaded.vad_search_window_sec == 15.0 assert loaded.vad_min_silence_sec == 0.5 assert loaded.vad_noise_db == -32.0 assert loaded.audio_retention_days == 60 def test_save_with_path_fields(tmp_paths: AppPaths) -> None: """Path-поля корректно сериализуются в JSON и обратно.""" sound_path = Path("/some/path/start.wav") original = Config(start_sound_path=sound_path) store = ConfigStore(tmp_paths.config_file) store.save(original) # Проверяем что в JSON путь сохранён как строка data = json.loads(tmp_paths.config_file.read_text()) assert data["start_sound_path"] == str(sound_path) loaded = store.load() assert loaded.start_sound_path == sound_path def test_current_raises_before_load(tmp_paths: AppPaths) -> None: """current() поднимает RuntimeError если load() не вызывался.""" store = ConfigStore(tmp_paths.config_file) with pytest.raises(RuntimeError, match="load"): store.current() def test_current_returns_after_load(tmp_paths: AppPaths) -> None: """current() возвращает конфиг после load().""" store = ConfigStore(tmp_paths.config_file) config = store.load() assert store.current() is config def test_load_ignores_unknown_keys(tmp_paths: AppPaths) -> None: """Неизвестные ключи из будущих версий конфига игнорируются.""" data = {"hotkey": "cmd+alt+x", "future_unknown_key": "value"} tmp_paths.config_file.write_text(json.dumps(data)) store = ConfigStore(tmp_paths.config_file) config = store.load() assert config.hotkey == "cmd+alt+x" def test_load_corrupted_json_returns_defaults(tmp_paths: AppPaths) -> None: """Повреждённый JSON файл → дефолтный конфиг (не падает).""" tmp_paths.config_file.write_text("{ NOT VALID JSON }") store = ConfigStore(tmp_paths.config_file) config = store.load() assert config.hotkey == "cmd+alt+d" @pytest.mark.parametrize("mode", ["raw", "summary", "translate_en", "email", "custom:Мой"]) def test_windows_modes_migrate_and_round_trip(tmp_path: Path, mode: str) -> None: """Upgrading and saving preserves legacy prompts, model, and selected mode.""" from voice_dictation.core.modes import DEFAULT_MODES path = tmp_path / "config.json" path.write_text( json.dumps( { "mode": mode, "proc_model": "my-model", "custom_modes": {"Мой": "Keep all facts", "Деловое письмо": "Custom collision"}, } ) ) store = ConfigStore(path) config = store.load() expected = ( "Мой" if mode == "custom:Мой" else next(spec.label for spec in DEFAULT_MODES if spec.key == mode) ) assert config.active_preset == expected assert len(config.summary_presets) == len(DEFAULT_MODES) + 2 assert config.summary_presets[-1].name != "Деловое письмо" assert config.summary_presets[-1].prompt == "Custom collision" assert all(p.model == "my-model" for p in config.summary_presets if p.prompt) store.save(config) assert ConfigStore(path).load() == config def test_older_summary_toggle_migrates(tmp_path: Path) -> None: path = tmp_path / "config.json" path.write_text('{"summary_mode": true, "summary_model": "legacy-model"}') config = ConfigStore(path).load() assert config.active_preset == "Summary (структурировать)" assert ( next(p for p in config.summary_presets if p.name == config.active_preset).model == "legacy-model" ) def test_audio_storage_directory_persists(tmp_paths): store = ConfigStore(tmp_paths.config_file) config = Config(audio_storage_dir="/synthetic/external audio") store.save(config) assert ConfigStore(tmp_paths.config_file).load().audio_storage_dir == config.audio_storage_dir