rlg 0.0.8

A Rust library that implements application-level logging with a simple, readable output format. Features include log rotation, network logging, and support for multiple structured formats like JSON, CEF, and more.
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
#![cfg(not(miri))]
// Copyright © 2024-2026 RustLogs (RLG). All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

//! Tests for the configuration module of RustLogs (RLG).
//!
//! This module contains comprehensive tests for the `Config` struct and related
//! functionality, including parsing, validation, environment variable handling,
//! and various configuration operations.

#[cfg(test)]
mod tests {
    use rlg::{
        config::{
            Config, ConfigError, LogRotation, LoggingDestination,
        },
        log_level::LogLevel,
    };
    use serde::Deserialize;
    use std::{
        collections::HashMap, env, num::NonZeroU64, path::PathBuf,
        str::FromStr,
    };
    use tempfile::tempdir;
    #[cfg(feature = "tokio")]
    use tokio::{fs, io::AsyncWriteExt};

    /// Tests parsing different variants of the LogLevel enum from strings.
    #[test]
    fn test_log_level_from_str_basic() {
        assert_eq!(LogLevel::from_str("INFO").unwrap(), LogLevel::INFO);
        assert_eq!(
            LogLevel::from_str("debug").unwrap(),
            LogLevel::DEBUG
        );
        assert_eq!(LogLevel::from_str("NONE").unwrap(), LogLevel::NONE);
        assert_eq!(LogLevel::from_str("warn").unwrap(), LogLevel::WARN);
        assert_eq!(
            LogLevel::from_str("ERROR").unwrap(),
            LogLevel::ERROR
        );
        assert!(LogLevel::from_str("INVALID").is_err());
    }

    /// Tests displaying the log file path from the Config struct.
    #[test]
    fn test_config_log_file_path_display() {
        let config = Config {
            version: "1.0".to_string(),
            profile: "test".to_string(),
            log_file_path: PathBuf::from("RLG.log"),
            log_level: LogLevel::INFO,
            log_rotation: None,
            log_format: "%level - %message".to_string(),
            logging_destinations: vec![],
            env_vars: HashMap::new(),
        };

        assert_eq!(
            config.log_file_path.display().to_string(),
            "RLG.log",
            "Log file path should be 'RLG.log'"
        );
        assert!(
            config.log_file_path.is_relative(),
            "The log file path should be a relative path"
        );
        assert_eq!(
            config.log_file_path.to_str().unwrap(),
            "RLG.log",
            "The string representation of the path should be 'RLG.log'"
        );
    }

    /// Tests loading configuration with invalid values for LOG_LEVEL and LOG_ROTATION.
    #[cfg(feature = "tokio")]
    #[tokio::test]
    #[allow(unsafe_code)]
    async fn test_config_load_with_invalid_values() {
        let temp_dir =
            tempdir().expect("Failed to create temp directory");
        let log_file_path = temp_dir.path().join("RLG.log");
        let mut log_file = fs::File::create(&log_file_path)
            .await
            .expect("Failed to create log file");
        log_file
            .write_all(b"This is a test log file")
            .await
            .expect("Failed to write to log file");

        let config_content = r#"
        version = "1.0"
        log_file_path = "RLG.log"
        log_format = "%level - %message"
    "#;

        let config_file_path = temp_dir.path().join("config.toml");
        fs::write(&config_file_path, config_content)
            .await
            .expect("Failed to write config file");

        // SAFETY: Test-only; no other threads depend on these env vars.
        unsafe { env::set_var("LOG_LEVEL", "INVALID_LOG_LEVEL") };
        unsafe { env::set_var("LOG_ROTATION", "INVALID_LOG_ROTATION") };

        let config_result =
            Config::load_async(Some(&config_file_path)).await;
        assert!(config_result.is_ok(), "Config load should not fail");

        let log_level_env =
            env::var("LOG_LEVEL").expect("LOG_LEVEL not set");
        let log_rotation_env =
            env::var("LOG_ROTATION").expect("LOG_ROTATION not set");

        assert!(
            log_level_env.parse::<LogLevel>().is_err(),
            "Expected LOG_LEVEL to be invalid"
        );
        assert!(
            log_rotation_env.parse::<LogRotation>().is_err(),
            "Expected LOG_ROTATION to be invalid"
        );

        // SAFETY: Test-only cleanup.
        unsafe { env::remove_var("LOG_LEVEL") };
        unsafe { env::remove_var("LOG_ROTATION") };

        fs::remove_file(log_file_path)
            .await
            .expect("Failed to remove log file");
    }

    /// Tests the cloning and copying capabilities of the LogRotation enum.
    #[test]
    fn test_log_rotation_clone_and_copy() {
        let size = NonZeroU64::new(1024 * 1024)
            .expect("Failed to create NonZeroU64 instance");
        let rotation1 = LogRotation::Size(size);
        let rotation2 = rotation1;
        assert_eq!(rotation1, rotation2);
    }

    /// Tests the ConfigError enum variants.
    #[test]
    fn test_config_error() {
        let env_var_error = ConfigError::EnvVarParseError(
            envy::Error::MissingValue("Test error"),
        );
        assert!(
            format!("{}", env_var_error)
                .contains("Environment variable parse error"),
            "Unexpected error message for EnvVarParseError: {}",
            env_var_error
        );
    }

    /// Tests the LoggingDestination enum variants.
    #[test]
    fn test_logging_destination() {
        let file_dest =
            LoggingDestination::File(PathBuf::from("test.log"));
        let stdout_dest = LoggingDestination::Stdout;
        let network_dest =
            LoggingDestination::Network("127.0.0.1:514".to_string());

        assert!(matches!(file_dest, LoggingDestination::File(_)));
        assert!(matches!(stdout_dest, LoggingDestination::Stdout));
        assert!(matches!(network_dest, LoggingDestination::Network(_)));
    }

    /// Comprehensive test for parsing various log levels, including invalid inputs.
    #[test]
    fn test_log_level_from_str_comprehensive() {
        let test_cases = [
            ("ALL", Ok(LogLevel::ALL)),
            ("DEBUG", Ok(LogLevel::DEBUG)),
            ("INFO", Ok(LogLevel::INFO)),
            ("WARN", Ok(LogLevel::WARN)),
            ("ERROR", Ok(LogLevel::ERROR)),
            ("FATAL", Ok(LogLevel::FATAL)),
            ("TRACE", Ok(LogLevel::TRACE)),
            ("VERBOSE", Ok(LogLevel::VERBOSE)),
            ("NONE", Ok(LogLevel::NONE)),
            ("DISABLED", Ok(LogLevel::DISABLED)),
            ("CRITICAL", Ok(LogLevel::CRITICAL)),
            ("invalid", Err(())),
        ];

        for (input, expected) in test_cases.iter() {
            let result = LogLevel::from_str(input);
            match (result, expected) {
                (Ok(level), Ok(expected_level)) => assert_eq!(
                    level, *expected_level,
                    "Failed for input: {}",
                    input
                ),
                (Err(_), Err(())) => {} // Test passed for invalid input
                _ => panic!("Unexpected result for input: {}", input),
            }
        }

        // Test case insensitivity
        assert!(matches!(
            LogLevel::from_str("info"),
            Ok(LogLevel::INFO)
        ));
        assert!(matches!(
            LogLevel::from_str("ErRoR"),
            Ok(LogLevel::ERROR)
        ));
    }

    /// Tests the Config::validate method with valid and invalid configurations.
    #[test]
    fn test_config_validate() {
        let temp_dir = env::temp_dir();
        let log_file_path = temp_dir.join("test_validate_RLG.log");

        std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&log_file_path)
            .unwrap();

        let mut config = Config {
            log_file_path,
            ..Default::default()
        };

        assert!(
            config.validate().is_ok(),
            "Validation should pass with valid config"
        );

        config.log_file_path = PathBuf::new();
        assert!(
            config.validate().is_err(),
            "Validation should fail with empty log file path"
        );
    }

    /// Tests the Config::expand_env_vars method.
    #[test]
    #[allow(unsafe_code)]
    fn test_config_expand_env_vars() {
        // SAFETY: Test-only; no other threads depend on this env var.
        unsafe {
            env::set_var("RLG_LOG_PATH", "/tmp/env_test_RLG.log")
        };

        let mut config = Config::default();
        config.env_vars.insert(
            "RLG_LOG_PATH".to_string(),
            "${RLG_LOG_PATH}".to_string(),
        );

        let expanded_config = config.expand_env_vars();

        assert_eq!(
            expanded_config.env_vars.get("RLG_LOG_PATH").unwrap(),
            "/tmp/env_test_RLG.log"
        );

        // SAFETY: Test-only cleanup.
        unsafe { env::remove_var("RLG_LOG_PATH") };
    }

    /// Tests the Config::hot_reload_async method.
    /// Tests the Config::diff method.
    #[test]
    fn test_config_diff() {
        let config1 = Config::default();
        let mut env_vars = HashMap::new();
        env_vars.insert("DEBUG".to_string(), "true".to_string());
        let config2 = Config {
            version: "2.0".to_string(),
            profile: "production".to_string(),
            log_file_path: PathBuf::from("prod.log"),
            log_level: LogLevel::ERROR,
            log_rotation: Some(LogRotation::Count(10)),
            log_format: "JSON".to_string(),
            logging_destinations: vec![LoggingDestination::Network(
                "localhost:8080".to_string(),
            )],
            env_vars,
        };

        let differences = Config::diff(&config1, &config2);

        assert_eq!(
            differences.get("version"),
            Some(&"1.0 -> 2.0".to_string())
        );
        assert_eq!(
            differences.get("profile"),
            Some(&"default -> production".to_string())
        );
        assert!(differences.contains_key("log_file_path"));
        assert!(differences.contains_key("log_level"));
        assert!(differences.contains_key("log_rotation"));
        assert!(differences.contains_key("log_format"));
        assert!(differences.contains_key("logging_destinations"));
        assert!(differences.contains_key("env_vars"));
    }

    /// Tests the Config::override_with method.
    #[test]
    fn test_config_override_with() {
        let mut env_vars1 = HashMap::new();
        env_vars1.insert("K1".to_string(), "V1".to_string());
        let config1 = Config {
            env_vars: env_vars1,
            ..Config::default()
        };
        let mut env_vars2 = HashMap::new();
        env_vars2.insert("K2".to_string(), "V2".to_string());
        let config2 = Config {
            profile: "test_profile".to_string(),
            log_format: "%level - %message".to_string(),
            env_vars: env_vars2,
            ..Config::default()
        };

        let merged_config = config1.override_with(&config2);

        assert_eq!(merged_config.profile, "test_profile");
        assert_eq!(merged_config.log_format, "%level - %message");
        assert!(merged_config.env_vars.contains_key("K1"));
        assert!(merged_config.env_vars.contains_key("K2"));
    }

    /// Tests the ConfigError enum variants thoroughly.
    #[test]
    fn test_config_error_enum() {
        #[allow(dead_code)]
        #[derive(Deserialize, Debug)]
        struct EnvConfig {
            required_field: String,
        }

        let env_var_error = ConfigError::EnvVarParseError(
            envy::from_env::<EnvConfig>().unwrap_err(),
        );

        let config_parse_error = ConfigError::ConfigParseError(
            config::ConfigError::Message("test error".to_string()),
        );

        let invalid_file_path_error =
            ConfigError::InvalidFilePath("invalid path".to_string());

        let env_var_error_message = format!("{}", env_var_error);
        println!("Env var error message: {}", env_var_error_message);

        assert!(
            env_var_error_message.contains("field")
                || env_var_error_message.contains("parse"),
            "Env var error should contain 'field' or 'parse' but was: {}",
            env_var_error_message
        );
        assert_eq!(
            format!("{}", config_parse_error),
            "Configuration parsing error: test error"
        );
        assert_eq!(
            format!("{}", invalid_file_path_error),
            "Invalid file path: invalid path"
        );
    }

    // Additional tests for Config methods

    /// Tests the Config::set method for all fields.
    #[test]
    fn test_config_set_all_fields() {
        let mut config = Config::default();

        assert!(config.set("version", "2.0").is_ok());
        assert_eq!(config.version, "2.0");

        assert!(config.set("profile", "new_profile").is_ok());
        assert_eq!(config.profile, "new_profile");

        assert!(
            config
                .set("log_file_path", PathBuf::from("new.log"))
                .is_ok()
        );
        assert_eq!(config.log_file_path, PathBuf::from("new.log"));

        assert!(config.set("log_level", LogLevel::DEBUG).is_ok());
        assert_eq!(config.log_level, LogLevel::DEBUG);

        let new_rotation = Some(LogRotation::Count(5));
        assert!(config.set("log_rotation", new_rotation).is_ok());
        assert_eq!(config.log_rotation, new_rotation);

        assert!(config.set("log_format", "[%level] %message").is_ok());
        assert_eq!(config.log_format, "[%level] %message");

        let new_dest = vec![LoggingDestination::Stdout];
        assert!(
            config
                .set("logging_destinations", new_dest.clone())
                .is_ok()
        );
        assert_eq!(config.logging_destinations, new_dest);

        let mut new_env = HashMap::new();
        new_env.insert("K".to_string(), "V".to_string());
        assert!(config.set("env_vars", &new_env).is_ok());
        assert_eq!(config.env_vars, new_env);

        assert!(config.set("non_existent", "value").is_err());
    }

    /// Tests the Config::save_to_file method.
    #[test]
    fn test_config_save_to_file() {
        let temp_dir =
            tempdir().expect("Failed to create temp directory");
        let config_path = temp_dir.path().join("test_config.json");

        let config = Config::default();
        assert!(config.save_to_file(&config_path).is_ok());

        assert!(
            config_path.exists(),
            "Config file should have been created"
        );
    }
}