1use std::io;
38use std::path::Path;
39use std::process::{Command, ExitStatus, Output};
40
41#[cfg(unix)]
42mod live;
43#[cfg(unix)]
44pub use live::{Fifo, Live, Scene, drain, live, scene};
45
46pub const KILLED_RUNS: u32 = 4;
49
50const KILL: i32 = 9;
51
52#[must_use]
54pub fn killed(status: ExitStatus) -> bool {
55 signal(status) == Some(KILL)
56}
57
58#[cfg(unix)]
59fn signal(status: ExitStatus) -> Option<i32> {
60 std::os::unix::process::ExitStatusExt::signal(&status)
61}
62
63#[cfg(not(unix))]
64fn signal(_: ExitStatus) -> Option<i32> {
65 None
66}
67
68#[track_caller]
79pub fn output(cmd: &mut Command) -> io::Result<Output> {
80 again(cmd, Command::output, |o| {
81 (o.status, tail(&o.stdout), tail(&o.stderr))
82 })
83}
84
85#[track_caller]
94pub fn status(cmd: &mut Command) -> io::Result<ExitStatus> {
95 again(cmd, Command::status, |s| (*s, String::new(), String::new()))
96}
97
98#[track_caller]
102fn again<T>(
103 cmd: &mut Command,
104 run: impl Fn(&mut Command) -> io::Result<T>,
105 ending: impl Fn(&T) -> (ExitStatus, String, String),
106) -> io::Result<T> {
107 let mut runs = 0;
108 let chosen = cmd.get_envs().any(|(k, _)| k == crate::scratch::VAR);
110 loop {
111 let own = (!chosen).then(|| crate::scratch::Scratch::new("child"));
114 if let Some(own) = &own {
115 cmd.env(crate::scratch::VAR, own.path());
116 }
117 let done = run(cmd)?;
118 drop(own);
119 runs += 1;
120 let (status, out, err) = ending(&done);
121 if !killed(status) {
122 return Ok(done);
123 }
124 assert!(
125 runs < KILLED_RUNS,
126 "{cmd:?}: killed by SIGKILL on each of its {runs} runs: the system ended it \
127 from outside (the OOM killer, or a person), not the code under test, so it \
128 came to no result\n--- stdout\n{out}\n--- stderr\n{err}"
129 );
130 }
131}
132
133pub(crate) fn tail(bytes: &[u8]) -> String {
135 let text = String::from_utf8_lossy(bytes);
136 let lines: Vec<&str> = text.lines().collect();
137 lines[lines.len().saturating_sub(20)..].join("\n")
138}
139
140pub const DIRECT: &[&str] = &[
143 ".kill()",
144 "Child::kill",
145 ".output()",
146 ".spawn()",
147 "Command::output",
148 "Command::status",
149 "Command::spawn",
150];
151
152#[must_use]
165pub fn direct_runs(root: &Path) -> Vec<String> {
166 let mut files = Vec::new();
167 crate::guard::rust_files(root, &mut files);
168 files.sort();
169 let mut found = Vec::new();
170 for path in files {
171 if path.ends_with("unityrs-testkit/src/child.rs")
172 || path
173 .parent()
174 .is_some_and(|p| p.ends_with("unityrs-testkit/src/child"))
175 {
176 continue;
177 }
178 let text =
179 std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
180 let (mut made, mut run) = (0, 0);
181 for (i, line) in text.lines().enumerate() {
182 let code = line.trim_start();
183 if code.starts_with("//") {
184 continue;
185 }
186 if DIRECT.iter().any(|d| code.contains(d)) {
187 found.push(format!("{}:{}: {}", path.display(), i + 1, code));
188 }
189 made += code.matches("Command::new(").count();
190 run += code.matches("child::output(").count()
191 + code.matches("child::status(").count()
192 + code.matches("child::live(").count();
193 }
194 if made > run {
195 found.push(format!(
196 "{}: {made} commands made, {run} run through unityrs_testkit::child",
197 path.display()
198 ));
199 }
200 }
201 found
202}
203
204#[cfg(test)]
208pub(crate) struct Marks(
209 pub(crate) std::path::PathBuf,
210 #[allow(dead_code, reason = "held for its drop, which removes the folder")]
211 crate::scratch::Scratch,
212);
213
214#[cfg(test)]
215impl Marks {
216 pub(crate) fn new(name: &str) -> Self {
217 let dir = crate::scratch::Scratch::new(&format!("marks-{name}"));
218 Self(dir.path().to_path_buf(), dir)
219 }
220
221 pub(crate) fn runs(&self) -> usize {
222 std::fs::read_dir(&self.0).unwrap().count()
223 }
224
225 pub(crate) fn killed(&self, n: u32) -> String {
228 format!("{n}:{}", self.0.display())
229 }
230}
231
232#[cfg(test)]
236pub(crate) fn kill_self_while(spec: &str) {
237 let (n, dir) = spec.split_once(':').unwrap();
238 let n: usize = n.parse().unwrap();
239 let dir = std::path::Path::new(dir);
240 let runs = std::fs::read_dir(dir).unwrap().count();
241 if runs < n {
242 std::fs::write(dir.join(runs.to_string()), b"").unwrap();
243 kill_self();
244 }
245}
246
247#[cfg(test)]
254pub(crate) fn kill_self() -> ! {
255 #[cfg(unix)]
256 {
257 use std::os::unix::process::CommandExt;
258 let e = Command::new("sh").args(["-c", "kill -KILL $$"]).exec();
259 panic!("cannot exec sh to kill the probe: {e}");
260 }
261 #[cfg(not(unix))]
262 panic!("no SIGKILL to send here");
263}
264
265#[cfg(all(test, unix))]
266mod tests {
267 use std::path::Path;
268 use std::process::Command;
269
270 use super::{KILLED_RUNS, Marks, direct_runs, output, status};
271
272 fn killed_while(n: usize, dir: &Path, last: &str) -> Command {
277 let script = format!(
278 "runs=$(( $(ls \"$1\" | wc -l) )); touch \"$1/$runs\"; \
279 if [ \"$runs\" -lt {n} ]; then kill -KILL $$; sleep 60; exit 7; fi; {last}"
280 );
281 let mut cmd = Command::new("sh");
282 cmd.arg("-c").arg(script).arg("sh").arg(dir);
283 cmd
284 }
285
286 fn refused(f: impl FnOnce() + std::panic::UnwindSafe) -> String {
287 let p = std::panic::catch_unwind(f).expect_err("the run did not fail");
288 p.downcast_ref::<String>().cloned().unwrap_or_default()
289 }
290
291 #[test]
294 fn a_child_killed_from_outside_once_is_run_again() {
295 let marks = Marks::new("once");
296 let o = output(&mut killed_while(1, &marks.0, "echo done; exit 3")).unwrap();
297 assert_eq!(o.status.code(), Some(3), "{o:?}");
298 assert_eq!(String::from_utf8_lossy(&o.stdout), "done\n");
299 assert_eq!(marks.runs(), 2);
300 let marks = Marks::new("once-status");
301 let s = status(&mut killed_while(1, &marks.0, "exit 0")).unwrap();
302 assert!(s.success(), "{s:?}");
303 assert_eq!(marks.runs(), 2);
304 }
305
306 #[test]
309 fn a_child_killed_on_all_but_its_last_run_comes_to_a_result() {
310 let marks = Marks::new("again");
311 let n = usize::try_from(KILLED_RUNS - 1).unwrap();
312 let o = output(&mut killed_while(n, &marks.0, "exit 0")).unwrap();
313 assert!(o.status.success(), "{o:?}");
314 assert_eq!(marks.runs(), n + 1);
315 }
316
317 #[test]
320 fn a_child_killed_on_every_run_fails_saying_the_system_killed_it() {
321 let marks = Marks::new("always");
322 let n = usize::try_from(KILLED_RUNS).unwrap();
323 let dir = marks.0.clone();
324 let m = refused(move || {
325 let mut cmd = killed_while(n, &dir, "exit 0");
326 let _ = output(&mut cmd);
327 });
328 assert_eq!(marks.runs(), n);
329 let want = format!("killed by SIGKILL on each of its {KILLED_RUNS} runs");
330 assert!(m.contains(&want), "{m}");
331 assert!(m.contains("the system ended it from outside"), "{m}");
332 assert!(m.contains("the OOM killer"), "{m}");
333 let marks = Marks::new("always-status");
334 let dir = marks.0.clone();
335 let m = refused(move || {
336 let _ = status(&mut killed_while(n, &dir, "exit 0"));
337 });
338 assert_eq!(marks.runs(), n);
339 assert!(m.contains(&want), "{m}");
340 }
341
342 #[test]
346 fn every_other_ending_is_the_first_run_result() {
347 use std::os::unix::process::ExitStatusExt;
348 for (script, code, signal) in [
349 ("exit 0", Some(0), None),
350 ("exit 101", Some(101), None),
351 ("kill -ABRT $$", None, Some(6)),
352 ("kill -SEGV $$", None, Some(11)),
353 ("kill -TERM $$", None, Some(15)),
354 ] {
355 let marks = Marks::new("own");
356 let mut cmd = Command::new("sh");
357 cmd.arg("-c")
358 .arg(format!("ulimit -c 0; touch \"$1/run\"; {script}"))
359 .arg("sh")
360 .arg(&marks.0);
361 let o = output(&mut cmd).unwrap();
362 assert_eq!(
363 (o.status.code(), o.status.signal()),
364 (code, signal),
365 "{script}"
366 );
367 assert_eq!(marks.runs(), 1, "{script}: run again");
368 }
369 }
370
371 #[test]
374 fn a_child_that_cannot_start_is_an_error() {
375 let mut cmd = Command::new("/nonexistent/unityrs-testkit-child");
376 assert!(output(&mut cmd).is_err());
377 assert!(status(&mut cmd).is_err());
378 }
379
380 #[test]
383 fn every_child_in_the_workspace_runs_through_here() {
384 let crates = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
385 let found = direct_runs(&crates);
386 assert!(
387 found.is_empty(),
388 "children run outside unityrs_testkit::child, which a SIGKILL from \
389 outside fails:\n{}",
390 found.join("\n")
391 );
392 }
393
394 #[test]
397 fn the_scan_finds_each_direct_run() {
398 let marks = Marks::new("scan");
399 let file = |name: &str, text: &str| std::fs::write(marks.0.join(name), text).unwrap();
400 file(
401 "clean.rs",
402 "let o = unityrs_testkit::child::output(Command::new(\"sh\").arg(\"x\"));\n\
403 let s = child::status(&mut Command::new(\"sh\"));\n\
404 let mut c = Command::new(\"sh\"); let p = child::live(scene, &mut c, false);\n\
405 // Command::new(\"sh\").output() in a comment\n\
406 assert_eq!(err.status(), 1);\n\
407 std::thread::scope(|s| { s.spawn(|| ()); });\n",
408 );
409 file("output.rs", "let o = Command::new(\"sh\").output();\n");
410 file(
411 "status.rs",
412 "let s = Command::new(\"sh\")\n .arg(\"x\")\n .status();\n",
413 );
414 file("spawn.rs", "let c = cmd.spawn();\n");
415 file(
416 "kill.rs",
417 "child.kill();\nstd::process::Child::kill(&mut child);\n",
418 );
419 file("path.rs", "let o = Command::output(&mut cmd);\n");
420 let found = direct_runs(&marks.0);
421 let at = |name: &str| marks.0.join(name).display().to_string();
422 assert_eq!(
423 found,
424 [
425 format!("{}:1: child.kill();", at("kill.rs")),
426 format!(
427 "{}:2: std::process::Child::kill(&mut child);",
428 at("kill.rs")
429 ),
430 format!(
431 "{}:1: let o = Command::new(\"sh\").output();",
432 at("output.rs")
433 ),
434 format!(
435 "{}: 1 commands made, 0 run through unityrs_testkit::child",
436 at("output.rs")
437 ),
438 format!("{}:1: let o = Command::output(&mut cmd);", at("path.rs")),
439 format!("{}:1: let c = cmd.spawn();", at("spawn.rs")),
440 format!(
441 "{}: 1 commands made, 0 run through unityrs_testkit::child",
442 at("status.rs")
443 ),
444 ]
445 );
446 }
447}