aws_smithy_runtime/test_util/
assertions.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6/// Asserts that a given string value `$str` contains a substring `$expected`.
7///
8/// This macro can also take a custom panic message with formatting.
9#[macro_export]
10macro_rules! assert_str_contains {
11    ($str:expr, $expected:expr) => {
12        assert_str_contains!($str, $expected, "")
13    };
14    ($str:expr, $expected:expr, $($fmt_args:tt)+) => {{
15        let s = $str;
16        let expected = $expected;
17        if !s.contains(&expected) {
18            panic!(
19                "assertion failed: `str.contains(expected)`\n{:>8}: {expected}\n{:>8}: {s}\n{}",
20                "expected",
21                "str",
22                ::std::fmt::format(::std::format_args!($($fmt_args)+)),
23            );
24        }
25    }};
26}
27
28#[cfg(test)]
29mod tests {
30    use std::panic::{catch_unwind, UnwindSafe};
31
32    fn expect_panic(f: impl FnOnce() + UnwindSafe) -> String {
33        *catch_unwind(f)
34            .expect_err("it should fail")
35            .downcast::<String>()
36            .expect("it should be a string")
37    }
38
39    #[test]
40    fn assert_str_contains() {
41        assert_str_contains!("foobar", "bar");
42        assert_str_contains!("foobar", "o");
43
44        assert_eq!(
45            "assertion failed: `str.contains(expected)`\nexpected: not-in-it\n     str: foobar\n",
46            expect_panic(|| assert_str_contains!("foobar", "not-in-it"))
47        );
48        assert_eq!(
49            "assertion failed: `str.contains(expected)`\nexpected: not-in-it\n     str: foobar\nsome custom message",
50            expect_panic(|| assert_str_contains!("foobar", "not-in-it", "some custom message"))
51        );
52        assert_eq!(
53            "assertion failed: `str.contains(expected)`\nexpected: not-in-it\n     str: foobar\nsome custom message with formatting",
54            expect_panic(|| assert_str_contains!("foobar", "not-in-it", "some custom message with {}", "formatting"))
55        );
56    }
57}