Skip to content

Commit

Permalink
test(parser): Show flag behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Feb 17, 2025
1 parent 32c119e commit c395d02
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
19 changes: 19 additions & 0 deletions tests/builder/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,22 @@ fn leading_dash_stripped() {
let cmd = Command::new("mycat").arg(Arg::new("filename").long("--filename"));
cmd.debug_assert();
}

#[test]
fn optional_value() {
let cmd = Command::new("flag").args([arg!(-f --flag "some flag").action(ArgAction::SetTrue)]);

let m = cmd.clone().try_get_matches_from(vec![""]).unwrap();
assert!(!*m.get_one::<bool>("flag").expect("defaulted by clap"));

let m = cmd.clone().try_get_matches_from(vec!["", "-f"]).unwrap();
assert!(*m.get_one::<bool>("flag").expect("defaulted by clap"));

cmd.clone()
.try_get_matches_from(vec!["", "-f", "true"])
.unwrap_err();

cmd.clone()
.try_get_matches_from(vec!["", "-f", "false"])
.unwrap_err();
}
24 changes: 24 additions & 0 deletions tests/derive/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,3 +329,27 @@ fn unit_for_negation() {
Opt::try_parse_from(["test", "--arg", "--no-arg"]).unwrap()
);
}

#[test]
#[should_panic = "Argument `alice`'s action SetTrue is incompatible with `num_args(0..=1)`"]
fn optional_value_flag() {
#[derive(Parser, PartialEq, Eq, Debug)]
struct Opt {
#[arg(short, long, num_args=0..=1)]
alice: bool,
}

assert_eq!(Opt { alice: false }, Opt::try_parse_from(["test"]).unwrap());
assert_eq!(
Opt { alice: true },
Opt::try_parse_from(["test", "-a"]).unwrap()
);
assert_eq!(
Opt { alice: true },
Opt::try_parse_from(["test", "-a", "true"]).unwrap()
);
assert_eq!(
Opt { alice: false },
Opt::try_parse_from(["test", "-a", "false"]).unwrap()
);
}

0 comments on commit c395d02

Please sign in to comment.