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 {
96 FakeProcesses {
97 script: Box::new(script),
98 calls: Mutex::new(Vec::new()),
99 }
100 }
101
102 #[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 pub fn calls(&self) -> Vec<Call> {
118 self.calls.lock().unwrap_or_else(PoisonError::into_inner).clone()
119 }
120
121 pub(crate) fn lines(&self) -> Vec<String> {
123 self.calls().iter().map(Call::line).collect()
124 }
125
126 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}