valico/json_schema/keywords/
conditional.rs1use serde_json::Value;
2
3use super::super::helpers;
4use super::super::schema;
5use super::super::validators;
6
7#[allow(missing_copy_implementations)]
8pub struct Conditional;
9impl super::Keyword for Conditional {
10 fn compile(&self, def: &Value, ctx: &schema::WalkContext<'_>) -> super::KeywordResult {
11 let maybe_if = def.get("if");
12 let maybe_then = def.get("then");
13 let maybe_else = def.get("else");
14
15 if maybe_if.is_none() {
16 Ok(None)
17 } else {
18 let if_ = helpers::alter_fragment_path(
19 ctx.url.clone(),
20 [ctx.escaped_fragment().as_ref(), "if"].join("/"),
21 );
22 let then_ = maybe_then.map(|_| {
23 helpers::alter_fragment_path(
24 ctx.url.clone(),
25 [ctx.escaped_fragment().as_ref(), "then"].join("/"),
26 )
27 });
28 let else_ = maybe_else.map(|_| {
29 helpers::alter_fragment_path(
30 ctx.url.clone(),
31 [ctx.escaped_fragment().as_ref(), "else"].join("/"),
32 )
33 });
34 Ok(Some(Box::new(validators::Conditional {
35 if_,
36 then_,
37 else_,
38 })))
39 }
40 }
41}
42
43#[cfg(test)]
44use super::super::builder;
45#[cfg(test)]
46use super::super::scope;
47#[cfg(test)]
48use serde_json::to_value;
49
50#[test]
51fn validate_if_then() {
52 let mut scope = scope::Scope::new();
53 let schema = scope.compile_and_return(
54 builder::schema(|s| {
55 s.if_(|if_| {
56 if_.minimum(5f64);
57 });
58 s.then_(|then_| {
59 then_.minimum(5f64);
60 then_.maximum(10f64);
61 });
62 })
63 .into_json(),
64 true,
65 );
66
67 assert!(schema.is_ok(), "{}", schema.err().unwrap().to_string());
68
69 let s = schema.unwrap();
70 assert_eq!(s.validate(&to_value(3).unwrap()).is_valid(), true);
71 assert_eq!(s.validate(&to_value(15).unwrap()).is_valid(), false);
72}
73
74#[test]
75fn validate_if_then_else() {
76 let mut scope = scope::Scope::new();
77 let schema = scope.compile_and_return(
78 builder::schema(|s| {
79 s.if_(|if_| {
80 if_.minimum(5f64);
81 });
82 s.then_(|then_| {
83 then_.minimum(5f64);
84 then_.maximum(10f64);
85 });
86 s.else_(|else_| {
87 else_.minimum(1f64);
88 else_.maximum(4f64);
89 });
90 })
91 .into_json(),
92 true,
93 );
94
95 assert!(schema.is_ok(), "{}", schema.err().unwrap().to_string());
96
97 let s = schema.unwrap();
98 assert_eq!(s.validate(&to_value(3).unwrap()).is_valid(), true);
99 assert_eq!(s.validate(&to_value(0).unwrap()).is_valid(), false);
100}