json_test/matchers/
type_matcher.rs1use super::JsonMatcher;
2use serde_json::Value;
3
4#[derive(Debug)]
5pub struct TypeMatcher {
6 expected_type: &'static str,
7}
8
9impl TypeMatcher {
10 pub fn new(expected_type: &'static str) -> Self {
11 Self { expected_type }
12 }
13
14 pub fn string() -> Self {
16 Self::new("string")
17 }
18
19 pub fn number() -> Self {
20 Self::new("number")
21 }
22
23 pub fn boolean() -> Self {
24 Self::new("boolean")
25 }
26
27 pub fn array() -> Self {
28 Self::new("array")
29 }
30
31 pub fn object() -> Self {
32 Self::new("object")
33 }
34
35 pub fn null() -> Self {
36 Self::new("null")
37 }
38}
39
40impl JsonMatcher for TypeMatcher {
41 fn matches(&self, value: &Value) -> bool {
42 match (self.expected_type, value) {
43 ("string", Value::String(_)) => true,
44 ("number", Value::Number(_)) => true,
45 ("boolean", Value::Bool(_)) => true,
46 ("null", Value::Null) => true,
47 ("array", Value::Array(_)) => true,
48 ("object", Value::Object(_)) => true,
49 _ => false,
50 }
51 }
52
53 fn description(&self) -> String {
54 format!("is of type {}", self.expected_type)
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61 use serde_json::json;
62
63 #[test]
64 fn test_type_matching() {
65 assert!(TypeMatcher::string().matches(&json!("test")));
67 assert!(!TypeMatcher::string().matches(&json!(42)));
68
69 assert!(TypeMatcher::number().matches(&json!(42)));
71 assert!(TypeMatcher::number().matches(&json!(42.5)));
72 assert!(!TypeMatcher::number().matches(&json!("42")));
73
74 assert!(TypeMatcher::boolean().matches(&json!(true)));
76 assert!(!TypeMatcher::boolean().matches(&json!(1)));
77
78 assert!(TypeMatcher::array().matches(&json!([1, 2, 3])));
80 assert!(!TypeMatcher::array().matches(&json!({"key": "value"})));
81
82 assert!(TypeMatcher::object().matches(&json!({"key": "value"})));
84 assert!(!TypeMatcher::object().matches(&json!([1, 2, 3])));
85
86 assert!(TypeMatcher::null().matches(&json!(null)));
88 assert!(!TypeMatcher::null().matches(&json!(42)));
89 }
90
91 #[test]
92 fn test_descriptions() {
93 assert_eq!(TypeMatcher::string().description(), "is of type string");
94 assert_eq!(TypeMatcher::number().description(), "is of type number");
95 }
96}