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::{
16     description::Description,
17     matcher::{Matcher, MatcherResult},
18 };
19 use std::{fmt::Debug, marker::PhantomData};
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>
ge<ActualT: Debug + PartialOrd<ExpectedT>, ExpectedT: Debug>( expected: ExpectedT, ) -> impl Matcher<ActualT = ActualT>77 pub fn ge<ActualT: Debug + PartialOrd<ExpectedT>, ExpectedT: Debug>(
78     expected: ExpectedT,
79 ) -> impl Matcher<ActualT = ActualT> {
80     GeMatcher::<ActualT, _> { expected, phantom: Default::default() }
81 }
82 
83 struct GeMatcher<ActualT, ExpectedT> {
84     expected: ExpectedT,
85     phantom: PhantomData<ActualT>,
86 }
87 
88 impl<ActualT: Debug + PartialOrd<ExpectedT>, ExpectedT: Debug> Matcher
89     for GeMatcher<ActualT, ExpectedT>
90 {
91     type ActualT = ActualT;
92 
matches(&self, actual: &ActualT) -> MatcherResult93     fn matches(&self, actual: &ActualT) -> MatcherResult {
94         (*actual >= self.expected).into()
95     }
96 
describe(&self, matcher_result: MatcherResult) -> Description97     fn describe(&self, matcher_result: MatcherResult) -> Description {
98         match matcher_result {
99             MatcherResult::Match => {
100                 format!("is greater than or equal to {:?}", self.expected).into()
101             }
102             MatcherResult::NoMatch => format!("is less than {:?}", self.expected).into(),
103         }
104     }
105 }
106 
107 #[cfg(test)]
108 mod tests {
109     use super::ge;
110     use crate::matcher::{Matcher, MatcherResult};
111     use crate::prelude::*;
112     use indoc::indoc;
113     use std::ffi::OsString;
114 
115     #[test]
ge_matches_i32_with_i32() -> Result<()>116     fn ge_matches_i32_with_i32() -> Result<()> {
117         let actual: i32 = 0;
118         let expected: i32 = 0;
119         verify_that!(actual, ge(expected))
120     }
121 
122     #[test]
ge_does_not_match_smaller_i32() -> Result<()>123     fn ge_does_not_match_smaller_i32() -> Result<()> {
124         let matcher = ge(10);
125         let result = matcher.matches(&9);
126         verify_that!(result, eq(MatcherResult::NoMatch))
127     }
128 
129     #[test]
ge_matches_bigger_str() -> Result<()>130     fn ge_matches_bigger_str() -> Result<()> {
131         verify_that!("B", ge("A"))
132     }
133 
134     #[test]
ge_does_not_match_lesser_str() -> Result<()>135     fn ge_does_not_match_lesser_str() -> Result<()> {
136         let matcher = ge("z");
137         let result = matcher.matches(&"a");
138         verify_that!(result, eq(MatcherResult::NoMatch))
139     }
140 
141     #[test]
ge_mismatch_contains_actual_and_expected() -> Result<()>142     fn ge_mismatch_contains_actual_and_expected() -> Result<()> {
143         let result = verify_that!(591, ge(927));
144 
145         verify_that!(
146             result,
147             err(displays_as(contains_substring(indoc!(
148                 "
149                 Value of: 591
150                 Expected: is greater than or equal to 927
151                 Actual: 591,
152                   which is less than 927
153                 "
154             ))))
155         )
156     }
157 
158     // Test `ge` matcher where actual is `&OsString` and expected is `&str`.
159     // Note that stdlib is a little bit inconsistent: `PartialOrd` exists for
160     // `OsString` and `str`, but only in one direction: it's only possible to
161     // compare `OsString` with `str` if `OsString` is on the left side of the
162     // ">=" operator (`impl PartialOrd<str> for OsString`).
163     //
164     // The comparison in the other direction is not defined.
165     //
166     // This means that the test case bellow effectively ensures that
167     // `verify_that(actual, ge(expected))` works if `actual >= expected` works
168     // (regardless whether the `expected >= actual` works`).
169     #[test]
ge_matches_owned_osstring_reference_with_string_reference() -> Result<()>170     fn ge_matches_owned_osstring_reference_with_string_reference() -> Result<()> {
171         let expected = "A";
172         let actual: OsString = "B".to_string().into();
173         verify_that!(&actual, ge(expected))
174     }
175 
176     #[test]
ge_matches_ipv6addr_with_ipaddr() -> Result<()>177     fn ge_matches_ipv6addr_with_ipaddr() -> Result<()> {
178         use std::net::IpAddr;
179         use std::net::Ipv6Addr;
180         let actual: Ipv6Addr = "2001:4860:4860::8844".parse().unwrap();
181         let expected: IpAddr = "127.0.0.1".parse().unwrap();
182         verify_that!(actual, ge(expected))
183     }
184 
185     #[test]
ge_matches_with_custom_partial_ord() -> Result<()>186     fn ge_matches_with_custom_partial_ord() -> Result<()> {
187         /// A custom "number" that is lower than all other numbers. The only
188         /// things we define about this "special" number is `PartialOrd` and
189         /// `PartialEq` against `u32`.
190         #[derive(Debug)]
191         struct VeryLowNumber {}
192 
193         impl std::cmp::PartialEq<u32> for VeryLowNumber {
194             fn eq(&self, _other: &u32) -> bool {
195                 false
196             }
197         }
198 
199         // PartialOrd (required for >) requires PartialEq.
200         impl std::cmp::PartialOrd<u32> for VeryLowNumber {
201             fn partial_cmp(&self, _other: &u32) -> Option<std::cmp::Ordering> {
202                 Some(std::cmp::Ordering::Less)
203             }
204         }
205 
206         impl std::cmp::PartialEq<VeryLowNumber> for u32 {
207             fn eq(&self, _other: &VeryLowNumber) -> bool {
208                 false
209             }
210         }
211 
212         impl std::cmp::PartialOrd<VeryLowNumber> for u32 {
213             fn partial_cmp(&self, _other: &VeryLowNumber) -> Option<std::cmp::Ordering> {
214                 Some(std::cmp::Ordering::Greater)
215             }
216         }
217 
218         let actual: u32 = 42;
219         let expected = VeryLowNumber {};
220 
221         verify_that!(actual, ge(expected))
222     }
223 }
224