From 93c26dd42075d94ff64ee9a9a0349c6c2eba2a89 Mon Sep 17 00:00:00 2001 From: Ed Page Date: Fri, 29 Oct 2021 16:08:59 -0500 Subject: [PATCH] test(derive): Verify derive-genned errors are formatted This is to help verify behavior added in #2943. We separated the error raising site from the error formatting site and this verifies that the formatting actually happens. --- clap_derive/tests/help.rs | 44 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/clap_derive/tests/help.rs b/clap_derive/tests/help.rs index 961f3c1ca7f..24ebf69810c 100644 --- a/clap_derive/tests/help.rs +++ b/clap_derive/tests/help.rs @@ -1,4 +1,4 @@ -use clap::{Args, IntoApp, Parser, Subcommand}; +use clap::{AppSettings, Args, ColorChoice, IntoApp, Parser, Subcommand}; #[test] fn arg_help_heading_applied() { @@ -183,3 +183,45 @@ fn flatten_field_with_help_heading() { .unwrap(); assert_eq!(should_be_in_section_a.get_help_heading(), Some("HEADING A")); } + +// The challenge with this test is creating an error situation not caught by `clap`'s error checking +// but by the code that `clap_derive` generates. +// +// Ultimately, the easiest way to confirm is to put a debug statement in the desired error path. +#[test] +fn derive_generated_error_has_full_context() { + #[derive(Debug, Parser)] + #[clap(setting(AppSettings::SubcommandsNegateReqs), color = ColorChoice::Never)] + struct Opts { + #[clap(long)] + req_str: String, + + #[clap(subcommand)] + cmd: Option, + } + + #[derive(Debug, Parser)] + enum SubCommands { + Sub { + #[clap(short, long, parse(from_occurrences))] + verbose: u8, + }, + } + + let result = Opts::try_parse_from(&["test", "sub"]); + assert!( + result.is_err(), + "`SubcommandsNegateReqs` with non-optional `req_str` should fail: {:?}", + result.unwrap() + ); + + let expected = r#"error: The following required argument was not provided: req-str + +USAGE: + clap_derive --req-str + clap_derive + +For more information try --help +"#; + assert_eq!(result.unwrap_err().to_string(), expected); +}