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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
pub(crate) mod context;
pub(crate) mod options;
use crate::{
error::ErrorIterator, keywords, keywords::Validators, paths::InstancePath, resolver::Resolver,
ValidationError,
};
use context::CompilationContext;
use options::CompilationOptions;
use serde_json::Value;
use url::Url;
pub(crate) const DEFAULT_ROOT_URL: &str = "json-schema:///";
#[derive(Debug)]
pub struct JSONSchema<'a> {
pub(crate) schema: &'a Value,
pub(crate) validators: Validators,
pub(crate) resolver: Resolver<'a>,
pub(crate) context: CompilationContext<'a>,
}
lazy_static::lazy_static! {
pub static ref DEFAULT_SCOPE: Url = url::Url::parse(DEFAULT_ROOT_URL).expect("Is a valid URL");
}
impl<'a> JSONSchema<'a> {
#[must_use]
pub fn options() -> CompilationOptions {
CompilationOptions::default()
}
pub fn compile(schema: &'a Value) -> Result<JSONSchema<'a>, ValidationError<'a>> {
Self::options().compile(schema)
}
#[inline]
pub fn validate(&'a self, instance: &'a Value) -> Result<(), ErrorIterator<'a>> {
let mut errors = self
.validators
.iter()
.flat_map(move |validator| validator.validate(self, instance, &InstancePath::new()))
.peekable();
if errors.peek().is_none() {
Ok(())
} else {
Err(Box::new(errors))
}
}
#[must_use]
#[inline]
pub fn is_valid(&self, instance: &Value) -> bool {
self.validators
.iter()
.all(|validator| validator.is_valid(self, instance))
}
}
#[inline]
pub(crate) fn compile_validators<'a, 'c>(
schema: &'a Value,
context: &'c CompilationContext,
) -> Result<Validators, ValidationError<'a>> {
let context = context.push(schema)?;
match schema {
Value::Bool(value) => match value {
true => Ok(vec![]),
false => Ok(vec![keywords::boolean::FalseValidator::compile(
context.into_pointer(),
)
.expect("Should always compile")]),
},
Value::Object(object) => {
if let Some(reference) = object.get("$ref") {
if let Value::String(reference) = reference {
Ok(vec![keywords::ref_::compile(schema, reference, &context)
.expect("Should always return Some")?])
} else {
Err(ValidationError::schema(schema))
}
} else {
let mut validators = Vec::with_capacity(object.len());
for (keyword, subschema) in object {
if let Some(compilation_func) = context.config.draft().get_validator(keyword) {
if let Some(validator) = compilation_func(object, subschema, &context) {
validators.push(validator?)
}
}
}
Ok(validators)
}
}
_ => Err(ValidationError::schema(schema)),
}
}
#[cfg(test)]
mod tests {
use super::JSONSchema;
use crate::{error::ValidationError, schemas};
use serde_json::{from_str, json, Value};
use std::{borrow::Cow, fs::File, io::Read, path::Path};
use url::Url;
fn load(path: &str, idx: usize) -> Value {
let path = Path::new(path);
let mut file = File::open(&path).unwrap();
let mut content = String::new();
file.read_to_string(&mut content).ok().unwrap();
let data: Value = from_str(&content).unwrap();
let case = &data.as_array().unwrap()[idx];
case.get("schema").unwrap().clone()
}
#[test]
fn only_keyword() {
let schema = json!({"type": "string"});
let compiled = JSONSchema::compile(&schema).unwrap();
let value1 = json!("AB");
let value2 = json!(1);
assert_eq!(compiled.validators.len(), 1);
assert!(compiled.validate(&value1).is_ok());
assert!(compiled.validate(&value2).is_err());
}
#[test]
fn resolve_ref() {
let schema = load("tests/suite/tests/draft7/ref.json", 4);
let compiled = JSONSchema::compile(&schema).unwrap();
let url = Url::parse("json-schema:///#/definitions/a").unwrap();
if let (resource, Cow::Borrowed(resolved)) = compiled
.resolver
.resolve_fragment(schemas::Draft::Draft7, &url, &schema)
.unwrap()
{
assert_eq!(resource, Url::parse("json-schema:///").unwrap());
assert_eq!(resolved, schema.pointer("/definitions/a").unwrap());
}
}
#[test]
fn validate_ref() {
let schema = load("tests/suite/tests/draft7/ref.json", 1);
let value = json!({"bar": 3});
let compiled = JSONSchema::compile(&schema).unwrap();
assert!(compiled.validate(&value).is_ok());
let value = json!({"bar": true});
assert!(compiled.validate(&value).is_err());
}
#[test]
fn wrong_schema_type() {
let schema = json!([1]);
let compiled = JSONSchema::compile(&schema);
assert!(compiled.is_err());
}
#[test]
fn multiple_errors() {
let schema = json!({"minProperties": 2, "propertyNames": {"minLength": 3}});
let value = json!({"a": 3});
let compiled = JSONSchema::compile(&schema).unwrap();
let result = compiled.validate(&value);
let errors: Vec<ValidationError> = result.unwrap_err().collect();
assert_eq!(errors.len(), 2);
assert_eq!(
errors[0].to_string(),
r#"{"a":3} has less than 2 properties"#
);
assert_eq!(errors[1].to_string(), r#""a" is shorter than 3 characters"#);
}
}