1
0
mirror of https://github.com/danog/strum.git synced 2024-12-03 18:07:52 +01:00
strum/strum_tests/tests/enum_variant_names.rs
Pascal Hertleif 96daaf4021 Add EnumVariantNames (#56)
* Add `EnumVariantNames`

This derive adds a static `variants()` methods yielding the names of
the enum variants. This happens to be exactly what clap [wants][1], and
is the last puzzle piece to use strum with clap/structopt.

[1]: https://docs.rs/clap/2.33.0/clap/macro.arg_enum.html

* Expand readme section for `EnumVariantNames`

* Return slice instead of array

This reduces the risk of breaking the public API by accident when adding
a new variant.

* Fix typo in Readme

* Add generic doc comment to `variants()` method

* Add test case using `variants` in clap/structopt
2019-07-15 10:06:33 -07:00

91 lines
1.8 KiB
Rust

#[macro_use]
extern crate strum_macros;
#[macro_use]
extern crate structopt;
extern crate strum;
#[test]
fn simple() {
#[allow(dead_code)]
#[derive(EnumVariantNames)]
enum Color {
Red,
Blue,
Yellow,
}
assert_eq!(&Color::variants(), &["Red", "Blue", "Yellow"]);
}
#[test]
fn plain_kebab() {
#[allow(dead_code)]
#[derive(EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
enum Color {
Red,
Blue,
Yellow,
RebeccaPurple,
}
assert_eq!(
&Color::variants(),
&["red", "blue", "yellow", "rebecca-purple"]
);
}
#[test]
fn non_plain_camel() {
#[allow(dead_code)]
#[derive(EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
enum Color {
DeepPink,
GreenYellow,
CornflowerBlue,
Other { r: u8, g: u8, b: u8 },
}
assert_eq!(
&Color::variants(),
&["deep-pink", "green-yellow", "cornflower-blue", "other"]
);
}
#[test]
fn clap_and_structopt() {
#[derive(Debug, EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
enum Color {
Red,
Blue,
Yellow,
RebeccaPurple,
}
assert_eq!(
&Color::variants(),
&["red", "blue", "yellow", "rebecca-purple"]
);
let _clap_example = clap::App::new("app").arg(
clap::Arg::with_name("color")
.long("color")
.possible_values(Color::variants())
.case_insensitive(true),
);
#[derive(Debug, StructOpt)]
#[allow(unused)]
struct StructOptExample {
/// The main color
#[structopt(
long = "color",
default_value = "Color::Blue",
raw(possible_values = "Color::variants()")
)]
color: Color,
}
}