1use jsonschema::JSONSchema;
4use serde_json::Value;
5
6use crate::error::WirdigenError;
7use crate::schema::JSON_SCHEMA;
8
9pub struct Validator {
10 schema_value: JSONSchema,
11}
12
13impl Validator {
14 pub fn new() -> Result<Validator, WirdigenError> {
16 let json_schema: Value = serde_json::from_str(JSON_SCHEMA)?;
17
18 let data = Self::compile_schema(json_schema)?;
19 Ok(Validator { schema_value: data })
20 }
21
22 pub fn validate(self, json_raw: &Value) -> bool {
24 match self.schema_value.validate(json_raw) {
25 Err(errors) => {
26 for err in errors {
27 eprintln!("{:#?}", err);
28 }
29 false
30 }
31 Ok(_) => true,
32 }
33 }
34}
35
36impl Validator {
37 fn compile_schema(value: Value) -> Result<JSONSchema, WirdigenError> {
38 match JSONSchema::compile(&value) {
39 Err(e) => Err(WirdigenError::JSONSchemaCompilation(e.to_string())),
40 Ok(data) => Ok(data),
41 }
42 }
43}
44
45#[cfg(test)]
46mod unit_test {
47 use super::*;
48
49 use std::fs::File;
50 use std::io::BufReader;
51
52 #[test]
53 fn validator_new() -> Result<(), WirdigenError> {
54 let _ = Validator::new()?;
55 Ok(())
56 }
57
58 #[test]
59 fn validator_compile_schema_valid() -> Result<(), WirdigenError> {
60 let valid_schema = r#"
61 {
62 "properties" : {
63 "test": {
64 "type": "string"
65 }
66 }
67 }"#;
68
69 let value = serde_json::from_str(valid_schema)?;
70
71 if let Err(_) = Validator::compile_schema(value) {
72 panic!("The schema should have compiled")
73 }
74 Ok(())
75 }
76
77 #[test]
78 fn validator_compile_schema_invalid() -> Result<(), WirdigenError> {
79 let invalid_schema = r#"
81 {
82 "properties" : {
83 "test": {
84 "type": "any"
85 }
86 }
87 }"#;
88
89 let value = serde_json::from_str(invalid_schema)?;
90
91 if let Ok(_) = Validator::compile_schema(value) {
92 panic!("The schema should not have compiled")
93 }
94 Ok(())
95 }
96
97 #[test]
98 fn validator_validate_true() -> Result<(), WirdigenError> {
99 let file = File::open("./example/example_dissector.json")?;
100 let rdr = BufReader::new(file);
101 let value: Value = serde_json::from_reader(rdr)?;
102 let mgr = Validator::new()?;
103
104 assert_eq!(mgr.validate(&value), true);
105 Ok(())
106 }
107
108 #[test]
109 fn validator_validate_false() -> Result<(), WirdigenError> {
110 let json_raw = r#"
112 {
113 }"#;
114
115 let value = serde_json::from_str(json_raw)?;
116
117 let mgr = Validator::new()?;
118
119 assert_eq!(mgr.validate(&value), false);
120 Ok(())
121 }
122}