Skip to main content

googletest/matchers/
ge_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 a value greater than or equal to (in the sense of `>=`) `expected`.
22///
23/// The types of `ActualT` of `actual` and `ExpectedT` of `expected` must be
24/// comparable via the `PartialOrd` trait. Namely, `ActualT` must implement
25/// `PartialOrd<ExpectedT>`.
26///
27/// ```
28/// # use googletest::prelude::*;
29/// # fn should_pass() -> Result<()> {
30/// verify_that!(1, ge(0))?; // Passes
31/// #     Ok(())
32/// # }
33/// # fn should_fail() -> Result<()> {
34/// verify_that!(0, ge(1))?; // Fails
35/// #     Ok(())
36/// # }
37/// # should_pass().unwrap();
38/// # should_fail().unwrap_err();
39/// ```
40///
41/// In most cases the params neeed to be the same type or they need to be cast
42/// explicitly. This can be surprising when comparing integer types or
43/// references:
44///
45/// ```compile_fail
46/// # use googletest::prelude::*;
47/// # fn should_not_compile() -> Result<()> {
48/// verify_that!(123u32, ge(0u64))?; // Does not compile
49/// verify_that!(123u32 as u64, ge(0u64))?; // Passes
50/// #     Ok(())
51/// # }
52/// ```
53///
54/// ```compile_fail
55/// # use googletest::prelude::*;
56/// # fn should_not_compile() -> Result<()> {
57/// let actual: &u32 = &2;
58/// let expected: u32 = 0;
59/// verify_that!(actual, ge(expected))?; // Does not compile
60/// #     Ok(())
61/// # }
62/// ```
63///
64/// ```
65/// # use googletest::prelude::*;
66/// # fn should_pass() -> Result<()> {
67/// let actual: &u32 = &2;
68/// let expected: u32 = 0;
69/// verify_that!(actual, ge(&expected))?; // Compiles and passes
70/// #     Ok(())
71/// # }
72/// # should_pass().unwrap();
73/// ```
74///
75/// You can find the standard library `PartialOrd` implementation in
76/// <https://doc.rust-lang.org/core/cmp/trait.PartialOrd.html#implementors>
77pub fn ge<ExpectedT>(expected: ExpectedT) -> GeMatcher<ExpectedT> {
78    GeMatcher { expected }
79}
80
81#[derive(MatcherBase)]
82pub struct GeMatcher<ExpectedT> {
83    expected: ExpectedT,
84}
85
86impl<ActualT: Debug + PartialOrd<ExpectedT> + Copy, ExpectedT: Debug> Matcher<ActualT>
87    for GeMatcher<ExpectedT>
88{
89    fn matches(&self, actual: ActualT) -> MatcherResult {
90        (actual >= self.expected).into()
91    }
92
93    fn describe(&self, matcher_result: MatcherResult) -> Description {
94        match matcher_result {
95            MatcherResult::Match => {
96                format!("is greater than or equal to {:?}", self.expected).into()
97            }
98            MatcherResult::NoMatch => format!("is less than {:?}", self.expected).into(),
99        }
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use crate::matcher::MatcherResult;
106    use crate::prelude::*;
107    use crate::Result;
108    use indoc::indoc;
109    use std::ffi::OsString;
110
111    #[test]
112    fn ge_matches_i32_with_i32() -> Result<()> {
113        let actual: i32 = 0;
114        let expected: i32 = 0;
115        verify_that!(actual, ge(expected))
116    }
117
118    #[test]
119    fn ge_does_not_match_smaller_i32() -> Result<()> {
120        let matcher = ge(10);
121        let result = matcher.matches(9);
122        verify_that!(result, eq(MatcherResult::NoMatch))
123    }
124
125    #[test]
126    fn ge_matches_bigger_str() -> Result<()> {
127        verify_that!("B", ge("A"))
128    }
129
130    #[test]
131    fn ge_does_not_match_lesser_str() -> Result<()> {
132        let matcher = ge("z");
133        let result = matcher.matches("a");
134        verify_that!(result, eq(MatcherResult::NoMatch))
135    }
136
137    #[test]
138    fn ge_mismatch_contains_actual_and_expected() -> Result<()> {
139        let result = verify_that!(591, ge(927));
140
141        verify_that!(
142            result,
143            err(displays_as(contains_substring(indoc!(
144                "
145                Value of: 591
146                Expected: is greater than or equal to 927
147                Actual: 591,
148                  which is less than 927
149                "
150            ))))
151        )
152    }
153
154    // Test `ge` matcher where actual is `&OsString` and expected is `&str`.
155    // Note that stdlib is a little bit inconsistent: `PartialOrd` exists for
156    // `OsString` and `str`, but only in one direction: it's only possible to
157    // compare `OsString` with `str` if `OsString` is on the left side of the
158    // ">=" operator (`impl PartialOrd<str> for OsString`).
159    //
160    // The comparison in the other direction is not defined.
161    //
162    // This means that the test case bellow effectively ensures that
163    // `verify_that(actual, ge(expected))` works if `actual >= expected` works
164    // (regardless whether the `expected >= actual` works`).
165    #[test]
166    fn ge_matches_owned_osstring_reference_with_string_reference() -> Result<()> {
167        let expected = "A";
168        let actual: OsString = "B".to_string().into();
169        verify_that!(&actual, ge(expected))
170    }
171
172    #[test]
173    fn ge_matches_ipv6addr_with_ipaddr() -> Result<()> {
174        use std::net::IpAddr;
175        use std::net::Ipv6Addr;
176        let actual: Ipv6Addr = "2001:4860:4860::8844".parse().unwrap();
177        let expected: IpAddr = "127.0.0.1".parse().unwrap();
178        verify_that!(actual, ge(expected))
179    }
180
181    #[test]
182    fn ge_matches_with_custom_partial_ord() -> Result<()> {
183        /// A custom "number" that is lower than all other numbers. The only
184        /// things we define about this "special" number is `PartialOrd` and
185        /// `PartialEq` against `u32`.
186        #[derive(Debug)]
187        struct VeryLowNumber {}
188
189        impl std::cmp::PartialEq<u32> for VeryLowNumber {
190            fn eq(&self, _other: &u32) -> bool {
191                false
192            }
193        }
194
195        // PartialOrd (required for >) requires PartialEq.
196        impl std::cmp::PartialOrd<u32> for VeryLowNumber {
197            fn partial_cmp(&self, _other: &u32) -> Option<std::cmp::Ordering> {
198                Some(std::cmp::Ordering::Less)
199            }
200        }
201
202        impl std::cmp::PartialEq<VeryLowNumber> for u32 {
203            fn eq(&self, _other: &VeryLowNumber) -> bool {
204                false
205            }
206        }
207
208        impl std::cmp::PartialOrd<VeryLowNumber> for u32 {
209            fn partial_cmp(&self, _other: &VeryLowNumber) -> Option<std::cmp::Ordering> {
210                Some(std::cmp::Ordering::Greater)
211            }
212        }
213
214        let actual: u32 = 42;
215        let expected = VeryLowNumber {};
216
217        verify_that!(actual, ge(expected))
218    }
219}