Skip to content

Commit 8c3406c

Browse files
hovinenbcopybara-github
authored andcommitted
Add #[must_use] attributes to the output of the verify_* and fail macros.
This causes a compiler to output a warning if the results of those macros are ignored. Doing so is syntactically valid but almost certainly indicates a programming error, since the test assertion result is thrown away rather than being evaluated. See also https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute. PiperOrigin-RevId: 503966328
1 parent 9c50b57 commit 8c3406c

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

googletest/src/assertions.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -182,11 +182,11 @@ macro_rules! verify_pred {
182182
/// [`and_log_failure`](crate::GoogleTestSupport::and_log_failure).
183183
#[macro_export]
184184
macro_rules! fail {
185-
($($message:expr),+) => {
186-
// Put this in an if block to instruct the compiler what both branches of the Result are.
187-
// Otherwise the compiler complains that it does not know the full type of the expression
188-
// result.
189-
if true {
185+
($($message:expr),+) => {{
186+
// We wrap this in a function so that we can annotate it with the must_use attribute.
187+
// must_use on expressions is still experimental.
188+
#[must_use = "The assertion result must be evaluated to affect the test result."]
189+
fn create_fail_result() -> $crate::Result<()> {
190190
Err($crate::internal::test_outcome::TestAssertionFailure::create(format!(
191191
"{}\n{}",
192192
format!($($message),*),
@@ -196,10 +196,9 @@ macro_rules! fail {
196196
column!(),
197197
),
198198
)))
199-
} else {
200-
Ok(())
201199
}
202-
};
200+
create_fail_result()
201+
}};
203202

204203
() => { fail!("Test failed") };
205204
}
@@ -305,6 +304,7 @@ pub mod internal {
305304
/// match.
306305
///
307306
/// **For internal use only. API stablility is not guaranteed!**
307+
#[must_use = "The assertion result must be evaluated to affect the test result."]
308308
pub fn check_matcher<T: Debug + ?Sized>(
309309
actual: &T,
310310
expected: impl Matcher<T>,
@@ -325,6 +325,7 @@ pub mod internal {
325325
/// This intended only for use by the macro [`crate::verify_pred`].
326326
///
327327
/// **For internal use only. API stablility is not guaranteed!**
328+
#[must_use = "The assertion result must be evaluated to affect the test result."]
328329
pub fn report_failed_predicate(
329330
actual_expr: &'static str,
330331
formatted_arguments: Vec<String>,

0 commit comments

Comments
 (0)