blob: 9a805d0c5b3d7fed0aa353deda4cf672ba12a33b [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Unit tests for `select_cases`, `RunDirectory`, `CaseDirectory`, evidence
//! export, and subreaper grandchild reaping.
use super::*;
#[test]
fn select_cases_sorts_dedups_and_filters() {
let sorted = select_cases(&["z", "a", "m"], None).unwrap();
assert_eq!(sorted, ["a", "m", "z"]);
assert_eq!(select_cases(&["z", "a"], Some("z")).unwrap(), ["z"]);
assert!(select_cases(&["dup", "dup"], None).is_err());
assert!(select_cases(&["a/b"], None).is_err());
assert!(select_cases(&["a"], Some("missing")).is_err());
}
#[cfg(target_os = "linux")]
#[test]
fn case_directory_reaps_timed_out_grandchild_via_subreaper() {
let run = RunDirectory::new("subreaper-check", Duration::from_millis(1500)).unwrap();
let mut case = run.case("grandchild").unwrap();
let pid_file = case.path().join("grandchild.pid");
// Spawn a fresh `/bin/sh -c` grandchild that atomically publishes its
// own `$$` via temp-file rename and `exec`s `sleep 30` in-place so the
// PID file is always complete before the 1.5s deadline fires.
let inner = "echo $$ > \"$1.tmp\" && mv \"$1.tmp\" \"$1\" && exec sleep 30";
let script = format!("/bin/sh -c '{inner}' _ {:?} & wait", pid_file.to_str().unwrap(),);
let inv = Invocation::new("/bin/sh", &["-c", &script]).env("PATH", "/usr/bin:/bin");
let outcome = case.run(&inv).unwrap();
assert!(matches!(outcome.termination, Termination::TimedOut(_)));
let pid_text = fs::read_to_string(&pid_file)
.expect("grandchild pid file must be published before timeout");
let gpid: i32 = pid_text.trim().parse().expect("valid grandchild pid");
assert!(gpid > 0, "unexpected grandchild pid {gpid}");
// SAFETY: probing PID liveness with signal 0.
let alive = unsafe { libc::kill(gpid, 0) };
assert_eq!(alive, -1, "grandchild {gpid} survived case timeout");
assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::ESRCH));
}
#[test]
fn select_cases_and_validate_case_name_edge_cases() {
assert_eq!(select_cases(&["b", "a", "c"], None).unwrap(), ["a", "b", "c"]);
let empty_err = select_cases(&[], None).unwrap_err();
assert!(empty_err.contains("no integration cases selected"), "{empty_err}");
let miss_err = select_cases(&["z", "a"], Some("missing")).unwrap_err();
assert!(miss_err.contains("\"missing\"") && miss_err.contains("a, z"), "{miss_err}");
let run = RunDirectory::new("rev-validate", Duration::from_secs(2)).unwrap();
for bad in ["", ".", "..", "/abs", "a/b", "./a", "a/.", "sub/.."] {
assert!(select_cases(&[bad], None).is_err(), "select_cases accepted {bad:?}");
assert!(run.case(bad).is_err(), "run.case accepted {bad:?}");
}
assert!(run.case("a\0b").is_err());
}
#[test]
fn run_cases_metadata_preflight_and_panic_collection() {
let run = RunDirectory::new("rev-42", Duration::from_millis(2500)).unwrap();
let run_json: serde_json::Value =
serde_json::from_str(&fs::read_to_string(run.path().join("run.json")).unwrap()).unwrap();
assert_eq!(run_json["source_revision_supplied_by_caller"], "rev-42");
assert_eq!(run_json["original_run_root"], run.path().to_str().unwrap());
assert_eq!(run_json["process_timeout_seconds"], 2.5);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(fs::metadata(run.path()).unwrap().permissions().mode() & 0o777, 0o700);
}
assert_eq!(
run.run_cases(&["a"], 0, |_, _| Ok(())).unwrap_err(),
"case list and worker count must be nonempty"
);
assert_eq!(
run.run_cases(&[], 1, |_, _| Ok(())).unwrap_err(),
"case list and worker count must be nonempty"
);
let calls = AtomicUsize::new(0);
for bad in [&["dup", "dup"][..], &["ok", "bad/name"][..]] {
let err = run
.run_cases(bad, 2, |_, _| {
calls.fetch_add(1, Ordering::SeqCst);
Ok(())
})
.unwrap_err();
assert!(!err.is_empty());
assert_eq!(calls.load(Ordering::SeqCst), 0, "body ran despite invalid catalog {bad:?}");
}
assert!(!run.path().join("cases/ok").exists());
let err = run
.run_cases(&["c", "a", "b"], 2, |name, case| match name {
"a" => Err("err-a".into()),
"b" => panic!("boom"),
"c" => case.write("ok.txt", b"1"),
_ => unreachable!(),
})
.unwrap_err();
assert_eq!(err, "a: err-a\nb: case panicked");
assert_eq!(fs::read(run.path().join("cases/c/ok.txt")).unwrap(), b"1");
let seq_run = RunDirectory::new("rev-seq", Duration::from_secs(2)).unwrap();
let seq_err = seq_run.run_cases(&["z-fail", "a-fail"], 1, |n, _| Err(n.into())).unwrap_err();
assert_eq!(seq_err, "a-fail: a-fail\nz-fail: z-fail");
run.run_cases_owned(&["owned-z", "owned-a"], 2, |_, case| {
#[cfg(unix)]
{
let inv = Invocation::new("/bin/sh", &["-c", "true"]).env("PATH", "/usr/bin:/bin");
assert!(
matches!(case.run_shared(&inv)?.termination, Termination::Exited(s) if s.success())
);
}
case.write("id.txt", b"ok")
})
.unwrap();
assert_eq!(fs::read(run.path().join("cases/owned-a/id.txt")).unwrap(), b"ok");
#[cfg(unix)]
assert!(run.path().join("cases/owned-a/commands/0000").is_dir());
}
#[test]
fn case_write_and_copy_enforce_containment_disjointness_and_fresh_inodes() {
let outside = tempfile::tempdir().unwrap();
let out_dir = outside.path().join("out");
fs::create_dir_all(&out_dir).unwrap();
let src_file = outside.path().join("src.txt");
fs::write(&src_file, b"new").unwrap();
let hl_orig = outside.path().join("hl-orig.txt");
fs::write(&hl_orig, b"old").unwrap();
let run = RunDirectory::new("rev-copy", Duration::from_secs(2)).unwrap();
let case = run.case("c").unwrap();
for bad in ["", ".", "..", "/abs", "../esc"] {
assert!(case.write(bad, b"x").is_err(), "write accepted {bad:?}");
assert!(case.copy(&src_file, bad).is_err(), "copy accepted {bad:?}");
}
case.write("nested/sub/file.txt", b"hello").unwrap();
assert_eq!(fs::read(case.path().join("nested/sub/file.txt")).unwrap(), b"hello");
#[cfg(unix)]
{
use std::os::unix::fs::{MetadataExt, symlink};
symlink(&out_dir, case.path().join("link")).unwrap();
assert!(case.write("link/pwn.txt", b"x").is_err());
assert!(!out_dir.join("pwn.txt").exists());
assert!(case.copy(&src_file, "link/pwn.txt").is_err());
let sym_src = outside.path().join("sym-src");
symlink(&src_file, &sym_src).unwrap();
assert!(case.copy(&sym_src, "from-sym.txt").is_err());
let alias_case = outside.path().join("alias-case");
symlink(case.path(), &alias_case).unwrap();
let alias_err = case.copy(&alias_case.join("nested"), "nested").unwrap_err();
assert!(
alias_err.contains("fixture copy source and destination must be disjoint"),
"{alias_err}"
);
let sym_cases = RunDirectory::new("rev-sym-cases", Duration::from_secs(2)).unwrap();
symlink(&out_dir, sym_cases.path().join("cases")).unwrap();
assert!(sym_cases.case("escape").is_err());
assert!(!out_dir.join("escape").exists());
let dst_hl = case.path().join("dst-hl.txt");
fs::hard_link(&hl_orig, &dst_hl).unwrap();
let orig_ino = fs::metadata(&hl_orig).unwrap().ino();
case.copy(&src_file, "dst-hl.txt").unwrap();
assert_eq!(fs::read(&dst_hl).unwrap(), b"new");
assert_ne!(fs::metadata(&dst_hl).unwrap().ino(), orig_ino);
assert_eq!(fs::read(&hl_orig).unwrap(), b"old");
}
let self_err = case.copy(case.path(), "sub-self").unwrap_err();
assert!(
self_err.contains("fixture copy source and destination must be disjoint"),
"{self_err}"
);
assert!(!case.path().join("sub-self").exists());
case.write("sub/inner/a.txt", b"1").unwrap();
let child_dir_err = case.copy(&case.path().join("sub/inner"), "sub").unwrap_err();
assert!(
child_dir_err.contains("fixture copy source and destination must be disjoint"),
"{child_dir_err}"
);
assert!(!case.path().join("sub/a.txt").exists());
let child_file_err = case.copy(&case.path().join("sub/inner/a.txt"), "sub").unwrap_err();
assert!(
child_file_err.contains("fixture copy source and destination must be disjoint"),
"{child_file_err}"
);
}
#[test]
fn run_directory_finish_retention_and_export_boundaries() {
let diag = tempfile::tempdir().unwrap();
let ok_run = RunDirectory::new("rev-ok", Duration::from_secs(2)).unwrap();
let ok_root = ok_run.path().to_path_buf();
ok_run.finish(Ok(()), Some(diag.path())).unwrap();
assert!(!ok_root.exists());
assert_eq!(fs::read_dir(diag.path()).unwrap().count(), 0);
let fail_run = RunDirectory::new("rev-fail", Duration::from_secs(2)).unwrap();
let fail_root = fail_run.path().to_path_buf();
fs::create_dir_all(fail_root.join("installation")).unwrap();
write_file(&fail_root.join("installation/huge.bin"), b"skip").unwrap();
write_file(&fail_root.join("notes.txt"), b"keep").unwrap();
let export_dir = diag.path().join(fail_root.file_name().unwrap());
fs::create_dir_all(&export_dir).unwrap();
let hl_outside = diag.path().join("outside-hl.txt");
fs::write(&hl_outside, b"untouched").unwrap();
fs::hard_link(&hl_outside, export_dir.join("notes.txt")).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&export_dir, fs::Permissions::from_mode(0o755)).unwrap();
}
let err = fail_run.finish(Err("boom".into()), Some(diag.path())).unwrap_err();
assert!(err.contains("boom") && err.contains("evidence retained at"));
assert!(err.contains(&format!("evidence exported to {}", export_dir.display())), "{err}");
assert_eq!(fs::read(fail_root.join("failure.txt")).unwrap(), b"boom");
assert_eq!(fs::read(export_dir.join("failure.txt")).unwrap(), b"boom");
assert_eq!(fs::read(export_dir.join("notes.txt")).unwrap(), b"keep");
assert_eq!(fs::read(&hl_outside).unwrap(), b"untouched");
assert!(export_dir.join("run.json").exists());
assert!(!export_dir.join("installation").exists());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(fs::metadata(&export_dir).unwrap().permissions().mode() & 0o777, 0o700);
}
fs::remove_dir_all(&fail_root).unwrap();
let inner_run = RunDirectory::new("rev-inner", Duration::from_secs(2)).unwrap();
let inner_root = inner_run.path().to_path_buf();
let inner_err = inner_run.finish(Err("boom".into()), Some(&inner_root)).unwrap_err();
assert!(inner_err.contains("boom"));
assert!(inner_err.contains(&format!("evidence retained at {}", inner_root.display())));
assert!(inner_err.contains("retention export incomplete at"), "{inner_err}");
assert!(inner_err.contains("evidence export must be disjoint"), "{inner_err}");
assert_eq!(fs::read(inner_root.join("failure.txt")).unwrap(), b"boom");
#[cfg(unix)]
{
std::os::unix::fs::symlink(inner_root.parent().unwrap(), diag.path().join("alias-parent"))
.unwrap();
let sym_err = RunDirectory::new("rev-sym", Duration::from_secs(2)).unwrap();
let sym_root = sym_err.path().to_path_buf();
let out = sym_err
.finish(Err("boom".into()), Some(&diag.path().join("alias-parent")))
.unwrap_err();
assert!(out.contains("evidence export must be disjoint"), "{out}");
fs::remove_dir_all(&sym_root).unwrap();
}
fs::remove_dir_all(&inner_root).unwrap();
}