From b5fd99bbd55ebe1a3488b8ea3717fba089293457 Mon Sep 17 00:00:00 2001 From: Aaron Jacobs Date: Thu, 30 Mar 2023 13:34:34 -0700 Subject: gtest.cc: run tests within a test suite in a deterministic order. Ensure that tests are run in the order specified in the source code, even if they are registered manually using RegisterTest. There should be no behavior change for the common case. PiperOrigin-RevId: 520729483 Change-Id: I400c78400c6929fccae0676214d993251f31888f --- googletest/src/gtest.cc | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 7832492d..c2581fa0 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -44,6 +44,7 @@ #include // NOLINT #include #include +#include #include #include #include @@ -2981,6 +2982,25 @@ void TestSuite::Run() { TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); + // Ensure our tests are in a deterministic order. + // + // We do this by sorting lexicographically on (file, line number), providing + // an order matching what the user can see in the source code. + // + // In the common case the line number comparison shouldn't be necessary, + // because the registrations made by the TEST macro are executed in order + // within a translation unit. But this is not true of the manual registration + // API, and in more exotic scenarios a single file may be part of multiple + // translation units. + std::stable_sort(test_info_list_.begin(), test_info_list_.end(), + [](const TestInfo* const a, const TestInfo* const b) { + if (const int result = std::strcmp(a->file(), a->file())) { + return result < 0; + } + + return a->line() < b->line(); + }); + // Call both legacy and the new API repeater->OnTestSuiteStart(*this); // Legacy API is deprecated but still available -- cgit v1.2.1