Compare commits

...

3 Commits

Author SHA1 Message Date
Manikandan K S
dfd342e8da
Merge f626ec47020aec8baa5d2a6a8546d53a6b3db8af into a0f06a70e3da7afa88da9527c43951bca1f7cef2 2026-07-29 15:06:03 -04:00
Abseil Team
a0f06a70e3 Make GoogleTest handle std::monostate and valueless_by_exception() for std::variant similarly to how it handles std::nullopt
Fixes: #2066
PiperOrigin-RevId: 955981465
Change-Id: I6b34dc2e634d4b727a50fb3e21e5d8e25c39a13b
2026-07-29 11:08:13 -07:00
Manikandan K. S.
f626ec4702 fix: avoid double invocation of side-effecting matchers in PredicateFormatterFromMatcher
EXPECT_THAT with Throws<E>() previously invoked the callable twice on
failure: once in Matches() and again in MatchPrintAndExplain() when
formatting the diagnostic message. This caused issues with stateful or
side-effecting callables.

Fix: call MatchAndExplain() once with an interested listener, capture
the result and explanation, then manually format the failure message
using UniversalPrint() + type info + listener explanation.

BREAKING CHANGE: PredicateFormatterFromMatcher no longer detects flaky
matchers that change their result based on IsInterested(). This only
affects pathological matchers; real matchers return consistent results
regardless of listener interest.

Fixes #4073
2026-07-26 00:51:45 +05:30
5 changed files with 80 additions and 45 deletions

View File

@ -1719,9 +1719,13 @@ class [[nodiscard]] PredicateFormatterFromMatcher {
// potentially unsafe downcasting of the matcher argument.
const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
// The expected path here is that the matcher should match (i.e. that most
// tests pass) so optimize for this case.
if (matcher.Matches(x)) {
// Capture the explanation during the initial match attempt so that
// side-effecting matchers (like Throws) are not invoked a second time
// when formatting the failure message.
StringMatchResultListener listener;
const bool matches = matcher.MatchAndExplain(x, &listener);
if (matches) {
return AssertionSuccess();
}
@ -1729,14 +1733,15 @@ class [[nodiscard]] PredicateFormatterFromMatcher {
ss << "Value of: " << value_text << "\n"
<< "Expected: ";
matcher.DescribeTo(&ss);
// Rerun the matcher to "PrintAndExplain" the failure.
StringMatchResultListener listener;
if (MatchPrintAndExplain(x, matcher, &listener)) {
ss << "\n The matcher failed on the initial attempt; but passed when "
"rerun to generate the explanation.";
ss << "\n Actual: ";
UniversalPrint(x, &ss);
#if GTEST_HAS_RTTI
{
const std::string& type_name = GetTypeName<T>();
if (IsReadableTypeName(type_name)) ss << " (of type " << type_name << ")";
}
ss << "\n Actual: " << listener.str();
#endif
PrintIfNotEmpty(listener.str(), &ss);
return AssertionFailure() << ss.str();
}

View File

@ -2805,9 +2805,6 @@ class PredicateFormatterFromMatcherTest : public ::testing::Test {
protected:
enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
// A matcher that can return different results when used multiple times on the
// same input. No real matcher should do this; but this lets us test that we
// detect such behavior and fail appropriately.
class MockMatcher : public MatcherInterface<Behavior> {
public:
bool MatchAndExplain(Behavior behavior,
@ -2815,20 +2812,11 @@ class PredicateFormatterFromMatcherTest : public ::testing::Test {
*listener << "[MatchAndExplain]";
switch (behavior) {
case kInitialSuccess:
// The first call to MatchAndExplain should use a "not interested"
// listener; so this is expected to return |true|. There should be no
// subsequent calls.
return !listener->IsInterested();
return true;
case kAlwaysFail:
return false;
case kFlaky:
// The first call to MatchAndExplain should use a "not interested"
// listener; so this will return |false|. Subsequent calls should have
// an "interested" listener; so this will return |true|, thus
// simulating a flaky matcher.
return listener->IsInterested();
return false;
}
GTEST_LOG_(FATAL) << "This should never be reached";
@ -2867,13 +2855,11 @@ TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
EXPECT_EQ(expect, result.message());
}
TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
TEST_F(PredicateFormatterFromMatcherTest, AlwaysFails) {
AssertionResult result = RunPredicateFormatter(kFlaky);
EXPECT_FALSE(result); // Implicit cast to bool.
std::string expect =
"Value of: dummy-name\nExpected: [DescribeTo]\n"
" The matcher failed on the initial attempt; but passed when rerun to "
"generate the explanation.\n"
" Actual: 2" +
OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
EXPECT_EQ(expect, result.message());

View File

@ -1754,6 +1754,19 @@ TEST(ThrowsTest, CallableExecutedExactlyOnce) {
EXPECT_EQ(a, 4u);
}
TEST(ThrowsTest, EvaluatesCallableOnlyOnceOnFailure) {
int call_count = 0;
auto stateful_lambda = [&call_count]() {
++call_count;
};
EXPECT_NONFATAL_FAILURE(
EXPECT_THAT(stateful_lambda, Throws<std::runtime_error>()),
"does not throw any exception");
EXPECT_EQ(call_count, 1);
}
TEST(ThrowsTest, Describe) {
Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
std::stringstream ss;

View File

@ -945,13 +945,13 @@ template <typename T>
class [[nodiscard]] UniversalPrinter<std::optional<T>> {
public:
static void Print(const std::optional<T>& value, ::std::ostream* os) {
*os << '(';
if (!value) {
*os << "nullopt";
UniversalPrint(std::nullopt, os);
} else {
*os << '(';
UniversalPrint(*value, os);
*os << ')';
}
*os << ')';
}
};
@ -961,27 +961,38 @@ class [[nodiscard]] UniversalPrinter<std::nullopt_t> {
static void Print(std::nullopt_t, ::std::ostream* os) { *os << "(nullopt)"; }
};
struct UniversalPrinterVisitor {
template <typename T>
void operator()(const T& arg) const {
*os << "'" << GetTypeName<T>() << "(index = " << index << ")' with value ";
UniversalPrint(arg, os);
}
::std::ostream* os;
std::size_t index;
};
// Printer for std::variant
template <typename... T>
class [[nodiscard]] UniversalPrinter<std::variant<T...>> {
public:
static void Print(const std::variant<T...>& value, ::std::ostream* os) {
*os << '(';
std::visit(Visitor{os, value.index()}, value);
*os << ')';
}
private:
struct Visitor {
template <typename U>
void operator()(const U& u) const {
*os << "'" << GetTypeName<U>() << "(index = " << index
<< ")' with value ";
UniversalPrint(u, os);
if (value.valueless_by_exception()) {
*os << "(valueless)";
} else {
*os << '(';
std::visit(UniversalPrinterVisitor{os, value.index()}, value);
*os << ')';
}
::std::ostream* os;
std::size_t index;
};
}
};
// Printer for std::monostate
template <>
class [[nodiscard]] UniversalPrinter<std::monostate> {
public:
static void Print(std::monostate, ::std::ostream* os) {
*os << "(monostate)";
}
};
// UniversalPrintArray(begin, len, os) prints an array of 'len'

View File

@ -2030,6 +2030,26 @@ TEST(PrintOneofTest, Basic) {
PrintToString(Type(NonPrintable{})));
}
TEST(PrintVariantTest, Monostate) {
EXPECT_EQ("(monostate)", PrintToString(std::monostate()));
#if GTEST_HAS_EXCEPTIONS
struct ThrowOnMove {
ThrowOnMove() = default;
ThrowOnMove(ThrowOnMove&& other) { *this = std::move(other); }
ThrowOnMove& operator=(ThrowOnMove&&) {
(void)std::vector<bool>().at(0);
return *this;
}
};
std::variant<std::monostate, ThrowOnMove> v = std::monostate();
EXPECT_EQ("('std::monostate(index = 0)' with value (monostate))",
PrintToString(v));
EXPECT_THROW(v = ThrowOnMove(), std::out_of_range);
EXPECT_EQ("(valueless)", PrintToString(v));
#endif
}
#if GTEST_INTERNAL_HAS_COMPARE_LIB
TEST(PrintOrderingTest, Basic) {
EXPECT_EQ("(less)", PrintToString(std::strong_ordering::less));