tracing_test/lib.rs
1//! Helper functions and macros that allow for easier testing of crates that use `tracing`.
2//!
3//! The focus is on testing the logging, not on debugging the tests. That's why the
4//! library ensures that the logs do not depend on external state. For example, the
5//! `RUST_LOG` env variable is not used for log filtering.
6//!
7//! Similar crates:
8//!
9//! - [test-log](https://crates.io/crates/test-log): Initialize loggers before
10//! running tests
11//! - [tracing-fluent-assertions](https://crates.io/crates/tracing-fluent-assertions):
12//! More powerful assertions that also allow analyzing spans
13//!
14//! ## Usage
15//!
16//! This crate should mainly be used through the
17//! [`#[traced_test]`](attr.traced_test.html) macro.
18//!
19//! First, add a dependency on `tracing-test` in `Cargo.toml`:
20//!
21//! ```toml
22//! tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
23//! tracing = "0.1"
24//! tracing-test = "0.1"
25//! ```
26//!
27//! Then, annotate your test function with the `#[traced_test]` macro.
28//!
29//! ```rust
30//! use tracing::{info, warn};
31//! use tracing_test::traced_test;
32//!
33//! #[tokio::test]
34//! #[traced_test]
35//! async fn test_logs_are_captured() {
36//! // Local log
37//! info!("This is being logged on the info level");
38//!
39//! // Log from a spawned task (which runs in a separate thread)
40//! tokio::spawn(async {
41//! warn!("This is being logged on the warn level from a spawned task");
42//! })
43//! .await
44//! .unwrap();
45//!
46//! // Ensure that certain strings are or aren't logged
47//! assert!(logs_contain("logged on the info level"));
48//! assert!(logs_contain("logged on the warn level"));
49//! assert!(!logs_contain("logged on the error level"));
50//!
51//! // Ensure that the string `logged` is logged exactly twice
52//! logs_assert(|lines: &[&str]| {
53//! match lines.iter().filter(|line| line.contains("logged")).count() {
54//! 2 => Ok(()),
55//! n => Err(format!("Expected two matching logs, but found {}", n)),
56//! }
57//! });
58//! }
59//! ```
60//!
61//! Done! You can write assertions using one of two injected functions:
62//!
63//! - `logs_contain(&str) -> bool`: Use this within an `assert!` call to ensure
64//! that a certain string is (or isn't) logged anywhere in the logs.
65//! - `logs_assert(f: impl Fn(&[&str]) -> Result<(), String>)`: Run a function
66//! against the log lines. If the function returns an `Err`, panic. This can
67//! be used to run arbitrary assertion logic against the logs.
68//!
69//! Logs are written to stdout, so they are captured by the cargo test runner
70//! by default, but printed if the test fails.
71//!
72//! Of course, you can also annotate regular non-async tests:
73//!
74//! ```rust
75//! use tracing::info;
76//! use tracing_test::traced_test;
77//!
78//! #[traced_test]
79//! #[test]
80//! fn plain_old_test() {
81//! assert!(!logs_contain("Logging from a non-async test"));
82//! info!("Logging from a non-async test");
83//! assert!(logs_contain("Logging from a non-async test"));
84//! assert!(!logs_contain("This was never logged"));
85//! }
86//! ```
87//!
88//! ## Rationale / Why You Need This
89//!
90//! Tracing allows you to set a default subscriber within a scope:
91//!
92//! ```rust
93//! # let subscriber = tracing::Dispatch::new(tracing_subscriber::FmtSubscriber::new());
94//! # let req = 123;
95//! # fn get_response(fake_req: u8) {}
96//! let response = tracing::dispatcher::with_default(&subscriber, || get_response(req));
97//! ```
98//!
99//! This works fine, as long as no threads are involved. As soon as you use a
100//! multi-threaded test runtime (e.g. the `#[tokio::test]` with the
101//! `rt-multi-thread` feature) and spawn tasks, the tracing logs in those tasks
102//! will not be captured by the subscriber.
103//!
104//! The macro provided in this crate registers a global default subscriber instead.
105//! This subscriber contains a writer which logs into a global static in-memory buffer.
106//!
107//! At the beginning of every test, the macro injects span opening code. The span
108//! uses the name of the test function (unless it's already taken, then a counter
109//! is appended). This means that the logs from a test are prefixed with the test
110//! name, which helps when debugging.
111//!
112//! Finally, a function called `logs_contain(value: &str)` is injected into every
113//! annotated test. It filters the logs in the buffer to include only lines
114//! containing ` {span_name}: ` and then searches the value in the matching log
115//! lines. This can be used to assert that a message was logged during a test.
116//!
117//! ## Per-crate Filtering
118//!
119//! By default, `tracing-test` sets an env filter that filters out all logs
120//! except the ones from your crate (equivalent to
121//! `RUST_LOG=<your_crate>=trace`). If you need to capture logs from other crates
122//! as well, you can turn off this log filtering globally by enabling the
123//! `no-env-filter` Cargo feature:
124//!
125//! ```toml
126//! tracing-test = { version = "0.1", features = ["no-env-filter"] }
127//! ```
128//!
129//! Note that this will result in _all_ logs from _all_ your dependencies being
130//! captured! This means that the `logs_contain` function may become less
131//! useful, and you might need to use `logs_assert` instead, with your own
132//! custom filtering logic.
133//!
134//! **Note:** Rust "integration tests" (in the `tests/` directory) are each
135//! built into a separate crate from the crate they test. As a result,
136//! integration tests must use `no-env-filter` to capture and observe logs.
137
138pub mod internal;
139mod subscriber;
140
141pub use tracing_test_macro::traced_test;