Skip to main content

isothrum_runner/process/
fake.rs

1//! Scripted processes for tests (feature `fake`): every call is recorded and answered from the
2//! test's script, so code that drives docker, vagrant or terraform runs without them and never
3//! touches real ones. In this crate's tests a reply can take time (`Reply::after`) and print its
4//! lines over time (`Reply::paced`): under Tokio's paused clock that time passes at once, so
5//! timeouts are tested without waiting.
6
7use std::sync::{Mutex, PoisonError};
8use std::time::Duration;
9
10use super::{Exit, OnLine, ProcessError, ProcessRunner, ProcessSpec};
11use crate::BoxFuture;
12use crate::events::Stream;
13
14/// One call a test's code made: the process it asked for, as it asked.
15pub type Call = ProcessSpec;
16
17/// A scripted process's answer.
18#[derive(Debug, Clone, PartialEq, Eq, Default)]
19#[non_exhaustive]
20pub struct Reply {
21    /// Its standard output lines.
22    pub stdout: Vec<String>,
23    /// Its standard error lines.
24    pub stderr: Vec<String>,
25    /// Its exit code.
26    pub code: i32,
27    /// Not installed.
28    pub missing: bool,
29    /// How long it runs before answering.
30    pub delay: Duration,
31    /// How long it runs before each line it prints, after `delay` (a slow download's progress).
32    pub pace: Duration,
33}
34
35impl Reply {
36    /// Exits 0, printing `stdout`'s lines.
37    pub fn ok(stdout: &str) -> Reply {
38        Reply {
39            stdout: stdout.lines().map(str::to_owned).collect(),
40            ..Reply::default()
41        }
42    }
43
44    /// Exits with `code`, printing `stderr`'s lines.
45    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    /// Isn't installed.
54    #[must_use]
55    pub fn missing() -> Reply {
56        Reply {
57            missing: true,
58            ..Reply::default()
59        }
60    }
61
62    /// The same answer, after running for `delay`.
63    #[cfg(test)]
64    #[must_use]
65    pub(crate) fn after(mut self, delay: Duration) -> Reply {
66        self.delay = delay;
67        self
68    }
69
70    /// The same answer, each line printed `pace` after the one before.
71    #[cfg(test)]
72    #[must_use]
73    pub(crate) fn paced(mut self, pace: Duration) -> Reply {
74        self.pace = pace;
75        self
76    }
77}
78
79type Script = Box<dyn Fn(&Call) -> Reply + Send + Sync>;
80
81/// Processes answered from a script.
82pub struct FakeProcesses {
83    script: Script,
84    calls: Mutex<Vec<Call>>,
85}
86
87impl std::fmt::Debug for FakeProcesses {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        f.debug_struct("FakeProcesses").field("calls", &self.lines()).finish_non_exhaustive()
90    }
91}
92
93impl FakeProcesses {
94    /// Each call answered by `script`.
95    pub fn new(script: impl Fn(&Call) -> Reply + Send + Sync + 'static) -> FakeProcesses {
96        FakeProcesses {
97            script: Box::new(script),
98            calls: Mutex::new(Vec::new()),
99        }
100    }
101
102    /// Each call answered by the first rule whose text its line contains; any other succeeds
103    /// with no output.
104    #[must_use]
105    pub fn rules(rules: &[(&str, Reply)]) -> FakeProcesses {
106        let rules: Vec<(String, Reply)> = rules.iter().map(|(k, r)| ((*k).to_owned(), r.clone())).collect();
107        FakeProcesses::new(move |call| {
108            let line = call.line();
109            rules
110                .iter()
111                .find(|(k, _)| line.contains(k.as_str()))
112                .map_or_else(|| Reply::ok(""), |(_, r)| r.clone())
113        })
114    }
115
116    /// Every call so far.
117    pub fn calls(&self) -> Vec<Call> {
118        self.calls.lock().unwrap_or_else(PoisonError::into_inner).clone()
119    }
120
121    /// Every call so far, as lines.
122    pub(crate) fn lines(&self) -> Vec<String> {
123        self.calls().iter().map(Call::line).collect()
124    }
125
126    /// The last call whose line contains `text`.
127    pub fn last(&self, text: &str) -> Option<Call> {
128        self.calls().into_iter().rev().find(|c| c.line().contains(text))
129    }
130
131    async fn answer(&self, spec: &ProcessSpec, on_line: OnLine<'_>) -> Result<Exit, ProcessError> {
132        let reply = (self.script)(spec);
133        self.calls.lock().unwrap_or_else(PoisonError::into_inner).push(spec.clone());
134        if !reply.delay.is_zero() {
135            tokio::time::sleep(reply.delay).await;
136        }
137        if reply.missing {
138            return Err(ProcessError::Missing { program: spec.program.clone() });
139        }
140        let lines = reply.stdout.iter().map(|l| (Stream::Stdout, l));
141        for (stream, line) in lines.chain(reply.stderr.iter().map(|l| (Stream::Stderr, l))) {
142            if !reply.pace.is_zero() {
143                tokio::time::sleep(reply.pace).await;
144            }
145            on_line(stream, line);
146        }
147        Ok(Exit { code: Some(reply.code) })
148    }
149}
150
151impl ProcessRunner for FakeProcesses {
152    fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
153        Box::pin(self.answer(spec, on_line))
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160    use crate::process::capture;
161
162    #[tokio::test(start_paused = true)]
163    async fn calls_are_recorded_and_answered_by_rule() {
164        let fake = FakeProcesses::rules(&[
165            ("compose ps", Reply::ok("[]")),
166            ("vagrant", Reply::missing()),
167            ("slow", Reply::fail(2, "boom").after(Duration::from_secs(600))),
168        ]);
169        assert_eq!(capture(&fake, &ProcessSpec::new("docker", ["compose", "ps"])).await.unwrap().stdout, ["[]"]);
170        assert!(matches!(
171            capture(&fake, &ProcessSpec::new("vagrant", ["up"])).await,
172            Err(ProcessError::Missing { .. })
173        ));
174        let slow = capture(&fake, &ProcessSpec::new("slow", Vec::<String>::new())).await.unwrap();
175        assert_eq!((slow.exit, slow.stderr), (Exit { code: Some(2) }, vec!["boom".to_owned()]));
176        assert_eq!(fake.lines(), ["docker compose ps", "vagrant up", "slow"]);
177        assert!(fake.last("vagrant").is_some() && fake.last("terraform").is_none());
178    }
179
180    #[tokio::test(start_paused = true)]
181    async fn a_paced_reply_prints_its_lines_a_pace_apart() {
182        let fake = FakeProcesses::rules(&[("pull", Reply::ok("a\nb").paced(Duration::from_secs(60)))]);
183        let started = tokio::time::Instant::now();
184        let mut seen = Vec::new();
185        let spec = ProcessSpec::new("pull", Vec::<String>::new());
186        fake.run(&spec, &mut |_, line| seen.push((line.to_owned(), started.elapsed().as_secs())))
187            .await
188            .unwrap();
189        assert_eq!(seen, [("a".to_owned(), 60), ("b".to_owned(), 120)]);
190    }
191}