Command in cargo_test_support::snapbox::cmd - Rust
Description: Process spawning for testing of non-interactive commands

Skip to main content

## Command

# Struct Command

    pub struct Command {
        cmd: Command,
        stdin: Option<Data>,
        timeout: Option<Duration>,
        _stderr_to_stdout: bool,
        config: Assert,
    }

Expand description

Process spawning for testing of non-interactive commands

## Fields§

§`cmd: Command`§`stdin: Option<Data>`§`timeout: Option<Duration>`§`_stderr_to_stdout: bool`§`config: Assert`

## Implementations§

§

### impl Command

#### §Builder API

#### pub fn cargo_bin(name: &str) -> Command

Look up the path to a cargo-built binary within an integration test

Cargo support:

- `>1.94`: works
- `>=1.91,<=1.93`: works with default `build-dir`
- `<=1.92`: works

##### §Panic

Panics if no binary is found

#### pub fn new(program: impl AsRef<OsStr>) -> Command

#### pub fn from_std(cmd: Command) -> Command

Constructs a new `Command` from a `std` `Command`.

#### pub fn with_assert(self, config: Assert) -> Command

Customize the assertion behavior

#### pub fn arg(self, arg: impl AsRef<OsStr>) -> Command

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 snapbox::cmd::Command;

    Command::new("ls")
            .arg("-l")
            .arg("-a")
            .assert()
            .success();

#### pub fn args(self, args: impl IntoIterator<Item = impl AsRef<OsStr>>) -> Command

Adds multiple arguments to pass to the program.

To pass a single argument see `arg`.

##### §Examples

Basic usage:

    use snapbox::cmd::Command;

    Command::new("ls")
            .args(&["-l", "-a"])
            .assert()
            .success();

#### pub fn env(self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> Command

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 snapbox::cmd::Command;

    Command::new("ls")
            .env("PATH", "/bin")
            .assert()
            .failure();

#### pub fn envs( self, vars: impl IntoIterator<Item = (impl AsRef<OsStr>, impl AsRef<OsStr>)>, ) -> Command

Adds or updates multiple environment variable mappings.

##### §Examples

Basic usage:

    use snapbox::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)
            .assert()
            .success();

#### pub fn env_remove(self, key: impl AsRef<OsStr>) -> Command

Removes an environment variable mapping.

##### §Examples

Basic usage:

    use snapbox::cmd::Command;

    Command::new("ls")
            .env_remove("PATH")
            .assert()
            .failure();

#### pub fn env_clear(self) -> Command

Clears the entire environment map for the child process.

##### §Examples

Basic usage:

    use snapbox::cmd::Command;

    Command::new("ls")
            .env_clear()
            .assert()
            .failure();

#### pub fn current_dir(self, dir: impl AsRef<Path>) -> Command

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 snapbox::cmd::Command;

    Command::new("ls")
            .current_dir("/bin")
            .assert()
            .success();

#### pub fn stdin(self, stream: impl IntoData) -> Command

Write `buffer` to `stdin` when the `Command` is run.

##### §Examples

    use snapbox::cmd::Command;

    let mut cmd = Command::new("cat")
        .arg("-et")
        .stdin("42")
        .assert()
        .stdout_eq("42");

§

### impl Command

#### §Run Command

#### pub fn assert(self) -> OutputAssert

Run the command and assert on the results

    use snapbox::cmd::Command;

    let mut cmd = Command::new("cat")
        .arg("-et")
        .stdin("42")
        .assert()
        .stdout_eq("42");

#### pub fn output(self) -> Result<Output, Error>

## Trait Implementations§

Source§

### impl ArgLineCommandExt for Command

Source§

#### fn arg<S: AsRef<OsStr>>(self, s: S) -> Self

Source§

#### fn arg_line(self, s: &str) -> Self

Source§

### impl ChannelChangerCommandExt for Command

Source§

#### fn masquerade_as_nightly_cargo(self, _reasons: &[&str]) -> Self

The list of reasons should be why nightly cargo is needed. If it is because of an unstable feature put the name of the feature as the reason, e.g. `&["print-im-a-teapot"]`.
§

### impl Debug for Command

§

#### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

### impl From<Command> for Command

§

#### fn from(cmd: Command) -> Command

Converts to this type from the input type.
Source§

### impl TestEnvCommandExt for Command

Source§

#### fn current_dir<S: AsRef<Path>>(self, path: S) -> Self

Source§

#### fn env<S: AsRef<OsStr>>(self, key: &str, value: S) -> Self

Source§

#### fn env_remove(self, key: &str) -> Self

Source§

#### fn test_env(self) -> Self

## Auto Trait Implementations§

§

### impl !RefUnwindSafe for Command

§

### impl !UnwindSafe for Command

§

### impl Freeze for Command

§

### impl Send for Command

§

### impl Sync for Command

§

### impl Unpin for Command

§

### impl UnsafeUnpin for Command

## Blanket Implementations§

Source§

### impl<T> Any for T
where T: 'static + ?Sized,

Source§

#### fn type_id(&self) -> TypeId

Gets the `TypeId` of `self`. Read more
Source§

### impl<T> Borrow<T> for T
where T: ?Sized,

Source§

#### fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

### impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

#### fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

### impl<T> From<T> for T

Source§

#### fn from(t: T) -> T

Returns the argument unchanged.

§

### impl<T> Instrument for T

§

#### fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [`Span`], returning an `Instrumented` wrapper. Read more
§

#### fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more
Source§

### impl<T, U> Into<U> for T
where U: From<T>,

Source§

#### fn into(self) -> U

Calls `U::from(self)`.

That is, this conversion is whatever the implementation of `From<T> for U` chooses to do.

Source§

### impl<T> IntoEither for T

Source§

#### fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts `self` into a `Left` variant of `Either<Self, Self>` if `into_left` is `true`. Converts `self` into a `Right` variant of `Either<Self, Self>` otherwise. Read more
Source§

#### fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts `self` into a `Left` variant of `Either<Self, Self>` if `into_left(&self)` returns `true`. Converts `self` into a `Right` variant of `Either<Self, Self>` otherwise. Read more
§

### impl<T> Pointable for T

§

#### const ALIGN: usize

The alignment of pointer.
§

#### type Init = T

The type for initializers.
§

#### unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

#### unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

#### unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

#### unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

### impl<T> Same for T

Source§

#### type Output = T

Should always be `Self`
§

### impl<D> ToDebug for D
where D: Debug,

§

#### fn to_debug(&self) -> Data

Source§

### impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

#### type Error = Infallible

The type returned in the event of a conversion error.
Source§

#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

### impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

#### type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

### impl<T> WithSubscriber for T

§

#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided `Subscriber` to this type, returning a [`WithDispatch`] wrapper. Read more
§

#### fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default `Subscriber` to this type, returning a [`WithDispatch`] wrapper. Read more

## Layout§

Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain `repr(...)` attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.

Size: 408 bytes