clap/tests/error.rs
Ed Page b9cc585997 feat: Expose clap-style errors to users
This gives users the basic error template for quick and dirty messages.
In addition to the lack of customization, they are not given anything to help
them with coloring or for programmayic use (info, source).

This is something I've wanted many times for one-off validation that
can't be expressed with clap's validation or it just wasn't worth
the hoops.  The more pressing need is for #2255, I need `clap_derive`
to be able to create error messages and `Error::with_description` seemed
too disjoint from the rest of the clap experience that it seemed like
users would immediately create issues about it showing up.

With this available, I've gone ahead and deprecated
`Error::with_description` (added in 58512f2fc), assuming this will be
sufficient for users needs (or they can use IO Errors as a back door).
I did so according to the pattern in #2718 despite us not being fully
resolved on that approach yet.
2021-10-16 19:03:17 -05:00

61 lines
1.7 KiB
Rust

mod utils;
use clap::{App, Arg, ColorChoice, Error, ErrorKind};
fn compare_error(
err: Error,
expected_kind: ErrorKind,
expected_output: &str,
stderr: bool,
) -> bool {
let actual_output = err.to_string();
assert_eq!(
stderr,
err.use_stderr(),
"Should Use STDERR failed. Should be {} but is {}",
stderr,
err.use_stderr()
);
assert_eq!(expected_kind, err.kind);
utils::compare(expected_output, actual_output)
}
#[test]
fn app_error() {
static MESSAGE: &str = "error: Failed for mysterious reasons
USAGE:
test [OPTIONS] --all
For more information try --help
";
let app = App::new("test")
.arg(
Arg::new("all")
.short('a')
.long("all")
.required(true)
.about("Also do versioning for private crates (will not be published)"),
)
.arg(
Arg::new("exact")
.long("exact")
.about("Specify inter dependency version numbers exactly with `=`"),
)
.arg(
Arg::new("no_git_commit")
.long("no-git-commit")
.about("Do not commit version changes"),
)
.arg(
Arg::new("no_git_push")
.long("no-git-push")
.about("Do not push generated commit and tags to git remote"),
);
#[cfg(feature = "color")]
let app = app.color(ColorChoice::Never);
let mut app = app;
let expected_kind = ErrorKind::InvalidValue;
let err = app.error(expected_kind, "Failed for mysterious reasons");
assert!(compare_error(err, expected_kind, MESSAGE, true));
}