confers 0.4.1

Production-ready Rust configuration library with zero boilerplate
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
//! Integration tests for error handling.
//!
//! These tests verify the error handling functionality including:
//! - Invalid configuration format errors
//! - Configuration validation failures
//! - Interpolation errors (circular references)
//! - Missing required fields
//! - Type mismatch errors

#![cfg(all(feature = "validation", feature = "interpolation"))]
#![allow(dead_code)]

mod common;

use std::path::PathBuf;

// ========================================
// Basic Error Tests
// ========================================

/// Test ConfigError variants are accessible.
#[test]
fn test_config_error_accessible() {
    use confers::ConfigError;

    // Verify we can construct various error types
    let _err = ConfigError::FileNotFound {
        filename: PathBuf::from("test.toml"),
        source: None,
    };

    let _err = ConfigError::InvalidValue {
        key: "test".to_string(),
        expected_type: "string".to_string(),
        message: "test message".to_string(),
    };
}

/// Test ErrorCode variants.
#[test]
fn test_error_code_variants() {
    use confers::error::ErrorCode;

    // Test all error codes exist and have expected values
    assert_eq!(ErrorCode::FileNotFound as u16, 1);
    assert_eq!(ErrorCode::FilePermission as u16, 2);
    assert_eq!(ErrorCode::FileParseError as u16, 3);
    assert_eq!(ErrorCode::IoError as u16, 10);
    assert_eq!(ErrorCode::ValidationFailed as u16, 100);
    assert_eq!(ErrorCode::TypeMismatch as u16, 101);
    assert_eq!(ErrorCode::InvalidValue as u16, 102);
    assert_eq!(ErrorCode::SchemaValidationFailed as u16, 103);
    assert_eq!(ErrorCode::DecryptionFailed as u16, 200);
    assert_eq!(ErrorCode::KeyRotationFailed as u16, 203);
    assert_eq!(ErrorCode::RemoteUnavailable as u16, 300);
    assert_eq!(ErrorCode::Timeout as u16, 900);
    assert_eq!(ErrorCode::SizeLimitExceeded as u16, 500);
    assert_eq!(ErrorCode::InterpolationError as u16, 402);
    assert_eq!(ErrorCode::CircularReference as u16, 400);
    assert_eq!(ErrorCode::ConcurrencyConflict as u16, 901);
    assert_eq!(ErrorCode::WatcherError as u16, 501);
    assert_eq!(ErrorCode::OverrideBlocked as u16, 401);
}

/// Test ErrorCode Display.
#[test]
fn test_error_code_display() {
    use confers::error::ErrorCode;

    assert_eq!(format!("{}", ErrorCode::FileNotFound), "FILE_NOT_FOUND");
    assert_eq!(format!("{}", ErrorCode::FileParseError), "FILE_PARSE_ERROR");
    assert_eq!(
        format!("{}", ErrorCode::ValidationFailed),
        "VALIDATION_FAILED"
    );
    assert_eq!(
        format!("{}", ErrorCode::CircularReference),
        "CIRCULAR_REFERENCE"
    );
}

// ========================================
// Invalid Format Error Tests (4.2.1)
// ========================================

/// Test invalid TOML format error (4.2.1).
#[test]
fn test_invalid_toml_format_error() {
    let temp_file = common::create_temp_config(
        r#"
        invalid toml content {{{
    "#,
        ".toml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct TestConfig {
        value: String,
    }

    // Use load_file_with_env to bypass path validation
    let result = TestConfig::load_file_with_env(temp_file.path());

    // Should fail to parse
    assert!(result.is_err());
}

/// Test invalid JSON format error (4.2.1).
#[test]
fn test_invalid_json_format_error() {
    let temp_file = common::create_temp_config(
        r#"
        { invalid json content }
    "#,
        ".json",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct TestConfig {
        value: String,
    }

    // Use load_file_with_env to bypass path validation
    let result = TestConfig::load_file_with_env(temp_file.path());

    // Should fail to parse
    assert!(result.is_err());
}

/// Test invalid YAML format error (4.2.1).
#[cfg(feature = "yaml")]
#[test]
fn test_invalid_yaml_format_error() {
    let temp_file = common::create_temp_config(
        r#"
        invalid: yaml: content:
          - item
        extra: invalid: indent
    "#,
        ".yaml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct TestConfig {
        value: String,
    }

    // Use load_file_with_env to bypass path validation
    let result = TestConfig::load_file_with_env(temp_file.path());

    // Should fail to parse
    assert!(result.is_err());
}

/// Test parse error location.
#[test]
fn test_parse_error_location() {
    use confers::error::ParseLocation;

    let loc = ParseLocation::new("test.toml", 10, 5);
    assert_eq!(loc.line, 10);
    assert_eq!(loc.column, 5);

    let loc_str = format!("{}", loc);
    assert!(loc_str.contains("test.toml"));
    assert!(loc_str.contains("10"));
    assert!(loc_str.contains("5"));
}

/// Test parse error from path.
#[test]
fn test_parse_error_from_path() {
    use confers::error::ParseLocation;

    let loc = ParseLocation::from_path(
        std::path::Path::new("/home/user/project/config.toml"),
        15,
        10,
    );

    assert_eq!(loc.line, 15);
    assert_eq!(loc.column, 10);
    assert!(loc.source_name.contains("config.toml"));
}

// ========================================
// Validation Failure Tests (4.2.2)
// ========================================

/// Test configuration validation failure (4.2.2).
#[test]
fn test_config_validation_failure() {
    use garde::Validate;
    use serde::Deserialize;

    #[derive(Debug, Clone, Deserialize, Validate)]
    struct ValidatedConfig {
        #[garde(length(min = 1, max = 10))]
        name: String,

        #[garde(range(min = 1, max = 100))]
        count: u32,
    }

    // Create invalid config
    let config = ValidatedConfig {
        name: "".to_string(), // Empty name - should fail
        count: 200,           // Out of range - should fail
    };

    let result = config.validate();
    assert!(result.is_err());
}

/// Test validation error with custom rule.
#[test]
fn test_validation_error_custom_rule() {
    use confers::ConfigError;

    let err = ConfigError::validation("field_name", "length(min=1)", "Field cannot be empty");

    if let confers::ConfigError::ValidationFailed {
        field,
        rule,
        message,
    } = err
    {
        assert_eq!(field, "field_name");
        assert_eq!(rule, "length(min=1)");
        assert_eq!(message, "Field cannot be empty");
    } else {
        panic!("Expected ValidationFailed error");
    }
}

/// Test validation error from garde report.
#[test]
fn test_validation_error_from_garde_report() {
    use confers::ConfigError;

    // Create a basic validation error
    let err = ConfigError::validation("test_field", "required", "test error");

    let code = err.code();
    assert!(matches!(code, confers::error::ErrorCode::ValidationFailed));
}

/// Test validation error user message.
#[test]
fn test_validation_error_user_message() {
    let err = confers::ConfigError::ValidationFailed {
        field: "email".to_string(),
        rule: "email".to_string(),
        message: "Invalid email format".to_string(),
    };

    let user_msg = err.user_message();
    assert!(user_msg.contains("email"));
    assert!(user_msg.contains("Invalid email format"));
}

// ========================================
// Interpolation Error Tests (4.2.3)
// ========================================

/// Test circular reference detection (4.2.3).
#[test]
fn test_circular_reference_detection() {
    // Create a config with circular interpolation
    let temp_file = common::create_temp_config(
        r#"
        a = "${b}"
        b = "${a}"
    "#,
        ".toml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct CircularConfig {
        a: String,
        b: String,
    }

    // Use load_file_with_env to bypass path validation
    let result = CircularConfig::load_file_with_env(temp_file.path());

    // Should detect circular reference
    assert!(result.is_err());
}

/// Test self-referencing variable error.
#[test]
fn test_self_reference_error() {
    let temp_file = common::create_temp_config(
        r#"
        value = "${value}"
    "#,
        ".toml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct SelfRefConfig {
        value: String,
    }

    let result = SelfRefConfig::load_file_with_env(temp_file.path());

    assert!(result.is_err());
}

/// Test undefined variable interpolation error.
#[test]
fn test_undefined_variable_error() {
    let temp_file = common::create_temp_config(
        r#"
        value = "${undefined_var}"
    "#,
        ".toml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct UndefinedConfig {
        value: String,
    }

    let result = UndefinedConfig::load_file_with_env(temp_file.path());

    // Should handle undefined variable gracefully
    match result {
        Ok(_config) => {
            // Some implementations may leave undefined as literal
        }
        Err(_) => {
            // This is also acceptable behavior
        }
    }
}

/// Test nested circular reference.
#[test]
fn test_nested_circular_reference() {
    let temp_file = common::create_temp_config(
        r#"
        a = "${b}"
        b = "${c}"
        c = "${a}"
    "#,
        ".toml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct NestedCircularConfig {
        a: String,
        b: String,
        c: String,
    }

    let result = NestedCircularConfig::load_file_with_env(temp_file.path());

    // Should detect circular reference
    assert!(result.is_err());
}

// ========================================
// Missing Required Field Tests (4.2.4)
// ========================================

/// Test missing required field error (4.2.4).
#[test]
fn test_missing_required_field_error() {
    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct RequiredConfig {
        required_field: String,
    }

    // Don't set required_field
    let temp_file = common::create_temp_config(
        r#"
        other_field = "value"
    "#,
        ".toml",
    );

    let result = RequiredConfig::load_file_with_env(temp_file.path());

    // Should fail due to missing required field
    assert!(result.is_err());
}

/// Test missing nested required field.
#[test]
fn test_missing_nested_required_field() {
    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct NestedConfig {
        db: DatabaseConfig,
    }

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct DatabaseConfig {
        host: String,
        port: u16,
    }

    let temp_file = common::create_temp_config(
        r#"
        [db]
        # missing host and port
    "#,
        ".toml",
    );

    let result = NestedConfig::load_file_with_env(temp_file.path());

    // String defaults to empty, u16 doesn't have default
    // So this should either work with defaults or fail
    // depending on the Config implementation
    match result {
        Ok(config) => {
            // If it works, verify the values
            assert_eq!(config.db.host, "");
        }
        Err(_) => {
            // Missing required fields is acceptable to fail
        }
    }
}

// ========================================
// Type Mismatch Tests (4.2.5)
// ========================================

/// Test type mismatch error (4.2.5).
#[test]
fn test_type_mismatch_error() {
    let temp_file = common::create_temp_config(
        r#"
        port = "not_a_number"
    "#,
        ".toml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct PortConfig {
        port: u16,
    }

    let result = PortConfig::load_file_with_env(temp_file.path());

    // Should fail type conversion
    assert!(result.is_err());
}

/// Test type mismatch for integer to string.
#[test]
fn test_integer_to_string_mismatch() {
    let temp_file = common::create_temp_config(
        r#"
        name = 12345
    "#,
        ".toml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct NameConfig {
        name: String,
    }

    let result = NameConfig::load_file_with_env(temp_file.path());

    // Should handle or reject type mismatch
    match result {
        Ok(config) => {
            // Some implementations may convert int to string
            assert_eq!(config.name, "12345");
        }
        Err(_) => {
            // Type mismatch is also acceptable
        }
    }
}

/// Test type mismatch for string to integer.
#[test]
fn test_string_to_integer_mismatch() {
    let temp_file = common::create_temp_config(
        r#"
        count = "not_an_integer"
    "#,
        ".toml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct CountConfig {
        count: i32,
    }

    let result = CountConfig::load_file_with_env(temp_file.path());

    // Should fail string to integer conversion
    assert!(result.is_err());
}

/// Test type mismatch for object to primitive.
#[test]
fn test_object_to_primitive_mismatch() {
    let temp_file = common::create_temp_config(
        r#"
        value = { nested = "object" }
    "#,
        ".toml",
    );

    #[derive(Debug, Clone, confers::Config, serde::Deserialize)]
    #[config()]
    struct SimpleConfig {
        value: String,
    }

    let result = SimpleConfig::load_file_with_env(temp_file.path());

    // Should fail object to string conversion
    assert!(result.is_err());
}

// ========================================
// Error Recovery and Retry Tests
// ========================================

/// Test retryable error detection.
#[test]
fn test_retryable_error_detection() {
    use confers::ConfigError;

    // Timeout is retryable
    let err = ConfigError::Timeout { duration_ms: 5000 };
    assert!(err.is_retryable());

    // Validation is not retryable
    let err = ConfigError::ValidationFailed {
        field: "test".to_string(),
        rule: "required".to_string(),
        message: "missing".to_string(),
    };
    assert!(!err.is_retryable());

    // RemoteUnavailable with retryable=true
    let err = ConfigError::RemoteUnavailable {
        error_type: "timeout".to_string(),
        retryable: true,
    };
    assert!(err.is_retryable());

    // RemoteUnavailable with retryable=false
    let err = ConfigError::RemoteUnavailable {
        error_type: "auth".to_string(),
        retryable: false,
    };
    assert!(!err.is_retryable());
}

/// Test IO error retryability.
#[test]
fn test_io_error_retryability() {
    use confers::ConfigError;
    use std::io;

    // Connection refused is retryable
    let io_err = io::Error::new(io::ErrorKind::ConnectionRefused, "connection refused");
    let err = ConfigError::IoError(io_err);
    assert!(err.is_retryable());

    // NotFound is not retryable
    let io_err = io::Error::new(io::ErrorKind::NotFound, "file not found");
    let err = ConfigError::IoError(io_err);
    assert!(!err.is_retryable());

    // TimedOut is retryable
    let io_err = io::Error::new(io::ErrorKind::TimedOut, "timed out");
    let err = ConfigError::IoError(io_err);
    assert!(err.is_retryable());
}

/// Test watcher error retryability.
#[test]
fn test_watcher_error_retryability() {
    use confers::ConfigError;

    let recoverable_err = ConfigError::WatcherError {
        message: "temporary error".to_string(),
        path: None,
        recoverable: true,
    };
    assert!(recoverable_err.is_retryable());

    let non_recoverable_err = ConfigError::WatcherError {
        message: "fatal error".to_string(),
        path: None,
        recoverable: false,
    };
    assert!(!non_recoverable_err.is_retryable());
}

// ========================================
// Error Message Tests
// ========================================

/// Test error user message formatting.
#[test]
fn test_error_user_message_formatting() {
    use confers::ConfigError;

    // File not found
    let err = ConfigError::FileNotFound {
        filename: PathBuf::from("/path/to/config.toml"),
        source: None,
    };
    let msg = err.user_message();
    assert!(msg.contains("config.toml"));
    assert!(msg.contains("not found"));

    // Version mismatch
    let err = ConfigError::VersionMismatch {
        found: 1,
        expected: 2,
    };
    let msg = err.user_message();
    assert!(msg.contains("1"));
    assert!(msg.contains("2"));

    // Timeout
    let err = ConfigError::Timeout { duration_ms: 30000 };
    let msg = err.user_message();
    assert!(msg.contains("30000"));
}

/// Test error audit message.
#[test]
fn test_error_audit_message() {
    use confers::ConfigError;

    let err = ConfigError::FileNotFound {
        filename: PathBuf::from("test.toml"),
        source: None,
    };

    let audit_msg = err.audit_message();
    assert!(audit_msg.contains("error_code"));
    assert!(audit_msg.contains("FILE_NOT_FOUND"));
    assert!(audit_msg.contains("operation=config"));
}

/// Test error sanitized chain.
#[test]
fn test_error_sanitized_chain() {
    use confers::ConfigError;

    let err = ConfigError::DecryptionFailed {
        message: "key mismatch".to_string(),
    };

    let chain = err.sanitized_chain();
    assert!(!chain.is_empty());
}

/// Test MultiSourceError.
#[test]
fn test_multi_source_error() {
    use confers::error::MultiSourceError;
    use confers::ConfigError;

    let errors: Vec<(&str, ConfigError)> = vec![
        ("source_1", ConfigError::Timeout { duration_ms: 1000 }),
        (
            "source_2",
            ConfigError::RemoteUnavailable {
                error_type: "connection".to_string(),
                retryable: true,
            },
        ),
    ];

    let multi_err = MultiSourceError::new(5, errors);

    assert_eq!(multi_err.failed_count, 2);
    assert_eq!(multi_err.total_count, 5);

    let display = format!("{}", multi_err);
    assert!(display.contains("2/5"));
}

/// Test MultiSourceError with partial config.
#[test]
fn test_multi_source_error_partial_config() {
    use confers::error::MultiSourceError;
    use confers::ConfigError;

    let errors: Vec<(&str, ConfigError)> = vec![(
        "source_1",
        ConfigError::FileNotFound {
            filename: PathBuf::from("missing.toml"),
            source: None,
        },
    )];

    let multi_err =
        MultiSourceError::with_partial(3, errors, serde_json::json!({ "partial": true }));

    assert_eq!(multi_err.failed_count, 1);
    assert_eq!(multi_err.total_count, 3);
    assert!(multi_err.partial_config().is_some());
}

// ========================================
// BuildResult Tests
// ========================================

/// Test BuildResult creation.
#[test]
fn test_build_result_ok() {
    use confers::error::BuildResult;

    let result: BuildResult<i32> = BuildResult::ok(42);
    assert!(!result.degraded);
    assert!(!result.has_warnings());
    assert_eq!(result.config, 42);
}

/// Test BuildResult with warnings.
#[test]
fn test_build_result_with_warnings() {
    use confers::error::{BuildResult, SourceWarning, WarningCode};

    let warnings = vec![SourceWarning {
        message: "unused key".to_string(),
        source: Some("config.toml".to_string()),
        code: WarningCode::UnusedKey,
    }];

    let result: BuildResult<i32> = BuildResult::with_warnings(42, warnings);

    assert!(!result.degraded);
    assert!(result.has_warnings());
}

/// Test BuildResult degraded.
#[test]
fn test_build_result_degraded() {
    use confers::error::BuildResult;

    let result: BuildResult<i32> = BuildResult::degraded(42, "remote source unavailable");

    assert!(result.degraded);
    assert_eq!(
        result.degraded_reason,
        Some("remote source unavailable".to_string())
    );
}

/// Test BuildResult map.
#[test]
fn test_build_result_map() {
    use confers::error::BuildResult;

    let result: BuildResult<i32> = BuildResult::ok(21);
    let mapped = result.map(|v| v * 2);

    assert_eq!(mapped.config, 42);
}

/// Test WarningCode display.
#[test]
fn test_warning_code_display() {
    use confers::error::WarningCode;

    assert_eq!(
        format!("{}", WarningCode::OptionalSourceSkipped),
        "OPTIONAL_SOURCE_SKIPPED"
    );
    assert_eq!(format!("{}", WarningCode::DeprecatedKey), "DEPRECATED_KEY");
    assert_eq!(format!("{}", WarningCode::DefaultUsed), "DEFAULT_USED");
    assert_eq!(format!("{}", WarningCode::UnusedKey), "UNUSED_KEY");
}

// ========================================
// Additional Error Scenario Tests
// ========================================

/// Test file not found error with source.
#[test]
fn test_file_not_found_with_source() {
    use confers::ConfigError;
    use std::io;

    let io_err = io::Error::new(io::ErrorKind::NotFound, "file not found");
    let err = ConfigError::FileNotFound {
        filename: PathBuf::from("/path/to/file.toml"),
        source: Some(io_err),
    };

    let msg = err.user_message();
    assert!(msg.contains("file.toml"));

    let code = err.code();
    assert!(matches!(code, confers::error::ErrorCode::FileNotFound));
}

/// Test migration error.
#[test]
fn test_migration_error() {
    use confers::ConfigError;

    let err = ConfigError::MigrationFailed {
        from: 1,
        to: 2,
        reason: "invalid transformation".to_string(),
        source: None,
    };

    let msg = err.user_message();
    assert!(msg.contains("v1"));
    assert!(msg.contains("v2"));
    assert!(msg.contains("invalid transformation"));
}

/// Test module not found error.
#[test]
fn test_module_not_found_error() {
    use confers::ConfigError;

    let err = ConfigError::ModuleNotFound {
        group: "database".to_string(),
        module: "postgresql".to_string(),
    };

    let msg = err.user_message();
    assert!(msg.contains("postgresql"));
    assert!(msg.contains("database"));
}

/// Test size limit exceeded error.
#[test]
fn test_size_limit_exceeded_error() {
    use confers::ConfigError;

    let err = ConfigError::SizeLimitExceeded {
        actual: 10485760, // 10 MB
        limit: 1048576,   // 1 MB
    };

    let msg = err.user_message();
    assert!(msg.contains("10485760"));
    assert!(msg.contains("1048576"));
}

/// Test key rotation failed error.
#[test]
fn test_key_rotation_failed_error() {
    use confers::ConfigError;

    let err = ConfigError::KeyRotationFailed {
        from_version: "v1".to_string(),
        to_version: "v2".to_string(),
        reason: "invalid key format".to_string(),
    };

    let msg = err.user_message();
    assert!(msg.contains("v1"));
    assert!(msg.contains("v2"));
}

/// Test override blocked error.
#[test]
fn test_override_blocked_error() {
    use confers::ConfigError;

    let err = ConfigError::OverrideBlocked {
        key: "api_key".to_string(),
        reason: "protected field".to_string(),
        override_source: Some("cli".to_string()),
    };

    let msg = err.user_message();
    assert!(msg.contains("api_key"));
    assert!(msg.contains("cli"));
}

/// Test concurrency conflict error.
#[test]
fn test_concurrency_conflict_error() {
    use confers::ConfigError;

    let err = ConfigError::ConcurrencyConflict {
        key: "counter".to_string(),
        message: "value changed during read".to_string(),
        expected_type: Some("i32".to_string()),
    };

    assert!(err.is_retryable());
    let msg = err.user_message();
    assert!(msg.contains("counter"));
}