blob: cb6b414e2a865c422ae6475753ddbe51508d892f [file] [log] [blame]
Haibo Huange7bfadf2020-09-23 21:23:42 -07001//! How to use `required_if` with structopt.
2use structopt::StructOpt;
3
4#[derive(Debug, StructOpt, PartialEq)]
5struct Opt {
6 /// Where to write the output: to `stdout` or `file`
7 #[structopt(short)]
8 out_type: String,
9
10 /// File name: only required when `out-type` is set to `file`
11 #[structopt(name = "FILE", required_if("out-type", "file"))]
12 file_name: Option<String>,
13}
14
15fn main() {
16 let opt = Opt::from_args();
17 println!("{:?}", opt);
18}
19
20#[cfg(test)]
21mod tests {
22 use super::*;
23
24 #[test]
25 fn test_opt_out_type_file_without_file_name_returns_err() {
26 let opt = Opt::from_iter_safe(&["test", "-o", "file"]);
27 let err = opt.unwrap_err();
28 assert_eq!(err.kind, clap::ErrorKind::MissingRequiredArgument);
29 }
30
31 #[test]
32 fn test_opt_out_type_file_with_file_name_returns_ok() {
33 let opt = Opt::from_iter_safe(&["test", "-o", "file", "filename"]);
34 let opt = opt.unwrap();
35 assert_eq!(
36 opt,
37 Opt {
38 out_type: "file".into(),
39 file_name: Some("filename".into()),
40 }
41 );
42 }
43}