static TEST_ENV_MUTEX: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
thread_local! {
static TEST_ENV_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static TEST_ENV_HELD: std::cell::RefCell<Option<std::sync::MutexGuard<'static, ()>>> =
const { std::cell::RefCell::new(None) };
}
#[track_caller]
pub fn test_env_lock() -> TestEnvGuard {
#[cfg(any(test, feature = "test-support"))]
refuse_in_batch();
let mutex = TEST_ENV_MUTEX.get_or_init(|| std::sync::Mutex::new(()));
TEST_ENV_DEPTH.with(|depth| {
if depth.get() == 0 {
let guard = mutex
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
TEST_ENV_HELD.with(|held| *held.borrow_mut() = Some(guard));
}
depth.set(depth.get() + 1);
});
TestEnvGuard {
_not_send_sync: std::marker::PhantomData,
}
}
#[cfg(any(test, feature = "test-support"))]
pub const TEST_BATCH_ENV: &str = "LEAN_CTX_TEST_BATCH";
#[cfg(any(test, feature = "test-support"))]
#[track_caller]
fn refuse_in_batch() {
let Some(log) = std::env::var_os(TEST_BATCH_ENV) else {
return;
};
let test = std::thread::current()
.name()
.unwrap_or("<unnamed thread>")
.to_owned();
let caller = std::panic::Location::caller();
if let Ok(mut file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&log)
{
use std::io::Write as _;
let line = format!("{test}\t{}:{}\n", caller.file(), caller.line());
let _ = file.write_all(line.as_bytes());
}
panic!(
"{test}: takes test_env_lock, so it needs a process of its own; \
the batched run ({TEST_BATCH_ENV}) re-runs it alone"
);
}
#[cfg(any(test, feature = "test-support"))]
pub fn holds_test_env_lock() -> bool {
TEST_ENV_DEPTH.with(|depth| depth.get() > 0)
}
pub struct TestEnvGuard {
_not_send_sync: std::marker::PhantomData<*const ()>,
}
impl Drop for TestEnvGuard {
fn drop(&mut self) {
TEST_ENV_DEPTH.with(|depth| {
let next = depth.get().saturating_sub(1);
depth.set(next);
if next == 0 {
TEST_ENV_HELD.with(|held| *held.borrow_mut() = None);
}
});
}
}
#[cfg(any(test, feature = "test-support"))]
pub fn set_var<K: AsRef<std::ffi::OsStr>, V: AsRef<std::ffi::OsStr>>(key: K, value: V) {
assert_lock_held();
unsafe { std::env::set_var(key, value) };
}
#[cfg(any(test, feature = "test-support"))]
pub fn remove_var<K: AsRef<std::ffi::OsStr>>(key: K) {
assert_lock_held();
unsafe { std::env::remove_var(key) };
}
#[cfg(any(test, feature = "test-support"))]
fn assert_lock_held() {
assert!(
holds_test_env_lock(),
"test environment mutation requires the current thread to hold test_env_lock()"
);
}
#[cfg(test)]
mod tests {
use super::{TEST_BATCH_ENV, test_env_lock};
const NAME: &str = "env_lock::tests::batch_tripwire_records_and_refuses";
#[test]
fn batch_tripwire_records_and_refuses() {
if std::env::var_os(TEST_BATCH_ENV).is_some() {
let _guard = test_env_lock();
unreachable!("test_env_lock returned inside a batched run");
}
let dir = tempfile::tempdir().expect("tempdir");
let log = dir.path().join("env-lock.log");
let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
.args([NAME, "--exact", "--test-threads=1"])
.env(TEST_BATCH_ENV, &log)
.output()
.expect("run the child test");
assert!(!output.status.success(), "the child must fail");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("needs a process of its own"), "{stdout}");
let recorded = std::fs::read_to_string(&log).expect("tripwire log");
let (thread, caller) = recorded
.trim_end()
.split_once('\t')
.expect("a `<thread>\\t<caller>` line");
assert!(
thread.ends_with("batch_tripwire_records_and_refuses"),
"libtest names the thread after the test: {recorded}"
);
assert!(caller.contains("env_lock.rs:"), "{recorded}");
}
}