Radish alpha
r
rad:zwTxygwuz5LDGBq255RA2CbNGrz8
Radicle CI broker
Radicle
Git
tests: hide log messages from output in successful tests
Merged liw opened 1 year ago

This was unexpectedly difficult to figure out, but I got there.

Signed-off-by: Lars Wirzenius liw@liw.fi

1 file changed +41 -1 513eb2c5 fa61cdda
modified src/logger.rs
@@ -4,6 +4,7 @@
use std::sync::Once;
use std::{
    fmt,
+
    io::Write,
    path::Path,
    sync::{Arc, Mutex},
    time::Duration,
@@ -55,6 +56,45 @@ impl From<LogLevel> for slog::Level {
    }
}

+
// A custom type for log output. We need this to hide log messages
+
// from output in successful tests. Cargo will hide standard output
+
// and error by default, which is what we want, but it seems this only
+
// applies to output via the `print!` family of macros. If we open a
+
// new handle for stdout or stderr, output via that handle is not
+
// captured by Cargo.
+
//
+
// Instead, we have our own log writer type that writes to stderr in
+
// production mode, and uses `print!` in tests.
+
#[derive(Default)]
+
struct LogWriter {}
+

+
#[cfg(test)]
+
impl Write for LogWriter {
+
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+
        let s = String::from_utf8_lossy(buf);
+
        print!("{s}");
+
        Ok(buf.len())
+
    }
+

+
    fn flush(&mut self) -> std::io::Result<()> {
+
        Ok(())
+
    }
+
}
+

+
#[cfg(not(test))]
+
impl Write for LogWriter {
+
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+
        let mut stderr = std::io::stderr();
+
        stderr.write_all(buf)?;
+
        stderr.flush()?;
+
        Ok(buf.len())
+
    }
+

+
    fn flush(&mut self) -> std::io::Result<()> {
+
        Ok(())
+
    }
+
}
+

pub struct Logger {
    minimum_log_level: Arc<Mutex<slog::Level>>,

@@ -74,7 +114,7 @@ impl Logger {
}

pub fn open() -> Logger {
-
    let underlying_logger = slog_json::Json::new(std::io::stderr())
+
    let underlying_logger = slog_json::Json::new(LogWriter::default())
        .add_default_keys()
        .set_flush(true)
        .set_newlines(true)