json_matcher/matchers/
boolean.rs1use serde_json::Value;
2
3use crate::{JsonMatcher, JsonMatcherError};
4
5pub enum BooleanMatcher {
6 Exact(bool),
7 Any,
8}
9
10impl BooleanMatcher {
11 pub fn exact(value: bool) -> Self {
12 Self::Exact(value)
13 }
14
15 pub fn any() -> Self {
16 Self::Any
17 }
18}
19
20impl JsonMatcher for BooleanMatcher {
21 fn json_matches(&self, value: &Value) -> Vec<JsonMatcherError> {
22 match value {
23 Value::Bool(actual) => match self {
24 BooleanMatcher::Exact(expected) => {
25 if *actual != *expected {
26 vec![JsonMatcherError::at_root(format!(
27 "Value is not {}",
28 expected
29 ))]
30 } else {
31 vec![]
32 }
33 }
34 BooleanMatcher::Any => vec![],
35 },
36 _ => vec![JsonMatcherError::at_root("Value is not a boolean")],
37 }
38 }
39}
40
41impl JsonMatcher for bool {
42 fn json_matches(&self, value: &Value) -> Vec<JsonMatcherError> {
43 BooleanMatcher::exact(*self).json_matches(value)
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use crate::assert_jm;
50 use crate::test::catch_string_panic;
51
52 use super::*;
53
54 #[test]
55 fn test_boolean_matcher() {
56 let get_matcher = || BooleanMatcher::exact(true);
57 assert_jm!(Value::Bool(true), get_matcher());
58 assert_eq!(
60 catch_string_panic(|| assert_jm!(Value::String("bloop".to_string()), get_matcher())),
61 r#"
62Json matcher failed:
63 - $: Value is not a boolean
64
65Actual:
66"bloop""#
67 );
68 assert_eq!(
70 catch_string_panic(|| assert_jm!(Value::Bool(false), get_matcher())),
71 r#"
72Json matcher failed:
73 - $: Value is not true
74
75Actual:
76false"#
77 );
78 }
79
80 #[test]
81 fn test_raw_implementations() {
82 assert_eq!(true.json_matches(&Value::Bool(true)), vec![]);
83 assert_eq!(
84 true.json_matches(&Value::Bool(false))
85 .into_iter()
86 .map(|x| x.to_string())
87 .collect::<String>(),
88 "$: Value is not true"
89 );
90 }
91}