assert_cmd/cmd.rs
1//! [`std::process::Command`] customized for testing.
2
3use std::ffi;
4use std::io;
5use std::io::{Read, Write};
6use std::ops::Deref;
7use std::path;
8use std::process;
9
10use crate::assert::Assert;
11use crate::assert::OutputAssertExt;
12use crate::output::DebugBuffer;
13use crate::output::DebugBytes;
14use crate::output::OutputError;
15use crate::output::OutputOkExt;
16use crate::output::OutputResult;
17
18/// [`std::process::Command`] customized for testing.
19#[derive(Debug)]
20pub struct Command {
21 cmd: process::Command,
22 stdin: Option<bstr::BString>,
23 timeout: Option<std::time::Duration>,
24}
25
26impl Command {
27 /// Constructs a new `Command` from a `std` `Command`.
28 pub fn from_std(cmd: process::Command) -> Self {
29 Self {
30 cmd,
31 stdin: None,
32 timeout: None,
33 }
34 }
35
36 /// Create a `Command` to run a specific binary of the current crate.
37 ///
38 /// See the [`cargo` module documentation][crate::cargo] for caveats and workarounds.
39 ///
40 /// Cargo support:
41 /// - `>1.94`: works
42 /// - `>=1.91,<=1.93`: works with default `build-dir`
43 /// - `<=1.92`: works
44 ///
45 /// # Panic
46 ///
47 /// Panicks if no binary is found
48 ///
49 /// # Examples
50 ///
51 /// ```rust,no_run
52 /// use assert_cmd::Command;
53 /// use assert_cmd::pkg_name;
54 ///
55 /// let mut cmd = Command::cargo_bin(pkg_name!())
56 /// .unwrap();
57 /// let output = cmd.unwrap();
58 /// println!("{:?}", output);
59 /// ```
60 ///
61 /// ```rust,no_run
62 /// use assert_cmd::Command;
63 ///
64 /// let mut cmd = Command::cargo_bin("bin_fixture")
65 /// .unwrap();
66 /// let output = cmd.unwrap();
67 /// println!("{:?}", output);
68 /// ```
69 ///
70 pub fn cargo_bin<S: AsRef<str>>(name: S) -> Result<Self, crate::cargo::CargoError> {
71 let cmd = crate::cargo::cargo_bin_cmd(name)?;
72 Ok(Self::from_std(cmd))
73 }
74
75 /// Write `buffer` to `stdin` when the `Command` is run.
76 ///
77 /// # Examples
78 ///
79 /// ```rust
80 /// use assert_cmd::Command;
81 ///
82 /// let mut cmd = Command::new("cat")
83 /// .arg("-et")
84 /// .write_stdin("42")
85 /// .assert()
86 /// .stdout("42");
87 /// ```
88 pub fn write_stdin<S>(&mut self, buffer: S) -> &mut Self
89 where
90 S: Into<Vec<u8>>,
91 {
92 self.stdin = Some(bstr::BString::from(buffer.into()));
93 self
94 }
95
96 /// Error out if a timeout is reached
97 ///
98 /// ```rust,no_run
99 /// use assert_cmd::Command;
100 ///
101 /// let assert = Command::cargo_bin("bin_fixture")
102 /// .unwrap()
103 /// .timeout(std::time::Duration::from_secs(1))
104 /// .env("sleep", "100")
105 /// .assert();
106 /// assert.failure();
107 /// ```
108 pub fn timeout(&mut self, timeout: std::time::Duration) -> &mut Self {
109 self.timeout = Some(timeout);
110 self
111 }
112
113 /// Write `path`s content to `stdin` when the `Command` is run.
114 ///
115 /// Paths are relative to the [`env::current_dir`][env_current_dir] and not
116 /// [`Command::current_dir`][Command_current_dir].
117 ///
118 /// [env_current_dir]: std::env::current_dir()
119 /// [Command_current_dir]: std::process::Command::current_dir()
120 pub fn pipe_stdin<P>(&mut self, file: P) -> io::Result<&mut Self>
121 where
122 P: AsRef<path::Path>,
123 {
124 let buffer = std::fs::read(file)?;
125 Ok(self.write_stdin(buffer))
126 }
127
128 /// Run a `Command`, returning an [`OutputResult`].
129 ///
130 /// # Examples
131 ///
132 /// ```rust
133 /// use assert_cmd::Command;
134 ///
135 /// let result = Command::new("echo")
136 /// .args(&["42"])
137 /// .ok();
138 /// assert!(result.is_ok());
139 /// ```
140 ///
141 pub fn ok(&mut self) -> OutputResult {
142 OutputOkExt::ok(self)
143 }
144
145 /// Run a `Command`, unwrapping the [`OutputResult`].
146 ///
147 /// # Examples
148 ///
149 /// ```rust
150 /// use assert_cmd::Command;
151 ///
152 /// let output = Command::new("echo")
153 /// .args(&["42"])
154 /// .unwrap();
155 /// ```
156 ///
157 pub fn unwrap(&mut self) -> process::Output {
158 OutputOkExt::unwrap(self)
159 }
160
161 /// Run a `Command`, unwrapping the error in the [`OutputResult`].
162 ///
163 /// # Examples
164 ///
165 /// ```rust,no_run
166 /// use assert_cmd::Command;
167 ///
168 /// let err = Command::new("a-command")
169 /// .args(&["--will-fail"])
170 /// .unwrap_err();
171 /// ```
172 ///
173 /// [Output]: std::process::Output
174 pub fn unwrap_err(&mut self) -> OutputError {
175 OutputOkExt::unwrap_err(self)
176 }
177
178 /// Run a `Command` and make assertions on the [`Output`].
179 ///
180 /// # Examples
181 ///
182 /// ```rust,no_run
183 /// use assert_cmd::Command;
184 ///
185 /// let mut cmd = Command::cargo_bin("bin_fixture")
186 /// .unwrap()
187 /// .assert()
188 /// .success();
189 /// ```
190 ///
191 /// [`Output`]: std::process::Output
192 #[must_use]
193 pub fn assert(&mut self) -> Assert {
194 OutputAssertExt::assert(self)
195 }
196}
197
198/// Mirror [`std::process::Command`]'s API
199impl Command {
200 /// Constructs a new `Command` for launching the program at
201 /// path `program`, with the following default configuration:
202 ///
203 /// * No arguments to the program
204 /// * Inherit the current process's environment
205 /// * Inherit the current process's working directory
206 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
207 ///
208 /// Builder methods are provided to change these defaults and
209 /// otherwise configure the process.
210 ///
211 /// If `program` is not an absolute path, the `PATH` will be searched in
212 /// an OS-defined way.
213 ///
214 /// The search path to be used may be controlled by setting the
215 /// `PATH` environment variable on the Command,
216 /// but this has some implementation limitations on Windows
217 /// (see issue #37519).
218 ///
219 /// # Examples
220 ///
221 /// Basic usage:
222 ///
223 /// ```no_run
224 /// use assert_cmd::Command;
225 ///
226 /// Command::new("sh").unwrap();
227 /// ```
228 pub fn new<S: AsRef<ffi::OsStr>>(program: S) -> Self {
229 let cmd = process::Command::new(program);
230 Self::from_std(cmd)
231 }
232
233 /// Adds an argument to pass to the program.
234 ///
235 /// Only one argument can be passed per use. So instead of:
236 ///
237 /// ```no_run
238 /// # assert_cmd::Command::new("sh")
239 /// .arg("-C /path/to/repo")
240 /// # ;
241 /// ```
242 ///
243 /// usage would be:
244 ///
245 /// ```no_run
246 /// # assert_cmd::Command::new("sh")
247 /// .arg("-C")
248 /// .arg("/path/to/repo")
249 /// # ;
250 /// ```
251 ///
252 /// To pass multiple arguments see [`args`].
253 ///
254 /// [`args`]: Command::args()
255 ///
256 /// # Examples
257 ///
258 /// Basic usage:
259 ///
260 /// ```no_run
261 /// use assert_cmd::Command;
262 ///
263 /// Command::new("ls")
264 /// .arg("-l")
265 /// .arg("-a")
266 /// .unwrap();
267 /// ```
268 pub fn arg<S: AsRef<ffi::OsStr>>(&mut self, arg: S) -> &mut Self {
269 self.cmd.arg(arg);
270 self
271 }
272
273 /// Adds multiple arguments to pass to the program.
274 ///
275 /// To pass a single argument see [`arg`].
276 ///
277 /// [`arg`]: Command::arg()
278 ///
279 /// # Examples
280 ///
281 /// Basic usage:
282 ///
283 /// ```no_run
284 /// use assert_cmd::Command;
285 ///
286 /// Command::new("ls")
287 /// .args(&["-l", "-a"])
288 /// .unwrap();
289 /// ```
290 pub fn args<I, S>(&mut self, args: I) -> &mut Self
291 where
292 I: IntoIterator<Item = S>,
293 S: AsRef<ffi::OsStr>,
294 {
295 self.cmd.args(args);
296 self
297 }
298
299 /// Inserts or updates an environment variable mapping.
300 ///
301 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
302 /// and case-sensitive on all other platforms.
303 ///
304 /// # Examples
305 ///
306 /// Basic usage:
307 ///
308 /// ```no_run
309 /// use assert_cmd::Command;
310 ///
311 /// Command::new("ls")
312 /// .env("PATH", "/bin")
313 /// .unwrap_err();
314 /// ```
315 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
316 where
317 K: AsRef<ffi::OsStr>,
318 V: AsRef<ffi::OsStr>,
319 {
320 self.cmd.env(key, val);
321 self
322 }
323
324 /// Adds or updates multiple environment variable mappings.
325 ///
326 /// # Examples
327 ///
328 /// Basic usage:
329 ///
330 /// ```no_run
331 /// use assert_cmd::Command;
332 /// use std::process::Stdio;
333 /// use std::env;
334 /// use std::collections::HashMap;
335 ///
336 /// let filtered_env : HashMap<String, String> =
337 /// env::vars().filter(|&(ref k, _)|
338 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
339 /// ).collect();
340 ///
341 /// Command::new("printenv")
342 /// .env_clear()
343 /// .envs(&filtered_env)
344 /// .unwrap();
345 /// ```
346 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
347 where
348 I: IntoIterator<Item = (K, V)>,
349 K: AsRef<ffi::OsStr>,
350 V: AsRef<ffi::OsStr>,
351 {
352 self.cmd.envs(vars);
353 self
354 }
355
356 /// Removes an environment variable mapping.
357 ///
358 /// # Examples
359 ///
360 /// Basic usage:
361 ///
362 /// ```no_run
363 /// use assert_cmd::Command;
364 ///
365 /// Command::new("ls")
366 /// .env_remove("PATH")
367 /// .unwrap_err();
368 /// ```
369 pub fn env_remove<K: AsRef<ffi::OsStr>>(&mut self, key: K) -> &mut Self {
370 self.cmd.env_remove(key);
371 self
372 }
373
374 /// Clears the entire environment map for the child process.
375 ///
376 /// # Examples
377 ///
378 /// Basic usage:
379 ///
380 /// ```no_run
381 /// use assert_cmd::Command;
382 ///
383 /// Command::new("ls")
384 /// .env_clear()
385 /// .unwrap_err();
386 /// ```
387 pub fn env_clear(&mut self) -> &mut Self {
388 self.cmd.env_clear();
389 self
390 }
391
392 /// Sets the working directory for the child process.
393 ///
394 /// # Platform-specific behavior
395 ///
396 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
397 /// whether it should be interpreted relative to the parent's working
398 /// directory or relative to `current_dir`. The behavior in this case is
399 /// platform specific and unstable, and it's recommended to use
400 /// [`canonicalize`] to get an absolute program path instead.
401 ///
402 /// # Examples
403 ///
404 /// Basic usage:
405 ///
406 /// ```no_run
407 /// use assert_cmd::Command;
408 ///
409 /// Command::new("ls")
410 /// .current_dir("/bin")
411 /// .unwrap();
412 /// ```
413 ///
414 /// [`canonicalize`]: std::fs::canonicalize()
415 pub fn current_dir<P: AsRef<path::Path>>(&mut self, dir: P) -> &mut Self {
416 self.cmd.current_dir(dir);
417 self
418 }
419
420 /// Executes the `Command` as a child process, waiting for it to finish and collecting all of its
421 /// output.
422 ///
423 /// By default, stdout and stderr are captured (and used to provide the resulting output).
424 /// Stdin is not inherited from the parent and any attempt by the child process to read from
425 /// the stdin stream will result in the stream immediately closing.
426 ///
427 /// # Examples
428 ///
429 /// ```should_panic
430 /// use assert_cmd::Command;
431 /// use std::io::{self, Write};
432 /// let output = Command::new("/bin/cat")
433 /// .arg("file.txt")
434 /// .output()
435 /// .expect("failed to execute process");
436 ///
437 /// println!("status: {}", output.status);
438 /// io::stdout().write_all(&output.stdout).unwrap();
439 /// io::stderr().write_all(&output.stderr).unwrap();
440 ///
441 /// assert!(output.status.success());
442 /// ```
443 pub fn output(&mut self) -> io::Result<process::Output> {
444 let spawn = self.spawn()?;
445 Self::wait_with_input_output(spawn, self.stdin.as_deref().cloned(), self.timeout)
446 }
447
448 /// If `input`, write it to `child`'s stdin while also reading `child`'s
449 /// stdout and stderr, then wait on `child` and return its status and output.
450 ///
451 /// This was lifted from `std::process::Child::wait_with_output` and modified
452 /// to also write to stdin.
453 fn wait_with_input_output(
454 mut child: process::Child,
455 input: Option<Vec<u8>>,
456 timeout: Option<std::time::Duration>,
457 ) -> io::Result<process::Output> {
458 #![allow(clippy::unwrap_used)] // changes behavior in some tests
459
460 fn read<R>(mut input: R) -> std::thread::JoinHandle<io::Result<Vec<u8>>>
461 where
462 R: Read + Send + 'static,
463 {
464 std::thread::spawn(move || {
465 let mut ret = Vec::new();
466 input.read_to_end(&mut ret).map(|_| ret)
467 })
468 }
469
470 let stdin = input.and_then(|i| {
471 child
472 .stdin
473 .take()
474 .map(|mut stdin| std::thread::spawn(move || stdin.write_all(&i)))
475 });
476 let stdout = child.stdout.take().map(read);
477 let stderr = child.stderr.take().map(read);
478
479 // Finish writing stdin before waiting, because waiting drops stdin.
480 stdin.and_then(|t| t.join().unwrap().ok());
481 let status = if let Some(timeout) = timeout {
482 wait_timeout::ChildExt::wait_timeout(&mut child, timeout)
483 .transpose()
484 .unwrap_or_else(|| {
485 let _ = child.kill();
486 child.wait()
487 })
488 } else {
489 child.wait()
490 }?;
491
492 let stdout = stdout
493 .and_then(|t| t.join().unwrap().ok())
494 .unwrap_or_default();
495 let stderr = stderr
496 .and_then(|t| t.join().unwrap().ok())
497 .unwrap_or_default();
498
499 Ok(process::Output {
500 status,
501 stdout,
502 stderr,
503 })
504 }
505
506 fn spawn(&mut self) -> io::Result<process::Child> {
507 // stdout/stderr should only be piped for `output` according to `process::Command::new`.
508 self.cmd.stdin(process::Stdio::piped());
509 self.cmd.stdout(process::Stdio::piped());
510 self.cmd.stderr(process::Stdio::piped());
511
512 self.cmd.spawn()
513 }
514
515 /// Returns the path to the program that was given to [`Command::new`].
516 ///
517 /// # Examples
518 ///
519 /// Basic usage:
520 ///
521 /// ```rust
522 /// use assert_cmd::Command;
523 ///
524 /// let cmd = Command::new("echo");
525 /// assert_eq!(cmd.get_program(), "echo");
526 /// ```
527 pub fn get_program(&self) -> &ffi::OsStr {
528 self.cmd.get_program()
529 }
530
531 /// Returns an iterator of the arguments that will be passed to the program.
532 ///
533 /// This does not include the path to the program as the first argument;
534 /// it only includes the arguments specified with [`Command::arg`] and
535 /// [`Command::args`].
536 ///
537 /// # Examples
538 ///
539 /// Basic usage:
540 ///
541 /// ```rust
542 /// use std::ffi::OsStr;
543 /// use assert_cmd::Command;
544 ///
545 /// let mut cmd = Command::new("echo");
546 /// cmd.arg("first").arg("second");
547 /// let args: Vec<&OsStr> = cmd.get_args().collect();
548 /// assert_eq!(args, &["first", "second"]);
549 /// ```
550 pub fn get_args(&self) -> process::CommandArgs<'_> {
551 self.cmd.get_args()
552 }
553
554 /// Returns an iterator of the environment variables explicitly set for the child process.
555 ///
556 /// Environment variables explicitly set using [`Command::env`], [`Command::envs`], and
557 /// [`Command::env_remove`] can be retrieved with this method.
558 ///
559 /// Note that this output does not include environment variables inherited from the parent
560 /// process.
561 ///
562 /// Each element is a tuple key/value pair `(&OsStr, Option<&OsStr>)`. A [`None`] value
563 /// indicates its key was explicitly removed via [`Command::env_remove`]. The associated key for
564 /// the [`None`] value will no longer inherit from its parent process.
565 ///
566 /// An empty iterator can indicate that no explicit mappings were added or that
567 /// [`Command::env_clear`] was called. After calling [`Command::env_clear`], the child process
568 /// will not inherit any environment variables from its parent process.
569 ///
570 /// # Examples
571 ///
572 /// Basic usage:
573 ///
574 /// ```rust
575 /// use std::ffi::OsStr;
576 /// use assert_cmd::Command;
577 ///
578 /// let mut cmd = Command::new("ls");
579 /// cmd.env("TERM", "dumb").env_remove("TZ");
580 /// let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
581 /// assert_eq!(envs, &[
582 /// (OsStr::new("TERM"), Some(OsStr::new("dumb"))),
583 /// (OsStr::new("TZ"), None)
584 /// ]);
585 /// ```
586 pub fn get_envs(&self) -> process::CommandEnvs<'_> {
587 self.cmd.get_envs()
588 }
589
590 /// Returns the working directory for the child process.
591 ///
592 /// This returns [`None`] if the working directory will not be changed.
593 ///
594 /// # Examples
595 ///
596 /// Basic usage:
597 ///
598 /// ```rust
599 /// use std::path::Path;
600 /// use assert_cmd::Command;
601 ///
602 /// let mut cmd = Command::new("ls");
603 /// assert_eq!(cmd.get_current_dir(), None);
604 /// cmd.current_dir("/bin");
605 /// assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
606 /// ```
607 pub fn get_current_dir(&self) -> Option<&path::Path> {
608 self.cmd.get_current_dir()
609 }
610}
611
612impl From<process::Command> for Command {
613 fn from(cmd: process::Command) -> Self {
614 Command::from_std(cmd)
615 }
616}
617
618impl OutputOkExt for &mut Command {
619 fn ok(self) -> OutputResult {
620 let output = self.output().map_err(OutputError::with_cause)?;
621 if output.status.success() {
622 Ok(output)
623 } else {
624 let error = OutputError::new(output).set_cmd(format!("{:?}", self.cmd));
625 let error = if let Some(stdin) = self.stdin.as_ref() {
626 error.set_stdin(stdin.deref().clone())
627 } else {
628 error
629 };
630 Err(error)
631 }
632 }
633
634 fn unwrap_err(self) -> OutputError {
635 match self.ok() {
636 Ok(output) => {
637 if let Some(stdin) = self.stdin.as_ref() {
638 panic!(
639 "Completed successfully:\ncommand=`{:?}`\nstdin=```{}```\nstdout=```{}```",
640 self.cmd,
641 DebugBytes::new(stdin),
642 DebugBytes::new(&output.stdout)
643 )
644 } else {
645 panic!(
646 "Completed successfully:\ncommand=`{:?}`\nstdout=```{}```",
647 self.cmd,
648 DebugBytes::new(&output.stdout)
649 )
650 }
651 }
652 Err(err) => err,
653 }
654 }
655}
656
657impl OutputAssertExt for &mut Command {
658 fn assert(self) -> Assert {
659 let output = match self.output() {
660 Ok(output) => output,
661 Err(err) => {
662 panic!("Failed to spawn {self:?}: {err}");
663 }
664 };
665 let assert = Assert::new(output).append_context("command", format!("{:?}", self.cmd));
666 if let Some(stdin) = self.stdin.as_ref() {
667 assert.append_context("stdin", DebugBuffer::new(stdin.deref().clone()))
668 } else {
669 assert
670 }
671 }
672}