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