clap/tests/derive/flatten.rs

298 lines
7 KiB
Rust
Raw Normal View History

2018-07-02 17:41:01 +00:00
// Copyright 2018 Guillaume Pinot (@TeXitoi) <texitoi@texitoi.eu>,
// Kevin Knapp (@kbknapp) <kbknapp@gmail.com>, and
2022-01-04 20:10:35 +00:00
// Ana Hobden (@hoverbear) <operator@hoverbear.org>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
2018-07-02 17:41:01 +00:00
//
// This work was derived from Structopt (https://github.com/TeXitoi/structopt)
// commit#ea76fa1b1b273e65e3b0b1046643715b49bec51f which is licensed under the
// MIT/Apache 2.0 license.
use crate::utils;
use clap::{Args, Parser, Subcommand};
#[test]
fn flatten() {
#[derive(Args, PartialEq, Debug)]
struct Common {
arg: i32,
}
#[derive(Parser, PartialEq, Debug)]
struct Opt {
#[command(flatten)]
common: Common,
}
2018-05-21 14:54:22 +00:00
assert_eq!(
Opt {
common: Common { arg: 42 }
},
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "42"]).unwrap()
2018-05-21 14:54:22 +00:00
);
2022-11-24 13:54:25 +00:00
assert!(Opt::try_parse_from(["test"]).is_err());
assert!(Opt::try_parse_from(["test", "42", "24"]).is_err());
}
2020-04-09 16:19:05 +00:00
#[cfg(debug_assertions)]
#[test]
#[should_panic]
fn flatten_twice() {
#[derive(Args, PartialEq, Debug)]
struct Common {
arg: i32,
}
#[derive(Parser, PartialEq, Debug)]
struct Opt {
#[command(flatten)]
c1: Common,
// Defines "arg" twice, so this should not work.
#[command(flatten)]
c2: Common,
}
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "42", "43"]).unwrap();
}
#[test]
fn flatten_in_subcommand() {
#[derive(Args, PartialEq, Debug)]
struct Common {
arg: i32,
}
#[derive(Args, PartialEq, Debug)]
struct Add {
#[arg(short)]
interactive: bool,
#[command(flatten)]
common: Common,
}
#[derive(Parser, PartialEq, Debug)]
enum Opt {
Fetch {
#[arg(short)]
all: bool,
#[command(flatten)]
common: Common,
},
Add(Add),
}
2018-05-21 14:54:22 +00:00
assert_eq!(
Opt::Fetch {
all: false,
common: Common { arg: 42 }
},
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "fetch", "42"]).unwrap()
2018-05-21 14:54:22 +00:00
);
assert_eq!(
Opt::Add(Add {
interactive: true,
common: Common { arg: 43 }
}),
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "add", "-i", "43"]).unwrap()
2018-05-21 14:54:22 +00:00
);
}
#[test]
fn update_args_with_flatten() {
#[derive(Args, PartialEq, Debug)]
struct Common {
arg: i32,
}
#[derive(Parser, PartialEq, Debug)]
struct Opt {
#[command(flatten)]
common: Common,
}
let mut opt = Opt {
common: Common { arg: 42 },
};
2022-11-24 13:54:25 +00:00
opt.try_update_from(["test"]).unwrap();
assert_eq!(Opt::try_parse_from(["test", "42"]).unwrap(), opt);
let mut opt = Opt {
common: Common { arg: 42 },
};
2022-11-24 13:54:25 +00:00
opt.try_update_from(["test", "52"]).unwrap();
assert_eq!(Opt::try_parse_from(["test", "52"]).unwrap(), opt);
}
#[derive(Subcommand, PartialEq, Debug)]
enum BaseCli {
Command1(Command1),
}
#[derive(Args, PartialEq, Debug)]
struct Command1 {
arg1: i32,
arg2: i32,
}
#[derive(Args, PartialEq, Debug)]
struct Command2 {
arg2: i32,
}
#[derive(Parser, PartialEq, Debug)]
enum Opt {
#[command(flatten)]
BaseCli(BaseCli),
Command2(Command2),
}
#[test]
fn merge_subcommands_with_flatten() {
assert_eq!(
Opt::BaseCli(BaseCli::Command1(Command1 { arg1: 42, arg2: 44 })),
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "command1", "42", "44"]).unwrap()
);
assert_eq!(
Opt::Command2(Command2 { arg2: 43 }),
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "command2", "43"]).unwrap()
);
}
2020-08-25 07:53:54 +00:00
#[test]
fn update_subcommands_with_flatten() {
let mut opt = Opt::BaseCli(BaseCli::Command1(Command1 { arg1: 12, arg2: 14 }));
2022-11-24 13:54:25 +00:00
opt.try_update_from(["test", "command1", "42", "44"])
.unwrap();
test(derive): Provide better error info `Parser::parse_from` will call `exit` on failure and we don't just lose backtrace information but we don't even know which of the tests running in parallel panicked. I ran into this when experimenting with `clap_derive` and I couldn't tell what actually failed. So let's switch to `Parse::try_parse_from`. Errors went from: ``` test option_option ... ok error: Found argument 'bar' which wasn't expected, or isn't valid in this context USAGE: clap_derive [OPTIONS] For more information try --help error: test failed, to rerun pass '--test arg_enum' ``` To: ``` test option_option ... ok test variant_with_defined_casing ... ok test skip_variant ... ok test default_value ... ok test vector ... FAILED test option_vector ... ok failures: ---- vector stdout ---- thread 'vector' panicked at 'called `Result::unwrap()` on an `Err` value: Error { message: Formatted(Colorizer { use_stderr: true, color_when: Auto , pieces: [("error:", Some(Red)), (" ", None), ("Found argument '", None), ("bar", Some(Yellow)), ("' which wasn't expected, or isn't valid in this context", None), ("\n\n", None), ("USAGE:\n clap_derive [OPTIONS]", None), ("\n\nFor more information try ", None), ("--help", Some(Green)), (" \n", None)] }), kind: UnknownArgument, info: ["bar"], source: None, backtrace: Backtrace }', clap_derive/tests/arg_enum.rs:388:56 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: vector test result: FAILED. 15 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--test arg_enum' ```
2021-10-30 14:55:50 +00:00
assert_eq!(
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "command1", "42", "44"]).unwrap(),
test(derive): Provide better error info `Parser::parse_from` will call `exit` on failure and we don't just lose backtrace information but we don't even know which of the tests running in parallel panicked. I ran into this when experimenting with `clap_derive` and I couldn't tell what actually failed. So let's switch to `Parse::try_parse_from`. Errors went from: ``` test option_option ... ok error: Found argument 'bar' which wasn't expected, or isn't valid in this context USAGE: clap_derive [OPTIONS] For more information try --help error: test failed, to rerun pass '--test arg_enum' ``` To: ``` test option_option ... ok test variant_with_defined_casing ... ok test skip_variant ... ok test default_value ... ok test vector ... FAILED test option_vector ... ok failures: ---- vector stdout ---- thread 'vector' panicked at 'called `Result::unwrap()` on an `Err` value: Error { message: Formatted(Colorizer { use_stderr: true, color_when: Auto , pieces: [("error:", Some(Red)), (" ", None), ("Found argument '", None), ("bar", Some(Yellow)), ("' which wasn't expected, or isn't valid in this context", None), ("\n\n", None), ("USAGE:\n clap_derive [OPTIONS]", None), ("\n\nFor more information try ", None), ("--help", Some(Green)), (" \n", None)] }), kind: UnknownArgument, info: ["bar"], source: None, backtrace: Backtrace }', clap_derive/tests/arg_enum.rs:388:56 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: vector test result: FAILED. 15 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--test arg_enum' ```
2021-10-30 14:55:50 +00:00
opt
);
let mut opt = Opt::BaseCli(BaseCli::Command1(Command1 { arg1: 12, arg2: 14 }));
2022-11-24 13:54:25 +00:00
opt.try_update_from(["test", "command1", "42"]).unwrap();
test(derive): Provide better error info `Parser::parse_from` will call `exit` on failure and we don't just lose backtrace information but we don't even know which of the tests running in parallel panicked. I ran into this when experimenting with `clap_derive` and I couldn't tell what actually failed. So let's switch to `Parse::try_parse_from`. Errors went from: ``` test option_option ... ok error: Found argument 'bar' which wasn't expected, or isn't valid in this context USAGE: clap_derive [OPTIONS] For more information try --help error: test failed, to rerun pass '--test arg_enum' ``` To: ``` test option_option ... ok test variant_with_defined_casing ... ok test skip_variant ... ok test default_value ... ok test vector ... FAILED test option_vector ... ok failures: ---- vector stdout ---- thread 'vector' panicked at 'called `Result::unwrap()` on an `Err` value: Error { message: Formatted(Colorizer { use_stderr: true, color_when: Auto , pieces: [("error:", Some(Red)), (" ", None), ("Found argument '", None), ("bar", Some(Yellow)), ("' which wasn't expected, or isn't valid in this context", None), ("\n\n", None), ("USAGE:\n clap_derive [OPTIONS]", None), ("\n\nFor more information try ", None), ("--help", Some(Green)), (" \n", None)] }), kind: UnknownArgument, info: ["bar"], source: None, backtrace: Backtrace }', clap_derive/tests/arg_enum.rs:388:56 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: vector test result: FAILED. 15 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--test arg_enum' ```
2021-10-30 14:55:50 +00:00
assert_eq!(
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "command1", "42", "14"]).unwrap(),
test(derive): Provide better error info `Parser::parse_from` will call `exit` on failure and we don't just lose backtrace information but we don't even know which of the tests running in parallel panicked. I ran into this when experimenting with `clap_derive` and I couldn't tell what actually failed. So let's switch to `Parse::try_parse_from`. Errors went from: ``` test option_option ... ok error: Found argument 'bar' which wasn't expected, or isn't valid in this context USAGE: clap_derive [OPTIONS] For more information try --help error: test failed, to rerun pass '--test arg_enum' ``` To: ``` test option_option ... ok test variant_with_defined_casing ... ok test skip_variant ... ok test default_value ... ok test vector ... FAILED test option_vector ... ok failures: ---- vector stdout ---- thread 'vector' panicked at 'called `Result::unwrap()` on an `Err` value: Error { message: Formatted(Colorizer { use_stderr: true, color_when: Auto , pieces: [("error:", Some(Red)), (" ", None), ("Found argument '", None), ("bar", Some(Yellow)), ("' which wasn't expected, or isn't valid in this context", None), ("\n\n", None), ("USAGE:\n clap_derive [OPTIONS]", None), ("\n\nFor more information try ", None), ("--help", Some(Green)), (" \n", None)] }), kind: UnknownArgument, info: ["bar"], source: None, backtrace: Backtrace }', clap_derive/tests/arg_enum.rs:388:56 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: vector test result: FAILED. 15 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--test arg_enum' ```
2021-10-30 14:55:50 +00:00
opt
);
let mut opt = Opt::BaseCli(BaseCli::Command1(Command1 { arg1: 12, arg2: 14 }));
2022-11-24 13:54:25 +00:00
opt.try_update_from(["test", "command2", "43"]).unwrap();
test(derive): Provide better error info `Parser::parse_from` will call `exit` on failure and we don't just lose backtrace information but we don't even know which of the tests running in parallel panicked. I ran into this when experimenting with `clap_derive` and I couldn't tell what actually failed. So let's switch to `Parse::try_parse_from`. Errors went from: ``` test option_option ... ok error: Found argument 'bar' which wasn't expected, or isn't valid in this context USAGE: clap_derive [OPTIONS] For more information try --help error: test failed, to rerun pass '--test arg_enum' ``` To: ``` test option_option ... ok test variant_with_defined_casing ... ok test skip_variant ... ok test default_value ... ok test vector ... FAILED test option_vector ... ok failures: ---- vector stdout ---- thread 'vector' panicked at 'called `Result::unwrap()` on an `Err` value: Error { message: Formatted(Colorizer { use_stderr: true, color_when: Auto , pieces: [("error:", Some(Red)), (" ", None), ("Found argument '", None), ("bar", Some(Yellow)), ("' which wasn't expected, or isn't valid in this context", None), ("\n\n", None), ("USAGE:\n clap_derive [OPTIONS]", None), ("\n\nFor more information try ", None), ("--help", Some(Green)), (" \n", None)] }), kind: UnknownArgument, info: ["bar"], source: None, backtrace: Backtrace }', clap_derive/tests/arg_enum.rs:388:56 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: vector test result: FAILED. 15 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--test arg_enum' ```
2021-10-30 14:55:50 +00:00
assert_eq!(
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "command2", "43"]).unwrap(),
test(derive): Provide better error info `Parser::parse_from` will call `exit` on failure and we don't just lose backtrace information but we don't even know which of the tests running in parallel panicked. I ran into this when experimenting with `clap_derive` and I couldn't tell what actually failed. So let's switch to `Parse::try_parse_from`. Errors went from: ``` test option_option ... ok error: Found argument 'bar' which wasn't expected, or isn't valid in this context USAGE: clap_derive [OPTIONS] For more information try --help error: test failed, to rerun pass '--test arg_enum' ``` To: ``` test option_option ... ok test variant_with_defined_casing ... ok test skip_variant ... ok test default_value ... ok test vector ... FAILED test option_vector ... ok failures: ---- vector stdout ---- thread 'vector' panicked at 'called `Result::unwrap()` on an `Err` value: Error { message: Formatted(Colorizer { use_stderr: true, color_when: Auto , pieces: [("error:", Some(Red)), (" ", None), ("Found argument '", None), ("bar", Some(Yellow)), ("' which wasn't expected, or isn't valid in this context", None), ("\n\n", None), ("USAGE:\n clap_derive [OPTIONS]", None), ("\n\nFor more information try ", None), ("--help", Some(Green)), (" \n", None)] }), kind: UnknownArgument, info: ["bar"], source: None, backtrace: Backtrace }', clap_derive/tests/arg_enum.rs:388:56 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: vector test result: FAILED. 15 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s error: test failed, to rerun pass '--test arg_enum' ```
2021-10-30 14:55:50 +00:00
opt
);
}
2020-08-25 07:53:54 +00:00
#[test]
fn flatten_with_doc_comment() {
#[derive(Args, PartialEq, Debug)]
struct Common {
/// This is an arg. Arg means "argument". Command line argument.
arg: i32,
2020-08-25 07:53:54 +00:00
}
#[derive(Parser, PartialEq, Debug)]
2020-08-25 07:53:54 +00:00
struct Opt {
/// The very important comment that clippy had me put here.
/// It knows better.
#[command(flatten)]
common: Common,
2020-08-25 07:53:54 +00:00
}
assert_eq!(
Opt {
common: Common { arg: 42 }
},
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "42"]).unwrap()
);
let help = utils::get_help::<Opt>();
assert!(help.contains("This is an arg."));
assert!(!help.contains("The very important"));
2020-08-25 07:53:54 +00:00
}
#[test]
fn docstrings_ordering_with_multiple_command() {
/// This is the docstring for Flattened
#[derive(Args)]
struct Flattened {
#[arg(long)]
foo: bool,
}
/// This is the docstring for Command
#[derive(Parser)]
struct Command {
#[command(flatten)]
flattened: Flattened,
}
let short_help = utils::get_help::<Command>();
assert!(short_help.contains("This is the docstring for Command"));
}
#[test]
fn docstrings_ordering_with_multiple_clap_partial() {
/// This is the docstring for Flattened
#[derive(Args)]
struct Flattened {
#[arg(long)]
foo: bool,
}
#[derive(Parser)]
struct Command {
#[command(flatten)]
flattened: Flattened,
}
let short_help = utils::get_help::<Command>();
assert!(short_help.contains("This is the docstring for Flattened"));
}
#[test]
fn optional_flatten() {
#[derive(Parser, Debug, PartialEq, Eq)]
struct Opt {
#[command(flatten)]
source: Option<Source>,
}
#[derive(clap::Args, Debug, PartialEq, Eq)]
struct Source {
crates: Vec<String>,
#[arg(long)]
path: Option<std::path::PathBuf>,
#[arg(long)]
git: Option<String>,
}
2022-11-24 13:54:25 +00:00
assert_eq!(Opt { source: None }, Opt::try_parse_from(["test"]).unwrap());
assert_eq!(
Opt {
source: Some(Source {
crates: vec!["serde".to_owned()],
path: None,
git: None,
}),
},
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "serde"]).unwrap()
);
assert_eq!(
Opt {
source: Some(Source {
crates: Vec::new(),
path: Some("./".into()),
git: None,
}),
},
2022-11-24 13:54:25 +00:00
Opt::try_parse_from(["test", "--path=./"]).unwrap()
);
}