1use std::sync::{Mutex, PoisonError};
8use std::time::Duration;
9
10use super::{Exit, OnLine, ProcessError, ProcessRunner, ProcessSpec};
11use crate::BoxFuture;
12use crate::events::Stream;
13
14pub type Call = ProcessSpec;
16
17#[derive(Debug, Clone, PartialEq, Eq, Default)]
19#[non_exhaustive]
20pub struct Reply {
21 pub stdout: Vec<String>,
23 pub stderr: Vec<String>,
25 pub code: i32,
27 pub missing: bool,
29 pub delay: Duration,
31 pub pace: Duration,
33}
34
35impl Reply {
36 pub fn ok(stdout: &str) -> Reply {
38 Reply {
39 stdout: stdout.lines().map(str::to_owned).collect(),
40 ..Reply::default()
41 }
42 }
43
44 pub fn fail(code: i32, stderr: &str) -> Reply {
46 Reply {
47 stderr: stderr.lines().map(str::to_owned).collect(),
48 code,
49 ..Reply::default()
50 }
51 }
52
53 #[must_use]
55 pub fn missing() -> Reply {
56 Reply {
57 missing: true,
58 ..Reply::default()
59 }
60 }
61
62 #[must_use]
64 pub fn after(mut self, delay: Duration) -> Reply {
65 self.delay = delay;
66 self
67 }
68
69 #[cfg(test)]
71 #[must_use]
72 pub(crate) fn paced(mut self, pace: Duration) -> Reply {
73 self.pace = pace;
74 self
75 }
76}
77
78type Answer = Box<dyn Fn(&Call) -> Reply + Send + Sync>;
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82enum Times {
83 AtLeastOnce,
85 Exactly(usize),
87 Any,
89}
90
91#[derive(Debug, Clone)]
94struct Expectation {
95 program: String,
96 args: Vec<String>,
97 reply: Reply,
98 times: Times,
99}
100
101impl Expectation {
102 #[expect(clippy::panic, reason = "a script that names no program is the test's mistake, said at once")]
103 fn new(call: &str, reply: Reply, times: Times) -> Expectation {
104 let mut words = call.split_whitespace().map(str::to_owned);
105 let Some(program) = words.next() else {
106 panic!("a scripted call names its program: {call:?}");
107 };
108 Expectation {
109 program,
110 args: words.collect(),
111 reply,
112 times,
113 }
114 }
115
116 fn matches(&self, call: &Call) -> bool {
117 call.program == self.program && call.args.len() >= self.args.len() && self.args.iter().zip(&call.args).all(|(want, got)| want == "*" || want == got)
118 }
119
120 fn describe(&self) -> String {
121 std::iter::once(self.program.as_str())
122 .chain(self.args.iter().map(String::as_str))
123 .collect::<Vec<_>>()
124 .join(" ")
125 }
126}
127
128#[derive(Debug, Clone, Default)]
135#[must_use]
136pub struct Script {
137 expectations: Vec<Expectation>,
138}
139
140impl Script {
141 pub fn expect(mut self, call: &str, reply: Reply) -> Script {
144 self.expectations.push(Expectation::new(call, reply, Times::AtLeastOnce));
145 self
146 }
147
148 pub fn expect_times(mut self, call: &str, times: usize, reply: Reply) -> Script {
150 self.expectations.push(Expectation::new(call, reply, Times::Exactly(times)));
151 self
152 }
153
154 pub fn allow(mut self, call: &str, reply: Reply) -> Script {
156 self.expectations.push(Expectation::new(call, reply, Times::Any));
157 self
158 }
159
160 #[must_use]
162 pub fn build(self) -> FakeProcesses {
163 FakeProcesses {
164 answer: Strictness::Strict {
165 used: Mutex::new(vec![0; self.expectations.len()]),
166 script: self,
167 },
168 calls: Mutex::new(Vec::new()),
169 unscripted: Mutex::new(Vec::new()),
170 }
171 }
172
173 fn answering(&self, call: &Call) -> Result<(usize, &Expectation), String> {
176 let matching: Vec<(usize, &Expectation)> = self.expectations.iter().enumerate().filter(|(_, e)| e.matches(call)).collect();
177 let most = matching.iter().map(|(_, e)| e.args.len()).max();
178 let best: Vec<(usize, &Expectation)> = matching.into_iter().filter(|(_, e)| Some(e.args.len()) == most).collect();
179 match best.as_slice() {
180 [one] => Ok(*one),
181 [] => Err(format!("unscripted call `{}`; the script expects:\n{}", call.line(), self.listing())),
182 many => Err(format!(
183 "call `{}` matches {} expectations equally: {}",
184 call.line(),
185 many.len(),
186 many.iter().map(|(_, e)| format!("`{}`", e.describe())).collect::<Vec<_>>().join(", ")
187 )),
188 }
189 }
190
191 fn listing(&self) -> String {
192 self.expectations.iter().map(|e| format!(" {}", e.describe())).collect::<Vec<_>>().join("\n")
193 }
194}
195
196enum Strictness {
198 Modelled(Answer),
200 Strict { script: Script, used: Mutex<Vec<usize>> },
202}
203
204pub struct FakeProcesses {
206 answer: Strictness,
207 calls: Mutex<Vec<Call>>,
208 unscripted: Mutex<Vec<String>>,
210}
211
212impl std::fmt::Debug for FakeProcesses {
213 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214 f.debug_struct("FakeProcesses").field("calls", &self.lines()).finish_non_exhaustive()
215 }
216}
217
218impl FakeProcesses {
219 pub fn model(answer: impl Fn(&Call) -> Reply + Send + Sync + 'static) -> FakeProcesses {
224 FakeProcesses {
225 answer: Strictness::Modelled(Box::new(answer)),
226 calls: Mutex::new(Vec::new()),
227 unscripted: Mutex::new(Vec::new()),
228 }
229 }
230
231 pub fn script() -> Script {
233 Script::default()
234 }
235
236 #[expect(clippy::panic, reason = "an unscripted call fails the test that made it")]
238 fn reply(&self, call: &Call) -> Reply {
239 match &self.answer {
240 Strictness::Modelled(answer) => answer(call),
241 Strictness::Strict { script, used } => match script.answering(call) {
242 Ok((i, expectation)) => {
243 if let Some(n) = used.lock().unwrap_or_else(PoisonError::into_inner).get_mut(i) {
244 *n += 1;
245 }
246 expectation.reply.clone()
247 }
248 Err(why) => {
249 self.unscripted.lock().unwrap_or_else(PoisonError::into_inner).push(why.clone());
250 panic!("{why}");
251 }
252 },
253 }
254 }
255
256 fn unmet(&self) -> Vec<String> {
258 let mut unmet = self.unscripted.lock().unwrap_or_else(PoisonError::into_inner).clone();
259 if let Strictness::Strict { script, used } = &self.answer {
260 let used = used.lock().unwrap_or_else(PoisonError::into_inner);
261 for (e, &n) in script.expectations.iter().zip(used.iter()) {
262 let met = match e.times {
263 Times::AtLeastOnce => n > 0,
264 Times::Exactly(times) => n == times,
265 Times::Any => true,
266 };
267 if !met {
268 unmet.push(format!("`{}` was expected {:?}, made {n} time(s)", e.describe(), e.times));
269 }
270 }
271 }
272 unmet
273 }
274
275 pub fn made(&self, call: &str) -> Vec<Call> {
279 let wanted = Expectation::new(call, Reply::default(), Times::Any);
280 self.calls().into_iter().filter(|c| wanted.matches(c)).collect()
281 }
282
283 pub fn calls(&self) -> Vec<Call> {
285 self.calls.lock().unwrap_or_else(PoisonError::into_inner).clone()
286 }
287
288 pub(crate) fn lines(&self) -> Vec<String> {
290 self.calls().iter().map(Call::line).collect()
291 }
292
293 pub fn last(&self, text: &str) -> Option<Call> {
295 self.calls().into_iter().rev().find(|c| c.line().contains(text))
296 }
297
298 async fn answer(&self, spec: &ProcessSpec, on_line: OnLine<'_>) -> Result<Exit, ProcessError> {
299 let reply = self.reply(spec);
300 self.calls.lock().unwrap_or_else(PoisonError::into_inner).push(spec.clone());
301 if !reply.delay.is_zero() {
302 tokio::time::sleep(reply.delay).await;
303 }
304 if reply.missing {
305 return Err(ProcessError::Missing { program: spec.program.clone() });
306 }
307 let lines = reply.stdout.iter().map(|l| (Stream::Stdout, l));
308 for (stream, line) in lines.chain(reply.stderr.iter().map(|l| (Stream::Stderr, l))) {
309 if !reply.pace.is_zero() {
310 tokio::time::sleep(reply.pace).await;
311 }
312 on_line(stream, line);
313 }
314 Ok(Exit { code: Some(reply.code) })
315 }
316}
317
318pub trait CallView {
320 fn flag(&self, name: &str) -> Option<&str>;
322 fn has(&self, name: &str) -> bool;
324 fn has_run(&self, run: &[&str]) -> bool;
326}
327
328impl CallView for Call {
329 fn flag(&self, name: &str) -> Option<&str> {
330 let prefixed = format!("{name}=");
331 let mut found = None;
332 let mut args = self.args.iter().peekable();
333 while let Some(arg) = args.next() {
334 if arg == name {
335 found = args.peek().map(|v| v.as_str());
336 } else if let Some(value) = arg.strip_prefix(&prefixed) {
337 found = Some(value);
338 }
339 }
340 found
341 }
342
343 fn has(&self, name: &str) -> bool {
344 self.args.iter().any(|a| a == name)
345 }
346
347 fn has_run(&self, run: &[&str]) -> bool {
348 run.is_empty() || self.args.windows(run.len()).any(|w| w.iter().zip(run).all(|(a, b)| a == b))
349 }
350}
351
352impl Drop for FakeProcesses {
353 fn drop(&mut self) {
354 let unmet = self.unmet();
355 if std::thread::panicking() {
356 return;
357 }
358 assert!(
359 unmet.is_empty(),
360 "the scripted processes weren't run as scripted:\n{}\ncalls made:\n{}",
361 unmet.join("\n"),
362 self.lines().join("\n")
363 );
364 }
365}
366
367impl ProcessRunner for FakeProcesses {
368 fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
369 Box::pin(self.answer(spec, on_line))
370 }
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376 use crate::process::{Captured, capture};
377
378 fn spec(line: &str) -> ProcessSpec {
379 let mut words = line.split_whitespace();
380 ProcessSpec::new(words.next().unwrap(), words)
381 }
382
383 fn panic_of(f: impl FnOnce()) -> String {
385 let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).expect_err("it panics");
386 err.downcast_ref::<String>()
387 .cloned()
388 .or_else(|| err.downcast_ref::<&str>().map(|s| (*s).to_owned()))
389 .unwrap()
390 }
391
392 fn run_on(fake: &FakeProcesses, line: &str) -> Result<Captured, ProcessError> {
394 let rt = tokio::runtime::Builder::new_current_thread().enable_time().start_paused(true).build().unwrap();
395 rt.block_on(capture(fake, &spec(line)))
396 }
397
398 #[tokio::test(start_paused = true)]
399 async fn a_scripted_call_is_answered_and_recorded() {
400 let fake = FakeProcesses::script()
401 .expect("docker compose ps", Reply::ok("[]"))
402 .expect("vagrant up", Reply::missing())
403 .expect("slow", Reply::fail(2, "boom").after(Duration::from_secs(600)))
404 .build();
405 assert_eq!(capture(&fake, &spec("docker compose ps --format json")).await.unwrap().stdout, ["[]"]);
406 assert!(matches!(capture(&fake, &spec("vagrant up")).await, Err(ProcessError::Missing { ref program }) if program == "vagrant"));
407 let slow = capture(&fake, &spec("slow")).await.unwrap();
408 assert_eq!((slow.exit, slow.stderr_tail), (Exit { code: Some(2) }, vec!["boom".to_owned()]));
409 assert_eq!(fake.lines(), ["docker compose ps --format json", "vagrant up", "slow"]);
410 assert_eq!(fake.last("vagrant").map(|c| c.line()), Some("vagrant up".to_owned()));
411 assert!(fake.last("terraform").is_none());
412 }
413
414 #[test]
415 fn an_unscripted_call_panics_naming_it_and_the_script() {
416 let fake = FakeProcesses::script().allow("docker compose ps", Reply::ok("[]")).build();
417 let message = panic_of(|| drop(run_on(&fake, "docker info --format x")));
418 assert!(message.contains("unscripted call `docker info --format x`"), "{message}");
419 assert!(message.contains("docker compose ps"), "the script is listed: {message}");
420 let again = panic_of(move || drop(fake));
422 assert!(again.contains("unscripted call `docker info --format x`"), "{again}");
423 }
424
425 #[test]
426 fn a_program_must_match_whole_and_its_arguments_in_order() {
427 let fake = FakeProcesses::script().allow("docker compose ps", Reply::ok("")).build();
428 for line in ["dockerd compose ps", "docker ps compose", "docker compose"] {
429 let message = panic_of(|| drop(run_on(&fake, line)));
430 assert!(message.contains("unscripted call"), "{line}: {message}");
431 }
432 panic_of(move || drop(fake));
433 }
434
435 #[test]
436 fn a_star_stands_for_any_one_argument() {
437 let fake = FakeProcesses::script().expect_times("docker compose -p * ps", 2, Reply::ok("[]")).build();
438 assert_eq!(run_on(&fake, "docker compose -p stack ps").unwrap().stdout, ["[]"]);
439 assert_eq!(run_on(&fake, "docker compose -p other ps -a").unwrap().stdout, ["[]"]);
440 }
441
442 #[test]
443 fn an_expectation_never_met_panics_when_the_fake_goes() {
444 let fake = FakeProcesses::script()
445 .allow("docker info", Reply::ok("29.0.0"))
446 .expect("vagrant up", Reply::ok(""))
447 .build();
448 run_on(&fake, "docker info").unwrap();
449 let message = panic_of(move || drop(fake));
450 assert!(message.contains("`vagrant up` was expected AtLeastOnce, made 0 time(s)"), "{message}");
451 assert!(message.contains("docker info"), "the calls made are listed: {message}");
452 }
453
454 #[test]
455 fn a_call_made_more_often_than_its_count_panics_when_the_fake_goes() {
456 let fake = FakeProcesses::script().expect_times("vagrant status", 1, Reply::ok("")).build();
457 run_on(&fake, "vagrant status").unwrap();
458 run_on(&fake, "vagrant status").unwrap();
459 let message = panic_of(move || drop(fake));
460 assert!(message.contains("`vagrant status` was expected Exactly(1), made 2 time(s)"), "{message}");
461 }
462
463 #[test]
464 fn the_expectation_naming_more_arguments_answers_whatever_the_order() {
465 let general_first = FakeProcesses::script()
466 .allow("docker compose", Reply::ok("general"))
467 .allow("docker compose ps", Reply::ok("specific"))
468 .build();
469 let specific_first = FakeProcesses::script()
470 .allow("docker compose ps", Reply::ok("specific"))
471 .allow("docker compose", Reply::ok("general"))
472 .build();
473 for fake in [general_first, specific_first] {
474 assert_eq!(run_on(&fake, "docker compose ps -q").unwrap().stdout, ["specific"]);
475 assert_eq!(run_on(&fake, "docker compose up").unwrap().stdout, ["general"]);
476 }
477 }
478
479 #[test]
480 fn two_expectations_matching_a_call_equally_panic() {
481 let fake = FakeProcesses::script()
482 .allow("docker compose * ps", Reply::ok("a"))
483 .allow("docker compose -p *", Reply::ok("b"))
484 .build();
485 let message = panic_of(|| drop(run_on(&fake, "docker compose -p ps")));
486 assert!(message.contains("matches 2 expectations equally"), "{message}");
487 panic_of(move || drop(fake));
488 }
489
490 #[test]
491 fn the_calls_made_are_read_by_program_arguments_and_options() {
492 let fake = FakeProcesses::script().allow("docker", Reply::ok("")).allow("vagrant", Reply::ok("")).build();
493 for line in [
494 "docker compose -p stack --profile access up -d",
495 "docker info",
496 "vagrant up web --provider=libvirt",
497 ] {
498 run_on(&fake, line).unwrap();
499 }
500 let up = fake.made("docker compose * * --profile");
501 assert_eq!(up.len(), 1, "{up:?}");
502 let up = up.first().unwrap();
503 assert_eq!((up.flag("-p"), up.flag("--profile")), (Some("stack"), Some("access")));
504 assert!(up.has("-d") && up.has_run(&["access", "up"]) && !up.has_run(&["up", "access"]));
505 let vagrant = fake.made("vagrant up");
506 assert_eq!(vagrant.first().and_then(|c| c.flag("--provider")), Some("libvirt"));
507 assert!(fake.made("dockerd").is_empty() && fake.made("docker compose ps").is_empty());
508 }
509
510 #[test]
511 fn a_model_answers_whatever_it_is_asked_and_adds_nothing() {
512 let model = FakeProcesses::model(|_| Reply::ok(""));
515 let out = run_on(&model, "docker info --format {{.ServerVersion}}").unwrap();
516 assert!(out.stdout.is_empty(), "{:?}", out.stdout);
517 }
518
519 #[tokio::test(start_paused = true)]
520 async fn a_paced_reply_prints_its_lines_a_pace_apart() {
521 let fake = FakeProcesses::script().expect("pull", Reply::ok("a\nb").paced(Duration::from_secs(60))).build();
522 let started = tokio::time::Instant::now();
523 let mut seen = Vec::new();
524 fake.run(&spec("pull"), &mut |_, line| seen.push((line.to_owned(), started.elapsed().as_secs())))
525 .await
526 .unwrap();
527 assert_eq!(seen, [("a".to_owned(), 60), ("b".to_owned(), 120)]);
528 }
529}