implement string enum validation

This commit is contained in:
Dietmar Maurer 2018-11-07 13:25:47 +01:00
parent 0a33b12851
commit a908292008
1 changed files with 36 additions and 4 deletions

View File

@ -97,6 +97,7 @@ pub const DEFAULTSTRING: JssString = JssString {
#[derive(Debug)] #[derive(Debug)]
pub enum ApiStringFormat { pub enum ApiStringFormat {
None, None,
Enum(Vec<String>),
Pattern(Box<Regex>), Pattern(Box<Regex>),
Complex(Box<Jss>), Complex(Box<Jss>),
} }
@ -175,11 +176,22 @@ fn parse_simple_value(value_str: &str, schema: &Jss) -> Result<Value, Error> {
} }
} }
if let ApiStringFormat::Pattern(ref regex) = jss_string.format { match jss_string.format {
ApiStringFormat::None => { /* do nothing */ }
ApiStringFormat::Pattern(ref regex) => {
if !regex.is_match(&res) { if !regex.is_match(&res) {
bail!("value does not match the regex pattern"); bail!("value does not match the regex pattern");
} }
} }
ApiStringFormat::Enum(ref stringvec) => {
if stringvec.iter().find(|&e| *e == res) == None {
bail!("value is not defined in the enumeration.");
}
}
ApiStringFormat::Complex(ref subschema) => {
bail!("implement me!");
}
}
Value::String(res) Value::String(res)
} }
@ -358,6 +370,26 @@ fn test_query_string() {
let res = parse_query_string("name=test", &schema, true); let res = parse_query_string("name=test", &schema, true);
assert!(res.is_ok()); assert!(res.is_ok());
// TEST string enums
let schema = parameter!{name => ApiString!{
optional => false,
format => ApiStringFormat::Enum(vec!["ev1".into(), "ev2".into()])
}};
let res = parse_query_string("name=noenum", &schema, true);
assert!(res.is_err());
let res = parse_query_string("name=ev1", &schema, true);
assert!(res.is_ok());
let res = parse_query_string("name=ev2", &schema, true);
assert!(res.is_ok());
let res = parse_query_string("name=ev3", &schema, true);
assert!(res.is_err());
} }
#[test] #[test]