Sub topic 14
Testing your CLI
This chapter assumes you can write a derived clap parser with subcommands and ValueEnum arguments, and that you can run cargo test. You should also know that a process exit code of 0 means success.
What to test
A command-line tool has three layers, and each is cheapest to test in a different way.
- The definition. Are the attributes consistent? For example, does a
conflicts_withname an argument that exists? - Parsing. Do the right command lines produce the right typed values, and do the wrong ones fail with the right error?
- Behavior. Does the compiled binary print the right output and exit with the right code?
The first two layers run inside the test process and need no binary. Only the third starts a real process.
A program to test
The examples use the task manager from the subcommands chapter. This version moves the output into a render function so the logic can be tested without printing. The package in Cargo.toml is named tasks, so the binary is also called tasks.
use clap::{Parser, Subcommand, ValueEnum};
#[derive(Parser, Debug)]
#[command(version, about = "A tiny task manager")]
struct Cli {
/// Print extra detail for any subcommand
#[arg(long, global = true)]
verbose: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Add a task
Add {
title: String,
#[arg(long, value_enum, default_value_t = Priority::Normal)]
priority: Priority,
},
/// List tasks
List {
#[arg(short, long)]
all: bool,
},
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum Priority {
Low,
Normal,
High,
}
fn render(cli: &Cli) -> String {
match &cli.command {
Commands::Add { title, priority } => {
format!("add {title:?} with priority {priority:?}")
}
Commands::List { all } => {
format!("list (all = {all}, verbose = {})", cli.verbose)
}
}
}
fn main() {
let cli = Cli::parse();
println!("{}", render(&cli));
}Checking the definition with debug_assert
Some mistakes are in the CLI definition rather than in the user's input. Examples are two arguments with the same long name, or conflicts_with = "verbos" where the argument is verbose. Command::debug_assert checks the whole definition and panics with a description of the problem.
#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;
#[test]
fn cli_definition_is_valid() {
Cli::command().debug_assert();
}
}CommandFactory provides Cli::command(), which builds the same Command the parser uses. Clap also runs these checks in debug builds when it parses. Doing it in a test covers every subcommand, including ones your manual runs never reach. Write this test once and keep it.
Testing parsing with try_parse_from
Cli::parse() reads std::env::args() and exits the process on error, which makes it unusable in a test. Cli::try_parse_from takes any iterator of arguments and returns Result<Cli, clap::Error>.
The first item is the program name, as in a real command line. If you leave it out, clap treats your first real argument as the program name and the test fails in a confusing way.
#[cfg(test)]
mod parse_tests {
use super::*;
use clap::error::ErrorKind;
#[test]
fn add_defaults_to_normal_priority() {
let cli = Cli::try_parse_from(["tasks", "add", "buy milk"]).unwrap();
assert!(matches!(
cli.command,
Commands::Add { ref title, priority: Priority::Normal } if title == "buy milk"
));
}
#[test]
fn global_flag_works_after_the_subcommand() {
let cli = Cli::try_parse_from(["tasks", "list", "--verbose"]).unwrap();
assert!(cli.verbose);
}
#[test]
fn rejects_unknown_priority() {
let err = Cli::try_parse_from(["tasks", "add", "x", "--priority", "urgent"])
.unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidValue);
}
#[test]
fn rejects_unknown_subcommand() {
let err = Cli::try_parse_from(["tasks", "remove"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidSubcommand);
}
#[test]
fn help_is_reported_as_an_error_value_with_exit_code_zero() {
let err = Cli::try_parse_from(["tasks", "--help"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::DisplayHelp);
assert_eq!(err.exit_code(), 0);
}
#[test]
fn render_describes_an_add() {
let cli = Cli::try_parse_from(["tasks", "add", "buy milk", "--priority", "high"])
.unwrap();
assert_eq!(render(&cli), "add \"buy milk\" with priority High");
}
}Assert on the error kind, not the message
clap::Error::kind() returns an ErrorKind. Assert on it rather than on the text of the message. Clap's wording can change between minor releases, but the kinds are part of its API. These are the kinds you will use most.
| Situation | `ErrorKind` |
|---|---|
| Value not in a `ValueEnum` or possible-values list | `InvalidValue` |
| Value failed a `value_parser`, such as `--port abc` or `--port 0` with a range | `ValueValidation` |
| Two arguments marked `conflicts_with` used together | `ArgumentConflict` |
| A required argument is missing | `MissingRequiredArgument` |
| An option or flag that does not exist | `UnknownArgument` |
| A subcommand that does not exist | `InvalidSubcommand` |
| `--help` or `--version` | `DisplayHelp`, `DisplayVersion` |
Help and version are not failures
--help and --version come back as Err from try_parse_from, because the parser stops before it can build a Cli. Their exit_code() is 0, and use_stderr() is false, so Cli::parse prints them to stdout. Real errors have exit code 2 and go to stderr. A test that only checks is_err() cannot tell these cases apart.
Testing the binary
Parsing tests cannot show that stdout, stderr, and the exit code behave correctly in a real process. For that, write an integration test in the tests/ directory. Cargo builds the binary first and exposes its path through the compile-time variable CARGO_BIN_EXE_<name>.
// tests/cli.rs
use std::process::Command;
fn tasks() -> Command {
Command::new(env!("CARGO_BIN_EXE_tasks"))
}
#[test]
fn list_succeeds_and_prints_to_stdout() {
let out = tasks().arg("list").output().unwrap();
assert!(out.status.success());
assert_eq!(
String::from_utf8_lossy(&out.stdout).trim(),
"list (all = false, verbose = false)"
);
}
#[test]
fn bad_priority_exits_with_code_2_and_writes_to_stderr() {
let out = tasks()
.args(["add", "x", "--priority", "urgent"])
.output()
.unwrap();
assert_eq!(out.status.code(), Some(2));
assert!(out.stdout.is_empty());
assert!(String::from_utf8_lossy(&out.stderr).contains("invalid value"));
}Integration tests can only use the binary's public interface. They cannot import Cli, which is private to main.rs. Keep them to a few checks that need a real process: exit codes, the stdout and stderr split, and environment variables.
The text assertion contains("invalid value") is a deliberate exception to the earlier advice. A separate process gives you no ErrorKind, so keep such text checks short and loose.
Environment variables in tests
Say --token has env = "APP_TOKEN". The environment belongs to the whole process, and cargo test runs tests in parallel threads. A unit test that sets APP_TOKEN can change the result of another test running at the same moment.
Test environment fallbacks in an integration test, where each child process gets its own environment:
let out = tasks().env("APP_TOKEN", "secret").arg("list").output().unwrap();Use .env_remove("APP_TOKEN") in tests that expect the variable to be absent. Otherwise they depend on what is set on the developer's machine.
Common errors
- Forgetting the program name in
try_parse_from. The first real argument is swallowed, and you get a missing-argument error. - Calling
Cli::parse()in a test. It reads the test runner's arguments and may exit the test process. - Using
unwrap_err()withoutDebugon the struct.unwrap_errneeds theOktype to implementDebug, so deriveDebugonCliand everything it contains. - Asserting full help text. It changes whenever you edit a doc comment. Test the
ErrorKindinstead, or use a snapshot tool if you need to catch accidental changes.
Exercise
You add #[arg(long, conflicts_with = "quiet")] verbose: bool and a quiet: bool field to a derived Cli. Write the test line that checks that ["app", "--quiet", "--verbose"] fails for the right reason. Name the method that converts the failure into a value you can inspect.
Show answer
Call Cli::try_parse_from(["app", "--quiet", "--verbose"]).unwrap_err() and assert err.kind() == clap::error::ErrorKind::ArgumentConflict. try_parse_from returns the failure as a Result instead of exiting the process, and unwrap_err() extracts the clap::Error so kind() can be compared.
Exercise
A parsing test for --port 0 with value_parser = clap::value_parser!(u16).range(1..=65535) asserts ErrorKind::InvalidValue and fails. What kind should it assert, and why?
Show answer
It should assert ErrorKind::ValueValidation. InvalidValue is for values outside a fixed set, such as a ValueEnum. A range check is a value parser rejecting its input, which clap reports as ValueValidation.