test_with_tracing/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Crate for defining tests that have tracing output.
5
6#![forbid(unsafe_code)]
7
8#[cfg(test)]
9extern crate self as test_with_tracing;
10
11pub use test_with_tracing_macro::test;
12use tracing::metadata::LevelFilter;
13use tracing_subscriber::filter::Targets;
14use tracing_subscriber::fmt::format::FmtSpan;
15use tracing_subscriber::prelude::*;
16
17#[doc(hidden)]
18/// Initializes `tracing` for tests.
19pub fn init() {
20    static ONCE: std::sync::Once = std::sync::Once::new();
21
22    ONCE.call_once(|| {
23        let targets = if let Ok(var) = std::env::var("RUST_LOG") {
24            var.parse().unwrap()
25        } else {
26            Targets::new().with_default(LevelFilter::DEBUG)
27        };
28        tracing_subscriber::fmt()
29            .pretty()
30            .with_ansi(false) // avoid polluting logs with escape sequences
31            .log_internal_errors(true)
32            .with_test_writer()
33            .with_max_level(LevelFilter::TRACE)
34            .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
35            .finish()
36            .with(targets)
37            .init();
38    });
39}
40
41#[cfg(test)]
42mod tests {
43    use super::test;
44
45    #[test]
46    fn test_it() {
47        tracing::info!("should show tracing warning");
48        log::info!("should show log warning");
49    }
50
51    #[test]
52    fn test_with_return() -> Result<(), Box<dyn std::error::Error>> {
53        tracing::info!("ok");
54        Ok(())
55    }
56}