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
//! Environment Variable Customization Test Suite
//!
//! Tests validate:
//! - Default environment variable conventions (prefix "APP", separator "__")
//! - Custom environment variable naming conventions
//! - Integration with LayerBuilder
//! - Backward compatibility with layering

use serde::{Deserialize, Serialize};
use serial_test::serial;
use settings_loader::LoadingOptions;
use std::fs;

// ============================================================================
// Test Configuration Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
struct TestConfig {
    #[serde(default)]
    app_name: String,
    #[serde(default)]
    port: u16,
    #[serde(default)]
    debug: bool,
    #[serde(default)]
    database: DatabaseConfig,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
struct DatabaseConfig {
    #[serde(default)]
    host: String,
    #[serde(default)]
    port: u16,
    #[serde(default)]
    user: String,
}

// ============================================================================
// LoadingOptions Implementations for Testing
// ============================================================================

/// Default LoadingOptions - uses APP prefix and __ separator
#[derive(Debug, Clone, Default)]
struct DefaultOptions;

impl LoadingOptions for DefaultOptions {
    type Error = settings_loader::SettingsError;

    fn config_path(&self) -> Option<std::path::PathBuf> {
        None
    }

    fn secrets_path(&self) -> Option<std::path::PathBuf> {
        None
    }

    fn implicit_search_paths(&self) -> Vec<std::path::PathBuf> {
        Vec::new()
    }
}

/// Custom Options - uses TURTLE prefix and __ separator
#[derive(Debug, Clone, Default)]
struct TurtleOptions;

impl LoadingOptions for TurtleOptions {
    type Error = settings_loader::SettingsError;

    fn config_path(&self) -> Option<std::path::PathBuf> {
        None
    }

    fn secrets_path(&self) -> Option<std::path::PathBuf> {
        None
    }

    fn implicit_search_paths(&self) -> Vec<std::path::PathBuf> {
        Vec::new()
    }

    /// Override prefix for Turtle naming convention
    fn env_prefix() -> &'static str {
        "TURTLE"
    }
}

/// Custom Options - uses CUSTOM prefix and ___ separator (triple underscore)
#[derive(Debug, Clone, Default)]
struct CustomSeparatorOptions;

impl LoadingOptions for CustomSeparatorOptions {
    type Error = settings_loader::SettingsError;

    fn config_path(&self) -> Option<std::path::PathBuf> {
        None
    }

    fn secrets_path(&self) -> Option<std::path::PathBuf> {
        None
    }

    fn implicit_search_paths(&self) -> Vec<std::path::PathBuf> {
        Vec::new()
    }

    /// Override separator to triple underscore
    fn env_separator() -> &'static str {
        "___"
    }
}

/// Custom Options - both prefix and separator overridden
#[derive(Debug, Clone, Default)]
struct FullyCustomOptions;

impl LoadingOptions for FullyCustomOptions {
    type Error = settings_loader::SettingsError;

    fn config_path(&self) -> Option<std::path::PathBuf> {
        None
    }

    fn secrets_path(&self) -> Option<std::path::PathBuf> {
        None
    }

    fn implicit_search_paths(&self) -> Vec<std::path::PathBuf> {
        Vec::new()
    }

    fn env_prefix() -> &'static str {
        "CUSTOM"
    }

    fn env_separator() -> &'static str {
        "_"
    }
}

// ============================================================================
// Test 1: Default Environment Variable Prefix
// ============================================================================

/// Test that default env prefix is "APP"
#[test]
fn test_default_env_prefix() {
    let prefix = DefaultOptions::env_prefix();
    assert_eq!(prefix, "APP", "Default prefix should be 'APP'");
}

// ============================================================================
// Test 2: Default Environment Variable Separator
// ============================================================================

/// Test that default env separator is "__"
#[test]
fn test_default_env_separator() {
    let separator = DefaultOptions::env_separator();
    assert_eq!(separator, "__", "Default separator should be '__' (double underscore)");
}

// ============================================================================
// Test 3: Custom Environment Variable Prefix
// ============================================================================

/// Test that custom prefix can be specified via trait override
#[test]
fn test_custom_env_prefix() {
    let prefix = TurtleOptions::env_prefix();
    assert_eq!(prefix, "TURTLE", "TurtleOptions should override prefix to 'TURTLE'");
}

// ============================================================================
// Test 4: Custom Environment Variable Separator
// ============================================================================

/// Test that custom separator can be specified via trait override
#[test]
fn test_custom_env_separator() {
    let separator = CustomSeparatorOptions::env_separator();
    assert_eq!(
        separator, "___",
        "CustomSeparatorOptions should override separator to '___'"
    );
}

// ============================================================================
// Test 5: Custom Prefix AND Separator
// ============================================================================

/// Test that both prefix and separator can be customized simultaneously
#[test]
fn test_custom_prefix_and_separator() {
    assert_eq!(FullyCustomOptions::env_prefix(), "CUSTOM", "Prefix should be 'CUSTOM'");
    assert_eq!(
        FullyCustomOptions::env_separator(),
        "_",
        "Separator should be '_' (single underscore)"
    );
}

// ============================================================================
// Test 6: LayerBuilder Respects Custom Prefix
// ============================================================================

/// Test that LayerBuilder.with_env_vars() can use custom prefix from LoadingOptions
#[test]
#[serial]
fn test_env_vars_with_custom_prefix() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join("config.yaml");
    fs::write(
        &config_path,
        "app_name: BaseApp\nport: 8000\ndebug: false\ndatabase:\n  host: localhost\n  port: 5432\n  user: default",
    )
    .unwrap();

    // Set environment variables with custom prefix and double underscore separator
    // TURTLE__PORT maps to port, TURTLE__DATABASE__HOST maps to database.host
    std::env::set_var("TURTLE__PORT", "9000");
    std::env::set_var("TURTLE__DATABASE__HOST", "prod.example.com");

    // Use custom prefix in LayerBuilder with __ separator
    let builder = settings_loader::LayerBuilder::new()
        .with_path(&config_path)
        .with_env_vars("TURTLE", "__");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    // Verify custom prefix values were loaded
    assert_eq!(result.port, 9000, "Port from TURTLE__PORT should override base config");
    assert_eq!(
        result.database.host, "prod.example.com",
        "Database host from TURTLE__DATABASE__HOST should override"
    );

    std::env::remove_var("TURTLE__PORT");
    std::env::remove_var("TURTLE__DATABASE__HOST");
}

// ============================================================================
// Test 7: LayerBuilder Respects Custom Separator
// ============================================================================

/// Test that LayerBuilder.with_env_vars() can use custom separator from LoadingOptions
#[test]
#[serial]
fn test_env_vars_with_custom_separator() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join("config.yaml");
    fs::write(
        &config_path,
        "app_name: SeparatorApp\nport: 8000\ndebug: false\ndatabase:\n  host: localhost\n  port: 5432\n  user: default",
    )
    .unwrap();

    // Set environment variables with custom separator (single underscore)
    // CUSTOM_PORT maps to port, CUSTOM_DATABASE_HOST maps to database.host (with single underscore)
    std::env::set_var("CUSTOM_PORT", "7000");
    std::env::set_var("CUSTOM_DATABASE_HOST", "sep.example.com");

    // Use custom separator in LayerBuilder (single underscore)
    let builder = settings_loader::LayerBuilder::new()
        .with_path(&config_path)
        .with_env_vars("CUSTOM", "_");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    // Verify custom separator values were loaded
    assert_eq!(
        result.port, 7000,
        "Port from CUSTOM_PORT should override with single separator"
    );
    assert_eq!(
        result.database.host, "sep.example.com",
        "Database host from CUSTOM_DATABASE_HOST should work with custom separator"
    );

    std::env::remove_var("CUSTOM_PORT");
    std::env::remove_var("CUSTOM_DATABASE_HOST");
}

// ============================================================================
// Test 8: Real-World Turtle Naming Convention
// ============================================================================

/// Test real-world Turtle application naming convention (TURTLE__LLM__*)
#[test]
fn test_turtle_style_naming_convention() {
    let prefix = TurtleOptions::env_prefix();
    let separator = TurtleOptions::env_separator();

    // Turtle would use TURTLE__LLM__MODEL, TURTLE__LLM__PROVIDER, etc.
    // Verify the methods return correct values for this convention
    assert_eq!(prefix, "TURTLE", "Turtle prefix incorrect");
    assert_eq!(separator, "__", "Turtle separator incorrect");

    // Example env vars that would work:
    // TURTLE__LLM__MODEL=ollama
    // TURTLE__LLM__PROVIDER=local
    // TURTLE__LLM__OLLAMA__BASE_URL=http://localhost:11434
}

// ============================================================================
// Test 9: Environment Variables Load with Custom Convention
// ============================================================================

/// Test full cycle: load config with custom env var naming convention
#[test]
#[serial]
fn test_env_var_loading_with_custom_convention() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join("config.yaml");
    fs::write(
        &config_path,
        "app_name: TurtleApp\nport: 8000\ndebug: false\ndatabase:\n  host: localhost\n  port: 5432\n  user: turtle",
    )
    .unwrap();

    // Set environment variables using Turtle convention with __ separator
    // TURTLE__APP_NAME → app_name, TURTLE__DATABASE__HOST → database.host, etc.
    std::env::set_var("TURTLE__APP_NAME", "TurtleCustom");
    std::env::set_var("TURTLE__PORT", "9999");
    std::env::set_var("TURTLE__DEBUG", "true");
    std::env::set_var("TURTLE__DATABASE__HOST", "turtle.db.local");
    std::env::set_var("TURTLE__DATABASE__USER", "turtle_admin");

    let builder = settings_loader::LayerBuilder::new()
        .with_path(&config_path)
        .with_env_vars("TURTLE", "__");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    // Verify Turtle convention worked
    assert_eq!(result.app_name, "TurtleCustom");
    assert_eq!(result.port, 9999);
    assert!(result.debug);
    assert_eq!(result.database.host, "turtle.db.local");
    assert_eq!(result.database.user, "turtle_admin");

    std::env::remove_var("TURTLE__APP_NAME");
    std::env::remove_var("TURTLE__PORT");
    std::env::remove_var("TURTLE__DEBUG");
    std::env::remove_var("TURTLE__DATABASE__HOST");
    std::env::remove_var("TURTLE__DATABASE__USER");
}

// ============================================================================
// Test 10: Backward Compatibility - Default Prefix Still Works
// ============================================================================

/// Test that existing code using default "APP" prefix continues to work
#[test]
#[serial]
fn test_backward_compatibility_default_prefix() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join("config.yaml");
    fs::write(
        &config_path,
        "app_name: LegacyApp\nport: 8000\ndebug: false\ndatabase:\n  host: localhost\n  port: 5432\n  user: legacy",
    )
    .unwrap();

    // Set environment variables using original APP convention with __ separator
    // APP__PORT → port, APP__DATABASE__HOST → database.host
    std::env::set_var("APP__PORT", "8888");
    std::env::set_var("APP__DATABASE__HOST", "legacy.db.local");

    // Use default prefix (should still be "APP")
    let builder = settings_loader::LayerBuilder::new()
        .with_path(&config_path)
        .with_env_vars("APP", "__");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.port, 8888);
    assert_eq!(result.database.host, "legacy.db.local");

    std::env::remove_var("APP__PORT");
    std::env::remove_var("APP__DATABASE__HOST");
}

// ============================================================================
// Test 11: Backward Compatibility - Default Separator Still Works
// ============================================================================

/// Test that existing code using default "__" separator continues to work
#[test]
#[serial]
fn test_backward_compatibility_default_separator() {
    assert_eq!(
        DefaultOptions::env_separator(),
        "__",
        "Default separator must remain '__' for backward compatibility"
    );

    // Verify the separator works with nested keys
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join("config.yaml");
    fs::write(
        &config_path,
        "app_name: LegacyApp\ndatabase:\n  host: localhost\n  port: 5432\n  user: default",
    )
    .unwrap();

    // With __ separator: APP__DATABASE__PORT maps to database.port
    std::env::set_var("APP__DATABASE__PORT", "3306");

    let builder = settings_loader::LayerBuilder::new()
        .with_path(&config_path)
        .with_env_vars("APP", "__");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.database.port, 3306);

    std::env::remove_var("APP__DATABASE__PORT");
}

// ============================================================================
// Test 12: Multiple Custom Implementations Can Coexist
// ============================================================================

/// Test that different LoadingOptions implementations can have different conventions
#[test]
fn test_multiple_custom_implementations() {
    // TurtleOptions uses TURTLE prefix
    let turtle_prefix = TurtleOptions::env_prefix();
    assert_eq!(turtle_prefix, "TURTLE");

    // FullyCustomOptions uses CUSTOM prefix
    let custom_prefix = FullyCustomOptions::env_prefix();
    assert_eq!(custom_prefix, "CUSTOM");

    // Different separators too
    let default_sep = DefaultOptions::env_separator();
    let custom_sep = FullyCustomOptions::env_separator();

    assert_eq!(default_sep, "__");
    assert_eq!(custom_sep, "_");

    // Multiple implementations can coexist in same application
    // e.g., one LoadingOptions for Turtle app, another for default app
}