use std::time::Duration;
use isothrum_runner::{Captured, ProcessError, ProcessRunner, ProcessSpec, capture};
#[derive(Debug)]
pub(crate) enum Unanswered {
NotStarted(ProcessError),
TimedOut(Duration),
}
impl Unanswered {
pub(crate) fn tool_is_there(&self) -> bool {
matches!(self, Unanswered::TimedOut(_))
}
}
impl std::fmt::Display for Unanswered {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Unanswered::NotStarted(e) => e.fmt(f),
Unanswered::TimedOut(limit) => write!(f, "no answer within {} s", limit.as_secs()),
}
}
}
pub(crate) async fn probe(runner: &dyn ProcessRunner, limit: Duration, program: &str, args: &[&str]) -> Result<Captured, Unanswered> {
probe_spec(runner, limit, &ProcessSpec::new(program, args.iter().copied())).await
}
pub(crate) async fn probe_spec(runner: &dyn ProcessRunner, limit: Duration, spec: &ProcessSpec) -> Result<Captured, Unanswered> {
match tokio::time::timeout(limit, capture(runner, spec)).await {
Ok(Ok(captured)) => Ok(captured),
Ok(Err(e)) => Err(Unanswered::NotStarted(e)),
Err(_) => Err(Unanswered::TimedOut(limit)),
}
}
pub(crate) fn all_lines(captured: &Captured) -> String {
captured.stdout.iter().chain(&captured.stderr_tail).cloned().collect::<Vec<_>>().join("\n")
}
pub(crate) async fn read_ok(runner: &dyn ProcessRunner, limit: Duration, program: &str, args: &[&str]) -> Result<String, String> {
probe(runner, limit, program, args)
.await
.map_err(|e| e.to_string())?
.output()
.map_err(|failed| failed.to_string())
}
#[cfg(test)]
mod tests {
use isothrum_runner::fake::{FakeProcesses, Reply};
use super::*;
const LIMIT: Duration = Duration::from_secs(25);
fn exiting(code: i32, stdout: &str) -> Reply {
let mut reply = Reply::ok(stdout);
reply.code = code;
reply
}
#[tokio::test(start_paused = true)]
async fn a_probe_returns_the_output_whatever_the_exit() {
let fake = FakeProcesses::script().expect("tool one", Reply::ok("line-a\nline-b")).build();
assert_eq!(probe(&fake, LIMIT, "tool", &["one"]).await.unwrap().stdout, ["line-a", "line-b"]);
let mut warned = exiting(2, "partial");
warned.stderr = vec!["WARNING: careful".to_owned()];
let failing = FakeProcesses::script().expect("tool two", warned).build();
assert_eq!(all_lines(&probe(&failing, LIMIT, "tool", &["two"]).await.unwrap()), "partial\nWARNING: careful");
}
#[tokio::test(start_paused = true)]
async fn a_failed_read_says_why_as_the_runner_does() {
let said = FakeProcesses::script().expect("tool", Reply::fail(1, "no such plugin")).build();
assert_eq!(read_ok(&said, LIMIT, "tool", &[]).await, Err("no such plugin (exited with code 1)".to_owned()));
let on_stdout = FakeProcesses::script().expect("tool", exiting(2, "refused: log in as admin")).build();
assert_eq!(
read_ok(&on_stdout, LIMIT, "tool", &[]).await,
Err("refused: log in as admin (exited with code 2)".to_owned())
);
let silent = FakeProcesses::script().expect("tool", Reply::fail(3, "")).build();
assert_eq!(read_ok(&silent, LIMIT, "tool", &[]).await, Err("exited with code 3".to_owned()));
}
#[tokio::test(start_paused = true)]
async fn a_missing_tool_is_said_as_missing_and_isnt_there() {
let fake = FakeProcesses::script().expect("tool", Reply::missing()).build();
let err = probe(&fake, LIMIT, "tool", &[]).await.unwrap_err();
assert!(
matches!(err, Unanswered::NotStarted(ProcessError::Missing { ref program }) if program == "tool"),
"{err:?}"
);
assert!(!err.tool_is_there());
}
#[tokio::test(start_paused = true)]
async fn a_tool_past_the_limit_is_there_and_said_as_timed_out() {
let err = probe(&crate::testing::Stuck, LIMIT, "VBoxManage", &["--version"]).await.unwrap_err();
assert!(err.tool_is_there());
assert_eq!(err.to_string(), "no answer within 25 s");
assert_eq!(
read_ok(&crate::testing::Stuck, LIMIT, "vagrant", &[]).await,
Err("no answer within 25 s".to_owned())
);
}
}