Print counterexample finding report when a Rust fuzz test panics. PiperOrigin-RevId: 1017406397
diff --git a/rust/e2e_tests/BUILD b/rust/e2e_tests/BUILD index bc706bd..5a76fa5 100644 --- a/rust/e2e_tests/BUILD +++ b/rust/e2e_tests/BUILD
@@ -87,6 +87,7 @@ srcs = ["gtest_registration_test.rs"], data = [ "@com_google_fuzztest//rust/e2e_tests/testdata:fuzz_tests_as_gtests", + "@com_google_fuzztest//rust/e2e_tests/testdata:fuzztest_main", ], edition = "2024", deps = [
diff --git a/rust/e2e_tests/gtest_registration_test.rs b/rust/e2e_tests/gtest_registration_test.rs index d001a59..603ce13 100644 --- a/rust/e2e_tests/gtest_registration_test.rs +++ b/rust/e2e_tests/gtest_registration_test.rs
@@ -53,3 +53,29 @@ expect_that!(stdout, matchers::contains_substring("bool_fuzz_test property function ran...")); } + +#[gtest] +fn test_panicking_fuzztest_prints_finding_report_in_smoke_test(fixture: &EnvVars) { + let target_binary_path = fixture.binary_path("fuzztest_main"); + + let output = Command::new(&target_binary_path) + .arg("find_bug_fuzz_test") + .arg("--nocapture") + .output() + .expect("Failed to execute test binary"); + + expect_false!(output.status.success()); + + let stderr = String::from_utf8_lossy(&output.stderr); + expect_that!(stderr, matchers::contains_substring("=== BUG FOUND!")); + expect_that!( + stderr, + matchers::contains_substring( + "Counterexample found for fuzztest_main::__fuzztest_mod__find_bug_fuzz_test::find_bug_fuzz_test." + ) + ); + expect_that!( + stderr, + matchers::contains_substring("The test fails with input:\nargument 0: ") + ); +}
diff --git a/rust/e2e_tests/worker_with_centipede_test.rs b/rust/e2e_tests/worker_with_centipede_test.rs index a1c50ce..abfc8d5 100644 --- a/rust/e2e_tests/worker_with_centipede_test.rs +++ b/rust/e2e_tests/worker_with_centipede_test.rs
@@ -90,6 +90,17 @@ // that length, not any kind of hex-escaping. expect_that!(stderr, matchers::contains_regex("Input bytes[ \t]*: \\\\x5PaNiC")); expect_that!(stderr, matchers::contains_substring("CRASH LOG: Bug found!")); + expect_that!(stderr, matchers::contains_substring("CRASH LOG: === BUG FOUND!")); + expect_that!( + stderr, + matchers::contains_substring( + "Counterexample found for fuzztest_main::__fuzztest_mod__find_rarer_bug_fuzz_test::find_rarer_bug_fuzz_test." + ) + ); + expect_that!( + stderr, + matchers::contains_substring("CRASH LOG: argument 0: [80, 97, 78, 105, 67]") + ); } #[gtest] @@ -101,6 +112,9 @@ ); expect_that!(stderr, matchers::contains_substring("CRASH LOG: Bug found!")); + expect_that!(stderr, matchers::contains_substring("CRASH LOG: === BUG FOUND!")); + expect_that!(stderr, matchers::contains_substring("CRASH LOG: argument 0: [")); + expect_that!(stderr, matchers::contains_substring("CRASH LOG: argument 1: [42")); } #[gtest] @@ -112,6 +126,10 @@ ); expect_that!(stderr, matchers::contains_substring("CRASH LOG: Bug found!")); + expect_that!(stderr, matchers::contains_substring("CRASH LOG: === BUG FOUND!")); + expect_that!(stderr, matchers::contains_substring("CRASH LOG: argument 0: [")); + expect_that!(stderr, matchers::contains_substring("CRASH LOG: argument 1: -")); + expect_that!(stderr, matchers::contains_substring("CRASH LOG: argument 2: ")); } #[gtest]
diff --git a/rust/fuzztest_macro/src/helpers/test_registration.rs b/rust/fuzztest_macro/src/helpers/test_registration.rs index a17af8e..f0c0615 100644 --- a/rust/fuzztest_macro/src/helpers/test_registration.rs +++ b/rust/fuzztest_macro/src/helpers/test_registration.rs
@@ -245,18 +245,25 @@ .downcast_ref::<#domain_struct_name<#(#corpus_generics),*>>() .expect("Attempt to recover user value before testing failed."); - let user_value = self.domain.lock() - .expect("Failed to acquire domain lock") - .corpus_to_user_value(wrapper) - .expect("Failed to get user value from corpus value"); + let get_user_value = || { + self.domain.lock() + .expect("Failed to acquire domain lock") + .corpus_to_user_value(wrapper) + .expect("Failed to get user value from corpus value") + }; + let user_value = get_user_value(); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (self.test_fn)(#(user_value.#fuzz_test_domain_field_names),* ) )); + if result.is_err() { + let user_value = get_user_value(); + self.print_finding_report( + &FUZZTEST_INFO, + &[#(::std::format!("{:?}", user_value.#fuzz_test_domain_field_names)),*], + ); + } result.is_ok() } - fn print_finding_report(&self) { - todo!("Not implemented!") - } fn domains(&self) -> std::sync::Arc<std::sync::Mutex<dyn #crate_name::domains::GenericDomain>> { std::sync::Arc::clone(&self.domain) as std::sync::Arc<std::sync::Mutex<dyn #crate_name::domains::GenericDomain>> } @@ -324,18 +331,26 @@ .downcast_ref::<__FuzzTestTestFuzzStateWrapper<T0::CorpusValue, T1::CorpusValue>>() .expect("Attempt to recover user value before testing failed."); - let user_value = self.domain.lock() + let get_user_value = || { + self.domain.lock() .expect("Failed to acquire domain lock") .corpus_to_user_value(wrapper) - .expect("Failed to get user value from corpus value"); + .expect("Failed to get user value from corpus value") + }; + // Safety: Data is not reused after the test. + let user_value = get_user_value(); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (self.test_fn)(user_value.a, user_value.b) )); + if result.is_err() { + let user_value = get_user_value(); + self.print_finding_report( + &FUZZTEST_INFO, + &[::std::format!("{:?}", user_value.a), ::std::format!("{:?}", user_value.b)], + ); + } result.is_ok() } - fn print_finding_report(&self) { - todo!("Not implemented!") - } fn domains(&self) -> std::sync::Arc<std::sync::Mutex<dyn ::fuzztest::domains::GenericDomain>> { std::sync::Arc::clone(&self.domain) as std::sync::Arc<std::sync::Mutex<dyn ::fuzztest::domains::GenericDomain>> }
diff --git a/rust/fuzztest_macro/src/lib.rs b/rust/fuzztest_macro/src/lib.rs index d51935a..8f96025 100644 --- a/rust/fuzztest_macro/src/lib.rs +++ b/rust/fuzztest_macro/src/lib.rs
@@ -59,7 +59,6 @@ /// } /// ``` /// ``` -/// #[proc_macro_attribute] pub fn fuzztest(args: TokenStream, input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as Item); @@ -71,8 +70,8 @@ let original_ident = test_fn.sig.ident.clone(); let fuzztest_name = original_ident.to_string(); - // TODO(mathuxny-73): Support the case where there are no arguments. Probably we should return an error - // in this case as it may not make sense to have a FuzzTest without input. + // TODO(mathuxny-73): Support the case where there are no arguments. Probably we should return + // an error in this case as it may not make sense to have a FuzzTest without input. let args = syn::punctuated::Punctuated::<FuzzTestArg, syn::Token![,]>::parse_terminated.parse(args); @@ -118,16 +117,17 @@ use super::#original_ident as #prop_fn_ident; - #fuzztest_object_tokenstream - - const _: () = { - static FUZZTEST_INFO: ::fuzztest::internal::FuzzTestInfo = + static FUZZTEST_INFO: ::fuzztest::internal::FuzzTestInfo = ::fuzztest::internal::FuzzTestInfo { name: #fuzztest_name, + module_path: module_path!(), file: file!(), line: line!(), }; + #fuzztest_object_tokenstream + + const _: () = { ::fuzztest::reexports::inventory::submit! { ::fuzztest::internal::FuzzTestRegistration { info: &FUZZTEST_INFO,
diff --git a/rust/src/internal.rs b/rust/src/internal.rs index 5f7e95b..ee1963a 100644 --- a/rust/src/internal.rs +++ b/rust/src/internal.rs
@@ -14,12 +14,15 @@ use super::domains::GenericCorpusValue; use super::domains::GenericDomain; - use std::collections::HashMap; +use std::fmt::Write; use std::sync::Arc; use std::sync::LazyLock; use std::sync::Mutex; +const REPORT_SEPARATOR: &str = "================================================================="; +const VALUE_MAX_PRINT_LENGTH: usize = 2048; + /// A trait implemented by types used to Fuzz a given property function. /// /// When a test is annotated with the `fuzztest` macro attribute, that test will be wrapped in a @@ -37,8 +40,12 @@ /// /// Returns `true` if the property function holds, `false` if it crashes. fn execute(&self, args: &GenericCorpusValue) -> bool; - fn print_finding_report(&self); fn domains(&self) -> Arc<Mutex<dyn GenericDomain>>; + + /// Formats and prints the counterexample finding report for `formatted_args` to `stderr`. + fn print_finding_report(&self, info: &FuzzTestInfo, formatted_args: &[String]) { + print_finding_report(info, formatted_args); + } } /// Identifies the property function of a fuzz test. @@ -47,10 +54,53 @@ /// appropriate values. pub struct FuzzTestInfo { pub name: &'static str, + pub module_path: &'static str, pub file: &'static str, pub line: u32, } +impl FuzzTestInfo { + /// Returns the fully qualified test name (e.g., + /// `escaping_test::__fuzztest_mod__unescaping_never_panics::unescaping_never_panics`). + fn full_test_name(&self) -> String { + format!("{}::{}", self.module_path, self.name) + } +} + +/// Formats the `=== BUG FOUND!` finding report block for the given fuzz test and formatted +/// arguments, truncating any argument that exceeds `VALUE_MAX_PRINT_LENGTH` bytes. +fn format_finding_report(info: &FuzzTestInfo, formatted_args: &[String]) -> String { + let mut out = String::new(); + let _ = writeln!(out, "\n{REPORT_SEPARATOR}"); + let _ = writeln!(out, "=== BUG FOUND!\n"); + let _ = writeln!( + out, + "{}:{}: Counterexample found for {}.", + info.file, + info.line, + info.full_test_name() + ); + let _ = writeln!(out, "The test fails with input:"); + for (idx, arg) in formatted_args.iter().enumerate() { + if arg.len() > VALUE_MAX_PRINT_LENGTH { + let mut end = VALUE_MAX_PRINT_LENGTH; + while !arg.is_char_boundary(end) { + end -= 1; + } + let _ = writeln!(out, "argument {idx}: {} ...<value too long>", &arg[..end]); + } else { + let _ = writeln!(out, "argument {idx}: {arg}"); + } + } + let _ = writeln!(out, "\n{REPORT_SEPARATOR}"); + out +} + +/// Prints the `=== BUG FOUND!` finding report block to `stderr`. +fn print_finding_report(info: &FuzzTestInfo, formatted_args: &[String]) { + eprint!("{}", format_finding_report(info, formatted_args)); +} + pub type BoxedFuzzTest = Box<dyn FuzzTest + Send + Sync>; pub struct FuzzTestRegistration { @@ -73,3 +123,60 @@ pub input_state: Option<I>, pub domain: D, } + +#[cfg(test)] +mod tests { + use super::*; + use googletest::prelude::*; + + #[googletest::test] + fn test_full_test_name_includes_crate_and_module_path() { + let info = FuzzTestInfo { + name: "unescaping_never_panics", + module_path: "escaping_test::__fuzztest_mod__unescaping_never_panics", + file: "third_party/googlefuzztest/rust/codelab/escaping_test.rs", + line: 72, + }; + expect_that!( + info.full_test_name(), + eq("escaping_test::__fuzztest_mod__unescaping_never_panics::unescaping_never_panics") + ); + } + + #[googletest::test] + fn test_format_finding_report_matches_expected_format() { + let info = FuzzTestInfo { + name: "test_name", + module_path: "crate_name::module_name", + file: "FILE", + line: 123, + }; + let args = vec![format!("{:?}", 17), format!("{:?}", "ABC")]; + let report = format_finding_report(&info, &args); + expect_that!( + report, + eq(concat!( + "\n=================================================================\n", + "=== BUG FOUND!\n\n", + "FILE:123: Counterexample found for crate_name::module_name::test_name.\n", + "The test fails with input:\n", + "argument 0: 17\n", + "argument 1: \"ABC\"\n\n", + "=================================================================\n", + )) + ); + } + + #[googletest::test] + fn test_format_finding_report_truncates_long_values_at_char_boundary() { + let info = FuzzTestInfo { + name: "test_name", + module_path: "crate_name::module_name", + file: "FILE", + line: 123, + }; + let long_str = "é".repeat(1500); + let report = format_finding_report(&info, &[long_str]); + expect_that!(report, contains_substring(" ...<value too long>\n")); + } +}