subx_cli/config/
test_service.rs

1//! Test configuration service for isolated testing.
2//!
3//! This module provides a configuration service implementation specifically
4//! designed for testing environments, offering complete isolation and
5//! predictable configuration states.
6
7use crate::config::service::ConfigService;
8use crate::error::SubXError;
9use crate::{Result, config::Config};
10use std::path::{Path, PathBuf};
11use std::sync::Mutex;
12
13/// Test configuration service implementation.
14///
15/// This service provides a fixed configuration for testing purposes,
16/// ensuring complete isolation between tests and predictable behavior.
17/// It does not load from external sources or cache.
18pub struct TestConfigService {
19    config: Mutex<Config>,
20}
21
22impl TestConfigService {
23    /// Set AI provider, model, and API key for testing.
24    pub fn set_ai_settings_and_key(&self, provider: &str, model: &str, api_key: &str) {
25        let mut cfg = self.config.lock().unwrap();
26        cfg.ai.provider = provider.to_string();
27        cfg.ai.model = model.to_string();
28        cfg.ai.api_key = if api_key.is_empty() {
29            None
30        } else {
31            Some(api_key.to_string())
32        };
33    }
34
35    /// Set AI provider, model, API key, and custom base URL for testing.
36    pub fn set_ai_settings_with_base_url(
37        &self,
38        provider: &str,
39        model: &str,
40        api_key: &str,
41        base_url: &str,
42    ) {
43        self.set_ai_settings_and_key(provider, model, api_key);
44        let mut cfg = self.config.lock().unwrap();
45        cfg.ai.base_url = base_url.to_string();
46    }
47    /// Create a new test configuration service with the provided configuration.
48    ///
49    /// # Arguments
50    ///
51    /// * `config` - The fixed configuration to use
52    pub fn new(config: Config) -> Self {
53        Self {
54            config: Mutex::new(config),
55        }
56    }
57
58    /// Create a test configuration service with default settings.
59    ///
60    /// This is useful for tests that don't need specific configuration values.
61    pub fn with_defaults() -> Self {
62        Self::new(Config::default())
63    }
64
65    /// Create a test configuration service with specific AI settings.
66    ///
67    /// # Arguments
68    ///
69    /// * `provider` - AI provider name
70    /// * `model` - AI model name
71    pub fn with_ai_settings(provider: &str, model: &str) -> Self {
72        let mut config = Config::default();
73        config.ai.provider = provider.to_string();
74        config.ai.model = model.to_string();
75        Self::new(config)
76    }
77
78    /// Create a test configuration service with specific AI settings including API key.
79    ///
80    /// # Arguments
81    ///
82    /// * `provider` - AI provider name
83    /// * `model` - AI model name
84    /// * `api_key` - API key for the provider
85    pub fn with_ai_settings_and_key(provider: &str, model: &str, api_key: &str) -> Self {
86        let mut config = Config::default();
87        config.ai.provider = provider.to_string();
88        config.ai.model = model.to_string();
89        config.ai.api_key = Some(api_key.to_string());
90        Self::new(config)
91    }
92
93    /// Create a test configuration service with specific sync settings.
94    ///
95    /// # Arguments
96    ///
97    /// * `correlation_threshold` - Correlation threshold for synchronization
98    /// * `max_offset` - Maximum time offset in seconds
99    pub fn with_sync_settings(correlation_threshold: f32, max_offset: f32) -> Self {
100        let mut config = Config::default();
101        config.sync.correlation_threshold = correlation_threshold;
102        config.sync.max_offset_seconds = max_offset;
103        Self::new(config)
104    }
105
106    /// Create a test configuration service with specific parallel processing settings.
107    ///
108    /// # Arguments
109    ///
110    /// * `max_workers` - Maximum number of parallel workers
111    /// * `queue_size` - Task queue size
112    pub fn with_parallel_settings(max_workers: usize, queue_size: usize) -> Self {
113        let mut config = Config::default();
114        config.general.max_concurrent_jobs = max_workers;
115        config.parallel.task_queue_size = queue_size;
116        Self::new(config)
117    }
118
119    /// Get the underlying configuration.
120    ///
121    /// This is useful for tests that need direct access to the configuration object.
122    pub fn config(&self) -> std::sync::MutexGuard<'_, Config> {
123        self.config.lock().unwrap()
124    }
125
126    /// Get a mutable reference to the underlying configuration.
127    ///
128    /// This allows tests to modify the configuration after creation.
129    pub fn config_mut(&self) -> std::sync::MutexGuard<'_, Config> {
130        self.config.lock().unwrap()
131    }
132}
133
134impl ConfigService for TestConfigService {
135    fn get_config(&self) -> Result<Config> {
136        Ok(self.config.lock().unwrap().clone())
137    }
138
139    fn reload(&self) -> Result<()> {
140        // Test configuration doesn't need reloading since it's fixed
141        Ok(())
142    }
143
144    fn save_config(&self) -> Result<()> {
145        // Test environment does not perform actual file I/O
146        Ok(())
147    }
148
149    fn save_config_to_file(&self, _path: &Path) -> Result<()> {
150        // Test environment does not perform actual file I/O
151        Ok(())
152    }
153
154    fn get_config_file_path(&self) -> Result<PathBuf> {
155        // Return a dummy path to avoid conflicts in test environment
156        Ok(PathBuf::from("/tmp/subx_test_config.toml"))
157    }
158
159    fn get_config_value(&self, key: &str) -> Result<String> {
160        // Delegate to current configuration
161        // Note: unwrap_or_default to handle Option fields
162        let config = self.config.lock().unwrap();
163        let parts: Vec<&str> = key.split('.').collect();
164        match parts.as_slice() {
165            ["ai", "provider"] => Ok(config.ai.provider.clone()),
166            ["ai", "model"] => Ok(config.ai.model.clone()),
167            ["ai", "api_key"] => Ok(config.ai.api_key.clone().unwrap_or_default()),
168            ["ai", "base_url"] => Ok(config.ai.base_url.clone()),
169            ["ai", "temperature"] => Ok(config.ai.temperature.to_string()),
170            ["ai", "max_sample_length"] => Ok(config.ai.max_sample_length.to_string()),
171            ["ai", "max_tokens"] => Ok(config.ai.max_tokens.to_string()),
172            ["ai", "retry_attempts"] => Ok(config.ai.retry_attempts.to_string()),
173            ["ai", "retry_delay_ms"] => Ok(config.ai.retry_delay_ms.to_string()),
174            ["ai", "request_timeout_seconds"] => Ok(config.ai.request_timeout_seconds.to_string()),
175            ["formats", "default_output"] => Ok(config.formats.default_output.clone()),
176            ["formats", "default_encoding"] => Ok(config.formats.default_encoding.clone()),
177            ["formats", "preserve_styling"] => Ok(config.formats.preserve_styling.to_string()),
178            ["formats", "encoding_detection_confidence"] => {
179                Ok(config.formats.encoding_detection_confidence.to_string())
180            }
181            ["sync", "max_offset_seconds"] => Ok(config.sync.max_offset_seconds.to_string()),
182            ["sync", "default_method"] => Ok(config.sync.default_method.clone()),
183            ["sync", "vad", "enabled"] => Ok(config.sync.vad.enabled.to_string()),
184            ["sync", "vad", "sensitivity"] => Ok(config.sync.vad.sensitivity.to_string()),
185            ["sync", "vad", "padding_chunks"] => Ok(config.sync.vad.padding_chunks.to_string()),
186            ["sync", "vad", "min_speech_duration_ms"] => {
187                Ok(config.sync.vad.min_speech_duration_ms.to_string())
188            }
189            ["general", "backup_enabled"] => Ok(config.general.backup_enabled.to_string()),
190            ["general", "task_timeout_seconds"] => {
191                Ok(config.general.task_timeout_seconds.to_string())
192            }
193            ["general", "enable_progress_bar"] => {
194                Ok(config.general.enable_progress_bar.to_string())
195            }
196            ["general", "worker_idle_timeout_seconds"] => {
197                Ok(config.general.worker_idle_timeout_seconds.to_string())
198            }
199            ["general", "max_concurrent_jobs"] => {
200                Ok(config.general.max_concurrent_jobs.to_string())
201            }
202            ["parallel", "max_workers"] => Ok(config.parallel.max_workers.to_string()),
203            ["parallel", "task_queue_size"] => Ok(config.parallel.task_queue_size.to_string()),
204            ["parallel", "enable_task_priorities"] => {
205                Ok(config.parallel.enable_task_priorities.to_string())
206            }
207            ["parallel", "auto_balance_workers"] => {
208                Ok(config.parallel.auto_balance_workers.to_string())
209            }
210            ["parallel", "overflow_strategy"] => {
211                Ok(format!("{:?}", config.parallel.overflow_strategy))
212            }
213            _ => Err(SubXError::config(format!(
214                "Unknown configuration key: {key}"
215            ))),
216        }
217    }
218
219    fn reset_to_defaults(&self) -> Result<()> {
220        // Reset the configuration to default values
221        *self.config.lock().unwrap() = Config::default();
222        Ok(())
223    }
224
225    fn set_config_value(&self, key: &str, value: &str) -> Result<()> {
226        // Load current configuration
227        let mut cfg = self.get_config()?;
228        // Validate and set the value using the same logic as ProductionConfigService
229        self.validate_and_set_value(&mut cfg, key, value)?;
230        // Validate the entire configuration
231        crate::config::validator::validate_config(&cfg)?;
232        // Update the internal configuration
233        *self.config.lock().unwrap() = cfg;
234        Ok(())
235    }
236}
237
238impl TestConfigService {
239    /// Validate and set a configuration value (same logic as ProductionConfigService).
240    fn validate_and_set_value(&self, config: &mut Config, key: &str, value: &str) -> Result<()> {
241        use crate::config::OverflowStrategy;
242        use crate::config::validation::*;
243        use crate::error::SubXError;
244
245        let parts: Vec<&str> = key.split('.').collect();
246        match parts.as_slice() {
247            ["ai", "provider"] => {
248                validate_enum(value, &["openai", "anthropic", "local"])?;
249                config.ai.provider = value.to_string();
250            }
251            ["ai", "api_key"] => {
252                if !value.is_empty() {
253                    validate_api_key(value)?;
254                    config.ai.api_key = Some(value.to_string());
255                } else {
256                    config.ai.api_key = None;
257                }
258            }
259            ["ai", "model"] => {
260                config.ai.model = value.to_string();
261            }
262            ["ai", "base_url"] => {
263                validate_url(value)?;
264                config.ai.base_url = value.to_string();
265            }
266            ["ai", "max_sample_length"] => {
267                let v = validate_usize_range(value, 100, 10000)?;
268                config.ai.max_sample_length = v;
269            }
270            ["ai", "temperature"] => {
271                let v = validate_float_range(value, 0.0, 1.0)?;
272                config.ai.temperature = v;
273            }
274            ["ai", "max_tokens"] => {
275                let v = validate_uint_range(value, 1, 100_000)?;
276                config.ai.max_tokens = v;
277            }
278            ["ai", "retry_attempts"] => {
279                let v = validate_uint_range(value, 1, 10)?;
280                config.ai.retry_attempts = v;
281            }
282            ["ai", "retry_delay_ms"] => {
283                let v = validate_u64_range(value, 100, 30000)?;
284                config.ai.retry_delay_ms = v;
285            }
286            ["ai", "request_timeout_seconds"] => {
287                let v = validate_u64_range(value, 10, 600)?;
288                config.ai.request_timeout_seconds = v;
289            }
290            ["formats", "default_output"] => {
291                validate_enum(value, &["srt", "ass", "vtt", "webvtt"])?;
292                config.formats.default_output = value.to_string();
293            }
294            ["formats", "preserve_styling"] => {
295                let v = parse_bool(value)?;
296                config.formats.preserve_styling = v;
297            }
298            ["formats", "default_encoding"] => {
299                validate_enum(value, &["utf-8", "gbk", "big5", "shift_jis"])?;
300                config.formats.default_encoding = value.to_string();
301            }
302            ["formats", "encoding_detection_confidence"] => {
303                let v = validate_float_range(value, 0.0, 1.0)?;
304                config.formats.encoding_detection_confidence = v;
305            }
306            ["sync", "max_offset_seconds"] => {
307                let v = validate_float_range(value, 0.0, 300.0)?;
308                config.sync.max_offset_seconds = v;
309            }
310            ["sync", "default_method"] => {
311                validate_enum(value, &["auto", "vad"])?;
312                config.sync.default_method = value.to_string();
313            }
314            ["sync", "vad", "enabled"] => {
315                let v = parse_bool(value)?;
316                config.sync.vad.enabled = v;
317            }
318            ["sync", "vad", "sensitivity"] => {
319                let v = validate_float_range(value, 0.0, 1.0)?;
320                config.sync.vad.sensitivity = v;
321            }
322            ["sync", "vad", "padding_chunks"] => {
323                let v = validate_uint_range(value, 0, u32::MAX)?;
324                config.sync.vad.padding_chunks = v;
325            }
326            ["sync", "vad", "min_speech_duration_ms"] => {
327                let v = validate_uint_range(value, 0, u32::MAX)?;
328                config.sync.vad.min_speech_duration_ms = v;
329            }
330            ["sync", "correlation_threshold"] => {
331                let v = validate_float_range(value, 0.0, 1.0)?;
332                config.sync.correlation_threshold = v;
333            }
334            ["sync", "dialogue_detection_threshold"] => {
335                let v = validate_float_range(value, 0.0, 1.0)?;
336                config.sync.dialogue_detection_threshold = v;
337            }
338            ["sync", "min_dialogue_duration_ms"] => {
339                let v = validate_uint_range(value, 100, 5000)?;
340                config.sync.min_dialogue_duration_ms = v;
341            }
342            ["sync", "dialogue_merge_gap_ms"] => {
343                let v = validate_uint_range(value, 50, 2000)?;
344                config.sync.dialogue_merge_gap_ms = v;
345            }
346            ["sync", "enable_dialogue_detection"] => {
347                let v = parse_bool(value)?;
348                config.sync.enable_dialogue_detection = v;
349            }
350            ["sync", "audio_sample_rate"] => {
351                let v = validate_uint_range(value, 8000, 192000)?;
352                config.sync.audio_sample_rate = v;
353            }
354            ["sync", "auto_detect_sample_rate"] => {
355                let v = parse_bool(value)?;
356                config.sync.auto_detect_sample_rate = v;
357            }
358            ["general", "backup_enabled"] => {
359                let v = parse_bool(value)?;
360                config.general.backup_enabled = v;
361            }
362            ["general", "max_concurrent_jobs"] => {
363                let v = validate_usize_range(value, 1, 64)?;
364                config.general.max_concurrent_jobs = v;
365            }
366            ["general", "task_timeout_seconds"] => {
367                let v = validate_u64_range(value, 30, 3600)?;
368                config.general.task_timeout_seconds = v;
369            }
370            ["general", "enable_progress_bar"] => {
371                let v = parse_bool(value)?;
372                config.general.enable_progress_bar = v;
373            }
374            ["general", "worker_idle_timeout_seconds"] => {
375                let v = validate_u64_range(value, 10, 3600)?;
376                config.general.worker_idle_timeout_seconds = v;
377            }
378            ["parallel", "max_workers"] => {
379                let v = validate_usize_range(value, 1, 64)?;
380                config.parallel.max_workers = v;
381            }
382            ["parallel", "task_queue_size"] => {
383                let v = validate_usize_range(value, 100, 10000)?;
384                config.parallel.task_queue_size = v;
385            }
386            ["parallel", "enable_task_priorities"] => {
387                let v = parse_bool(value)?;
388                config.parallel.enable_task_priorities = v;
389            }
390            ["parallel", "auto_balance_workers"] => {
391                let v = parse_bool(value)?;
392                config.parallel.auto_balance_workers = v;
393            }
394            ["parallel", "overflow_strategy"] => {
395                validate_enum(value, &["Block", "Drop", "Expand"])?;
396                config.parallel.overflow_strategy = match value {
397                    "Block" => OverflowStrategy::Block,
398                    "Drop" => OverflowStrategy::Drop,
399                    "Expand" => OverflowStrategy::Expand,
400                    _ => unreachable!(),
401                };
402            }
403            _ => {
404                return Err(SubXError::config(format!(
405                    "Unknown configuration key: {key}"
406                )));
407            }
408        }
409        Ok(())
410    }
411}
412
413impl Default for TestConfigService {
414    fn default() -> Self {
415        Self::with_defaults()
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    #[test]
424    fn test_config_service_with_defaults() {
425        let service = TestConfigService::with_defaults();
426        let config = service.get_config().unwrap();
427
428        assert_eq!(config.ai.provider, "openai");
429        assert_eq!(config.ai.model, "gpt-4.1-mini");
430    }
431
432    #[test]
433    fn test_config_service_with_ai_settings() {
434        let service = TestConfigService::with_ai_settings("anthropic", "claude-3");
435        let config = service.get_config().unwrap();
436
437        assert_eq!(config.ai.provider, "anthropic");
438        assert_eq!(config.ai.model, "claude-3");
439    }
440
441    #[test]
442    fn test_config_service_with_ai_settings_and_key() {
443        let service =
444            TestConfigService::with_ai_settings_and_key("openai", "gpt-4.1", "test-api-key");
445        let config = service.get_config().unwrap();
446
447        assert_eq!(config.ai.provider, "openai");
448        assert_eq!(config.ai.model, "gpt-4.1");
449        assert_eq!(config.ai.api_key, Some("test-api-key".to_string()));
450    }
451
452    #[test]
453    fn test_config_service_with_ai_settings_and_key_openrouter() {
454        let service = TestConfigService::with_ai_settings_and_key(
455            "openrouter",
456            "deepseek/deepseek-r1-0528:free",
457            "test-openrouter-key",
458        );
459        let config = service.get_config().unwrap();
460        assert_eq!(config.ai.provider, "openrouter");
461        assert_eq!(config.ai.model, "deepseek/deepseek-r1-0528:free");
462        assert_eq!(config.ai.api_key, Some("test-openrouter-key".to_string()));
463    }
464
465    #[test]
466    fn test_config_service_with_sync_settings() {
467        let service = TestConfigService::with_sync_settings(0.8, 45.0);
468        let config = service.get_config().unwrap();
469
470        assert_eq!(config.sync.correlation_threshold, 0.8);
471        assert_eq!(config.sync.max_offset_seconds, 45.0);
472    }
473
474    #[test]
475    fn test_config_service_with_parallel_settings() {
476        let service = TestConfigService::with_parallel_settings(8, 200);
477        let config = service.get_config().unwrap();
478
479        assert_eq!(config.general.max_concurrent_jobs, 8);
480        assert_eq!(config.parallel.task_queue_size, 200);
481    }
482
483    #[test]
484    fn test_config_service_reload() {
485        let service = TestConfigService::with_defaults();
486
487        // Reload should always succeed for test service
488        assert!(service.reload().is_ok());
489    }
490
491    #[test]
492    fn test_config_service_direct_access() {
493        let service = TestConfigService::with_defaults();
494
495        // Test direct read access
496        assert_eq!(service.config().ai.provider, "openai");
497
498        // Test mutable access
499        service.config_mut().ai.provider = "modified".to_string();
500        assert_eq!(service.config().ai.provider, "modified");
501
502        let config = service.get_config().unwrap();
503        assert_eq!(config.ai.provider, "modified");
504    }
505}