macro_rules! contains_each {
    ($(,)?) => { ... };
    ($(($key_matcher:expr, $value_matcher:expr)),* $(,)?) => { ... };
    ($($matcher:expr),* $(,)?) => { ... };
}
Expand description

Matches a container containing elements matched by the given matchers.

To match, each given matcher must have a corresponding element in the container which it matches. There must be a mapping uniquely matching each matcher to a container element. The container can, however, contain additional elements that don’t correspond to any matcher.

Put another way, contains_each! matches if there is a subset of the actual container which unordered_elements_are would match.

verify_that!(vec![3, 2, 1], contains_each![eq(2), ge(3)])?;   // Passes
verify_that!(vec![3, 2, 1], contains_each![ge(2), ge(2)])?;   // Passes
verify_that!(vec![1], contains_each![eq(1), ge(2)])?;         // Fails: container too small
verify_that!(vec![3, 2, 1], contains_each![eq(1), ge(4)])?;   // Fails: second matcher unmatched
verify_that!(vec![3, 2, 1], contains_each![ge(3), ge(3), ge(3)])?; // Fails: no matching

The actual value must be a container such as a Vec, an array, or a dereferenced slice. More precisely, a shared borrow of the actual value must implement IntoIterator.

This can also match against HashMap and similar collections. The arguments are a sequence of pairs of matchers corresponding to the keys and their respective values.

let value: HashMap<u32, &'static str> =
    HashMap::from_iter([(1, "One"), (2, "Two"), (3, "Three")]);
verify_that!(value, contains_each![(eq(2), eq("Two")), (eq(1), eq("One"))])

This matcher does not support matching directly against an Iterator. To match against an iterator, use Iterator::collect to build a Vec.

The matcher proceeds in three stages:

  1. It first checks whether the actual value is large enough to possibly be matched by each of the given matchers. If not, then it immediately fails explaining that the size is too small.

  2. It then checks whether each matcher matches at least one corresponding element in the actual container and fails if that is not the case. The failure message indicates which matcher had no corresponding element.

  3. Finally, it checks whether the mapping of matchers to corresponding actual elements is 1-1 and fails if that is not the case. The failure message then shows the best matching it could find, including which matchers did not have corresponding unique elements in the container.