Compare commits

...

8 Commits

Author SHA1 Message Date
strager
01eb661b43
Merge dd45329f01818ae7eb5fd637a9d5d325edc96c98 into 3ff51c3e80f2c2eb105d43ecb9acab9a62e01600 2026-07-29 14:14:06 +12: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
Abseil Team
ecb18f0b03 Automated Code Change
PiperOrigin-RevId: 955003621
Change-Id: I83518a7f947d9f7d9b89fe14e1219d32bcdc95a3
2026-07-27 21:17:32 -07:00
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
Matthew Glazar
dd45329f01 Print stacktraces using std::stacktrace if available
If std::stacktrace is available (currently only GCC (opt-in feature) and
MSVC), use it for printing stack traces.

If both Abseil and std::stacktrace are available, prefer
std::stacktrace.

Advantages of std::stacktrace over Abseil:

* Includes file and line information
* Includes DLL information
* Better stack trace quality on Windows

Disadvantages of std::stacktrace compared to Abseil:

* Runs more slowly on Windows
* Includes information which might not be relevant such as byte offsets
* Printed lines are longer thus harder to skim

Before (Windows using Abseil):

    [ RUN      ] FooTest.Xyz
    [snip]\googletest-filter-unittest_.cc(49): error: Failed
    Expected failure.
    Stack trace:
      00007FF69EF90E8D: testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test,void>
      00007FF69EF90AC3: testing::internal::HandleExceptionsInMethodIfSupported<testing::Test,void>
      00007FF69EF5C01B: testing::Test::Run
      00007FF69EF5CCC5: testing::TestInfo::Run
      00007FF69EF5D6EC: testing::TestSuite::Run
    ... Google Test internal frames ...

    [  FAILED  ] FooTest.Xyz (21 ms)

After (Windows using MSVC STL's std::stacktrace):

    [ RUN      ] FooTest.Xyz
    [snip]\googletest-filter-unittest_.cc(49): error: Failed
    Expected failure.
    Stack trace:
      00007FF6770283A9: googletest_filter_unittest_!`anonymous namespace'::FooTest_Xyz_Test::TestBody+0x89 [snip]\googletest-filter-unittest_.cc:49
      00007FF677080E8D: googletest_filter_unittest_!testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test,void>+0x1D [snip]\gtest.cc:2609
      00007FF677080AC3: googletest_filter_unittest_!testing::internal::HandleExceptionsInMethodIfSupported<testing::Test,void>+0x73 [snip]\gtest.cc:2652
      00007FF67704C01B: googletest_filter_unittest_!testing::Test::Run+0xAB [snip]\gtest.cc:2698
    ... Google Test internal frames ...

    [  FAILED  ] FooTest.Xyz (127 ms)
2023-08-09 21:03:33 -07:00
Matthew Glazar
8aaea6c092 Split OsStackTraceGetter into AbslStackTraceGetter + NoopStackTraceGetter
The OsStackTraceGetter class does different things depending on whether
GTEST_HAS_ABSL is set. I want to add another implementation of
OsStackTraceGetter, and I think it's ugly if my new implementation
litters OsStackTraceGetter with more #if-s.

Split OsStackTraceGetter into two different classes:

* AbslStackTraceGetter, which is only defined if GTEST_HAS_ABSL is set.
  This class behaves the same as OsStackTraceGetter currently behaves.
* NoopStackTraceGetter, which is always defined. This class behaves the
  same as OsStackTraceGetter currently behaves if GTEST_HAS_ABSL is not
  set.

After this refactor, it is easier to add new OsStackTraceGetter
backend classes.
2023-08-09 21:03:33 -07:00
10 changed files with 158 additions and 36 deletions

View File

@ -30,6 +30,8 @@
// Tests that Google Mock constructs can be used in a large number of
// threads concurrently.
#include <iterator>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
@ -188,7 +190,7 @@ TEST(StressTest, CanUseGMockWithThreads) {
&TestPartiallyOrderedExpectationsWithThreads,
};
const int kRoutines = sizeof(test_routines) / sizeof(test_routines[0]);
const int kRoutines = std::size(test_routines);
const int kCopiesOfEachRoutine = kMaxTestThreads / kRoutines;
const int kTestThreads = kCopiesOfEachRoutine * kRoutines;
ThreadWithParam<Dummy>* threads[kTestThreads] = {};

View File

@ -202,6 +202,7 @@
// specializations. Always defined to 0 or 1
// GTEST_USE_OWN_FLAGFILE_FLAG_ - Always defined to 0 or 1.
// GTEST_HAS_CXXABI_H_ - Always defined to 0 or 1.
// GTEST_HAS_STD_STACKTRACE_ - Always defined to 0 or 1.
// GTEST_CAN_STREAM_RESULTS_ - Always defined to 0 or 1.
// GTEST_HAS_ALT_PATH_SEP_ - Always defined to 0 or 1.
// GTEST_WIDE_STRING_USES_UTF16_ - Always defined to 0 or 1.
@ -887,6 +888,14 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#endif
#endif
#if !defined(GTEST_HAS_STD_STACKTRACE_)
#if defined(__cpp_lib_stacktrace) && __cpp_lib_stacktrace >= 202011L
#define GTEST_HAS_STD_STACKTRACE_ 1
#else
#define GTEST_HAS_STD_STACKTRACE_ 0
#endif
#endif
// A function level attribute to disable checking for use of uninitialized
// memory when built with MemorySanitizer.
#if GTEST_HAVE_ATTRIBUTE_(no_sanitize_memory)

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

@ -60,6 +60,10 @@
#include <windows.h> // NOLINT
#endif // GTEST_OS_WINDOWS
#if GTEST_HAS_STD_STACKTRACE_
#include <stacktrace>
#endif
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
@ -431,16 +435,16 @@ class OsStackTraceGetterInterface {
delete;
};
#ifdef GTEST_HAS_ABSL
// A working implementation of the OsStackTraceGetterInterface interface.
class OsStackTraceGetter : public OsStackTraceGetterInterface {
class AbslStackTraceGetter : public OsStackTraceGetterInterface {
public:
OsStackTraceGetter() = default;
AbslStackTraceGetter() = default;
std::string CurrentStackTrace(int max_depth, int skip_count) override;
void UponLeavingGTest() override;
private:
#ifdef GTEST_HAS_ABSL
Mutex mutex_; // Protects all internal state.
// We save the stack frame below the frame that calls user code.
@ -448,10 +452,43 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface {
// the user code changes between the call to UponLeavingGTest()
// and any calls to the stack trace code from within the user code.
void* caller_frame_ = nullptr;
AbslStackTraceGetter(const AbslStackTraceGetter&) = delete;
AbslStackTraceGetter& operator=(const AbslStackTraceGetter&) = delete;
};
#endif // GTEST_HAS_ABSL
OsStackTraceGetter(const OsStackTraceGetter&) = delete;
OsStackTraceGetter& operator=(const OsStackTraceGetter&) = delete;
#if GTEST_HAS_STD_STACKTRACE_
// A working implementation of the OsStackTraceGetterInterface interface.
class StdStackTraceGetter : public OsStackTraceGetterInterface {
public:
StdStackTraceGetter() = default;
std::string CurrentStackTrace(int max_depth, int skip_count) override;
void UponLeavingGTest() override;
private:
Mutex mutex_; // Protects all internal state.
// We save the stack frame below the frame that calls user code.
// We do this because the address of the frame immediately below
// the user code changes between the call to UponLeavingGTest()
// and any calls to the stack trace code from within the user code.
std::stacktrace_entry::native_handle_type caller_frame_ = {};
StdStackTraceGetter(const StdStackTraceGetter&) = delete;
StdStackTraceGetter& operator=(const StdStackTraceGetter&) = delete;
};
#endif // GTEST_HAS_STD_STACKTRACE_
// An implementation of OsStackTraceGetterInterface which returns no
// stack trace.
class NoopStackTraceGetter : public OsStackTraceGetterInterface {
public:
NoopStackTraceGetter() = default;
std::string CurrentStackTrace(int max_depth, int skip_count) override;
void UponLeavingGTest() override;
};
// Information about a Google Test trace point.
@ -587,7 +624,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
@ -620,8 +657,8 @@ class GTEST_API_ UnitTestImpl {
void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
// Returns the current OS stack trace getter if it is not NULL;
// otherwise, creates an OsStackTraceGetter, makes it the current
// getter, and returns it.
// otherwise, creates an OsStackTraceGetterInterface, makes it the
// current getter, and returns it.
OsStackTraceGetterInterface* os_stack_trace_getter();
// Returns the current OS stack trace as an std::string.
@ -935,9 +972,9 @@ class GTEST_API_ UnitTestImpl {
TestEventListeners listeners_;
// The OS stack trace getter. Will be deleted when the UnitTest
// object is destructed. By default, an OsStackTraceGetter is used,
// but the user can set this field to use a custom getter if that is
// desired.
// object is destructed. By default, an OsStackTraceGetterInterface
// is created when os_stack_trace_getter is first called, but the user
// can set this field to use a custom getter if that is desired.
OsStackTraceGetterInterface* os_stack_trace_getter_;
// True if and only if PostFlagParsingInit() has been called.

View File

@ -155,6 +155,10 @@
#include "absl/strings/strip.h"
#endif // GTEST_HAS_ABSL
#if GTEST_HAS_STD_STACKTRACE_
#include <stacktrace>
#endif
// Checks builtin compiler feature |x| while avoiding an extra layer of #ifdefs
// at the callsite.
#if defined(__has_builtin)
@ -5096,9 +5100,9 @@ void StreamingListener::SocketWriter::MakeConnection() {
const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
"... " GTEST_NAME_ " internal frames ...";
std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
GTEST_LOCK_EXCLUDED_(mutex_) {
#ifdef GTEST_HAS_ABSL
std::string AbslStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
GTEST_LOCK_EXCLUDED_(mutex_) {
std::string result;
if (max_depth <= 0) {
@ -5138,16 +5142,11 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
}
return result;
#else // !GTEST_HAS_ABSL
static_cast<void>(max_depth);
static_cast<void>(skip_count);
return "";
#endif // GTEST_HAS_ABSL
}
#endif // GTEST_HAS_ABSL
void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
#ifdef GTEST_HAS_ABSL
void AbslStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
void* caller_frame = nullptr;
if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {
caller_frame = nullptr;
@ -5155,7 +5154,75 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
MutexLock lock(mutex_);
caller_frame_ = caller_frame;
}
#endif // GTEST_HAS_ABSL
#if GTEST_HAS_STD_STACKTRACE_
std::string StdStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
GTEST_LOCK_EXCLUDED_(mutex_) {
if (max_depth <= 0) {
return "";
}
max_depth = std::min(max_depth, kMaxStackTraceDepth);
// Skips the frames requested by the caller, plus this function.
skip_count += 1;
std::stacktrace stack = std::stacktrace::current(skip_count, max_depth);
std::stacktrace_entry::native_handle_type caller_frame = {};
{
MutexLock lock(&mutex_);
caller_frame = caller_frame_;
}
std::ostringstream result;
for (const std::stacktrace_entry &entry : stack) {
if (entry.native_handle() == caller_frame &&
!GTEST_FLAG_GET(show_internal_stack_frames)) {
// Add a marker to the trace and stop adding frames.
result << kElidedFramesMarker << '\n';
break;
}
result << " " << entry.native_handle() << ": ";
std::string description = entry.description();
if (description.empty()) {
result << "(unknown)";
} else {
result << description;
}
std::string source_file = entry.source_file();
if (!source_file.empty()) {
result << ' ' << source_file << ':' << entry.source_line();
}
result << '\n';
}
return std::move(result).str();
}
#endif // GTEST_HAS_ABSL
#if GTEST_HAS_STD_STACKTRACE_
void StdStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
std::stacktrace stack = std::stacktrace::current(/*skip=*/2, /*max_depth=*/1);
std::stacktrace_entry::native_handle_type caller_frame = {};
if (!stack.empty()) {
caller_frame = stack[0].native_handle();
}
MutexLock lock(&mutex_);
caller_frame_ = caller_frame;
}
#endif // GTEST_HAS_ABSL
std::string NoopStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) {
static_cast<void>(max_depth);
static_cast<void>(skip_count);
return "";
}
void NoopStackTraceGetter::UponLeavingGTest() {
// Do nothing.
}
#ifdef GTEST_INTERNAL_HAS_PREMATURE_EXIT_FILE
@ -6455,14 +6522,18 @@ void UnitTestImpl::set_os_stack_trace_getter(
}
// Returns the current OS stack trace getter if it is not NULL;
// otherwise, creates an OsStackTraceGetter, makes it the current
// getter, and returns it.
// otherwise, creates an OsStackTraceGetterInterface, makes it the
// current getter, and returns it.
OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
if (os_stack_trace_getter_ == nullptr) {
#ifdef GTEST_OS_STACK_TRACE_GETTER_
os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
#elif GTEST_HAS_STD_STACKTRACE_
os_stack_trace_getter_ = new StdStackTraceGetter;
#elif defined(GTEST_HAS_ABSL)
os_stack_trace_getter_ = new AbslStackTraceGetter;
#else
os_stack_trace_getter_ = new OsStackTraceGetter;
os_stack_trace_getter_ = new NoopStackTraceGetter;
#endif // GTEST_OS_STACK_TRACE_GETTER_
}

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.