1#[cfg(test)]
9use std::process::ExitStatus;
10
11pub use gitflow_cli_adapter_utils::{
12 CommandOutput, CommandRunner, EnvSource, RealCommandRunner, RealEnv,
13};
14
15#[cfg(test)]
20#[derive(Debug, Clone)]
21pub struct MockCommandRunner {
22 result: MockResult,
23 recorded: std::sync::Arc<std::sync::Mutex<RecordedCalls>>,
25}
26
27#[cfg(test)]
29type RecordedCall = (String, Vec<String>);
30
31#[cfg(test)]
33type RecordedCalls = Vec<RecordedCall>;
34
35#[cfg(test)]
36#[derive(Debug, Clone)]
37enum MockResult {
38 Output(CommandOutput),
40 Error(std::io::ErrorKind, String),
42}
43
44#[cfg(test)]
45impl MockCommandRunner {
46 #[cfg(unix)]
47 pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
48 use std::os::unix::process::ExitStatusExt;
49 ExitStatus::from_raw(code)
50 }
51
52 #[cfg(windows)]
53 pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
54 use std::os::windows::process::ExitStatusExt;
55 let raw = u32::try_from(code).unwrap_or(1);
57 ExitStatus::from_raw(raw)
58 }
59
60 #[must_use]
62 pub fn success(stdout: &str) -> Self {
63 Self {
64 result: MockResult::Output(CommandOutput {
65 status: Self::make_exit_status(0),
66 stdout: stdout.as_bytes().to_vec(),
67 stderr: Vec::new(),
68 }),
69 recorded: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
70 }
71 }
72
73 #[must_use]
75 pub fn failure(stderr: &str, code: i32) -> Self {
76 Self {
77 result: MockResult::Output(CommandOutput {
78 status: Self::make_exit_status(code),
79 stdout: Vec::new(),
80 stderr: stderr.as_bytes().to_vec(),
81 }),
82 recorded: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
83 }
84 }
85
86 #[must_use]
88 pub fn spawn_error() -> Self {
89 Self {
90 result: MockResult::Error(std::io::ErrorKind::NotFound, "command not found".to_owned()),
91 recorded: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
92 }
93 }
94
95 #[must_use]
102 pub fn recorded_calls(&self) -> Vec<(String, Vec<String>)> {
103 self.recorded.lock().expect("mock mutex poisoned").clone()
104 }
105}
106
107#[cfg(test)]
108#[async_trait::async_trait]
109impl CommandRunner for MockCommandRunner {
110 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
111 self.recorded.lock().expect("mock mutex poisoned").push((
112 program.to_string(),
113 args.iter().map(|s| (*s).to_string()).collect(),
114 ));
115 match &self.result {
116 MockResult::Output(output) => Ok(output.clone()),
117 MockResult::Error(kind, message) => Err(std::io::Error::new(*kind, message.clone())),
118 }
119 }
120
121 async fn run_with_stdin(
122 &self,
123 program: &str,
124 args: &[&str],
125 _stdin_data: &[u8],
126 ) -> std::io::Result<CommandOutput> {
127 self.run(program, args).await
128 }
129}
130
131#[cfg(test)]
139#[derive(Debug, Clone)]
140pub struct SequencedMockCommandRunner {
141 responses: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<CommandOutput>>>,
142 recorded: std::sync::Arc<std::sync::Mutex<RecordedCalls>>,
144}
145
146#[cfg(test)]
147impl SequencedMockCommandRunner {
148 #[must_use]
155 pub fn new(outputs: Vec<CommandOutput>) -> Self {
156 Self {
157 responses: std::sync::Arc::new(std::sync::Mutex::new(outputs.into())),
158 recorded: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
159 }
160 }
161
162 #[must_use]
167 pub fn from_results(results: &[(bool, &str)]) -> Self {
168 let outputs = results
169 .iter()
170 .map(|&(ok, text)| {
171 if ok {
172 CommandOutput {
173 status: MockCommandRunner::make_exit_status(0),
174 stdout: text.as_bytes().to_vec(),
175 stderr: Vec::new(),
176 }
177 } else {
178 CommandOutput {
179 status: MockCommandRunner::make_exit_status(1),
180 stdout: Vec::new(),
181 stderr: text.as_bytes().to_vec(),
182 }
183 }
184 })
185 .collect();
186 Self::new(outputs)
187 }
188
189 #[must_use]
196 pub fn recorded_calls(&self) -> RecordedCalls {
197 self.recorded.lock().expect("mock mutex poisoned").clone()
198 }
199}
200
201#[cfg(test)]
202#[async_trait::async_trait]
203impl CommandRunner for SequencedMockCommandRunner {
204 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
205 self.recorded.lock().expect("mock mutex poisoned").push((
206 program.to_string(),
207 args.iter().map(|s| (*s).to_string()).collect(),
208 ));
209 let mut guard = self
210 .responses
211 .lock()
212 .expect("SequencedMockCommandRunner mutex poisoned");
213 guard
214 .pop_front()
215 .ok_or_else(|| std::io::Error::other("no more responses"))
216 }
217
218 async fn run_with_stdin(
219 &self,
220 program: &str,
221 args: &[&str],
222 _stdin_data: &[u8],
223 ) -> std::io::Result<CommandOutput> {
224 self.run(program, args).await
225 }
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231
232 #[tokio::test]
233 async fn test_should_return_success_output_from_mock() {
234 let runner = MockCommandRunner::success("hello");
235 let output = runner
236 .run("gh", &["--version"])
237 .await
238 .expect("should succeed");
239 assert!(output.status.success());
240 assert_eq!(output.stdout, b"hello");
241 assert!(output.stderr.is_empty());
242 }
243
244 #[tokio::test]
245 async fn test_should_return_failure_output_from_mock() {
246 let runner = MockCommandRunner::failure("not found", 1);
247 let output = runner
248 .run("gh", &["repo", "view"])
249 .await
250 .expect("should succeed");
251 assert!(!output.status.success());
252 assert!(output.stdout.is_empty());
253 assert_eq!(output.stderr, b"not found");
254 }
255
256 #[tokio::test]
257 async fn test_should_return_spawn_error_from_mock() {
258 let runner = MockCommandRunner::spawn_error();
259 let err = runner
260 .run("gh", &["--version"])
261 .await
262 .expect_err("should fail");
263 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
264 }
265
266 #[tokio::test]
267 async fn test_should_clone_command_output() {
268 let runner = MockCommandRunner::success("data");
269 let output = runner.run("gh", &[]).await.expect("should succeed");
270 let cloned = output.clone();
271 assert_eq!(output.stdout, cloned.stdout);
272 assert_eq!(output.stderr, cloned.stderr);
273 }
274
275 #[tokio::test]
276 async fn test_should_clone_mock_runner() {
277 let runner = MockCommandRunner::success("cloneable");
278 let cloned = runner.clone();
279 let output = cloned.run("gh", &[]).await.expect("should succeed");
280 assert_eq!(output.stdout, b"cloneable");
281 }
282
283 #[tokio::test]
284 async fn test_should_yield_sequenced_responses() {
285 let runner = SequencedMockCommandRunner::from_results(&[
286 (true, "first"),
287 (false, "error"),
288 (true, "third"),
289 ]);
290
291 let out1 = runner.run("gh", &[]).await.expect("first should succeed");
292 assert!(out1.status.success());
293 assert_eq!(out1.stdout, b"first");
294
295 let out2 = runner
296 .run("gh", &[])
297 .await
298 .expect("second should 'succeed' as Output");
299 assert!(!out2.status.success());
300 assert_eq!(out2.stderr, b"error");
301
302 let out3 = runner.run("gh", &[]).await.expect("third should succeed");
303 assert_eq!(out3.stdout, b"third");
304 }
305
306 #[tokio::test]
307 async fn test_should_error_when_sequence_exhausted() {
308 let runner = SequencedMockCommandRunner::from_results(&[(true, "only")]);
309
310 let _ = runner.run("gh", &[]).await.expect("first call");
311 let err = runner.run("gh", &[]).await.expect_err("exhausted");
312 assert_eq!(err.kind(), std::io::ErrorKind::Other);
313 }
314
315 #[tokio::test]
316 async fn test_should_record_calls() {
317 let runner = MockCommandRunner::success("ok");
318 runner
319 .run("gh", &["label", "list"])
320 .await
321 .expect("should run");
322 runner
323 .run_with_stdin("gh", &["api", "repos/o/r"], b"data")
324 .await
325 .expect("should run with stdin");
326 let calls = runner.recorded_calls();
327 assert_eq!(calls.len(), 2);
328 assert_eq!(calls[0].0, "gh");
329 assert_eq!(calls[0].1, vec!["label", "list"]);
330 assert_eq!(calls[1].0, "gh");
331 assert_eq!(calls[1].1, vec!["api", "repos/o/r"]);
332 }
333}