test_bin 0.6.0

A crate for getting the crate binary in an integration test.
Documentation
//! A module for getting the crate binary in an integration test.
//!
//! If you are writing a command-line interface app then it is useful to write
//! an integration test that uses the binary. You most likely want to launch the
//! binary and inspect the output. This module lets you get the binary so it can
//! be tested.
//!
//! # Examples
//!
//! basic usage:
//!
//! ```ignore
//! let output = test_bin::get_test_bin("my_cli_app")
//!     .output()
//!     .expect("Failed to start my_cli_app");
//! assert_eq!(
//!     String::from_utf8_lossy(&output.stdout),
//!     "Output from my CLI app!\n"
//! );
//! ```
//!
//! Refer to the [`std::process::Command` documentation](https://doc.rust-lang.org/std/process/struct.Command.html)
//! for how to pass arguments, check exit status and more.
//!
//! NOTE: The `get_test_bin` function was deprecated in version 0.5.0 in favor
//! of the `get_test_bin!` macro and then undeprecated in version 0.6.0. The
//! macro was added because there was talk of changing cargo so the function
//! wouldn't work. Fortunately, cargo was changed so that the macro wasn't
//! needed. The `get_test_bin` function is the recommended way of using
//! this crate. See [Cargo issue 14125](https://github.com/rust-lang/cargo/issues/14125).
//!
//! The `get_test_bin!` macro uses the `CARGO_BIN_EXE_<name>` environment
//! variable which was introduced in [Rust 1.43 released on 23 April 2020](https://releases.rs/docs/1.43.0/).
//!

/// Returns the crate's binary as a `Command` that can be used for integration
/// tests.
///
/// # Arguments
///
/// * `bin_name` - The name of the binary you want to test.
///
/// # Remarks
///
/// It panics on error. This is by design so the test that uses it fails.
pub fn get_test_bin(bin_name: &str) -> std::process::Command {
    let mut path = std::path::PathBuf::new();
    // Try using the new CARGO_BIN_EXE_ environment variable.
    let bin_path_key = format!("CARGO_BIN_EXE_{}", bin_name);
    if let Ok(bin_path) = std::env::var(bin_path_key) {
        path.push(bin_path);
    } else {
        // Use the legacy fallback method of finding the path.
        // Create full path to binary.
        path = get_test_bin_dir_fallback();
        path.push(bin_name);
        path.set_extension(std::env::consts::EXE_EXTENSION);

        if !path.exists() {
            // Print all environment variables.
            for (key, value) in std::env::vars() {
                println!("{key}: {value}");
            }
            let path: &'static str = env!("PATH");
            println!("the $PATH variable at the time of compiling was: {path}");
        }
    }

    assert!(path.exists());

    // Create command
    std::process::Command::new(path.into_os_string())
}

/// Returns the directory of the crate's binary.
///
/// # Remarks
///
/// It panics on error. This is by design so the test that uses it fails.
fn get_test_bin_dir_fallback() -> std::path::PathBuf {
    // Cargo puts the integration test binary in target/debug/deps
    let current_exe =
        std::env::current_exe().expect("Failed to get the path of the integration test binary");
    let current_dir = current_exe
        .parent()
        .expect("Failed to get the directory of the integration test binary");

    let test_bin_dir = current_dir
        .parent()
        .expect("Failed to get the binary folder");
    test_bin_dir.to_owned()
}

/// Returns the crate's binary as a `Command` that can be used for integration
/// tests.
///
/// # Arguments
///
/// * `bin_name` - The name of the binary you want to test. It must be a string literal.
///
/// # Remarks
///
/// It will fail to compile if the `bin_name` is incorrect. The `bin_name` is
/// used for creating an environment variable.
///
/// If you want to not use a string literal every time then you can define a
/// macro that returns a string literal:
/// ```rust
/// macro_rules! my_cli_app {
///    () => ( "my_cli_app" )
/// }
/// ```
/// And then use `my_cli_app!()` as the argument.
#[macro_export]
macro_rules! get_test_bin {
    ($x:expr) => {
        {
            // Get path string. See the CARGO_BIN_EXE_<name> documentation:
            // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates
            let path_str = env!(concat!("CARGO_BIN_EXE_", $x));
            // Create command
            std::process::Command::new(path_str)
        }
    };
}