expect_json/expects/ops/contains/
string_contains.rs

1use 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;
8
9#[derive(Clone, Debug, Serialize, Deserialize)]
10pub struct StringContains {
11    content: String,
12}
13
14impl StringContains {
15    pub(crate) fn new(content: String) -> Self {
16        Self { content }
17    }
18}
19
20impl JsonExpectOp for StringContains {
21    fn on_string<'a>(self, context: &mut Context<'a>, received: &'a str) -> JsonValueEqResult<()> {
22        if !received.contains(&self.content) {
23            return Err(JsonValueEqError::StringContainsNotFound {
24                context: context.to_static(),
25                expected: self.content.into(),
26                received_full_string: received.to_owned().into(),
27            });
28        }
29
30        Ok(())
31    }
32}
33
34impl From<StringContains> for SerializeExpectOp {
35    fn from(contains: StringContains) -> Self {
36        SerializeExpectOp::StringContains(contains)
37    }
38}
39
40#[cfg(test)]
41mod test_string_contains {
42    use crate::expect;
43    use crate::expect_json_eq;
44    use pretty_assertions::assert_eq;
45    use serde_json::json;
46
47    #[test]
48    fn it_should_be_equal_for_identical_strings() {
49        let left = json!("1, 2, 3");
50        let right = json!(expect.contains("1, 2, 3"));
51
52        let output = expect_json_eq(&left, &right);
53        assert!(output.is_ok());
54    }
55
56    #[test]
57    fn it_should_be_equal_for_partial_matches_in_middle() {
58        let left = json!("0, 1, 2, 3, 4");
59        let right = json!(expect.contains("1, 2, 3"));
60
61        let output = expect_json_eq(&left, &right);
62        assert!(output.is_ok());
63    }
64
65    #[test]
66    fn it_should_be_equal_for_empty_match() {
67        let left = json!("0, 1, 2, 3, 4, 5");
68        let right = json!(expect.contains(""));
69
70        let output = expect_json_eq(&left, &right);
71        assert!(output.is_ok());
72    }
73
74    #[test]
75    fn it_should_error_for_totall_different_values() {
76        let left = json!("1, 2, 3");
77        let right = json!(expect.contains("a, b, c"));
78
79        let output = expect_json_eq(&left, &right).unwrap_err().to_string();
80        assert_eq!(
81            output,
82            r#"Json string at root does not contain expected value,
83    expected string to contain "a, b, c", but it was not found.
84    received "1, 2, 3""#
85        );
86    }
87}