googletest/matchers/
anything_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 anything. This matcher always succeeds.
22///
23/// This is useful to check if `actual` matches the specific structure (like
24/// `Some(...)`)  but without caring about the internal value.
25///
26/// ```
27/// # use googletest::prelude::*;
28/// # fn should_pass() -> Result<()> {
29/// let option = Some("Some value");
30/// verify_that!(option, some(anything()))?;
31/// #     Ok(())
32/// # }
33/// # should_pass().unwrap();
34/// ```
35pub fn anything() -> Anything {
36    Anything
37}
38
39#[derive(MatcherBase)]
40pub struct Anything;
41
42impl<T: Debug + Copy> Matcher<T> for Anything {
43    fn matches(&self, _: T) -> MatcherResult {
44        MatcherResult::Match
45    }
46
47    fn describe(&self, matcher_result: MatcherResult) -> Description {
48        match matcher_result {
49            MatcherResult::Match => "is anything".into(),
50            MatcherResult::NoMatch => "never matches".into(),
51        }
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use crate::prelude::*;
58    use crate::Result;
59
60    #[test]
61    fn anything_matches_i32() -> Result<()> {
62        let value = 32;
63        verify_that!(value, anything())?;
64        Ok(())
65    }
66
67    #[test]
68    fn anything_matches_str() -> Result<()> {
69        let value = "32";
70        verify_that!(value, anything())?;
71        Ok(())
72    }
73
74    #[test]
75    fn anything_matches_option() -> Result<()> {
76        let value = Some(32);
77        verify_that!(value, some(anything()))?;
78        Ok(())
79    }
80}