Sub topic 14
Testing your CLI
This chapter assumes you can write Rust unit tests with cargo test and that you have a clap CLI defined with #[derive(Parser)]. It covers two techniques. The first checks that the CLI definition is valid. The second feeds arguments to the parser and inspects the result.
Why test the parser
A CLI definition can be wrong in ways the compiler cannot see. Two arguments might share a short name. A conflicts_with might name an argument that does not exist. Without a test, clap often reports these mistakes only when a user runs the program.
You can also test parsing without starting a process. Cli::parse() reads the real process arguments and exits on error, which makes it awkward to test. try_parse_from takes an iterator of arguments and returns a Result, so a test can check the outcome directly.
Checking the definition with debug_assert
CommandFactory::command() builds the Command that the derive macro generates. Calling debug_assert() on it runs clap's internal checks on the definition. A failed check panics with a message that names the problem.
Feeding arguments with try_parse_from
The first item of the iterator plays the role of the program name, as in a real command line. Use any placeholder, such as "app".
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
#[arg(long, default_value_t = 8080)]
port: u16,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}
#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;
#[test]
fn cli_definition_is_valid() {
Cli::command().debug_assert();
}
#[test]
fn parses_port() {
let cli = Cli::try_parse_from(["app", "--port", "9000"]).unwrap();
assert_eq!(cli.port, 9000);
}
#[test]
fn uses_default_port() {
let cli = Cli::try_parse_from(["app"]).unwrap();
assert_eq!(cli.port, 8080);
}
#[test]
fn rejects_non_numeric_port() {
assert!(Cli::try_parse_from(["app", "--port", "abc"]).is_err());
}
}Run the tests with cargo test. All four should pass.
Testing for specific errors
is_err() tells you that parsing failed, but not why. A failure of the wrong kind can still pass such a test. The error returned by try_parse_from has a kind() method that returns an ErrorKind. Matching on it makes the test precise.
use clap::error::ErrorKind;
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
#[arg(long, conflicts_with = "verbose")]
quiet: bool,
#[arg(long)]
verbose: bool,
}
fn main() {
println!("{:?}", Cli::parse());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quiet_conflicts_with_verbose() {
let err = Cli::try_parse_from(["app", "--quiet", "--verbose"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
}
}Common mistakes
- Leaving out the program name.
try_parse_from(["--port", "9000"])treats--portas the program name, so the value is ignored and you get the default. - Calling
Cli::parse()in a test. A parse error callsstd::process::exit, which ends the whole test run instead of failing one test. - Skipping
debug_assert. Without it, definition mistakes can stay hidden until a particular argument combination is used.
Exercise
Why does Cli::try_parse_from(["--port", "9000"]) not give you port 9000, and how do you fix it?
Show answer
The first item is taken as the program name, not as an argument. Here --port is consumed as the name, so 9000 is parsed as a positional argument, which is an error for this struct, or the default is used if one is accepted. Add a placeholder program name first: ["app", "--port", "9000"].
Exercise
What does Cli::command().debug_assert() check that try_parse_from tests do not?
Show answer
It checks the definition itself, such as duplicate short names or references to arguments that do not exist, for every argument at once. try_parse_from tests only exercise the paths that the supplied arguments reach.