]>
Commit | Line | Data |
---|---|---|
f20569fa XL |
1 | //! How to use `required_if` with structopt. |
2 | use structopt::StructOpt; | |
3 | ||
4 | #[derive(Debug, StructOpt, PartialEq)] | |
5 | struct 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 | ||
15 | fn main() { | |
16 | let opt = Opt::from_args(); | |
17 | println!("{:?}", opt); | |
18 | } | |
19 | ||
20 | #[cfg(test)] | |
21 | mod 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 | } |