Skip to main content

facet_testhelpers/
lib.rs

1//! TeamDman-maintained fork of [facet-testhelpers](https://github.com/facet-rs/facet/tree/65bae5c31a7ce401bc44630fb96250ea884cfd3e/facet-testhelpers), published as
2//! [teamy-facet-testhelpers](https://crates.io/crates/teamy-facet-testhelpers).
3//! This fork uses its own Facet crate identities; use matching Teamy packages.
4//! Upstream MIT OR Apache-2.0 licensing and attribution are retained.
5//! See the [release notes](https://github.com/TeamDman/facet/blob/teamy-main/TEAMY_RELEASE.md).
6//!
7#![warn(missing_docs)]
8#![warn(clippy::std_instead_of_core)]
9#![warn(clippy::std_instead_of_alloc)]
10#![forbid(unsafe_code)]
11//!
12//! [![crates.io](https://img.shields.io/crates/v/teamy-facet-testhelpers.svg)](https://crates.io/crates/teamy-facet-testhelpers)
13//! [![documentation](https://docs.rs/teamy-facet-testhelpers/badge.svg)](https://docs.rs/teamy-facet-testhelpers)
14//! [![MIT/Apache-2.0 licensed](https://img.shields.io/crates/l/teamy-facet-testhelpers.svg)](./LICENSE-MIT)
15//! [![Discord](https://img.shields.io/discord/1379550208551026748?logo=discord&label=discord)](https://discord.gg/JhD7CwCJ8F)
16//!
17//! Lightweight test helpers: a log facade that always does tracing (with colors),
18//! and color-backtrace using the btparse backend.
19//!
20//! ## Usage
21//!
22//! Add this to your test files:
23//!
24//! ```rust
25//! #[facet_testhelpers::test]
26//! fn my_test() {
27//!     log::info!("This will be printed with color!");
28//!     // Your test code here
29//! }
30//! ```
31//!
32//! The test macro sets up a simple logger that works with both `cargo test` and `cargo nextest run`.
33//!
34//! ### Recommendation
35//!
36//! While this crate works with regular `cargo test`, we recommend using [`cargo-nextest`](https://nexte.st) for:
37//! - Process-per-test isolation
38//! - Faster parallel test execution
39//! - Better test output and reporting
40//!
41//! Install with:
42//! ```bash
43//! cargo install cargo-nextest
44//! ```
45//!
46//! Then run tests with:
47//! ```bash
48//! cargo nextest run
49//! ```
50//!
51#![doc = include_str!("../readme-footer.md")]
52
53pub use facet_testhelpers_macros::test;
54
55use std::sync::LazyLock;
56use std::time::Instant;
57use tracing_subscriber::filter::Targets;
58use tracing_subscriber::fmt::format::Writer;
59use tracing_subscriber::fmt::time::FormatTime;
60use tracing_subscriber::layer::SubscriberExt;
61use tracing_subscriber::util::SubscriberInitExt;
62
63static START_TIME: LazyLock<Instant> = LazyLock::new(Instant::now);
64
65struct Uptime;
66
67impl FormatTime for Uptime {
68    fn format_time(&self, w: &mut Writer<'_>) -> core::fmt::Result {
69        let elapsed = START_TIME.elapsed();
70        let secs = elapsed.as_secs();
71        let millis = elapsed.subsec_millis();
72        write!(w, "{:4}.{:03}s", secs, millis)
73    }
74}
75
76/// Lazy initialization of the global tracing subscriber.
77///
78/// This ensures the subscriber is set up exactly once, regardless of how many
79/// tests run in the same process.
80static SUBSCRIBER_INIT: LazyLock<()> = LazyLock::new(|| {
81    // Force start time initialization
82    let _ = *START_TIME;
83
84    let verbosity = color_backtrace::Verbosity::Medium;
85
86    // Install color-backtrace for better panic output (with forced backtraces and colors)
87    color_backtrace::BacktracePrinter::new()
88        .verbosity(verbosity)
89        .add_frame_filter(Box::new(|frames| {
90            frames.retain(|frame| {
91                let dominated_by_noise = |name: &str| {
92                    // Test harness internals
93                    name.starts_with("test::run_test")
94                        || name.starts_with("test::__rust_begin_short_backtrace")
95                        // Panic/unwind machinery
96                        || name.starts_with("std::panicking::")
97                        || name.starts_with("std::panic::")
98                        || name.starts_with("core::panicking::")
99                        // Thread spawning
100                        || name.starts_with("std::thread::Builder::spawn_unchecked_")
101                        || name.starts_with("std::sys::thread::")
102                        || name.starts_with("std::sys::backtrace::")
103                        // FnOnce::call_once trampolines in std/core/alloc
104                        || name.starts_with("core::ops::function::FnOnce::call_once")
105                        || name.starts_with("<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once")
106                        // AssertUnwindSafe wrapper
107                        || name.starts_with("<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once")
108                        // Low-level threading primitives
109                        || name.starts_with("__pthread")
110                };
111                match &frame.name {
112                    Some(name) => !dominated_by_noise(name),
113                    None => true,
114                }
115            })
116        }))
117        .install(Box::new(termcolor::StandardStream::stderr(
118            termcolor::ColorChoice::AlwaysAnsi,
119        )));
120
121    let filter = std::env::var("FACET_LOG")
122        .ok()
123        .and_then(|s| s.parse::<Targets>().ok())
124        .unwrap_or_else(|| {
125            eprintln!("Assuming FACET_LOG=debug (feel free to set the $FACET_LOG env var to override tracing filters) (note: $RUST_LOG doesn't do anything)");
126            Targets::new().with_default(tracing::Level::DEBUG)
127        });
128
129    fn is_set_to_1(key: &str) -> bool {
130        match std::env::var(key) {
131            Ok(val) => val == "1",
132            Err(_) => false,
133        }
134    }
135
136    let is_verbose = is_set_to_1("FACET_LOG_VERBOSE");
137    if !is_verbose {
138        eprintln!(
139            "You can set FACET_LOG_VERBOSE=1 to see targets, files and line numbers for each tracing message"
140        );
141    }
142
143    tracing_subscriber::registry()
144        .with(
145            tracing_subscriber::fmt::layer()
146                .with_ansi(true)
147                .with_timer(Uptime)
148                .with_target(false)
149                .with_level(true)
150                .with_file(is_verbose)
151                .with_line_number(is_verbose)
152                .compact(),
153        )
154        .with(filter)
155        .try_init()
156        .ok();
157});
158
159/// Set up a tracing subscriber for tests.
160///
161/// This function ensures the subscriber is initialized exactly once using
162/// [`LazyLock`], making it safe to use with both `cargo test` and
163/// `cargo nextest run`.
164///
165/// # Recommendation
166///
167/// While this works with regular `cargo test`, we recommend using
168/// `cargo nextest run` for:
169/// - Process-per-test isolation
170/// - Faster parallel test execution
171/// - Better test output and reporting
172///
173/// Install nextest with: `cargo install cargo-nextest`
174///
175/// For more information, visit: <https://nexte.st>
176pub fn setup() {
177    // Print a helpful message if not using nextest
178    let is_nextest = std::env::var("NEXTEST").as_deref() == Ok("1");
179    if !is_nextest {
180        static NEXTEST_WARNING: LazyLock<()> = LazyLock::new(|| {
181            eprintln!(
182                "💡 Tip: Consider using `cargo nextest run` for better test output and performance."
183            );
184            eprintln!("   Install with: cargo install cargo-nextest");
185            eprintln!("   More info: https://nexte.st");
186            eprintln!();
187        });
188        #[allow(clippy::let_unit_value)]
189        let _ = *NEXTEST_WARNING;
190    }
191
192    // Ensure the subscriber is initialized
193    #[allow(clippy::let_unit_value)]
194    let _ = *SUBSCRIBER_INIT;
195}
196
197/// An error type that panics when it's built (such as when you use `?`
198/// to coerce to it)
199#[derive(Debug)]
200pub struct IPanic;
201
202impl<E> From<E> for IPanic
203where
204    E: core::error::Error + Send + Sync,
205{
206    #[track_caller]
207    fn from(value: E) -> Self {
208        panic!("from: {}: {value}", core::panic::Location::caller())
209    }
210}