expect_json/
expect_json_eq.rs

1use crate::ExpectJsonError;
2use crate::ExpectJsonResult;
3use crate::expect_core::Context;
4use crate::internals::json_eq;
5use serde::Serialize;
6
7pub fn expect_json_eq<R, E>(received_raw: &R, expected_raw: &E) -> ExpectJsonResult<()>
8where
9    R: Serialize,
10    E: Serialize,
11{
12    let received =
13        serde_json::to_value(received_raw).map_err(ExpectJsonError::FailedToSerialiseReceived)?;
14    let expected =
15        serde_json::to_value(expected_raw).map_err(ExpectJsonError::FailedToSerialiseExpected)?;
16
17    let mut context = Context::new();
18    json_eq(&mut context, &received, &expected)?;
19
20    Ok(())
21}
22
23#[cfg(test)]
24mod test_expect_json_eq {
25    use super::*;
26    use serde::ser::Error;
27    use serde_json::json;
28
29    struct FailingSerialize;
30    impl Serialize for FailingSerialize {
31        fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
32        where
33            S: serde::Serializer,
34        {
35            Err(S::Error::custom("testing"))
36        }
37    }
38
39    #[test]
40    fn it_should_return_correct_error_if_expect_fails_to_serialise() {
41        let received = json!(123);
42        let expected = FailingSerialize;
43        let error = expect_json_eq(&received, &expected).unwrap_err();
44        let error_dbg = format!("{error:?}");
45
46        // This funky debug oriented approach is to work around the test coverage in LLVM Cov.
47        // The problem is that testing code is included, and matches causes an explosion in variants.
48
49        // assert_matches!(error, ExpectJsonEqError::FailedToSerialiseExpected(..));
50        assert!(error_dbg.starts_with("FailedToSerialiseExpected("));
51    }
52
53    #[test]
54    fn it_should_return_correct_error_if_received_fails_to_serialise() {
55        let received = FailingSerialize;
56        let expected = json!(123);
57        let error = expect_json_eq(&received, &expected).unwrap_err();
58        let error_dbg = format!("{error:?}");
59
60        // assert_matches!(error, ExpectJsonEqError::FailedToSerialiseReceived(..));
61        assert!(error_dbg.starts_with("FailedToSerialiseReceived("));
62    }
63
64    #[test]
65    fn it_should_return_correct_error_if_json_eq_error() {
66        let received = json!(123);
67        let expected = json!("🦊");
68        let error = expect_json_eq(&received, &expected).unwrap_err();
69        let error_dbg = format!("{error:?}");
70
71        // assert_matches!(error, ExpectJsonError::DifferentTypes(..));
72        assert!(error_dbg.starts_with("DifferentTypes"));
73    }
74}