1use std::process::ExitStatus;
8
9#[derive(Debug, Clone)]
11pub struct CommandOutput {
12 pub status: ExitStatus,
14 pub stdout: Vec<u8>,
16 pub stderr: Vec<u8>,
18}
19
20#[async_trait::async_trait]
22pub trait CommandRunner: std::fmt::Debug + Send + Sync {
23 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput>;
29
30 async fn run_with_stdin(
41 &self,
42 program: &str,
43 args: &[&str],
44 stdin_data: &[u8],
45 ) -> std::io::Result<CommandOutput>;
46}
47
48#[derive(Debug, Clone, Default)]
50pub struct RealCommandRunner;
51
52#[async_trait::async_trait]
53impl CommandRunner for RealCommandRunner {
54 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
55 let output = tokio::process::Command::new(program)
56 .args(args)
57 .output()
58 .await?;
59 Ok(CommandOutput {
60 status: output.status,
61 stdout: output.stdout,
62 stderr: output.stderr,
63 })
64 }
65
66 async fn run_with_stdin(
67 &self,
68 program: &str,
69 args: &[&str],
70 stdin_data: &[u8],
71 ) -> std::io::Result<CommandOutput> {
72 use tokio::io::AsyncWriteExt;
73
74 let mut child = tokio::process::Command::new(program)
75 .args(args)
76 .stdin(std::process::Stdio::piped())
77 .stdout(std::process::Stdio::piped())
78 .stderr(std::process::Stdio::piped())
79 .spawn()?;
80
81 if let Some(mut stdin) = child.stdin.take() {
82 stdin.write_all(stdin_data).await?;
83 drop(stdin);
84 }
85
86 let output = child.wait_with_output().await?;
87 Ok(CommandOutput {
88 status: output.status,
89 stdout: output.stdout,
90 stderr: output.stderr,
91 })
92 }
93}
94
95#[cfg(test)]
100#[derive(Debug, Clone)]
101pub struct MockCommandRunner {
102 result: MockResult,
103}
104
105#[cfg(test)]
106#[derive(Debug, Clone)]
107enum MockResult {
108 Output(CommandOutput),
110 Error(std::io::ErrorKind, String),
112}
113
114#[cfg(test)]
115impl MockCommandRunner {
116 #[cfg(unix)]
117 pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
118 use std::os::unix::process::ExitStatusExt;
119 ExitStatus::from_raw(code)
120 }
121
122 #[cfg(windows)]
123 pub(crate) fn make_exit_status(code: i32) -> ExitStatus {
124 use std::os::windows::process::ExitStatusExt;
125 let raw = u32::try_from(code).unwrap_or(1);
127 ExitStatus::from_raw(raw)
128 }
129
130 #[must_use]
132 pub fn success(stdout: &str) -> Self {
133 Self {
134 result: MockResult::Output(CommandOutput {
135 status: Self::make_exit_status(0),
136 stdout: stdout.as_bytes().to_vec(),
137 stderr: Vec::new(),
138 }),
139 }
140 }
141
142 #[must_use]
144 pub fn failure(stderr: &str, code: i32) -> Self {
145 Self {
146 result: MockResult::Output(CommandOutput {
147 status: Self::make_exit_status(code),
148 stdout: Vec::new(),
149 stderr: stderr.as_bytes().to_vec(),
150 }),
151 }
152 }
153
154 #[must_use]
156 pub fn spawn_error() -> Self {
157 Self {
158 result: MockResult::Error(std::io::ErrorKind::NotFound, "command not found".to_owned()),
159 }
160 }
161}
162
163#[cfg(test)]
164#[async_trait::async_trait]
165impl CommandRunner for MockCommandRunner {
166 async fn run(&self, _program: &str, _args: &[&str]) -> std::io::Result<CommandOutput> {
167 match &self.result {
168 MockResult::Output(output) => Ok(output.clone()),
169 MockResult::Error(kind, message) => Err(std::io::Error::new(*kind, message.clone())),
170 }
171 }
172
173 async fn run_with_stdin(
174 &self,
175 program: &str,
176 args: &[&str],
177 _stdin_data: &[u8],
178 ) -> std::io::Result<CommandOutput> {
179 self.run(program, args).await
180 }
181}
182
183#[cfg(test)]
189#[derive(Debug, Clone)]
190pub struct RecordingMockRunner {
191 inner: MockCommandRunner,
192 calls: std::sync::Arc<std::sync::Mutex<Vec<Vec<String>>>>,
193}
194
195#[cfg(test)]
196impl RecordingMockRunner {
197 #[must_use]
199 pub fn success(stdout: &str) -> Self {
200 Self {
201 inner: MockCommandRunner::success(stdout),
202 calls: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
203 }
204 }
205
206 #[must_use]
208 pub fn failure(stderr: &str, code: i32) -> Self {
209 Self {
210 inner: MockCommandRunner::failure(stderr, code),
211 calls: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
212 }
213 }
214
215 #[must_use]
222 pub fn calls(&self) -> Vec<Vec<String>> {
223 self.calls
224 .lock()
225 .expect("RecordingMockRunner mutex poisoned")
226 .clone()
227 }
228}
229
230#[cfg(test)]
231#[async_trait::async_trait]
232impl CommandRunner for RecordingMockRunner {
233 async fn run(&self, program: &str, args: &[&str]) -> std::io::Result<CommandOutput> {
234 self.calls
235 .lock()
236 .expect("RecordingMockRunner mutex poisoned")
237 .push(args.iter().map(|s| (*s).to_owned()).collect());
238 self.inner.run(program, args).await
239 }
240
241 async fn run_with_stdin(
242 &self,
243 program: &str,
244 args: &[&str],
245 stdin_data: &[u8],
246 ) -> std::io::Result<CommandOutput> {
247 self.calls
248 .lock()
249 .expect("RecordingMockRunner mutex poisoned")
250 .push(args.iter().map(|s| (*s).to_owned()).collect());
251 self.inner.run_with_stdin(program, args, stdin_data).await
252 }
253}
254
255#[cfg(test)]
261#[derive(Debug, Clone)]
262pub struct SequencedMockCommandRunner {
263 responses: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<CommandOutput>>>,
264}
265
266#[cfg(test)]
267impl SequencedMockCommandRunner {
268 #[must_use]
270 pub fn new(outputs: Vec<CommandOutput>) -> Self {
271 Self {
272 responses: std::sync::Arc::new(std::sync::Mutex::new(outputs.into())),
273 }
274 }
275
276 #[must_use]
278 pub fn from_results(results: &[(bool, &str)]) -> Self {
279 let outputs = results
280 .iter()
281 .map(|&(ok, text)| {
282 if ok {
283 CommandOutput {
284 status: MockCommandRunner::make_exit_status(0),
285 stdout: text.as_bytes().to_vec(),
286 stderr: Vec::new(),
287 }
288 } else {
289 CommandOutput {
290 status: MockCommandRunner::make_exit_status(1),
291 stdout: Vec::new(),
292 stderr: text.as_bytes().to_vec(),
293 }
294 }
295 })
296 .collect();
297 Self::new(outputs)
298 }
299}
300
301#[cfg(test)]
302#[async_trait::async_trait]
303impl CommandRunner for SequencedMockCommandRunner {
304 async fn run(&self, _program: &str, _args: &[&str]) -> std::io::Result<CommandOutput> {
305 let mut guard = self
306 .responses
307 .lock()
308 .expect("SequencedMockCommandRunner mutex poisoned");
309 guard
310 .pop_front()
311 .ok_or_else(|| std::io::Error::other("no more responses"))
312 }
313
314 async fn run_with_stdin(
315 &self,
316 program: &str,
317 args: &[&str],
318 _stdin_data: &[u8],
319 ) -> std::io::Result<CommandOutput> {
320 self.run(program, args).await
321 }
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327
328 #[tokio::test]
329 async fn test_should_return_success_output_from_mock() {
330 let runner = MockCommandRunner::success("hello");
331 let output = runner
332 .run("gc", &["--version"])
333 .await
334 .expect("should succeed");
335 assert!(output.status.success());
336 assert_eq!(output.stdout, b"hello");
337 assert!(output.stderr.is_empty());
338 }
339
340 #[tokio::test]
341 async fn test_should_return_failure_output_from_mock() {
342 let runner = MockCommandRunner::failure("not found", 1);
343 let output = runner
344 .run("gc", &["repo", "view"])
345 .await
346 .expect("should succeed");
347 assert!(!output.status.success());
348 assert!(output.stdout.is_empty());
349 assert_eq!(output.stderr, b"not found");
350 }
351
352 #[tokio::test]
353 async fn test_should_return_spawn_error_from_mock() {
354 let runner = MockCommandRunner::spawn_error();
355 let err = runner
356 .run("gc", &["--version"])
357 .await
358 .expect_err("should fail");
359 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
360 }
361
362 #[tokio::test]
363 async fn test_should_clone_command_output() {
364 let runner = MockCommandRunner::success("data");
365 let output = runner.run("gc", &[]).await.expect("should succeed");
366 let cloned = output.clone();
367 assert_eq!(output.stdout, cloned.stdout);
368 assert_eq!(output.stderr, cloned.stderr);
369 }
370
371 #[tokio::test]
372 async fn test_should_clone_mock_runner() {
373 let runner = MockCommandRunner::success("cloneable");
374 let cloned = runner.clone();
375 let output = cloned.run("gc", &[]).await.expect("should succeed");
376 assert_eq!(output.stdout, b"cloneable");
377 }
378
379 #[tokio::test]
380 async fn test_should_record_arguments_in_recording_runner() {
381 let runner = RecordingMockRunner::success("{}");
382 let output = runner
383 .run("gc", &["pr", "view", "20", "--json"])
384 .await
385 .expect("should succeed");
386 assert!(output.status.success());
387
388 let calls = runner.calls();
389 assert_eq!(calls.len(), 1);
390 assert_eq!(calls[0], vec!["pr", "view", "20", "--json"]);
391 }
392
393 #[tokio::test]
394 async fn test_should_record_multiple_calls_in_order() {
395 let runner = RecordingMockRunner::success("ok");
396 runner
397 .run("gc", &["issue", "label", "1", "--add", "bug"])
398 .await
399 .expect("first");
400 runner
401 .run("gc", &["issue", "label", "1", "--remove", "bug"])
402 .await
403 .expect("second");
404
405 let calls = runner.calls();
406 assert_eq!(calls.len(), 2);
407 assert_eq!(calls[1], vec!["issue", "label", "1", "--remove", "bug"]);
408 }
409
410 #[tokio::test]
411 async fn test_should_yield_sequenced_responses() {
412 let runner = SequencedMockCommandRunner::from_results(&[
413 (true, "first"),
414 (false, "error"),
415 (true, "third"),
416 ]);
417
418 let out1 = runner.run("gc", &[]).await.expect("first should succeed");
419 assert!(out1.status.success());
420 assert_eq!(out1.stdout, b"first");
421
422 let out2 = runner
423 .run("gc", &[])
424 .await
425 .expect("second should 'succeed' as Output");
426 assert!(!out2.status.success());
427 assert_eq!(out2.stderr, b"error");
428
429 let out3 = runner.run("gc", &[]).await.expect("third should succeed");
430 assert_eq!(out3.stdout, b"third");
431 }
432
433 #[tokio::test]
434 async fn test_should_error_when_sequence_exhausted() {
435 let runner = SequencedMockCommandRunner::from_results(&[(true, "only")]);
436
437 let _ = runner.run("gc", &[]).await.expect("first call");
438 let err = runner.run("gc", &[]).await.expect_err("exhausted");
439 assert_eq!(err.kind(), std::io::ErrorKind::Other);
440 }
441}