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)]
137#[derive(Debug, Clone)]
138pub struct RecordingMockRunner {
139 inner: MockCommandRunner,
140 calls: std::sync::Arc<std::sync::Mutex<Vec<Vec<String>>>>,
141}
142
143#[cfg(test)]
144impl RecordingMockRunner {
145 #[must_use]
147 pub fn success(stdout: &str) -> Self {
148 Self {
149 inner: MockCommandRunner::success(stdout),
150 calls: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
151 }
152 }
153
154 #[must_use]
156 pub fn failure(stderr: &str, code: i32) -> Self {
157 Self {
158 inner: MockCommandRunner::failure(stderr, code),
159 calls: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
160 }
161 }
162
163 #[must_use]
170 pub fn calls(&self) -> Vec<Vec<String>> {
171 self.calls
172 .lock()
173 .expect("RecordingMockRunner mutex poisoned")
174 .clone()
175 }
176}
177
178#[cfg(test)]
179#[async_trait::async_trait]
180impl CommandRunner for RecordingMockRunner {
181 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
182 self.calls
183 .lock()
184 .expect("RecordingMockRunner mutex poisoned")
185 .push(args.iter().map(|s| (*s).to_owned()).collect());
186 self.inner.run(program, args).await
187 }
188
189 async fn run_with_stdin(
190 &self,
191 program: &str,
192 args: &[&str],
193 stdin_data: &[u8],
194 ) -> std::io::Result<CommandOutput> {
195 self.calls
196 .lock()
197 .expect("RecordingMockRunner mutex poisoned")
198 .push(args.iter().map(|s| (*s).to_owned()).collect());
199 self.inner.run_with_stdin(program, args, stdin_data).await
200 }
201}
202
203#[cfg(test)]
209#[derive(Debug, Clone)]
210pub struct SequencedMockCommandRunner {
211 responses: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<CommandOutput>>>,
212 recorded: std::sync::Arc<std::sync::Mutex<RecordedCalls>>,
214}
215
216#[cfg(test)]
217impl SequencedMockCommandRunner {
218 #[must_use]
220 pub fn new(outputs: Vec<CommandOutput>) -> Self {
221 Self {
222 responses: std::sync::Arc::new(std::sync::Mutex::new(outputs.into())),
223 recorded: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
224 }
225 }
226
227 #[must_use]
229 pub fn from_results(results: &[(bool, &str)]) -> Self {
230 let outputs = results
231 .iter()
232 .map(|&(ok, text)| {
233 if ok {
234 CommandOutput {
235 status: MockCommandRunner::make_exit_status(0),
236 stdout: text.as_bytes().to_vec(),
237 stderr: Vec::new(),
238 }
239 } else {
240 CommandOutput {
241 status: MockCommandRunner::make_exit_status(1),
242 stdout: Vec::new(),
243 stderr: text.as_bytes().to_vec(),
244 }
245 }
246 })
247 .collect();
248 Self::new(outputs)
249 }
250
251 #[must_use]
258 pub fn recorded_calls(&self) -> Vec<(String, Vec<String>)> {
259 self.recorded.lock().expect("mock mutex poisoned").clone()
260 }
261}
262
263#[cfg(test)]
264#[async_trait::async_trait]
265impl CommandRunner for SequencedMockCommandRunner {
266 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
267 self.recorded.lock().expect("mock mutex poisoned").push((
268 program.to_string(),
269 args.iter().map(|s| (*s).to_string()).collect(),
270 ));
271 let mut guard = self
272 .responses
273 .lock()
274 .expect("SequencedMockCommandRunner mutex poisoned");
275 guard
276 .pop_front()
277 .ok_or_else(|| std::io::Error::other("no more responses"))
278 }
279
280 async fn run_with_stdin(
281 &self,
282 program: &str,
283 args: &[&str],
284 _stdin_data: &[u8],
285 ) -> std::io::Result<CommandOutput> {
286 self.run(program, args).await
287 }
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293
294 #[tokio::test]
295 async fn test_should_return_success_output_from_mock() {
296 let runner = MockCommandRunner::success("hello");
297 let output = runner
298 .run("gc", &["--version"])
299 .await
300 .expect("should succeed");
301 assert!(output.status.success());
302 assert_eq!(output.stdout, b"hello");
303 assert!(output.stderr.is_empty());
304 }
305
306 #[tokio::test]
307 async fn test_should_return_failure_output_from_mock() {
308 let runner = MockCommandRunner::failure("not found", 1);
309 let output = runner
310 .run("gc", &["repo", "view"])
311 .await
312 .expect("should succeed");
313 assert!(!output.status.success());
314 assert!(output.stdout.is_empty());
315 assert_eq!(output.stderr, b"not found");
316 }
317
318 #[tokio::test]
319 async fn test_should_return_spawn_error_from_mock() {
320 let runner = MockCommandRunner::spawn_error();
321 let err = runner
322 .run("gc", &["--version"])
323 .await
324 .expect_err("should fail");
325 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
326 }
327
328 #[tokio::test]
329 async fn test_should_clone_command_output() {
330 let runner = MockCommandRunner::success("data");
331 let output = runner.run("gc", &[]).await.expect("should succeed");
332 let cloned = output.clone();
333 assert_eq!(output.stdout, cloned.stdout);
334 assert_eq!(output.stderr, cloned.stderr);
335 }
336
337 #[tokio::test]
338 async fn test_should_clone_mock_runner() {
339 let runner = MockCommandRunner::success("cloneable");
340 let cloned = runner.clone();
341 let output = cloned.run("gc", &[]).await.expect("should succeed");
342 assert_eq!(output.stdout, b"cloneable");
343 }
344
345 #[tokio::test]
346 async fn test_should_record_arguments_in_recording_runner() {
347 let runner = RecordingMockRunner::success("{}");
348 let output = runner
349 .run("gc", &["pr", "view", "20", "--json"])
350 .await
351 .expect("should succeed");
352 assert!(output.status.success());
353
354 let calls = runner.calls();
355 assert_eq!(calls.len(), 1);
356 assert_eq!(calls[0], vec!["pr", "view", "20", "--json"]);
357 }
358
359 #[tokio::test]
360 async fn test_should_record_multiple_calls_in_order() {
361 let runner = RecordingMockRunner::success("ok");
362 runner
363 .run("gc", &["issue", "label", "1", "--add", "bug"])
364 .await
365 .expect("first");
366 runner
367 .run("gc", &["issue", "label", "1", "--remove", "bug"])
368 .await
369 .expect("second");
370
371 let calls = runner.calls();
372 assert_eq!(calls.len(), 2);
373 assert_eq!(calls[1], vec!["issue", "label", "1", "--remove", "bug"]);
374 }
375
376 #[tokio::test]
377 async fn test_should_yield_sequenced_responses() {
378 let runner = SequencedMockCommandRunner::from_results(&[
379 (true, "first"),
380 (false, "error"),
381 (true, "third"),
382 ]);
383
384 let out1 = runner.run("gc", &[]).await.expect("first should succeed");
385 assert!(out1.status.success());
386 assert_eq!(out1.stdout, b"first");
387
388 let out2 = runner
389 .run("gc", &[])
390 .await
391 .expect("second should 'succeed' as Output");
392 assert!(!out2.status.success());
393 assert_eq!(out2.stderr, b"error");
394
395 let out3 = runner.run("gc", &[]).await.expect("third should succeed");
396 assert_eq!(out3.stdout, b"third");
397 }
398
399 #[tokio::test]
400 async fn test_should_error_when_sequence_exhausted() {
401 let runner = SequencedMockCommandRunner::from_results(&[(true, "only")]);
402
403 let _ = runner.run("gc", &[]).await.expect("first call");
404 let err = runner.run("gc", &[]).await.expect_err("exhausted");
405 assert_eq!(err.kind(), std::io::ErrorKind::Other);
406 }
407
408 #[tokio::test]
409 async fn test_should_record_argv_for_each_sequenced_call() {
410 let runner = SequencedMockCommandRunner::from_results(&[(true, "[]"), (true, "[]")]);
411
412 runner
413 .run("gitcode", &["issue", "list", "--page", "1"])
414 .await
415 .expect("first call should succeed");
416 runner
417 .run("gitcode", &["issue", "list", "--page", "2"])
418 .await
419 .expect("second call should succeed");
420
421 let calls = runner.recorded_calls();
422 assert_eq!(calls.len(), 2);
423 assert_eq!(calls[0].0, "gitcode");
424 assert!(calls[0].1.contains(&"1".to_string()));
425 assert!(calls[1].1.contains(&"2".to_string()));
426 }
427}