expect_json/expects/ops/contains/
string_contains.rs

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