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`. One answer is the fake's own: the engine probe (`docker
95    /// info --format {{.ServerVersion}}`), which a script answers with a success that prints
96    /// nothing (its catch-all), prints a version, as a running Docker does; the runner reads an
97    /// empty answer as a daemon down (Docker 26 and older exit 0 then), so a script that means a
98    /// down engine answers the probe itself, with a failure or an empty line (`"\n"`).
99    pub fn new(script: impl Fn(&Call) -> Reply + Send + Sync + 'static) -> FakeProcesses {
100        FakeProcesses {
101            script: Box::new(move |call| {
102                let reply = script(call);
103                let silent_success = reply.code == 0 && !reply.missing && reply.stdout.is_empty();
104                if silent_success && call.program == "docker" && call.args.first().map(String::as_str) == Some("info") {
105                    return Reply::ok("29.0.0");
106                }
107                reply
108            }),
109            calls: Mutex::new(Vec::new()),
110        }
111    }
112
113    /// Each call answered by the first rule whose text its line contains; any other succeeds
114    /// with no output.
115    #[must_use]
116    pub fn rules(rules: &[(&str, Reply)]) -> FakeProcesses {
117        let rules: Vec<(String, Reply)> = rules.iter().map(|(k, r)| ((*k).to_owned(), r.clone())).collect();
118        FakeProcesses::new(move |call| {
119            let line = call.line();
120            rules
121                .iter()
122                .find(|(k, _)| line.contains(k.as_str()))
123                .map_or_else(|| Reply::ok(""), |(_, r)| r.clone())
124        })
125    }
126
127    /// Every call so far.
128    pub fn calls(&self) -> Vec<Call> {
129        self.calls.lock().unwrap_or_else(PoisonError::into_inner).clone()
130    }
131
132    /// Every call so far, as lines.
133    pub(crate) fn lines(&self) -> Vec<String> {
134        self.calls().iter().map(Call::line).collect()
135    }
136
137    /// The last call whose line contains `text`.
138    pub fn last(&self, text: &str) -> Option<Call> {
139        self.calls().into_iter().rev().find(|c| c.line().contains(text))
140    }
141
142    async fn answer(&self, spec: &ProcessSpec, on_line: OnLine<'_>) -> Result<Exit, ProcessError> {
143        let reply = (self.script)(spec);
144        self.calls.lock().unwrap_or_else(PoisonError::into_inner).push(spec.clone());
145        if !reply.delay.is_zero() {
146            tokio::time::sleep(reply.delay).await;
147        }
148        if reply.missing {
149            return Err(ProcessError::Missing { program: spec.program.clone() });
150        }
151        let lines = reply.stdout.iter().map(|l| (Stream::Stdout, l));
152        for (stream, line) in lines.chain(reply.stderr.iter().map(|l| (Stream::Stderr, l))) {
153            if !reply.pace.is_zero() {
154                tokio::time::sleep(reply.pace).await;
155            }
156            on_line(stream, line);
157        }
158        Ok(Exit { code: Some(reply.code) })
159    }
160}
161
162impl ProcessRunner for FakeProcesses {
163    fn run<'a>(&'a self, spec: &'a ProcessSpec, on_line: OnLine<'a>) -> BoxFuture<'a, Result<Exit, ProcessError>> {
164        Box::pin(self.answer(spec, on_line))
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use crate::process::capture;
172
173    #[tokio::test(start_paused = true)]
174    async fn calls_are_recorded_and_answered_by_rule() {
175        let fake = FakeProcesses::rules(&[
176            ("compose ps", Reply::ok("[]")),
177            ("vagrant", Reply::missing()),
178            ("slow", Reply::fail(2, "boom").after(Duration::from_secs(600))),
179        ]);
180        assert_eq!(capture(&fake, &ProcessSpec::new("docker", ["compose", "ps"])).await.unwrap().stdout, ["[]"]);
181        assert!(matches!(
182            capture(&fake, &ProcessSpec::new("vagrant", ["up"])).await,
183            Err(ProcessError::Missing { .. })
184        ));
185        let slow = capture(&fake, &ProcessSpec::new("slow", Vec::<String>::new())).await.unwrap();
186        assert_eq!((slow.exit, slow.stderr), (Exit { code: Some(2) }, vec!["boom".to_owned()]));
187        assert_eq!(fake.lines(), ["docker compose ps", "vagrant up", "slow"]);
188        assert!(fake.last("vagrant").is_some() && fake.last("terraform").is_none());
189    }
190
191    #[tokio::test(start_paused = true)]
192    async fn a_paced_reply_prints_its_lines_a_pace_apart() {
193        let fake = FakeProcesses::rules(&[("pull", Reply::ok("a\nb").paced(Duration::from_secs(60)))]);
194        let started = tokio::time::Instant::now();
195        let mut seen = Vec::new();
196        let spec = ProcessSpec::new("pull", Vec::<String>::new());
197        fake.run(&spec, &mut |_, line| seen.push((line.to_owned(), started.elapsed().as_secs())))
198            .await
199            .unwrap();
200        assert_eq!(seen, [("a".to_owned(), 60), ("b".to_owned(), 120)]);
201    }
202}