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