valico/json_schema/keywords/
ref_.rs
1use serde_json::{Value};
2use url::{Url};
3
4use super::super::schema;
5use super::super::validators;
6
7#[allow(missing_copy_implementations)]
8pub struct Ref;
9impl super::Keyword for Ref {
10 fn compile(&self, def: &Value, ctx: &schema::WalkContext) -> super::KeywordResult {
11 let ref_ = keyword_key_exists!(def, "$ref");
12
13 if ref_.is_string() {
14 let url = Url::options().base_url(Some(ctx.url)).parse(ref_.as_str().unwrap());
15 match url {
16 Ok(url) => {
17 Ok(Some(Box::new(validators::Ref {
18 url: url
19 })))
20 },
21 Err(_) => {
22 Err(schema::SchemaError::Malformed {
23 path: ctx.fragment.join("/"),
24 detail: "The value of $ref MUST be an URI-encoded JSON Pointer".to_string()
25 })
26 }
27 }
28 } else {
29 Err(schema::SchemaError::Malformed {
30 path: ctx.fragment.join("/"),
31 detail: "The value of multipleOf MUST be a string".to_string()
32 })
33 }
34 }
35
36 fn is_exclusive(&self) -> bool {
37 true
38 }
39}
40
41#[cfg(test)] use super::super::scope;
42#[cfg(test)] use super::super::builder;
43#[cfg(test)] use serde_json::to_value;
44
45#[test]
46fn validate() {
47 let mut scope = scope::Scope::new();
48 let schema = scope.compile_and_return(builder::schema(|s| {
49 s.array();
50 s.max_items(2u64);
51 s.items_schema(|items| {
52 items.ref_("#");
53 })
54 }).into_json(), true).ok().unwrap();
55
56 let array: Vec<String> = vec![];
57 let array2: Vec<Vec<String>> = vec![vec![], vec![]];
58 let array3: Vec<Vec<String>> = vec![vec![], vec![], vec![]];
59
60 assert_eq!(schema.validate(&to_value(&array).unwrap()).is_valid(), true);
61 assert_eq!(schema.validate(&to_value(&array2).unwrap()).is_valid(), true);
62
63 assert_eq!(schema.validate(&to_value(&array3).unwrap()).is_valid(), false);
64 assert_eq!(schema.validate(&to_value(&vec![1,2]).unwrap()).is_valid(), false);
65}