Skip to main content

tpt_cli_snap/
lib.rs

1//! CLI process testing with integrated snapshot assertions.
2//!
3//! `tpt-cli-snap` bridges [`assert_cmd`] (which runs a binary and lets you
4//! inspect its output) and [`tpt_snapshot_lite`] (which compares output against
5//! `.snap` files). The result is readable, self-documenting binary-output tests:
6//!
7//! ```no_run
8//! use tpt_cli_snap::CliTest;
9//!
10//! let outcome = CliTest::cargo_bin("my-binary")
11//!     .unwrap()
12//!     .arg("--format=json")
13//!     .arg("status")
14//!     .assert_snapshot("status_json");
15//! outcome.assert_success();
16//! ```
17//!
18//! Snapshots are stored under `<crate_root>/tests/snapshots/` by default; use the
19//! [`cli_snap_dir!`](crate::cli_snap_dir) macro to point at the *calling* crate's
20//! manifest directory, or pass an explicit directory with
21//! [`CliTest::with_snap_dir`].
22//!
23//! Set `UPDATE_SNAPSHOTS=1` to (re)create snapshot files — the flag is passed
24//! straight through to `tpt-snapshot-lite`.
25
26use std::ffi::OsStr;
27use std::path::PathBuf;
28use std::process::Output;
29
30use assert_cmd::cargo::CargoError;
31use assert_cmd::Command;
32use tpt_snapshot_lite::Snapshot;
33
34/// Default snapshot directory for the *calling* crate, evaluated at the call
35/// site's compile time: `<CARGO_MANIFEST_DIR>/tests/snapshots`.
36///
37/// This is the same directory `tpt-snapshot-lite` uses by default, so the two
38/// crates share a snapshot layout.
39///
40/// # Examples
41///
42/// ```ignore
43/// use tpt_cli_snap::{CliTest, cli_snap_dir};
44///
45/// let outcome = CliTest::cargo_bin("wm")
46///     .assert_snapshot_with_dir("ls", cli_snap_dir!());
47/// ```
48#[macro_export]
49macro_rules! cli_snap_dir {
50    () => {
51        concat!(env!("CARGO_MANIFEST_DIR"), "/tests/snapshots")
52    };
53}
54
55/// The result of running a CLI command, with snapshot assertions already applied.
56///
57/// Returned by the `assert_snapshot*` family; use the chaining methods to also
58/// assert exit code and signal behaviour.
59pub struct CliOutcome {
60    output: Output,
61    cmd_name: String,
62}
63
64impl CliOutcome {
65    /// Assert the process exited successfully (status `0`).
66    ///
67    /// # Panics
68    ///
69    /// Panics if the exit status is non-zero, including a dump of captured
70    /// stdout/stderr.
71    #[track_caller]
72    pub fn assert_success(&self) -> &Self {
73        assert!(
74            self.output.status.success(),
75            "command `{}` did not exit successfully.\nstdout: {}\nstderr: {}",
76            self.cmd_name,
77            String::from_utf8_lossy(&self.output.stdout),
78            String::from_utf8_lossy(&self.output.stderr),
79        );
80        self
81    }
82
83    /// Assert the process exited with the given code.
84    #[track_caller]
85    pub fn assert_code(&self, code: i32) -> &Self {
86        let actual = self.output.status.code().unwrap_or(-1);
87        assert!(
88            actual == code,
89            "command `{}` exited with {actual}, expected {code}",
90            self.cmd_name,
91        );
92        self
93    }
94
95    /// Assert the process failed (non-zero exit).
96    #[track_caller]
97    pub fn assert_failure(&self) -> &Self {
98        assert!(
99            !self.output.status.success(),
100            "command `{}` unexpectedly succeeded",
101            self.cmd_name,
102        );
103        self
104    }
105
106    /// The raw captured process output.
107    pub fn output(&self) -> &Output {
108        &self.output
109    }
110
111    /// The captured stdout bytes.
112    pub fn stdout(&self) -> &[u8] {
113        &self.output.stdout
114    }
115
116    /// The captured stderr bytes.
117    pub fn stderr(&self) -> &[u8] {
118        &self.output.stderr
119    }
120
121    /// The exit status code (or `-1` if terminated by a signal).
122    pub fn code(&self) -> i32 {
123        self.output.status.code().unwrap_or(-1)
124    }
125}
126
127/// Builder for a CLI test: a binary plus the args/env/stdin to run it with.
128pub struct CliTest {
129    command: Command,
130    name: String,
131    snap_dir: PathBuf,
132}
133
134impl CliTest {
135    /// Run the binary produced by `cargo test` for the named crate (the common
136    /// case — test your own binary or a workspace fixture binary).
137    pub fn cargo_bin(name: &str) -> Result<Self, CargoError> {
138        let command = Command::cargo_bin(name)?;
139        Ok(Self {
140            command,
141            name: name.to_string(),
142            snap_dir: PathBuf::from(cli_snap_dir!()),
143        })
144    }
145
146    /// Wrap an arbitrary [`Command`] (e.g. a system binary or a pre-built path).
147    pub fn command(command: Command) -> Self {
148        let name = command.get_program().to_string_lossy().into_owned();
149        Self {
150            command,
151            name,
152            snap_dir: PathBuf::from(cli_snap_dir!()),
153        }
154    }
155
156    /// Override the snapshot directory used by the `assert_snapshot*` methods.
157    pub fn with_snap_dir(mut self, dir: impl Into<PathBuf>) -> Self {
158        self.snap_dir = dir.into();
159        self
160    }
161
162    /// Append a single argument.
163    pub fn arg(mut self, arg: impl AsRef<OsStr>) -> Self {
164        self.command.arg(arg);
165        self
166    }
167
168    /// Append multiple arguments.
169    pub fn args<I, S>(mut self, args: I) -> Self
170    where
171        I: IntoIterator<Item = S>,
172        S: AsRef<OsStr>,
173    {
174        self.command.args(args);
175        self
176    }
177
178    /// Set an environment variable for the child process.
179    pub fn env(mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> Self {
180        self.command.env(key, value);
181        self
182    }
183
184    /// Remove an environment variable from the child process.
185    pub fn env_remove(mut self, key: impl AsRef<OsStr>) -> Self {
186        self.command.env_remove(key);
187        self
188    }
189
190    /// Feed `input` to the child process's stdin.
191    pub fn stdin(mut self, input: impl AsRef<[u8]>) -> Self {
192        self.command.write_stdin(input.as_ref().to_vec());
193        self
194    }
195
196    /// Run the process and snapshot its **stdout** against `<name>.snap`.
197    ///
198    /// The snapshot flag (`UPDATE_SNAPSHOTS`) is passed straight through from the
199    /// environment to `tpt-snapshot-lite`.
200    #[track_caller]
201    pub fn assert_snapshot(mut self, name: &str) -> CliOutcome {
202        let output = self
203            .command
204            .output()
205            .unwrap_or_else(|e| panic!("failed to run `{}`: {e}", self.name));
206        let snap = Snapshot::new(name, self.snap_dir.to_str().expect("valid snap dir"));
207        snap.assert_display(&String::from_utf8_lossy(&output.stdout));
208        CliOutcome {
209            output,
210            cmd_name: self.name,
211        }
212    }
213
214    /// Run the process and snapshot its **stderr** against `<name>.snap`.
215    #[track_caller]
216    pub fn assert_snapshot_stderr(mut self, name: &str) -> CliOutcome {
217        let output = self
218            .command
219            .output()
220            .unwrap_or_else(|e| panic!("failed to run `{}`: {e}", self.name));
221        let snap = Snapshot::new(name, self.snap_dir.to_str().expect("valid snap dir"));
222        snap.assert_display(&String::from_utf8_lossy(&output.stderr));
223        CliOutcome {
224            output,
225            cmd_name: self.name,
226        }
227    }
228
229    /// Run the process and snapshot the **combined stdout + stderr** against
230    /// `<name>.snap`. A `---- stderr ----` separator distinguishes the two streams.
231    #[track_caller]
232    pub fn assert_snapshot_both(mut self, name: &str) -> CliOutcome {
233        let output = self
234            .command
235            .output()
236            .unwrap_or_else(|e| panic!("failed to run `{}`: {e}", self.name));
237        let mut combined = String::new();
238        combined.push_str("---- stdout ----\n");
239        combined.push_str(&String::from_utf8_lossy(&output.stdout));
240        combined.push_str("---- stderr ----\n");
241        combined.push_str(&String::from_utf8_lossy(&output.stderr));
242        let snap = Snapshot::new(name, self.snap_dir.to_str().expect("valid snap dir"));
243        snap.assert_display(&combined);
244        CliOutcome {
245            output,
246            cmd_name: self.name,
247        }
248    }
249}