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
15 use crate::description::Description;
16 use crate::matcher::{Matcher, MatcherResult};
17 use std::fmt::Debug;
18 use std::marker::PhantomData;
19
20 /// Matches an `Option` containing `None`.
21 ///
22 /// ```
23 /// # use googletest::prelude::*;
24 /// # fn should_pass() -> Result<()> {
25 /// verify_that!(None::<()>, none())?; // Passes
26 /// # Ok(())
27 /// # }
28 /// # fn should_fail() -> Result<()> {
29 /// verify_that!(Some("Some value"), none())?; // Fails
30 /// # Ok(())
31 /// # }
32 /// # should_pass().unwrap();
33 /// # should_fail().unwrap_err();
34 /// ```
none<T: Debug>() -> impl Matcher<ActualT = Option<T>>35 pub fn none<T: Debug>() -> impl Matcher<ActualT = Option<T>> {
36 NoneMatcher::<T> { phantom: Default::default() }
37 }
38
39 struct NoneMatcher<T> {
40 phantom: PhantomData<T>,
41 }
42
43 impl<T: Debug> Matcher for NoneMatcher<T> {
44 type ActualT = Option<T>;
45
matches(&self, actual: &Option<T>) -> MatcherResult46 fn matches(&self, actual: &Option<T>) -> MatcherResult {
47 (actual.is_none()).into()
48 }
49
describe(&self, matcher_result: MatcherResult) -> Description50 fn describe(&self, matcher_result: MatcherResult) -> Description {
51 match matcher_result {
52 MatcherResult::Match => "is none".into(),
53 MatcherResult::NoMatch => "is some(_)".into(),
54 }
55 }
56 }
57
58 #[cfg(test)]
59 mod tests {
60 use super::none;
61 use crate::matcher::{Matcher, MatcherResult};
62 use crate::prelude::*;
63
64 #[test]
none_matches_option_with_none() -> Result<()>65 fn none_matches_option_with_none() -> Result<()> {
66 let matcher = none::<i32>();
67
68 let result = matcher.matches(&None);
69
70 verify_that!(result, eq(MatcherResult::Match))
71 }
72
73 #[test]
none_does_not_match_option_with_value() -> Result<()>74 fn none_does_not_match_option_with_value() -> Result<()> {
75 let matcher = none();
76
77 let result = matcher.matches(&Some(0));
78
79 verify_that!(result, eq(MatcherResult::NoMatch))
80 }
81 }
82