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/// This is deprecated. Use `is_empty()` instead.
46#[deprecated(since = "0.14.1", note = "Use `is_empty()` instead.")]
47pub fn empty() -> EmptyMatcher {
48 EmptyMatcher
49}
50
51#[derive(MatcherBase)]
52pub struct EmptyMatcher;
53
54impl<T: Debug + Copy> Matcher<T> for EmptyMatcher
55where
56 T: IntoIterator,
57{
58 fn matches(&self, actual: T) -> MatcherResult {
59 actual.into_iter().next().is_none().into()
60 }
61
62 fn describe(&self, matcher_result: MatcherResult) -> Description {
63 if matcher_result.into() { "is empty" } else { "isn't empty" }.into()
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use crate::prelude::*;
70 use crate::Result;
71 use std::collections::HashSet;
72
73 #[test]
74 fn empty_matcher_match_empty_vec() -> Result<()> {
75 let value: Vec<i32> = vec![];
76 verify_that!(value, is_empty())
77 }
78
79 #[test]
80 fn empty_matcher_does_not_match_empty_vec() -> Result<()> {
81 let value = vec![1, 2, 3];
82 verify_that!(value, not(is_empty()))
83 }
84
85 #[test]
86 fn empty_matcher_matches_empty_slice() -> Result<()> {
87 let value: &[i32] = &[];
88 verify_that!(value, is_empty())
89 }
90
91 #[test]
92 fn empty_matcher_matches_empty_hash_set() -> Result<()> {
93 let value: HashSet<i32> = HashSet::new();
94 verify_that!(value, is_empty())
95 }
96}