1
use std::io::{self, Write};
2
use std::process::Command;
3
use std::sync::{Arc, Mutex};
4

            
5
use server::telemetry::{init_logging, init_with_writer, resolve_filter};
6
use tracing::level_filters::LevelFilter;
7

            
8
const CHILD_ENV: &str = "NOMISYNC_LOGGING_TEST_CHILD";
9
const MARKER: &str = "marker-from-log-record";
10

            
11
#[derive(Clone, Default)]
12
struct Capture(Arc<Mutex<Vec<u8>>>);
13

            
14
impl Write for Capture {
15
1
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
16
1
        self.0
17
1
            .lock()
18
            .map_err(|_| io::Error::other("capture poisoned"))?
19
1
            .extend_from_slice(buf);
20
1
        Ok(buf.len())
21
1
    }
22

            
23
    fn flush(&mut self) -> io::Result<()> {
24
        Ok(())
25
    }
26
}
27

            
28
#[test]
29
1
fn log_record_reaches_the_subscriber() -> Result<(), Box<dyn std::error::Error>> {
30
1
    let capture = Capture::default();
31
1
    let sink = capture.clone();
32
1
    init_with_writer(
33
1
        resolve_filter(Some(LevelFilter::INFO), None, LevelFilter::WARN),
34
1
        move || sink.clone(),
35
1
        false,
36
    )?;
37

            
38
1
    log::info!("{MARKER}");
39

            
40
1
    let captured = String::from_utf8(capture.0.lock().map_err(|_| "poisoned")?.clone())?;
41
1
    assert!(captured.contains(MARKER), "captured: {captured:?}");
42
1
    Ok(())
43
1
}
44

            
45
#[test]
46
2
fn child_logs_through_init_logging() -> Result<(), Box<dyn std::error::Error>> {
47
2
    if std::env::var_os(CHILD_ENV).is_none() {
48
1
        return Ok(());
49
1
    }
50
1
    init_logging(Some(LevelFilter::INFO), LevelFilter::WARN)?;
51
1
    log::info!("{MARKER}");
52
1
    Ok(())
53
2
}
54

            
55
#[test]
56
1
fn logging_writes_stderr_and_keeps_stdout_clean() -> Result<(), Box<dyn std::error::Error>> {
57
1
    let out = Command::new(std::env::current_exe()?)
58
1
        .args(["--exact", "child_logs_through_init_logging", "--nocapture"])
59
1
        .env(CHILD_ENV, "1")
60
1
        .env("RUST_LOG", "off")
61
        .output()?;
62

            
63
1
    let stderr = String::from_utf8(out.stderr)?;
64
1
    assert!(out.status.success());
65
1
    assert!(!String::from_utf8(out.stdout)?.contains(MARKER));
66
1
    assert!(stderr.contains(MARKER));
67
1
    assert!(
68
1
        !stderr.contains('\u{1b}'),
69
        "a piped stderr must carry no colour codes: {stderr:?}"
70
    );
71
1
    Ok(())
72
1
}