pub struct Command { /* private fields */ }
Expand description
std::process::Command
customized for testing.
Implementations§
Source§impl Command
impl Command
Sourcepub fn cargo_bin<S: AsRef<str>>(name: S) -> Result<Self, CargoError>
pub fn cargo_bin<S: AsRef<str>>(name: S) -> Result<Self, CargoError>
Create a Command
to run a specific binary of the current crate.
See the cargo
module documentation for caveats and workarounds.
NOTE: Prefer cargo_bin!
as this makes assumptions about cargo
§Examples
use assert_cmd::Command;
let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME"))
.unwrap();
let output = cmd.unwrap();
println!("{:?}", output);
use assert_cmd::Command;
let mut cmd = Command::cargo_bin("bin_fixture")
.unwrap();
let output = cmd.unwrap();
println!("{:?}", output);
Sourcepub fn write_stdin<S>(&mut self, buffer: S) -> &mut Self
pub fn write_stdin<S>(&mut self, buffer: S) -> &mut Self
Write buffer
to stdin
when the Command
is run.
§Examples
use assert_cmd::Command;
let mut cmd = Command::new("cat")
.arg("-et")
.write_stdin("42")
.assert()
.stdout("42");
Sourcepub fn timeout(&mut self, timeout: Duration) -> &mut Self
pub fn timeout(&mut self, timeout: Duration) -> &mut Self
Error out if a timeout is reached
use assert_cmd::Command;
let assert = Command::cargo_bin("bin_fixture")
.unwrap()
.timeout(std::time::Duration::from_secs(1))
.env("sleep", "100")
.assert();
assert.failure();
Sourcepub fn pipe_stdin<P>(&mut self, file: P) -> Result<&mut Self>
pub fn pipe_stdin<P>(&mut self, file: P) -> Result<&mut Self>
Write path
s content to stdin
when the Command
is run.
Paths are relative to the env::current_dir
and not
Command::current_dir
.
Sourcepub fn ok(&mut self) -> OutputResult
pub fn ok(&mut self) -> OutputResult
Run a Command
, returning an OutputResult
.
§Examples
use assert_cmd::Command;
let result = Command::new("echo")
.args(&["42"])
.ok();
assert!(result.is_ok());
Sourcepub fn unwrap(&mut self) -> Output
pub fn unwrap(&mut self) -> Output
Run a Command
, unwrapping the OutputResult
.
§Examples
use assert_cmd::Command;
let output = Command::new("echo")
.args(&["42"])
.unwrap();
Sourcepub fn unwrap_err(&mut self) -> OutputError
pub fn unwrap_err(&mut self) -> OutputError
Run a Command
, unwrapping the error in the OutputResult
.
§Examples
use assert_cmd::Command;
let err = Command::new("a-command")
.args(&["--will-fail"])
.unwrap_err();
Source§impl Command
Mirror std::process::Command
’s API
impl Command
Mirror std::process::Command
’s API
Sourcepub fn new<S: AsRef<OsStr>>(program: S) -> Self
pub fn new<S: AsRef<OsStr>>(program: S) -> Self
Constructs a new Command
for launching the program at
path program
, with the following default configuration:
- No arguments to the program
- Inherit the current process’s environment
- Inherit the current process’s working directory
- Inherit stdin/stdout/stderr for
spawn
orstatus
, but create pipes foroutput
Builder methods are provided to change these defaults and otherwise configure the process.
If program
is not an absolute path, the PATH
will be searched in
an OS-defined way.
The search path to be used may be controlled by setting the
PATH
environment variable on the Command,
but this has some implementation limitations on Windows
(see issue #37519).
§Examples
Basic usage:
use assert_cmd::Command;
Command::new("sh").unwrap();
Sourcepub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self
Adds an argument to pass to the program.
Only one argument can be passed per use. So instead of:
.arg("-C /path/to/repo")
usage would be:
.arg("-C")
.arg("/path/to/repo")
To pass multiple arguments see args
.
§Examples
Basic usage:
use assert_cmd::Command;
Command::new("ls")
.arg("-l")
.arg("-a")
.unwrap();
Sourcepub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
Inserts or updates an environment variable mapping.
Note that environment variable names are case-insensitive (but case-preserving) on Windows, and case-sensitive on all other platforms.
§Examples
Basic usage:
use assert_cmd::Command;
Command::new("ls")
.env("PATH", "/bin")
.unwrap_err();
Sourcepub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
Adds or updates multiple environment variable mappings.
§Examples
Basic usage:
use assert_cmd::Command;
use std::process::Stdio;
use std::env;
use std::collections::HashMap;
let filtered_env : HashMap<String, String> =
env::vars().filter(|&(ref k, _)|
k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
).collect();
Command::new("printenv")
.env_clear()
.envs(&filtered_env)
.unwrap();
Sourcepub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Self
pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Self
Removes an environment variable mapping.
§Examples
Basic usage:
use assert_cmd::Command;
Command::new("ls")
.env_remove("PATH")
.unwrap_err();
Sourcepub fn env_clear(&mut self) -> &mut Self
pub fn env_clear(&mut self) -> &mut Self
Clears the entire environment map for the child process.
§Examples
Basic usage:
use assert_cmd::Command;
Command::new("ls")
.env_clear()
.unwrap_err();
Sourcepub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self
pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self
Sets the working directory for the child process.
§Platform-specific behavior
If the program path is relative (e.g., "./script.sh"
), it’s ambiguous
whether it should be interpreted relative to the parent’s working
directory or relative to current_dir
. The behavior in this case is
platform specific and unstable, and it’s recommended to use
canonicalize
to get an absolute program path instead.
§Examples
Basic usage:
use assert_cmd::Command;
Command::new("ls")
.current_dir("/bin")
.unwrap();
Sourcepub fn output(&mut self) -> Result<Output>
pub fn output(&mut self) -> Result<Output>
Executes the Command
as a child process, waiting for it to finish and collecting all of its
output.
By default, stdout and stderr are captured (and used to provide the resulting output). Stdin is not inherited from the parent and any attempt by the child process to read from the stdin stream will result in the stream immediately closing.
§Examples
use assert_cmd::Command;
use std::io::{self, Write};
let output = Command::new("/bin/cat")
.arg("file.txt")
.output()
.expect("failed to execute process");
println!("status: {}", output.status);
io::stdout().write_all(&output.stdout).unwrap();
io::stderr().write_all(&output.stderr).unwrap();
assert!(output.status.success());
Sourcepub fn get_program(&self) -> &OsStr
pub fn get_program(&self) -> &OsStr
Returns the path to the program that was given to Command::new
.
§Examples
Basic usage:
use assert_cmd::Command;
let cmd = Command::new("echo");
assert_eq!(cmd.get_program(), "echo");
Sourcepub fn get_args(&self) -> CommandArgs<'_>
pub fn get_args(&self) -> CommandArgs<'_>
Returns an iterator of the arguments that will be passed to the program.
This does not include the path to the program as the first argument;
it only includes the arguments specified with Command::arg
and
Command::args
.
§Examples
Basic usage:
use std::ffi::OsStr;
use assert_cmd::Command;
let mut cmd = Command::new("echo");
cmd.arg("first").arg("second");
let args: Vec<&OsStr> = cmd.get_args().collect();
assert_eq!(args, &["first", "second"]);
Sourcepub fn get_envs(&self) -> CommandEnvs<'_>
pub fn get_envs(&self) -> CommandEnvs<'_>
Returns an iterator of the environment variables explicitly set for the child process.
Environment variables explicitly set using Command::env
, Command::envs
, and
Command::env_remove
can be retrieved with this method.
Note that this output does not include environment variables inherited from the parent process.
Each element is a tuple key/value pair (&OsStr, Option<&OsStr>)
. A None
value
indicates its key was explicitly removed via Command::env_remove
. The associated key for
the None
value will no longer inherit from its parent process.
An empty iterator can indicate that no explicit mappings were added or that
Command::env_clear
was called. After calling Command::env_clear
, the child process
will not inherit any environment variables from its parent process.
§Examples
Basic usage:
use std::ffi::OsStr;
use assert_cmd::Command;
let mut cmd = Command::new("ls");
cmd.env("TERM", "dumb").env_remove("TZ");
let envs: Vec<(&OsStr, Option<&OsStr>)> = cmd.get_envs().collect();
assert_eq!(envs, &[
(OsStr::new("TERM"), Some(OsStr::new("dumb"))),
(OsStr::new("TZ"), None)
]);
Sourcepub fn get_current_dir(&self) -> Option<&Path>
pub fn get_current_dir(&self) -> Option<&Path>
Returns the working directory for the child process.
This returns None
if the working directory will not be changed.
§Examples
Basic usage:
use std::path::Path;
use assert_cmd::Command;
let mut cmd = Command::new("ls");
assert_eq!(cmd.get_current_dir(), None);
cmd.current_dir("/bin");
assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));