use crate::draft::Draft;
use crate::error::{ErrorIterator, ValidationError};
use crate::node::SchemaNode;
use crate::paths::LazyLocation;
use serde_json::Value;
pub struct Validator {
root: SchemaNode,
draft: Draft,
}
impl Validator {
#[allow(dead_code)]
pub(crate) fn new(root: SchemaNode, draft: Draft) -> Self {
Self { root, draft }
}
#[must_use]
pub fn is_valid(&self, instance: &Value) -> bool {
let mut ctx = crate::keywords::ValidationContext::new();
self.root.is_valid(instance, &mut ctx)
}
pub fn validate(&self, instance: &Value) -> Result<(), ValidationError> {
let mut ctx = crate::keywords::ValidationContext::new();
let path = LazyLocation::new();
self.root.validate(instance, &path, &mut ctx)
}
#[must_use]
pub fn iter_errors(&self, instance: &Value) -> ErrorIterator {
let mut ctx = crate::keywords::ValidationContext::new();
let path = LazyLocation::new();
self.root.iter_errors(instance, &path, &mut ctx)
}
#[must_use]
pub fn draft(&self) -> Draft {
self.draft
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::draft::Draft;
use crate::node::SchemaNode;
use serde_json::json;
#[test]
fn always_valid() {
let v = Validator::new(SchemaNode::AlwaysValid, Draft::Draft7);
assert!(v.is_valid(&json!("anything")));
}
#[test]
fn always_invalid() {
let v = Validator::new(
SchemaNode::AlwaysInvalid {
schema_path: crate::paths::Location::new(),
},
Draft::Draft7,
);
assert!(!v.is_valid(&json!("anything")));
}
#[test]
fn draft_returns_correct() {
let v = Validator::new(SchemaNode::AlwaysValid, Draft::Draft202012);
assert_eq!(v.draft(), Draft::Draft202012);
}
}