valico/json_schema/keywords/
required.rs1use serde_json::Value;
2
3use super::super::schema;
4use super::super::validators;
5
6#[allow(missing_copy_implementations)]
7pub struct Required;
8impl super::Keyword for Required {
9 fn compile(&self, def: &Value, ctx: &schema::WalkContext<'_>) -> super::KeywordResult {
10 let required = keyword_key_exists!(def, "required");
11
12 if required.is_array() {
13 let required = required.as_array().unwrap();
14
15 let mut items = vec![];
16 for item in required.iter() {
17 if item.is_string() {
18 items.push(item.as_str().unwrap().to_string())
19 } else {
20 return Err(schema::SchemaError::Malformed {
21 path: ctx.fragment.join("/"),
22 detail: "The values of `required` MUST be strings".to_string(),
23 });
24 }
25 }
26
27 Ok(Some(Box::new(validators::Required { items })))
28 } else {
29 Err(schema::SchemaError::Malformed {
30 path: ctx.fragment.join("/"),
31 detail: "The value of this keyword MUST be an array.".to_string(),
32 })
33 }
34 }
35}
36
37#[cfg(test)]
38use super::super::builder;
39#[cfg(test)]
40use super::super::scope;
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.required(vec!["prop1".to_string(), "prop2".to_string()]);
49 })
50 .into_json(),
51 true,
52 )
53 .ok()
54 .unwrap();
55
56 assert_eq!(
57 schema
58 .validate(
59 &jsonway::object(|obj| {
60 obj.set("prop1", 0);
61 })
62 .unwrap()
63 )
64 .is_valid(),
65 false
66 );
67
68 assert_eq!(
69 schema
70 .validate(
71 &jsonway::object(|obj| {
72 obj.set("prop2", 0);
73 })
74 .unwrap()
75 )
76 .is_valid(),
77 false
78 );
79
80 assert_eq!(
81 schema
82 .validate(
83 &jsonway::object(|obj| {
84 obj.set("prop1", 0);
85 obj.set("prop2", 0);
86 })
87 .unwrap()
88 )
89 .is_valid(),
90 true
91 );
92}
93
94#[test]
95fn malformed() {
96 let mut scope = scope::Scope::new();
97
98 assert!(scope
99 .compile_and_return(
100 jsonway::object(|schema| {
101 schema.array("required", |required| required.push(1));
102 })
103 .unwrap(),
104 true
105 )
106 .is_err());
107}