Skip to main content

nu_test_support/
assertions.rs

1use nu_utils::container::Container;
2use std::{borrow::Borrow, fmt::Debug};
3
4/// Assert that a haystack contains the given needle.
5///
6/// Uses the [`Container`] abstraction so it works with slices, vectors, sets,
7/// maps (by key), strings, and ranges.
8/// The error message includes both the container and the item for quick debugging.
9///
10/// # Panics
11///
12/// Panics if `haystack.contains(needle)` returns false.
13#[track_caller]
14pub fn assert_contains<H, N>(needle: N, haystack: H)
15where
16    H: Container + Debug,
17    N: Borrow<H::Item>,
18    H::Item: Debug,
19{
20    let item = needle.borrow();
21
22    assert!(
23        haystack.contains(item),
24        "{haystack:?} does not contain {item:?}"
25    );
26}
27
28/// Assert that a haystack does not contain the given needle.
29///
30/// Uses the [`Container`] abstraction so it works with slices, vectors, sets,
31/// maps (by key), strings, and ranges.
32/// The error message includes both the container and the item for quick debugging.
33///
34/// # Panics
35///
36/// Panics if `haystack.contains(needle)` returns true.
37#[track_caller]
38pub fn assert_contains_not<H, N>(needle: N, haystack: H)
39where
40    H: Container + Debug,
41    N: Borrow<H::Item>,
42    H::Item: Debug,
43{
44    let item = needle.borrow();
45
46    assert!(!haystack.contains(item), "{haystack:?} contains {item:?}");
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    #[expect(clippy::needless_borrows_for_generic_args)]
55    fn test_something() {
56        assert_contains(1, [1, 2, 3]);
57        assert_contains(2, &[1, 2, 3]);
58        assert_contains("a", "abc");
59        assert_contains("b", String::from("abc"));
60        assert_contains(String::from("b"), String::from("abc"));
61        assert_contains("c", &String::from("abc"));
62        assert_contains(2, vec![1, 2, 3]);
63        assert_contains(1, &vec![1, 2, 3]);
64    }
65
66    #[test]
67    #[expect(clippy::needless_borrows_for_generic_args)]
68    fn test_contains_not() {
69        assert_contains_not(4, [1, 2, 3]);
70        assert_contains_not(4, &[1, 2, 3]);
71        assert_contains_not("d", "abc");
72        assert_contains_not("d", String::from("abc"));
73        assert_contains_not(String::from("d"), String::from("abc"));
74        assert_contains_not("d", &String::from("abc"));
75        assert_contains_not(4, vec![1, 2, 3]);
76        assert_contains_not(4, &vec![1, 2, 3]);
77    }
78}