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)] use super::super::scope;
34#[cfg(test)] use jsonway;
35#[cfg(test)] use super::super::builder;
36#[cfg(test)] use serde_json::to_value;
37
38#[test]
39fn validate() {
40 let mut scope = scope::Scope::new();
41 let schema = scope.compile_and_return(builder::schema(|s| {
42 s.multiple_of(3.5f64);
43 }).into_json(), true).ok().unwrap();
44
45 assert_eq!(schema.validate(&to_value(&"").unwrap()).is_valid(), true);
46 assert_eq!(schema.validate(&to_value(&7).unwrap()).is_valid(), true);
47 assert_eq!(schema.validate(&to_value(&6).unwrap()).is_valid(), false);
48}
49
50#[test]
51fn malformed() {
52 let mut scope = scope::Scope::new();
53
54 assert!(scope.compile_and_return(jsonway::object(|schema| {
55 schema.set("multipleOf", "".to_string());
56 }).unwrap(), true).is_err());
57
58 assert!(scope.compile_and_return(jsonway::object(|schema| {
59 schema.set("multipleOf", to_value(&0).unwrap());
60 }).unwrap(), true).is_err());
61
62 assert!(scope.compile_and_return(jsonway::object(|schema| {
63 schema.set("multipleOf", to_value(&-1).unwrap());
64 }).unwrap(), true).is_err());
65}