Files
craft-libs/crates/testkit/tests/log_foreign.rs
T
dotCooCoo 3a40898a42 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.
2026-11-14 11:43:03 -08:00

34 lines
1.1 KiB
Rust

//! 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);
}