diff --git a/Cargo.lock b/Cargo.lock index a1c1d3fc35..4fb77126ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4368,6 +4368,7 @@ name = "craft-testkit" version = "0.1.0" dependencies = [ "libc", + "log", "png 0.18.1", "rustix 1.1.6", "serde_json", diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 76f47eac72..7ad434395b 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -18,12 +18,15 @@ mcp = ["dep:serde_json"] corpus = ["dep:sha2", "dep:libc"] # `font-coverage`: `skip::craft_fonts_cover`, which parses font data with skrifa. font-coverage = ["dep:skrifa"] +# `log`: capture of the records a test logs, per thread or process wide. +log = ["dep:log"] [dependencies] png = { version = "0.18", optional = true } sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +log = { workspace = true, optional = true } skrifa = { workspace = true, optional = true } tempfile = "3.20" toml = { version = "1", default-features = false, features = ["parse", "serde", "std"] } @@ -36,6 +39,19 @@ rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } [dev-dependencies] tempfile = "3" +[[test]] +name = "log_thread" +required-features = ["log"] + +[[test]] +name = "log_global" +harness = false +required-features = ["log"] + +[[test]] +name = "log_foreign" +required-features = ["log"] + [[test]] name = "mcp" required-features = ["mcp"] diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 3d352cc702..09f8d93bb7 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -267,6 +267,49 @@ let dir = craft_testkit::TempDir::new("export")?; std::fs::write(dir.file("out.png")?, &png)?; ``` +## 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 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`: + +```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) + .expect("spawn") + .join() + .expect("join"); + let records = capture.drain().expect("drain"); + assert!(records.iter().any(|r| r.message.contains("off the main thread"))); +} +``` + ## `image` feature `craft-testkit = { ..., features = ["image"] }` adds `craft_testkit::image` and `assert_similar!`. It depends on `png` 0.18. @@ -512,6 +555,13 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie | `private_dir` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` | `75a654f4f8` | | `TempDir` | storytold/cadcraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | `8e69890223` | +### log + +| Code | Repository | Path | SHA | +|---|---|---|---| +| `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` | + ### image | Code | Source | @@ -618,6 +668,14 @@ cases change, and keep the test names. | CADCraft | `crates/engine/tests/support/temp_dir.rs`, `crates/ui-egui/tests/support/temp_dir.rs` | Pending. Its `TempDir` empties a leftover folder of the same name; `temp` makes a new one. | | `craft-media-testkit` | `private_dir()` in `crates/media-testkit/src/lib.rs` | Pending. `private_dir()` is unchanged. | +### log + +| Consumer | Code it replaces | 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` | + ### image | Consumer | Today | State | diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index c579cad4bb..195486312a 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -38,6 +38,10 @@ //! truncation of it and those copies, one after another on a worker thread with a time limit for //! each, and fails the test with the case that panicked or did not finish. //! +//! 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. +//! //! On targets other than `wasm32`, `serial` holds `serial::TestLock`, a lock that a `static` //! can hold and that the thread holding it can take again, and `serial::gpu_lock`, the one lock //! for GPU tests. Every GPU test in a process must take this lock, because a test that takes a @@ -89,6 +93,8 @@ pub mod guards; pub mod hostile; #[cfg(feature = "image")] pub mod image; +#[cfg(all(feature = "log", not(target_arch = "wasm32")))] +pub mod log; #[cfg(all(feature = "mcp", not(target_arch = "wasm32")))] pub mod mcp; pub mod rng; diff --git a/crates/testkit/src/log.rs b/crates/testkit/src/log.rs new file mode 100644 index 0000000000..d48410391f --- /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 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; +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)); +}