expect_json/expects/
serialize_expect.rs1use crate::expects::ExpectMagicId;
2use crate::expects::SerializeExpectOp;
3use serde::Deserialize;
4use serde::Serialize;
5use serde_json::Value;
6
7#[derive(Clone, Debug, Serialize, Deserialize)]
8pub struct SerializeExpect {
9 pub magic_id: ExpectMagicId,
10 pub inner: SerializeExpectOp,
11}
12
13impl SerializeExpect {
14 pub fn new(inner: SerializeExpectOp) -> Self {
15 Self {
16 magic_id: ExpectMagicId::__ExpectJson_MagicId_0ABDBD14_93D1_4D73_8E26_0177D8A280A4__,
17 inner,
18 }
19 }
20
21 pub fn maybe_parse(value: &Value) -> Option<Self> {
22 if !Self::has_magic_id(value) {
23 return None;
24 }
25
26 let obj = serde_json::from_value::<Self>(value.clone())
27 .expect("Failed to decode internal expect structure from Json");
28 Some(obj)
29 }
30}
31
32impl SerializeExpect {
33 pub fn has_magic_id(value: &Value) -> bool {
34 value
35 .as_object()
36 .and_then(|obj| obj.get_key_value("magic_id"))
37 .map(|(_, maybe_value_str)| ExpectMagicId::is_magic_id_value(maybe_value_str))
38 .unwrap_or_default()
39 }
40}
41
42impl<S> From<S> for SerializeExpect
43where
44 SerializeExpectOp: From<S>,
45{
46 fn from(inner: S) -> Self {
47 Self {
48 magic_id: Default::default(),
49 inner: SerializeExpectOp::from(inner),
50 }
51 }
52}
53
54#[cfg(test)]
55mod test_serialize {
56 use crate::expect;
57 use assert_json_diff::assert_json_eq;
58 use serde_json::json;
59
60 #[test]
61 fn it_should_serialize_into_expected_structure_with_magic_id() {
62 let output = json!(expect.contains([1, 2, 3]));
63 let expected = json!({
64 "magic_id": "__ExpectJson_MagicId_0ABDBD14_93D1_4D73_8E26_0177D8A280A4__",
65 "inner": {
66 "type": "ArrayContains",
67 "values": [1, 2, 3],
68 },
69 });
70
71 assert_json_eq!(output, expected);
72 }
73}