From 3a40898a424be3df9b6cc6d329d9d3675d79d4b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:43:03 -0800 Subject: [PATCH 1/3] craft-testkit: capture log records per thread or process wide behind the log feature Add the `log` feature with `craft_testkit::log`, the shared form of the `test_log.rs` helper in craft-libs `docx` and `wordmodel` (and WordCraft `doc` and `formats`) and of SoundCraft's process-wide logger in `clap-host/tests/editor_main_thread.rs`: - `warnings(f)` and `records(level, f)` return the closure's result with the records the calling thread logged while it ran. - `capture_global(level)` returns a handle whose `drain()` takes the records logged on every thread. `log::set_logger` can be called once per process, so the first capture fixes the mode for the test binary, and a call for the other mode returns `ModeConflict`. Compared with the copied helper: - An earlier foreign logger returns `LoggerAlreadySet` instead of an empty capture, and the closure does not run. - A capture raises the global maximum level and never lowers it. - A nested capture on the same thread returns `NestedCapture` instead of clearing the outer capture's records. - A panic in the closure ends the capture on that thread. Each capture keeps at most 4,096 records and 1 MiB of text and returns `Overflow { dropped }` past either limit. Message formatting stops at the byte limit. Only one `GlobalCapture` is alive at a time; dropping it ends the capture, and a record checked against one capture is not kept by the next. The module and its tests are native only. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 20 ++ crates/testkit/README.md | 54 +++++ crates/testkit/src/lib.rs | 6 + crates/testkit/src/log.rs | 360 ++++++++++++++++++++++++++++ crates/testkit/tests/log_foreign.rs | 33 +++ crates/testkit/tests/log_global.rs | 123 ++++++++++ crates/testkit/tests/log_thread.rs | 141 +++++++++++ 8 files changed, 740 insertions(+) create mode 100644 crates/testkit/src/log.rs create mode 100644 crates/testkit/tests/log_foreign.rs create mode 100644 crates/testkit/tests/log_global.rs create mode 100644 crates/testkit/tests/log_thread.rs diff --git a/Cargo.lock b/Cargo.lock index 7b8d513e3b..5d6d102d3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2572,6 +2572,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "log", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d2a3b3179f..2b1484ea99 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -7,7 +7,27 @@ rust-version.workspace = true repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" +[features] +# `log`: capture of the records a test logs, per thread or process wide. +log = ["dep:log"] + [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +log = { workspace = true, optional = true } + +[[test]] +name = "log_thread" +required-features = ["log"] + +[[test]] +name = "log_global" +harness = false +required-features = ["log"] + +[[test]] +name = "log_foreign" +required-features = ["log"] + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index d7208396b6..1c5e09c657 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,60 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags lines naming `std::time::Instant` outside comments without `web_time`. On `wasm32-unknown-unknown`, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), and build artifacts (`target/`, `.git/`). +## Log capture: `log` + +The `log` feature adds `craft_testkit::log` and the `log` dependency. The module is built on every target except `wasm32`. + +| Function | Captures | Returns | +|---|---|---| +| `warnings(f)` | warnings and errors logged on the calling thread while `f` runs | `Result<(T, Vec), CaptureError>` with the messages | +| `records(level, f)` | records at `level` or more severe logged on the calling thread while `f` runs | `Result<(T, Vec), CaptureError>` with level, target and message | +| `capture_global(level)` | records at `level` or more severe logged on any thread | `Result`; `drain()` takes the records captured since the last drain | + +`log::set_logger` can be called once per process, so the first capture to install the logger sets the mode for the whole test binary: per thread (`warnings`, `records`) or process wide (`capture_global`). The functions return these errors without running the closure or changing the maximum level: + +| Error | When | +|---|---| +| `LoggerAlreadySet` | another logger was installed first | +| `ModeConflict` | the binary already captures in the other mode | +| `NestedCapture` | `warnings` or `records` is called inside a capture on the same thread | +| `GlobalCaptureActive` | another `GlobalCapture` is alive; dropping it ends that capture, and the logger stays installed | + +A capture raises `log::max_level()` to the level it asks for and never lowers it. When the closure panics, the capture on that thread ends and the panic continues. Records from other threads do not appear in a per-thread capture. + +A capture keeps at most `MAX_RECORDS` (4,096) records and `MAX_BYTES` (1 MiB) of message and target text. Formatting a message stops once it passes `MAX_BYTES`. A record over either limit is dropped and counted, and the capture returns `CaptureError::Overflow { dropped }` instead of a partial list. For `drain`, the limits apply to each interval between drains. + +Run process-wide captures in a binary of their own, for example a `[[test]]` with `harness = false`: + +```rust +fn main() { + let capture = craft_testkit::log::capture_global(log::LevelFilter::Warn).expect("capture"); + std::thread::Builder::new() + .name("audio".into()) + .spawn(|| drop_the_plugin()) + .expect("spawn") + .join() + .expect("join"); + let records = capture.drain().expect("drain"); + assert!(records.iter().any(|r| r.message.contains("off the main thread"))); +} +``` + +### Origin + +| Module | Source repository | Path | Revision | +|---|---|---|---| +| `log` (per thread) | storytold/craft-libs | `crates/docx/src/test_log.rs` (the same file as `crates/wordmodel/src/test_log.rs` and WordCraft's `crates/doc/src/test_log.rs` and `crates/formats/src/test_log.rs`) | `e3e31693` | +| `log` (process wide) | storytold/soundcraft | `crates/clap-host/tests/editor_main_thread.rs:18-41` | `e6cbf761` | + +### Migration + +| Consumer | Uses | State | +|---|---|---| +| craft-libs `docx`, `wordmodel` | their private `test_log.rs` | Pending: a separate pull request switches both | +| WordCraft `doc`, `formats` | their private `test_log.rs` | Pending: a separate pull request in WordCraft | +| SoundCraft `clap-host` | the logger in `tests/editor_main_thread.rs` | Pending: a separate pull request in SoundCraft switches it to `capture_global` | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b0e61fc8b5..fad8f96902 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -14,6 +14,10 @@ //! where `std::time::Instant::now()` panics on `wasm32`. //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests. //! +//! With the `log` feature, on targets other than `wasm32`, `log::warnings` and `log::records` +//! capture the records the calling thread logs while a closure runs, and `log::capture_global` +//! captures the records every thread logs. One test binary uses one of the two modes. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -25,6 +29,8 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(all(feature = "log", not(target_arch = "wasm32")))] +pub mod log; pub use guards::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/src/log.rs b/crates/testkit/src/log.rs new file mode 100644 index 0000000000..2b672c1aeb --- /dev/null +++ b/crates/testkit/src/log.rs @@ -0,0 +1,360 @@ +//! Capture of the records a test logs through the `log` crate. +//! +//! The module installs one `log::Log` implementation for the process. `log::set_logger` can be +//! called once per process, so a test binary uses one of two modes, and the first call that +//! installs the logger fixes the mode for the rest of the process: +//! +//! - Per thread: [`warnings`] and [`records`] run a closure and return its result with the records +//! logged on the calling thread while it ran. Records from other threads are not captured. +//! - Process wide: [`capture_global`] returns a [`GlobalCapture`] whose [`GlobalCapture::drain`] +//! takes the records logged on every thread since the last drain. +//! +//! A call for the other mode returns [`CaptureError::ModeConflict`]. When another logger is already +//! installed, every call returns [`CaptureError::LoggerAlreadySet`], runs no closure and leaves the +//! global maximum level as it is. +//! +//! A capture raises the global maximum level (`log::max_level`) to the level it asks for and never +//! lowers it, so a capture does not hide records from code that raised the level earlier. Each +//! capture filters by its own level. +//! +//! A capture keeps at most [`MAX_RECORDS`] records and [`MAX_BYTES`] bytes of message and target +//! text. Formatting a message stops once it passes [`MAX_BYTES`]. A record over either limit is +//! dropped and counted, and the capture then returns [`CaptureError::Overflow`] with the number +//! dropped instead of a partial list. + +use std::cell::RefCell; +use std::fmt; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use ::log::{Level, LevelFilter, Log, Metadata, Record}; + +/// The most records one capture keeps. +pub const MAX_RECORDS: usize = 4096; + +/// The most bytes of message and target text one capture keeps. +pub const MAX_BYTES: usize = 1 << 20; + +/// One captured record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CapturedRecord { + /// The record's level. + pub level: Level, + /// The record's target, by default the module path of the call. + pub target: String, + /// The formatted message. + pub message: String, +} + +/// Why a capture could not run or could not return its records. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum CaptureError { + /// Another logger was installed in this process before this module's logger. + LoggerAlreadySet, + /// This process captures in the other mode: per thread or process wide. + ModeConflict, + /// [`warnings`] or [`records`] was called inside a capture on the same thread. + NestedCapture, + /// A [`GlobalCapture`] is still alive in this process. + GlobalCaptureActive, + /// The capture reached [`MAX_RECORDS`] or [`MAX_BYTES`] and dropped this many records. + Overflow { + /// The number of records dropped. + dropped: usize, + }, +} + +impl fmt::Display for CaptureError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::LoggerAlreadySet => f.write_str("another logger is already installed in this process"), + Self::ModeConflict => f.write_str("this process already captures logs in the other mode (per thread or process wide)"), + Self::NestedCapture => f.write_str("a log capture is already running on this thread"), + Self::GlobalCaptureActive => f.write_str("a process-wide log capture is already alive"), + Self::Overflow { dropped } => { + write!(f, "the log capture dropped {dropped} records over its limit of {MAX_RECORDS} records or {MAX_BYTES} bytes") + } + } + } +} + +impl std::error::Error for CaptureError {} + +const MODE_NONE: u8 = 0; +const MODE_THREAD: u8 = 1; +const MODE_GLOBAL: u8 = 2; + +/// The installed mode, read by the logger on every record. +static MODE: AtomicU8 = AtomicU8::new(MODE_NONE); + +/// Serializes installation and changes of the global maximum level. +static INSTALL: Mutex<()> = Mutex::new(()); + +/// The bits of [`GLOBAL_STATE`] that hold the level. +const LEVEL_BITS: u32 = 3; +const LEVEL_MASK: u64 = (1 << LEVEL_BITS) - 1; + +/// The process-wide capture's session number shifted left by [`LEVEL_BITS`], with its level as a +/// `LevelFilter` number in the low bits (`0`, `Off`, when no capture is alive). The logger reads +/// both in one load, so a record checked against one capture is never kept by a later one. +static GLOBAL_STATE: AtomicU64 = AtomicU64::new(0); + +static GLOBAL: Mutex = Mutex::new(Buffer::new()); + +/// Records kept within [`MAX_RECORDS`] and [`MAX_BYTES`], with a count of those dropped. +struct Buffer { + records: Vec, + bytes: usize, + dropped: usize, + /// For the process-wide buffer: whether a [`GlobalCapture`] is alive, and its session. + alive: bool, + session: u64, +} + +impl Buffer { + const fn new() -> Self { + Self { records: Vec::new(), bytes: 0, dropped: 0, alive: false, session: 0 } + } + + /// Keeps `record`, or counts it as dropped when it is `None` or over a limit. + fn push(&mut self, record: Option) { + let Some(record) = record else { + self.dropped = self.dropped.saturating_add(1); + return; + }; + let size = record.message.len().saturating_add(record.target.len()); + if self.records.len() >= MAX_RECORDS || size > MAX_BYTES.saturating_sub(self.bytes) { + self.dropped = self.dropped.saturating_add(1); + return; + } + self.bytes += size; + self.records.push(record); + } + + /// The kept records, or the overflow, leaving the buffer empty. + fn take(&mut self) -> Result, CaptureError> { + let records = std::mem::take(&mut self.records); + let dropped = std::mem::take(&mut self.dropped); + self.bytes = 0; + if dropped > 0 { Err(CaptureError::Overflow { dropped }) } else { Ok(records) } + } +} + +/// The per-thread capture running on a thread. +struct Scope { + level: LevelFilter, + buffer: Buffer, +} + +thread_local! { + static SCOPE: RefCell> = const { RefCell::new(None) }; +} + +/// A `fmt::Write` that keeps at most [`MAX_BYTES`] bytes and fails the write that would pass them. +struct Bounded { + text: String, + over: bool, +} + +impl fmt::Write for Bounded { + fn write_str(&mut self, s: &str) -> fmt::Result { + if s.len() > MAX_BYTES.saturating_sub(self.text.len()) { + self.over = true; + return Err(fmt::Error); + } + self.text.push_str(s); + Ok(()) + } +} + +/// The record with its message formatted, or `None` when its message or target passes +/// [`MAX_BYTES`]. +fn capture(record: &Record) -> Option { + let target = record.target(); + if target.len() > MAX_BYTES { + return None; + } + let mut message = Bounded { text: String::new(), over: false }; + // A `Display` implementation's own error leaves the text written so far. + let _ = fmt::write(&mut message, *record.args()); + if message.over { + return None; + } + Some(CapturedRecord { level: record.level(), target: target.to_owned(), message: message.text }) +} + +struct Capture; + +static CAPTURE: Capture = Capture; + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn thread_level() -> LevelFilter { + SCOPE.try_with(|s| s.try_borrow().ok().and_then(|s| s.as_ref().map(|s| s.level))).ok().flatten().unwrap_or(LevelFilter::Off) +} + +impl Log for Capture { + fn enabled(&self, metadata: &Metadata) -> bool { + match MODE.load(Ordering::Acquire) { + MODE_THREAD => metadata.level() <= thread_level(), + MODE_GLOBAL => metadata.level() as u64 <= GLOBAL_STATE.load(Ordering::Acquire) & LEVEL_MASK, + _ => false, + } + } + + fn log(&self, record: &Record) { + let level = record.level(); + // Each message is formatted before any capture state is borrowed or locked, so a + // `Display` implementation that logs does not find that state in use. + match MODE.load(Ordering::Acquire) { + MODE_THREAD => { + if level > thread_level() { + return; + } + let captured = capture(record); + let _ = SCOPE.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() + && let Some(scope) = s.as_mut() + && level <= scope.level + { + scope.buffer.push(captured); + } + }); + } + MODE_GLOBAL => { + let state = GLOBAL_STATE.load(Ordering::Acquire); + if level as u64 > state & LEVEL_MASK { + return; + } + let captured = capture(record); + let mut buffer = lock(&GLOBAL); + if buffer.alive && buffer.session == state >> LEVEL_BITS { + buffer.push(captured); + } + } + _ => {} + } + } + + fn flush(&self) {} +} + +/// Installs the logger in `mode` if no mode is set, then raises the global maximum level to +/// `level`. Nothing changes when the logger cannot be installed or the mode differs. +fn install(mode: u8, level: LevelFilter) -> Result<(), CaptureError> { + let _guard = lock(&INSTALL); + match MODE.load(Ordering::Acquire) { + MODE_NONE => { + ::log::set_logger(&CAPTURE).map_err(|_| CaptureError::LoggerAlreadySet)?; + MODE.store(mode, Ordering::Release); + } + m if m == mode => {} + _ => return Err(CaptureError::ModeConflict), + } + if ::log::max_level() < level { + ::log::set_max_level(level); + } + Ok(()) +} + +/// Clears this thread's capture when dropped, including during a panic in the captured closure. +struct ScopeGuard; + +impl Drop for ScopeGuard { + fn drop(&mut self) { + let _ = SCOPE.try_with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + *s = None; + } + }); + } +} + +/// `f`'s result and the records at `level` or more severe that the calling thread logged while +/// `f` ran. +/// +/// Records logged on other threads are not captured. Returns an error without running `f` when +/// another logger is installed, when this process captures process wide, or when a capture is +/// already running on this thread. Returns [`CaptureError::Overflow`] after `f` has run when it +/// logged more than the limits allow; `f`'s result is dropped in that case. +/// +/// If `f` panics, the capture ends and the panic continues. +pub fn records(level: LevelFilter, f: impl FnOnce() -> T) -> Result<(T, Vec), CaptureError> { + let running = SCOPE.try_with(|s| s.try_borrow().map_or(true, |s| s.is_some())).unwrap_or(true); + if running { + return Err(CaptureError::NestedCapture); + } + install(MODE_THREAD, level)?; + let started = SCOPE + .try_with(|s| match s.try_borrow_mut() { + Ok(mut s) if s.is_none() => { + *s = Some(Scope { level, buffer: Buffer::new() }); + true + } + _ => false, + }) + .unwrap_or(false); + if !started { + return Err(CaptureError::NestedCapture); + } + let guard = ScopeGuard; + let out = f(); + let taken = + SCOPE.try_with(|s| s.try_borrow_mut().ok().and_then(|mut s| s.take()).map(|mut s| s.buffer.take())).ok().flatten().unwrap_or(Ok(Vec::new())); + drop(guard); + taken.map(|records| (out, records)) +} + +/// `f`'s result and the messages of the warnings and errors the calling thread logged while `f` +/// ran. +/// +/// The same as [`records`] at `LevelFilter::Warn`, keeping only each record's message. +pub fn warnings(f: impl FnOnce() -> T) -> Result<(T, Vec), CaptureError> { + records(LevelFilter::Warn, f).map(|(out, records)| (out, records.into_iter().map(|r| r.message).collect())) +} + +/// Starts capturing the records at `level` or more severe that any thread logs. +/// +/// Returns an error when another logger is installed, when this process captures per thread, or +/// when another [`GlobalCapture`] is alive. Dropping the handle stops the capture and discards +/// the records it holds; the logger stays installed, and a later call starts a new capture. +pub fn capture_global(level: LevelFilter) -> Result { + let mut buffer = lock(&GLOBAL); + if buffer.alive { + return Err(CaptureError::GlobalCaptureActive); + } + install(MODE_GLOBAL, level)?; + let session = buffer.session.wrapping_add(1) & (u64::MAX >> LEVEL_BITS); + *buffer = Buffer { alive: true, session, ..Buffer::new() }; + GLOBAL_STATE.store((session << LEVEL_BITS) | level as u64, Ordering::Release); + Ok(GlobalCapture { _private: () }) +} + +/// A live process-wide capture. See [`capture_global`]. +#[derive(Debug)] +pub struct GlobalCapture { + _private: (), +} + +impl GlobalCapture { + /// The records captured on every thread since the capture started or since the last drain, in + /// the order they reached the capture. + /// + /// Returns [`CaptureError::Overflow`] when records were dropped in that interval; the records + /// kept in that interval are then discarded, and the next interval starts empty. + pub fn drain(&self) -> Result, CaptureError> { + lock(&GLOBAL).take() + } +} + +impl Drop for GlobalCapture { + fn drop(&mut self) { + let mut buffer = lock(&GLOBAL); + let session = buffer.session; + GLOBAL_STATE.store(session << LEVEL_BITS, Ordering::Release); + *buffer = Buffer { session, ..Buffer::new() }; + } +} diff --git a/crates/testkit/tests/log_foreign.rs b/crates/testkit/tests/log_foreign.rs new file mode 100644 index 0000000000..24650a83a0 --- /dev/null +++ b/crates/testkit/tests/log_foreign.rs @@ -0,0 +1,33 @@ +//! Capture in a process where another logger was installed first. +#![cfg(not(target_arch = "wasm32"))] + +use craft_testkit::log::{CaptureError, capture_global, records, warnings}; +use log::{LevelFilter, Log, Metadata, Record}; + +struct Foreign; + +impl Log for Foreign { + fn enabled(&self, _: &Metadata) -> bool { + true + } + + fn log(&self, _: &Record) {} + + fn flush(&self) {} +} + +static FOREIGN: Foreign = Foreign; + +#[test] +fn every_capture_is_refused_and_nothing_changes() { + // The first call installs the foreign logger; this is the only test in the binary. + log::set_logger(&FOREIGN).expect("install the foreign logger"); + log::set_max_level(LevelFilter::Error); + + let mut ran = false; + assert_eq!(warnings(|| ran = true).map(|_| ()), Err(CaptureError::LoggerAlreadySet)); + assert_eq!(records(LevelFilter::Trace, || ran = true).map(|_| ()), Err(CaptureError::LoggerAlreadySet)); + assert_eq!(capture_global(LevelFilter::Trace).map(|_| ()), Err(CaptureError::LoggerAlreadySet)); + assert!(!ran, "a refused capture must not run its closure"); + assert_eq!(log::max_level(), LevelFilter::Error); +} diff --git a/crates/testkit/tests/log_global.rs b/crates/testkit/tests/log_global.rs new file mode 100644 index 0000000000..4345c2a2ce --- /dev/null +++ b/crates/testkit/tests/log_global.rs @@ -0,0 +1,123 @@ +//! Process-wide capture, in a binary without the test harness so the cases run one after another +//! on the main thread, as a `harness = false` consumer runs them. The process captures process +//! wide from the first case on. The module is native only, so on `wasm32` the binary runs nothing. + +fn main() { + // nextest lists custom-harness tests with `--list`; this binary is one test. + if std::env::args().any(|a| a == "--list") { + println!("log_global: test"); + return; + } + #[cfg(not(target_arch = "wasm32"))] + cases::run(); +} + +#[cfg(not(target_arch = "wasm32"))] +mod cases { + use std::fmt; + use std::sync::mpsc::{self, Receiver, Sender}; + + use craft_testkit::log::{CaptureError, CapturedRecord, MAX_RECORDS, capture_global, records, warnings}; + use log::{Level, LevelFilter}; + + pub fn run() { + a_record_from_another_thread_is_drained(); + the_level_filters_and_a_drain_empties_the_capture(); + a_second_live_capture_is_refused_and_a_new_one_starts_after_drop(); + a_record_checked_against_one_capture_is_not_kept_by_the_next(); + an_undrained_capture_reports_what_it_dropped(); + a_capture_does_not_lower_a_raised_maximum_level(); + per_thread_captures_are_refused_in_a_process_wide_process(); + println!("log_global: 7 cases passed"); + } + + fn a_record_from_another_thread_is_drained() { + let capture = capture_global(LevelFilter::Warn).expect("capture"); + std::thread::Builder::new() + .name("audio".into()) + .spawn(|| log::warn!(target: "clap_host", "editor dropped off the main thread")) + .expect("spawn") + .join() + .expect("join"); + assert_eq!( + capture.drain().expect("drain"), + [CapturedRecord { level: Level::Warn, target: "clap_host".into(), message: "editor dropped off the main thread".into() }] + ); + } + + fn the_level_filters_and_a_drain_empties_the_capture() { + let capture = capture_global(LevelFilter::Info).expect("capture"); + log::debug!("below info"); + log::info!("info"); + log::error!("error"); + let messages: Vec = capture.drain().expect("drain").into_iter().map(|r| r.message).collect(); + assert_eq!(messages, ["info", "error"]); + assert!(capture.drain().expect("second drain").is_empty()); + } + + fn a_second_live_capture_is_refused_and_a_new_one_starts_after_drop() { + let first = capture_global(LevelFilter::Warn).expect("capture"); + log::warn!("held by the first capture"); + assert_eq!(capture_global(LevelFilter::Warn).map(|_| ()), Err(CaptureError::GlobalCaptureActive)); + drop(first); + log::warn!("between captures"); + let second = capture_global(LevelFilter::Warn).expect("a new capture after drop"); + log::warn!("held by the second capture"); + let messages: Vec = second.drain().expect("drain").into_iter().map(|r| r.message).collect(); + assert_eq!(messages, ["held by the second capture"]); + } + + /// Signals on `started` when formatting begins, then waits on `go` before writing its text. + struct Gate { + started: Sender<()>, + go: Receiver<()>, + } + + impl fmt::Display for Gate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.started.send(()).expect("signal the start"); + self.go.recv().expect("wait for go"); + f.write_str("checked against the first capture") + } + } + + fn a_record_checked_against_one_capture_is_not_kept_by_the_next() { + let first = capture_global(LevelFilter::Warn).expect("capture"); + let (started_tx, started_rx) = mpsc::channel(); + let (go_tx, go_rx) = mpsc::channel(); + let gate = Gate { started: started_tx, go: go_rx }; + let logger = std::thread::spawn(move || log::warn!("{gate}")); + started_rx.recv().expect("formatting started"); + drop(first); + let second = capture_global(LevelFilter::Warn).expect("a new capture"); + go_tx.send(()).expect("release the formatter"); + logger.join().expect("join"); + assert!(second.drain().expect("drain").is_empty()); + } + + fn an_undrained_capture_reports_what_it_dropped() { + let capture = capture_global(LevelFilter::Warn).expect("capture"); + for i in 0..MAX_RECORDS + 2 { + log::warn!("{i}"); + } + assert_eq!(capture.drain(), Err(CaptureError::Overflow { dropped: 2 })); + log::warn!("after the overflow"); + let messages: Vec = capture.drain().expect("drain after an overflow").into_iter().map(|r| r.message).collect(); + assert_eq!(messages, ["after the overflow"]); + } + + fn a_capture_does_not_lower_a_raised_maximum_level() { + log::set_max_level(LevelFilter::Trace); + let capture = capture_global(LevelFilter::Warn).expect("capture"); + log::info!("below warn"); + assert_eq!(log::max_level(), LevelFilter::Trace); + assert!(capture.drain().expect("drain").is_empty()); + } + + fn per_thread_captures_are_refused_in_a_process_wide_process() { + let mut ran = false; + assert_eq!(warnings(|| ran = true).map(|_| ()), Err(CaptureError::ModeConflict)); + assert_eq!(records(LevelFilter::Trace, || ran = true).map(|_| ()), Err(CaptureError::ModeConflict)); + assert!(!ran, "a refused capture must not run its closure"); + } +} diff --git a/crates/testkit/tests/log_thread.rs b/crates/testkit/tests/log_thread.rs new file mode 100644 index 0000000000..9c472f806d --- /dev/null +++ b/crates/testkit/tests/log_thread.rs @@ -0,0 +1,141 @@ +//! Per-thread capture. Every test in this binary captures per thread, so the logger runs in that +//! mode for the whole process. +#![cfg(not(target_arch = "wasm32"))] + +use std::fmt; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use craft_testkit::log::{CaptureError, CapturedRecord, MAX_BYTES, MAX_RECORDS, capture_global, records, warnings}; +use log::{Level, LevelFilter}; + +#[test] +fn warnings_returns_the_result_and_the_warnings_and_errors() { + let (out, lines) = warnings(|| { + log::info!("not a warning"); + log::warn!("kept {} of {}", 3, 4); + log::error!("an error"); + log::debug!("not a warning either"); + 7 + }) + .expect("capture"); + assert_eq!(out, 7); + assert_eq!(lines, ["kept 3 of 4", "an error"]); +} + +#[test] +fn records_keep_level_and_target_at_the_requested_level() { + let ((), got) = records(LevelFilter::Info, || { + log::info!(target: "craft::test", "opened"); + log::debug!("dropped"); + log::warn!("short"); + }) + .expect("capture"); + assert_eq!( + got, + [ + CapturedRecord { level: Level::Info, target: "craft::test".into(), message: "opened".into() }, + CapturedRecord { level: Level::Warn, target: module_path!().into(), message: "short".into() }, + ] + ); +} + +// No test in this binary raises the maximum level above `Info`, so the nested-capture test can +// check that a refused `Trace` capture leaves it below `Trace`. + +#[test] +fn a_capture_does_not_lower_a_raised_maximum_level() { + log::set_max_level(LevelFilter::Info); + let ((), lines) = warnings(|| log::info!("below warn")).expect("capture"); + assert!(lines.is_empty()); + assert_eq!(log::max_level(), LevelFilter::Info); +} + +#[test] +fn a_nested_capture_is_refused_and_the_outer_one_keeps_its_records() { + let ran = AtomicBool::new(false); + let (inner, lines) = warnings(|| { + log::warn!("before"); + let inner = warnings(|| ran.store(true, Ordering::SeqCst)); + let deeper = records(LevelFilter::Trace, || ran.store(true, Ordering::SeqCst)); + log::warn!("after"); + (inner.map(|_| ()), deeper.map(|_| ())) + }) + .expect("outer capture"); + assert_eq!(inner, (Err(CaptureError::NestedCapture), Err(CaptureError::NestedCapture))); + assert!(!ran.load(Ordering::SeqCst), "a nested closure must not run"); + assert!(log::max_level() < LevelFilter::Trace, "a refused capture must not raise the maximum level"); + assert_eq!(lines, ["before", "after"]); +} + +#[test] +fn a_panic_ends_the_capture_and_the_next_one_starts_empty() { + let caught = catch_unwind(AssertUnwindSafe(|| { + warnings(|| { + log::warn!("left behind"); + panic!("closure failed"); + }) + })); + assert!(caught.is_err()); + let ((), lines) = warnings(|| log::warn!("next")).expect("a new capture after the panic"); + assert_eq!(lines, ["next"]); +} + +#[test] +fn records_from_other_threads_are_not_captured() { + let ((), lines) = warnings(|| { + std::thread::spawn(|| log::warn!("elsewhere")).join().expect("join"); + log::warn!("here"); + }) + .expect("capture"); + assert_eq!(lines, ["here"]); +} + +#[test] +fn records_over_the_count_limit_are_reported() { + let got = warnings(|| { + for i in 0..=MAX_RECORDS { + log::warn!("{i}"); + } + }); + assert_eq!(got.map(|_| ()), Err(CaptureError::Overflow { dropped: 1 })); + let ((), lines) = warnings(|| log::warn!("fits")).expect("a new capture after an overflow"); + assert_eq!(lines, ["fits"]); +} + +#[test] +fn a_message_over_the_byte_limit_is_reported() { + let long = "x".repeat(MAX_BYTES); + let got = warnings(|| { + log::warn!("short"); + log::warn!("{long}"); + }); + assert_eq!(got.map(|_| ()), Err(CaptureError::Overflow { dropped: 1 })); +} + +/// Writes one byte at a time until a write fails, counting the writes that succeed. +struct Endless<'a>(&'a AtomicUsize); + +impl fmt::Display for Endless<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for _ in 0..2 * MAX_BYTES { + f.write_str("x")?; + self.0.fetch_add(1, Ordering::SeqCst); + } + Ok(()) + } +} + +#[test] +fn formatting_a_message_stops_at_the_byte_limit() { + let written = AtomicUsize::new(0); + let got = warnings(|| log::warn!("{}", Endless(&written))); + assert_eq!(got.map(|_| ()), Err(CaptureError::Overflow { dropped: 1 })); + assert_eq!(written.load(Ordering::SeqCst), MAX_BYTES); +} + +#[test] +fn a_global_capture_is_refused_in_a_per_thread_process() { + warnings(|| ()).expect("per-thread capture installs the logger"); + assert_eq!(capture_global(LevelFilter::Warn).map(|_| ()), Err(CaptureError::ModeConflict)); +} From fc7882fc961a61ca94d4f64458afd61197de14da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:23:26 -0800 Subject: [PATCH 2/3] craft-testkit: describe where formatting a log message stops at the byte limit Formatting stops at the first write that would take the message past MAX_BYTES, so a message never passes the limit. --- crates/testkit/README.md | 2 +- crates/testkit/src/log.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 04f98831e8..1d238ccb40 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -32,7 +32,7 @@ The `log` feature adds `craft_testkit::log` and the `log` dependency. The module A capture raises `log::max_level()` to the level it asks for and never lowers it. When the closure panics, the capture on that thread ends and the panic continues. Records from other threads do not appear in a per-thread capture. -A capture keeps at most `MAX_RECORDS` (4,096) records and `MAX_BYTES` (1 MiB) of message and target text. Formatting a message stops once it passes `MAX_BYTES`. A record over either limit is dropped and counted, and the capture returns `CaptureError::Overflow { dropped }` instead of a partial list. For `drain`, the limits apply to each interval between drains. +A capture keeps at most `MAX_RECORDS` (4,096) records and `MAX_BYTES` (1 MiB) of message and target text. Formatting a message stops at the first write that would take it past `MAX_BYTES`. A record over either limit is dropped and counted, and the capture returns `CaptureError::Overflow { dropped }` instead of a partial list. For `drain`, the limits apply to each interval between drains. Run process-wide captures in a binary of their own, for example a `[[test]]` with `harness = false`: diff --git a/crates/testkit/src/log.rs b/crates/testkit/src/log.rs index 2b672c1aeb..d48410391f 100644 --- a/crates/testkit/src/log.rs +++ b/crates/testkit/src/log.rs @@ -18,9 +18,9 @@ //! capture filters by its own level. //! //! A capture keeps at most [`MAX_RECORDS`] records and [`MAX_BYTES`] bytes of message and target -//! text. Formatting a message stops once it passes [`MAX_BYTES`]. A record over either limit is -//! dropped and counted, and the capture then returns [`CaptureError::Overflow`] with the number -//! dropped instead of a partial list. +//! text. Formatting a message stops at the first write that would take it past [`MAX_BYTES`]. A +//! record over either limit is dropped and counted, and the capture then returns +//! [`CaptureError::Overflow`] with the number dropped instead of a partial list. use std::cell::RefCell; use std::fmt; From 1f31eede1c2d694d979f8ec521a8861a696341d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 05:49:15 -0800 Subject: [PATCH 3/3] testkit: define the function the capture example calls The README's process-wide capture example called drop_the_plugin without defining it, so a copied test did not compile. The example now defines it as a function that logs a warning containing the text the assertion looks for. --- crates/testkit/README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index d32341f017..94e1c0c4fa 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -284,11 +284,15 @@ A capture keeps at most `MAX_RECORDS` (4,096) records and `MAX_BYTES` (1 MiB) of Run process-wide captures in a binary of their own, for example a `[[test]]` with `harness = false`: ```rust +fn drop_the_plugin() { + log::warn!("plugin dropped off the main thread"); +} + fn main() { let capture = craft_testkit::log::capture_global(log::LevelFilter::Warn).expect("capture"); std::thread::Builder::new() .name("audio".into()) - .spawn(|| drop_the_plugin()) + .spawn(drop_the_plugin) .expect("spawn") .join() .expect("join");