googletest/
assertions.rs

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