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
//! Constraint Validation Property Tests
//!
//! Property-based tests using proptest for comprehensive edge case coverage.
//! These tests verify validation robustness, boundary handling, and performance
//! across all constraint types (Pattern, Range, Length, OneOf, Required).

#![cfg(feature = "metadata")]

#[cfg(test)]
#[cfg(feature = "metadata")]
mod validation_property_tests {
    #![allow(unused_imports)]
    use proptest::prelude::*;
    use serde_json::json;
    use settings_loader::metadata::{Constraint, SettingMetadata, SettingType, Visibility};
    use std::time::Instant;

    // ============================================================================
    // PATTERN CONSTRAINT PROPERTY TESTS
    // ============================================================================

    proptest! {
        #[test]
        fn prop_pattern_lowercase_letters_valid(s in "[a-z]+") {
            let constraint = Constraint::Pattern("[a-z]+".to_string());
            prop_assert!(constraint.validate("test", &json!(s)).is_ok());
        }

        #[test]
        fn prop_pattern_digits_reject_letters(s in "[a-z]+") {
            let constraint = Constraint::Pattern("[0-9]+".to_string());
            prop_assert!(constraint.validate("test", &json!(s)).is_err());
        }

        #[test]
        fn prop_pattern_hex_validation(s in "[0-9a-f]+") {
            let constraint = Constraint::Pattern("^[0-9a-f]*$".to_string());
            prop_assert!(constraint.validate("test", &json!(s)).is_ok());
        }

        #[test]
        fn prop_pattern_email_like(user in "[a-z0-9]{3,10}", domain in "[a-z]{3,10}") {
            let pattern = format!("^{}@{}$", user, domain);
            let email = format!("{}@{}", user, domain);
            let constraint = Constraint::Pattern(pattern);
            prop_assert!(constraint.validate("email", &json!(email)).is_ok());
        }
    }

    // ============================================================================
    // RANGE CONSTRAINT PROPERTY TESTS
    // ============================================================================

    proptest! {
        #[test]
        fn prop_range_within_bounds_accepts(n in 1i64..=100i64) {
            let constraint = Constraint::Range { min: 1.0, max: 100.0 };
            prop_assert!(constraint.validate("test", &json!(n)).is_ok());
        }

        #[test]
        fn prop_range_below_min_rejects(n in i64::MIN..=0i64) {
            let constraint = Constraint::Range { min: 1.0, max: 100.0 };
            if (n as f64) < 1.0 {
                prop_assert!(constraint.validate("test", &json!(n)).is_err());
            }
        }

        #[test]
        fn prop_range_above_max_rejects(n in 101i64..i64::MAX) {
            let constraint = Constraint::Range { min: 1.0, max: 100.0 };
            prop_assert!(constraint.validate("test", &json!(n)).is_err());
        }

        #[test]
        fn prop_range_float_precision(n in 0.0f64..=1.0f64) {
            let constraint = Constraint::Range { min: 0.0, max: 1.0 };
            prop_assert!(constraint.validate("test", &json!(n)).is_ok());
        }

        #[test]
        fn prop_range_float_above_max(n in 1.0f64..100.0f64) {
            let constraint = Constraint::Range { min: 0.0, max: 1.0 };
            if n > 1.0 && n.is_finite() {
                prop_assert!(constraint.validate("test", &json!(n)).is_err());
            }
        }

        #[test]
        fn prop_range_exact_boundaries(
            min in -1000.0f64..=1000.0f64,
            offset in 1.0f64..=1000.0f64,
        ) {
            prop_assume!(min.is_finite() && offset.is_finite());
            let max = min + offset;
            let constraint = Constraint::Range { min, max };

            // Test exactly at min
            prop_assert!(constraint.validate("test", &json!(min)).is_ok());

            // Test exactly at max
            prop_assert!(constraint.validate("test", &json!(max)).is_ok());

            // Test just below min
            let just_below = min - 0.01;
            prop_assert!(constraint.validate("test", &json!(just_below)).is_err());

            // Test just above max
            let just_above = max + 0.01;
            prop_assert!(constraint.validate("test", &json!(just_above)).is_err());
        }

        #[test]
        fn prop_range_zero_within_bounds(min in -100.0f64..=0.0f64, max in 0.0f64..=100.0f64) {
            let constraint = Constraint::Range { min, max };
            prop_assert!(constraint.validate("test", &json!(0)).is_ok());
        }
    }

    // ============================================================================
    // LENGTH CONSTRAINT PROPERTY TESTS
    // ============================================================================

    proptest! {
        #[test]
        fn prop_length_valid_range(s in "[a-z]{1,10}") {
            let constraint = Constraint::Length { min: 1, max: 10 };
            prop_assert!(constraint.validate("test", &json!(s)).is_ok());
        }

        #[test]
        fn prop_length_too_long(s in "[a-z]{11,50}") {
            let constraint = Constraint::Length { min: 1, max: 10 };
            prop_assert!(constraint.validate("test", &json!(s)).is_err());
        }

        #[test]
        fn prop_length_at_boundaries(
            min in 1usize..=10usize,
            max in 1usize..=10usize,
        ) {
            prop_assume!(min <= max);
            let constraint = Constraint::Length { min, max };

            // Test exact min length
            let min_string = "a".repeat(min);
            prop_assert!(constraint.validate("test", &json!(min_string)).is_ok());

            // Test exact max length
            let max_string = "a".repeat(max);
            prop_assert!(constraint.validate("test", &json!(max_string)).is_ok());

            // Test one below min
            if min > 1 {
                let below_min = "a".repeat(min - 1);
                prop_assert!(constraint.validate("test", &json!(below_min)).is_err());
            }

            // Test one above max
            let above_max = "a".repeat(max + 1);
            prop_assert!(constraint.validate("test", &json!(above_max)).is_err());
        }

        #[test]
        fn prop_length_unicode_strings(s in "\\PC{1,10}") {
            let constraint = Constraint::Length { min: 1, max: 10 };
            // Should handle unicode correctly
            let result = constraint.validate("test", &json!(s));
            let _ = result; // Just ensure no panic
        }
    }

    // ============================================================================
    // ONEOF CONSTRAINT PROPERTY TESTS
    // ============================================================================

    proptest! {
        #[test]
        fn prop_oneof_valid_value(idx in 0usize..3usize) {
            let allowed = vec!["red".to_string(), "green".to_string(), "blue".to_string()];
            let value = allowed[idx].clone();
            let constraint = Constraint::OneOf(allowed);
            prop_assert!(constraint.validate("test", &json!(value)).is_ok());
        }

        #[test]
        fn prop_oneof_rejects_outside_set(s in "[a-z]{4,10}") {
            let constraint = Constraint::OneOf(vec![
                "red".to_string(),
                "green".to_string(),
                "blue".to_string(),
            ]);
            if !["red", "green", "blue"].contains(&s.as_str()) {
                prop_assert!(constraint.validate("test", &json!(s)).is_err());
            }
        }

        #[test]
        fn prop_oneof_case_sensitive(s in "[a-z]{3,10}") {
            let allowed = vec!["RED".to_string(), "GREEN".to_string()];
            let constraint = Constraint::OneOf(allowed);
            // Lowercase values should not match uppercase
            if s != "RED" && s != "GREEN" {
                prop_assert!(constraint.validate("test", &json!(s)).is_err());
            }
        }

        #[test]
        fn prop_oneof_with_many_options(
            options in prop::collection::vec("[a-z0-9]{2,5}", 5..20),
            idx in 0usize..100,
        ) {
            let constraint = Constraint::OneOf(options.clone());
            let test_idx = idx % options.len();
            let valid_value = &options[test_idx];
            prop_assert!(constraint.validate("test", &json!(valid_value.clone())).is_ok());
        }
    }

    // ============================================================================
    // TYPE VALIDATION BOUNDARY TESTS
    // ============================================================================

    proptest! {
        #[test]
        fn prop_integer_type_bounds(min in 0i64..100i64, max in 100i64..1000i64) {
            let setting_type = SettingType::Integer { min: Some(min), max: Some(max) };

            prop_assert!(setting_type.validate("test", &json!(min)).is_ok());
            prop_assert!(setting_type.validate("test", &json!(max)).is_ok());

            let mid = min + (max - min) / 2;
            prop_assert!(setting_type.validate("test", &json!(mid)).is_ok());

            prop_assert!(setting_type.validate("test", &json!(min - 1)).is_err());
            prop_assert!(setting_type.validate("test", &json!(max + 1)).is_err());
        }

        #[test]
        fn prop_float_type_boundary(min in 0.0f64..100.0f64, max in 100.0f64..1000.0f64) {
            prop_assume!(min.is_finite() && max.is_finite());
            let setting_type = SettingType::Float { min: Some(min), max: Some(max) };

            prop_assert!(setting_type.validate("test", &json!(min)).is_ok());
            prop_assert!(setting_type.validate("test", &json!(max)).is_ok());
        }

        #[test]
        fn prop_string_type_length_bounds(min in 1usize..=5usize, max in 5usize..=20usize) {
            let setting_type = SettingType::String {
                pattern: None,
                min_length: Some(min),
                max_length: Some(max),
            };

            let valid = "a".repeat(min);
            prop_assert!(setting_type.validate("test", &json!(valid)).is_ok());

            let too_short = "a".repeat(min.saturating_sub(1));
            if min > 0 {
                prop_assert!(setting_type.validate("test", &json!(too_short)).is_err());
            }

            let too_long = "a".repeat(max + 1);
            prop_assert!(setting_type.validate("test", &json!(too_long)).is_err());
        }
    }

    // ============================================================================
    // ERROR MESSAGE CONSISTENCY TESTS
    // ============================================================================

    proptest! {
        #[test]
        fn prop_pattern_error_contains_key(pattern in "[a-z]{3,10}") {
            let constraint = Constraint::Pattern(pattern.clone());
            let result = constraint.validate("test_key", &json!("123"));

            if result.is_err() {
                let error_msg = result.unwrap_err().to_string();
                prop_assert!(error_msg.contains("test_key"));
            }
        }

        #[test]
        fn prop_range_error_shows_bounds(min in 1f64..10f64, max in 10f64..100f64) {
            let constraint = Constraint::Range { min, max };
            let result = constraint.validate("test_key", &json!(1000));

            if result.is_err() {
                let error_msg = result.unwrap_err().to_string();
                prop_assert!(error_msg.contains("test_key"));
            }
        }

        #[test]
        fn prop_length_error_shows_actual_length(
            min in 1usize..=5usize,
            max in 5usize..=10usize,
        ) {
            let constraint = Constraint::Length { min, max };
            let too_short = "a".repeat(min.saturating_sub(1));
            let result = constraint.validate("test_key", &json!(too_short));

            if result.is_err() && min > 0 {
                let error_msg = result.unwrap_err().to_string();
                prop_assert!(error_msg.contains("test_key"));
            }
        }

        #[test]
        fn prop_oneof_error_shows_key(allowed_vals in prop::collection::vec("[a-z]+", 1..5)) {
            let allowed = allowed_vals.to_vec();
            let constraint = Constraint::OneOf(allowed);
            let result = constraint.validate("test_key", &json!("invalid_xyz"));

            if result.is_err() {
                let error_msg = result.unwrap_err().to_string();
                prop_assert!(error_msg.contains("test_key"));
            }
        }
    }

    // ============================================================================
    // PERFORMANCE TESTS
    // ============================================================================

    #[test]
    fn prop_validation_performance_pattern() {
        let constraint = Constraint::Pattern("[a-z0-9]+".to_string());
        let start = Instant::now();

        for i in 0..1000 {
            let _ = constraint.validate("test", &json!(format!("value{}", i)));
        }

        let elapsed = start.elapsed();
        let millis = elapsed.as_millis();
        // 1000 validations should complete in under 1000ms (avg ~1ms per)
        assert!(
            millis < 1000,
            "Pattern validation too slow: {:?}ms for 1000 ops (avg {}ms each)",
            millis,
            millis / 1000
        );
    }

    #[test]
    fn prop_validation_performance_range() {
        let constraint = Constraint::Range { min: 0.0, max: 1000.0 };
        let start = Instant::now();

        for i in 0..1000 {
            let _ = constraint.validate("test", &json!(i));
        }

        let elapsed = start.elapsed();
        let millis = elapsed.as_millis();
        assert!(millis < 1000, "Range validation too slow: {:?}ms for 1000 ops", millis);
    }

    #[test]
    fn prop_validation_performance_length() {
        let constraint = Constraint::Length { min: 1, max: 100 };
        let start = Instant::now();

        for i in 0..1000 {
            let _ = constraint.validate("test", &json!(format!("value_{}", i)));
        }

        let elapsed = start.elapsed();
        let millis = elapsed.as_millis();
        assert!(millis < 1000, "Length validation too slow: {:?}ms for 1000 ops", millis);
    }

    #[test]
    fn prop_validation_performance_oneof() {
        let allowed = ["red", "green", "blue", "yellow", "purple"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let constraint = Constraint::OneOf(allowed);
        let start = Instant::now();

        let colors = ["red", "green", "blue", "yellow", "purple"];
        for i in 0..1000 {
            let _ = constraint.validate("test", &json!(colors[i % 5]));
        }

        let elapsed = start.elapsed();
        let millis = elapsed.as_millis();
        assert!(millis < 1000, "OneOf validation too slow: {:?}ms for 1000 ops", millis);
    }

    // ============================================================================
    // EDGE CASE TESTS
    // ============================================================================

    proptest! {
        #[test]
        fn prop_empty_string_length_constraint(max in 1usize..=100usize) {
            let constraint = Constraint::Length { min: 0, max };
            prop_assert!(constraint.validate("test", &json!("")).is_ok());
        }

        #[test]
        fn prop_zero_value_range_constraint(_dummy in 0u32..=0u32) {
            let constraint = Constraint::Range { min: -100.0, max: 100.0 };
            prop_assert!(constraint.validate("test", &json!(0)).is_ok());
        }

        #[test]
        fn prop_pattern_empty_string(pattern in "[a-z]*") {
            let constraint = Constraint::Pattern(pattern);
            let result = constraint.validate("test", &json!(""));
            // Empty string might or might not match depending on pattern
            let _ = result;
        }
    }

    #[test]
    fn prop_null_value_required_constraint() {
        let constraint = Constraint::Required;
        assert!(constraint.validate("test", &json!(null)).is_err());
    }

    // ============================================================================
    // COMPLEX VALIDATION SCENARIOS
    // ============================================================================

    proptest! {
        #[test]
        fn prop_metadata_multiple_constraints(
            pattern in "[a-z]{3,10}",
            min_len in 1usize..=5usize,
            max_len in 5usize..=20usize,
        ) {
            let metadata = SettingMetadata {
                key: "username".to_string(),
                label: "Username".to_string(),
                description: "User username".to_string(),
                setting_type: SettingType::String {
                    pattern: Some(pattern),
                    min_length: Some(min_len),
                    max_length: Some(max_len),
                },
                default: None,
                constraints: vec![
                    Constraint::Required,
                    Constraint::Length {
                        min: min_len,
                        max: max_len,
                    },
                ],
                visibility: Visibility::Public,
                group: None,
            };

            // Test with valid value
            let valid = "hello";
            if valid.len() >= min_len && valid.len() <= max_len {
                let result = metadata.validate(&json!(valid));
                // At minimum shouldn't panic
                let _ = result;
            }
        }

        #[test]
        fn prop_secret_visibility_validation(
            value in "[a-zA-Z0-9]{8,32}",
        ) {
            let metadata = SettingMetadata {
                key: "api_secret".to_string(),
                label: "API Secret".to_string(),
                description: "Secret API key".to_string(),
                setting_type: SettingType::String {
                    pattern: None,
                    min_length: Some(8),
                    max_length: None,
                },
                default: None,
                constraints: vec![Constraint::Required],
                visibility: Visibility::Secret,
                group: None,
            };

            let result = metadata.validate(&json!(value));
            // Should not panic and result should be valid for good values
            let _ = result;
        }
    }

    // ============================================================================
    // CONSTRAINT HINT MESSAGE TESTS
    // ============================================================================

    #[test]
    fn test_pattern_error_includes_hint() {
        use settings_loader::validation::ValidationError;

        let error = ValidationError::InvalidPattern {
            key: "email".to_string(),
            pattern: "[a-z0-9]+@[a-z0-9]+\\.[a-z]{2,}".to_string(),
            value: "invalid".to_string(),
        };

        let msg = error.to_string();
        // Should include the pattern hint
        assert!(msg.contains("expected:"), "Error should include 'expected:' hint");
        assert!(
            msg.contains("pattern matching"),
            "Error should mention pattern constraint"
        );
    }

    #[test]
    fn test_range_error_includes_hint() {
        use settings_loader::validation::ValidationError;

        let error = ValidationError::OutOfRange {
            key: "port".to_string(),
            min: 1024.0,
            max: 65535.0,
            value: 70000.0,
        };

        let msg = error.to_string();
        // Should include the range hint
        assert!(msg.contains("expected:"), "Error should include 'expected:' hint");
        assert!(msg.contains("between"), "Error should mention 'between' in hint");
        assert!(msg.contains("1024"), "Error should show min bound");
        assert!(msg.contains("65535"), "Error should show max bound");
    }

    #[test]
    fn test_oneof_error_includes_hint() {
        use settings_loader::validation::ValidationError;

        let error = ValidationError::NotOneOf {
            key: "env".to_string(),
            expected: vec!["dev".to_string(), "staging".to_string(), "prod".to_string()],
            actual: "invalid".to_string(),
        };

        let msg = error.to_string();
        // Should include the allowed values hint
        assert!(msg.contains("expected:"), "Error should include 'expected:' hint");
        assert!(msg.contains("one of"), "Error should mention 'one of' in hint");
        assert!(msg.contains("dev"), "Error should list allowed values");
    }

    #[test]
    fn test_constraint_hints_actionable() {
        use settings_loader::validation::ValidationError;

        // Pattern error should be actionable
        let pattern_error = ValidationError::InvalidPattern {
            key: "username".to_string(),
            pattern: "^[a-zA-Z0-9_]{3,16}$".to_string(),
            value: "ab".to_string(),
        };
        let pattern_msg = pattern_error.to_string();
        assert!(
            pattern_msg.contains("expected:") && pattern_msg.contains("pattern"),
            "Pattern error should provide actionable hint"
        );

        // Range error should be actionable
        let range_error = ValidationError::OutOfRange {
            key: "connections".to_string(),
            min: 1.0,
            max: 1000.0,
            value: 5000.0,
        };
        let range_msg = range_error.to_string();
        assert!(
            range_msg.contains("expected:") && range_msg.contains("between"),
            "Range error should provide actionable hint"
        );
    }
}