bind-conf/bind_conf_derive/tests/test_derive_struct.rs

133 lines
3.0 KiB
Rust

use bind_conf_derive::*;
use bind_conf::{Parse, Parser};
#[test]
fn derive_struct() {
#[derive(Parse, Debug, PartialEq)]
struct MyStruct {
#[parse(rename = "other-name")]
first_field: Option<String>,
#[parse(alias = "my-other-name")]
second_field: String,
}
assert_eq!(
Parser::new(r#"{
second-field "my other string";
other-name my-string;
}"#).read::<MyStruct>().unwrap(),
MyStruct {
first_field: Some("my-string".into()),
second_field: "my other string".into(),
}
);
assert_eq!(
Parser::new(r#"{
my-other-name "im a lonely statement";
}"#).read::<MyStruct>().unwrap(),
MyStruct {
first_field: None,
second_field: "im a lonely statement".into(),
}
);
}
#[test]
fn derive_struct_inline() {
#[derive(Parse, Debug, PartialEq)]
struct MyStruct {
#[parse(inline)]
first_field: String,
second_field: String,
}
assert_eq!(
Parser::new(r#"
"im inline" {
second-field "im in block";
}
"#).read::<MyStruct>().unwrap(),
MyStruct {
first_field: "im inline".into(),
second_field: "im in block".into(),
}
);
}
#[test]
fn derive_struct_inline_without_block() {
#[derive(Parse, Debug, PartialEq)]
struct MyStruct {
#[parse(inline)]
first_field: String,
#[parse(inline)]
second_field: String,
}
assert_eq!(
Parser::new(r#"
"im inline" "me too"
"#).read::<MyStruct>().unwrap(),
MyStruct {
first_field: "im inline".into(),
second_field: "me too".into(),
}
);
}
#[test]
fn derive_struct_newtype() {
#[derive(Parse, Debug, PartialEq)]
struct MyNewType(String);
assert_eq!(
Parser::new("my-value;").read::<MyNewType>().unwrap(),
MyNewType("my-value".into())
);
}
#[test]
fn derive_struct_default() {
mod my_mod {
pub fn my_field_default() -> String {
"such default string".into()
}
}
#[derive(Parse, Debug, PartialEq)]
struct MyStruct {
#[parse(default = "my_mod::my_field_default")]
my_field: String
}
assert_eq!(
Parser::new("{ }").read::<MyStruct>().unwrap(),
MyStruct { my_field: my_mod::my_field_default() }
);
}
#[test]
fn derive_struct_inline_default() {
pub fn my_field_default() -> String {
"such default string".into()
}
#[derive(Parse, Debug, PartialEq)]
struct MyStruct {
#[parse(inline)]
my_field: String,
#[parse(inline, default = "my_field_default")]
my_other_field: String
}
assert_eq!(
Parser::new(r#" "value"; "#).read::<MyStruct>().unwrap(),
MyStruct {
my_field: "value".into(),
my_other_field: my_field_default()
}
);
}