pub const SCRUBBED_ENV: [&str; 2] = ["SKULD_LABELS", "SKULD_NEXTEST_METADATA_PATH"];
pub const NOCAPTURE: &str = "--nocapture";
pub fn command(program: impl AsRef<std::ffi::OsStr>) -> std::process::Command {
let mut command = std::process::Command::new(program);
scrub_env(|var| _ = command.env_remove(var));
command
}
pub fn scrub_env(mut remove: impl FnMut(&str)) {
for var in SCRUBBED_ENV {
remove(var);
}
}
pub fn fixture_args(fixture: &str) -> [&str; 4] {
["--test-threads=1", "--exact", fixture, NOCAPTURE]
}
pub const JSON_FORMAT: [&str; 2] = ["--format", "json"];
pub fn with_json_events(cmd: &mut std::process::Command) -> &mut std::process::Command {
cmd.args(JSON_FORMAT)
}
#[derive(Debug, PartialEq, Eq)]
pub struct SuiteOutcome {
pub test_count: u64,
pub passed: u64,
pub failed: u64,
pub ignored: u64,
}
pub fn suite_outcome(stdout: &[u8]) -> Result<SuiteOutcome, String> {
let mut started = Vec::new();
let mut terminal = Vec::new();
for line in String::from_utf8_lossy(stdout).lines() {
let event = match serde_json::from_str::<serde_json::Value>(line) {
Ok(event) if event.is_object() => event,
_ => {
log::debug!("not a JSON event: {line:?}");
continue;
}
};
if event["type"] != "suite" {
continue;
}
match event["event"].as_str() {
Some("started") => started.push(event),
Some("ok" | "failed") => terminal.push(event),
other => return Err(format!("a suite event of unknown kind {other:?}: {line}")),
}
}
let [started] = started.as_slice() else {
return Err(format!(
"expected exactly one suite `started` event, found {} (the child must run with `--format json`)",
started.len()
));
};
let [terminal] = terminal.as_slice() else {
return Err(format!(
"expected exactly one terminal suite event (`ok` or `failed`), found {}",
terminal.len()
));
};
let count = |event: &serde_json::Value, field: &str| {
event[field]
.as_u64()
.ok_or_else(|| format!("the suite event {event} has no numeric `{field}`"))
};
Ok(SuiteOutcome {
test_count: count(started, "test_count")?,
passed: count(terminal, "passed")?,
failed: count(terminal, "failed")?,
ignored: count(terminal, "ignored")?,
})
}
pub fn suite_passed_exactly_one(output: &std::process::Output) -> Result<(), String> {
if !output.status.success() {
return Err(format!("the child exited with {}", output.status));
}
let outcome = suite_outcome(&output.stdout)?;
if outcome.test_count == 1 && outcome.passed == 1 && outcome.failed == 0 {
Ok(())
} else {
Err(format!(
"expected exactly one test run and passed, got {outcome:?}; `--exact` probably matched none"
))
}
}