use std::ffi::OsStr;
use std::io::Write as _;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};
pub(crate) const MARKER: &str = ".oakum-unit-fixture";
pub(crate) const LEDGER: &str = "fixture-leaks.log";
const RETAIN: &str = "OAKUM_TEST_RETAIN";
fn base() -> PathBuf {
match option_env!("CARGO_TARGET_TMPDIR") {
Some(dir) => PathBuf::from(dir),
None => {
if let Some(dir) = option_env!("OAKUM_TARGET_TMP") {
PathBuf::from(dir)
} else {
panic!("unit fixtures need OAKUM_TARGET_TMP from crates/oakum/build.rs");
}
}
}
}
pub(crate) struct Fixture {
container: PathBuf,
root: PathBuf,
}
impl Fixture {
pub(crate) fn new(suite: &str, label: &str) -> Self {
static SEQ: AtomicU32 = AtomicU32::new(0);
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
let container = base().join(format!(
"oakum-{suite}-{label}-{}-{seq}",
std::process::id()
));
std::fs::create_dir_all(base()).expect("fixture base");
match std::fs::create_dir(&container) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => panic!(
"fixture container {} already exists: a previous run leaked it, \
so remove that directory before rerunning",
container.display()
),
Err(err) => panic!("fixture container {}: {err}", container.display()),
}
let root = container.join(label);
std::fs::create_dir_all(&root).expect("fixture root");
std::fs::write(container.join(MARKER), "").expect("fixture marker");
Self { container, root }
}
pub(crate) fn container(&self) -> &Path {
&self.container
}
}
impl Deref for Fixture {
type Target = Path;
fn deref(&self) -> &Path {
&self.root
}
}
impl AsRef<Path> for Fixture {
fn as_ref(&self) -> &Path {
&self.root
}
}
impl AsRef<OsStr> for Fixture {
fn as_ref(&self) -> &OsStr {
self.root.as_os_str()
}
}
impl Drop for Fixture {
fn drop(&mut self) {
if std::env::var_os(RETAIN).is_some_and(|value| !value.is_empty() && value != "0") {
eprintln!("{RETAIN}: kept {}", self.container.display());
return;
}
let err = match std::fs::remove_dir_all(&self.container) {
Ok(()) => return,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return,
Err(err) => err,
};
let diagnosis = leak_diagnosis(&self.container);
let restored = std::fs::write(self.container.join(MARKER), "");
let recorded = record_leak(&self.container, &format!("{err} — {diagnosis}"));
eprintln!(
"fixture leak: {} — {err} — {diagnosis}",
self.container.display()
);
if let Err(marker_err) = &restored {
eprintln!("fixture marker not restored, so the gate is blind: {marker_err}");
}
if let Err(ledger_err) = &recorded {
eprintln!("fixture ledger unwritable: {ledger_err}");
}
assert!(
std::thread::panicking(),
"fixture leak: {} — {err} — {diagnosis}",
self.container.display()
);
}
}
fn record_leak(container: &Path, reason: &str) -> std::io::Result<()> {
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(base().join(LEDGER))?
.write_all(format!("{}\t{reason}\n", container.display()).as_bytes())
}
mod leak_diagnosis;
pub(crate) use leak_diagnosis::leak_diagnosis;
#[cfg(unix)]
fn dac_enforced() -> Result<bool, String> {
use std::os::unix::fs::PermissionsExt as _;
let root = Fixture::new("dac", "probe");
let chmod = |mode: u32| -> Result<u32, String> {
let mut perms = std::fs::metadata(&root)
.map_err(|err| format!("stat {}: {err}", root.display()))?
.permissions();
let before = perms.mode();
perms.set_mode(mode);
std::fs::set_permissions(&root, perms)
.map_err(|err| format!("chmod {} to {mode:o}: {err}", root.display()))?;
Ok(before)
};
let original_mode = chmod(0o555)?;
let refused = match std::fs::write(root.join("probe"), "") {
Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => true,
Err(err) => return Err(format!("write into {}: {err}", root.display())),
Ok(()) => false,
};
chmod(original_mode)?;
Ok(refused)
}
#[cfg(unix)]
fn refusal_cause(probe: Result<bool, String>) -> String {
match probe {
Ok(true) => String::new(),
Ok(false) => {
String::from(" because DAC is not enforced for this process (running as root?)")
}
Err(failure) => format!("; the DAC probe could not tell why ({failure})"),
}
}
#[cfg(unix)]
#[allow(
dead_code,
reason = "used by the cli's unit tests, which only the bin target compiles"
)]
#[track_caller]
pub(crate) fn expect_refused<T, E>(result: Result<T, E>, what: &str) -> E {
let Err(err) = result else {
panic!(
"{what}: expected a refusal, but the operation landed{}",
refusal_cause(dac_enforced())
)
};
err
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
#[cfg(unix)]
use super::refusal_cause;
use super::{base, Fixture, LEDGER, MARKER};
#[cfg(unix)]
#[test]
fn a_landed_refusal_names_what_the_probe_found() {
assert_eq!(refusal_cause(Ok(true)), "");
assert_eq!(
refusal_cause(Ok(false)),
" because DAC is not enforced for this process (running as root?)"
);
assert_eq!(
refusal_cause(Err(String::from("chmod x to 555: EPERM"))),
"; the DAC probe could not tell why (chmod x to 555: EPERM)"
);
}
#[test]
fn a_dropped_fixture_removes_its_container() {
let container = {
let root = Fixture::new("unit", "dropped");
std::fs::write(root.join("file.txt"), "x").expect("write");
assert!(root.container().join(MARKER).is_file());
root.container().to_path_buf()
};
assert!(!container.exists(), "{} survived", container.display());
}
#[test]
fn a_panicking_test_still_removes_its_fixture() {
let seen = std::sync::Mutex::new(std::path::PathBuf::new());
let caught = std::panic::catch_unwind(|| {
let root = Fixture::new("unit", "panicking");
*seen.lock().expect("lock") = root.container().to_path_buf();
panic!("the fixture must not outlive this panic");
});
assert!(caught.is_err(), "the probe was supposed to panic");
let container = seen.lock().expect("lock").clone();
assert!(!container.as_os_str().is_empty(), "never built one");
assert!(!container.exists(), "{} survived", container.display());
}
#[cfg(unix)]
#[test]
fn a_container_that_cannot_be_removed_reaches_the_gate() {
use std::os::unix::fs::PermissionsExt as _;
let ledger_path = base().join(LEDGER);
let seen = std::sync::Mutex::new(PathBuf::new());
let blocked = std::sync::Mutex::new(PathBuf::new());
let reclaimed = std::panic::catch_unwind(|| {
let root = Fixture::new("unit", "unremovable");
*seen.lock().expect("lock") = root.container().to_path_buf();
let stuck = root.join("stuck");
std::fs::create_dir_all(stuck.join("child")).expect("stuck");
std::fs::set_permissions(&stuck, std::fs::Permissions::from_mode(0o555))
.expect("chmod");
*blocked.lock().expect("lock") = stuck;
});
let container = seen.lock().expect("lock").clone();
let recorded = std::fs::read_to_string(&ledger_path).unwrap_or_default();
let marked = container.join(MARKER).is_file();
let _ = std::fs::set_permissions(
&*blocked.lock().expect("lock"),
std::fs::Permissions::from_mode(0o755),
);
std::fs::remove_dir_all(&container)
.unwrap_or_else(|err| panic!("could not repair {}: {err}", container.display()));
assert!(reclaimed.is_err(), "a failed reclaim must fail its test");
assert!(
marked,
"{} kept no marker, so a lost ledger would hide it",
container.display()
);
assert!(
recorded.contains(&container.display().to_string()),
"the failed reclaim was not recorded: {recorded:?}"
);
}
#[test]
fn a_container_already_gone_is_not_reported() {
let ledger_path = base().join(LEDGER);
let container = {
let root = Fixture::new("unit", "vanished");
let container = root.container().to_path_buf();
std::fs::remove_dir_all(&container).expect("remove ahead of Drop");
container
};
let recorded = std::fs::read_to_string(&ledger_path).unwrap_or_default();
assert!(
!recorded.contains(&container.display().to_string()),
"an already-gone container was reported as a leak: {recorded:?}"
);
}
#[test]
fn the_same_label_twice_gets_two_containers() {
let one = Fixture::new("unit", "same");
let two = Fixture::new("unit", "same");
assert_ne!(one.container(), two.container());
assert!(one.is_dir() && two.is_dir());
}
#[test]
fn unit_fixtures_land_in_the_target_tmp() {
let expected = PathBuf::from(env!("OAKUM_TARGET_TMP"));
let root = Fixture::new("unit", "scoped");
assert!(
root.container().starts_with(&expected),
"{} is not under {}",
root.container().display(),
expected.display()
);
}
}