What would be the most idiomatic way to write tests for a CLI program using clap
? I'm currently doing it like this:
#[derive(Debug, Parser)]
#[clap(author, version, about)]
pub struct StructArgs {
#[clap(subcommand)]
pub command_type: CommandType,
}
#[derive(Debug, Subcommand)]
pub enum CommandType {
Command1(Command1Args),
...
}
#[derive(Debug, Args)]
pub struct Command1Args {
pub field: String,
...
}
impl Command1Args {
...
}
#[test]
fn test_do_stuff() {
let args = StructArgs::try_parse_from(
std::iter::once("<PROGRAM NAME>")
.chain(
["<ARG 1>", ..., "<ARG n>"]
.iter()
.cloned()
)
);
if let CommandType::Command1(command1_args) = args.command_type {
// do stuff with command1_args
} else {
panic!();
}
}
Basically I pass to clap
an iterator of arguments, then I check if the parsed command structure matches with the CommandType
I expect, and I proceed to test its methods and internal state. The panic
in the else branch is for failing the test if for some reason I get an unexpected CommandType
, meaning most likely that I have written something wrong in the iterator.
Can this be improved further?