Skip to content

Commit c395d02

Browse files
committed
test(parser): Show flag behavior
1 parent 32c119e commit c395d02

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

tests/builder/flags.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,3 +222,22 @@ fn leading_dash_stripped() {
222222
let cmd = Command::new("mycat").arg(Arg::new("filename").long("--filename"));
223223
cmd.debug_assert();
224224
}
225+
226+
#[test]
227+
fn optional_value() {
228+
let cmd = Command::new("flag").args([arg!(-f --flag "some flag").action(ArgAction::SetTrue)]);
229+
230+
let m = cmd.clone().try_get_matches_from(vec![""]).unwrap();
231+
assert!(!*m.get_one::<bool>("flag").expect("defaulted by clap"));
232+
233+
let m = cmd.clone().try_get_matches_from(vec!["", "-f"]).unwrap();
234+
assert!(*m.get_one::<bool>("flag").expect("defaulted by clap"));
235+
236+
cmd.clone()
237+
.try_get_matches_from(vec!["", "-f", "true"])
238+
.unwrap_err();
239+
240+
cmd.clone()
241+
.try_get_matches_from(vec!["", "-f", "false"])
242+
.unwrap_err();
243+
}

tests/derive/flags.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,3 +329,27 @@ fn unit_for_negation() {
329329
Opt::try_parse_from(["test", "--arg", "--no-arg"]).unwrap()
330330
);
331331
}
332+
333+
#[test]
334+
#[should_panic = "Argument `alice`'s action SetTrue is incompatible with `num_args(0..=1)`"]
335+
fn optional_value_flag() {
336+
#[derive(Parser, PartialEq, Eq, Debug)]
337+
struct Opt {
338+
#[arg(short, long, num_args=0..=1)]
339+
alice: bool,
340+
}
341+
342+
assert_eq!(Opt { alice: false }, Opt::try_parse_from(["test"]).unwrap());
343+
assert_eq!(
344+
Opt { alice: true },
345+
Opt::try_parse_from(["test", "-a"]).unwrap()
346+
);
347+
assert_eq!(
348+
Opt { alice: true },
349+
Opt::try_parse_from(["test", "-a", "true"]).unwrap()
350+
);
351+
assert_eq!(
352+
Opt { alice: false },
353+
Opt::try_parse_from(["test", "-a", "false"]).unwrap()
354+
);
355+
}

0 commit comments

Comments
 (0)