use std::sync::{Mutex, PoisonError};
use std::time::Duration;
use super::{Exit, OnLine, ProcessError, ProcessRunner, ProcessSpec};
use crate::BoxFuture;
use crate::events::Stream;
pub type Call = ProcessSpec;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Reply {
pub stdout: Vec<String>,
pub stderr: Vec<String>,
pub code: i32,
pub missing: bool,
pub delay: Duration,
pub pace: Duration,
}
impl Reply {
pub fn ok(stdout: &str) -> Reply {
Reply {
stdout: stdout.lines().map(str::to_owned).collect(),
..Reply::default()
}
}
pub fn fail(code: i32, stderr: &str) -> Reply {
Reply {
stderr: stderr.lines().map(str::to_owned).collect(),
code,
..Reply::default()
}
}
#[must_use]
pub fn missing() -> Reply {
Reply {
missing: true,
..Reply::default()
}
}
#[must_use]
pub fn after(mut self, delay: Duration) -> Reply {
self.delay = delay;
self
}
#[cfg(test)]
#[must_use]
pub(crate) fn paced(mut self, pace: Duration) -> Reply {
self.pace = pace;
self
}
}
type Answer = Box<dyn Fn(&Call) -> Reply + Send + Sync>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Times {
AtLeastOnce,
Exactly(usize),
Any,
}
#[derive(Debug, Clone)]
struct Expectation {
program: String,
args: Vec<String>,
reply: Reply,
times: Times,
}
impl Expectation {
#[expect(clippy::panic, reason = "a script that names no program is the test's mistake, said at once")]
fn new(call: &str, reply: Reply, times: Times) -> Expectation {
let mut words = call.split_whitespace().map(str::to_owned);
let Some(program) = words.next() else {
panic!("a scripted call names its program: {call:?}");
};
Expectation {
program,
args: words.collect(),
reply,
times,
}
}
fn matches(&self, call: &Call) -> bool {
call.program == self.program && call.args.len() >= self.args.len() && self.args.iter().zip(&call.args).all(|(want, got)| want == "*" || want == got)
}
fn describe(&self) -> String {
std::iter::once(self.program.as_str())
.chain(self.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" ")
}
}
#[derive(Debug, Clone, Default)]
#[must_use]
pub struct Script {
expectations: Vec<Expectation>,
}
impl Script {
pub fn expect(mut self, call: &str, reply: Reply) -> Script {
self.expectations.push(Expectation::new(call, reply, Times::AtLeastOnce));
self
}
pub fn expect_times(mut self, call: &str, times: usize, reply: Reply) -> Script {
self.expectations.push(Expectation::new(call, reply, Times::Exactly(times)));
self
}
pub fn allow(mut self, call: &str, reply: Reply) -> Script {
self.expectations.push(Expectation::new(call, reply, Times::Any));
self
}
#[must_use]
pub fn build(self) -> FakeProcesses {
FakeProcesses {
answer: Strictness::Strict {
used: Mutex::new(vec![0; self.expectations.len()]),
script: self,
},
calls: Mutex::new(Vec::new()),
unscripted: Mutex::new(Vec::new()),
}
}
fn answering(&self, call: &Call) -> Result<(usize, &Expectation), String> {
let matching: Vec<(usize, &Expectation)> = self.expectations.iter().enumerate().filter(|(_, e)| e.matches(call)).collect();
let most = matching.iter().map(|(_, e)| e.args.len()).max();
let best: Vec<(usize, &Expectation)> = matching.into_iter().filter(|(_, e)| Some(e.args.len()) == most).collect();
match best.as_slice() {
[one] => Ok(*one),
[] => Err(format!("unscripted call `{}`; the script expects:\n{}", call.line(), self.listing())),
many => Err(format!(
"call `{}` matches {} expectations equally: {}",
call.line(),
many.len(),
many.iter().map(|(_, e)| format!("`{}`", e.describe())).collect::<Vec<_>>().join(", ")
)),
}
}
fn listing(&self) -> String {
self.expectations.iter().map(|e| format!(" {}", e.describe())).collect::<Vec<_>>().join("\n")
}
}
enum Strictness {
Modelled(Answer),
Strict { script: Script, used: Mutex<Vec<usize>> },
}
pub struct FakeProcesses {
answer: Strictness,
calls: Mutex<Vec<Call>>,
unscripted: Mutex<Vec<String>>,
}
impl std::fmt::Debug for FakeProcesses {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FakeProcesses").field("calls", &self.lines()).finish_non_exhaustive()
}
}
impl FakeProcesses {
pub fn model(answer: impl Fn(&Call) -> Reply + Send + Sync + 'static) -> FakeProcesses {
FakeProcesses {
answer: Strictness::Modelled(Box::new(answer)),
calls: Mutex::new(Vec::new()),
unscripted: Mutex::new(Vec::new()),
}
}
pub fn script() -> Script {
Script::default()
}
#[expect(clippy::panic, reason = "an unscripted call fails the test that made it")]
fn reply(&self, call: &Call) -> Reply {
match &self.answer {
Strictness::Modelled(answer) => answer(call),
Strictness::Strict { script, used } => match script.answering(call) {
Ok((i, expectation)) => {
if let Some(n) = used.lock().unwrap_or_else(PoisonError::into_inner).get_mut(i) {
*n += 1;
}
expectation.reply.clone()
}
Err(why) => {
self.unscripted.lock().unwrap_or_else(PoisonError::into_inner).push(why.clone());
panic!("{why}");
}
},
}
}
fn unmet(&self) -> Vec<String> {
let mut unmet = self.unscripted.lock().unwrap_or_else(PoisonError::into_inner).clone();
if let Strictness::Strict { script, used } = &self.answer {
let used = used.lock().unwrap_or_else(PoisonError::into_inner);
for (e, &n) in script.expectations.iter().zip(used.iter()) {
let met = match e.times {
Times::AtLeastOnce => n > 0,
Times::Exactly(times) => n == times,
Times::Any => true,
};
if !met {
unmet.push(format!("`{}` was expected {:?}, made {n} time(s)", e.describe(), e.times));
}
}
}
unmet
}
pub fn made(&self, call: &str) -> Vec<Call> {
let wanted = Expectation::new(call, Reply::default(), Times::Any);
self.calls().into_iter().filter(|c| wanted.matches(c)).collect()
}
pub fn calls(&self) -> Vec<Call> {
self.calls.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
pub(crate) fn lines(&self) -> Vec<String> {
self.calls().iter().map(Call::line).collect()
}
pub fn last(&self, text: &str) -> Option<Call> {
self.calls().into_iter().rev().find(|c| c.line().contains(text))
}
async fn answer(&self, spec: &ProcessSpec, on_line: OnLine<'_>) -> Result<Exit, ProcessError> {
let reply = self.reply(spec);
self.calls.lock().unwrap_or_else(PoisonError::into_inner).push(spec.clone());
if !reply.delay.is_zero() {
tokio::time::sleep(reply.delay).await;
}
if reply.missing {
return Err(ProcessError::Missing { program: spec.program.clone() });
}
let lines = reply.stdout.iter().map(|l| (Stream::Stdout, l));
for (stream, line) in lines.chain(reply.stderr.iter().map(|l| (Stream::Stderr, l))) {
if !reply.pace.is_zero() {
tokio::time::sleep(reply.pace).await;
}
on_line(stream, line);
}
Ok(Exit { code: Some(reply.code) })
}
}
pub trait CallView {
fn flag(&self, name: &str) -> Option<&str>;
fn has(&self, name: &str) -> bool;
fn has_run(&self, run: &[&str]) -> bool;
}
impl CallView for Call {
fn flag(&self, name: &str) -> Option<&str> {
let prefixed = format!("{name}=");
let mut found = None;
let mut args = self.args.iter().peekable();
while let Some(arg) = args.next() {
if arg == name {
found = args.peek().map(|v| v.as_str());
} else if let Some(value) = arg.strip_prefix(&prefixed) {
found = Some(value);
}
}
found
}
fn has(&self, name: &str) -> bool {
self.args.iter().any(|a| a == name)
}
fn has_run(&self, run: &[&str]) -> bool {
run.is_empty() || self.args.windows(run.len()).any(|w| w.iter().zip(run).all(|(a, b)| a == b))
}
}
impl Drop for FakeProcesses {
fn drop(&mut self) {
let unmet = self.unmet();
if std::thread::panicking() {
return;
}
assert!(
unmet.is_empty(),
"the scripted processes weren't run as scripted:\n{}\ncalls made:\n{}",
unmet.join("\n"),
self.lines().join("\n")
);
}
}
impl ProcessRunner for FakeProcesses {
fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
Box::pin(self.answer(spec, on_line))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::process::{Captured, capture};
fn spec(line: &str) -> ProcessSpec {
let mut words = line.split_whitespace();
ProcessSpec::new(words.next().unwrap(), words)
}
fn panic_of(f: impl FnOnce()) -> String {
let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).expect_err("it panics");
err.downcast_ref::<String>()
.cloned()
.or_else(|| err.downcast_ref::<&str>().map(|s| (*s).to_owned()))
.unwrap()
}
fn run_on(fake: &FakeProcesses, line: &str) -> Result<Captured, ProcessError> {
let rt = tokio::runtime::Builder::new_current_thread().enable_time().start_paused(true).build().unwrap();
rt.block_on(capture(fake, &spec(line)))
}
#[tokio::test(start_paused = true)]
async fn a_scripted_call_is_answered_and_recorded() {
let fake = FakeProcesses::script()
.expect("docker compose ps", Reply::ok("[]"))
.expect("vagrant up", Reply::missing())
.expect("slow", Reply::fail(2, "boom").after(Duration::from_secs(600)))
.build();
assert_eq!(capture(&fake, &spec("docker compose ps --format json")).await.unwrap().stdout, ["[]"]);
assert!(matches!(capture(&fake, &spec("vagrant up")).await, Err(ProcessError::Missing { ref program }) if program == "vagrant"));
let slow = capture(&fake, &spec("slow")).await.unwrap();
assert_eq!((slow.exit, slow.stderr_tail), (Exit { code: Some(2) }, vec!["boom".to_owned()]));
assert_eq!(fake.lines(), ["docker compose ps --format json", "vagrant up", "slow"]);
assert_eq!(fake.last("vagrant").map(|c| c.line()), Some("vagrant up".to_owned()));
assert!(fake.last("terraform").is_none());
}
#[test]
fn an_unscripted_call_panics_naming_it_and_the_script() {
let fake = FakeProcesses::script().allow("docker compose ps", Reply::ok("[]")).build();
let message = panic_of(|| drop(run_on(&fake, "docker info --format x")));
assert!(message.contains("unscripted call `docker info --format x`"), "{message}");
assert!(message.contains("docker compose ps"), "the script is listed: {message}");
let again = panic_of(move || drop(fake));
assert!(again.contains("unscripted call `docker info --format x`"), "{again}");
}
#[test]
fn a_program_must_match_whole_and_its_arguments_in_order() {
let fake = FakeProcesses::script().allow("docker compose ps", Reply::ok("")).build();
for line in ["dockerd compose ps", "docker ps compose", "docker compose"] {
let message = panic_of(|| drop(run_on(&fake, line)));
assert!(message.contains("unscripted call"), "{line}: {message}");
}
panic_of(move || drop(fake));
}
#[test]
fn a_star_stands_for_any_one_argument() {
let fake = FakeProcesses::script().expect_times("docker compose -p * ps", 2, Reply::ok("[]")).build();
assert_eq!(run_on(&fake, "docker compose -p stack ps").unwrap().stdout, ["[]"]);
assert_eq!(run_on(&fake, "docker compose -p other ps -a").unwrap().stdout, ["[]"]);
}
#[test]
fn an_expectation_never_met_panics_when_the_fake_goes() {
let fake = FakeProcesses::script()
.allow("docker info", Reply::ok("29.0.0"))
.expect("vagrant up", Reply::ok(""))
.build();
run_on(&fake, "docker info").unwrap();
let message = panic_of(move || drop(fake));
assert!(message.contains("`vagrant up` was expected AtLeastOnce, made 0 time(s)"), "{message}");
assert!(message.contains("docker info"), "the calls made are listed: {message}");
}
#[test]
fn a_call_made_more_often_than_its_count_panics_when_the_fake_goes() {
let fake = FakeProcesses::script().expect_times("vagrant status", 1, Reply::ok("")).build();
run_on(&fake, "vagrant status").unwrap();
run_on(&fake, "vagrant status").unwrap();
let message = panic_of(move || drop(fake));
assert!(message.contains("`vagrant status` was expected Exactly(1), made 2 time(s)"), "{message}");
}
#[test]
fn the_expectation_naming_more_arguments_answers_whatever_the_order() {
let general_first = FakeProcesses::script()
.allow("docker compose", Reply::ok("general"))
.allow("docker compose ps", Reply::ok("specific"))
.build();
let specific_first = FakeProcesses::script()
.allow("docker compose ps", Reply::ok("specific"))
.allow("docker compose", Reply::ok("general"))
.build();
for fake in [general_first, specific_first] {
assert_eq!(run_on(&fake, "docker compose ps -q").unwrap().stdout, ["specific"]);
assert_eq!(run_on(&fake, "docker compose up").unwrap().stdout, ["general"]);
}
}
#[test]
fn two_expectations_matching_a_call_equally_panic() {
let fake = FakeProcesses::script()
.allow("docker compose * ps", Reply::ok("a"))
.allow("docker compose -p *", Reply::ok("b"))
.build();
let message = panic_of(|| drop(run_on(&fake, "docker compose -p ps")));
assert!(message.contains("matches 2 expectations equally"), "{message}");
panic_of(move || drop(fake));
}
#[test]
fn the_calls_made_are_read_by_program_arguments_and_options() {
let fake = FakeProcesses::script().allow("docker", Reply::ok("")).allow("vagrant", Reply::ok("")).build();
for line in [
"docker compose -p stack --profile access up -d",
"docker info",
"vagrant up web --provider=libvirt",
] {
run_on(&fake, line).unwrap();
}
let up = fake.made("docker compose * * --profile");
assert_eq!(up.len(), 1, "{up:?}");
let up = up.first().unwrap();
assert_eq!((up.flag("-p"), up.flag("--profile")), (Some("stack"), Some("access")));
assert!(up.has("-d") && up.has_run(&["access", "up"]) && !up.has_run(&["up", "access"]));
let vagrant = fake.made("vagrant up");
assert_eq!(vagrant.first().and_then(|c| c.flag("--provider")), Some("libvirt"));
assert!(fake.made("dockerd").is_empty() && fake.made("docker compose ps").is_empty());
}
#[test]
fn a_model_answers_whatever_it_is_asked_and_adds_nothing() {
let model = FakeProcesses::model(|_| Reply::ok(""));
let out = run_on(&model, "docker info --format {{.ServerVersion}}").unwrap();
assert!(out.stdout.is_empty(), "{:?}", out.stdout);
}
#[tokio::test(start_paused = true)]
async fn a_paced_reply_prints_its_lines_a_pace_apart() {
let fake = FakeProcesses::script().expect("pull", Reply::ok("a\nb").paced(Duration::from_secs(60))).build();
let started = tokio::time::Instant::now();
let mut seen = Vec::new();
fake.run(&spec("pull"), &mut |_, line| seen.push((line.to_owned(), started.elapsed().as_secs())))
.await
.unwrap();
assert_eq!(seen, [("a".to_owned(), 60), ("b".to_owned(), 120)]);
}
}