json_test/matchers/
mod.rs

1mod regex;
2mod type_matcher;
3mod value;
4
5pub use regex::RegexMatcher;
6pub use type_matcher::TypeMatcher;
7pub use value::ValueMatcher;
8
9use serde_json::Value;
10use std::fmt::Debug;
11
12/// Core trait for implementing JSON value matchers.
13///
14/// This trait allows creation of custom matchers for flexible value validation.
15/// Implementors must provide both matching logic and a description of the matcher.
16///
17/// # Examples
18///
19/// ```rust
20/// use json_test::JsonMatcher;
21/// use serde_json::Value;
22///
23/// #[derive(Debug)]
24/// struct DateMatcher;
25///
26/// impl JsonMatcher for DateMatcher {
27///     fn matches(&self, value: &Value) -> bool {
28///         value.as_str()
29///             .map(|s| s.contains("-"))
30///             .unwrap_or(false)
31///     }
32///
33///     fn description(&self) -> String {
34///         "is a date string".to_string()
35///     }
36/// }
37/// ```
38pub trait JsonMatcher: Debug {
39    /// Tests if a JSON value matches this matcher's criteria.
40    ///
41    /// # Arguments
42    ///
43    /// * `value` - The JSON value to test
44    ///
45    /// # Returns
46    ///
47    /// Returns `true` if the value matches the criteria, `false` otherwise.
48    fn matches(&self, value: &Value) -> bool;
49
50    /// Returns a human-readable description of the matcher's criteria.
51    ///
52    /// This description is used in error messages when assertions fail.
53    fn description(&self) -> String;
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59    use serde_json::json;
60
61    /// Simple test matcher implementation
62    #[derive(Debug)]
63    struct TestMatcher(bool);
64
65    impl JsonMatcher for TestMatcher {
66        fn matches(&self, _: &Value) -> bool {
67            self.0
68        }
69
70        fn description(&self) -> String {
71            format!("always returns {}", self.0)
72        }
73    }
74
75    #[test]
76    fn test_matcher_trait() {
77        let value = json!(42);
78
79        let true_matcher = TestMatcher(true);
80        assert!(true_matcher.matches(&value));
81        assert_eq!(true_matcher.description(), "always returns true");
82
83        let false_matcher = TestMatcher(false);
84        assert!(!false_matcher.matches(&value));
85    }
86}