isothrum_runner/process/
fake.rs1use 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 #[cfg(test)]
64 #[must_use]
65 pub(crate) fn after(mut self, delay: Duration) -> Reply {
66 self.delay = delay;
67 self
68 }
69
70 #[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
81pub 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 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 #[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 pub fn calls(&self) -> Vec<Call> {
129 self.calls.lock().unwrap_or_else(PoisonError::into_inner).clone()
130 }
131
132 pub(crate) fn lines(&self) -> Vec<String> {
134 self.calls().iter().map(Call::line).collect()
135 }
136
137 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}