• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     // specialized to sequences:
124     ($actual:expr, [$($expecteds:expr),+ $(,)?]) => {
125         {
126             use $crate::assertions::internal::Subject as _;
127             $actual.check(
128                 $crate::matchers::elements_are![$($expecteds),+],
129                 stringify!($actual),
130             )
131         }
132     };
133 
134     // specialized to unordered sequences:
135     ($actual:expr, {$($expecteds:expr),+ $(,)?}) => {
136         {
137             use $crate::assertions::internal::Subject as  _;
138             $actual.check(
139                 $crate::matchers::unordered_elements_are![$($expecteds),+],
140                 stringify!($actual),
141             )
142         }
143     };
144 
145     // general case:
146     ($actual:expr, $expected:expr $(,)?) => {
147         {
148             use $crate::assertions::internal::Subject as  _;
149             $actual.check(
150                 $expected,
151                 stringify!($actual),
152             )
153         }
154     };
155 }
156 
157 /// Asserts that the given predicate applied to the given arguments returns
158 /// true.
159 ///
160 /// Similarly to [`verify_that`], this evaluates to a `Result` whose `Ok`
161 /// variant indicates that the given predicate returned true and whose `Err`
162 /// variant indicates that it returned false.
163 ///
164 /// The failure message contains detailed information about the arguments. For
165 /// example:
166 ///
167 /// ```
168 /// # use googletest::prelude::*;
169 /// fn equals_modulo(a: i32, b: i32, n: i32) -> bool { a % n == b % n }
170 ///
171 /// # /* The attribute macro would prevent the function from being compiled in a doctest.
172 /// #[test]
173 /// # */
174 /// fn test() -> Result<()> {
175 ///     let a = 1;
176 ///     fn b(_x: i32) -> i32 { 7 }
177 ///     verify_pred!(equals_modulo(a, b(b(2)), 2 + 3))?;
178 ///     Ok(())
179 /// }
180 /// # verify_that!(
181 /// #     test(),
182 /// #     err(displays_as(contains_substring("equals_modulo(a, b(b(2)), 2 + 3) was false with")))
183 /// # ).unwrap();
184 /// ```
185 ///
186 /// This results in the following message:
187 ///
188 /// ```text
189 /// equals_modulo(a, b(b(2)), 2 + 3) was false with
190 ///   a = 1,
191 ///   b(b(2)) = 7,
192 ///   2 + 3 = 5,
193 /// ```
194 ///
195 /// The predicate can also be a method on a struct, e.g.:
196 ///
197 /// ```ignore
198 /// struct AStruct {};
199 ///
200 /// impl AStruct {
201 ///   fn equals_modulo(...) {...}
202 /// }
203 ///
204 /// verify_pred!((AStruct {}).equals_modulo(a, b, n))?;
205 /// ```
206 ///
207 /// The expression passed to this macro must return `bool`. In the most general
208 /// case, it prints out each of the `.`-separated parts of the expression and
209 /// the arguments of all top-level method calls as long as they implement
210 /// `Debug`. It evaluates every value (including the method receivers) exactly
211 /// once. Effectively, for `verify_pred!((a + 1).b.c(x + y, &mut z, 2))`, it
212 /// generates code analogous to the following, which allows printing accurate
213 /// intermediate values even if they are subsequently consumed (moved out) or
214 /// mutated in-place by the expression:
215 ///
216 /// ```ignore
217 /// let mut error_message = "(a + 1).b.c(x + y, 2) was false with".to_string();
218 /// let mut x1 = (a + 1);
219 /// write!(error_message, "\n  (a + 1) = {:?},", x1);
220 /// write!(error_message, "\n  (a + 1).b = {:?},", x1.b);
221 /// let mut x2 = x + y;
222 /// write!(error_message, "\n  x + y = {:?},", x2);
223 /// let mut x3 = &mut z;
224 /// write!(error_message, "\n  & mut z = {:?},", x3);
225 /// let mut x4 = x1.b.c(x2, x3, 2);
226 /// if (x4) {
227 ///   Ok(())
228 /// } else {
229 ///   Err(error_message)
230 /// }
231 /// ```
232 ///
233 /// Wrapping the passed-in expression in parens or curly braces will prevent the
234 /// detailed printing of the expression.
235 ///
236 /// ```ignore
237 /// verify_pred!((a.foo()).bar())?;
238 /// ```
239 ///
240 /// would not print `a`, but would print `(a.foo())` and `(a.foo()).bar()` on
241 /// error.
242 #[macro_export]
243 macro_rules! verify_pred {
244     ($expr:expr $(,)?) => {
245         $crate::assertions::internal::__googletest_macro_verify_pred!($expr)
246     };
247 }
248 
249 /// Evaluates to a `Result` which contains an `Err` variant with the given test
250 /// failure message.
251 ///
252 /// This can be used to force the test to fail if its execution reaches a
253 /// particular point. For example:
254 ///
255 /// ```ignore
256 /// match some_value {
257 ///     ExpectedVariant => {...}
258 ///     UnwantedVaraint => {
259 ///         fail!("This thing which should not happen happened anyway")?;
260 ///     }
261 /// }
262 /// ```
263 ///
264 /// One may include formatted arguments in the failure message:
265 ///
266 /// ```ignore
267 /// match some_value {
268 ///     ExpectedVariant => {...}
269 ///     UnwantedVaraint => {
270 ///         fail!("This thing which should not happen happened anyway: {}", some_value)?;
271 ///     }
272 /// }
273 /// ```
274 ///
275 /// One may also omit the message, in which case the test failure message will
276 /// be generic:
277 ///
278 /// ```ignore
279 /// match some_value {
280 ///     ExpectedVariant => {...}
281 ///     UnwantedVaraint => {
282 ///         fail!()?;
283 ///     }
284 /// }
285 /// ```
286 ///
287 /// Unlike `panic!` but analogously to [`verify_that`] and [`verify_pred`], this
288 /// macro has no effect on the flow of control but instead returns a `Result`
289 /// which must be handled by the invoking function. This can be done with the
290 /// question mark operator (as above) or the method
291 /// [`and_log_failure`](crate::GoogleTestSupport::and_log_failure).
292 #[macro_export]
293 macro_rules! fail {
294     ($($message:expr),+ $(,)?) => {{
295         $crate::assertions::internal::create_fail_result(
296             format!($($message),*),
297         )
298     }};
299 
300     () => { fail!("Test failed") };
301 }
302 
303 /// Generates a success. This **does not** make the overall test succeed. A test
304 /// is only considered successful if none of its assertions fail during its
305 /// execution.
306 ///
307 /// The succeed!() assertion is purely documentary. The only user visible output
308 /// is a stdout with information on where the success was generated from.
309 ///
310 /// ```ignore
311 /// fn test_to_be_implemented() {
312 ///     succeed!();
313 /// }
314 /// ```
315 ///
316 /// One may include formatted arguments in the success message:
317 ///
318 /// ```ignore
319 /// fn test_to_be_implemented() {
320 ///     succeed!("I am just a fake test: {}", "a fake test indeed");
321 /// }
322 /// ```
323 #[macro_export]
324 macro_rules! succeed {
325     ($($message:expr),+ $(,)?) => {{
326         println!(
327             "{}\n at {}:{}:{}",
328             format!($($message),*),
329             file!(), line!(), column!()
330         );
331     }};
332 
333     () => {
334         succeed!("Success")
335     };
336 }
337 
338 /// Generates a failure marking the test as failed but continue execution.
339 ///
340 /// This is a **not-fatal** failure. The test continues execution even after the
341 /// macro execution.
342 ///
343 /// This can only be invoked inside tests with the
344 /// [`gtest`][crate::gtest] attribute. The failure must be generated
345 /// in the same thread as that running the test itself.
346 ///
347 /// ```ignore
348 /// use googletest::prelude::*;
349 ///
350 /// #[gtest]
351 /// fn should_fail_but_not_abort() {
352 ///     add_failure!();
353 /// }
354 /// ```
355 ///
356 /// One may include formatted arguments in the failure message:
357 ///
358 /// ```ignore
359 /// use googletest::prelude::*;
360 ///
361 /// #[gtest]
362 /// fn should_fail_but_not_abort() {
363 ///     add_failure!("I am just a fake test: {}", "a fake test indeed");
364 /// }
365 /// ```
366 #[macro_export]
367 macro_rules! add_failure {
368     ($($message:expr),+ $(,)?) => {{
369         use $crate::GoogleTestSupport as _;
370         $crate::assertions::internal::create_fail_result(
371             format!($($message),*),
372         ).and_log_failure();
373     }};
374 
375     () => {
376         add_failure!("Failed")
377     };
378 }
379 
380 /// Generates a failure at specified location marking the test as failed but
381 /// continue execution.
382 ///
383 /// This is a **not-fatal** failure. The test continues execution even after the
384 /// macro execution.
385 ///
386 /// This can only be invoked inside tests with the
387 /// [`gtest`][crate::gtest] attribute. The failure must be generated
388 /// in the same thread as that running the test itself.
389 ///
390 /// ```ignore
391 /// use googletest::prelude::*;
392 ///
393 /// #[gtest]
394 /// fn should_fail_but_not_abort() {
395 ///     add_failure_at!("src/my_file.rs", 32, 12);
396 /// }
397 /// ```
398 ///
399 /// One may include formatted arguments in the failure message:
400 ///
401 /// ```ignore
402 /// use googletest::prelude::*;
403 ///
404 /// #[gtest]
405 /// fn should_fail_but_not_abort() {
406 ///     add_failure_at!(
407 ///         "src/my_file.rs",
408 ///         32,
409 ///         12,
410 ///         "I am just a fake test: {}", "a fake test indeed",
411 ///     );
412 /// }
413 /// ```
414 #[macro_export]
415 macro_rules! add_failure_at {
416     ($file:expr, $line:expr, $column:expr, $($message:expr),+ $(,)?) => {{
417         use $crate::GoogleTestSupport as _;
418         $crate::assertions::internal::create_fail_result(
419             format!($($message),*),
420         ).map_err(|e| e.with_fake_location($file, $line, $column)).and_log_failure();
421     }};
422 
423     ($file:expr, $line:expr, $column:expr $(,)?) => {
424         add_failure_at!($file, $line, $column, "Failed")
425     };
426 }
427 
428 /// Verify if the condition evaluates to true and returns `Result`.
429 ///
430 /// Evaluates to `Result::Ok(())` if the condition is true and
431 /// `Result::Err(TestAssertionFailure)` if it evaluates to false. The caller
432 /// must then decide how to handle the `Err` variant. It has a few options:
433 ///   * Abort the current function with the `?` operator. This requires that the
434 ///     function return a suitable `Result`.
435 ///   * Log the failure and continue by calling the method `and_log_failure`.
436 ///
437 /// Of course, one can also use all other standard methods on `Result`.
438 ///
439 /// **Invoking this macro by itself does not cause a test failure to be recorded
440 /// or output.** The resulting `Result` must be handled as described above to
441 /// cause the test to be recorded as a failure.
442 ///
443 /// Example:
444 /// ```ignore
445 /// use googletest::prelude::*;
446 ///
447 /// #[test]
448 /// fn should_fail() -> Result<()> {
449 ///     verify_true!(2 + 2 == 5)
450 /// }
451 /// ```
452 #[macro_export]
453 macro_rules! verify_true {
454     ($condition:expr) => {{
455         use $crate::assertions::internal::Subject as _;
456         ($condition).check($crate::matchers::eq(true), stringify!($condition))
457     }};
458 }
459 
460 /// Marks test as failed and continue execution if the expression evaluates to
461 /// false.
462 ///
463 /// This is a **not-fatal** failure. The test continues execution even after the
464 /// macro execution.
465 ///
466 /// This can only be invoked inside tests with the
467 /// [`gtest`][crate::gtest] attribute. The failure must be generated
468 /// in the same thread as that running the test itself.
469 ///
470 /// Example:
471 /// ```ignore
472 /// use googletest::prelude::*;
473 ///
474 /// #[gtest]
475 /// fn should_fail() {
476 ///     expect_true!(2 + 2 == 5);
477 ///     println!("This will print");
478 /// }
479 /// ```
480 #[macro_export]
481 macro_rules! expect_true {
482     ($condition:expr) => {{
483         use $crate::GoogleTestSupport as _;
484         verify_true!($condition).and_log_failure()
485     }};
486 }
487 
488 /// Verify if the condition evaluates to false and returns `Result`.
489 ///
490 /// Evaluates to `Result::Ok(())` if the condition is false and
491 /// `Result::Err(TestAssertionFailure)` if it evaluates to true. The caller
492 /// must then decide how to handle the `Err` variant. It has a few options:
493 ///   * Abort the current function with the `?` operator. This requires that the
494 ///     function return a suitable `Result`.
495 ///   * Log the failure and continue by calling the method `and_log_failure`.
496 ///
497 /// Of course, one can also use all other standard methods on `Result`.
498 ///
499 /// **Invoking this macro by itself does not cause a test failure to be recorded
500 /// or output.** The resulting `Result` must be handled as described above to
501 /// cause the test to be recorded as a failure.
502 ///
503 /// Example:
504 /// ```ignore
505 /// use googletest::prelude::*;
506 ///
507 /// #[test]
508 /// fn should_fail() -> Result<()> {
509 ///     verify_false!(2 + 2 == 4)
510 /// }
511 /// ```
512 #[macro_export]
513 macro_rules! verify_false {
514     ($condition:expr) => {{
515         use $crate::assertions::internal::Subject as _;
516         ($condition).check($crate::matchers::eq(false), stringify!($condition))
517     }};
518 }
519 
520 /// Marks test as failed and continue execution if the expression evaluates to
521 /// true.
522 ///
523 /// This is a **not-fatal** failure. The test continues execution even after the
524 /// macro execution.
525 ///
526 /// This can only be invoked inside tests with the
527 /// [`gtest`][crate::gtest] attribute. The failure must be generated
528 /// in the same thread as that running the test itself.
529 ///
530 /// Example:
531 /// ```ignore
532 /// use googletest::prelude::*;
533 ///
534 /// #[gtest]
535 /// fn should_fail() {
536 ///     expect_false!(2 + 2 == 4);
537 ///     println!("This will print");
538 /// }
539 /// ```
540 #[macro_export]
541 macro_rules! expect_false {
542     ($condition:expr) => {{
543         use $crate::GoogleTestSupport as _;
544         verify_false!($condition).and_log_failure()
545     }};
546 }
547 
548 /// Checks whether the second argument is equal to the first argument.
549 ///
550 /// Evaluates to `Result::Ok(())` if they are equal and
551 /// `Result::Err(TestAssertionFailure)` if they are not. The caller must then
552 /// decide how to handle the `Err` variant. It has a few options:
553 ///  * Abort the current function with the `?` operator. This requires that the
554 ///    function return a suitable `Result`.
555 ///  * Log the test failure and continue by calling the method
556 ///    `and_log_failure`.
557 ///
558 /// Of course, one can also use all other standard methods on `Result`.
559 ///
560 /// **Invoking this macro by itself does not cause a test failure to be recorded
561 /// or output.** The resulting `Result` must be handled as described above to
562 /// cause the test to be recorded as a failure.
563 ///
564 /// Example:
565 /// ```ignore
566 /// use googletest::prelude::*;
567 ///
568 /// #[test]
569 /// fn should_fail() -> Result<()> {
570 ///     verify_eq!(2, 1)
571 /// }
572 /// ```
573 ///
574 /// This macro has special support for matching against container. Namely:
575 ///  * `verify_eq!(actual, [e1, e2, ...])` is equivalent to
576 ///    `verify_that!(actual, elements_are![eq(e1), eq(e2), ...])`
577 ///  * `verify_eq!(actual, {e1, e2, ...})` is equivalent to
578 ///    `verify_that!(actual, unordered_elements_are![eq(e1), eq(e2), ...])`
579 #[macro_export]
580 macro_rules! verify_eq {
581     // Specialization for ordered sequences of tuples:
582     ($actual:expr, [ $( ( $($tuple_elt:expr),* ) ),+ $(,)? ] $(,)?) => {
583         verify_that!(&$actual, [
584             $(
585                 // tuple matching
586                 (
587                     $(
588                         $crate::matchers::eq(&$tuple_elt)
589                     ),*
590                 )
591             ),*
592         ])
593     };
594 
595     // Specialization for unordered sequences of tuples:
596     ($actual:expr, { $( ( $($tuple_elt:expr),* ) ),+ $(,)?} $(,)?) => {
597         verify_that!(&$actual, {
598             $(
599                 // tuple matching
600                 (
601                     $(
602                         $crate::matchers::eq(&$tuple_elt)
603                     ),*
604                 )
605             ),*
606         })
607     };
608 
609     // Ordered sequences:
610     ($actual:expr, [$($expected:expr),+ $(,)?] $(,)?) => {
611         verify_that!(&$actual, [$($crate::matchers::eq(&$expected)),*])
612     };
613 
614     // Unordered sequences:
615     ($actual:expr, {$($expected:expr),+ $(,)?} $(,)?) => {
616         verify_that!(&$actual, {$($crate::matchers::eq(&$expected)),*})
617     };
618 
619     // General case:
620     ($actual:expr, $expected:expr $(,)?) => {
621         verify_that!(&$actual, $crate::matchers::eq(&$expected))
622     };
623 }
624 
625 /// Marks test as failed and continues execution if the second argument is not
626 /// equal to first argument.
627 ///
628 /// This is a **not-fatal** failure. The test continues execution even after the
629 /// macro execution.
630 ///
631 /// This can only be invoked inside tests with the
632 /// [`gtest`][crate::gtest] attribute. The failure must be generated
633 /// in the same thread as that running the test itself.
634 ///
635 /// Example:
636 /// ```ignore
637 /// use googletest::prelude::*;
638 ///
639 /// #[gtest]
640 /// fn should_fail() {
641 ///     expect_eq!(2, 1);
642 ///     println!("This will print!");
643 /// }
644 /// ```
645 ///
646 /// This macro has special support for matching against container. Namely:
647 ///  * `expect_eq!(actual, [e1, e2, ...])` for checking actual contains "e1, e2,
648 ///    ..." in order.
649 ///  * `expect_eq!(actual, {e1, e2, ...})` for checking actual contains "e1, e2,
650 ///    ..." in any order.
651 ///
652 /// One may include formatted arguments in the failure message:
653 ///```ignore
654 /// use googletest::prelude::*;
655 ///
656 /// #[gtest]
657 /// fn should_fail() {
658 ///     let argument = "argument"
659 ///     expect_eq!(2, 1, "custom failure message: {argument}");
660 ///     println!("This will print!");
661 /// }
662 /// ```
663 #[macro_export]
664 macro_rules! expect_eq {
665     ($actual:expr, [$($expected:expr),+ $(,)?] $(,)?) => {{
666         use $crate::GoogleTestSupport as _;
667         verify_eq!($actual, [$($expected),*]).and_log_failure();
668     }};
669     ($actual:expr, [$($expected:expr),+ $(,)?], $($format_args:expr),* $(,)?) => {{
670         use $crate::GoogleTestSupport as _;
671         verify_eq!($actual, [$($expected),*])
672             .with_failure_message(|| format!($($format_args),*))
673             .and_log_failure();
674     }};
675     ($actual:expr, {$($expected:expr),+ $(,)?} $(,)?) => {{
676         use $crate::GoogleTestSupport as _;
677         verify_eq!($actual, {$($expected),*}).and_log_failure();
678     }};
679     ($actual:expr, {$($expected:expr),+ $(,)?}, $($format_args:expr),* $(,)?) => {{
680         use $crate::GoogleTestSupport as _;
681         verify_eq!($actual, {$($expected),*})
682             .with_failure_message(|| format!($($format_args),*))
683             .and_log_failure();
684     }};
685     ($actual:expr, $expected:expr $(,)?) => {{
686         use $crate::GoogleTestSupport as _;
687         verify_eq!($actual, $expected).and_log_failure();
688     }};
689     ($actual:expr, $expected:expr, $($format_args:expr),* $(,)?) => {{
690         use $crate::GoogleTestSupport as _;
691         verify_eq!($actual, $expected)
692             .with_failure_message(|| format!($($format_args),*))
693             .and_log_failure();
694     }};
695 }
696 
697 /// Checks whether the second argument is not equal to the first argument.
698 ///
699 /// Evaluates to `Result::Ok(())` if they are not equal and
700 /// `Result::Err(TestAssertionFailure)` if they are equal. The caller must then
701 /// decide how to handle the `Err` variant. It has a few options:
702 ///  * Abort the current function with the `?` operator. This requires that the
703 ///    function return a suitable `Result`.
704 ///  * Log the test failure and continue by calling the method
705 ///    `and_log_failure`.
706 ///
707 /// Of course, one can also use all other standard methods on `Result`.
708 ///
709 /// **Invoking this macro by itself does not cause a test failure to be recorded
710 /// or output.** The resulting `Result` must be handled as described above to
711 /// cause the test to be recorded as a failure.
712 ///
713 /// Example:
714 /// ```ignore
715 /// use googletest::prelude::*;
716 ///
717 /// #[test]
718 /// fn should_fail() -> Result<()> {
719 ///     verify_ne!(1, 1)
720 /// }
721 /// ```
722 #[macro_export]
723 macro_rules! verify_ne {
724     ($actual:expr, $expected:expr $(,)?) => {
725         verify_that!(&$actual, $crate::matchers::not($crate::matchers::eq(&$expected)))
726     };
727 }
728 
729 /// Marks test as failed and continues execution if the second argument is
730 /// equal to first argument.
731 ///
732 /// This is a **not-fatal** failure. The test continues execution even after the
733 /// macro execution.
734 ///
735 /// This can only be invoked inside tests with the
736 /// [`gtest`][crate::gtest] attribute. The failure must be generated
737 /// in the same thread as that running the test itself.
738 ///
739 /// Example:
740 /// ```ignore
741 /// use googletest::prelude::*;
742 ///
743 /// #[gtest]
744 /// fn should_fail() {
745 ///     expect_ne!(1, 1);
746 ///     println!("This will print!");
747 /// }
748 /// ```
749 ///
750 /// One may include formatted arguments in the failure message:
751 ///```ignore
752 /// use googletest::prelude::*;
753 ///
754 /// #[gtest]
755 /// fn should_fail() {
756 ///     let argument = "argument"
757 ///     expect_ne!(1, 1, "custom failure message: {argument}");
758 ///     println!("This will print!");
759 /// }
760 /// ```
761 #[macro_export]
762 macro_rules! expect_ne {
763     ($actual:expr, $expected:expr, $($format_args:expr),+ $(,)?) => {{
764         use $crate::GoogleTestSupport as _;
765         verify_ne!($actual, $expected)
766             .with_failure_message(|| format!($($format_args),*))
767             .and_log_failure();
768     }};
769     ($actual:expr, $expected:expr $(,)?) => {{
770         use $crate::GoogleTestSupport as _;
771         verify_ne!($actual, $expected).and_log_failure();
772     }};
773 }
774 
775 /// Checks whether the first argument is less than second argument.
776 ///
777 /// Evaluates to `Result::Ok(())` if the first argument is less than the second
778 /// and `Result::Err(TestAssertionFailure)` if it is greater or equal. The
779 /// caller must then decide how to handle the `Err` variant. It has a few
780 /// options:
781 ///  * Abort the current function with the `?` operator. This requires that the
782 ///    function return a suitable `Result`.
783 ///  * Log the test failure and continue by calling the method
784 ///    `and_log_failure`.
785 ///
786 /// Of course, one can also use all other standard methods on `Result`.
787 ///
788 /// **Invoking this macro by itself does not cause a test failure to be recorded
789 /// or output.** The resulting `Result` must be handled as described above to
790 /// cause the test to be recorded as a failure.
791 ///
792 /// Example:
793 /// ```ignore
794 /// use googletest::prelude::*;
795 ///
796 /// #[test]
797 /// fn should_fail() -> Result<()> {
798 ///     verify_lt!(2, 1)
799 /// }
800 #[macro_export]
801 macro_rules! verify_lt {
802     ($actual:expr, $expected:expr $(,)?) => {
803         verify_that!($actual, $crate::matchers::lt($expected))
804     };
805 }
806 
807 /// Marks test as failed and continues execution if the first argument is
808 /// greater or equal to second argument.
809 ///
810 /// This is a **not-fatal** failure. The test continues execution even after the
811 /// macro execution.
812 ///
813 /// This can only be invoked inside tests with the
814 /// [`gtest`][crate::gtest] attribute. The failure must be generated
815 /// in the same thread as that running the test itself.
816 ///
817 /// Example:
818 /// ```ignore
819 /// use googletest::prelude::*;
820 ///
821 /// #[gtest]
822 /// fn should_fail() {
823 ///     expect_lt!(2, 1);
824 ///     println!("This will print!");
825 /// }
826 /// ```
827 ///
828 /// One may include formatted arguments in the failure message:
829 ///```ignore
830 /// use googletest::prelude::*;
831 ///
832 /// #[gtest]
833 /// fn should_fail() {
834 ///     let argument = "argument"
835 ///     expect_lt!(1, 1, "custom failure message: {argument}");
836 ///     println!("This will print!");
837 /// }
838 /// ```
839 #[macro_export]
840 macro_rules! expect_lt {
841     ($actual:expr, $expected:expr, $($format_args:expr),+ $(,)?) => {{
842         use $crate::GoogleTestSupport as _;
843         verify_lt!($actual, $expected)
844             .with_failure_message(|| format!($($format_args),*))
845             .and_log_failure();
846     }};
847     ($actual:expr, $expected:expr $(,)?) => {{
848         use $crate::GoogleTestSupport as _;
849         verify_lt!($actual, $expected).and_log_failure();
850     }};
851 }
852 
853 /// Checks whether the first argument is less than or equal to the second
854 /// argument.
855 ///
856 /// Evaluates to `Result::Ok(())` if the first argument is less than or equal to
857 /// the second and `Result::Err(TestAssertionFailure)` if it is greater. The
858 /// caller must then decide how to handle the `Err` variant. It has a few
859 /// options:
860 ///  * Abort the current function with the `?` operator. This requires that the
861 ///    function return a suitable `Result`.
862 ///  * Log the test failure and continue by calling the method
863 ///    `and_log_failure`.
864 ///
865 /// Of course, one can also use all other standard methods on `Result`.
866 ///
867 /// **Invoking this macro by itself does not cause a test failure to be recorded
868 /// or output.** The resulting `Result` must be handled as described above to
869 /// cause the test to be recorded as a failure.
870 ///
871 /// Example:
872 /// ```ignore
873 /// use googletest::prelude::*;
874 ///
875 /// #[test]
876 /// fn should_fail() -> Result<()> {
877 ///     verify_le!(2, 1)
878 /// }
879 #[macro_export]
880 macro_rules! verify_le {
881     ($actual:expr, $expected:expr $(,)?) => {
882         verify_that!($actual, $crate::matchers::le($expected))
883     };
884 }
885 
886 /// Marks test as failed and continues execution if the first argument is
887 /// greater than the second argument.
888 ///
889 /// This is a **not-fatal** failure. The test continues execution even after the
890 /// macro execution.
891 ///
892 /// This can only be invoked inside tests with the
893 /// [`gtest`][crate::gtest] attribute. The failure must be generated
894 /// in the same thread as that running the test itself.
895 ///
896 /// Example:
897 /// ```ignore
898 /// use googletest::prelude::*;
899 ///
900 /// #[gtest]
901 /// fn should_fail() {
902 ///     expect_le!(2, 1);
903 ///     println!("This will print!");
904 /// }
905 /// ```
906 ///
907 /// One may include formatted arguments in the failure message:
908 ///```ignore
909 /// use googletest::prelude::*;
910 ///
911 /// #[gtest]
912 /// fn should_fail() {
913 ///     let argument = "argument"
914 ///     expect_le!(2, 1, "custom failure message: {argument}");
915 ///     println!("This will print!");
916 /// }
917 /// ```
918 #[macro_export]
919 macro_rules! expect_le {
920     ($actual:expr, $expected:expr, $($format_args:expr),+ $(,)?) => {{
921         use $crate::GoogleTestSupport as _;
922         verify_le!($actual, $expected)
923             .with_failure_message(|| format!($($format_args),*))
924             .and_log_failure();
925     }};
926     ($actual:expr, $expected:expr $(,)?) => {{
927         use $crate::GoogleTestSupport as _;
928         verify_le!($actual, $expected).and_log_failure();
929     }};
930 }
931 
932 /// Checks whether the first argument is greater than the second argument.
933 ///
934 /// Evaluates to `Result::Ok(())` if the first argument is greater than
935 /// the second and `Result::Err(TestAssertionFailure)` if it is not. The
936 /// caller must then decide how to handle the `Err` variant. It has a few
937 /// options:
938 ///  * Abort the current function with the `?` operator. This requires that the
939 ///    function return a suitable `Result`.
940 ///  * Log the test failure and continue by calling the method
941 ///    `and_log_failure`.
942 ///
943 /// Of course, one can also use all other standard methods on `Result`.
944 ///
945 /// **Invoking this macro by itself does not cause a test failure to be recorded
946 /// or output.** The resulting `Result` must be handled as described above to
947 /// cause the test to be recorded as a failure.
948 ///
949 /// Example:
950 /// ```ignore
951 /// use googletest::prelude::*;
952 ///
953 /// #[test]
954 /// fn should_fail() -> Result<()> {
955 ///     verify_gt!(1, 2)
956 /// }
957 #[macro_export]
958 macro_rules! verify_gt {
959     ($actual:expr, $expected:expr $(,)?) => {
960         verify_that!($actual, $crate::matchers::gt($expected))
961     };
962 }
963 
964 /// Marks test as failed and continues execution if the first argument is
965 /// not greater than the second argument.
966 ///
967 /// This is a **not-fatal** failure. The test continues execution even after the
968 /// macro execution.
969 ///
970 /// This can only be invoked inside tests with the
971 /// [`gtest`][crate::gtest] attribute. The failure must be generated
972 /// in the same thread as that running the test itself.
973 ///
974 /// Example:
975 /// ```ignore
976 /// use googletest::prelude::*;
977 ///
978 /// #[gtest]
979 /// fn should_fail() {
980 ///     expect_gt!(1, 2);
981 ///     println!("This will print!");
982 /// }
983 /// ```
984 ///
985 /// One may include formatted arguments in the failure message:
986 ///```ignore
987 /// use googletest::prelude::*;
988 ///
989 /// #[gtest]
990 /// fn should_fail() {
991 ///     let argument = "argument"
992 ///     expect_gt!(1, 2, "custom failure message: {argument}");
993 ///     println!("This will print!");
994 /// }
995 /// ```
996 #[macro_export]
997 macro_rules! expect_gt {
998     ($actual:expr, $expected:expr, $($format_args:expr),+ $(,)?) => {{
999         use $crate::GoogleTestSupport as _;
1000         verify_gt!($actual, $expected)
1001             .with_failure_message(|| format!($($format_args),*))
1002             .and_log_failure();
1003     }};
1004     ($actual:expr, $expected:expr $(,)?) => {{
1005         use $crate::GoogleTestSupport as _;
1006         verify_gt!($actual, $expected).and_log_failure();
1007     }};
1008 }
1009 
1010 /// Checks whether the first argument is greater than or equal to the second
1011 /// argument.
1012 ///
1013 /// Evaluates to `Result::Ok(())` if the first argument is greater than or equal
1014 /// to the second and `Result::Err(TestAssertionFailure)` if it is not. The
1015 /// caller must then decide how to handle the `Err` variant. It has a few
1016 /// options:
1017 ///  * Abort the current function with the `?` operator. This requires that the
1018 ///    function return a suitable `Result`.
1019 ///  * Log the test failure and continue by calling the method
1020 ///    `and_log_failure`.
1021 ///
1022 /// Of course, one can also use all other standard methods on `Result`.
1023 ///
1024 /// **Invoking this macro by itself does not cause a test failure to be recorded
1025 /// or output.** The resulting `Result` must be handled as described above to
1026 /// cause the test to be recorded as a failure.
1027 ///
1028 /// Example:
1029 /// ```ignore
1030 /// use googletest::prelude::*;
1031 ///
1032 /// #[test]
1033 /// fn should_fail() -> Result<()> {
1034 ///     verify_ge!(1, 2)
1035 /// }
1036 /// ```
1037 #[macro_export]
1038 macro_rules! verify_ge {
1039     ($actual:expr, $expected:expr $(,)?) => {
1040         verify_that!($actual, $crate::matchers::ge($expected))
1041     };
1042 }
1043 
1044 /// Marks test as failed and continues execution if the first argument is
1045 /// not greater than or equal to the second argument.
1046 ///
1047 /// This is a **not-fatal** failure. The test continues execution even after the
1048 /// macro execution.
1049 ///
1050 /// This can only be invoked inside tests with the
1051 /// [`gtest`][crate::gtest] attribute. The failure must be generated
1052 /// in the same thread as that running the test itself.
1053 ///
1054 /// Example:
1055 /// ```ignore
1056 /// use googletest::prelude::*;
1057 ///
1058 /// #[gtest]
1059 /// fn should_fail() {
1060 ///     expect_ge!(1, 2);
1061 ///     println!("This will print!");
1062 /// }
1063 /// ```
1064 ///
1065 /// One may include formatted arguments in the failure message:
1066 ///```ignore
1067 /// use googletest::prelude::*;
1068 ///
1069 /// #[gtest]
1070 /// fn should_fail() {
1071 ///     let argument = "argument"
1072 ///     expect_ge!(1, 2, "custom failure message: {argument}");
1073 ///     println!("This will print!");
1074 /// }
1075 /// ```
1076 #[macro_export]
1077 macro_rules! expect_ge {
1078     ($actual:expr, $expected:expr, $($format_args:expr),+ $(,)?) => {{
1079         use $crate::GoogleTestSupport as _;
1080         verify_ge!($actual, $expected)
1081             .with_failure_message(|| format!($($format_args),*))
1082             .and_log_failure();
1083     }};
1084     ($actual:expr, $expected:expr $(,)?) => {{
1085         use $crate::GoogleTestSupport as _;
1086         verify_ge!($actual, $expected).and_log_failure();
1087     }};
1088 }
1089 
1090 /// Checks whether the float given by first argument is approximately
1091 /// equal to second argument.
1092 ///
1093 /// This automatically computes a tolerance from the magnitude of `expected` and
1094 /// matches any actual value within this tolerance of the expected value. The
1095 /// tolerance is chosen to account for the inaccuracies in most ordinary
1096 /// floating point calculations. To see details of how the tolerance is
1097 /// calculated look at the implementation of
1098 /// [`googletest::approx_eq`][crate::matchers::approx_eq].
1099 ///
1100 /// Evaluates to `Result::Ok(())` if the first argument is approximately equal
1101 /// to the second and `Result::Err(TestAssertionFailure)` if it is not. The
1102 /// caller must then decide how to handle the `Err` variant. It has a few
1103 /// options:
1104 ///  * Abort the current function with the `?` operator. This requires that the
1105 ///    function return a suitable `Result`.
1106 ///  * Log the test failure and continue by calling the method
1107 ///    `and_log_failure`.
1108 ///
1109 /// Of course, one can also use all other standard methods on `Result`.
1110 ///
1111 /// **Invoking this macro by itself does not cause a test failure to be recorded
1112 /// or output.** The resulting `Result` must be handled as described above to
1113 /// cause the test to be recorded as a failure.
1114 ///
1115 /// Example:
1116 /// ```ignore
1117 /// use googletest::prelude::*;
1118 ///
1119 /// #[test]
1120 /// fn should_fail() -> Result<()> {
1121 ///     verify_float_eq!(1.0, 2.0)
1122 /// }
1123 /// ```
1124 #[macro_export]
1125 macro_rules! verify_float_eq {
1126     ($actual:expr, $expected:expr $(,)?) => {
1127         verify_that!($actual, $crate::matchers::approx_eq($expected))
1128     };
1129 }
1130 
1131 /// Marks test as failed and continues execution if the float given by the first
1132 /// argument is not approximately equal to the float given by the second
1133 /// argument.
1134 ///
1135 /// This automatically computes a tolerance from the magnitude of `expected` and
1136 /// matches any actual value within this tolerance of the expected value. The
1137 /// tolerance is chosen to account for the inaccuracies in most ordinary
1138 /// floating point calculations. To see details of how the tolerance is
1139 /// calculated look at the implementation of
1140 /// [`googletest::approx_eq`][crate::matchers::approx_eq].
1141 ///
1142 /// This is a **not-fatal** failure. The test continues execution even after the
1143 /// macro execution.
1144 ///
1145 /// This can only be invoked inside tests with the
1146 /// [`gtest`][crate::gtest] attribute. The failure must be generated
1147 /// in the same thread as that running the test itself.
1148 ///
1149 /// Example:
1150 /// ```ignore
1151 /// use googletest::prelude::*;
1152 ///
1153 /// #[gtest]
1154 /// fn should_fail() {
1155 ///     expect_float_eq!(1.0, 2.0);
1156 ///     println!("This will print!");
1157 /// }
1158 /// ```
1159 ///
1160 /// One may include formatted arguments in the failure message:
1161 ///```ignore
1162 /// use googletest::prelude::*;
1163 ///
1164 /// #[gtest]
1165 /// fn should_fail() {
1166 ///     let argument = "argument"
1167 ///     expect_float_eq!(1.0, 2.0, "custom failure message: {argument}");
1168 ///     println!("This will print!");
1169 /// }
1170 /// ```
1171 #[macro_export]
1172 macro_rules! expect_float_eq {
1173     ($actual:expr, $expected:expr, $($format_args:expr),+ $(,)?) => {{
1174         use $crate::GoogleTestSupport as _;
1175         verify_float_eq!($actual, $expected)
1176             .with_failure_message(|| format!($($format_args),*))
1177             .and_log_failure();
1178     }};
1179     ($actual:expr, $expected:expr $(,)?) => {{
1180         use $crate::GoogleTestSupport as _;
1181         verify_float_eq!($actual, $expected).and_log_failure();
1182     }};
1183 }
1184 
1185 /// Checks whether the float given by first argument is equal to second argument
1186 /// with error tolerance of max_abs_error.
1187 ///
1188 /// Evaluates to `Result::Ok(())` if the first argument is approximately equal
1189 /// to the second and `Result::Err(TestAssertionFailure)` if it is not. The
1190 /// caller must then decide how to handle the `Err` variant. It has a few
1191 /// options:
1192 ///  * Abort the current function with the `?` operator. This requires that the
1193 ///    function return a suitable `Result`.
1194 ///  * Log the test failure and continue by calling the method
1195 ///    `and_log_failure`.
1196 ///
1197 /// Of course, one can also use all other standard methods on `Result`.
1198 ///
1199 /// **Invoking this macro by itself does not cause a test failure to be recorded
1200 /// or output.** The resulting `Result` must be handled as described above to
1201 /// cause the test to be recorded as a failure.
1202 ///
1203 /// Example:
1204 /// ```ignore
1205 /// use googletest::prelude::*;
1206 ///
1207 /// #[test]
1208 /// fn should_fail() -> Result<()> {
1209 ///     verify_near!(1.12345, 1.12346, 1e-6)
1210 /// }
1211 /// ```
1212 #[macro_export]
1213 macro_rules! verify_near {
1214     ($actual:expr, $expected:expr, $max_abs_error:expr $(,)?) => {
1215         verify_that!($actual, $crate::matchers::near($expected, $max_abs_error))
1216     };
1217 }
1218 
1219 /// Marks the test as failed and continues execution if the float given by first
1220 /// argument is not equal to second argument with error tolerance of
1221 /// max_abs_error.
1222 ///
1223 /// This is a **not-fatal** failure. The test continues execution even after the
1224 /// macro execution.
1225 ///
1226 /// This can only be invoked inside tests with the
1227 /// [`gtest`][crate::gtest] attribute. The failure must be generated
1228 /// in the same thread as that running the test itself.
1229 ///
1230 /// Example:
1231 /// ```ignore
1232 /// use googletest::prelude::*;
1233 ///
1234 /// #[gtest]
1235 /// fn should_fail() {
1236 ///     expect_near!(1.12345, 1.12346, 1e-6);
1237 ///     println!("This will print!");
1238 /// }
1239 /// ```
1240 ///
1241 /// One may include formatted arguments in the failure message:
1242 ///```ignore
1243 /// use googletest::prelude::*;
1244 ///
1245 /// #[gtest]
1246 /// fn should_fail() {
1247 ///     let argument = "argument"
1248 ///     expect_near!(1.12345, 1.12346, 1e-6, "custom failure message: {argument}");
1249 ///     println!("This will print!");
1250 /// }
1251 /// ```
1252 #[macro_export]
1253 macro_rules! expect_near {
1254     ($actual:expr, $expected:expr, $max_abs_error:expr, $($format_args:expr),+ $(,)?) => {{
1255         use $crate::GoogleTestSupport as _;
1256         verify_near!($actual, $expected, $max_abs_error)
1257             .with_failure_message(|| format!($($format_args),*))
1258             .and_log_failure();
1259     }};
1260     ($actual:expr, $expected:expr, $max_abs_error:expr $(,)?) => {{
1261         use $crate::GoogleTestSupport as _;
1262         verify_near!($actual, $expected, $max_abs_error).and_log_failure();
1263     }};
1264 }
1265 
1266 /// Matches the given value against the given matcher, panicking if it does not
1267 /// match.
1268 ///
1269 /// ```should_panic
1270 /// # use googletest::prelude::*;
1271 /// # fn should_fail() {
1272 /// let value = 2;
1273 /// assert_that!(value, eq(3));  // Fails and panics.
1274 /// # }
1275 /// # should_fail();
1276 /// ```
1277 ///
1278 /// This is analogous to assertions in most Rust test libraries, where a failed
1279 /// assertion causes a panic.
1280 ///
1281 /// One may optionally add arguments which will be formatted and appended to a
1282 /// failure message. For example:
1283 ///
1284 /// ```should_panic
1285 /// # use googletest::prelude::*;
1286 /// # fn should_fail() {
1287 /// let value = 2;
1288 /// let extra_information = "Some additional information";
1289 /// assert_that!(value, eq(3), "Test failed. Extra information: {extra_information}.");
1290 /// # }
1291 /// # should_fail();
1292 /// ```
1293 ///
1294 /// This is output as follows:
1295 ///
1296 /// ```text
1297 /// Value of: value
1298 /// Expected: is equal to 3
1299 /// Actual: 2,
1300 ///   which isn't equal to 3
1301 ///   at ...
1302 /// Test failed. Extra information: Some additional information.
1303 /// ```
1304 ///
1305 /// **Note for users of [GoogleTest for C++](http://google.github.io/googletest/):**
1306 /// This differs from the `ASSERT_THAT` macro in that it panics rather
1307 /// than triggering an early return from the invoking function. To get behaviour
1308 /// equivalent to `ASSERT_THAT`, use [`verify_that!`] with the `?` operator.
1309 #[macro_export]
1310 macro_rules! assert_that {
1311     // specialized to sequence:
1312     ($actual:expr, [ $($expected:expr),* ] $(,)?) => {
1313         match $crate::verify_that!($actual, [ $($expected),* ]) {
1314             Ok(_) => {}
1315             Err(e) => {
1316                 // The extra newline before the assertion failure message makes the failure a
1317                 // bit easier to read when there's some generic boilerplate from the panic.
1318                 panic!("\n{}", e);
1319             }
1320         }
1321     };
1322 
1323     // specialized to unordered sequence
1324     ($actual:expr, { $($expected:expr),* } $(,)?) => {
1325         match $crate::verify_that!($actual, { $($expected),* }) {
1326             Ok(_) => {}
1327             Err(e) => {
1328                 // The extra newline before the assertion failure message makes the failure a
1329                 // bit easier to read when there's some generic boilerplate from the panic.
1330                 panic!("\n{}", e);
1331             }
1332         }
1333     };
1334 
1335     // w/ format args, specialized to sequence:
1336     ($actual:expr, [ $($expected:expr),* ], $($format_args:expr),* $(,)?) => {
1337         match $crate::verify_that!($actual, [ $($expected),* ])
1338             .with_failure_message(|| format!($($format_args),*))
1339         {
1340             Ok(_) => {}
1341             Err(e) => {
1342                 // The extra newline before the assertion failure message makes the failure a
1343                 // bit easier to read when there's some generic boilerplate from the panic.
1344                 panic!("\n{}", e);
1345             }
1346         }
1347     };
1348 
1349     // w/ format args, specialized to unordered sequence:
1350     ($actual:expr, { $($expected:expr),* }, $($format_args:expr),* $(,)?) => {
1351         match $crate::verify_that!($actual, { $($expected),* })
1352             .with_failure_message(|| format!($($format_args),*))
1353         {
1354             Ok(_) => {}
1355             Err(e) => {
1356                 // The extra newline before the assertion failure message makes the failure a
1357                 // bit easier to read when there's some generic boilerplate from the panic.
1358                 panic!("\n{}", e);
1359             }
1360         }
1361     };
1362 
1363     // general case:
1364     ($actual:expr, $expected:expr $(,)?) => {
1365         match $crate::verify_that!($actual, $expected) {
1366             Ok(_) => {}
1367             Err(e) => {
1368                 // The extra newline before the assertion failure message makes the failure a
1369                 // bit easier to read when there's some generic boilerplate from the panic.
1370                 panic!("\n{}", e);
1371             }
1372         }
1373     };
1374 
1375     // w/ format args, general case:
1376     ($actual:expr, $expected:expr, $($format_args:expr),* $(,)?) => {
1377         match $crate::verify_that!($actual, $expected)
1378             .with_failure_message(|| format!($($format_args),*))
1379         {
1380             Ok(_) => {}
1381             Err(e) => {
1382                 // The extra newline before the assertion failure message makes the failure a
1383                 // bit easier to read when there's some generic boilerplate from the panic.
1384                 panic!("\n{}", e);
1385             }
1386         }
1387     };
1388 }
1389 
1390 /// Asserts that the given predicate applied to the given arguments returns
1391 /// true, panicking if it does not.
1392 ///
1393 /// **Note for users of [GoogleTest for C++](http://google.github.io/googletest/):**
1394 /// This differs from the `ASSERT_PRED*` family of macros in that it panics
1395 /// rather than triggering an early return from the invoking function. To get
1396 /// behaviour equivalent to `ASSERT_PRED*`, use [`verify_pred!`] with the `?`
1397 /// operator.
1398 #[macro_export]
1399 macro_rules! assert_pred {
1400     ($($content:tt)*) => {
1401         match $crate::verify_pred!($($content)*) {
1402             Ok(_) => {}
1403             Err(e) => {
1404                 // The extra newline before the assertion failure message makes the failure a
1405                 // bit easier to read when there's some generic boilerplate from the panic.
1406                 panic!("\n{}", e);
1407             }
1408         }
1409     };
1410 }
1411 
1412 /// Matches the given value against the given matcher, marking the test as
1413 /// failed but continuing execution if it does not match.
1414 ///
1415 /// This is a *non-fatal* assertion: the test continues
1416 /// execution in the event of assertion failure.
1417 ///
1418 /// This can only be invoked inside tests with the
1419 /// [`gtest`][crate::gtest] attribute. The assertion must
1420 /// occur in the same thread as that running the test itself.
1421 ///
1422 /// Invoking this macro is equivalent to using
1423 /// [`and_log_failure`](crate::GoogleTestSupport::and_log_failure) as follows:
1424 ///
1425 /// ```ignore
1426 /// verify_that!(actual, expected).and_log_failure()
1427 /// ```
1428 ///
1429 /// One may optionally add arguments which will be formatted and appended to a
1430 /// failure message. For example:
1431 ///
1432 /// ```
1433 /// # use googletest::prelude::*;
1434 /// # fn should_fail() -> std::result::Result<(), googletest::internal::test_outcome::TestFailure> {
1435 /// # googletest::internal::test_outcome::TestOutcome::init_current_test_outcome();
1436 /// let value = 2;
1437 /// let extra_information = "Some additional information";
1438 /// expect_that!(value, eq(3), "Test failed. Extra information: {extra_information}.");
1439 /// # googletest::internal::test_outcome::TestOutcome::close_current_test_outcome::<&str>(Ok(()))
1440 /// # }
1441 /// # should_fail().unwrap_err();
1442 /// ```
1443 ///
1444 /// This is output as follows:
1445 ///
1446 /// ```text
1447 /// Value of: value
1448 /// Expected: is equal to 3
1449 /// Actual: 2,
1450 ///   which isn't equal to 3
1451 ///   at ...
1452 /// Test failed. Extra information: Some additional information.
1453 /// ```
1454 #[macro_export]
1455 macro_rules! expect_that {
1456     // specialized to sequence:
1457     ($actual:expr, [$($expected:expr),*] $(,)?) => {{
1458         use $crate::GoogleTestSupport as _;
1459         $crate::verify_that!($actual, [$($expected),*]).and_log_failure();
1460     }};
1461 
1462     // specialized to unordered sequence:
1463     ($actual:expr, {$($expected:expr),*} $(,)?) => {{
1464         use $crate::GoogleTestSupport as _;
1465         $crate::verify_that!($actual, {$($expected),*}).and_log_failure();
1466     }};
1467 
1468     // w/ format args, specialized to sequence:
1469     ($actual:expr, [$($expected:expr),*], $($format_args:expr),* $(,)?) => {
1470         use $crate::GoogleTestSupport as _;
1471         $crate::verify_that!($actual, [$($expected),*])
1472             .with_failure_message(|| format!($($format_args),*))
1473             .and_log_failure()
1474     };
1475 
1476     // w/ format args, specialized to unordered sequence:
1477     ($actual:expr, {$($expected:expr),*}, $($format_args:expr),* $(,)?) => {
1478         use $crate::GoogleTestSupport as _;
1479         $crate::verify_that!($actual, {$($expected),*})
1480             .with_failure_message(|| format!($($format_args),*))
1481             .and_log_failure()
1482     };
1483 
1484     // general case:
1485     ($actual:expr, $expected:expr $(,)?) => {{
1486         use $crate::GoogleTestSupport as _;
1487         $crate::verify_that!($actual, $expected).and_log_failure();
1488     }};
1489 
1490     // w/ format args, general case:
1491     ($actual:expr, $expected:expr, $($format_args:expr),* $(,)?) => {
1492         use $crate::GoogleTestSupport as _;
1493         $crate::verify_that!($actual, $expected)
1494             .with_failure_message(|| format!($($format_args),*))
1495             .and_log_failure()
1496     };
1497 }
1498 
1499 /// Asserts that the given predicate applied to the given arguments returns
1500 /// true, failing the test but continuing execution if not.
1501 ///
1502 /// This is a *non-fatal* predicate assertion: the test
1503 /// continues execution in the event of assertion failure.
1504 ///
1505 /// This can only be invoked inside tests with the
1506 /// [`gtest`][crate::gtest] attribute. The assertion must
1507 /// occur in the same thread as that running the test itself.
1508 ///
1509 /// Invoking this macro is equivalent to using
1510 /// [`and_log_failure`](crate::GoogleTestSupport::and_log_failure) as follows:
1511 ///
1512 /// ```ignore
1513 /// verify_pred!(predicate(...)).and_log_failure()
1514 /// ```
1515 #[macro_export]
1516 macro_rules! expect_pred {
1517     ($($content:tt)*) => {{
1518         use $crate::GoogleTestSupport as _;
1519         $crate::verify_pred!($($content)*).and_log_failure();
1520     }};
1521 }
1522 
1523 /// Functions for use only by the procedural macros in this module.
1524 ///
1525 /// **For internal use only. API stablility is not guaranteed!**
1526 #[doc(hidden)]
1527 pub mod internal {
1528     use crate::{
1529         internal::test_outcome::TestAssertionFailure,
1530         matcher::{create_assertion_failure, Matcher, MatcherResult},
1531     };
1532     use std::fmt::Debug;
1533 
1534     pub use ::googletest_macro::__googletest_macro_verify_pred;
1535 
1536     /// Extension trait to perform autoref through method lookup in the
1537     /// assertion macros. With this trait, the subject can be either a value
1538     /// or a reference. For example, this trait makes the following code
1539     /// compile and work:
1540     /// ```
1541     /// # use googletest::prelude::*;
1542     /// # fn would_not_compile_without_autoref() -> Result<()> {
1543     /// let not_copyable = vec![1,2,3];
1544     /// verify_that!(not_copyable, empty())?;
1545     /// # Ok(())
1546     /// # }
1547     /// ```
1548     /// See [Method Lookup](https://rustc-dev-guide.rust-lang.org/method-lookup.html)
1549     pub trait Subject: Copy + Debug {
1550         /// Checks whether the matcher `expected` matches the `Subject `self`,
1551         /// adding a test failure report if it does not match.
1552         ///
1553         /// Returns `Ok(())` if the value matches and `Err(_)` if it does not
1554         /// match.
1555         ///
1556         /// **For internal use only. API stablility is not guaranteed!**
1557         #[must_use = "The assertion result must be evaluated to affect the test result."]
1558         #[track_caller]
check( self, expected: impl Matcher<Self>, actual_expr: &'static str, ) -> Result<(), TestAssertionFailure>1559         fn check(
1560             self,
1561             expected: impl Matcher<Self>,
1562             actual_expr: &'static str,
1563         ) -> Result<(), TestAssertionFailure> {
1564             match expected.matches(self) {
1565                 MatcherResult::Match => Ok(()),
1566                 MatcherResult::NoMatch => {
1567                     Err(create_assertion_failure(&expected, self, actual_expr))
1568                 }
1569             }
1570         }
1571     }
1572 
1573     impl<T: Copy + Debug> Subject for T {}
1574 
1575     /// Creates a failure at specified location.
1576     ///
1577     /// **For internal use only. API stability is not guaranteed!**
1578     #[must_use = "The assertion result must be evaluated to affect the test result."]
1579     #[track_caller]
create_fail_result(message: String) -> crate::Result<()>1580     pub fn create_fail_result(message: String) -> crate::Result<()> {
1581         Err(crate::internal::test_outcome::TestAssertionFailure::create(message))
1582     }
1583 }
1584 
1585 #[cfg(test)]
1586 mod tests {
1587     use crate::prelude::*;
1588 
1589     #[test]
verify_of_hash_maps_with_str_string_matching() -> Result<()>1590     fn verify_of_hash_maps_with_str_string_matching() -> Result<()> {
1591         let hash_map: std::collections::HashMap<String, String> =
1592             std::collections::HashMap::from([("a".into(), "A".into()), ("b".into(), "B".into())]);
1593         verify_eq!(hash_map, {("a", "A"), ("b", "B")})
1594     }
1595 
1596     #[test]
verify_of_hash_maps_with_ad_hoc_struct() -> Result<()>1597     fn verify_of_hash_maps_with_ad_hoc_struct() -> Result<()> {
1598         #[derive(PartialEq, Debug)]
1599         struct Greek(String);
1600 
1601         let hash_map: std::collections::HashMap<String, Greek> = std::collections::HashMap::from([
1602             ("a".into(), Greek("Alpha".into())),
1603             ("b".into(), Greek("Beta".into())),
1604         ]);
1605         verify_eq!(hash_map, {
1606             ("b", Greek("Beta".into())),
1607             ("a", Greek("Alpha".into())),
1608         })
1609     }
1610 
1611     #[test]
verify_of_hash_maps_with_i32s() -> Result<()>1612     fn verify_of_hash_maps_with_i32s() -> Result<()> {
1613         let hash_map: std::collections::HashMap<i32, i32> =
1614             std::collections::HashMap::from([(1, 1), (2, 4), (-1, 1), (-3, 9)]);
1615         verify_eq!(hash_map, {
1616             (-3, 9),
1617             (-1, 1),
1618             (1, 1),
1619             (2, 4),
1620         })
1621     }
1622 
1623     #[test]
verify_eq_of_unordered_pairs() -> Result<()>1624     fn verify_eq_of_unordered_pairs() -> Result<()> {
1625         verify_eq!(vec![(1, 2), (2, 3)], {(1, 2), (2, 3)})?;
1626         verify_eq!(vec![(1, 2), (2, 3)], {(2, 3), (1, 2)})
1627     }
1628 
1629     #[test]
verify_eq_of_unordered_structs() -> Result<()>1630     fn verify_eq_of_unordered_structs() -> Result<()> {
1631         #[derive(PartialEq, Debug)]
1632         struct P(i32, i32);
1633 
1634         verify_eq!(vec![P(1, 1), P(1, 2), P(3, 7)],
1635                   {P(1, 1), P(1, 2), P(3, 7)})?;
1636         verify_eq!(vec![P(1, 1), P(1, 2), P(3, 7)],
1637                   {P(3,7), P(1, 1), P(1, 2)})
1638     }
1639 
1640     #[test]
verify_eq_of_ordered_pairs() -> Result<()>1641     fn verify_eq_of_ordered_pairs() -> Result<()> {
1642         verify_eq!(vec![(1, 2), (2, 3)], [(1, 2), (2, 3)])
1643     }
1644 
1645     #[test]
verify_eq_of_ordered_structs() -> Result<()>1646     fn verify_eq_of_ordered_structs() -> Result<()> {
1647         #[derive(PartialEq, Debug)]
1648         struct P(i32, i32);
1649 
1650         verify_eq!(vec![P(1, 1), P(1, 2), P(3, 7)], [P(1, 1), P(1, 2), P(3, 7)])
1651     }
1652 
1653     #[test]
verify_eq_of_ordered_pairs_order_matters() -> Result<()>1654     fn verify_eq_of_ordered_pairs_order_matters() -> Result<()> {
1655         let result = verify_eq!(vec![(1, 2), (2, 3)], [(2, 3), (1, 2)]);
1656         verify_that!(result, err(anything()))
1657     }
1658 
1659     #[test]
verify_eq_of_ordered_structs_order_matters() -> Result<()>1660     fn verify_eq_of_ordered_structs_order_matters() -> Result<()> {
1661         #[derive(PartialEq, Debug)]
1662         struct P(i32, i32);
1663 
1664         let result = verify_eq!(vec![P(1, 1), P(1, 2), P(3, 7)], [P(3, 7), P(1, 1), P(1, 2)]);
1665         verify_that!(result, err(anything()))
1666     }
1667 }
1668