Compare commits

...

6 Commits

Author SHA1 Message Date
Manikandan K S
2988866b9b
Merge f626ec47020aec8baa5d2a6a8546d53a6b3db8af into 3ff51c3e80f2c2eb105d43ecb9acab9a62e01600 2026-07-28 16:28:53 -04:00
Copybara-Service
3ff51c3e80 Merge pull request #5041 from alvinjaison:fix/get-test-suite-shuffle-index
PiperOrigin-RevId: 955317170
Change-Id: I40e01cdafe58768ccdb743dcf38717e48edcde41
2026-07-28 09:58:12 -07:00
Abseil Team
c6f04243ed Automated Code Change
PiperOrigin-RevId: 955021426
Change-Id: I3ab06e960011d1d0cd44ea00595a5067aaa7f30b
2026-07-27 22:07:28 -07:00
Abseil Team
af4c3cfcb3 Automated Code Change
PiperOrigin-RevId: 955017590
Change-Id: I5125f56376603462fb63796fec1fbc50fd4d935f
2026-07-27 21:57:20 -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
Alvin Jaison
1269db9643 Fix GetTestSuite(i) ignoring shuffle order UnitTestImpl::GetTestSuite(int i) computes the shuffled index from test_suite_indices_ but then accesses test_suites_ using the raw parameter 'i' instead of the computed 'index'. This causes the public API UnitTest::GetTestSuite(i) to return test suites in original registration order rather than the active shuffle order. The mutable variant GetMutableSuiteCase(i) correctly uses 'index', and the equivalent function TestSuite::GetTestInfo(i) also uses 'index'. This was a copy-paste typo introduced in commit bd851333 (Sep 2009) when the shuffle feature was first added. The bug is observable from within TestEventListener callbacks during test execution when --gtest_shuffle is active. 2026-07-24 16:11:55 +01:00
10 changed files with 47 additions and 40 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

@ -39,6 +39,8 @@
#include "sample2.h"
#include <iterator>
#include "gtest/gtest.h"
namespace {
// In this example, we test the MyString class (a simple string).
@ -78,7 +80,7 @@ const char kHelloString[] = "Hello, world!";
TEST(MyString, ConstructorFromCString) {
const MyString s(kHelloString);
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
EXPECT_EQ(sizeof(kHelloString) / sizeof(kHelloString[0]) - 1, s.Length());
EXPECT_EQ(std::size(kHelloString) - 1, s.Length());
}
// Tests the copy c'tor.

View File

@ -587,7 +587,7 @@ class GTEST_API_ UnitTestImpl {
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
const TestSuite* GetTestSuite(int i) const {
const int index = GetElementOr(test_suite_indices_, i, -1);
return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];
return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];
}
// Legacy API is deprecated but still available

View File

@ -32,6 +32,7 @@
// This file verifies Google Test event listeners receive events at the
// right times.
#include <iterator>
#include <string>
#include <vector>
@ -498,8 +499,7 @@ int main(int argc, char** argv) {
"1st.OnTestProgramEnd"};
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
VerifyResults(events, expected_events,
sizeof(expected_events) / sizeof(expected_events[0]));
VerifyResults(events, expected_events, std::size(expected_events));
// We need to check manually for ad hoc test failures that happen after
// RUN_ALL_TESTS finishes.

View File

@ -36,6 +36,7 @@
#include <stdlib.h>
#include <algorithm>
#include <iterator>
#include <string>
#include "gtest/gtest-spi.h"
@ -149,7 +150,7 @@ TEST(LoggingTest, InterleavingLoggingAndAssertions) {
static const int a[4] = {3, 9, 2, 6};
printf("(expecting 2 failures on (3) >= (a[i]))\n");
for (int i = 0; i < static_cast<int>(sizeof(a) / sizeof(*a)); i++) {
for (int i = 0; i < static_cast<int>(std::size(a)); i++) {
printf("i == %d\n", i);
EXPECT_GE(3, a[i]);
}

View File

@ -39,6 +39,7 @@
#include <cstdint>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <set>
#include <sstream>
@ -737,10 +738,7 @@ const int test_generation_params[] = {36, 42, 72};
class TestGenerationTest : public TestWithParam<int> {
public:
enum {
PARAMETER_COUNT =
sizeof(test_generation_params) / sizeof(test_generation_params[0])
};
enum { PARAMETER_COUNT = std::size(test_generation_params) };
typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;

View File

@ -39,6 +39,7 @@
#include <deque>
#include <forward_list>
#include <functional>
#include <iterator>
#include <limits>
#include <list>
#include <map>
@ -1784,7 +1785,7 @@ TEST(IsValidUTF8Test, IllFormedUTF8) {
// too.
{"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n As Text: \"\""}};
for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) {
for (int i = 0; i < int(std::size(kTestdata)); ++i) {
EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
}
}

View File

@ -33,6 +33,8 @@
#include "gtest/gtest.h"
#include <iterator>
// Verifies that the command line flag variables can be accessed in
// code once "gtest.h" has been #included.
// Do not move it after other gtest #includes.
@ -5853,9 +5855,8 @@ class ParseFlagsTest : public Test {
// to specify the array sizes.
#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
TestParsingFlags(sizeof(argv1) / sizeof(*argv1) - 1, argv1, \
sizeof(argv2) / sizeof(*argv2) - 1, argv2, expected, \
should_print_help)
TestParsingFlags(std::size(argv1) - 1, argv1, std::size(argv2) - 1, argv2, \
expected, should_print_help)
};
// Tests parsing an empty command line.