1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
//! Minimal capturing logger: installed once per process (`log::set_logger` is
//! once-per-process); records every message so tests assert by unique marker.
//!
//! Records are append-only and never erased: each test takes a [`mark`] and scans
//! only records emitted after it via [`contains_since`], so a stale record from an
//! earlier test (e.g. a same-shape marker under OS pid reuse) can never satisfy an
//! assertion, and no test can erase another's records.
use std::sync::{Condvar, Mutex, OnceLock};
use std::thread::ThreadId;
struct CaptureLog;
static RECORDS: Mutex<Vec<(log::Level, String, ThreadId)>> = Mutex::new(Vec::new());
/// Signalled at every record, for [`wait_for_since`].
static RECORDED: Condvar = Condvar::new();
static INSTALLED: OnceLock<()> = OnceLock::new();
impl log::Log for CaptureLog {
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
true
}
fn log(&self, record: &log::Record<'_>) {
RECORDS
.lock()
.unwrap()
.push((record.level(), record.args().to_string(), std::thread::current().id()));
RECORDED.notify_all();
}
fn flush(&self) {}
}
pub(crate) fn install() {
INSTALLED.get_or_init(|| {
log::set_logger(&CaptureLog).expect("first logger in this test process");
log::set_max_level(log::LevelFilter::Trace);
});
}
/// Current end of the record buffer — scan from here with [`contains_since`].
pub(crate) fn mark() -> usize {
RECORDS.lock().unwrap().len()
}
/// True if any record emitted at or after `mark` contains `marker`. Never panics:
/// records are append-only, so `mark` (a past length) is always in bounds.
pub(crate) fn contains_since(mark: usize, marker: &str) -> bool {
RECORDS.lock().unwrap()[mark..]
.iter()
.any(|(_, m, _)| m.contains(marker))
}
/// Blocks until a record emitted at or after `mark` contains `marker`, and returns its text. The wait is on
/// the log's own condition: no time is chosen, so a record that never comes holds the caller.
#[cfg(all(test, windows, feature = "tokio"))]
pub(crate) fn wait_for_since(mark: usize, marker: &str) -> String {
let records = RECORDS.lock().unwrap();
let records = RECORDED
.wait_while(records, |records| {
!records[mark..].iter().any(|(_, m, _)| m.contains(marker))
})
.unwrap();
let (_, text, _) = records[mark..]
.iter()
.find(|(_, m, _)| m.contains(marker))
.expect("the wait ended on this record");
text.clone()
}
/// The text of every record emitted at or after `mark` that contains `marker`.
pub(crate) fn records_since(mark: usize, marker: &str) -> Vec<String> {
RECORDS.lock().unwrap()[mark..]
.iter()
.filter(|(_, m, _)| m.contains(marker))
.map(|(_, m, _)| m.clone())
.collect()
}
/// The levels of every record emitted at or after `mark` that contains `marker`.
///
/// A level is part of a log record's meaning, not decoration: it is what decides whether an
/// embedder's sink shows the message by default. Assertions about "this condition must not be
/// narrated at `warn`" are therefore assertions about the level, which [`contains_since`]
/// cannot see.
pub(crate) fn levels_since(mark: usize, marker: &str) -> Vec<log::Level> {
RECORDS.lock().unwrap()[mark..]
.iter()
.filter(|(_, m, _)| m.contains(marker))
.map(|(level, _, _)| *level)
.collect()
}
/// Pins a test's log output: no record at `Warn` or worse may be emitted while it lives. Declare it
/// FIRST in a test, so it drops last, after the test's children have been torn down and their
/// teardown has logged. Skipped while the test is already panicking, so it never masks the real
/// failure. Mirrors `tests/common`'s `WarnWatch` (minus its `expecting`, which no test here needs),
/// which a separate compilation unit cannot share.
///
/// Reads the process-wide capture from its creation on, so it assumes one test per process (what
/// nextest runs).
#[must_use = "the watch asserts when dropped; bind it to a named `_watch`, not `_`"]
pub(crate) struct WarnWatch {
mark: usize,
}
/// A [`WarnWatch`] over the records from now on. Installs the capture.
pub(crate) fn warn_watch() -> WarnWatch {
install();
WarnWatch { mark: mark() }
}
impl Drop for WarnWatch {
fn drop(&mut self) {
if std::thread::panicking() {
return;
}
let warnings: Vec<String> = RECORDS.lock().unwrap()[self.mark..]
.iter()
.filter(|(level, _, _)| *level <= log::Level::Warn)
.map(|(_, m, _)| m.clone())
.collect();
assert!(
warnings.is_empty(),
"unexpected warning(s) at Warn or above: {warnings:#?}"
);
}
}
/// Like [`records_since`], but only records emitted by the CALLING thread. For a marker that is
/// a constant message prefix shared by every test in the process, this is what keeps a
/// concurrently-running test's identical record from satisfying (or breaking) the assertion.
#[cfg(test)]
pub(crate) fn records_since_on_current_thread(mark: usize, marker: &str) -> Vec<(log::Level, String)> {
let me = std::thread::current().id();
RECORDS.lock().unwrap()[mark..]
.iter()
.filter(|(_, m, t)| *t == me && m.contains(marker))
.map(|(level, m, _)| (*level, m.clone()))
.collect()
}
/// The text of every record at `Warn` or worse that the CALLING thread logged since `mark` and
/// that contains `marker`. Pass `""` for every such record.
#[cfg(test)]
pub(crate) fn warns_since(mark: usize, marker: &str) -> Vec<String> {
let me = std::thread::current().id();
RECORDS.lock().unwrap()[mark..]
.iter()
.filter(|(level, m, t)| *t == me && *level <= log::Level::Warn && m.contains(marker))
.map(|(_, m, _)| m.clone())
.collect()
}
#[cfg(test)]
#[path = "log_capture_tests.rs"]
mod log_capture_tests;