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 // There are no visible documentation elements in this module; the declarative
16 // macros are documented at the top level.
17 #![doc(hidden)]
18 
19 /// Checks whether the `Matcher` given by the second argument matches the first
20 /// argument.
21 ///
22 /// Evaluates to `Result::Ok(())` if the matcher matches and
23 /// `Result::Err(TestAssertionFailure)` if it does not. The caller must then
24 /// decide how to handle the `Err` variant. It has a few options:
25 ///
26 ///  * Abort the current function with the `?` operator. This requires that the
27 ///    function return a suitable `Result`.
28 ///  * Log the test failure and continue by calling the method
29 ///    `and_log_failure`.
30 ///
31 /// Of course, one can also use all other standard methods on `Result`.
32 ///
33 /// **Invoking this macro by itself does not cause a test failure to be recorded
34 /// or output.** The resulting `Result` must be handled as described above to
35 /// cause the test to be recorded as a failure.
36 ///
37 /// Example:
38 /// ```
39 /// # use googletest::prelude::*;
40 /// # fn should_pass() -> Result<()> {
41 /// verify_that!(42, eq(42))?; // This will pass.
42 /// # Ok(())
43 /// # }
44 /// # should_pass().unwrap();
45 /// # fn should_fail() -> Result<()> {
46 /// # googletest::internal::test_outcome::TestOutcome::init_current_test_outcome();
47 /// verify_that!(42, eq(123)).and_log_failure();
48 ///             // This will log a test failure and allow execution to continue.
49 /// let _ = verify_that!(42, eq(123)); // This will do nothing.
50 /// verify_that!(42, eq(123))?; // This will fail, returning immediately.
51 /// verify_that!(42, eq(0))?; // This will not run.
52 /// # googletest::internal::test_outcome::TestOutcome::close_current_test_outcome::<&str>(Ok(()))
53 /// #     .unwrap_err();
54 /// # Ok(())
55 /// # }
56 /// # verify_that!(should_fail(), err(displays_as(contains_substring("Expected: is equal to 123"))))
57 /// #     .unwrap();
58 /// ```
59 ///
60 /// This macro has special support for matching against container. Namely:
61 ///   * `verify_that!(actual, [m1, m2, ...])` is equivalent to
62 ///     `verify_that!(actual, elements_are![m1, m2, ...])`
63 ///   * `verify_that!(actual, {m1, m2, ...})` is equivalent to
64 ///     `verify_that!(actual, unordered_elements_are![m1, m2, ...])`
65 ///
66 /// ## Matching against tuples
67 ///
68 /// One can match against a tuple by constructing a tuple of matchers as
69 /// follows:
70 ///
71 /// ```
72 /// # use googletest::prelude::*;
73 /// # fn should_pass() -> Result<()> {
74 /// verify_that!((123, 456), (eq(123), eq(456)))?; // Passes
75 /// #     Ok(())
76 /// # }
77 /// # fn should_fail() -> Result<()> {
78 /// verify_that!((123, 456), (eq(123), eq(0)))?; // Fails: second matcher does not match
79 /// #     Ok(())
80 /// # }
81 /// # should_pass().unwrap();
82 /// # should_fail().unwrap_err();
83 /// ```
84 ///
85 /// This also works with composed matchers:
86 ///
87 /// ```
88 /// # use googletest::prelude::*;
89 /// # fn should_pass() -> Result<()> {
90 /// verify_that!((123, 456), not((eq(456), eq(123))))?; // Passes
91 /// #     Ok(())
92 /// # }
93 /// # should_pass().unwrap();
94 /// ```
95 ///
96 /// Matchers must correspond to the actual tuple in count and type. Otherwise
97 /// the test will fail to compile.
98 ///
99 /// ```compile_fail
100 /// # use googletest::prelude::*;
101 /// # fn should_not_compile() -> Result<()> {
102 /// verify_that!((123, 456), (eq(123),))?; // Does not compile: wrong tuple size
103 /// verify_that!((123, "A string"), (eq(123), eq(456)))?; // Does not compile: wrong type
104 /// #     Ok(())
105 /// # }
106 /// ```
107 ///
108 /// All fields must be covered by matchers. Use
109 /// [`anything`][crate::matchers::anything] for fields which are not relevant
110 /// for the test.
111 ///
112 /// ```
113 /// # use googletest::prelude::*;
114 /// verify_that!((123, 456), (eq(123), anything()))
115 /// #     .unwrap();
116 /// ```
117 ///
118 /// This supports tuples of up to 12 elements. Tuples longer than that do not
119 /// automatically inherit the `Debug` trait from their members, so are generally
120 /// not supported; see [Rust by Example](https://doc.rust-lang.org/rust-by-example/primitives/tuples.html#tuples).
121 #[macro_export]
122 macro_rules! verify_that {
123     ($actual:expr, [$($expecteds:expr),+ $(,)?]) => {
124         $crate::assertions::internal::check_matcher(
125             &$actual,
126             $crate::matchers::elements_are![$($expecteds),+],
127             stringify!($actual),
128             $crate::internal::source_location::SourceLocation::new(file!(), line!(), column!()),
129         )
130     };
131     ($actual:expr, {$($expecteds:expr),+ $(,)?}) => {
132         $crate::assertions::internal::check_matcher(
133             &$actual,
134             $crate::matchers::unordered_elements_are![$($expecteds),+],
135             stringify!($actual),
136             $crate::internal::source_location::SourceLocation::new(file!(), line!(), column!()),
137         )
138     };
139     ($actual:expr, $expected:expr $(,)?) => {
140         $crate::assertions::internal::check_matcher(
141             &$actual,
142             $expected,
143             stringify!($actual),
144             $crate::internal::source_location::SourceLocation::new(file!(), line!(), column!()),
145         )
146     };
147 }
148 
149 /// Asserts that the given predicate applied to the given arguments returns
150 /// true.
151 ///
152 /// Similarly to [`verify_that`], this evaluates to a `Result` whose `Ok`
153 /// variant indicates that the given predicate returned true and whose `Err`
154 /// variant indicates that it returned false.
155 ///
156 /// The failure message contains detailed information about the arguments. For
157 /// example:
158 ///
159 /// ```
160 /// # use googletest::prelude::*;
161 /// fn equals_modulo(a: i32, b: i32, n: i32) -> bool { a % n == b % n }
162 ///
163 /// # /* The attribute macro would prevent the function from being compiled in a doctest.
164 /// #[test]
165 /// # */
166 /// fn test() -> Result<()> {
167 ///     let a = 1;
168 ///     let b = 7;
169 ///     let n = 5;
170 ///     verify_pred!(equals_modulo(a, b, n))?;
171 ///     Ok(())
172 /// }
173 /// # verify_that!(
174 /// #     test(),
175 /// #     err(displays_as(contains_substring("equals_modulo(a, b, n) was false with")))
176 /// # ).unwrap();
177 /// ```
178 ///
179 /// This results in the following message:
180 ///
181 /// ```text
182 /// equals_modulo(a, b, n) was false with
183 ///   a = 1,
184 ///   b = 7,
185 ///   n = 5
186 /// ```
187 ///
188 /// The function passed to this macro must return `bool`. Each of the arguments
189 /// must evaluate to a type implementing [`std::fmt::Debug`]. The debug output
190 /// is used to construct the failure message.
191 ///
192 /// The predicate can also be a method on a struct, e.g.:
193 ///
194 /// ```ignore
195 /// struct AStruct {};
196 ///
197 /// impl AStruct {
198 ///   fn equals_modulo(...) {...}
199 /// }
200 ///
201 /// verify_pred!((AStruct {}).equals_modulo(a, b, n))?;
202 /// ```
203 ///
204 /// **Warning:** This macro assumes that the arguments passed to the predicate
205 /// are either *variables* or *calls to pure functions*. If two subsequent
206 /// invocations to any of the expresssions passed as arguments result in
207 /// different values, then the output message of a test failure will deviate
208 /// from the values actually passed to the predicate. For this reason, *always
209 /// assign the outputs of non-pure functions to variables before using them in
210 /// this macro. For example:
211 ///
212 /// ```ignore
213 /// let output = generate_random_number();  // Assigned outside of verify_pred.
214 /// verify_pred!(is_sufficiently_random(output))?;
215 /// ```
216 #[macro_export]
217 macro_rules! verify_pred {
218     ([$($predicate:tt)*]($($arg:tt),* $(,)?)) => {
219         if !$($predicate)*($($arg),*) {
220             $crate::assertions::internal::report_failed_predicate(
221                 concat!(stringify!($($predicate)*), stringify!(($($arg),*))),
222                 vec![$((format!(concat!(stringify!($arg), " = {:?}"), $arg))),*],
223                 $crate::internal::source_location::SourceLocation::new(
224                     file!(),
225                     line!(),
226                     column!(),
227                 ),
228             )
229         } else {
230             Ok(())
231         }
232     };
233 
234     ([$($predicate:tt)*] $first:tt $($rest:tt)*) => {
235         $crate::verify_pred!([$($predicate)* $first] $($rest)*)
236     };
237 
238     ($first:tt $($rest:tt)*) => {
239         $crate::verify_pred!([$first] $($rest)*)
240     };
241 }
242 
243 /// Evaluates to a `Result` which contains an `Err` variant with the given test
244 /// failure message.
245 ///
246 /// This can be used to force the test to fail if its execution reaches a
247 /// particular point. For example:
248 ///
249 /// ```ignore
250 /// match some_value {
251 ///     ExpectedVariant => {...}
252 ///     UnwantedVaraint => {
253 ///         fail!("This thing which should not happen happened anyway")?;
254 ///     }
255 /// }
256 /// ```
257 ///
258 /// One may include formatted arguments in the failure message:
259 ///
260 /// ```ignore
261 /// match some_value {
262 ///     ExpectedVariant => {...}
263 ///     UnwantedVaraint => {
264 ///         fail!("This thing which should not happen happened anyway: {}", some_value)?;
265 ///     }
266 /// }
267 /// ```
268 ///
269 /// One may also omit the message, in which case the test failure message will
270 /// be generic:
271 ///
272 /// ```ignore
273 /// match some_value {
274 ///     ExpectedVariant => {...}
275 ///     UnwantedVaraint => {
276 ///         fail!()?;
277 ///     }
278 /// }
279 /// ```
280 ///
281 /// Unlike `panic!` but analogously to [`verify_that`] and [`verify_pred`], this
282 /// macro has no effect on the flow of control but instead returns a `Result`
283 /// which must be handled by the invoking function. This can be done with the
284 /// question mark operator (as above) or the method
285 /// [`and_log_failure`](crate::GoogleTestSupport::and_log_failure).
286 #[macro_export]
287 macro_rules! fail {
288     ($($message:expr),+) => {{
289         // We wrap this in a function so that we can annotate it with the must_use attribute.
290         // must_use on expressions is still experimental.
291         #[must_use = "The assertion result must be evaluated to affect the test result."]
292         fn create_fail_result(message: String) -> $crate::Result<()> {
293             Err($crate::internal::test_outcome::TestAssertionFailure::create(format!(
294                 "{}\n{}",
295                 message,
296                 $crate::internal::source_location::SourceLocation::new(
297                     file!(),
298                     line!(),
299                     column!(),
300                 ),
301             )))
302         }
303         create_fail_result(format!($($message),*))
304     }};
305 
306     () => { fail!("Test failed") };
307 }
308 
309 /// Matches the given value against the given matcher, panicking if it does not
310 /// match.
311 ///
312 /// ```should_panic
313 /// # use googletest::prelude::*;
314 /// # fn should_fail() {
315 /// let value = 2;
316 /// assert_that!(value, eq(3));  // Fails and panics.
317 /// # }
318 /// # should_fail();
319 /// ```
320 ///
321 /// This is analogous to assertions in most Rust test libraries, where a failed
322 /// assertion causes a panic.
323 ///
324 /// One may optionally add arguments which will be formatted and appended to a
325 /// failure message. For example:
326 ///
327 /// ```should_panic
328 /// # use googletest::prelude::*;
329 /// # fn should_fail() {
330 /// let value = 2;
331 /// let extra_information = "Some additional information";
332 /// assert_that!(value, eq(3), "Test failed. Extra information: {extra_information}.");
333 /// # }
334 /// # should_fail();
335 /// ```
336 ///
337 /// This is output as follows:
338 ///
339 /// ```text
340 /// Value of: value
341 /// Expected: is equal to 3
342 /// Actual: 2,
343 ///   which isn't equal to 3
344 ///   at ...
345 /// Test failed. Extra information: Some additional information.
346 /// ```
347 ///
348 /// **Note for users of [GoogleTest for C++](http://google.github.io/googletest/):**
349 /// This differs from the `ASSERT_THAT` macro in that it panics rather
350 /// than triggering an early return from the invoking function. To get behaviour
351 /// equivalent to `ASSERT_THAT`, use [`verify_that!`] with the `?` operator.
352 #[macro_export]
353 macro_rules! assert_that {
354     ($actual:expr, $expected:expr $(,)?) => {
355         match $crate::verify_that!($actual, $expected) {
356             Ok(_) => {}
357             Err(e) => {
358                 // The extra newline before the assertion failure message makes the failure a
359                 // bit easier to read when there's some generic boilerplate from the panic.
360                 panic!("\n{}", e);
361             }
362         }
363     };
364 
365     ($actual:expr, $expected:expr, $($format_args:expr),* $(,)?) => {
366         match $crate::verify_that!($actual, $expected)
367             .with_failure_message(|| format!($($format_args),*))
368         {
369             Ok(_) => {}
370             Err(e) => {
371                 // The extra newline before the assertion failure message makes the failure a
372                 // bit easier to read when there's some generic boilerplate from the panic.
373                 panic!("\n{}", e);
374             }
375         }
376     };
377 }
378 
379 /// Asserts that the given predicate applied to the given arguments returns
380 /// true, panicking if it does not.
381 ///
382 /// **Note for users of [GoogleTest for C++](http://google.github.io/googletest/):**
383 /// This differs from the `ASSERT_PRED*` family of macros in that it panics
384 /// rather than triggering an early return from the invoking function. To get
385 /// behaviour equivalent to `ASSERT_PRED*`, use [`verify_pred!`] with the `?`
386 /// operator.
387 #[macro_export]
388 macro_rules! assert_pred {
389     ($($content:tt)*) => {
390         match $crate::verify_pred!($($content)*) {
391             Ok(_) => {}
392             Err(e) => {
393                 // The extra newline before the assertion failure message makes the failure a
394                 // bit easier to read when there's some generic boilerplate from the panic.
395                 panic!("\n{}", e);
396             }
397         }
398     };
399 }
400 
401 /// Matches the given value against the given matcher, marking the test as
402 /// failed but continuing execution if it does not match.
403 ///
404 /// This is a *non-fatal* assertion: the test continues
405 /// execution in the event of assertion failure.
406 ///
407 /// This can only be invoked inside tests with the
408 /// [`googletest::test`][crate::test] attribute. The assertion must
409 /// occur in the same thread as that running the test itself.
410 ///
411 /// Invoking this macro is equivalent to using
412 /// [`and_log_failure`](crate::GoogleTestSupport::and_log_failure) as follows:
413 ///
414 /// ```ignore
415 /// verify_that!(actual, expected).and_log_failure()
416 /// ```
417 ///
418 /// One may optionally add arguments which will be formatted and appended to a
419 /// failure message. For example:
420 ///
421 /// ```
422 /// # use googletest::prelude::*;
423 /// # fn should_fail() -> std::result::Result<(), googletest::internal::test_outcome::TestFailure> {
424 /// # googletest::internal::test_outcome::TestOutcome::init_current_test_outcome();
425 /// let value = 2;
426 /// let extra_information = "Some additional information";
427 /// expect_that!(value, eq(3), "Test failed. Extra information: {extra_information}.");
428 /// # googletest::internal::test_outcome::TestOutcome::close_current_test_outcome::<&str>(Ok(()))
429 /// # }
430 /// # should_fail().unwrap_err();
431 /// ```
432 ///
433 /// This is output as follows:
434 ///
435 /// ```text
436 /// Value of: value
437 /// Expected: is equal to 3
438 /// Actual: 2,
439 ///   which isn't equal to 3
440 ///   at ...
441 /// Test failed. Extra information: Some additional information.
442 /// ```
443 #[macro_export]
444 macro_rules! expect_that {
445     ($actual:expr, $expected:expr $(,)?) => {{
446         use $crate::GoogleTestSupport;
447         $crate::verify_that!($actual, $expected).and_log_failure();
448     }};
449 
450     ($actual:expr, $expected:expr, $($format_args:expr),* $(,)?) => {
451         $crate::verify_that!($actual, $expected)
452             .with_failure_message(|| format!($($format_args),*))
453             .and_log_failure()
454     };
455 }
456 
457 /// Asserts that the given predicate applied to the given arguments returns
458 /// true, failing the test but continuing execution if not.
459 ///
460 /// This is a *non-fatal* predicate assertion: the test
461 /// continues execution in the event of assertion failure.
462 ///
463 /// This can only be invoked inside tests with the
464 /// [`googletest::test`][crate::test] attribute. The assertion must
465 /// occur in the same thread as that running the test itself.
466 ///
467 /// Invoking this macro is equivalent to using
468 /// [`and_log_failure`](crate::GoogleTestSupport::and_log_failure) as follows:
469 ///
470 /// ```ignore
471 /// verify_pred!(predicate(...)).and_log_failure()
472 /// ```
473 #[macro_export]
474 macro_rules! expect_pred {
475     ($($content:tt)*) => {{
476         use $crate::GoogleTestSupport;
477         $crate::verify_pred!($($content)*).and_log_failure();
478     }};
479 }
480 
481 /// Functions for use only by the procedural macros in this module.
482 ///
483 /// **For internal use only. API stablility is not guaranteed!**
484 #[doc(hidden)]
485 pub mod internal {
486     use crate::{
487         internal::{source_location::SourceLocation, test_outcome::TestAssertionFailure},
488         matcher::{create_assertion_failure, Matcher, MatcherResult},
489     };
490     use std::fmt::Debug;
491 
492     /// Checks whether the matcher `expected` matches the value `actual`, adding
493     /// a test failure report if it does not match.
494     ///
495     /// Returns `Ok(())` if the value matches and `Err(())` if it does not
496     /// match.
497     ///
498     /// **For internal use only. API stablility is not guaranteed!**
499     #[must_use = "The assertion result must be evaluated to affect the test result."]
check_matcher<T: Debug + ?Sized>( actual: &T, expected: impl Matcher<ActualT = T>, actual_expr: &'static str, source_location: SourceLocation, ) -> Result<(), TestAssertionFailure>500     pub fn check_matcher<T: Debug + ?Sized>(
501         actual: &T,
502         expected: impl Matcher<ActualT = T>,
503         actual_expr: &'static str,
504         source_location: SourceLocation,
505     ) -> Result<(), TestAssertionFailure> {
506         match expected.matches(actual) {
507             MatcherResult::Match => Ok(()),
508             MatcherResult::NoMatch => {
509                 Err(create_assertion_failure(&expected, actual, actual_expr, source_location))
510             }
511         }
512     }
513 
514     /// Constructs a `Result::Err(TestAssertionFailure)` for a predicate failure
515     /// as produced by the macro [`crate::verify_pred`].
516     ///
517     /// This intended only for use by the macro [`crate::verify_pred`].
518     ///
519     /// **For internal use only. API stablility is not guaranteed!**
520     #[must_use = "The assertion result must be evaluated to affect the test result."]
report_failed_predicate( actual_expr: &'static str, formatted_arguments: Vec<String>, source_location: SourceLocation, ) -> Result<(), TestAssertionFailure>521     pub fn report_failed_predicate(
522         actual_expr: &'static str,
523         formatted_arguments: Vec<String>,
524         source_location: SourceLocation,
525     ) -> Result<(), TestAssertionFailure> {
526         Err(TestAssertionFailure::create(format!(
527             "{} was false with\n  {}\n{}",
528             actual_expr,
529             formatted_arguments.join(",\n  "),
530             source_location,
531         )))
532     }
533 }
534