settings_loader 1.0.0

Opinionated configuration settings load mechanism for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! Configuration Editor Test Suite

#[cfg(feature = "editor")]
mod editor_tests {
    use std::fs;
    use std::path::PathBuf;
    use tempfile::TempDir;

    use settings_loader::editor::json::JsonLayerEditor;
    use settings_loader::editor::toml::TomlLayerEditor;
    use settings_loader::editor::yaml::YamlLayerEditor;
    use settings_loader::editor::{
        ConfigFormat, Editor, EditorError, LayerEditor, SettingsEditor, SettingsLoaderEditor,
    };
    use trim_margin::MarginTrimmable;

    // ========================================================================
    // Test 1-3: ConfigFormat Enum & from_path() Detection
    // ========================================================================

    /// Test ConfigFormat enum has all 5 format variants
    #[test]
    fn test_config_format_enum_variants() {
        // ConfigFormat should have exactly 5 variants:
        // - Toml
        // - Json
        // - Yaml
        // - Hjson (optional, may be deferred)
        // - Ron (optional, may be deferred)
        //
        // Must be: Debug, Clone, Copy, PartialEq, Eq

        // Test that all 3 required variants can be constructed
        let toml = ConfigFormat::Toml;
        let json = ConfigFormat::Json;
        let yaml = ConfigFormat::Yaml;

        // Test Clone trait
        let toml_cloned = toml;
        assert_eq!(toml, toml_cloned);

        // Test Copy trait (implicitly by using values multiple times)
        let _copy1 = toml;
        let _copy2 = toml;

        // Test Debug trait
        let debug_str = format!("{:?}", toml);
        assert!(!debug_str.is_empty());
        assert!(debug_str.contains("Toml"));

        // Test PartialEq trait
        assert_eq!(toml, ConfigFormat::Toml);
        assert_eq!(json, ConfigFormat::Json);
        assert_eq!(yaml, ConfigFormat::Yaml);
        assert_ne!(toml, json);
        assert_ne!(json, yaml);
        assert_ne!(toml, yaml);

        // Test Eq trait (verify reflexivity)
        assert!(toml == toml);
        assert!(json == json);
        assert!(yaml == yaml);

        // Test that all variants are distinct
        let all_formats = [toml, json, yaml];
        for (i, fmt1) in all_formats.iter().enumerate() {
            for (j, fmt2) in all_formats.iter().enumerate() {
                if i == j {
                    assert_eq!(fmt1, fmt2, "Same format should be equal");
                } else {
                    assert_ne!(fmt1, fmt2, "Different formats should not be equal");
                }
            }
        }
    }

    /// Test from_path() detects TOML files
    #[test]
    fn test_config_format_from_path_toml() {
        let toml_path = PathBuf::from("settings.toml");
        assert_eq!(ConfigFormat::from_path(&toml_path), Some(ConfigFormat::Toml));
    }

    /// Test from_path() detects JSON files
    #[test]
    fn test_config_format_from_path_json() {
        let json_path = PathBuf::from("config.json");
        assert_eq!(ConfigFormat::from_path(&json_path), Some(ConfigFormat::Json));
    }

    /// Test from_path() detects YAML files
    #[test]
    fn test_config_format_from_path_yaml() {
        let yaml_path = PathBuf::from("settings.yaml");
        assert_eq!(ConfigFormat::from_path(&yaml_path), Some(ConfigFormat::Yaml));

        let yml_path = PathBuf::from("settings.yml");
        assert_eq!(ConfigFormat::from_path(&yml_path), Some(ConfigFormat::Yaml));
    }

    /// Test from_path() returns None for unknown extensions
    #[test]
    fn test_config_format_from_path_unknown() {
        let unknown_path = PathBuf::from("settings.txt");
        assert_eq!(ConfigFormat::from_path(&unknown_path), None);
    }

    // ========================================================================
    // Test 5-8: LayerEditor Basic Operations (TOML)
    // ========================================================================

    /// Test opening existing TOML file
    #[test]
    fn test_toml_layer_editor_open_existing_file() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        // Create test TOML file
        fs::write(&toml_path, "app_name = \"test_app\"\nversion = \"1.0.0\"").unwrap();

        // Open should succeed
        let editor = TomlLayerEditor::open(&toml_path).expect("Failed to open TOML");
        assert!(!editor.is_dirty());
    }

    /// Test get() retrieves values from TOML
    #[test]
    fn test_toml_layer_editor_get_string_value() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        fs::write(&toml_path, "app_name = \"my_app\"").unwrap();

        let editor = TomlLayerEditor::open(&toml_path).unwrap();
        let value: String = editor.get("app_name").expect("Failed to get value");
        assert_eq!(value, "my_app");
    }

    /// Test set() modifies values in TOML
    #[test]
    fn test_toml_layer_editor_set_string_value() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        fs::write(&toml_path, "app_name = \"old_app\"").unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.set("app_name", "new_app").expect("Failed to set value");
        assert!(editor.is_dirty());
        let value: String = editor.get("app_name").unwrap();
        assert_eq!(value, "new_app");
    }

    /// Test unset() removes keys from TOML
    #[test]
    fn test_toml_layer_editor_unset_key() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        fs::write(&toml_path, "app_name = \"test\"\nversion = \"1.0\"").unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.unset("version").expect("Failed to unset key");
        assert!(editor.is_dirty());
        let value: Option<String> = editor.get("version");
        assert!(value.is_none());
    }

    /// Test keys() returns all top-level keys
    #[test]
    fn test_toml_layer_editor_keys() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        fs::write(&toml_path, "app_name = \"test\"\nversion = \"1.0\"\ndebug = true").unwrap();

        let editor = TomlLayerEditor::open(&toml_path).unwrap();
        let keys = editor.keys();
        assert!(keys.contains(&"app_name".to_string()));
        assert!(keys.contains(&"version".to_string()));
        assert!(keys.contains(&"debug".to_string()));
    }

    // ========================================================================
    // Test 9-11: LayerEditor Dotted Path Navigation
    // ========================================================================

    /// Test get() with dotted path
    #[test]
    fn test_toml_layer_editor_get_nested_dotted_path() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        fs::write(&toml_path, "[database]\nhost = \"localhost\"\nport = 5432").unwrap();

        let editor = TomlLayerEditor::open(&toml_path).unwrap();
        let host: String = editor.get("database.host").unwrap();
        assert_eq!(host, "localhost");
        let port: u16 = editor.get("database.port").unwrap();
        assert_eq!(port, 5432);
    }

    /// Test set() with dotted path creates nested structure
    #[test]
    fn test_toml_layer_editor_set_nested_dotted_path() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        fs::write(&toml_path, "# Empty config").unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.set("database.host", "db.example.com").unwrap();
        editor.set("database.port", 3306).unwrap();
        let host: String = editor.get("database.host").unwrap();
        assert_eq!(host, "db.example.com");
    }

    /// Test unset() with dotted path
    #[test]
    fn test_toml_layer_editor_unset_nested_dotted_path() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        fs::write(&toml_path, "[database]\nhost = \"localhost\"\nport = 5432").unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.unset("database.port").unwrap();
        let port: Option<u16> = editor.get("database.port");
        assert!(port.is_none());
    }

    // ========================================================================
    // Test 12-14: Dirty Flag Tracking & Save Operations
    // ========================================================================

    /// Test is_dirty() returns false initially
    #[test]
    fn test_toml_layer_editor_dirty_flag_initial_state() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");
        fs::write(&toml_path, "app_name = \"test\"").unwrap();

        let editor = TomlLayerEditor::open(&toml_path).unwrap();
        assert!(!editor.is_dirty());
    }

    /// Test is_dirty() returns true after modification
    #[test]
    fn test_toml_layer_editor_dirty_flag_after_modification() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");
        fs::write(&toml_path, "app_name = \"test\"").unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.set("app_name", "modified").unwrap();
        assert!(editor.is_dirty());
    }

    /// Test save() writes changes to file
    #[test]
    fn test_toml_layer_editor_save_persists_changes() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");
        fs::write(&toml_path, "app_name = \"original\"").unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.set("app_name", "updated").unwrap();
        editor.save().expect("Failed to save");
        assert!(!editor.is_dirty());

        // Verify file was actually updated
        let content = fs::read_to_string(&toml_path).unwrap();
        assert!(content.contains("updated"));
    }

    // ========================================================================
    // Test 15-16: Atomic Writes
    // ========================================================================

    /// Test save() uses temp file + rename pattern
    #[test]
    fn test_toml_layer_editor_save_atomic_write() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");
        fs::write(&toml_path, "app_name = \"test\"").unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.set("app_name", "modified").unwrap();
        editor.save().unwrap();

        // Verify original file was atomically replaced
        let content = fs::read_to_string(&toml_path).unwrap();
        assert!(content.contains("modified"));
        // No temp files should remain
        let entries: Vec<_> = fs::read_dir(temp_dir.path()).unwrap().filter_map(Result::ok).collect();
        assert_eq!(entries.len(), 1); // Only settings.toml
    }

    /// Test save() uses atomic writes to prevent partial/corrupted files
    #[test]
    fn test_toml_layer_editor_save_error_leaves_original_untouched() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");
        let original_content = "app_name = \"original\"";
        fs::write(&toml_path, original_content).unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.set("app_name", "modified").unwrap();

        // The atomic write pattern (temp file + rename) ensures that either:
        // 1. The save succeeds and the new file replaces the old one
        // 2. The save fails and the old file remains untouched
        //
        // Note: Testing actual I/O errors (disk full, permission denied) is
        // platform-specific and flaky. The implementation pattern itself
        // (temp file + atomic rename) is what prevents corruption.
        // This test verifies the pattern works in the happy path.

        let content_before = fs::read_to_string(&toml_path).unwrap();
        assert_eq!(content_before, original_content);

        editor.save().unwrap();
        let content_after = fs::read_to_string(&toml_path).unwrap();
        assert!(content_after.contains("modified"));
    }

    // ========================================================================
    // Test 17-18: TOML Comment Preservation (UNIQUE FEATURE)
    // ========================================================================

    /// Test TOML comments are preserved after modification
    #[test]
    fn test_toml_layer_editor_preserves_comments() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        let original_toml = r#"# Application Configuration
app_name = "my_app"  # The application name
version = "1.0.0"    # Version number

# Database Settings
[database]
host = "localhost"   # Database host
port = 5432          # Database port
"#;

        fs::write(&toml_path, original_toml).unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.set("version", "2.0.0").unwrap();
        editor.save().unwrap();

        let modified_toml = fs::read_to_string(&toml_path).unwrap();

        // All comments should be preserved
        assert!(modified_toml.contains("# Application Configuration"));
        assert!(modified_toml.contains("# The application name"));
        assert!(modified_toml.contains("# Database Settings"));
        assert!(modified_toml.contains("# Database host"));
        assert!(modified_toml.contains("# Database port"));

        // Modified value should be updated
        assert!(modified_toml.contains("version = \"2.0.0\""));
        assert!(!modified_toml.contains("version = \"1.0.0\""));
    }

    /// Test TOML whitespace and formatting preserved
    #[test]
    fn test_toml_layer_editor_preserves_formatting() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");

        let original_toml = r#"[database]
# Critical settings
host = "localhost"

# Optional settings
ssl_enabled = true
"#;

        fs::write(&toml_path, original_toml).unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        editor.set("database.ssl_enabled", false).unwrap();
        editor.save().unwrap();

        let modified_toml = fs::read_to_string(&toml_path).unwrap();

        // Comments and blank lines should be preserved
        assert!(modified_toml.contains("# Critical settings"));
        assert!(modified_toml.contains("# Optional settings"));
        assert_eq!(modified_toml.matches('\n').count(), original_toml.matches('\n').count());
    }

    // ========================================================================
    // Test 19-20: JSON Backend (No Comment Preservation)
    // ========================================================================

    /// Test JSON editor opens and gets values
    #[test]
    fn test_json_layer_editor_roundtrip() {
        let temp_dir = TempDir::new().unwrap();
        let json_path = temp_dir.path().join("settings.json");

        let json_content = r#"{
      "app_name": "test_app",
      "version": "1.0.0"
    }"#;

        fs::write(&json_path, json_content).unwrap();

        let mut editor = JsonLayerEditor::open(&json_path).unwrap();
        let app_name: String = editor.get("app_name").unwrap();
        assert_eq!(app_name, "test_app");

        editor.set("version", "2.0.0").unwrap();
        editor.save().unwrap();

        let modified_json = fs::read_to_string(&json_path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&modified_json).unwrap();
        assert_eq!(parsed["version"], "2.0.0");
    }

    /// Test JSON nested path navigation
    #[test]
    fn test_json_layer_editor_nested_paths() {
        let temp_dir = TempDir::new().unwrap();
        let json_path = temp_dir.path().join("settings.json");

        let json_content = r#"{
      "database": {
        "host": "localhost",
        "port": 5432
      }
    }"#;

        fs::write(&json_path, json_content).unwrap();

        let editor = JsonLayerEditor::open(&json_path).unwrap();
        let host: String = editor.get("database.host").unwrap();
        assert_eq!(host, "localhost");
        let port: u16 = editor.get("database.port").unwrap();
        assert_eq!(port, 5432);
    }

    // // ========================================================================
    // // Test 21-22: YAML Backend
    // // ========================================================================

    /// Test YAML editor roundtrip
    #[test]
    fn test_yaml_layer_editor_roundtrip() {
        let temp_dir = TempDir::new().unwrap();
        let yaml_path = temp_dir.path().join("settings.yaml");

        let yaml_content = r#"
            |app_name: test_app
            |version: "1.0.0"
            |"#
        .trim_margin()
        .unwrap();

        fs::write(&yaml_path, yaml_content).unwrap();

        let mut editor = YamlLayerEditor::open(&yaml_path).unwrap();
        let app_name: String = editor.get("app_name").unwrap();
        assert_eq!(app_name, "test_app");

        editor.set("version", "2.0.0").unwrap();
        editor.save().unwrap();

        let modified_yaml = fs::read_to_string(&yaml_path).unwrap();
        assert!(modified_yaml.contains("version: \"2.0.0\"") || modified_yaml.contains("version: 2.0.0"));
    }

    /// Test YAML nested structures
    #[test]
    fn test_yaml_layer_editor_nested_structures() {
        let temp_dir = TempDir::new().unwrap();
        let yaml_path = temp_dir.path().join("settings.yaml");

        let yaml_content = r#"
            |database:
            |  host: localhost
            |  port: 5432
            |  enabled: true
            |"#
        .trim_margin()
        .unwrap();

        fs::write(&yaml_path, yaml_content).unwrap();

        let editor = YamlLayerEditor::open(&yaml_path).unwrap();
        let host: String = editor.get("database.host").unwrap();
        assert_eq!(host, "localhost");
    }

    // ========================================================================
    // Test 23-24: Error Handling
    // ========================================================================

    /// Test opening non-existent file returns error
    #[test]
    fn test_layer_editor_open_nonexistent_file_error() {
        let _nonexistent_path = PathBuf::from("/tmp/nonexistent_config_12345.toml");

        let result = TomlLayerEditor::open(&_nonexistent_path);
        assert!(result.is_err());
        match result.unwrap_err() {
            EditorError::IoError(_) => {},
            _ => panic!("Expected IoError"),
        }
    }

    /// Test getting non-existent key returns None
    #[test]
    fn test_layer_editor_get_nonexistent_key() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");
        fs::write(&toml_path, "existing_key = \"value\"").unwrap();

        let editor = TomlLayerEditor::open(&toml_path).unwrap();
        let result: Option<String> = editor.get("nonexistent_key");
        assert!(result.is_none());
    }

    /// Test unsetting non-existent key returns error
    #[test]
    fn test_layer_editor_unset_nonexistent_key_error() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");
        fs::write(&toml_path, "existing_key = \"value\"").unwrap();

        let mut editor = TomlLayerEditor::open(&toml_path).unwrap();
        let result = editor.unset("nonexistent_key");
        assert!(result.is_err());
        match result.unwrap_err() {
            EditorError::KeyNotFound(_) => {},
            _ => panic!("Expected KeyNotFound"),
        }
    }

    /// Test type mismatch error
    #[test]
    fn test_layer_editor_type_mismatch_error() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("settings.toml");
        fs::write(&toml_path, "port = 5432").unwrap();

        let editor = TomlLayerEditor::open(&toml_path).unwrap();
        let result: Option<String> = editor.get("port");
        // Should fail: trying to get u16 value as String
        assert!(result.is_none());
    }

    // ========================================================================
    // Test 25-26: SettingsEditor Factory Trait
    // ========================================================================

    /// Test SettingsEditor::open() format detection
    #[test]
    fn test_settings_editor_open_format_detection() {
        let temp_dir = TempDir::new().unwrap();
        let toml_path = temp_dir.path().join("config.toml");
        fs::write(&toml_path, "test = true").unwrap();

        let editor = SettingsLoaderEditor::open(&toml_path).unwrap();
        match editor {
            Editor::Toml(_) => {}, // Expected Toml editor
            _ => panic!("Expected Toml editor"),
        }

        let json_path = temp_dir.path().join("config.json");
        fs::write(&json_path, "{ \"test\": true }").unwrap();
        let editor = SettingsLoaderEditor::open(&json_path).unwrap();
        match editor {
            Editor::Json(_) => {}, // Expected Json editor
            _ => panic!("Expected Json editor"),
        }

        let yaml_path = temp_dir.path().join("config.yaml");
        fs::write(&yaml_path, "test: true").unwrap();
        let editor = SettingsLoaderEditor::open(&yaml_path).unwrap();
        match editor {
            Editor::Yaml(_) => {}, // Expected Yaml editor
            _ => panic!("Expected Yaml editor"),
        }
    }

    /// Test SettingsEditor::create() with explicit format
    #[test]
    fn test_settings_editor_create_with_format() {
        let temp_dir = TempDir::new().unwrap();
        let new_toml_path = temp_dir.path().join("new_config.toml");

        let editor = SettingsLoaderEditor::create(&new_toml_path, ConfigFormat::Toml).unwrap();
        assert!(!editor.is_dirty());
        assert!(new_toml_path.exists());
        match editor {
            Editor::Toml(_) => {}, // Expected Toml editor
            _ => panic!("Expected Toml editor"),
        }

        let new_json_path = temp_dir.path().join("new_config.json");
        let editor = SettingsLoaderEditor::create(&new_json_path, ConfigFormat::Json).unwrap();
        assert!(!editor.is_dirty());
        assert!(new_json_path.exists());
        match editor {
            Editor::Json(_) => {},
            _ => panic!("Expected Json editor"),
        }

        let new_yaml_path = temp_dir.path().join("new_config.yaml");
        let editor = SettingsLoaderEditor::create(&new_yaml_path, ConfigFormat::Yaml).unwrap();
        assert!(!editor.is_dirty());
        assert!(new_yaml_path.exists());
        match editor {
            Editor::Yaml(_) => {},
            _ => panic!("Expected Yaml editor"),
        }
    }

    // ========================================================================
    // Test 27: Real-World Turtle TUI Scenario
    // ========================================================================

    /// Test Turtle configuration editing workflow
    #[test]
    fn test_turtle_tui_configuration_editing_scenario() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("turtle_settings.toml");

        let turtle_config = r#"# Spark Turtle Configuration

[app]
name = "Spark Turtle"
version = "0.1.0"

# Logging Configuration
[logging]
level = "info"
format = "json"

# TUI Settings
[tui]
theme = "dark"
enabled = true
"#;

        fs::write(&config_path, turtle_config).unwrap();

        // Scenario: User opens TUI, sees current settings, edits them
        let mut editor = SettingsLoaderEditor::open(&config_path).unwrap();

        // Get current values
        let current_level: String = editor.get("logging.level").unwrap();
        assert_eq!(current_level, "info");

        // User changes logging level
        editor.set("logging.level", "debug").unwrap();
        assert!(editor.is_dirty());

        // User changes theme
        editor.set("tui.theme", "light").unwrap();

        // User confirms changes
        editor.save().unwrap();
        assert!(!editor.is_dirty());

        // Verify changes persisted
        let updated_content = fs::read_to_string(&config_path).unwrap();
        assert!(updated_content.contains("level = \"debug\""));
        assert!(updated_content.contains("theme = \"light\""));

        // Comments should still be there (unique feature!)
        assert!(updated_content.contains("# Logging Configuration"));
        assert!(updated_content.contains("# TUI Settings"));
    }

    // ========================================================================
    // Test 28: EditorError Enum Variants
    // ========================================================================

    /// Test EditorError variants exist and convert properly
    #[test]
    fn test_editor_error_variants() {
        // EditorError should have variants for:
        // - IoError (from std::io::Error)
        // - ParseError (format parsing failures)
        // - SerializationError (serialization failures)
        // - KeyNotFound (missing key in config)
        // - FormatMismatch (wrong file format)
        // - TypeMismatch (type conversion failures)
        //
        // All should implement Display, Debug, Error traits

        // Test that errors convert from io::Error
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let editor_error = EditorError::from(io_err);

        // Verify it can be formatted for display
        let error_msg = format!("{}", editor_error);
        assert!(!error_msg.is_empty());

        // Verify it can be debugged
        let debug_msg = format!("{:?}", editor_error);
        assert!(!debug_msg.is_empty());
    }

    // ========================================================================
    // Test 29: ConfigEditor Multi-Layer Orchestration
    // ========================================================================

    #[test]
    fn test_config_editor_multi_layer_orchestration() {
        use serde::Deserialize;
        use settings_loader::{ConfigEditor, LayerBuilder, SettingsLoader};

        let temp_dir = TempDir::new().unwrap();
        let user_path = temp_dir.path().join("user.toml");
        let project_path = temp_dir.path().join("project.json");

        fs::write(&user_path, "theme = \"dark\"\nfont_size = 12").unwrap();
        fs::write(&project_path, r#"{ "project_name": "Test", "font_size": 14 }"#).unwrap();

        #[derive(Debug, Deserialize)]
        struct MySettings {
            theme: String,
            font_size: u8,
            project_name: String,
        }

        impl SettingsLoader for MySettings {
            type Options = settings_loader::NoOptions;
        }

        // Setup builder with multiple layers
        let initial_builder = LayerBuilder::new();
        let builder = initial_builder
            .with_path(user_path.clone())
            .with_path(project_path.clone());

        let (config_builder, source_map) = builder.build_with_provenance().unwrap();
        let config = config_builder.build().unwrap();
        let settings: MySettings = config.try_deserialize().unwrap();

        // Verify initial load results
        assert_eq!(settings.theme, "dark");
        assert_eq!(settings.project_name, "Test");
        assert_eq!(settings.font_size, 14);

        let mut config_editor = ConfigEditor::new(source_map);

        // Verify we can get values from different files
        let theme: String = config_editor.get("theme").unwrap().unwrap();
        assert_eq!(theme, "dark"); // From user.toml

        let project_name: String = config_editor.get("project_name").unwrap().unwrap();
        assert_eq!(project_name, "Test"); // From project.json

        let font_size: u8 = config_editor.get("font_size").unwrap().unwrap();
        assert_eq!(font_size, 14); // From project.json (overrides user.toml)

        // Modify values
        config_editor.set("theme", "light").unwrap(); // Should go to user.toml
        config_editor.set("project_name", "Updated Project").unwrap(); // Should go to project.json

        // Save all
        config_editor.save().unwrap();

        // Verify files were updated correctly
        let user_content = fs::read_to_string(&user_path).unwrap();
        assert!(user_content.contains("theme = \"light\""));

        let project_content = fs::read_to_string(&project_path).unwrap();
        assert!(project_content.contains("\"Updated Project\""));
    }
}

#[cfg(not(feature = "editor"))]
mod tests_without_feature {
    /// Placeholder test when editor feature is disabled
    #[test]
    fn editor_feature_not_enabled() {
        // This test documents that configuration editor tests require the "editor" feature
        // Run with: cargo test --features editor
    }
}