diode-base 0.3.0

Basic services for the diode library
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
use diode::Extract;
use diode_base::{Config, ConfigSection, config_section};
use serde::{Deserialize, Serialize};
use std::fs;
use tempfile::NamedTempFile;
use tokio;

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct TestConfig {
    name: String,
    port: u16,
    enabled: bool,
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct DatabaseConfig {
    host: String,
    port: u16,
    ssl: bool,
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct ServerConfig {
    bind_addr: String,
    workers: u32,
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct CacheConfig {
    enabled: bool,
}

#[config_section("test_section")]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct TestSectionConfig {
    name: String,
    value: i32,
}

#[config_section("database")]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct DatabaseSectionConfig {
    host: String,
    port: u16,
    ssl: bool,
}

#[tokio::test]
async fn test_config_new() {
    let config = Config::new();
    assert!(config.is_empty());
}

#[tokio::test]
async fn test_config_default() {
    let config = Config::default();
    assert!(config.is_empty());
}

#[tokio::test]
async fn test_config_set_and_get() {
    let mut config = Config::new();

    let test_config = TestConfig {
        name: "test_app".to_string(),
        port: 8080,
        enabled: true,
    };

    // Test setting a value
    config.set("app", &test_config).unwrap();

    // Test getting the value back
    let retrieved: TestConfig = config.get("app").unwrap();
    assert_eq!(retrieved, test_config);
}

#[tokio::test]
async fn test_config_get_nonexistent() {
    let config = Config::new();

    // Getting non-existent key should return null/default value
    let result: Option<String> = config.get("nonexistent").unwrap();
    assert_eq!(result, None);
}

#[tokio::test]
async fn test_config_with() {
    let test_config = TestConfig {
        name: "test_app".to_string(),
        port: 8080,
        enabled: true,
    };

    let config = Config::new().with("app", &test_config);

    let retrieved: TestConfig = config.get("app").unwrap();
    assert_eq!(retrieved, test_config);
}

#[tokio::test]
async fn test_config_parse_from_string() {
    let json_str = r#"
    {
        "app": {
            "name": "test_app",
            "port": 8080,
            "enabled": true
        }
    }
    "#;

    let config = Config::parse(json_str).unwrap();
    let app_config: TestConfig = config.get("app").unwrap();

    assert_eq!(app_config.name, "test_app");
    assert_eq!(app_config.port, 8080);
    assert_eq!(app_config.enabled, true);
}

#[tokio::test]
async fn test_config_parse_invalid_json() {
    let invalid_json = r#"{ "invalid": json }"#;

    let result = Config::parse(invalid_json);
    assert!(result.is_err());
}

#[tokio::test]
async fn test_config_parse_file() {
    let json_content = r#"
    {
        "server": {
            "bind_addr": "127.0.0.1:8080",
            "workers": 4
        },
        "database": {
            "host": "localhost",
            "port": 5432,
            "ssl": true
        }
    }
    "#;

    // Create a temporary file
    let temp_file = NamedTempFile::new().unwrap();
    fs::write(temp_file.path(), json_content).unwrap();

    let config = Config::parse_file(temp_file.path()).await.unwrap();
    let server_config: ServerConfig = config.get("server").unwrap();
    let database_config: DatabaseConfig = config.get("database").unwrap();

    assert_eq!(server_config.bind_addr, "127.0.0.1:8080");
    assert_eq!(server_config.workers, 4);
    assert_eq!(database_config.host, "localhost");
    assert_eq!(database_config.port, 5432);
    assert_eq!(database_config.ssl, true);
}

#[tokio::test]
async fn test_config_parse_file_not_found() {
    let result = Config::parse_file("nonexistent_file.json").await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_config_merge_objects() {
    let mut base_config = Config::parse(
        r#"
    {
        "server": {
            "bind_addr": "localhost:8080",
            "workers": 1
        },
        "database": {
            "host": "localhost"
        }
    }
    "#,
    )
    .unwrap();

    let override_config = Config::parse(
        r#"
    {
        "server": {
            "bind_addr": "0.0.0.0:8080",
            "workers": 4
        },
        "database": {
            "port": 5432,
            "ssl": true
        },
        "cache": {
            "enabled": true
        }
    }
    "#,
    )
    .unwrap();

    base_config.merge_from(override_config).unwrap();

    // Check merged values by getting the typed objects
    let server_config: ServerConfig = base_config.get("server").unwrap();
    let database_config: DatabaseConfig = base_config.get("database").unwrap();
    let cache_config: CacheConfig = base_config.get("cache").unwrap();

    assert_eq!(server_config.bind_addr, "0.0.0.0:8080");
    assert_eq!(server_config.workers, 4);

    assert_eq!(database_config.host, "localhost");
    assert_eq!(database_config.port, 5432);
    assert_eq!(database_config.ssl, true);

    assert_eq!(cache_config.enabled, true);
}

#[tokio::test]
async fn test_config_merge_arrays() {
    let mut base_config = Config::parse(
        r#"
    {
        "tags": ["production", "web"]
    }
    "#,
    )
    .unwrap();

    let override_config = Config::parse(
        r#"
    {
        "tags": ["monitoring", "logging"]
    }
    "#,
    )
    .unwrap();

    base_config.merge_from(override_config).unwrap();

    let tags: Vec<String> = base_config.get("tags").unwrap();
    assert_eq!(tags, vec!["production", "web", "monitoring", "logging"]);
}

#[tokio::test]
async fn test_config_merge_replace_primitives() {
    let mut base_config = Config::parse(
        r#"
    {
        "port": 8080,
        "enabled": false,
        "name": "old_name"
    }
    "#,
    )
    .unwrap();

    let override_config = Config::parse(
        r#"
    {
        "port": 9090,
        "enabled": true,
        "name": "new_name"
    }
    "#,
    )
    .unwrap();

    base_config.merge_from(override_config).unwrap();

    let port: u16 = base_config.get("port").unwrap();
    let enabled: bool = base_config.get("enabled").unwrap();
    let name: String = base_config.get("name").unwrap();

    assert_eq!(port, 9090);
    assert_eq!(enabled, true);
    assert_eq!(name, "new_name");
}

#[tokio::test]
async fn test_config_set_different_types() {
    let mut config = Config::new();

    // Test setting different types
    config.set("string_value", "hello").unwrap();
    config.set("number_value", 42i32).unwrap();
    config.set("bool_value", true).unwrap();
    config.set("array_value", vec![1, 2, 3]).unwrap();

    // Test getting them back
    let string_val: String = config.get("string_value").unwrap();
    let number_val: i32 = config.get("number_value").unwrap();
    let bool_val: bool = config.get("bool_value").unwrap();
    let array_val: Vec<i32> = config.get("array_value").unwrap();

    assert_eq!(string_val, "hello");
    assert_eq!(number_val, 42);
    assert_eq!(bool_val, true);
    assert_eq!(array_val, vec![1, 2, 3]);
}

#[tokio::test]
async fn test_config_type_conversion_error() {
    let mut config = Config::new();
    config.set("string_value", "not_a_number").unwrap();

    // Trying to get string as number should fail
    let result: Result<i32, _> = config.get("string_value");
    assert!(result.is_err());
}

#[tokio::test]
async fn test_config_serialization() {
    let mut config = Config::new();
    config.set("app_name", "test_app").unwrap();
    config.set("version", "1.0.0").unwrap();
    config.set("port", 8080u16).unwrap();

    // Test serialization
    let serialized = serde_json::to_string(&config).unwrap();

    // Test deserialization
    let deserialized: Config = serde_json::from_str(&serialized).unwrap();

    let app_name: String = deserialized.get("app_name").unwrap();
    let version: String = deserialized.get("version").unwrap();
    let port: u16 = deserialized.get("port").unwrap();

    assert_eq!(app_name, "test_app");
    assert_eq!(version, "1.0.0");
    assert_eq!(port, 8080);
}

#[tokio::test]
async fn test_config_empty_merge() {
    let mut config = Config::parse(r#"{"key": "value"}"#).unwrap();
    let empty_config = Config::new();

    config.merge_from(empty_config).unwrap();

    let value: String = config.get("key").unwrap();
    assert_eq!(value, "value");
}

#[tokio::test]
async fn test_config_complex_nested_structure() {
    let complex_json = r#"
    {
        "application": {
            "name": "my-app",
            "version": "1.0.0",
            "features": {
                "auth": {
                    "enabled": true,
                    "providers": ["oauth", "saml"]
                },
                "logging": {
                    "level": "info",
                    "outputs": ["console", "file"]
                }
            }
        },
        "infrastructure": {
            "database": {
                "primary": {
                    "host": "db1.example.com",
                    "port": 5432
                },
                "replica": {
                    "host": "db2.example.com",
                    "port": 5432
                }
            }
        }
    }
    "#;

    let config = Config::parse(complex_json).unwrap();

    // Test nested access by getting objects and then accessing their fields
    let application: serde_json::Value = config.get("application").unwrap();
    let infrastructure: serde_json::Value = config.get("infrastructure").unwrap();

    assert_eq!(application["name"].as_str().unwrap(), "my-app");
    assert_eq!(
        application["features"]["auth"]["enabled"]
            .as_bool()
            .unwrap(),
        true
    );
    let providers: Vec<&str> = application["features"]["auth"]["providers"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert_eq!(providers, vec!["oauth", "saml"]);
    assert_eq!(
        infrastructure["database"]["primary"]["host"]
            .as_str()
            .unwrap(),
        "db1.example.com"
    );
}

#[tokio::test]
async fn test_config_section_macro() {
    // Test that the macro correctly generates the key() method
    assert_eq!(TestSectionConfig::key(), "test_section");
    assert_eq!(DatabaseSectionConfig::key(), "database");

    // Test that the macro works with actual config
    let config = Config::parse(
        r#"
    {
        "test_section": {
            "name": "test_name",
            "value": 42
        },
        "database": {
            "host": "localhost",
            "port": 5432,
            "ssl": true
        }
    }
    "#,
    )
    .unwrap();

    // Test getting config sections using the generated key
    let test_section: TestSectionConfig = config.get(TestSectionConfig::key()).unwrap();
    let database_section: DatabaseSectionConfig = config.get(DatabaseSectionConfig::key()).unwrap();

    assert_eq!(test_section.name, "test_name");
    assert_eq!(test_section.value, 42);

    assert_eq!(database_section.host, "localhost");
    assert_eq!(database_section.port, 5432);
    assert_eq!(database_section.ssl, true);
}

#[tokio::test]
async fn test_config_section_macro_with_injection() {
    use diode::App;

    // Create config with test data
    let config = Config::parse(
        r#"
    {
        "test_section": {
            "name": "injected_name",
            "value": 123
        },
        "database": {
            "host": "injected_host",
            "port": 3306,
            "ssl": false
        }
    }
    "#,
    )
    .unwrap();

    // Create app with config
    let mut app_builder = App::builder();
    app_builder.add_component(config);

    // Test extraction using dependency injection
    let test_section: TestSectionConfig = diode_base::Config::extract(&app_builder).unwrap();
    let database_section: DatabaseSectionConfig =
        diode_base::Config::extract(&app_builder).unwrap();

    // Verify extracted data
    assert_eq!(test_section.name, "injected_name");
    assert_eq!(test_section.value, 123);

    assert_eq!(database_section.host, "injected_host");
    assert_eq!(database_section.port, 3306);
    assert_eq!(database_section.ssl, false);
}