Lines
100 %
Functions
Branches
use super::*;
use std::process::Command;
use std::time::{Duration, Instant};
#[test]
fn a_stat_line_is_read_past_a_command_name_with_spaces_and_parens() {
let line = "4242 (a (b) c) R 17 4242 4242 0 -1 4194304 1 0 0 0 250 50 7 3 20 0 1 0";
let stat = parse(line).expect("a well-formed line parses");
assert_eq!((stat.pid, stat.ppid, stat.ticks), (4242, 17, 310));
}
fn a_truncated_stat_line_is_skipped() {
assert!(parse("4242 (sh) S 17 4242").is_none());
assert!(parse("garbage").is_none());
fn a_busy_child_is_counted_in_its_parents_tree() {
let _processes = crate::test_support::processes();
let me = std::process::id();
let before = tree_ticks(me);
let mut child = Command::new("bash")
.args(["-c", "while :; do :; done"])
.spawn()
.expect("bash runs");
// A loaded or CPU-throttled runner gives the child less than a core, so
// wait for the ticks instead of sampling a fixed window.
let started = Instant::now();
let mut seen = 0;
while seen < TICKS_PER_SECOND / 2 && started.elapsed() < Duration::from_secs(30) {
std::thread::sleep(Duration::from_millis(100));
seen = seen.max(tree_ticks(me).saturating_sub(before));
child.kill().expect("the spinning child is killed");
child.wait().expect("the killed child is reaped");
assert!(
seen >= TICKS_PER_SECOND / 2,
"a spinning child must show up as CPU work, saw {seen} ticks"
);
fn a_reaped_childs_cpu_stays_in_the_live_parents_total() {
use nix::sys::signal::{Signal, kill};
use nix::unistd::Pid;
use std::io::{BufRead, BufReader};
use std::process::Stdio;
let mut parent = Command::new("sh")
.args(["-c", "while :; do :; done & echo $!; wait; exec sleep 30"])
.stdout(Stdio::piped())
.expect("sh runs");
let mut line = String::new();
let burner = parent
.stdout
.take()
.map(BufReader::new)
.and_then(|mut out| out.read_line(&mut line).ok())
.and_then(|_| line.trim().parse::<i32>().ok());
while tree_ticks(parent.id()) < TICKS_PER_SECOND / 4
&& started.elapsed() < Duration::from_secs(30)
{
std::thread::sleep(Duration::from_millis(50));
let before = tree_ticks(parent.id());
let killed = burner.map(|pid| kill(Pid::from_raw(pid), Signal::SIGKILL));
let mut after = before;
let sampled = Instant::now();
while sampled.elapsed() < Duration::from_secs(1) {
after = after.min(tree_ticks(parent.id()));
let _ = parent.kill();
let _ = parent.wait();
assert!(matches!(killed, Some(Ok(()))), "the burner was not killed");
before >= TICKS_PER_SECOND / 4,
"the burner never showed CPU work, saw {before} ticks"
after >= before,
"the tree total fell from {before} to {after} after the child was reaped"
fn an_unknown_root_has_no_ticks() {
assert_eq!(tree_ticks(u32::MAX), 0);