Validator

Trait Validator 

Source
pub trait Validator {
    // Required method
    fn validate<'a>(&self, value: &'a Value) -> Result<(), Error<'a>>;

    // Provided method
    fn and<T>(self, validator: T) -> And<Self, T>
       where Self: Sized,
             T: Validator { ... }
}
Expand description

Abstract the validation action for assert_json! macro.

Any custom validation rule can be easily use in the macro by implementing the Validator::validate method.

use assert_json::{assert_json, Error, Validator, Value};

fn optional_string(expected: Option<String>) -> impl Validator {
    OptionalStringValidator { expected }
}

/// Matches a null JSON value if expected is None, else check if the strings
/// are equals
struct OptionalStringValidator {
    expected: Option<String>,
}

impl Validator for OptionalStringValidator {
    fn validate<'a>(&self, value: &'a Value) -> Result<(), Error<'a>> {
        if let Some(expected_str) = &self.expected {
            let string_value = value
                .as_str()
                .ok_or_else(|| Error::InvalidType(value, String::from("string")))?;

            if expected_str == string_value {
                Ok(())
            } else {
                Err(Error::InvalidValue(value, expected_str.clone()))
            }
        } else {
            value.as_null()
                .ok_or_else(|| Error::InvalidType(value, String::from("null")))
        }
    }
}

let json = r#"
    {
        "key": "value",
        "none": null
    }
"#;
assert_json!(json, {
    "key": optional_string(Some(String::from("value"))),
    "none": optional_string(None),
});

Required Methods§

Source

fn validate<'a>(&self, value: &'a Value) -> Result<(), Error<'a>>

Provided Methods§

Source

fn and<T>(self, validator: T) -> And<Self, T>
where Self: Sized, T: Validator,

Implementors§