### Usage example Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/macro.cargo_bin_cmd.html Demonstrates how to initialize a command using the macro. ```rust use assert_cmd::prelude::*; use assert_cmd::cargo::cargo_bin_cmd; use std::process::Command; let mut cmd = cargo_bin_cmd!(); let output = cmd.unwrap(); ``` -------------------------------- ### Run Specific Binary by Name Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/trait.CommandCargoExt.html Example of running a specific binary fixture by name using CommandCargoExt. ```rust use assert_cmd::prelude::*; use std::process::Command; let mut cmd = Command::cargo_bin("bin_fixture") .unwrap(); let output = cmd.unwrap(); println!("{:?}", output); ``` -------------------------------- ### FromIterator Implementation Examples Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Shows how collecting an iterator of Results short-circuits on the first Err encountered. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### Get program path Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Returns the path to the program provided to Command::new. ```rust use assert_cmd::Command; let cmd = Command::new("echo"); assert_eq!(cmd.get_program(), "echo"); ``` -------------------------------- ### Run Current Crate Binary Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/trait.CommandCargoExt.html Example of using CommandCargoExt to run the current crate's binary using the pkg_name macro. ```rust use assert_cmd::prelude::*; use assert_cmd::pkg_name; use std::process::Command; let mut cmd = Command::cargo_bin(pkg_name!()) .unwrap(); let output = cmd.unwrap(); println!("{:?}", output); ``` -------------------------------- ### Referencing Result Values Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Examples for converting Result to references using as_ref and as_mut. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Converting Result to Option Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Examples for converting Result to Option using ok and err methods. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### Asserting stderr output Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/assert.rs.html Examples demonstrating how to validate stderr using predicates, byte slices, or strings. ```rust use assert_cmd::prelude::*; use std::process::Command; use predicates::prelude::*; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stderr(predicate::eq(b"world\n" as &[u8])); ``` ```rust use assert_cmd::prelude::*; use std::process::Command; use predicates::prelude::*; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stderr(predicate::str::diff("world\n")); ``` ```rust use assert_cmd::prelude::*; use std::process::Command; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stderr(b"world\n" as &[u8]); ``` ```rust use assert_cmd::prelude::*; use std::process::Command; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stderr("world\n"); ``` -------------------------------- ### IntoIterator Implementation Examples Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Demonstrates converting a Result into an iterator that yields the contained value if Ok, or nothing if Err. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result = Err("nothing!"); let v: Vec = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### Checking Result with Predicates Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Examples for checking Result status using predicates with is_ok_and and is_err_and. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` ```rust use std::io::{Error, ErrorKind}; let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Checking Result Status Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Examples for checking if a Result is Ok or Err. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### Unwrap Unchecked Examples Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Demonstrates the use of unwrap_unchecked, which is unsafe and causes undefined behavior if called on an Err variant. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Get command arguments Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Returns an iterator of the arguments passed to the program, excluding the program path itself. ```rust 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"]); ``` -------------------------------- ### crate_name! Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/macro.crate_name.html A deprecated macro used to get the crate name. Users should use pkg_name! instead. ```APIDOC ## crate_name! ### Description Retrieves the name of the crate. Note that this macro is deprecated since version 2.1.0 and has been replaced by `pkg_name!`. ### Syntax `crate_name!()` ``` -------------------------------- ### Unwrap Err Unchecked Examples Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Demonstrates the use of unwrap_err_unchecked, which is unsafe and causes undefined behavior if called on an Ok variant. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Configure and assert on command execution Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/index.html Demonstrates configuring arguments, environment variables, and stdin, followed by assertions on failure status, exit code, and stdout. ```rust use assert_cmd::Command; let mut cmd = Command::cargo_bin("bin_fixture").unwrap(); let assert = cmd .arg("-A") .env("stdout", "hello") .env("exit", "42") .write_stdin("42") .assert(); assert .failure() .code(42) .stdout("hello\n"); ``` -------------------------------- ### Manage environment variables with Command Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Demonstrates setting and removing environment variables for a command process. ```rust 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) ]); ``` -------------------------------- ### Command::new Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Constructs a new Command for launching the program at the specified path. ```APIDOC ## Command::new(program: S) ### Description Constructs a new Command for launching the program at the provided path. If the program is not an absolute path, the PATH environment variable will be searched. ### Parameters - **program** (S: AsRef) - Required - The path or name of the program to execute. ``` -------------------------------- ### Launch a crate binary with CommandCargoExt Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cargo.rs.html Use Command::cargo_bin to create a command for a binary in the current project. This requires the assert_cmd::prelude::* import. ```rust use assert_cmd::prelude::*; use assert_cmd::pkg_name; use std::process::Command; let mut cmd = Command::cargo_bin(pkg_name!()) .unwrap(); let output = cmd.unwrap(); ``` ```rust use assert_cmd::prelude::*; use assert_cmd::pkg_name; use std::process::Command; let mut cmd = Command::cargo_bin(pkg_name!()) .unwrap(); let output = cmd.unwrap(); println!("{:?}", output); ``` ```rust use assert_cmd::prelude::*; use assert_cmd::pkg_name; use std::process::Command; let mut cmd = Command::cargo_bin(pkg_name!()) .unwrap(); let output = cmd.unwrap(); println!("{:?}", output); ``` ```rust use assert_cmd::prelude::*; use std::process::Command; let mut cmd = Command::cargo_bin("bin_fixture") .unwrap(); let output = cmd.unwrap(); println!("{:?}", output); ``` -------------------------------- ### Run a crate binary with CommandCargoExt Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/index.html Demonstrates using CommandCargoExt to launch a binary from the current crate in an integration test. ```rust use assert_cmd::prelude::*; use assert_cmd::pkg_name; use std::process::Command; let mut cmd = Command::cargo_bin(pkg_name!()) .unwrap(); let output = cmd.unwrap(); ``` -------------------------------- ### Configure working directory with Command Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Shows how to check and set the current working directory for a command. ```rust 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"))); ``` -------------------------------- ### Using IntoOutputPredicate for command output assertions Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/trait.IntoOutputPredicate.html Demonstrates how to use predicates to verify command output, including the shorthand syntax enabled by IntoOutputPredicate. ```rust use assert_cmd::prelude::*; use std::process::Command; use predicates::prelude::*; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stdout(predicate::str::diff("hello\n").from_utf8()); // which can be shortened to: Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stdout("hello\n"); ``` -------------------------------- ### Convert Command Output to OutputResult Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/output/trait.OutputOkExt.html Demonstrates using the ok method to convert a command's output into an OutputResult. ```rust use assert_cmd::prelude::*; use std::process::Command; let result = Command::new("echo") .args(&["42"]) .ok(); assert!(result.is_ok()); ``` -------------------------------- ### Command::ok Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Executes the command and returns an OutputResult. ```APIDOC ## Command::ok() ### Description Runs the command and returns an OutputResult, which can be used to verify the command's exit status and output. ``` -------------------------------- ### Run a basic command assertion Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/index.html Initialize a command using the crate's binary and assert that it completes successfully. ```rust use assert_cmd::Command; let mut cmd = Command::cargo_bin("bin_fixture").unwrap(); cmd.assert().success(); ``` -------------------------------- ### get_program Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Returns the path to the program. ```APIDOC ## pub fn get_program(&self) -> &OsStr ### Description Returns the path to the program that was given to Command::new. ``` -------------------------------- ### Run Command and Handle Output Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Methods for executing a command and retrieving the result or output. ```rust use assert_cmd::Command; let result = Command::new("echo") .args(&["42"]) .ok(); assert!(result.is_ok()); ``` ```rust use assert_cmd::Command; let output = Command::new("echo") .args(&["42"]) .unwrap(); ``` ```rust use assert_cmd::Command; let err = Command::new("a-command") .args(&["--will-fail"]) ``` -------------------------------- ### Run Command and Return Result Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Executes the command and returns an OutputResult. ```rust use assert_cmd::Command; let result = Command::new("echo") .args(&["42"]) .ok(); assert!(result.is_ok()); ``` -------------------------------- ### Convert Output Predicates Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/assert.rs.html Demonstrates creating output predicates from different data types using convert_output. ```rust let pred = convert_output(predicate::eq(b"Hello" as &[u8])); assert!(pred.eval(b"Hello" as &[u8])); ``` ```rust #[test] fn into_output_from_bytes() { let pred = convert_output(b"Hello" as &[u8]); assert!(pred.eval(b"Hello" as &[u8])); } ``` ```rust #[test] fn into_output_from_vec() { let pred = convert_output(vec![b'H', b'e', b'l', b'l', b'o']); assert!(pred.eval(b"Hello" as &[u8])); } ``` ```rust #[test] fn into_output_from_str() { let pred = convert_output("Hello"); assert!(pred.eval(b"Hello" as &[u8])); } ``` -------------------------------- ### Create New Command Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Constructs a new Command instance for a given program path. ```rust use assert_cmd::Command; Command::new("sh").unwrap(); ``` -------------------------------- ### Asserting Command Success Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/trait.OutputAssertExt.html Demonstrates how to use the assert method to verify that a command executed successfully. ```rust use assert_cmd::prelude::*; use std::process::Command; let mut cmd = Command::cargo_bin("bin_fixture") .unwrap(); cmd.assert() .success(); ``` -------------------------------- ### Command::cargo_bin Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/index.html Initializes a Command by locating a binary within the current Cargo project. ```APIDOC ## Command::cargo_bin(name: &str) ### Description Creates a new Command instance configured to run a binary from the current Cargo project. ### Parameters - **name** (str) - Required - The name of the binary to execute. ``` -------------------------------- ### Assert Command Output Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Executes the command and prepares to make assertions on the output. ```rust use assert_cmd::Command; let mut cmd = Command::cargo_bin("bin_fixture") .unwrap() .assert() .success(); ``` -------------------------------- ### output Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Executes the command and collects output. ```APIDOC ## pub fn output(&mut self) -> Result ### Description Executes the Command as a child process, waiting for it to finish and collecting all of its output. ``` -------------------------------- ### Asserting Command Output Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/assert.rs.html Demonstrates how to verify the contents of stdout using byte or string predicates. ```rust use assert_cmd::prelude::*; use std::process::Command; use predicates::prelude::*; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stdout(predicate::eq(b"hello\n" as &[u8])); ``` ```rust use assert_cmd::prelude::*; use std::process::Command; use predicates::prelude::*; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") ``` -------------------------------- ### Command::args Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Adds multiple arguments to the command. ```APIDOC ## Command::args(args: I) ### Description Adds multiple arguments to pass to the program. ### Parameters - **args** (I: IntoIterator) - Required - An iterator of arguments to add. ``` -------------------------------- ### cargo_bin_cmd! Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/macro.cargo_bin_cmd.html Creates a Command for the binary target's executable. This macro is intended for use within integration tests or benchmarks. ```APIDOC ## cargo_bin_cmd! ### Description Creates a `Command` for the binary target's executable. The `bin_target_name` parameter is optional and represents the name of the binary target exactly as-is. ### Signature `cargo_bin_cmd!()` `cargo_bin_cmd!(bin_target_name: expr)` ### Usage Example ```rust use assert_cmd::prelude::*; use assert_cmd::cargo::cargo_bin_cmd; use std::process::Command; let mut cmd = cargo_bin_cmd!(); let output = cmd.unwrap(); ``` ``` -------------------------------- ### Command::unwrap Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Executes the command and unwraps the result into a standard process::Output. ```APIDOC ## Command::unwrap() ### Description Runs the command and unwraps the OutputResult. Panics if the command fails or encounters an error. ### Returns - **process::Output** - The captured output of the command. ``` -------------------------------- ### Create Command for Cargo Binary Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Constructs a Command to run a binary from the current crate. Panics if the binary is not found. ```rust use assert_cmd::Command; use assert_cmd::pkg_name; let mut cmd = Command::cargo_bin(pkg_name!()) .unwrap(); let output = cmd.unwrap(); println!("{:?}", output); ``` ```rust use assert_cmd::Command; let mut cmd = Command::cargo_bin("bin_fixture") .unwrap(); let output = cmd.unwrap(); println!("{:?}", output); ``` -------------------------------- ### envs Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Sets multiple environment variables for the child process. ```APIDOC ## fn envs(&mut self, vars: I) ### Description Sets multiple environment variables for the child process. The input is an iterator of key-value pairs. ### Parameters - **vars** (IntoIterator) - Required - An iterator of environment variable keys and values. ``` -------------------------------- ### Unwrap Command Output Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Executes the command and unwraps the resulting Output. ```rust use assert_cmd::Command; let output = Command::new("echo") .args(&["42"]) .unwrap(); ``` -------------------------------- ### Locate and Execute Cargo Binaries Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cargo.rs.html Resolves a binary path and wraps it in a process::Command, optionally applying a runner if configured via environment variables. ```rust pub(crate) fn cargo_bin_cmd>(name: S) -> Result { let path = cargo_bin(name); if path.is_file() { if let Some(runner) = cargo_runner() { let mut cmd = process::Command::new(&runner[0]); cmd.args(&runner[1..]).arg(path); Ok(cmd) } else { Ok(process::Command::new(path)) } } else { Err(CargoError::with_cause(NotFoundError { path })) } } ``` -------------------------------- ### Asserting process exit codes with IntoCodePredicate Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/trait.IntoCodePredicate.html Demonstrates using Assert::code to verify exit codes, showing both explicit predicate usage and the shorthand integer conversion. ```rust use assert_cmd::prelude::*; use std::process::Command; use predicates::prelude::*; Command::cargo_bin("bin_fixture") .unwrap() .env("exit", "42") .assert() .code(predicate::eq(42)); // which can be shortened to: Command::cargo_bin("bin_fixture") .unwrap() .env("exit", "42") .assert() .code(42); ``` -------------------------------- ### Run a binary using escargot Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/index.html Provides a more flexible alternative to CommandCargoExt for complex build scenarios, such as specifying custom binary targets or build modes. ```rust use assert_cmd::prelude::*; use std::process::Command; let bin_under_test = escargot::CargoBuild::new() .bin("bin_fixture") .current_release() .current_target() .run() .unwrap(); let mut cmd = bin_under_test.command(); let output = cmd.unwrap(); println!("{:?}", output); ``` -------------------------------- ### Create an OutputError Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/output/struct.OutputError.html Demonstrates how to trigger an error by executing a command that fails. ```rust use assert_cmd::prelude::*; use std::process::Command; let err = Command::new("a-command") .args(&["--will-fail"]) .unwrap_err(); ``` -------------------------------- ### assert Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Wraps the command with an interface that provides assertions on the Output. ```APIDOC ## fn assert(self) -> Assert ### Description Wrap with an interface for that provides assertions on the Output. ### Signature `fn assert(self) -> Assert` ``` -------------------------------- ### Retrieve package name with pkg_name Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/macro.pkg_name.html Use the macro to dynamically specify the binary name when creating a Command instance for testing. ```rust use assert_cmd::Command; let mut cmd = Command::cargo_bin(assert_cmd::pkg_name!()).unwrap(); let assert = cmd .arg("-A") .env("stdout", "hello") .env("exit", "42") .write_stdin("42") .assert(); assert .failure() .code(42) .stdout("hello\n"); ``` -------------------------------- ### Configuring Environment Variables Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Set or update environment variables for the command execution. ```rust use assert_cmd::Command; Command::new("ls") .env("PATH", "/bin") .unwrap_err(); ``` ```rust use assert_cmd::Command; use std::process::Stdio; use std::env; use std::collections::HashMap; let filtered_env : HashMap = env::vars().filter(|&(ref k, _)| k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH" ).collect(); Command::new("printenv") ``` -------------------------------- ### get_args Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Returns an iterator of the arguments that will be passed to the program, excluding the program path itself. ```APIDOC ## get_args ### Description 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. ### Signature pub fn get_args(&self) -> process::CommandArgs<'_> ``` -------------------------------- ### Set current directory Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Sets the working directory for the child process. ```rust use assert_cmd::Command; Command::new("ls") .current_dir("/bin") .unwrap(); ``` -------------------------------- ### get_args Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Returns an iterator of the arguments. ```APIDOC ## pub fn get_args(&self) -> CommandArgs<'_> ### Description Returns an iterator of the arguments that will be passed to the program. ``` -------------------------------- ### Command::assert Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/index.html Executes the command and returns an Assert object for validating the process output and exit status. ```APIDOC ## Command::assert() ### Description Runs the configured command and returns an Assert object to perform validations on the resulting process state. ### Returns - **Assert** - An object providing methods like success(), failure(), code(), stdout(), and stderr() for validation. ``` -------------------------------- ### Execute command and capture output Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Executes the command as a child process and collects stdout and stderr. ```rust 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()); ``` -------------------------------- ### envs Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Adds or updates multiple environment variable mappings. ```APIDOC ## pub fn envs(&mut self, vars: I) -> &mut Self ### Description Adds or updates multiple environment variable mappings from an iterator. ``` -------------------------------- ### fn unwrap(self) -> Output Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/output/trait.OutputOkExt.html Unwraps an Output, providing a more descriptive error message than the standard .ok().unwrap() approach. ```APIDOC ## fn unwrap(self) -> Output ### Description Unwrap a Output but with a prettier message than .ok().unwrap(). ### Signature `fn unwrap(self) -> Output` ### Example ```rust use assert_cmd::prelude::*; use std::process::Command; let output = Command::new("echo").args(&["42"]).unwrap(); ``` ``` -------------------------------- ### cargo_bin Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/trait.CommandCargoExt.html Creates a Command to run a specific binary of the current crate. This method may utilize a runner configured via the CARGO_TARGET__RUNNER environment variable. ```APIDOC ## fn cargo_bin>(name: S) -> Result ### Description Creates a `Command` to run a specific binary of the current crate. This is useful for running binaries that cannot be launched directly, such as cross-compiled binaries. ### Parameters - **name** (S: AsRef) - Required - The name of the binary to execute. ### Returns - **Result** - Returns the configured Command or a CargoError if the binary is not found. ### Panics - Panics if no binary is found. ### Example ```rust use assert_cmd::prelude::*; use std::process::Command; let mut cmd = Command::cargo_bin("bin_fixture").unwrap(); ``` ``` -------------------------------- ### Asserting command output with StrOutputPredicate Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/struct.StrOutputPredicate.html Demonstrates using a string predicate to verify the stderr output of a command. ```rust use assert_cmd::prelude::*; use std::process::Command; use predicates::prelude::*; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stderr(predicate::str::diff("world\n")); ``` -------------------------------- ### Add Command Arguments Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Methods for adding single or multiple arguments to the command. ```rust .arg("-C /path/to/repo") ``` ```rust .arg("-C") .arg("/path/to/repo") ``` ```rust use assert_cmd::Command; Command::new("ls") .arg("-l") .arg("-a") .unwrap(); ``` ```rust use assert_cmd::Command; Command::new("ls") .args(&["-l", "-a"]) .unwrap(); ``` -------------------------------- ### Calculate Product of Result Iterator Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Demonstrates using the product method on an iterator of Results, which short-circuits on the first Err encountered. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### Asserting command output with StrContentOutputPredicate Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/struct.StrContentOutputPredicate.html Demonstrates using string-based assertions on command output, which internally utilizes StrContentOutputPredicate. ```rust use assert_cmd::prelude::*; use std::process::Command; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stderr("world\n"); ``` -------------------------------- ### fn ok(self) -> OutputResult Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/output/trait.OutputOkExt.html Converts a type to an OutputResult. This is typically implemented on std::process::Output. ```APIDOC ## fn ok(self) -> OutputResult ### Description Converts an Output to an OutputResult. ### Signature `fn ok(self) -> OutputResult` ### Example ```rust use assert_cmd::prelude::*; use std::process::Command; let result = Command::new("echo").args(&["42"]).ok(); assert!(result.is_ok()); ``` ``` -------------------------------- ### Command::arg Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Adds a single argument to the command. ```APIDOC ## Command::arg(arg: S) ### Description Adds a single argument to pass to the program. Only one argument can be passed per call. ### Parameters - **arg** (S: AsRef) - Required - The argument to add. ``` -------------------------------- ### fn assert(self) -> Assert Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/trait.OutputAssertExt.html Wraps the current object with an interface that provides assertions on the command output. ```APIDOC ## fn assert(self) -> Assert ### Description Wraps the command output or command object with an interface that provides assertions on the `Output` state. ### Signature `fn assert(self) -> Assert` ### Usage Example ```rust use assert_cmd::prelude::*; use std::process::Command; let mut cmd = Command::cargo_bin("bin_fixture").unwrap(); cmd.assert().success(); ``` ``` -------------------------------- ### current_dir Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Sets the working directory for the child process. ```APIDOC ## pub fn current_dir>(&mut self, dir: P) -> &mut Self ### Description Sets the working directory for the child process. ``` -------------------------------- ### Fallback with or Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Returns the provided result if the current result is Err, otherwise returns the Ok value. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### env Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Inserts or updates an environment variable mapping for the child process. ```APIDOC ## pub fn env(&mut self, key: K, val: V) -> &mut Self ### Description 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. ``` -------------------------------- ### CommandCargoExt::cargo_bin Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/index.html An extension method for std::process::Command to create a command for a binary target within the current Cargo project. ```APIDOC ## CommandCargoExt::cargo_bin(name: &str) ### Description Creates a std::process::Command configured to run a binary target from the current Cargo project. ### Signature fn cargo_bin(name: &str) -> Result ### Parameters - **name** (&str) - Required - The name of the binary target to execute. ### Usage Example ```rust use assert_cmd::prelude::*; use std::process::Command; let mut cmd = Command::cargo_bin("my_bin_name").unwrap(); ``` ``` -------------------------------- ### Asserting command output with bytes Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/struct.BytesContentOutputPredicate.html Demonstrates using a byte slice to assert against the stderr output of a command. ```rust use assert_cmd::prelude::*; use std::process::Command; Command::cargo_bin("bin_fixture") .unwrap() .env("stdout", "hello") .env("stderr", "world") .assert() .stderr(b"world\n" as &[u8]); ``` -------------------------------- ### Macro definition Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/macro.cargo_bin_cmd.html The signature of the cargo_bin_cmd macro. ```rust macro_rules! cargo_bin_cmd { () => { ... }; ($bin_target_name:expr) => { ... }; } ``` -------------------------------- ### get_envs Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cmd/struct.Command.html Returns an iterator of the environment variables. ```APIDOC ## pub fn get_envs(&self) -> CommandEnvs<'_> ### Description Returns an iterator of the environment variables explicitly set for the child process. ``` -------------------------------- ### Handle AssertError with try_success Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/struct.AssertError.html Demonstrates using try_success to handle potential assertion errors and perform conditional checks on command output. ```rust use assert_cmd::prelude::*; use std::process::Command; use predicates::prelude::*; let result = Command::new("echo") .assert(); match result.try_success() { Ok(assert) => { assert.stdout(predicate::eq(b"Success\n" as &[u8])); } Err(err) => { err.assert().stdout(predicate::eq(b"Err but some specific output you might want to check\n" as &[u8])); } } ``` -------------------------------- ### Expect a Result value Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Use expect() to retrieve the Ok value or panic with a custom message. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Define Palette and Styled structures Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/color.rs.html Internal structures for managing terminal color palettes and applying styles to displayable content. ```rust #[derive(Copy, Clone, Debug, Default)] pub(crate) struct Palette { key: anstyle::Style, value: anstyle::Style, } impl Palette { pub(crate) fn color() -> Self { if cfg!(feature = "color") { Self { key: anstyle::AnsiColor::Blue.on_default() | anstyle::Effects::BOLD, value: anstyle::AnsiColor::Yellow.on_default() | anstyle::Effects::BOLD, } } else { Self::plain() } } pub(crate) fn plain() -> Self { Self::default() } pub(crate) fn key(self, display: D) -> Styled { Styled::new(display, self.key) } pub(crate) fn value(self, display: D) -> Styled { Styled::new(display, self.value) } } #[derive(Debug)] pub(crate) struct Styled { display: D, style: anstyle::Style, } impl Styled { pub(crate) fn new(display: D, style: anstyle::Style) -> Self { Self { display, style } } } impl std::fmt::Display for Styled { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if f.alternate() { write!(f, "{}", self.style.render())?; self.display.fmt(f)?; write!(f, "{}", self.style.render_reset())?; Ok(()) } else { self.display.fmt(f) } } } ``` -------------------------------- ### Legacy Binary Lookup Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cargo.rs.html Fallback mechanism to locate binaries in the target directory if environment variables are missing. ```rust fn legacy_cargo_bin(name: &str) -> Option { let target_dir = target_dir()?; let bin_path = target_dir.join(format!("{}{}", name, env::consts::EXE_SUFFIX)); if !bin_path.exists() { return None; } Some(bin_path) } fn target_dir() -> Option { let mut path = env::current_exe().ok()?; let _test_bin_name = path.pop(); if path.ends_with("deps") { let _deps = path.pop(); } Some(path) } ``` -------------------------------- ### pkg_name!() Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/macros.rs.html Retrieves the package name from the project's Cargo.toml at compile time. ```APIDOC ## pkg_name!() ### Description Returns the package name defined in the Cargo.toml file. This is useful for dynamically referencing the current crate's binary name. ### Usage ```rust let name = assert_cmd::pkg_name!(); ``` ``` -------------------------------- ### Command::write_stdin Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Configures the command to write the provided buffer to stdin upon execution. ```APIDOC ## Command::write_stdin(buffer: S) ### Description Writes the provided buffer to stdin when the Command is run. ### Parameters - **buffer** (S: Into>) - Required - The data to write to stdin. ``` -------------------------------- ### OutputError::set_cmd Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/output/struct.OutputError.html Adds the command line string to the error for additional context. ```APIDOC ### pub fn set_cmd(self, cmd: String) -> Self Attaches the command line string to the error instance. ``` -------------------------------- ### Using AssertResult with try_success Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/type.AssertResult.html Demonstrates capturing an assertion result using the try_success method. ```rust use assert_cmd::prelude::*; use std::process::Command; let result = Command::new("echo") .assert() .try_success(); assert!(result.is_ok()); ``` -------------------------------- ### OutputAssertExt::assert Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/assert.rs.html Wraps a Command or Output into an Assert interface to perform assertions. ```APIDOC ## fn assert(self) -> Assert ### Description Wraps the current object (Command or Output) with an interface that provides assertions on the process output. ### Usage ```rust use assert_cmd::prelude::*; use std::process::Command; let mut cmd = Command::cargo_bin("bin_fixture").unwrap(); cmd.assert().success(); ``` ``` -------------------------------- ### Asserting Command Failure Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/assert.rs.html Verify that a command failed to execute. ```rust use assert_cmd::prelude::*; use std::process::Command; Command::cargo_bin("bin_fixture") .unwrap() ``` -------------------------------- ### Unwrap Command Output Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/output/trait.OutputOkExt.html Uses the unwrap method to retrieve the process output with a more descriptive error message. ```rust use assert_cmd::prelude::*; use std::process::Command; let output = Command::new("echo") .args(&["42"]) .unwrap(); ``` -------------------------------- ### Access Output from OutputError Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/output/struct.OutputError.html Shows how to retrieve the underlying process output from an error instance. ```rust use assert_cmd::prelude::*; use std::process::Command; let err = Command::new("a-command") .args(&["--will-fail"]) .unwrap_err(); let output = err .as_output() .unwrap(); assert_eq!(Some(42), output.status.code()); ``` -------------------------------- ### Testing IntoOutputPredicate conversion Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/assert.rs.html Unit test verifying the conversion of a predicate into an output predicate. ```rust fn convert_output(pred: I) -> P where I: IntoOutputPredicate

, P: Predicate<[u8]>, { pred.into_output() } #[test] fn into_output_from_pred() { ``` -------------------------------- ### Handle Missing Cargo Binaries Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cargo.rs.html Generates a panic message listing available binaries when a requested binary is not found. ```rust #[track_caller] fn missing_cargo_bin(name: &str) -> ! { let possible_names: Vec<_> = env::vars_os() .filter_map(|(k, _)| k.into_string().ok()) .filter_map(|k| k.strip_prefix(CARGO_BIN_EXE_).map(|s| s.to_owned())) .collect(); if possible_names.is_empty() { panic!("`CARGO_BIN_EXE_{name}` is unset help: if this is running within a unit test, move it to an integration test to gain access to `CARGO_BIN_EXE_{name}`") } else { let mut names = String::new(); for (i, name) in possible_names.iter().enumerate() { use std::fmt::Write as _; if i != 0 { let _ = write!(&mut names, ", "); } let _ = write!(&mut names, "\"{name}\""); } panic!( "`CARGO_BIN_EXE_{name}` is unset help: available binary names are {names}" ) } } ``` -------------------------------- ### Assert::stdout Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/assert.rs.html Verifies that the command's standard output matches the provided predicate or value. ```APIDOC ## pub fn stdout(self, pred: I) -> Self ### Description Ensures the command wrote the expected data to stdout. This method accepts various types that implement IntoOutputPredicate, such as byte slices or strings. ### Parameters - **pred** (I: IntoOutputPredicate

) - Required - The predicate or value to compare against the command's stdout. ``` -------------------------------- ### Command::env Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Sets or updates an environment variable for the command. ```APIDOC ## Command::env(key: K, val: V) ### Description Inserts or updates an environment variable mapping for the command process. ### Parameters - **key** (K: AsRef) - Required - The environment variable name. - **val** (V: AsRef) - Required - The value to set for the environment variable. ``` -------------------------------- ### Verify Command Success Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/struct.Assert.html Ensures the command completed with a success exit status. ```rust use assert_cmd::prelude::*; use std::process::Command; Command::cargo_bin("bin_fixture") .unwrap() .assert() .success(); ``` -------------------------------- ### Command::pipe_stdin Source: https://docs.rs/assert_cmd/2.2.2/src/assert_cmd/cmd.rs.html Reads content from a file and pipes it to the command's stdin. ```APIDOC ## Command::pipe_stdin(file: P) ### Description Reads the content of the specified file and writes it to stdin when the Command is run. Paths are relative to the current working directory. ### Parameters - **file** (P: AsRef) - Required - The path to the file to read. ``` -------------------------------- ### cargo_bin! Macro Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/cargo/index.html A macro to retrieve the absolute path to a binary target's executable. ```APIDOC ## cargo_bin!(name) ### Description Returns the absolute path to the specified binary target's executable as a PathBuf. ### Parameters - **name** (identifier) - Required - The name of the binary target. ### Usage Example ```rust let path = assert_cmd::cargo::cargo_bin!("my_bin_name"); ``` ``` -------------------------------- ### pkg_name!() Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/macro.pkg_name.html A macro that returns the package name from the project's Cargo.toml file. It is commonly used to identify the binary to be tested via Command::cargo_bin(). ```APIDOC ## pkg_name! ### Description Retrieves the package name from the project's `Cargo.toml` at compile time. ### Usage ```rust use assert_cmd::Command; let mut cmd = Command::cargo_bin(assert_cmd::pkg_name!()).unwrap(); ``` ``` -------------------------------- ### Verify Command Failure Source: https://docs.rs/assert_cmd/2.2.2/assert_cmd/assert/struct.Assert.html Ensures the command completed with a non-zero exit status. ```rust use assert_cmd::prelude::*; use std::process::Command; Command::cargo_bin("bin_fixture") .unwrap() .env("exit", "1") .assert() .failure(); ```