Skip to content

Commit 366c9de

Browse files
committed
Create TestLogger.
1 parent 8b3f39a commit 366c9de

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/types.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,58 @@ impl Logger for RGSSLogger {
3636
println!("{:<5} [{} : {}, {}] {}", record.level.to_string(), record.module_path, record.file, record.line, record.args);
3737
}
3838
}
39+
40+
#[cfg(test)]
41+
pub mod tests {
42+
use std::collections::HashMap;
43+
use std::sync::{Mutex};
44+
use lightning::util::logger::{Level, Logger, Record};
45+
46+
pub struct TestLogger {
47+
level: Level,
48+
pub(crate) id: String,
49+
pub lines: Mutex<HashMap<(String, String), usize>>,
50+
}
51+
52+
impl TestLogger {
53+
pub fn new() -> TestLogger {
54+
Self::with_id("".to_owned())
55+
}
56+
pub fn with_id(id: String) -> TestLogger {
57+
TestLogger {
58+
level: Level::Trace,
59+
id,
60+
lines: Mutex::new(HashMap::new()),
61+
}
62+
}
63+
pub fn enable(&mut self, level: Level) {
64+
self.level = level;
65+
}
66+
pub fn assert_log(&self, module: String, line: String, count: usize) {
67+
let log_entries = self.lines.lock().unwrap();
68+
assert_eq!(log_entries.get(&(module, line)), Some(&count));
69+
}
70+
71+
/// Search for the number of occurrence of the logged lines which
72+
/// 1. belongs to the specified module and
73+
/// 2. contains `line` in it.
74+
/// And asserts if the number of occurrences is the same with the given `count`
75+
pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
76+
let log_entries = self.lines.lock().unwrap();
77+
let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
78+
m == module && l.contains(line)
79+
}).map(|(_, c)| { c }).sum();
80+
assert_eq!(l, count)
81+
}
82+
}
83+
84+
impl Logger for TestLogger {
85+
fn log(&self, record: &Record) {
86+
*self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
87+
if record.level >= self.level {
88+
// #[cfg(feature = "std")]
89+
println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
90+
}
91+
}
92+
}
93+
}

0 commit comments

Comments
 (0)