Skip to main content

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_.is_empty() {
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)]
35use super::super::builder;
36#[cfg(test)]
37use super::super::scope;
38
39#[cfg(test)]
40use serde_json::to_value;
41
42#[test]
43fn validate() {
44    let mut scope = scope::Scope::new();
45    let schema = scope
46        .compile_and_return(
47            builder::schema(|s| {
48                s.enum_(|items| {
49                    items.push("prop1".to_string());
50                    items.push("prop2".to_string());
51                })
52            })
53            .into_json(),
54            true,
55        )
56        .ok()
57        .unwrap();
58
59    assert_eq!(
60        schema.validate(&to_value("prop1").unwrap()).is_valid(),
61        true
62    );
63    assert_eq!(
64        schema.validate(&to_value("prop2").unwrap()).is_valid(),
65        true
66    );
67    assert_eq!(
68        schema.validate(&to_value("prop3").unwrap()).is_valid(),
69        false
70    );
71    assert_eq!(schema.validate(&to_value(1).unwrap()).is_valid(), false);
72}
73
74#[test]
75fn malformed() {
76    let mut scope = scope::Scope::new();
77
78    assert!(scope
79        .compile_and_return(
80            jsonway::object(|schema| {
81                schema.array("enum", |_| {});
82            })
83            .unwrap(),
84            true
85        )
86        .is_err());
87
88    assert!(scope
89        .compile_and_return(
90            jsonway::object(|schema| {
91                schema.object("enum", |_| {});
92            })
93            .unwrap(),
94            true
95        )
96        .is_err());
97}