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#[cfg(test)]
29mod tests {
30    use super::*;
31
32    #[test]
33    #[expect(clippy::needless_borrows_for_generic_args)]
34    fn test_something() {
35        assert_contains(1, [1, 2, 3]);
36        assert_contains(2, &[1, 2, 3]);
37        assert_contains("a", "abc");
38        assert_contains("b", String::from("abc"));
39        assert_contains(String::from("b"), String::from("abc"));
40        assert_contains("c", &String::from("abc"));
41        assert_contains(2, vec![1, 2, 3]);
42        assert_contains(1, &vec![1, 2, 3]);
43    }
44}