clap/tests/builder/validators.rs

67 lines
1.8 KiB
Rust
Raw Normal View History

2022-02-12 03:48:29 +00:00
use clap::{Arg, Command};
#[cfg(debug_assertions)]
#[test]
#[should_panic = "Argument 'test' has both `validator` and `validator_os` set which is not allowed"]
fn both_validator_and_validator_os() {
2022-02-12 03:48:29 +00:00
let _ = Command::new("test")
.arg(
Arg::new("test")
.validator(|val| val.parse::<u32>().map_err(|e| e.to_string()))
.validator_os(|val| {
val.to_str()
.unwrap()
.parse::<u32>()
.map_err(|e| e.to_string())
}),
)
2022-02-14 21:47:20 +00:00
.try_get_matches_from(&["cmd", "1"]);
}
#[test]
fn test_validator_fromstr_trait() {
use std::str::FromStr;
2022-02-12 03:48:29 +00:00
let matches = Command::new("test")
.arg(Arg::new("from_str").validator(u32::from_str))
2022-02-14 21:47:20 +00:00
.try_get_matches_from(&["cmd", "1234"])
.expect("match failed");
assert_eq!(matches.value_of_t::<u32>("from_str").ok(), Some(1234));
}
#[test]
fn test_validator_msg_newline() {
2022-02-12 03:48:29 +00:00
let res = Command::new("test")
.arg(Arg::new("test").validator(|val| val.parse::<u32>().map_err(|e| e.to_string())))
2022-02-14 21:47:20 +00:00
.try_get_matches_from(&["cmd", "f"]);
assert!(res.is_err());
let err = res.unwrap_err();
2020-08-22 09:43:58 +00:00
assert!(
err.to_string()
.contains("Invalid value \"f\" for '<test>': invalid digit found in string"),
2020-08-22 09:43:58 +00:00
"{}",
err
);
// This message is the only thing that gets printed -- make sure it ends with a newline
let msg = format!("{}", err);
assert!(msg.ends_with('\n'));
}
2020-07-03 08:00:11 +00:00
#[test]
fn stateful_validator() {
let mut state = false;
2022-02-12 03:48:29 +00:00
Command::new("test")
2020-07-03 08:00:11 +00:00
.arg(Arg::new("test").validator(|val| {
state = true;
val.parse::<u32>().map_err(|e| e.to_string())
}))
2022-02-14 21:47:20 +00:00
.try_get_matches_from(&["cmd", "10"])
2020-07-03 08:00:11 +00:00
.unwrap();
assert!(state);
}