Skip to main content

valico/json_schema/keywords/
multiple_of.rs

1use serde_json::Value;
2
3use super::super::schema;
4use super::super::validators;
5
6#[allow(missing_copy_implementations)]
7pub struct MultipleOf;
8impl super::Keyword for MultipleOf {
9    fn compile(&self, def: &Value, ctx: &schema::WalkContext<'_>) -> super::KeywordResult {
10        let multiple_of = keyword_key_exists!(def, "multipleOf");
11
12        if multiple_of.is_number() {
13            let multiple_of = multiple_of.as_f64().unwrap();
14            if multiple_of > 0f64 {
15                Ok(Some(Box::new(validators::MultipleOf {
16                    number: multiple_of,
17                })))
18            } else {
19                Err(schema::SchemaError::Malformed {
20                    path: ctx.fragment.join("/"),
21                    detail: "The value of multipleOf MUST be strictly greater than 0".to_string(),
22                })
23            }
24        } else {
25            Err(schema::SchemaError::Malformed {
26                path: ctx.fragment.join("/"),
27                detail: "The value of multipleOf MUST be a JSON number".to_string(),
28            })
29        }
30    }
31}
32
33#[cfg(test)]
34use super::super::builder;
35#[cfg(test)]
36use super::super::scope;
37#[cfg(test)]
38use serde_json::to_value;
39
40#[test]
41fn validate() {
42    let mut scope = scope::Scope::new();
43    let schema = scope
44        .compile_and_return(
45            builder::schema(|s| {
46                s.multiple_of(3.5f64);
47            })
48            .into_json(),
49            true,
50        )
51        .ok()
52        .unwrap();
53
54    assert_eq!(schema.validate(&to_value("").unwrap()).is_valid(), true);
55    assert_eq!(schema.validate(&to_value(7).unwrap()).is_valid(), true);
56    assert_eq!(schema.validate(&to_value(6).unwrap()).is_valid(), false);
57}
58
59#[test]
60fn malformed() {
61    let mut scope = scope::Scope::new();
62
63    assert!(scope
64        .compile_and_return(
65            jsonway::object(|schema| {
66                schema.set("multipleOf", "".to_string());
67            })
68            .unwrap(),
69            true
70        )
71        .is_err());
72
73    assert!(scope
74        .compile_and_return(
75            jsonway::object(|schema| {
76                schema.set("multipleOf", to_value(0).unwrap());
77            })
78            .unwrap(),
79            true
80        )
81        .is_err());
82
83    assert!(scope
84        .compile_and_return(
85            jsonway::object(|schema| {
86                schema.set("multipleOf", to_value(-1).unwrap());
87            })
88            .unwrap(),
89            true
90        )
91        .is_err());
92}