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
use nanologger::{LogLevel, LogOutput, LoggerBuilder};
use proptest::prelude::*;
use std::io::Write;
use std::sync::{Arc, Mutex};
/// A shared buffer that implements Write, allowing us to inspect output
/// after the logger has taken ownership.
#[derive(Clone)]
struct SharedBuf(Arc<Mutex<Vec<u8>>>);
impl SharedBuf {
fn new() -> Self {
SharedBuf(Arc::new(Mutex::new(Vec::new())))
}
fn contents(&self) -> String {
String::from_utf8_lossy(&self.0.lock().unwrap()).to_string()
}
}
impl Write for SharedBuf {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// WriteLogger output is always plain text (no ANSI escapes).
///
/// NOTE: Because the global logger can only be initialized once per process,
/// this test initializes a single logger with Trace level and a Writer output,
/// then tests multiple generated inputs against it. The proptest runner
/// executes within a single process, so we initialize once via std::sync::Once.
#[test]
fn test_write_logger_plain_text() {
let buf = SharedBuf::new();
let buf_reader = buf.clone();
LoggerBuilder::new()
.level(LogLevel::Trace)
.add_output(LogOutput::writer(LogLevel::Trace, buf))
.init()
.expect("init should succeed");
// Use proptest's TestRunner manually since we need the global logger
// initialized before running generated cases.
let mut runner = proptest::test_runner::TestRunner::default();
let strategy = (
prop_oneof![
Just(LogLevel::Error),
Just(LogLevel::Warn),
Just(LogLevel::Info),
Just(LogLevel::Debug),
Just(LogLevel::Trace),
],
"[a-zA-Z0-9 _]{1,80}",
);
runner
.run(&strategy, |(level, msg)| {
// Clear buffer before each test case
buf_reader.0.lock().unwrap().clear();
nanologger::__log_with_context(level, &msg, "test_mod", "test.rs", 1);
let output = buf_reader.contents();
// Output must contain the message text
prop_assert!(
output.contains(&msg),
"Output should contain message {:?}, got {:?}",
msg,
output
);
// Output must not contain ANSI escape sequences
prop_assert!(
!output.contains("\x1b["),
"WriteLogger output must not contain ANSI escapes: {:?}",
output
);
// Output must end with newline
prop_assert!(output.ends_with('\n'), "Output should end with newline");
Ok(())
})
.unwrap();
}