1#[cfg(test)]
9use std::process::ExitStatus;
10#[cfg(test)]
11use std::sync::Arc;
12
13pub use gitflow_cli_adapter_utils::{
14 CommandOutput, CommandRunner, EnvSource, RealCommandRunner, RealEnv,
15};
16
17#[cfg(test)]
19type RecordedCall = (String, Vec<String>);
20
21#[cfg(test)]
23type RecordedCalls = Vec<RecordedCall>;
24
25#[cfg(test)]
30#[derive(Debug, Clone)]
31pub struct MockCommandRunner {
32 result: MockResult,
33 recorded: Arc<std::sync::Mutex<RecordedCalls>>,
35}
36
37#[cfg(test)]
38#[derive(Debug, Clone)]
39enum MockResult {
40 Output(CommandOutput),
42 Error(std::io::ErrorKind, String),
44}
45
46#[cfg(test)]
47impl MockCommandRunner {
48 #[cfg(unix)]
49 pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
50 use std::os::unix::process::ExitStatusExt;
51 ExitStatus::from_raw(code)
52 }
53
54 #[cfg(windows)]
55 pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
56 use std::os::windows::process::ExitStatusExt;
57 let raw = u32::try_from(code).unwrap_or(1);
59 ExitStatus::from_raw(raw)
60 }
61
62 #[must_use]
64 pub fn success(stdout: &str) -> Self {
65 Self {
66 result: MockResult::Output(CommandOutput {
67 status: Self::make_exit_status(0),
68 stdout: stdout.as_bytes().to_vec(),
69 stderr: Vec::new(),
70 }),
71 recorded: Arc::new(std::sync::Mutex::new(Vec::new())),
72 }
73 }
74
75 #[must_use]
81 pub fn success_with_stderr(stdout: &str, stderr: &str) -> Self {
82 Self {
83 result: MockResult::Output(CommandOutput {
84 status: Self::make_exit_status(0),
85 stdout: stdout.as_bytes().to_vec(),
86 stderr: stderr.as_bytes().to_vec(),
87 }),
88 recorded: Arc::new(std::sync::Mutex::new(Vec::new())),
89 }
90 }
91
92 #[must_use]
94 pub fn failure(stderr: &str, code: i32) -> Self {
95 Self {
96 result: MockResult::Output(CommandOutput {
97 status: Self::make_exit_status(code),
98 stdout: Vec::new(),
99 stderr: stderr.as_bytes().to_vec(),
100 }),
101 recorded: Arc::new(std::sync::Mutex::new(Vec::new())),
102 }
103 }
104
105 #[must_use]
107 pub fn spawn_error() -> Self {
108 Self {
109 result: MockResult::Error(std::io::ErrorKind::NotFound, "command not found".to_owned()),
110 recorded: Arc::new(std::sync::Mutex::new(Vec::new())),
111 }
112 }
113
114 #[must_use]
121 pub fn recorded_calls(&self) -> Vec<(String, Vec<String>)> {
122 self.recorded.lock().expect("mock mutex poisoned").clone()
123 }
124}
125
126#[cfg(test)]
127#[async_trait::async_trait]
128impl CommandRunner for MockCommandRunner {
129 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
130 self.recorded.lock().expect("mock mutex poisoned").push((
131 program.to_string(),
132 args.iter().map(|s| (*s).to_string()).collect(),
133 ));
134 match &self.result {
135 MockResult::Output(output) => Ok(output.clone()),
136 MockResult::Error(kind, message) => Err(std::io::Error::new(*kind, message.clone())),
137 }
138 }
139
140 async fn run_with_stdin(
141 &self,
142 program: &str,
143 args: &[&str],
144 _stdin_data: &[u8],
145 ) -> std::io::Result<CommandOutput> {
146 self.recorded.lock().expect("mock mutex poisoned").push((
147 program.to_string(),
148 args.iter().map(|s| (*s).to_string()).collect(),
149 ));
150 self.run(program, args).await
151 }
152}
153
154#[cfg(test)]
160#[derive(Debug, Clone)]
161pub struct SequencedMockCommandRunner {
162 responses: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<CommandOutput>>>,
163 recorded: Arc<std::sync::Mutex<RecordedCalls>>,
165}
166
167#[cfg(test)]
168impl SequencedMockCommandRunner {
169 #[must_use]
171 pub fn new(outputs: Vec<CommandOutput>) -> Self {
172 Self {
173 responses: std::sync::Arc::new(std::sync::Mutex::new(outputs.into())),
174 recorded: Arc::new(std::sync::Mutex::new(Vec::new())),
175 }
176 }
177
178 #[must_use]
183 pub fn from_results(results: &[(bool, &str)]) -> Self {
184 let outputs = results
185 .iter()
186 .map(|&(ok, text)| {
187 if ok {
188 CommandOutput {
189 status: MockCommandRunner::make_exit_status(0),
190 stdout: text.as_bytes().to_vec(),
191 stderr: Vec::new(),
192 }
193 } else {
194 CommandOutput {
195 status: MockCommandRunner::make_exit_status(1),
196 stdout: Vec::new(),
197 stderr: text.as_bytes().to_vec(),
198 }
199 }
200 })
201 .collect();
202 Self::new(outputs)
203 }
204
205 #[must_use]
212 pub fn recorded_calls(&self) -> Vec<(String, Vec<String>)> {
213 self.recorded.lock().expect("mock mutex poisoned").clone()
214 }
215}
216
217#[cfg(test)]
218#[async_trait::async_trait]
219impl CommandRunner for SequencedMockCommandRunner {
220 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
221 self.recorded.lock().expect("mock mutex poisoned").push((
222 program.to_string(),
223 args.iter().map(|s| (*s).to_string()).collect(),
224 ));
225 let mut guard = self
226 .responses
227 .lock()
228 .expect("SequencedMockCommandRunner mutex poisoned");
229 guard
230 .pop_front()
231 .ok_or_else(|| std::io::Error::other("no more responses"))
232 }
233
234 async fn run_with_stdin(
235 &self,
236 program: &str,
237 args: &[&str],
238 _stdin_data: &[u8],
239 ) -> std::io::Result<CommandOutput> {
240 self.run(program, args).await
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[tokio::test]
249 async fn test_should_return_success_output_from_mock() {
250 let runner = MockCommandRunner::success("hello");
251 let output = runner
252 .run("glab", &["--version"])
253 .await
254 .expect("should succeed");
255 assert!(output.status.success());
256 assert_eq!(output.stdout, b"hello");
257 assert!(output.stderr.is_empty());
258 }
259
260 #[tokio::test]
261 async fn test_should_return_failure_output_from_mock() {
262 let runner = MockCommandRunner::failure("not found", 1);
263 let output = runner
264 .run("glab", &["repo", "view"])
265 .await
266 .expect("should succeed");
267 assert!(!output.status.success());
268 assert!(output.stdout.is_empty());
269 assert_eq!(output.stderr, b"not found");
270 }
271
272 #[tokio::test]
273 async fn test_should_return_spawn_error_from_mock() {
274 let runner = MockCommandRunner::spawn_error();
275 let err = runner
276 .run("glab", &["--version"])
277 .await
278 .expect_err("should fail");
279 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
280 }
281
282 #[tokio::test]
283 async fn test_should_clone_command_output() {
284 let runner = MockCommandRunner::success("data");
285 let output = runner.run("glab", &[]).await.expect("should succeed");
286 let cloned = output.clone();
287 assert_eq!(output.stdout, cloned.stdout);
288 assert_eq!(output.stderr, cloned.stderr);
289 }
290
291 #[tokio::test]
292 async fn test_should_clone_mock_runner() {
293 let runner = MockCommandRunner::success("cloneable");
294 let cloned = runner.clone();
295 let output = cloned.run("glab", &[]).await.expect("should succeed");
296 assert_eq!(output.stdout, b"cloneable");
297 }
298
299 #[tokio::test]
300 async fn test_should_yield_sequenced_responses() {
301 let runner = SequencedMockCommandRunner::from_results(&[
302 (true, "first"),
303 (false, "error"),
304 (true, "third"),
305 ]);
306
307 let out1 = runner.run("glab", &[]).await.expect("first should succeed");
308 assert!(out1.status.success());
309 assert_eq!(out1.stdout, b"first");
310
311 let out2 = runner
312 .run("glab", &[])
313 .await
314 .expect("second should 'succeed' as Output");
315 assert!(!out2.status.success());
316 assert_eq!(out2.stderr, b"error");
317
318 let out3 = runner.run("glab", &[]).await.expect("third should succeed");
319 assert_eq!(out3.stdout, b"third");
320 }
321
322 #[tokio::test]
323 async fn test_should_error_when_sequence_exhausted() {
324 let runner = SequencedMockCommandRunner::from_results(&[(true, "only")]);
325
326 let _ = runner.run("glab", &[]).await.expect("first call");
327 let err = runner.run("glab", &[]).await.expect_err("exhausted");
328 assert_eq!(err.kind(), std::io::ErrorKind::Other);
329 }
330
331 #[tokio::test]
332 async fn test_should_record_glab_calls() {
333 let runner = MockCommandRunner::success("ok");
334 runner
335 .run("glab", &["issue", "close", "42", "--repo", "owner/repo"])
336 .await
337 .expect("should succeed");
338 let calls = runner.recorded_calls();
339 assert_eq!(calls.len(), 1);
340 assert_eq!(calls[0].0, "glab");
341 assert_eq!(
342 calls[0].1,
343 vec!["issue", "close", "42", "--repo", "owner/repo"]
344 .into_iter()
345 .map(String::from)
346 .collect::<Vec<_>>()
347 );
348 }
349
350 #[tokio::test]
351 async fn test_should_record_sequenced_glab_calls() {
352 let runner = SequencedMockCommandRunner::from_results(&[(true, "first"), (true, "second")]);
353 runner
354 .run("glab", &["issue", "list", "--repo", "owner/repo"])
355 .await
356 .expect("first should succeed");
357 runner
358 .run("glab", &["issue", "view", "1", "--repo", "owner/repo"])
359 .await
360 .expect("second should succeed");
361 let calls = runner.recorded_calls();
362 assert_eq!(calls.len(), 2);
363 assert_eq!(calls[0].0, "glab");
364 assert_eq!(calls[1].0, "glab");
365 assert_eq!(
366 calls[1].1,
367 vec!["issue", "view", "1", "--repo", "owner/repo"]
368 );
369 }
370}