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: {}",
215                key
216            ))),
217        }
218    }
219
220    fn reset_to_defaults(&self) -> Result<()> {
221        // Reset the configuration to default values
222        *self.config.lock().unwrap() = Config::default();
223        Ok(())
224    }
225
226    fn set_config_value(&self, key: &str, value: &str) -> Result<()> {
227        // Load current configuration
228        let mut cfg = self.get_config()?;
229        // Validate and set the value using the same logic as ProductionConfigService
230        self.validate_and_set_value(&mut cfg, key, value)?;
231        // Validate the entire configuration
232        crate::config::validator::validate_config(&cfg)?;
233        // Update the internal configuration
234        *self.config.lock().unwrap() = cfg;
235        Ok(())
236    }
237}
238
239impl TestConfigService {
240    /// Validate and set a configuration value (same logic as ProductionConfigService).
241    fn validate_and_set_value(&self, config: &mut Config, key: &str, value: &str) -> Result<()> {
242        use crate::config::OverflowStrategy;
243        use crate::config::validation::*;
244        use crate::error::SubXError;
245
246        let parts: Vec<&str> = key.split('.').collect();
247        match parts.as_slice() {
248            ["ai", "provider"] => {
249                validate_enum(value, &["openai", "anthropic", "local"])?;
250                config.ai.provider = value.to_string();
251            }
252            ["ai", "api_key"] => {
253                if !value.is_empty() {
254                    validate_api_key(value)?;
255                    config.ai.api_key = Some(value.to_string());
256                } else {
257                    config.ai.api_key = None;
258                }
259            }
260            ["ai", "model"] => {
261                config.ai.model = value.to_string();
262            }
263            ["ai", "base_url"] => {
264                validate_url(value)?;
265                config.ai.base_url = value.to_string();
266            }
267            ["ai", "max_sample_length"] => {
268                let v = validate_usize_range(value, 100, 10000)?;
269                config.ai.max_sample_length = v;
270            }
271            ["ai", "temperature"] => {
272                let v = validate_float_range(value, 0.0, 1.0)?;
273                config.ai.temperature = v;
274            }
275            ["ai", "max_tokens"] => {
276                let v = validate_uint_range(value, 1, 100_000)?;
277                config.ai.max_tokens = v;
278            }
279            ["ai", "retry_attempts"] => {
280                let v = validate_uint_range(value, 1, 10)?;
281                config.ai.retry_attempts = v;
282            }
283            ["ai", "retry_delay_ms"] => {
284                let v = validate_u64_range(value, 100, 30000)?;
285                config.ai.retry_delay_ms = v;
286            }
287            ["ai", "request_timeout_seconds"] => {
288                let v = validate_u64_range(value, 10, 600)?;
289                config.ai.request_timeout_seconds = v;
290            }
291            ["formats", "default_output"] => {
292                validate_enum(value, &["srt", "ass", "vtt", "webvtt"])?;
293                config.formats.default_output = value.to_string();
294            }
295            ["formats", "preserve_styling"] => {
296                let v = parse_bool(value)?;
297                config.formats.preserve_styling = v;
298            }
299            ["formats", "default_encoding"] => {
300                validate_enum(value, &["utf-8", "gbk", "big5", "shift_jis"])?;
301                config.formats.default_encoding = value.to_string();
302            }
303            ["formats", "encoding_detection_confidence"] => {
304                let v = validate_float_range(value, 0.0, 1.0)?;
305                config.formats.encoding_detection_confidence = v;
306            }
307            ["sync", "max_offset_seconds"] => {
308                let v = validate_float_range(value, 0.0, 300.0)?;
309                config.sync.max_offset_seconds = v;
310            }
311            ["sync", "default_method"] => {
312                validate_enum(value, &["auto", "vad"])?;
313                config.sync.default_method = value.to_string();
314            }
315            ["sync", "vad", "enabled"] => {
316                let v = parse_bool(value)?;
317                config.sync.vad.enabled = v;
318            }
319            ["sync", "vad", "sensitivity"] => {
320                let v = validate_float_range(value, 0.0, 1.0)?;
321                config.sync.vad.sensitivity = v;
322            }
323            ["sync", "vad", "padding_chunks"] => {
324                let v = validate_uint_range(value, 0, u32::MAX)?;
325                config.sync.vad.padding_chunks = v;
326            }
327            ["sync", "vad", "min_speech_duration_ms"] => {
328                let v = validate_uint_range(value, 0, u32::MAX)?;
329                config.sync.vad.min_speech_duration_ms = v;
330            }
331            ["sync", "correlation_threshold"] => {
332                let v = validate_float_range(value, 0.0, 1.0)?;
333                config.sync.correlation_threshold = v;
334            }
335            ["sync", "dialogue_detection_threshold"] => {
336                let v = validate_float_range(value, 0.0, 1.0)?;
337                config.sync.dialogue_detection_threshold = v;
338            }
339            ["sync", "min_dialogue_duration_ms"] => {
340                let v = validate_uint_range(value, 100, 5000)?;
341                config.sync.min_dialogue_duration_ms = v;
342            }
343            ["sync", "dialogue_merge_gap_ms"] => {
344                let v = validate_uint_range(value, 50, 2000)?;
345                config.sync.dialogue_merge_gap_ms = v;
346            }
347            ["sync", "enable_dialogue_detection"] => {
348                let v = parse_bool(value)?;
349                config.sync.enable_dialogue_detection = v;
350            }
351            ["sync", "audio_sample_rate"] => {
352                let v = validate_uint_range(value, 8000, 192000)?;
353                config.sync.audio_sample_rate = v;
354            }
355            ["sync", "auto_detect_sample_rate"] => {
356                let v = parse_bool(value)?;
357                config.sync.auto_detect_sample_rate = v;
358            }
359            ["general", "backup_enabled"] => {
360                let v = parse_bool(value)?;
361                config.general.backup_enabled = v;
362            }
363            ["general", "max_concurrent_jobs"] => {
364                let v = validate_usize_range(value, 1, 64)?;
365                config.general.max_concurrent_jobs = v;
366            }
367            ["general", "task_timeout_seconds"] => {
368                let v = validate_u64_range(value, 30, 3600)?;
369                config.general.task_timeout_seconds = v;
370            }
371            ["general", "enable_progress_bar"] => {
372                let v = parse_bool(value)?;
373                config.general.enable_progress_bar = v;
374            }
375            ["general", "worker_idle_timeout_seconds"] => {
376                let v = validate_u64_range(value, 10, 3600)?;
377                config.general.worker_idle_timeout_seconds = v;
378            }
379            ["parallel", "max_workers"] => {
380                let v = validate_usize_range(value, 1, 64)?;
381                config.parallel.max_workers = v;
382            }
383            ["parallel", "task_queue_size"] => {
384                let v = validate_usize_range(value, 100, 10000)?;
385                config.parallel.task_queue_size = v;
386            }
387            ["parallel", "enable_task_priorities"] => {
388                let v = parse_bool(value)?;
389                config.parallel.enable_task_priorities = v;
390            }
391            ["parallel", "auto_balance_workers"] => {
392                let v = parse_bool(value)?;
393                config.parallel.auto_balance_workers = v;
394            }
395            ["parallel", "overflow_strategy"] => {
396                validate_enum(value, &["Block", "Drop", "Expand"])?;
397                config.parallel.overflow_strategy = match value {
398                    "Block" => OverflowStrategy::Block,
399                    "Drop" => OverflowStrategy::Drop,
400                    "Expand" => OverflowStrategy::Expand,
401                    _ => unreachable!(),
402                };
403            }
404            _ => {
405                return Err(SubXError::config(format!(
406                    "Unknown configuration key: {}",
407                    key
408                )));
409            }
410        }
411        Ok(())
412    }
413}
414
415impl Default for TestConfigService {
416    fn default() -> Self {
417        Self::with_defaults()
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    #[test]
426    fn test_config_service_with_defaults() {
427        let service = TestConfigService::with_defaults();
428        let config = service.get_config().unwrap();
429
430        assert_eq!(config.ai.provider, "openai");
431        assert_eq!(config.ai.model, "gpt-4.1-mini");
432    }
433
434    #[test]
435    fn test_config_service_with_ai_settings() {
436        let service = TestConfigService::with_ai_settings("anthropic", "claude-3");
437        let config = service.get_config().unwrap();
438
439        assert_eq!(config.ai.provider, "anthropic");
440        assert_eq!(config.ai.model, "claude-3");
441    }
442
443    #[test]
444    fn test_config_service_with_ai_settings_and_key() {
445        let service =
446            TestConfigService::with_ai_settings_and_key("openai", "gpt-4.1", "test-api-key");
447        let config = service.get_config().unwrap();
448
449        assert_eq!(config.ai.provider, "openai");
450        assert_eq!(config.ai.model, "gpt-4.1");
451        assert_eq!(config.ai.api_key, Some("test-api-key".to_string()));
452    }
453
454    #[test]
455    fn test_config_service_with_sync_settings() {
456        let service = TestConfigService::with_sync_settings(0.8, 45.0);
457        let config = service.get_config().unwrap();
458
459        assert_eq!(config.sync.correlation_threshold, 0.8);
460        assert_eq!(config.sync.max_offset_seconds, 45.0);
461    }
462
463    #[test]
464    fn test_config_service_with_parallel_settings() {
465        let service = TestConfigService::with_parallel_settings(8, 200);
466        let config = service.get_config().unwrap();
467
468        assert_eq!(config.general.max_concurrent_jobs, 8);
469        assert_eq!(config.parallel.task_queue_size, 200);
470    }
471
472    #[test]
473    fn test_config_service_reload() {
474        let service = TestConfigService::with_defaults();
475
476        // Reload should always succeed for test service
477        assert!(service.reload().is_ok());
478    }
479
480    #[test]
481    fn test_config_service_direct_access() {
482        let service = TestConfigService::with_defaults();
483
484        // Test direct read access
485        assert_eq!(service.config().ai.provider, "openai");
486
487        // Test mutable access
488        service.config_mut().ai.provider = "modified".to_string();
489        assert_eq!(service.config().ai.provider, "modified");
490
491        let config = service.get_config().unwrap();
492        assert_eq!(config.ai.provider, "modified");
493    }
494}