valico/json_schema/keywords/
enum_.rs
1use serde_json::{Value};
2
3use super::super::schema;
4use super::super::validators;
5
6#[allow(missing_copy_implementations)]
7pub struct Enum;
8impl super::Keyword for Enum {
9 fn compile(&self, def: &Value, ctx: &schema::WalkContext) -> super::KeywordResult {
10 let enum_ = keyword_key_exists!(def, "enum");
11
12 if enum_.is_array() {
13 let enum_ = enum_.as_array().unwrap();
14
15 if enum_.len() == 0 {
16 return Err(schema::SchemaError::Malformed {
17 path: ctx.fragment.join("/"),
18 detail: "This array MUST have at least one element.".to_string()
19 })
20 }
21
22 Ok(Some(Box::new(validators::Enum {
23 items: enum_.clone()
24 })))
25 } else {
26 Err(schema::SchemaError::Malformed {
27 path: ctx.fragment.join("/"),
28 detail: "The value of this keyword MUST be an array.".to_string()
29 })
30 }
31 }
32}
33
34#[cfg(test)] use super::super::scope;
35#[cfg(test)] use jsonway;
36#[cfg(test)] use super::super::builder;
37#[cfg(test)] use serde_json::to_value;
38
39#[test]
40fn validate() {
41 let mut scope = scope::Scope::new();
42 let schema = scope.compile_and_return(builder::schema(|s| {
43 s.enum_(|items| {
44 items.push("prop1".to_string());
45 items.push("prop2".to_string());
46 })
47 }).into_json(), true).ok().unwrap();
48
49 assert_eq!(schema.validate(&to_value(&"prop1").unwrap()).is_valid(), true);
50 assert_eq!(schema.validate(&to_value(&"prop2").unwrap()).is_valid(), true);
51 assert_eq!(schema.validate(&to_value(&"prop3").unwrap()).is_valid(), false);
52 assert_eq!(schema.validate(&to_value(&1).unwrap()).is_valid(), false);
53}
54
55#[test]
56fn malformed() {
57 let mut scope = scope::Scope::new();
58
59 assert!(scope.compile_and_return(jsonway::object(|schema| {
60 schema.array("enum", |_| {});
61 }).unwrap(), true).is_err());
62
63 assert!(scope.compile_and_return(jsonway::object(|schema| {
64 schema.object("enum", |_| {});
65 }).unwrap(), true).is_err());
66}