googletest/matchers/empty_matcher.rs
1// Copyright 2022 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::{
16 description::Description,
17 matcher::{Matcher, MatcherBase, MatcherResult},
18};
19use std::fmt::Debug;
20
21/// Matches an empty container.
22///
23/// `T` can be any container that implements `IntoIterator`. For instance, `T`
24/// can be the reference of a common container like `&Vec` and
25/// [`&HashSet`][std::collections::HashSet].
26///
27/// ```
28/// # use googletest::prelude::*;
29/// # use std::collections::HashSet;
30/// # fn should_pass() -> Result<()> {
31/// let value: Vec<i32> = vec![];
32/// verify_that!(value, is_empty())?;
33/// let value: HashSet<i32> = HashSet::new();
34/// verify_that!(value, is_empty())?;
35/// let value: &[u32] = &[];
36/// verify_that!(value, is_empty())?;
37/// # Ok(())
38/// # }
39/// # should_pass().unwrap();
40/// ```
41pub fn is_empty() -> EmptyMatcher {
42 EmptyMatcher
43}
44
45#[derive(MatcherBase)]
46pub struct EmptyMatcher;
47
48impl<T: Debug + Copy> Matcher<T> for EmptyMatcher
49where
50 T: IntoIterator,
51{
52 fn matches(&self, actual: T) -> MatcherResult {
53 actual.into_iter().next().is_none().into()
54 }
55
56 fn describe(&self, matcher_result: MatcherResult) -> Description {
57 if matcher_result.into() { "is empty" } else { "isn't empty" }.into()
58 }
59}
60
61#[cfg(test)]
62mod tests {
63 use crate::prelude::*;
64 use crate::Result;
65 use std::collections::HashSet;
66
67 #[test]
68 fn empty_matcher_match_empty_vec() -> Result<()> {
69 let value: Vec<i32> = vec![];
70 verify_that!(value, is_empty())
71 }
72
73 #[test]
74 fn empty_matcher_does_not_match_empty_vec() -> Result<()> {
75 let value = vec![1, 2, 3];
76 verify_that!(value, not(is_empty()))
77 }
78
79 #[test]
80 fn empty_matcher_matches_empty_slice() -> Result<()> {
81 let value: &[i32] = &[];
82 verify_that!(value, is_empty())
83 }
84
85 #[test]
86 fn empty_matcher_matches_empty_hash_set() -> Result<()> {
87 let value: HashSet<i32> = HashSet::new();
88 verify_that!(value, is_empty())
89 }
90}