expect_json/expects/ops/contains/
array_contains.rs1use crate::expects::SerializeExpectOp;
2use crate::internals::Context;
3use crate::internals::JsonExpectOp;
4use crate::internals::JsonValueEqError;
5use crate::internals::JsonValueEqResult;
6use serde::Deserialize;
7use serde::Serialize;
8use serde_json::Value;
9use std::collections::HashSet;
10
11#[derive(Clone, Debug, Serialize, Deserialize)]
12pub struct ArrayContains {
13 values: Vec<Value>,
14}
15
16impl ArrayContains {
17 pub(crate) fn new(values: Vec<Value>) -> Self {
18 Self { values }
19 }
20}
21
22impl JsonExpectOp for ArrayContains {
23 fn on_array<'a>(
24 self,
25 context: &mut Context<'a>,
26 received_values: &'a [Value],
27 ) -> JsonValueEqResult<()> {
28 let received_items_in_set = received_values.iter().collect::<HashSet<&'a Value>>();
29
30 for expected in self.values {
31 if !received_items_in_set.contains(&expected) {
32 return Err(JsonValueEqError::ArrayContainsNotFound {
33 context: context.to_static(),
34 expected: expected.into(),
35 received_full_array: received_values.to_owned().into(),
36 });
37 }
38 }
39
40 Ok(())
41 }
42}
43
44impl From<ArrayContains> for SerializeExpectOp {
45 fn from(contains: ArrayContains) -> Self {
46 SerializeExpectOp::ArrayContains(contains)
47 }
48}
49
50#[cfg(test)]
51mod test_array_contains {
52 use crate::expect;
53 use crate::expect_json_eq;
54 use pretty_assertions::assert_eq;
55 use serde_json::json;
56
57 #[test]
58 fn it_should_be_equal_for_identical_numeric_arrays() {
59 let left = json!([1, 2, 3]);
60 let right = json!(expect.contains([1, 2, 3]));
61
62 let output = expect_json_eq(&left, &right);
63 assert!(output.is_ok());
64 }
65
66 #[test]
67 fn it_should_be_equal_for_reversed_identical_numeric_arrays() {
68 let left = json!([1, 2, 3]);
69 let right = json!(expect.contains([3, 2, 1]));
70
71 let output = expect_json_eq(&left, &right);
72 assert!(output.is_ok());
73 }
74
75 #[test]
76 fn it_should_be_equal_for_partial_contains() {
77 let left = json!([0, 1, 2, 3, 4, 5]);
78 let right = json!(expect.contains([1, 2, 3]));
79
80 let output = expect_json_eq(&left, &right);
81 assert!(output.is_ok());
82 }
83
84 #[test]
85 fn it_should_error_for_totall_different_values() {
86 let left = json!([0, 1, 2, 3]);
87 let right = json!(expect.contains([4, 5, 6]));
88
89 let output = expect_json_eq(&left, &right).unwrap_err().to_string();
90 assert_eq!(
91 output,
92 r#"Json array at root does not contain expected value,
93 expected array to contain the integer 4, but it was not found.
94 received [0, 1, 2, 3]"#
95 );
96 }
97}