test_bin/
lib.rs

1//! A module for getting the crate binary in an integration test.
2//!
3//! If you are writing a command-line interface app then it is useful to write
4//! an integration test that uses the binary. You most likely want to launch the
5//! binary and inspect the output. This module lets you get the binary so it can
6//! be tested.
7//!
8//! # Examples
9//!
10//! basic usage:
11//!
12//! ```no_run
13//! let output = test_bin::get_test_bin("my_cli_app")
14//!     .output()
15//!     .expect("Failed to start my_binary");
16//! assert_eq!(
17//!     String::from_utf8_lossy(&output.stdout),
18//!     "Output from my CLI app!\n"
19//! );
20//! ```
21//!
22//! Refer to the [`std::process::Command` documentation](https://doc.rust-lang.org/std/process/struct.Command.html)
23//! for how to pass arguments, check exit status and more.
24
25/// Returns the crate's binary as a `Command` that can be used for integration
26/// tests.
27///
28/// # Arguments
29///
30/// * `bin_name` - The name of the binary you want to test.
31///
32/// # Remarks
33///
34/// It panics on error. This is by design so the test that uses it fails.
35pub fn get_test_bin(bin_name: &str) -> std::process::Command {
36    // Create full path to binary
37    let mut path = get_test_bin_dir();
38    path.push(bin_name);
39    path.set_extension(std::env::consts::EXE_EXTENSION);
40
41    assert!(path.exists());
42
43    // Create command
44    std::process::Command::new(path.into_os_string())
45}
46
47/// Returns the directory of the crate's binary.
48///
49/// # Remarks
50///
51/// It panics on error. This is by design so the test that uses it fails.
52fn get_test_bin_dir() -> std::path::PathBuf {
53    // Cargo puts the integration test binary in target/debug/deps
54    let current_exe =
55        std::env::current_exe().expect("Failed to get the path of the integration test binary");
56    let current_dir = current_exe
57        .parent()
58        .expect("Failed to get the directory of the integration test binary");
59
60    let test_bin_dir = current_dir
61        .parent()
62        .expect("Failed to get the binary folder");
63    test_bin_dir.to_owned()
64}