use std::io;
use std::path::Path;
use std::process::{Command, ExitStatus, Output};
#[cfg(unix)]
mod live;
#[cfg(unix)]
pub use live::{Fifo, Live, Scene, drain, live, scene};
pub const KILLED_RUNS: u32 = 4;
const KILL: i32 = 9;
#[must_use]
pub fn killed(status: ExitStatus) -> bool {
signal(status) == Some(KILL)
}
#[cfg(unix)]
fn signal(status: ExitStatus) -> Option<i32> {
std::os::unix::process::ExitStatusExt::signal(&status)
}
#[cfg(not(unix))]
fn signal(_: ExitStatus) -> Option<i32> {
None
}
#[track_caller]
pub fn output(cmd: &mut Command) -> io::Result<Output> {
again(cmd, Command::output, |o| {
(o.status, tail(&o.stdout), tail(&o.stderr))
})
}
#[track_caller]
pub fn status(cmd: &mut Command) -> io::Result<ExitStatus> {
again(cmd, Command::status, |s| (*s, String::new(), String::new()))
}
#[track_caller]
fn again<T>(
cmd: &mut Command,
run: impl Fn(&mut Command) -> io::Result<T>,
ending: impl Fn(&T) -> (ExitStatus, String, String),
) -> io::Result<T> {
let mut runs = 0;
let chosen = cmd.get_envs().any(|(k, _)| k == crate::scratch::VAR);
loop {
let own = (!chosen).then(|| crate::scratch::Scratch::new("child"));
if let Some(own) = &own {
cmd.env(crate::scratch::VAR, own.path());
}
let done = run(cmd)?;
drop(own);
runs += 1;
let (status, out, err) = ending(&done);
if !killed(status) {
return Ok(done);
}
assert!(
runs < KILLED_RUNS,
"{cmd:?}: killed by SIGKILL on each of its {runs} runs: the system ended it \
from outside (the OOM killer, or a person), not the code under test, so it \
came to no result\n--- stdout\n{out}\n--- stderr\n{err}"
);
}
}
pub(crate) fn tail(bytes: &[u8]) -> String {
let text = String::from_utf8_lossy(bytes);
let lines: Vec<&str> = text.lines().collect();
lines[lines.len().saturating_sub(20)..].join("\n")
}
pub const DIRECT: &[&str] = &[
".kill()",
"Child::kill",
".output()",
".spawn()",
"Command::output",
"Command::status",
"Command::spawn",
];
#[must_use]
pub fn direct_runs(root: &Path) -> Vec<String> {
let mut files = Vec::new();
crate::guard::rust_files(root, &mut files);
files.sort();
let mut found = Vec::new();
for path in files {
if path.ends_with("unityrs-testkit/src/child.rs")
|| path
.parent()
.is_some_and(|p| p.ends_with("unityrs-testkit/src/child"))
{
continue;
}
let text =
std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let (mut made, mut run) = (0, 0);
for (i, line) in text.lines().enumerate() {
let code = line.trim_start();
if code.starts_with("//") {
continue;
}
if DIRECT.iter().any(|d| code.contains(d)) {
found.push(format!("{}:{}: {}", path.display(), i + 1, code));
}
made += code.matches("Command::new(").count();
run += code.matches("child::output(").count()
+ code.matches("child::status(").count()
+ code.matches("child::live(").count();
}
if made > run {
found.push(format!(
"{}: {made} commands made, {run} run through unityrs_testkit::child",
path.display()
));
}
}
found
}
#[cfg(test)]
pub(crate) struct Marks(
pub(crate) std::path::PathBuf,
#[allow(dead_code, reason = "held for its drop, which removes the folder")]
crate::scratch::Scratch,
);
#[cfg(test)]
impl Marks {
pub(crate) fn new(name: &str) -> Self {
let dir = crate::scratch::Scratch::new(&format!("marks-{name}"));
Self(dir.path().to_path_buf(), dir)
}
pub(crate) fn runs(&self) -> usize {
std::fs::read_dir(&self.0).unwrap().count()
}
pub(crate) fn killed(&self, n: u32) -> String {
format!("{n}:{}", self.0.display())
}
}
#[cfg(test)]
pub(crate) fn kill_self_while(spec: &str) {
let (n, dir) = spec.split_once(':').unwrap();
let n: usize = n.parse().unwrap();
let dir = std::path::Path::new(dir);
let runs = std::fs::read_dir(dir).unwrap().count();
if runs < n {
std::fs::write(dir.join(runs.to_string()), b"").unwrap();
kill_self();
}
}
#[cfg(test)]
pub(crate) fn kill_self() -> ! {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
let e = Command::new("sh").args(["-c", "kill -KILL $$"]).exec();
panic!("cannot exec sh to kill the probe: {e}");
}
#[cfg(not(unix))]
panic!("no SIGKILL to send here");
}
#[cfg(all(test, unix))]
mod tests {
use std::path::Path;
use std::process::Command;
use super::{KILLED_RUNS, Marks, direct_runs, output, status};
fn killed_while(n: usize, dir: &Path, last: &str) -> Command {
let script = format!(
"runs=$(( $(ls \"$1\" | wc -l) )); touch \"$1/$runs\"; \
if [ \"$runs\" -lt {n} ]; then kill -KILL $$; sleep 60; exit 7; fi; {last}"
);
let mut cmd = Command::new("sh");
cmd.arg("-c").arg(script).arg("sh").arg(dir);
cmd
}
fn refused(f: impl FnOnce() + std::panic::UnwindSafe) -> String {
let p = std::panic::catch_unwind(f).expect_err("the run did not fail");
p.downcast_ref::<String>().cloned().unwrap_or_default()
}
#[test]
fn a_child_killed_from_outside_once_is_run_again() {
let marks = Marks::new("once");
let o = output(&mut killed_while(1, &marks.0, "echo done; exit 3")).unwrap();
assert_eq!(o.status.code(), Some(3), "{o:?}");
assert_eq!(String::from_utf8_lossy(&o.stdout), "done\n");
assert_eq!(marks.runs(), 2);
let marks = Marks::new("once-status");
let s = status(&mut killed_while(1, &marks.0, "exit 0")).unwrap();
assert!(s.success(), "{s:?}");
assert_eq!(marks.runs(), 2);
}
#[test]
fn a_child_killed_on_all_but_its_last_run_comes_to_a_result() {
let marks = Marks::new("again");
let n = usize::try_from(KILLED_RUNS - 1).unwrap();
let o = output(&mut killed_while(n, &marks.0, "exit 0")).unwrap();
assert!(o.status.success(), "{o:?}");
assert_eq!(marks.runs(), n + 1);
}
#[test]
fn a_child_killed_on_every_run_fails_saying_the_system_killed_it() {
let marks = Marks::new("always");
let n = usize::try_from(KILLED_RUNS).unwrap();
let dir = marks.0.clone();
let m = refused(move || {
let mut cmd = killed_while(n, &dir, "exit 0");
let _ = output(&mut cmd);
});
assert_eq!(marks.runs(), n);
let want = format!("killed by SIGKILL on each of its {KILLED_RUNS} runs");
assert!(m.contains(&want), "{m}");
assert!(m.contains("the system ended it from outside"), "{m}");
assert!(m.contains("the OOM killer"), "{m}");
let marks = Marks::new("always-status");
let dir = marks.0.clone();
let m = refused(move || {
let _ = status(&mut killed_while(n, &dir, "exit 0"));
});
assert_eq!(marks.runs(), n);
assert!(m.contains(&want), "{m}");
}
#[test]
fn every_other_ending_is_the_first_run_result() {
use std::os::unix::process::ExitStatusExt;
for (script, code, signal) in [
("exit 0", Some(0), None),
("exit 101", Some(101), None),
("kill -ABRT $$", None, Some(6)),
("kill -SEGV $$", None, Some(11)),
("kill -TERM $$", None, Some(15)),
] {
let marks = Marks::new("own");
let mut cmd = Command::new("sh");
cmd.arg("-c")
.arg(format!("ulimit -c 0; touch \"$1/run\"; {script}"))
.arg("sh")
.arg(&marks.0);
let o = output(&mut cmd).unwrap();
assert_eq!(
(o.status.code(), o.status.signal()),
(code, signal),
"{script}"
);
assert_eq!(marks.runs(), 1, "{script}: run again");
}
}
#[test]
fn a_child_that_cannot_start_is_an_error() {
let mut cmd = Command::new("/nonexistent/unityrs-testkit-child");
assert!(output(&mut cmd).is_err());
assert!(status(&mut cmd).is_err());
}
#[test]
fn every_child_in_the_workspace_runs_through_here() {
let crates = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let found = direct_runs(&crates);
assert!(
found.is_empty(),
"children run outside unityrs_testkit::child, which a SIGKILL from \
outside fails:\n{}",
found.join("\n")
);
}
#[test]
fn the_scan_finds_each_direct_run() {
let marks = Marks::new("scan");
let file = |name: &str, text: &str| std::fs::write(marks.0.join(name), text).unwrap();
file(
"clean.rs",
"let o = unityrs_testkit::child::output(Command::new(\"sh\").arg(\"x\"));\n\
let s = child::status(&mut Command::new(\"sh\"));\n\
let mut c = Command::new(\"sh\"); let p = child::live(scene, &mut c, false);\n\
// Command::new(\"sh\").output() in a comment\n\
assert_eq!(err.status(), 1);\n\
std::thread::scope(|s| { s.spawn(|| ()); });\n",
);
file("output.rs", "let o = Command::new(\"sh\").output();\n");
file(
"status.rs",
"let s = Command::new(\"sh\")\n .arg(\"x\")\n .status();\n",
);
file("spawn.rs", "let c = cmd.spawn();\n");
file(
"kill.rs",
"child.kill();\nstd::process::Child::kill(&mut child);\n",
);
file("path.rs", "let o = Command::output(&mut cmd);\n");
let found = direct_runs(&marks.0);
let at = |name: &str| marks.0.join(name).display().to_string();
assert_eq!(
found,
[
format!("{}:1: child.kill();", at("kill.rs")),
format!(
"{}:2: std::process::Child::kill(&mut child);",
at("kill.rs")
),
format!(
"{}:1: let o = Command::new(\"sh\").output();",
at("output.rs")
),
format!(
"{}: 1 commands made, 0 run through unityrs_testkit::child",
at("output.rs")
),
format!("{}:1: let o = Command::output(&mut cmd);", at("path.rs")),
format!("{}:1: let c = cmd.spawn();", at("spawn.rs")),
format!(
"{}: 1 commands made, 0 run through unityrs_testkit::child",
at("status.rs")
),
]
);
}
}