1 // Copyright 2018 Guillaume Pinot (@TeXitoi) <texitoi@texitoi.eu>
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 
9 #[macro_use]
10 extern crate structopt;
11 
12 use structopt::StructOpt;
13 
14 #[test]
flatten()15 fn flatten() {
16     #[derive(StructOpt, PartialEq, Debug)]
17     struct Common {
18         arg: i32,
19     }
20 
21     #[derive(StructOpt, PartialEq, Debug)]
22     struct Opt {
23         #[structopt(flatten)]
24         common: Common,
25     }
26     assert_eq!(
27         Opt {
28             common: Common { arg: 42 }
29         },
30         Opt::from_iter(&["test", "42"])
31     );
32     assert!(Opt::clap().get_matches_from_safe(&["test"]).is_err());
33     assert!(Opt::clap()
34         .get_matches_from_safe(&["test", "42", "24"])
35         .is_err());
36 }
37 
38 #[test]
39 #[should_panic]
flatten_twice()40 fn flatten_twice() {
41     #[derive(StructOpt, PartialEq, Debug)]
42     struct Common {
43         arg: i32,
44     }
45 
46     #[derive(StructOpt, PartialEq, Debug)]
47     struct Opt {
48         #[structopt(flatten)]
49         c1: Common,
50         // Defines "arg" twice, so this should not work.
51         #[structopt(flatten)]
52         c2: Common,
53     }
54     Opt::from_iter(&["test", "42", "43"]);
55 }
56 
57 #[test]
flatten_in_subcommand()58 fn flatten_in_subcommand() {
59     #[derive(StructOpt, PartialEq, Debug)]
60     struct Common {
61         arg: i32,
62     }
63 
64     #[derive(StructOpt, PartialEq, Debug)]
65     struct Add {
66         #[structopt(short = "i")]
67         interactive: bool,
68         #[structopt(flatten)]
69         common: Common,
70     }
71 
72     #[derive(StructOpt, PartialEq, Debug)]
73     enum Opt {
74         #[structopt(name = "fetch")]
75         Fetch {
76             #[structopt(short = "a")]
77             all: bool,
78             #[structopt(flatten)]
79             common: Common,
80         },
81 
82         #[structopt(name = "add")]
83         Add(Add),
84     }
85 
86     assert_eq!(
87         Opt::Fetch {
88             all: false,
89             common: Common { arg: 42 }
90         },
91         Opt::from_iter(&["test", "fetch", "42"])
92     );
93     assert_eq!(
94         Opt::Add(Add {
95             interactive: true,
96             common: Common { arg: 43 }
97         }),
98         Opt::from_iter(&["test", "add", "-i", "43"])
99     );
100 }
101