From 263220d2c1211e3ec95602ff3c81cf75cd55e19a Mon Sep 17 00:00:00 2001 From: Yuriy Chernyshov Date: Thu, 24 Dec 2020 12:20:38 +0300 Subject: [PATCH 001/472] Use proper feature test macro to test if library supports char8_t Reference is here: https://en.cppreference.com/w/cpp/feature_test This PR fixes the weird case of compiling with `clang++ -std=c++17 -fchar8_t` --- googletest/include/gtest/gtest-printers.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 463f0aff7e..5998b5372c 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -349,7 +349,7 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t); #endif From 9614d8c1d69dee9de2e0771a0da2b69a34964e33 Mon Sep 17 00:00:00 2001 From: Julien JEMINE Date: Tue, 29 Dec 2020 16:46:55 +0100 Subject: [PATCH 002/472] Using auto instead of container::const_iterator --- googlemock/include/gmock/gmock-matchers.h | 17 +++++++---------- googletest/src/gtest-internal-inl.h | 2 +- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 9641ed4264..71dc128b13 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -2370,7 +2370,6 @@ class ContainerEqMatcher { typedef internal::StlContainerView< typename std::remove_const::type> LhsView; - typedef typename LhsView::type LhsStlContainer; StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); if (lhs_stl_container == expected_) return true; @@ -2379,8 +2378,7 @@ class ContainerEqMatcher { if (os != nullptr) { // Something is different. Check for extra values first. bool printed_header = false; - for (typename LhsStlContainer::const_iterator it = - lhs_stl_container.begin(); + for (auto it = lhs_stl_container.begin(); it != lhs_stl_container.end(); ++it) { if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) == expected_.end()) { @@ -2396,7 +2394,7 @@ class ContainerEqMatcher { // Now check for missing values. bool printed_header2 = false; - for (typename StlContainer::const_iterator it = expected_.begin(); + for (auto it = expected_.begin(); it != expected_.end(); ++it) { if (internal::ArrayAwareFind( lhs_stl_container.begin(), lhs_stl_container.end(), *it) == @@ -2580,8 +2578,8 @@ class PointwiseMatcher { return false; } - typename LhsStlContainer::const_iterator left = lhs_stl_container.begin(); - typename RhsStlContainer::const_iterator right = rhs_.begin(); + auto left = lhs_stl_container.begin(); + auto right = rhs_.begin(); for (size_t i = 0; i != actual_size; ++i, ++left, ++right) { if (listener->IsInterested()) { StringMatchResultListener inner_listener; @@ -2644,7 +2642,7 @@ class QuantifierMatcherImpl : public MatcherInterface { MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); size_t i = 0; - for (typename StlContainer::const_iterator it = stl_container.begin(); + for (auto it = stl_container.begin(); it != stl_container.end(); ++it, ++i) { StringMatchResultListener inner_listener; const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); @@ -3241,7 +3239,7 @@ class ElementsAreMatcherImpl : public MatcherInterface { // explanations[i] is the explanation of the element at index i. ::std::vector explanations(count()); StlContainerReference stl_container = View::ConstReference(container); - typename StlContainer::const_iterator it = stl_container.begin(); + auto it = stl_container.begin(); size_t exam_pos = 0; bool mismatch_found = false; // Have we found a mismatched element yet? @@ -3434,7 +3432,6 @@ class UnorderedElementsAreMatcherImpl typedef internal::StlContainerView View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; - typedef typename StlContainer::const_iterator StlContainerConstIterator; typedef typename StlContainer::value_type Element; template @@ -4597,7 +4594,7 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, // Create a matcher for each element in rhs_container. ::std::vector > matchers; - for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin(); + for (auto it = rhs_stl_container.begin(); it != rhs_stl_container.end(); ++it) { matchers.push_back( internal::MatcherBindSecond(tuple2_matcher, *it)); diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 38306c8f5d..b4d820bf19 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -290,7 +290,7 @@ inline int CountIf(const Container& c, Predicate predicate) { // Implemented as an explicit loop since std::count_if() in libCstd on // Solaris has a non-standard signature. int count = 0; - for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { + for (auto it = c.begin(); it != c.end(); ++it) { if (predicate(*it)) ++count; } From 05e9fa23f74a4766294f858c16e87a1560261340 Mon Sep 17 00:00:00 2001 From: Mattias Ellert Date: Wed, 30 Dec 2020 13:50:04 +0100 Subject: [PATCH 003/472] Port to GNU/Hurd --- googletest/include/gtest/internal/gtest-port-arch.h | 2 ++ googletest/include/gtest/internal/gtest-port.h | 9 ++++++--- googletest/src/gtest-port.cc | 2 +- googletest/test/googletest-port-test.cc | 2 +- googletest/test/gtest_help_test.py | 3 ++- 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h index 813bf2c659..a75cd5bb85 100644 --- a/googletest/include/gtest/internal/gtest-port-arch.h +++ b/googletest/include/gtest/internal/gtest-port-arch.h @@ -78,6 +78,8 @@ # define GTEST_OS_FREEBSD 1 #elif defined __Fuchsia__ # define GTEST_OS_FUCHSIA 1 +#elif defined(__GNU__) +# define GTEST_OS_GNU_HURD 1 #elif defined(__GLIBC__) && defined(__FreeBSD_kernel__) # define GTEST_OS_GNU_KFREEBSD 1 #elif defined __linux__ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 6b66362f17..f62f58769a 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -116,6 +116,7 @@ // GTEST_OS_DRAGONFLY - DragonFlyBSD // GTEST_OS_FREEBSD - FreeBSD // GTEST_OS_FUCHSIA - Fuchsia +// GTEST_OS_GNU_HURD - GNU/Hurd // GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD // GTEST_OS_HAIKU - Haiku // GTEST_OS_HPUX - HP-UX @@ -543,7 +544,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \ GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \ - GTEST_OS_HAIKU) + GTEST_OS_HAIKU || GTEST_OS_GNU_HURD) #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD @@ -603,7 +604,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \ GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \ GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ - GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU) + GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU || \ + GTEST_OS_GNU_HURD) # define GTEST_HAS_DEATH_TEST 1 #endif @@ -623,7 +625,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Determines whether test results can be streamed to a socket. #if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \ - GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD + GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD || \ + GTEST_OS_GNU_HURD # define GTEST_CAN_STREAM_RESULTS_ 1 #endif diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index 3f39f71c07..989c59ae55 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -98,7 +98,7 @@ const int kStdOutFileno = STDOUT_FILENO; const int kStdErrFileno = STDERR_FILENO; #endif // _MSC_VER -#if GTEST_OS_LINUX +#if GTEST_OS_LINUX || GTEST_OS_GNU_HURD namespace { template diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 4a87df0b82..e3ad4ddec1 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -280,7 +280,7 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \ GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ - GTEST_OS_NETBSD || GTEST_OS_OPENBSD + GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD void* ThreadFunc(void* data) { internal::Mutex* mutex = static_cast(data); mutex->Lock(); diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py index 8d953bbd9d..54d450474d 100755 --- a/googletest/test/gtest_help_test.py +++ b/googletest/test/gtest_help_test.py @@ -43,6 +43,7 @@ IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' +IS_GNUHURD = os.name == 'posix' and os.uname()[0] == 'GNU' IS_GNUKFREEBSD = os.name == 'posix' and os.uname()[0] == 'GNU/kFreeBSD' IS_WINDOWS = os.name == 'nt' @@ -112,7 +113,7 @@ def TestHelpFlag(self, flag): self.assertEquals(0, exit_code) self.assert_(HELP_REGEX.search(output), output) - if IS_LINUX or IS_GNUKFREEBSD: + if IS_LINUX or IS_GNUHURD or IS_GNUKFREEBSD: self.assert_(STREAM_RESULT_TO_FLAG in output, output) else: self.assert_(STREAM_RESULT_TO_FLAG not in output, output) From 1745a405eb7c70e0e4488023a4f2c69fd6faed4f Mon Sep 17 00:00:00 2001 From: Hyuk Myeong Date: Sun, 13 Jun 2021 19:50:40 +0900 Subject: [PATCH 004/472] fix typos --- README.md | 8 ++++---- docs/gmock_cheat_sheet.md | 4 ++-- docs/gmock_for_dummies.md | 2 +- docs/pkgconfig.md | 2 +- docs/reference/actions.md | 14 +++++++------- docs/reference/matchers.md | 2 +- googletest/README.md | 2 +- 7 files changed, 17 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 7d872a57ed..e207d38975 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,9 @@ Our documentation is now live on GitHub Pages at https://google.github.io/googletest/. We recommend browsing the documentation on GitHub Pages rather than directly in the repository. -#### Release 1.10.x +#### Release 1.11.0 -[Release 1.10.x](https://github.com/google/googletest/releases/tag/release-1.10.0) +[Release 1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0) is now available. #### Coming Soon @@ -109,8 +109,8 @@ Windows and Linux platforms. [GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that runs your test binary, allows you to track its progress via a progress bar, and -displays a list of test failures. Clicking on one shows failure text. Google -Test UI is written in C#. +displays a list of test failures. Clicking on one shows failure text. GoogleTest +UI is written in C#. [GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event listener for GoogleTest that implements the diff --git a/docs/gmock_cheat_sheet.md b/docs/gmock_cheat_sheet.md index 17ed7a54d8..09aeef07d6 100644 --- a/docs/gmock_cheat_sheet.md +++ b/docs/gmock_cheat_sheet.md @@ -230,8 +230,8 @@ class MockFunction { }; ``` -See this [recipe](gmock_cook_book.md#using-check-points) for one application of -it. +See this [recipe](gmock_cook_book.md#useful-mocks-created-using-gmock) for one +application of it. ## Flags diff --git a/docs/gmock_for_dummies.md b/docs/gmock_for_dummies.md index 1f4cc246c4..459bb7f01b 100644 --- a/docs/gmock_for_dummies.md +++ b/docs/gmock_for_dummies.md @@ -480,7 +480,7 @@ the *default* action for the function every time (unless, of course, you have a `WillRepeatedly()`.). What can we do inside `WillOnce()` besides `Return()`? You can return a -reference using `ReturnRef(*variable*)`, or invoke a pre-defined function, among +reference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function, among [others](gmock_cook_book.md#using-actions). **Important note:** The `EXPECT_CALL()` statement evaluates the action clause diff --git a/docs/pkgconfig.md b/docs/pkgconfig.md index 768e9b4c26..18a2546a38 100644 --- a/docs/pkgconfig.md +++ b/docs/pkgconfig.md @@ -105,7 +105,7 @@ includedir=/usr/include Name: gtest Description: GoogleTest (without main() function) -Version: 1.10.0 +Version: 1.11.0 URL: https://github.com/google/googletest Libs: -L${libdir} -lgtest -lpthread Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread diff --git a/docs/reference/actions.md b/docs/reference/actions.md index 166d2a897a..ab81a129ef 100644 --- a/docs/reference/actions.md +++ b/docs/reference/actions.md @@ -6,7 +6,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace. ## Returning a Value -| | | +| Action | Description | | :-------------------------------- | :-------------------------------------------- | | `Return()` | Return from a `void` mock function. | | `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed. | @@ -20,7 +20,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace. ## Side Effects -| | | +| Action | Description | | :--------------------------------- | :-------------------------------------- | | `Assign(&variable, value)` | Assign `value` to variable. | | `DeleteArg()` | Delete the `N`-th (0-based) argument, which must be a pointer. | @@ -38,9 +38,9 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace. In the following, by "callable" we mean a free function, `std::function`, functor, or lambda. -| | | +| Action | Description | | :---------------------------------- | :------------------------------------- | -| `f` | Invoke f with the arguments passed to the mock function, where f is a callable. | +| `f` | Invoke `f` with the arguments passed to the mock function, where `f` is a callable. | | `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. | | `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. | | `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | @@ -86,7 +86,7 @@ value, and `foo` by reference. ## Default Action -| Matcher | Description | +| Action | Description | | :------------ | :----------------------------------------------------- | | `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | @@ -96,7 +96,7 @@ composite action - trying to do so will result in a run-time error. ## Composite Actions -| | | +| Action | Description | | :----------------------------- | :------------------------------------------ | | `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a readonly view of the arguments. | | `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. | @@ -106,7 +106,7 @@ composite action - trying to do so will result in a run-time error. ## Defining Actions -| | | +| Macro | Description | | :--------------------------------- | :-------------------------------------- | | `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | | `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | diff --git a/docs/reference/matchers.md b/docs/reference/matchers.md index 9e40cab704..8697060d22 100644 --- a/docs/reference/matchers.md +++ b/docs/reference/matchers.md @@ -259,7 +259,7 @@ which must be a permanent callback. ## Defining Matchers -| Matcher | Description | +| Macro | Description | | :----------------------------------- | :------------------------------------ | | `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | | `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. | diff --git a/googletest/README.md b/googletest/README.md index 1f8b349ae7..c8aedb7877 100644 --- a/googletest/README.md +++ b/googletest/README.md @@ -25,7 +25,7 @@ When building GoogleTest as a standalone project, the typical workflow starts with ``` -git clone https://github.com/google/googletest.git -b release-1.10.0 +git clone https://github.com/google/googletest.git -b release-1.11.0 cd googletest # Main directory of the cloned repository. mkdir build # Create a directory to hold the build output. cd build From 5ef9f63a72bbc4814ad704d22c74b23530793bb2 Mon Sep 17 00:00:00 2001 From: Vasilii Pochkaenko Date: Thu, 3 Jun 2021 14:21:40 +0700 Subject: [PATCH 005/472] feat: make a matcher ElementsAreArray applicable for std ranges --- googlemock/include/gmock/gmock-matchers.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 99f1774a84..b88199f29e 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -3527,8 +3527,8 @@ inline internal::ElementsAreArrayMatcher ElementsAreArray( } template -inline internal::ElementsAreArrayMatcher -ElementsAreArray(const Container& container) { +inline auto ElementsAreArray(const Container& container) + -> decltype(ElementsAreArray(container.begin(), container.end())) { return ElementsAreArray(container.begin(), container.end()); } From f7902802f1a61140e188223fb6d1c95925cbec4a Mon Sep 17 00:00:00 2001 From: dmauro Date: Fri, 18 Jun 2021 19:32:08 +0000 Subject: [PATCH 006/472] Googletest export Remove -Werror from the CMake compiler flags We should not force warnings as errors on users. Sometimes compilers introduce new warnings which will break builds. Instead, we manually turn this flag on in our continuous integration scripts so we can catch these errors, but not force them on our users. Fixes #3447 PiperOrigin-RevId: 380241852 --- googletest/cmake/internal_utils.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake index 8d8d60a86c..58fc9bfbee 100644 --- a/googletest/cmake/internal_utils.cmake +++ b/googletest/cmake/internal_utils.cmake @@ -84,13 +84,13 @@ macro(config_compiler_and_linker) # Ensure MSVC treats source files as UTF-8 encoded. set(cxx_base_flags "${cxx_base_flags} -utf-8") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") - set(cxx_base_flags "-Wall -Wshadow -Werror -Wconversion") + set(cxx_base_flags "-Wall -Wshadow -Wconversion") set(cxx_exception_flags "-fexceptions") set(cxx_no_exception_flags "-fno-exceptions") set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Wchar-subscripts -Winline -Wredundant-decls") set(cxx_no_rtti_flags "-fno-rtti") elseif (CMAKE_COMPILER_IS_GNUCXX) - set(cxx_base_flags "-Wall -Wshadow -Werror") + set(cxx_base_flags "-Wall -Wshadow") if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0) set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else") endif() From 10088504350a1b7192615382828fa8662c79949e Mon Sep 17 00:00:00 2001 From: Alex Karatarakis Date: Wed, 23 Jun 2021 14:57:22 -0700 Subject: [PATCH 007/472] Fix EXPECT_DEATH() and ASSERT_DEATH() triggering -Wcovered-switch-default EXPECT_DEATH() and ASSERT_DEATH() have a switch case where every possible case is covered. This makes the default case unnecessary and triggers -Wcovered-switch-default. Due to these being macros, the lines are expanded in user code and are thus subject to warnings of the target codebase. Fixes #3456 --- googletest/include/gtest/internal/gtest-death-test-internal.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 490296dfad..867a840d08 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -236,8 +236,6 @@ inline Matcher MakeDeathTestMatcher( gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ break; \ } \ - default: \ - break; \ } \ } \ } else \ From 4281d2149c4ff791ff346778558a9d606554982d Mon Sep 17 00:00:00 2001 From: Manuel Binna Date: Fri, 25 Jun 2021 06:35:18 +0200 Subject: [PATCH 008/472] Don't link pthread on QNX On QNX, pthread is part of libc [1]. There's no separate pthread library to link. [1] https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.lib_ref/topic/p/pthread_create.html --- BUILD.bazel | 7 +++++++ googlemock/test/BUILD.bazel | 1 + googletest/test/BUILD.bazel | 1 + 3 files changed, 9 insertions(+) diff --git a/BUILD.bazel b/BUILD.bazel index 965c518d7a..3c9a228f42 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -38,6 +38,11 @@ licenses(["notice"]) exports_files(["LICENSE"]) +config_setting( + name = "qnx", + constraint_values = ["@platforms//os:qnx"], +) + config_setting( name = "windows", constraint_values = ["@platforms//os:windows"], @@ -86,6 +91,7 @@ cc_library( "googlemock/include/gmock/*.h", ]), copts = select({ + ":qnx": [], ":windows": [], "//conditions:default": ["-pthread"], }), @@ -104,6 +110,7 @@ cc_library( "googletest/include", ], linkopts = select({ + ":qnx": [], ":windows": [], "//conditions:default": ["-pthread"], }), diff --git a/googlemock/test/BUILD.bazel b/googlemock/test/BUILD.bazel index efb7306b22..6193ed4daf 100644 --- a/googlemock/test/BUILD.bazel +++ b/googlemock/test/BUILD.bazel @@ -41,6 +41,7 @@ cc_test( size = "small", srcs = glob(include = ["gmock-*.cc"]), linkopts = select({ + "//:qnx": [], "//:windows": [], "//conditions:default": ["-pthread"], }), diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index b06a00a106..7b78555ed2 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -95,6 +95,7 @@ cc_test( "googletest/test", ], linkopts = select({ + "//:qnx": [], "//:windows": [], "//conditions:default": ["-pthread"], }), From 255323cf092e46b2a9f0ded173bb4b91dd52486e Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 28 Jun 2021 16:48:06 -0400 Subject: [PATCH 009/472] Googletest export Deleting deprecated file. PiperOrigin-RevId: 381938709 --- library.json | 62 ---------------------------------------------------- 1 file changed, 62 deletions(-) delete mode 100644 library.json diff --git a/library.json b/library.json deleted file mode 100644 index f61bf003e8..0000000000 --- a/library.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "googletest", - "keywords": "unittest, unit, test, gtest, gmock", - "description": "googletest is a testing framework developed by the Testing Technology team with Google's specific requirements and constraints in mind. No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it supports any kind of tests, not just unit tests.", - "license": "BSD-3-Clause", - "homepage": "https://github.com/google/googletest/blob/master/README.md", - "repository": { - "type": "git", - "url": "https://github.com/google/googletest.git" - }, - "version": "1.10.0", - "frameworks": "arduino", - "platforms": [ - "espressif32", - "espressif8266" - ], - "export": { - "include": [ - "googlemock/include/*", - "googlemock/src/*", - "googletest/include/*", - "googletest/src/*" - ], - "exclude": [ - "ci", - "googlemock/cmake", - "googlemock/scripts", - "googlemock/test", - "googlemock/CMakeLists.txt", - "googletest/cmake", - "googletest/scripts", - "googletest/test", - "googletest/CMakeLists.txt" - ] - }, - "build": { - "flags": [ - "-Igooglemock/include", - "-Igooglemock", - "-Igoogletest/include", - "-Igoogletest" - ], - "srcFilter": [ - "+<*>", - "-<.git/>", - "-", - "-", - "-", - "+", - "+", - "+", - "-", - "-", - "-", - "-", - "-", - "-", - "+", - "+" - ] - } -} From 22e6055c75caa53a98f5a6b9887d67c3574888d6 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Mon, 28 Jun 2021 17:52:38 -0400 Subject: [PATCH 010/472] Googletest export Make multiple attempts to verify GetThreadCount() Testing GetThreadCount() is inheritently noisy, as other threads can be started or destroyed between two calls to GetThreadCount(). This is especially true under certain analyzer configurations, such as TSAN. PiperOrigin-RevId: 381951799 --- googletest/test/googletest-port-test.cc | 73 +++++++++++++++++-------- 1 file changed, 49 insertions(+), 24 deletions(-) diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 2697355db2..16d30c46b7 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -289,36 +289,61 @@ void* ThreadFunc(void* data) { } TEST(GetThreadCountTest, ReturnsCorrectValue) { - const size_t starting_count = GetThreadCount(); - pthread_t thread_id; + size_t starting_count; + size_t thread_count_after_create; + size_t thread_count_after_join; + + // We can't guarantee that no other thread was created or destroyed between + // any two calls to GetThreadCount(). We make multiple attempts, hoping that + // background noise is not constant and we would see the "right" values at + // some point. + for (int attempt = 0; attempt < 20; ++attempt) { + starting_count = GetThreadCount(); + pthread_t thread_id; + + internal::Mutex mutex; + { + internal::MutexLock lock(&mutex); + pthread_attr_t attr; + ASSERT_EQ(0, pthread_attr_init(&attr)); + ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); + + const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); + ASSERT_EQ(0, pthread_attr_destroy(&attr)); + ASSERT_EQ(0, status); + } - internal::Mutex mutex; - { - internal::MutexLock lock(&mutex); - pthread_attr_t attr; - ASSERT_EQ(0, pthread_attr_init(&attr)); - ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); - - const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); - ASSERT_EQ(0, pthread_attr_destroy(&attr)); - ASSERT_EQ(0, status); - EXPECT_EQ(starting_count + 1, GetThreadCount()); - } + thread_count_after_create = GetThreadCount(); - void* dummy; - ASSERT_EQ(0, pthread_join(thread_id, &dummy)); + void* dummy; + ASSERT_EQ(0, pthread_join(thread_id, &dummy)); - // The OS may not immediately report the updated thread count after - // joining a thread, causing flakiness in this test. To counter that, we - // wait for up to .5 seconds for the OS to report the correct value. - for (int i = 0; i < 5; ++i) { - if (GetThreadCount() == starting_count) - break; + // Join before we decide whether we need to retry the test. Retry if an + // arbitrary other thread was created or destroyed in the meantime. + if (thread_count_after_create != starting_count + 1) continue; + + // The OS may not immediately report the updated thread count after + // joining a thread, causing flakiness in this test. To counter that, we + // wait for up to .5 seconds for the OS to report the correct value. + bool thread_count_matches = false; + for (int i = 0; i < 5; ++i) { + thread_count_after_join = GetThreadCount(); + if (thread_count_after_join == starting_count) { + thread_count_matches = true; + break; + } + + SleepMilliseconds(100); + } + + // Retry if an arbitrary other thread was created or destroyed. + if (!thread_count_matches) continue; - SleepMilliseconds(100); + break; } - EXPECT_EQ(starting_count, GetThreadCount()); + EXPECT_EQ(thread_count_after_create, starting_count + 1); + EXPECT_EQ(thread_count_after_join, starting_count); } #else TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) { From 4ec4cd23f486bf70efcc5d2caa40f24368f752e3 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 29 Jun 2021 21:55:02 -0400 Subject: [PATCH 011/472] Googletest export Implement 'Contains(e).Times(n)' matcher modifier which allows to test for arbitrary occurrences including absence with Times(0). PiperOrigin-RevId: 382210276 --- docs/reference/matchers.md | 1 + googlemock/include/gmock/gmock-matchers.h | 128 +++++++++++++++++++++- googlemock/test/gmock-matchers_test.cc | 97 ++++++++++++++-- 3 files changed, 209 insertions(+), 17 deletions(-) diff --git a/docs/reference/matchers.md b/docs/reference/matchers.md index 8697060d22..0d8f81be14 100644 --- a/docs/reference/matchers.md +++ b/docs/reference/matchers.md @@ -116,6 +116,7 @@ messages, you can use: | `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. | | `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | | `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | +| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which can be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains(e).Times(0)`. | | `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | | `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. | | `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index be174b7a85..e1a7606326 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -2581,7 +2581,7 @@ class PointwiseMatcher { StringMatchResultListener inner_listener; // Create InnerMatcherArg as a temporarily object to avoid it outlives // *left and *right. Dereference or the conversion to `const T&` may - // return temp objects, e.g for vector. + // return temp objects, e.g. for vector. if (!mono_tuple_matcher_.MatchAndExplain( InnerMatcherArg(ImplicitCast_(*left), ImplicitCast_(*right)), @@ -2653,6 +2653,54 @@ class QuantifierMatcherImpl : public MatcherInterface { return all_elements_should_match; } + bool MatchAndExplainImpl(const Matcher& count_matcher, + Container container, + MatchResultListener* listener) const { + StlContainerReference stl_container = View::ConstReference(container); + size_t i = 0; + std::vector match_elements; + for (auto it = stl_container.begin(); it != stl_container.end(); + ++it, ++i) { + StringMatchResultListener inner_listener; + const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); + if (matches) { + match_elements.push_back(i); + } + } + if (listener->IsInterested()) { + if (match_elements.empty()) { + *listener << "has no element that matches"; + } else if (match_elements.size() == 1) { + *listener << "whose element #" << match_elements[0] << " matches"; + } else { + *listener << "whose elements ("; + std::string sep = ""; + for (size_t e : match_elements) { + *listener << sep << e; + sep = ", "; + } + *listener << ") match"; + } + } + StringMatchResultListener count_listener; + if (count_matcher.MatchAndExplain(match_elements.size(), &count_listener)) { + *listener << " and whose match quantity of " << match_elements.size() + << " matches"; + PrintIfNotEmpty(count_listener.str(), listener->stream()); + return true; + } else { + if (match_elements.empty()) { + *listener << " and"; + } else { + *listener << " but"; + } + *listener << " whose match quantity of " << match_elements.size() + << " does not match"; + PrintIfNotEmpty(count_listener.str(), listener->stream()); + return false; + } + } + protected: const Matcher inner_matcher_; }; @@ -2709,6 +2757,58 @@ class EachMatcherImpl : public QuantifierMatcherImpl { } }; +// Implements Contains(element_matcher).Times(n) for the given argument type +// Container. +template +class ContainsTimesMatcherImpl : public QuantifierMatcherImpl { + public: + template + explicit ContainsTimesMatcherImpl(InnerMatcher inner_matcher, + Matcher count_matcher) + : QuantifierMatcherImpl(inner_matcher), + count_matcher_(std::move(count_matcher)) {} + + void DescribeTo(::std::ostream* os) const override { + *os << "quantity of elements that match "; + this->inner_matcher_.DescribeTo(os); + *os << " "; + count_matcher_.DescribeTo(os); + } + + void DescribeNegationTo(::std::ostream* os) const override { + *os << "quantity of elements that match "; + this->inner_matcher_.DescribeTo(os); + *os << " "; + count_matcher_.DescribeNegationTo(os); + } + + bool MatchAndExplain(Container container, + MatchResultListener* listener) const override { + return this->MatchAndExplainImpl(count_matcher_, container, listener); + } + + private: + const Matcher count_matcher_; +}; + +// Implements polymorphic Contains(element_matcher).Times(n). +template +class ContainsTimesMatcher { + public: + explicit ContainsTimesMatcher(M m, Matcher count_matcher) + : inner_matcher_(m), count_matcher_(std::move(count_matcher)) {} + + template + operator Matcher() const { // NOLINT + return Matcher(new ContainsTimesMatcherImpl( + inner_matcher_, count_matcher_)); + } + + private: + const M inner_matcher_; + const Matcher count_matcher_; +}; + // Implements polymorphic Contains(element_matcher). template class ContainsMatcher { @@ -2716,11 +2816,15 @@ class ContainsMatcher { explicit ContainsMatcher(M m) : inner_matcher_(m) {} template - operator Matcher() const { + operator Matcher() const { // NOLINT return Matcher( new ContainsMatcherImpl(inner_matcher_)); } + ContainsTimesMatcher Times(Matcher count_matcher) const { + return ContainsTimesMatcher(inner_matcher_, std::move(count_matcher)); + } + private: const M inner_matcher_; }; @@ -2732,7 +2836,7 @@ class EachMatcher { explicit EachMatcher(M m) : inner_matcher_(m) {} template - operator Matcher() const { + operator Matcher() const { // NOLINT return Matcher( new EachMatcherImpl(inner_matcher_)); } @@ -4615,7 +4719,6 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, return UnorderedPointwise(tuple2_matcher, std::vector(rhs)); } - // Matches an STL-style container or a native array that contains at // least one element matching the given value or matcher. // @@ -4625,7 +4728,7 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, // page_ids.insert(1); // EXPECT_THAT(page_ids, Contains(1)); // EXPECT_THAT(page_ids, Contains(Gt(2))); -// EXPECT_THAT(page_ids, Not(Contains(4))); +// EXPECT_THAT(page_ids, Not(Contains(4))); // See below for Times(0) // // ::std::map page_lengths; // page_lengths[1] = 100; @@ -4634,6 +4737,19 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, // // const char* user_ids[] = { "joe", "mike", "tom" }; // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom")))); +// +// The matcher supports a modifier `Times` that allows to check for arbitrary +// occurrences including testing for absence with Times(0). +// +// Examples: +// ::std::vector ids; +// ids.insert(1); +// ids.insert(1); +// ids.insert(3); +// EXPECT_THAT(ids, Contains(1).Times(2)); // 1 occurs 2 times +// EXPECT_THAT(ids, Contains(2).Times(0)); // 2 is not present +// EXPECT_THAT(ids, Contains(3).Times(Ge(1))); // 3 occurs at least once + template inline internal::ContainsMatcher Contains(M matcher) { return internal::ContainsMatcher(matcher); @@ -4760,7 +4876,7 @@ inline internal::UnorderedElementsAreArrayMatcher IsSubsetOf( // Matches an STL-style container or a native array that contains only // elements matching the given value or matcher. // -// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only +// Each(m) is semantically equivalent to `Not(Contains(Not(m)))`. Only // the messages are different. // // Examples: diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 1f48a76c28..e7ce97c62c 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -114,31 +114,32 @@ std::vector> MakeUniquePtrs(const std::vector& ints) { } // For testing ExplainMatchResultTo(). -class GreaterThanMatcher : public MatcherInterface { +template +class GreaterThanMatcher : public MatcherInterface { public: - explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {} + explicit GreaterThanMatcher(T rhs) : rhs_(rhs) {} void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; } - bool MatchAndExplain(int lhs, MatchResultListener* listener) const override { - const int diff = lhs - rhs_; - if (diff > 0) { - *listener << "which is " << diff << " more than " << rhs_; - } else if (diff == 0) { + bool MatchAndExplain(T lhs, MatchResultListener* listener) const override { + if (lhs > rhs_) { + *listener << "which is " << (lhs - rhs_) << " more than " << rhs_; + } else if (lhs == rhs_) { *listener << "which is the same as " << rhs_; } else { - *listener << "which is " << -diff << " less than " << rhs_; + *listener << "which is " << (rhs_ - lhs) << " less than " << rhs_; } return lhs > rhs_; } private: - int rhs_; + const T rhs_; }; -Matcher GreaterThan(int n) { - return MakeMatcher(new GreaterThanMatcher(n)); +template +Matcher GreaterThan(T n) { + return MakeMatcher(new GreaterThanMatcher(n)); } std::string OfType(const std::string& type_name) { @@ -8023,6 +8024,7 @@ TEST(ContainsTest, ListMatchesWhenElementIsInContainer) { some_list.push_back(3); some_list.push_back(1); some_list.push_back(2); + some_list.push_back(3); EXPECT_THAT(some_list, Contains(1)); EXPECT_THAT(some_list, Contains(Gt(2.5))); EXPECT_THAT(some_list, Contains(Eq(2.0f))); @@ -8147,6 +8149,79 @@ TEST(ContainsTest, WorksForTwoDimensionalNativeArray) { EXPECT_THAT(a, Contains(Not(Contains(5)))); } +// Tests Contains().Times(). + +TEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) { + list some_list; + some_list.push_back(3); + some_list.push_back(1); + some_list.push_back(2); + some_list.push_back(3); + EXPECT_THAT(some_list, Contains(3).Times(2)); + EXPECT_THAT(some_list, Contains(2).Times(1)); + EXPECT_THAT(some_list, Contains(Ge(2)).Times(3)); + EXPECT_THAT(some_list, Contains(Ge(2)).Times(Gt(2))); + EXPECT_THAT(some_list, Contains(4).Times(0)); + EXPECT_THAT(some_list, Contains(_).Times(4)); + EXPECT_THAT(some_list, Not(Contains(5).Times(1))); + EXPECT_THAT(some_list, Contains(5).Times(_)); // Times(_) always matches + EXPECT_THAT(some_list, Not(Contains(3).Times(1))); + EXPECT_THAT(some_list, Contains(3).Times(Not(1))); + EXPECT_THAT(list{}, Not(Contains(_))); +} + +TEST(ContainsTimes, ExplainsMatchResultCorrectly) { + const int a[2] = {1, 2}; + Matcher m = Contains(2).Times(3); + EXPECT_EQ( + "whose element #1 matches but whose match quantity of 1 does not match", + Explain(m, a)); + + m = Contains(3).Times(0); + EXPECT_EQ("has no element that matches and whose match quantity of 0 matches", + Explain(m, a)); + + m = Contains(3).Times(4); + EXPECT_EQ( + "has no element that matches and whose match quantity of 0 does not " + "match", + Explain(m, a)); + + m = Contains(2).Times(4); + EXPECT_EQ( + "whose element #1 matches but whose match quantity of 1 does not " + "match", + Explain(m, a)); + + m = Contains(GreaterThan(0)).Times(2); + EXPECT_EQ("whose elements (0, 1) match and whose match quantity of 2 matches", + Explain(m, a)); + + m = Contains(GreaterThan(10)).Times(Gt(1)); + EXPECT_EQ( + "has no element that matches and whose match quantity of 0 does not " + "match", + Explain(m, a)); + + m = Contains(GreaterThan(0)).Times(GreaterThan(5)); + EXPECT_EQ( + "whose elements (0, 1) match but whose match quantity of 2 does not " + "match, which is 3 less than 5", + Explain(m, a)); +} + +TEST(ContainsTimes, DescribesItselfCorrectly) { + Matcher> m = Contains(1).Times(2); + EXPECT_EQ("quantity of elements that match is equal to 1 is equal to 2", + Describe(m)); + + Matcher> m2 = Not(m); + EXPECT_EQ("quantity of elements that match is equal to 1 isn't equal to 2", + Describe(m2)); +} + +// Tests AllOfArray() + TEST(AllOfArrayTest, BasicForms) { // Iterator std::vector v0{}; From 155de14cd861a29886e85a1f98407d93e16b0595 Mon Sep 17 00:00:00 2001 From: Jeremy Nimmer Date: Thu, 1 Jul 2021 11:43:07 -0700 Subject: [PATCH 012/472] Use GTEST_DONT_DEFINE_TEST_F to guard TEST_F The documentation is clear that the FOO we'll be guarding always matches the spelling of the DONT macro. A single guard macro should not toggle more than one implementation macro. This fixes a regression in 7413280c52c1f759395572a384165023d24eeb57. Relatedly, improve the documentation of the DONT macros to bring the list of valid FOO values up to date. --- googletest/README.md | 4 +++- googletest/include/gtest/gtest.h | 9 +++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/googletest/README.md b/googletest/README.md index c8aedb7877..83ae6cf555 100644 --- a/googletest/README.md +++ b/googletest/README.md @@ -203,7 +203,9 @@ add -DGTEST_DONT_DEFINE_FOO=1 to the compiler flags to tell GoogleTest to change the macro's name from `FOO` -to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For +to `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`, +`ASSERT_GT`, `ASSERT_LE`, `ASSERT_LT`, `ASSERT_NE`, `ASSERT_TRUE`, +`EXPECT_FALSE`, `EXPECT_TRUE`, `FAIL`, `SUCCEED`, `TEST`, or `TEST_F`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write GTEST_TEST(SomeTest, DoesThis) { ... } diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 7a5d057c4a..258c42bbdf 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -2379,12 +2379,13 @@ constexpr bool StaticAssertTypeEq() noexcept { // EXPECT_EQ(b_.size(), 1); // } // -// GOOGLETEST_CM0011 DO NOT DELETE -#if !GTEST_DONT_DEFINE_TEST -#define TEST_F(test_fixture, test_name)\ +#define GTEST_TEST_F(test_fixture, test_name)\ GTEST_TEST_(test_fixture, test_name, test_fixture, \ ::testing::internal::GetTypeId()) -#endif // !GTEST_DONT_DEFINE_TEST +// GOOGLETEST_CM0011 DO NOT DELETE +#if !GTEST_DONT_DEFINE_TEST_F +#define TEST_F(test_fixture, test_name) GTEST_TEST_F(test_fixture, test_name) +#endif // Returns a path to temporary directory. // Tries to determine an appropriate directory for the platform. From f0ff512b7585ff566b25c1d7c92e0065b4bca036 Mon Sep 17 00:00:00 2001 From: Manuel Binna Date: Wed, 7 Jul 2021 19:14:58 +0200 Subject: [PATCH 013/472] Link -lregex on QNX According to the 2nd point on [1], -lregex is required on QNX. [1] https://www.qnx.com/developers/docs/7.1/#com.qnx.doc.ide.userguide/topic/writing_test_programs.html --- BUILD.bazel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.bazel b/BUILD.bazel index 3c9a228f42..153a348b27 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -110,7 +110,7 @@ cc_library( "googletest/include", ], linkopts = select({ - ":qnx": [], + ":qnx": ["-lregex"], ":windows": [], "//conditions:default": ["-pthread"], }), From 4cfd14984fb0ae68ae434ae6e82d67b75986adec Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Fri, 2 Jul 2021 11:58:28 -0400 Subject: [PATCH 014/472] Googletest export gtest: Add a flag to only set up/tear down test environments once when repeating Currently when running a test multiple times using `--gtest_repeat` the global test environment(s) are set up and torn down for each iteration of the test. When checking for flakes in tests that have expensive dependencies that are set up in the test environment (subprocesses, external dependencies, etc) this can become expensive. To support finding flakes in tests that fit into this category, where the setup phase is expensive but each test case is fast, allow callers to specify via `--gtest_recreate_environments_when_repeating=false` that the test environments should only be set up once, for the first iteration, and only torn down once, on the last iteration. This makes running a test with `--gtest_repeat=1000` a much faster and more pleasant experience. PiperOrigin-RevId: 382748942 --- googletest/include/gtest/gtest.h | 6 ++ googletest/src/gtest-internal-inl.h | 7 +++ googletest/src/gtest.cc | 53 +++++++++++++--- .../googletest-global-environment-unittest.py | 60 ++++++++++++++++++- googletest/test/gtest_unittest.cc | 34 +++++++++++ 5 files changed, 149 insertions(+), 11 deletions(-) diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 7a5d057c4a..7e8e83ff40 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -138,6 +138,12 @@ GTEST_DECLARE_int32_(random_seed); // is 1. If the value is -1 the tests are repeating forever. GTEST_DECLARE_int32_(repeat); +// This flag controls whether Google Test Environments are recreated for each +// repeat of the tests. The default value is true. If set to false the global +// test Environment objects are only set up once, for the first iteration, and +// only torn down once, for the last. +GTEST_DECLARE_bool_(recreate_environments_when_repeating); + // This flag controls whether Google Test includes Google Test internal // stack frames in failure stack traces. GTEST_DECLARE_bool_(show_internal_stack_frames); diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 6d8cecbbb3..59762c7ea2 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -93,6 +93,8 @@ const char kPrintTimeFlag[] = "print_time"; const char kPrintUTF8Flag[] = "print_utf8"; const char kRandomSeedFlag[] = "random_seed"; const char kRepeatFlag[] = "repeat"; +const char kRecreateEnvironmentsWhenRepeatingFlag[] = + "recreate_environments_when_repeating"; const char kShuffleFlag[] = "shuffle"; const char kStackTraceDepthFlag[] = "stack_trace_depth"; const char kStreamResultToFlag[] = "stream_result_to"; @@ -176,6 +178,8 @@ class GTestFlagSaver { print_utf8_ = GTEST_FLAG(print_utf8); random_seed_ = GTEST_FLAG(random_seed); repeat_ = GTEST_FLAG(repeat); + recreate_environments_when_repeating_ = + GTEST_FLAG(recreate_environments_when_repeating); shuffle_ = GTEST_FLAG(shuffle); stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); stream_result_to_ = GTEST_FLAG(stream_result_to); @@ -200,6 +204,8 @@ class GTestFlagSaver { GTEST_FLAG(print_utf8) = print_utf8_; GTEST_FLAG(random_seed) = random_seed_; GTEST_FLAG(repeat) = repeat_; + GTEST_FLAG(recreate_environments_when_repeating) = + recreate_environments_when_repeating_; GTEST_FLAG(shuffle) = shuffle_; GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; GTEST_FLAG(stream_result_to) = stream_result_to_; @@ -224,6 +230,7 @@ class GTestFlagSaver { bool print_utf8_; int32_t random_seed_; int32_t repeat_; + bool recreate_environments_when_repeating_; bool shuffle_; int32_t stack_trace_depth_; std::string stream_result_to_; diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 21c611aff1..9a380ebdc8 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -304,6 +304,17 @@ GTEST_DEFINE_int32_( "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); +GTEST_DEFINE_bool_( + recreate_environments_when_repeating, + internal::BoolFromGTestEnv("recreate_environments_when_repeating", true), + "Controls whether global test environments are recreated for each repeat " + "of the tests. If set to false the global test environments are only set " + "up once, for the first iteration, and only torn down once, for the last. " + "Useful for shaking out flaky tests with stable, expensive test " + "environments. If --gtest_repeat is set to a negative number, meaning " + "there is no last run, the environments will always be recreated to avoid " + "leaks."); + GTEST_DEFINE_bool_(show_internal_stack_frames, false, "True if and only if " GTEST_NAME_ " should include internal stack frames when " @@ -5805,8 +5816,19 @@ bool UnitTestImpl::RunAllTests() { // How many times to repeat the tests? We don't want to repeat them // when we are inside the subprocess of a death test. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); + // Repeats forever if the repeat count is negative. const bool gtest_repeat_forever = repeat < 0; + + // Should test environments be set up and torn down for each repeat, or only + // set up on the first and torn down on the last iteration? If there is no + // "last" iteration because the tests will repeat forever, always recreate the + // environments to avoid leaks in case one of the environments is using + // resources that are external to this process. Without this check there would + // be no way to clean up those external resources automatically. + const bool recreate_environments_when_repeating = + GTEST_FLAG(recreate_environments_when_repeating) || gtest_repeat_forever; + for (int i = 0; gtest_repeat_forever || i != repeat; i++) { // We want to preserve failures generated by ad-hoc test // assertions executed before RUN_ALL_TESTS(). @@ -5828,10 +5850,13 @@ bool UnitTestImpl::RunAllTests() { // Runs each test suite if there is at least one test to run. if (has_tests_to_run) { - // Sets up all environments beforehand. - repeater->OnEnvironmentsSetUpStart(*parent_); - ForEach(environments_, SetUpEnvironment); - repeater->OnEnvironmentsSetUpEnd(*parent_); + // Sets up all environments beforehand. If test environments aren't + // recreated for each iteration, only do so on the first iteration. + if (i == 0 || recreate_environments_when_repeating) { + repeater->OnEnvironmentsSetUpStart(*parent_); + ForEach(environments_, SetUpEnvironment); + repeater->OnEnvironmentsSetUpEnd(*parent_); + } // Runs the tests only if there was no fatal failure or skip triggered // during global set-up. @@ -5871,11 +5896,15 @@ bool UnitTestImpl::RunAllTests() { } } - // Tears down all environments in reverse order afterwards. - repeater->OnEnvironmentsTearDownStart(*parent_); - std::for_each(environments_.rbegin(), environments_.rend(), - TearDownEnvironment); - repeater->OnEnvironmentsTearDownEnd(*parent_); + // Tears down all environments in reverse order afterwards. If test + // environments aren't recreated for each iteration, only do so on the + // last iteration. + if (i == repeat - 1 || recreate_environments_when_repeating) { + repeater->OnEnvironmentsTearDownStart(*parent_); + std::for_each(environments_.rbegin(), environments_.rend(), + TearDownEnvironment); + repeater->OnEnvironmentsTearDownEnd(*parent_); + } } elapsed_time_ = timer.Elapsed(); @@ -6437,6 +6466,10 @@ static const char kColorEncodedHelpMessage[] = "random_seed=@Y[NUMBER]@D\n" " Random number seed to use for shuffling test orders (between 1 and\n" " 99999, or 0 to use a seed based on the current time).\n" + " @G--" GTEST_FLAG_PREFIX_ + "recreate_environments_when_repeating@D\n" + " Sets up and tears down the global test environment on each repeat\n" + " of the test.\n" "\n" "Test Output:\n" " @G--" GTEST_FLAG_PREFIX_ @@ -6519,6 +6552,8 @@ static bool ParseGoogleTestFlag(const char* const arg) { ParseBoolFlag(arg, kPrintUTF8Flag, >EST_FLAG(print_utf8)) || ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || + ParseBoolFlag(arg, kRecreateEnvironmentsWhenRepeatingFlag, + >EST_FLAG(recreate_environments_when_repeating)) || ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || ParseInt32Flag(arg, kStackTraceDepthFlag, >EST_FLAG(stack_trace_depth)) || diff --git a/googletest/test/googletest-global-environment-unittest.py b/googletest/test/googletest-global-environment-unittest.py index 32ba628535..f3475599be 100644 --- a/googletest/test/googletest-global-environment-unittest.py +++ b/googletest/test/googletest-global-environment-unittest.py @@ -35,16 +35,17 @@ googletest-global-environment-unittest_ (a program written with Google Test). """ +import re import gtest_test_utils -def RunAndReturnOutput(): +def RunAndReturnOutput(args=None): """Runs the test program and returns its output.""" return gtest_test_utils.Subprocess([ gtest_test_utils.GetTestExecutablePath( 'googletest-global-environment-unittest_') - ]).output + ] + (args or [])).output class GTestGlobalEnvironmentUnitTest(gtest_test_utils.TestCase): @@ -67,6 +68,61 @@ def testEnvironmentSetUpFails(self): # The test case shouldn't have been run. self.assertNotIn('Unexpected call', txt) + def testEnvironmentSetUpAndTornDownForEachRepeat(self): + """Tests the behavior of test environments and gtest_repeat.""" + + txt = RunAndReturnOutput(['--gtest_repeat=2']) + + # By default, with gtest_repeat=2, the global test environment should be set + # up and torn down for each iteration. + expected_pattern = ('(.|\n)*' + r'Repeating all tests \(iteration 1\)' + '(.|\n)*' + 'Global test environment set-up.' + '(.|\n)*' + 'SomeTest.DoesFoo' + '(.|\n)*' + 'Global test environment tear-down' + '(.|\n)*' + r'Repeating all tests \(iteration 2\)' + '(.|\n)*' + 'Global test environment set-up.' + '(.|\n)*' + 'SomeTest.DoesFoo' + '(.|\n)*' + 'Global test environment tear-down' + '(.|\n)*') + self.assertRegex(txt, expected_pattern) + + def testEnvironmentSetUpAndTornDownOnce(self): + """Tests environment and --gtest_recreate_environments_when_repeating.""" + + txt = RunAndReturnOutput([ + '--gtest_repeat=2', '--gtest_recreate_environments_when_repeating=false' + ]) + + # When --gtest_recreate_environments_when_repeating is false, the test + # environment should only be set up and torn down once, at the start and + # end of the test respectively. + expected_pattern = ('(.|\n)*' + r'Repeating all tests \(iteration 1\)' + '(.|\n)*' + 'Global test environment set-up.' + '(.|\n)*' + 'SomeTest.DoesFoo' + '(.|\n)*' + r'Repeating all tests \(iteration 2\)' + '(.|\n)*' + 'SomeTest.DoesFoo' + '(.|\n)*' + 'Global test environment tear-down' + '(.|\n)*') + self.assertRegex(txt, expected_pattern) + + self.assertEqual(len(re.findall('Global test environment set-up', txt)), 1) + self.assertEqual( + len(re.findall('Global test environment tear-down', txt)), 1) + if __name__ == '__main__': gtest_test_utils.Main() diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 1730e8b8c9..402bb6d2af 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -48,6 +48,7 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { testing::GTEST_FLAG(brief) || testing::GTEST_FLAG(print_time) || testing::GTEST_FLAG(random_seed) || testing::GTEST_FLAG(repeat) > 0 || + testing::GTEST_FLAG(recreate_environments_when_repeating) || testing::GTEST_FLAG(show_internal_stack_frames) || testing::GTEST_FLAG(shuffle) || testing::GTEST_FLAG(stack_trace_depth) > 0 || @@ -212,6 +213,7 @@ using testing::GTEST_FLAG(brief); using testing::GTEST_FLAG(print_time); using testing::GTEST_FLAG(random_seed); using testing::GTEST_FLAG(repeat); +using testing::GTEST_FLAG(recreate_environments_when_repeating); using testing::GTEST_FLAG(show_internal_stack_frames); using testing::GTEST_FLAG(shuffle); using testing::GTEST_FLAG(stack_trace_depth); @@ -1610,6 +1612,7 @@ class GTestFlagSaverTest : public Test { GTEST_FLAG(print_time) = true; GTEST_FLAG(random_seed) = 0; GTEST_FLAG(repeat) = 1; + GTEST_FLAG(recreate_environments_when_repeating) = true; GTEST_FLAG(shuffle) = false; GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; GTEST_FLAG(stream_result_to) = ""; @@ -1639,6 +1642,7 @@ class GTestFlagSaverTest : public Test { EXPECT_TRUE(GTEST_FLAG(print_time)); EXPECT_EQ(0, GTEST_FLAG(random_seed)); EXPECT_EQ(1, GTEST_FLAG(repeat)); + EXPECT_TRUE(GTEST_FLAG(recreate_environments_when_repeating)); EXPECT_FALSE(GTEST_FLAG(shuffle)); EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth)); EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str()); @@ -1657,6 +1661,7 @@ class GTestFlagSaverTest : public Test { GTEST_FLAG(print_time) = false; GTEST_FLAG(random_seed) = 1; GTEST_FLAG(repeat) = 100; + GTEST_FLAG(recreate_environments_when_repeating) = false; GTEST_FLAG(shuffle) = true; GTEST_FLAG(stack_trace_depth) = 1; GTEST_FLAG(stream_result_to) = "localhost:1234"; @@ -5580,6 +5585,7 @@ struct Flags { print_time(true), random_seed(0), repeat(1), + recreate_environments_when_repeating(true), shuffle(false), stack_trace_depth(kMaxStackTraceDepth), stream_result_to(""), @@ -5683,6 +5689,16 @@ struct Flags { return flags; } + // Creates a Flags struct where the gtest_recreate_environments_when_repeating + // flag has the given value. + static Flags RecreateEnvironmentsWhenRepeating( + bool recreate_environments_when_repeating) { + Flags flags; + flags.recreate_environments_when_repeating = + recreate_environments_when_repeating; + return flags; + } + // Creates a Flags struct where the gtest_shuffle flag has the given // value. static Flags Shuffle(bool shuffle) { @@ -5728,6 +5744,7 @@ struct Flags { bool print_time; int32_t random_seed; int32_t repeat; + bool recreate_environments_when_repeating; bool shuffle; int32_t stack_trace_depth; const char* stream_result_to; @@ -5751,6 +5768,7 @@ class ParseFlagsTest : public Test { GTEST_FLAG(print_time) = true; GTEST_FLAG(random_seed) = 0; GTEST_FLAG(repeat) = 1; + GTEST_FLAG(recreate_environments_when_repeating) = true; GTEST_FLAG(shuffle) = false; GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; GTEST_FLAG(stream_result_to) = ""; @@ -5783,6 +5801,8 @@ class ParseFlagsTest : public Test { EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time)); EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed)); EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat)); + EXPECT_EQ(expected.recreate_environments_when_repeating, + GTEST_FLAG(recreate_environments_when_repeating)); EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle)); EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth)); EXPECT_STREQ(expected.stream_result_to, @@ -6161,6 +6181,20 @@ TEST_F(ParseFlagsTest, Repeat) { GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false); } +// Tests parsing --gtest_recreate_environments_when_repeating +TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) { + const char* argv[] = { + "foo.exe", + "--gtest_recreate_environments_when_repeating=0", + nullptr, + }; + + const char* argv2[] = {"foo.exe", nullptr}; + + GTEST_TEST_PARSING_FLAGS_( + argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false); +} + // Tests having a --gtest_also_run_disabled_tests flag TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) { const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr}; From 977cffc4423a2d6c0df3fc9a7b5253b8f79c3f18 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Fri, 2 Jul 2021 17:01:11 -0400 Subject: [PATCH 015/472] Googletest export Introduce GTEST_FLAG_GET and GTEST_FLAG_SET macros. PiperOrigin-RevId: 382808313 --- googlemock/test/gmock-internal-utils_test.cc | 3 +- googlemock/test/gmock-matchers_test.cc | 2 +- googletest/include/gtest/gtest-death-test.h | 4 +- googletest/include/gtest/gtest.h | 21 +- .../include/gtest/internal/custom/README.md | 2 + .../internal/gtest-death-test-internal.h | 4 +- .../include/gtest/internal/gtest-port.h | 40 ++- googletest/src/gtest-death-test.cc | 83 +++--- googletest/src/gtest-internal-inl.h | 114 +++----- googletest/src/gtest-printers.cc | 2 +- googletest/src/gtest.cc | 258 +++++++++-------- googletest/test/googletest-death-test-test.cc | 54 ++-- .../test/googletest-death-test_ex_test.cc | 6 +- googletest/test/googletest-env-var-test_.cc | 26 +- googletest/test/googletest-listener-test.cc | 2 +- googletest/test/googletest-options-test.cc | 24 +- googletest/test/googletest-output-test_.cc | 4 +- googletest/test/gtest_environment_test.cc | 6 +- googletest/test/gtest_repeat_test.cc | 30 +- .../test/gtest_throw_on_failure_ex_test.cc | 2 +- googletest/test/gtest_unittest.cc | 271 ++++++++---------- 21 files changed, 470 insertions(+), 488 deletions(-) diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index 0d15e8f482..bd7e3353d9 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -440,7 +440,8 @@ TEST(LogTest, NoSkippingStackFrameInOptMode) { const std::string log = GetCapturedStdout(); std::string expected_trace = - (testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString(); + (testing::Message() << GTEST_FLAG_GET(stack_trace_depth) << "::") + .GetString(); std::string expected_message = "\nGMOCK WARNING:\n" "Test log.\n" diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index e7ce97c62c..6c22990393 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -6328,7 +6328,7 @@ TEST_P(BipartiteRandomTest, LargerNets) { int iters = GetParam().second; MatchMatrix graph(static_cast(nodes), static_cast(nodes)); - auto seed = static_cast(GTEST_FLAG(random_seed)); + auto seed = static_cast(GTEST_FLAG_GET(random_seed)); if (seed == 0) { seed = static_cast(time(nullptr)); } diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 9b4d4d1337..4df53d973d 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -40,8 +40,6 @@ #include "gtest/internal/gtest-death-test-internal.h" -namespace testing { - // This flag controls the style of death tests. Valid values are "threadsafe", // meaning that the death test child process will re-execute the test binary // from the start, running only a single death test, or "fast", @@ -49,6 +47,8 @@ namespace testing { // after forking. GTEST_DECLARE_string_(death_test_style); +namespace testing { + #if GTEST_HAS_DEATH_TEST namespace internal { diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 7e8e83ff40..482228a6a4 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -73,17 +73,6 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) -namespace testing { - -// Silence C4100 (unreferenced formal parameter) and 4805 -// unsafe mix of type 'const int' and type 'const bool' -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4805) -# pragma warning(disable:4100) -#endif - - // Declares the flags. // This flag temporary enables the disabled tests. @@ -169,6 +158,16 @@ GTEST_DECLARE_string_(stream_result_to); GTEST_DECLARE_string_(flagfile); #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ +namespace testing { + +// Silence C4100 (unreferenced formal parameter) and 4805 +// unsafe mix of type 'const int' and type 'const bool' +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4805) +#pragma warning(disable : 4100) +#endif + // The upper limit for valid stack trace depths. const int kMaxStackTraceDepth = 100; diff --git a/googletest/include/gtest/internal/custom/README.md b/googletest/include/gtest/internal/custom/README.md index ff391fb4e2..0af3539abf 100644 --- a/googletest/include/gtest/internal/custom/README.md +++ b/googletest/include/gtest/internal/custom/README.md @@ -26,6 +26,8 @@ The following macros can be defined: * `GTEST_DEFINE_bool_(name, default_val, doc)` * `GTEST_DEFINE_int32_(name, default_val, doc)` * `GTEST_DEFINE_string_(name, default_val, doc)` +* `GTEST_FLAG_GET(flag_name)` +* `GTEST_FLAG_SET(flag_name, value)` ### Logging: diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 867a840d08..44277c3869 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -42,11 +42,11 @@ #include #include +GTEST_DECLARE_string_(internal_run_death_test); + namespace testing { namespace internal { -GTEST_DECLARE_string_(internal_run_death_test); - // Names of the flags (needed for parsing Google Test flags). const char kDeathTestStyleFlag[] = "death_test_style"; const char kDeathTestUseFork[] = "death_test_use_fork"; diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 361354bf85..524bbeb011 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -2216,22 +2216,40 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver // Macros for declaring flags. -# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) -# define GTEST_DECLARE_int32_(name) \ - GTEST_API_ extern std::int32_t GTEST_FLAG(name) -# define GTEST_DECLARE_string_(name) \ - GTEST_API_ extern ::std::string GTEST_FLAG(name) +#define GTEST_DECLARE_bool_(name) \ + namespace testing { \ + GTEST_API_ extern bool GTEST_FLAG(name); \ + } +#define GTEST_DECLARE_int32_(name) \ + namespace testing { \ + GTEST_API_ extern std::int32_t GTEST_FLAG(name); \ + } +#define GTEST_DECLARE_string_(name) \ + namespace testing { \ + GTEST_API_ extern ::std::string GTEST_FLAG(name); \ + } // Macros for defining flags. -# define GTEST_DEFINE_bool_(name, default_val, doc) \ - GTEST_API_ bool GTEST_FLAG(name) = (default_val) -# define GTEST_DEFINE_int32_(name, default_val, doc) \ - GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val) -# define GTEST_DEFINE_string_(name, default_val, doc) \ - GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) +#define GTEST_DEFINE_bool_(name, default_val, doc) \ + namespace testing { \ + GTEST_API_ bool GTEST_FLAG(name) = (default_val); \ + } +#define GTEST_DEFINE_int32_(name, default_val, doc) \ + namespace testing { \ + GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val); \ + } +#define GTEST_DEFINE_string_(name, default_val, doc) \ + namespace testing { \ + GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val); \ + } #endif // !defined(GTEST_DECLARE_bool_) +#if !defined(GTEST_FLAG_GET) +#define GTEST_FLAG_GET(name) ::testing::GTEST_FLAG(name) +#define GTEST_FLAG_SET(name, value) (void)(::testing::GTEST_FLAG(name) = value) +#endif // !defined(GTEST_FLAG_GET) + // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index bf4f6331da..52af2c795e 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -96,9 +96,12 @@ namespace testing { // used internally at Google, is "threadsafe". static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE; +} // namespace testing + GTEST_DEFINE_string_( death_test_style, - internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), + testing::internal::StringFromGTestEnv("death_test_style", + testing::kDefaultDeathTestStyle), "Indicates how to run a death test in a forked child process: " "\"threadsafe\" (child process re-executes the test binary " "from the beginning, running only the specific death test) or " @@ -107,7 +110,7 @@ GTEST_DEFINE_string_( GTEST_DEFINE_bool_( death_test_use_fork, - internal::BoolFromGTestEnv("death_test_use_fork", false), + testing::internal::BoolFromGTestEnv("death_test_use_fork", false), "Instructs to use fork()/_exit() instead of clone() in death tests. " "Ignored and always uses fork() on POSIX systems where clone() is not " "implemented. Useful when running under valgrind or similar tools if " @@ -117,7 +120,6 @@ GTEST_DEFINE_bool_( "work in 99% of the cases. Once valgrind is fixed, this flag will " "most likely be removed."); -namespace internal { GTEST_DEFINE_string_( internal_run_death_test, "", "Indicates the file, line number, temporal index of " @@ -126,7 +128,8 @@ GTEST_DEFINE_string_( "the '|' characters. This flag is specified if and only if the " "current process is a sub-process launched for running a thread-safe " "death test. FOR INTERNAL USE ONLY."); -} // namespace internal + +namespace testing { #if GTEST_HAS_DEATH_TEST @@ -148,12 +151,12 @@ bool InDeathTestChild() { // On Windows and Fuchsia, death tests are thread-safe regardless of the value // of the death_test_style flag. - return !GTEST_FLAG(internal_run_death_test).empty(); + return !GTEST_FLAG_GET(internal_run_death_test).empty(); # else - if (GTEST_FLAG(death_test_style) == "threadsafe") - return !GTEST_FLAG(internal_run_death_test).empty(); + if (GTEST_FLAG_GET(death_test_style) == "threadsafe") + return !GTEST_FLAG_GET(internal_run_death_test).empty(); else return g_in_fast_death_test_child; #endif @@ -756,18 +759,18 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { nullptr)); // The even is unnamed. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr); const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + - kFilterFlag + "=" + info->test_suite_name() + - "." + info->name(); + "filter=" + info->test_suite_name() + "." + + info->name(); const std::string internal_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + - "=" + file_ + "|" + StreamableToString(line_) + "|" + - StreamableToString(death_test_index) + "|" + + std::string("--") + GTEST_FLAG_PREFIX_ + + "internal_run_death_test=" + file_ + "|" + StreamableToString(line_) + + "|" + StreamableToString(death_test_index) + "|" + StreamableToString(static_cast(::GetCurrentProcessId())) + // size_t has the same width as pointers on both 32-bit and 64-bit // Windows platforms. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. - "|" + StreamableToString(reinterpret_cast(write_handle)) + - "|" + StreamableToString(reinterpret_cast(event_handle_.Get())); + "|" + StreamableToString(reinterpret_cast(write_handle)) + "|" + + StreamableToString(reinterpret_cast(event_handle_.Get())); char executable_path[_MAX_PATH + 1]; // NOLINT GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr, @@ -987,8 +990,8 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { // Build the child process command line. const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + - kFilterFlag + "=" + info->test_suite_name() + - "." + info->name(); + "filter=" + info->test_suite_name() + "." + + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" @@ -1351,7 +1354,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { # endif // GTEST_OS_LINUX # if GTEST_HAS_CLONE - const bool use_fork = GTEST_FLAG(death_test_use_fork); + const bool use_fork = GTEST_FLAG_GET(death_test_use_fork); if (!use_fork) { static const bool stack_grows_down = StackGrowsDown(); @@ -1420,13 +1423,13 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + - kFilterFlag + "=" + info->test_suite_name() + - "." + info->name(); - const std::string internal_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" - + file_ + "|" + StreamableToString(line_) + "|" - + StreamableToString(death_test_index) + "|" - + StreamableToString(pipe_fd[1]); + "filter=" + info->test_suite_name() + "." + + info->name(); + const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + + "internal_run_death_test=" + file_ + "|" + + StreamableToString(line_) + "|" + + StreamableToString(death_test_index) + "|" + + StreamableToString(pipe_fd[1]); Arguments args; args.AddArguments(GetArgvsForDeathTestChildProcess()); args.AddArgument(filter_flag.c_str()); @@ -1482,32 +1485,32 @@ bool DefaultDeathTestFactory::Create(const char* statement, # if GTEST_OS_WINDOWS - if (GTEST_FLAG(death_test_style) == "threadsafe" || - GTEST_FLAG(death_test_style) == "fast") { + if (GTEST_FLAG_GET(death_test_style) == "threadsafe" || + GTEST_FLAG_GET(death_test_style) == "fast") { *test = new WindowsDeathTest(statement, std::move(matcher), file, line); } # elif GTEST_OS_FUCHSIA - if (GTEST_FLAG(death_test_style) == "threadsafe" || - GTEST_FLAG(death_test_style) == "fast") { + if (GTEST_FLAG_GET(death_test_style) == "threadsafe" || + GTEST_FLAG_GET(death_test_style) == "fast") { *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line); } # else - if (GTEST_FLAG(death_test_style) == "threadsafe") { + if (GTEST_FLAG_GET(death_test_style) == "threadsafe") { *test = new ExecDeathTest(statement, std::move(matcher), file, line); - } else if (GTEST_FLAG(death_test_style) == "fast") { + } else if (GTEST_FLAG_GET(death_test_style) == "fast") { *test = new NoExecDeathTest(statement, std::move(matcher)); } # endif // GTEST_OS_WINDOWS else { // NOLINT - this is more readable than unbalanced brackets inside #if. - DeathTest::set_last_death_test_message( - "Unknown death test style \"" + GTEST_FLAG(death_test_style) - + "\" encountered"); + DeathTest::set_last_death_test_message("Unknown death test style \"" + + GTEST_FLAG_GET(death_test_style) + + "\" encountered"); return false; } @@ -1584,14 +1587,14 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id, // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { - if (GTEST_FLAG(internal_run_death_test) == "") return nullptr; + if (GTEST_FLAG_GET(internal_run_death_test) == "") return nullptr; // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we // can use it here. int line = -1; int index = -1; ::std::vector< ::std::string> fields; - SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); + SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields); int write_fd = -1; # if GTEST_OS_WINDOWS @@ -1607,7 +1610,7 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + - GTEST_FLAG(internal_run_death_test)); + GTEST_FLAG_GET(internal_run_death_test)); } write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, @@ -1618,8 +1621,8 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index)) { - DeathTestAbort("Bad --gtest_internal_run_death_test flag: " - + GTEST_FLAG(internal_run_death_test)); + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG_GET(internal_run_death_test)); } # else @@ -1628,8 +1631,8 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &write_fd)) { - DeathTestAbort("Bad --gtest_internal_run_death_test flag: " - + GTEST_FLAG(internal_run_death_test)); + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + + GTEST_FLAG_GET(internal_run_death_test)); } # endif // GTEST_OS_WINDOWS diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 59762c7ea2..075b84c258 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -64,8 +64,6 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) -namespace testing { - // Declares the flags. // // We don't want the users to modify this flag in the code, but want @@ -73,34 +71,13 @@ namespace testing { // declare it here as opposed to in gtest.h. GTEST_DECLARE_bool_(death_test_use_fork); +namespace testing { namespace internal { // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; -// Names of the flags (needed for parsing Google Test flags). -const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; -const char kBreakOnFailureFlag[] = "break_on_failure"; -const char kCatchExceptionsFlag[] = "catch_exceptions"; -const char kColorFlag[] = "color"; -const char kFailFast[] = "fail_fast"; -const char kFilterFlag[] = "filter"; -const char kListTestsFlag[] = "list_tests"; -const char kOutputFlag[] = "output"; -const char kBriefFlag[] = "brief"; -const char kPrintTimeFlag[] = "print_time"; -const char kPrintUTF8Flag[] = "print_utf8"; -const char kRandomSeedFlag[] = "random_seed"; -const char kRepeatFlag[] = "repeat"; -const char kRecreateEnvironmentsWhenRepeatingFlag[] = - "recreate_environments_when_repeating"; -const char kShuffleFlag[] = "shuffle"; -const char kStackTraceDepthFlag[] = "stack_trace_depth"; -const char kStreamResultToFlag[] = "stream_result_to"; -const char kThrowOnFailureFlag[] = "throw_on_failure"; -const char kFlagfileFlag[] = "flagfile"; - // A valid random seed must be in [1, kMaxRandomSeed]. const int kMaxRandomSeed = 99999; @@ -127,8 +104,7 @@ GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. -GTEST_API_ bool ParseInt32Flag( - const char* str, const char* flag, int32_t* value); +GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. @@ -162,54 +138,54 @@ class GTestFlagSaver { public: // The c'tor. GTestFlagSaver() { - also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); - break_on_failure_ = GTEST_FLAG(break_on_failure); - catch_exceptions_ = GTEST_FLAG(catch_exceptions); - color_ = GTEST_FLAG(color); - death_test_style_ = GTEST_FLAG(death_test_style); - death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); - fail_fast_ = GTEST_FLAG(fail_fast); - filter_ = GTEST_FLAG(filter); - internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); - list_tests_ = GTEST_FLAG(list_tests); - output_ = GTEST_FLAG(output); - brief_ = GTEST_FLAG(brief); - print_time_ = GTEST_FLAG(print_time); - print_utf8_ = GTEST_FLAG(print_utf8); - random_seed_ = GTEST_FLAG(random_seed); - repeat_ = GTEST_FLAG(repeat); + also_run_disabled_tests_ = GTEST_FLAG_GET(also_run_disabled_tests); + break_on_failure_ = GTEST_FLAG_GET(break_on_failure); + catch_exceptions_ = GTEST_FLAG_GET(catch_exceptions); + color_ = GTEST_FLAG_GET(color); + death_test_style_ = GTEST_FLAG_GET(death_test_style); + death_test_use_fork_ = GTEST_FLAG_GET(death_test_use_fork); + fail_fast_ = GTEST_FLAG_GET(fail_fast); + filter_ = GTEST_FLAG_GET(filter); + internal_run_death_test_ = GTEST_FLAG_GET(internal_run_death_test); + list_tests_ = GTEST_FLAG_GET(list_tests); + output_ = GTEST_FLAG_GET(output); + brief_ = GTEST_FLAG_GET(brief); + print_time_ = GTEST_FLAG_GET(print_time); + print_utf8_ = GTEST_FLAG_GET(print_utf8); + random_seed_ = GTEST_FLAG_GET(random_seed); + repeat_ = GTEST_FLAG_GET(repeat); recreate_environments_when_repeating_ = - GTEST_FLAG(recreate_environments_when_repeating); - shuffle_ = GTEST_FLAG(shuffle); - stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); - stream_result_to_ = GTEST_FLAG(stream_result_to); - throw_on_failure_ = GTEST_FLAG(throw_on_failure); + GTEST_FLAG_GET(recreate_environments_when_repeating); + shuffle_ = GTEST_FLAG_GET(shuffle); + stack_trace_depth_ = GTEST_FLAG_GET(stack_trace_depth); + stream_result_to_ = GTEST_FLAG_GET(stream_result_to); + throw_on_failure_ = GTEST_FLAG_GET(throw_on_failure); } // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. ~GTestFlagSaver() { - GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; - GTEST_FLAG(break_on_failure) = break_on_failure_; - GTEST_FLAG(catch_exceptions) = catch_exceptions_; - GTEST_FLAG(color) = color_; - GTEST_FLAG(death_test_style) = death_test_style_; - GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; - GTEST_FLAG(filter) = filter_; - GTEST_FLAG(fail_fast) = fail_fast_; - GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; - GTEST_FLAG(list_tests) = list_tests_; - GTEST_FLAG(output) = output_; - GTEST_FLAG(brief) = brief_; - GTEST_FLAG(print_time) = print_time_; - GTEST_FLAG(print_utf8) = print_utf8_; - GTEST_FLAG(random_seed) = random_seed_; - GTEST_FLAG(repeat) = repeat_; - GTEST_FLAG(recreate_environments_when_repeating) = - recreate_environments_when_repeating_; - GTEST_FLAG(shuffle) = shuffle_; - GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; - GTEST_FLAG(stream_result_to) = stream_result_to_; - GTEST_FLAG(throw_on_failure) = throw_on_failure_; + GTEST_FLAG_SET(also_run_disabled_tests, also_run_disabled_tests_); + GTEST_FLAG_SET(break_on_failure, break_on_failure_); + GTEST_FLAG_SET(catch_exceptions, catch_exceptions_); + GTEST_FLAG_SET(color, color_); + GTEST_FLAG_SET(death_test_style, death_test_style_); + GTEST_FLAG_SET(death_test_use_fork, death_test_use_fork_); + GTEST_FLAG_SET(filter, filter_); + GTEST_FLAG_SET(fail_fast, fail_fast_); + GTEST_FLAG_SET(internal_run_death_test, internal_run_death_test_); + GTEST_FLAG_SET(list_tests, list_tests_); + GTEST_FLAG_SET(output, output_); + GTEST_FLAG_SET(brief, brief_); + GTEST_FLAG_SET(print_time, print_time_); + GTEST_FLAG_SET(print_utf8, print_utf8_); + GTEST_FLAG_SET(random_seed, random_seed_); + GTEST_FLAG_SET(repeat, repeat_); + GTEST_FLAG_SET(recreate_environments_when_repeating, + recreate_environments_when_repeating_); + GTEST_FLAG_SET(shuffle, shuffle_); + GTEST_FLAG_SET(stack_trace_depth, stack_trace_depth_); + GTEST_FLAG_SET(stream_result_to, stream_result_to_); + GTEST_FLAG_SET(throw_on_failure, throw_on_failure_); } private: diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc index 1b68fcb500..41e29ccd60 100644 --- a/googletest/src/gtest-printers.cc +++ b/googletest/src/gtest-printers.cc @@ -502,7 +502,7 @@ void ConditionalPrintAsText(const char* str, size_t length, ostream* os) { void PrintStringTo(const ::std::string& s, ostream* os) { if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) { - if (GTEST_FLAG(print_utf8)) { + if (GTEST_FLAG_GET(print_utf8)) { ConditionalPrintAsText(s.data(), s.size(), os); } } diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 9a380ebdc8..5a38768e4c 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -216,28 +216,33 @@ static bool GetDefaultFailFast() { return false; } +} // namespace testing + GTEST_DEFINE_bool_( - fail_fast, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()), + fail_fast, + testing::internal::BoolFromGTestEnv("fail_fast", + testing::GetDefaultFailFast()), "True if and only if a test failure should stop further test execution."); GTEST_DEFINE_bool_( also_run_disabled_tests, - internal::BoolFromGTestEnv("also_run_disabled_tests", false), + testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false), "Run disabled tests too, in addition to the tests normally being run."); GTEST_DEFINE_bool_( - break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false), + break_on_failure, + testing::internal::BoolFromGTestEnv("break_on_failure", false), "True if and only if a failed assertion should be a debugger " "break-point."); GTEST_DEFINE_bool_(catch_exceptions, - internal::BoolFromGTestEnv("catch_exceptions", true), + testing::internal::BoolFromGTestEnv("catch_exceptions", + true), "True if and only if " GTEST_NAME_ " should catch exceptions and treat them as test failures."); GTEST_DEFINE_string_( - color, - internal::StringFromGTestEnv("color", "auto"), + color, testing::internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " @@ -245,7 +250,8 @@ GTEST_DEFINE_string_( GTEST_DEFINE_string_( filter, - internal::StringFromGTestEnv("filter", GetDefaultFilter()), + testing::internal::StringFromGTestEnv("filter", + testing::GetDefaultFilter()), "A colon-separated list of glob (not regex) patterns " "for filtering the tests to run, optionally followed by a " "'-' and a : separated list of negative patterns (tests to " @@ -254,8 +260,10 @@ GTEST_DEFINE_string_( GTEST_DEFINE_bool_( install_failure_signal_handler, - internal::BoolFromGTestEnv("install_failure_signal_handler", false), - "If true and supported on the current platform, " GTEST_NAME_ " should " + testing::internal::BoolFromGTestEnv("install_failure_signal_handler", + false), + "If true and supported on the current platform, " GTEST_NAME_ + " should " "install a signal handler that dumps debugging information when fatal " "signals are raised."); @@ -269,8 +277,8 @@ GTEST_DEFINE_bool_(list_tests, false, // '' GTEST_DEFINE_string_( output, - internal::StringFromGTestEnv("output", - internal::OutputFlagAlsoCheckEnvVar().c_str()), + testing::internal::StringFromGTestEnv( + "output", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()), "A format (defaults to \"xml\" but can be specified to be \"json\"), " "optionally followed by a colon and an output file name or directory. " "A directory is indicated by a trailing pathname separator. " @@ -281,32 +289,33 @@ GTEST_DEFINE_string_( "digits."); GTEST_DEFINE_bool_( - brief, internal::BoolFromGTestEnv("brief", false), + brief, testing::internal::BoolFromGTestEnv("brief", false), "True if only test failures should be displayed in text output."); -GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true), +GTEST_DEFINE_bool_(print_time, + testing::internal::BoolFromGTestEnv("print_time", true), "True if and only if " GTEST_NAME_ " should display elapsed time in text output."); -GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true), +GTEST_DEFINE_bool_(print_utf8, + testing::internal::BoolFromGTestEnv("print_utf8", true), "True if and only if " GTEST_NAME_ " prints UTF8 characters as text."); GTEST_DEFINE_int32_( - random_seed, - internal::Int32FromGTestEnv("random_seed", 0), + random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time."); GTEST_DEFINE_int32_( - repeat, - internal::Int32FromGTestEnv("repeat", 1), + repeat, testing::internal::Int32FromGTestEnv("repeat", 1), "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); GTEST_DEFINE_bool_( recreate_environments_when_repeating, - internal::BoolFromGTestEnv("recreate_environments_when_repeating", true), + testing::internal::BoolFromGTestEnv("recreate_environments_when_repeating", + true), "Controls whether global test environments are recreated for each repeat " "of the tests. If set to false the global test environments are only set " "up once, for the first iteration, and only torn down once, for the last. " @@ -320,37 +329,39 @@ GTEST_DEFINE_bool_(show_internal_stack_frames, false, " should include internal stack frames when " "printing test failure stack traces."); -GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false), +GTEST_DEFINE_bool_(shuffle, + testing::internal::BoolFromGTestEnv("shuffle", false), "True if and only if " GTEST_NAME_ " should randomize tests' order on every run."); GTEST_DEFINE_int32_( stack_trace_depth, - internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), + testing::internal::Int32FromGTestEnv("stack_trace_depth", + testing::kMaxStackTraceDepth), "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); GTEST_DEFINE_string_( stream_result_to, - internal::StringFromGTestEnv("stream_result_to", ""), + testing::internal::StringFromGTestEnv("stream_result_to", ""), "This flag specifies the host name and the port number on which to stream " "test results. Example: \"localhost:555\". The flag is effective only on " "Linux."); GTEST_DEFINE_bool_( throw_on_failure, - internal::BoolFromGTestEnv("throw_on_failure", false), + testing::internal::BoolFromGTestEnv("throw_on_failure", false), "When this flag is specified, a failed assertion will throw an exception " "if exceptions are enabled or exit the program with a non-zero code " "otherwise. For use with an external test framework."); #if GTEST_USE_OWN_FLAGFILE_FLAG_ GTEST_DEFINE_string_( - flagfile, - internal::StringFromGTestEnv("flagfile", ""), + flagfile, testing::internal::StringFromGTestEnv("flagfile", ""), "This flag specifies the flagfile to read command-line flags from."); #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ +namespace testing { namespace internal { // Generates a random number from [0, range), using a Linear @@ -617,7 +628,8 @@ FilePath GetCurrentExecutableName() { // Returns the output format, or "" for normal printed output. std::string UnitTestOptions::GetOutputFormat() { - const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); + std::string s = GTEST_FLAG_GET(output); + const char* const gtest_output_flag = s.c_str(); const char* const colon = strchr(gtest_output_flag, ':'); return (colon == nullptr) ? std::string(gtest_output_flag) @@ -628,7 +640,8 @@ std::string UnitTestOptions::GetOutputFormat() { // Returns the name of the requested output file, or the default if none // was explicitly specified. std::string UnitTestOptions::GetAbsolutePathToOutputFile() { - const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); + std::string s = GTEST_FLAG_GET(output); + const char* const gtest_output_flag = s.c_str(); std::string format = GetOutputFormat(); if (format.empty()) @@ -743,12 +756,13 @@ bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, // Split --gtest_filter at '-', if there is one, to separate into // positive filter and negative filter portions - const char* const p = GTEST_FLAG(filter).c_str(); + std::string str = GTEST_FLAG_GET(filter); + const char* const p = str.c_str(); const char* const dash = strchr(p, '-'); std::string positive; std::string negative; if (dash == nullptr) { - positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter + positive = str.c_str(); // Whole string is a positive filter negative = ""; } else { positive = std::string(p, dash); // Everything up to the dash @@ -782,7 +796,7 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { bool should_handle = true; - if (!GTEST_FLAG(catch_exceptions)) + if (!GTEST_FLAG_GET(catch_exceptions)) should_handle = false; else if (exception_code == EXCEPTION_BREAKPOINT) should_handle = false; @@ -1035,11 +1049,10 @@ int UnitTestImpl::test_to_run_count() const { // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { return os_stack_trace_getter()->CurrentStackTrace( - static_cast(GTEST_FLAG(stack_trace_depth)), - skip_count + 1 + static_cast(GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1 // Skips the user-specified number of frames plus this function // itself. - ); // NOLINT + ); // NOLINT } // A helper class for measuring elapsed times. @@ -2634,7 +2647,7 @@ Result HandleExceptionsInMethodIfSupported( // try { // // Perform the test method. // } catch (...) { - // if (GTEST_FLAG(catch_exceptions)) + // if (GTEST_FLAG_GET(catch_exceptions)) // // Report the exception as failure. // else // throw; // Re-throws the original exception. @@ -3024,7 +3037,8 @@ void TestSuite::Run() { internal::Timer timer; for (int i = 0; i < total_test_count(); i++) { GetMutableTestInfo(i)->Run(); - if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) { + if (GTEST_FLAG_GET(fail_fast) && + GetMutableTestInfo(i)->result()->Failed()) { for (int j = i + 1; j < total_test_count(); j++) { GetMutableTestInfo(j)->Skip(); } @@ -3243,7 +3257,8 @@ static const char* GetAnsiColorCode(GTestColor color) { // Returns true if and only if Google Test should use colors in the output. bool ShouldUseColor(bool stdout_is_tty) { - const char* const gtest_color = GTEST_FLAG(color).c_str(); + std::string c = GTEST_FLAG_GET(color); + const char* const gtest_color = c.c_str(); if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW @@ -3398,10 +3413,11 @@ class PrettyUnitTestResultPrinter : public TestEventListener { // Fired before each iteration of tests starts. void PrettyUnitTestResultPrinter::OnTestIterationStart( const UnitTest& unit_test, int iteration) { - if (GTEST_FLAG(repeat) != 1) + if (GTEST_FLAG_GET(repeat) != 1) printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); - const char* const filter = GTEST_FLAG(filter).c_str(); + std::string f = GTEST_FLAG_GET(filter); + const char* const filter = f.c_str(); // Prints the filter if it's not *. This reminds the user that some // tests may be skipped. @@ -3417,7 +3433,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart( internal::posix::GetEnv(kTestTotalShards)); } - if (GTEST_FLAG(shuffle)) { + if (GTEST_FLAG_GET(shuffle)) { ColoredPrintf(GTestColor::kYellow, "Note: Randomizing tests' orders with a seed of %d .\n", unit_test.random_seed()); @@ -3500,7 +3516,7 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); - if (GTEST_FLAG(print_time)) { + if (GTEST_FLAG_GET(print_time)) { printf(" (%s ms)\n", internal::StreamableToString( test_info.result()->elapsed_time()).c_str()); } else { @@ -3511,7 +3527,7 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { - if (!GTEST_FLAG(print_time)) return; + if (!GTEST_FLAG_GET(print_time)) return; const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); @@ -3522,7 +3538,7 @@ void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { } #else void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) { - if (!GTEST_FLAG(print_time)) return; + if (!GTEST_FLAG_GET(print_time)) return; const std::string counts = FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); @@ -3618,7 +3634,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); - if (GTEST_FLAG(print_time)) { + if (GTEST_FLAG_GET(print_time)) { printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); } @@ -3639,7 +3655,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, } int num_disabled = unit_test.reportable_disabled_test_count(); - if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { + if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) { if (unit_test.Passed()) { printf("\n"); // Add a spacer if no FAILURE banner is displayed. } @@ -3711,7 +3727,7 @@ void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { PrintTestName(test_info.test_suite_name(), test_info.name()); PrintFullTestCommentIfPresent(test_info); - if (GTEST_FLAG(print_time)) { + if (GTEST_FLAG_GET(print_time)) { printf(" (%s ms)\n", internal::StreamableToString(test_info.result()->elapsed_time()) .c_str()); @@ -3728,7 +3744,7 @@ void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); - if (GTEST_FLAG(print_time)) { + if (GTEST_FLAG_GET(print_time)) { printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); } @@ -3743,7 +3759,7 @@ void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, } int num_disabled = unit_test.reportable_disabled_test_count(); - if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { + if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) { if (unit_test.Passed()) { printf("\n"); // Add a spacer if no FAILURE banner is displayed. } @@ -4227,7 +4243,7 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, OutputXmlAttribute(stream, kTestsuite, "type_param", test_info.type_param()); } - if (GTEST_FLAG(list_tests)) { + if (GTEST_FLAG_GET(list_tests)) { OutputXmlAttribute(stream, kTestsuite, "file", test_info.file()); OutputXmlAttribute(stream, kTestsuite, "line", StreamableToString(test_info.line())); @@ -4306,7 +4322,7 @@ void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream, OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name()); OutputXmlAttribute(stream, kTestsuite, "tests", StreamableToString(test_suite.reportable_test_count())); - if (!GTEST_FLAG(list_tests)) { + if (!GTEST_FLAG_GET(list_tests)) { OutputXmlAttribute(stream, kTestsuite, "failures", StreamableToString(test_suite.failed_test_count())); OutputXmlAttribute( @@ -4354,7 +4370,7 @@ void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, stream, kTestsuites, "timestamp", FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); - if (GTEST_FLAG(shuffle)) { + if (GTEST_FLAG_GET(shuffle)) { OutputXmlAttribute(stream, kTestsuites, "random_seed", StreamableToString(unit_test.random_seed())); } @@ -4631,7 +4647,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult( *stream << Indent(4) << "{\n"; OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6)); OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6)); - if (!GTEST_FLAG(list_tests)) { + if (!GTEST_FLAG_GET(list_tests)) { OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6)); OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6)); OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6)); @@ -4685,7 +4701,7 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(), kIndent); } - if (GTEST_FLAG(list_tests)) { + if (GTEST_FLAG_GET(list_tests)) { OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); *stream << "\n" << Indent(8) << "}"; @@ -4749,7 +4765,7 @@ void JsonUnitTestResultPrinter::PrintJsonTestSuite( OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent); OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(), kIndent); - if (!GTEST_FLAG(list_tests)) { + if (!GTEST_FLAG_GET(list_tests)) { OutputJsonKey(stream, kTestsuite, "failures", test_suite.failed_test_count(), kIndent); OutputJsonKey(stream, kTestsuite, "disabled", @@ -4796,7 +4812,7 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, OutputJsonKey(stream, kTestsuites, "disabled", unit_test.reportable_disabled_test_count(), kIndent); OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent); - if (GTEST_FLAG(shuffle)) { + if (GTEST_FLAG_GET(shuffle)) { OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(), kIndent); } @@ -4973,7 +4989,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) for (int i = 0; i < raw_stack_size; ++i) { if (raw_stack[i] == caller_frame && - !GTEST_FLAG(show_internal_stack_frames)) { + !GTEST_FLAG_GET(show_internal_stack_frames)) { // Add a marker to the trace and stop adding frames. absl::StrAppend(&result, kElidedFramesMarker, "\n"); break; @@ -5325,7 +5341,7 @@ void UnitTest::AddTestPartResult( // in the code (perhaps in order to use Google Test assertions // with another testing framework) and specify the former on the // command line for debugging. - if (GTEST_FLAG(break_on_failure)) { + if (GTEST_FLAG_GET(break_on_failure)) { #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Using DebugBreak on Windows allows gtest to still break into a debugger // when a failure happens and both the --gtest_break_on_failure and @@ -5342,7 +5358,7 @@ void UnitTest::AddTestPartResult( // portability: some debuggers don't correctly trap abort(). *static_cast(nullptr) = 1; #endif // GTEST_OS_WINDOWS - } else if (GTEST_FLAG(throw_on_failure)) { + } else if (GTEST_FLAG_GET(throw_on_failure)) { #if GTEST_HAS_EXCEPTIONS throw internal::GoogleTestFailureException(result); #else @@ -5371,7 +5387,7 @@ void UnitTest::RecordProperty(const std::string& key, // from the main thread. int UnitTest::Run() { const bool in_death_test_child_process = - internal::GTEST_FLAG(internal_run_death_test).length() > 0; + GTEST_FLAG_GET(internal_run_death_test).length() > 0; // Google Test implements this protocol for catching that a test // program exits before returning control to Google Test: @@ -5401,7 +5417,7 @@ int UnitTest::Run() { // Captures the value of GTEST_FLAG(catch_exceptions). This value will be // used for the duration of the program. - impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); + impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions)); #if GTEST_OS_WINDOWS // Either the user wants Google Test to catch exceptions thrown by the @@ -5428,7 +5444,7 @@ int UnitTest::Run() { // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement // executed. Google Test will notify the user of any unexpected // failure via stderr. - if (!GTEST_FLAG(break_on_failure)) + if (!GTEST_FLAG_GET(break_on_failure)) _set_abort_behavior( 0x0, // Clear the following flags: _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. @@ -5610,7 +5626,7 @@ void UnitTestImpl::ConfigureXmlOutput() { // Initializes event listeners for streaming test results in string form. // Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureStreamingOutput() { - const std::string& target = GTEST_FLAG(stream_result_to); + const std::string& target = GTEST_FLAG_GET(stream_result_to); if (!target.empty()) { const size_t pos = target.find(':'); if (pos != std::string::npos) { @@ -5653,7 +5669,7 @@ void UnitTestImpl::PostFlagParsingInit() { // to shut down the default XML output before invoking RUN_ALL_TESTS. ConfigureXmlOutput(); - if (GTEST_FLAG(brief)) { + if (GTEST_FLAG_GET(brief)) { listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter); } @@ -5663,7 +5679,7 @@ void UnitTestImpl::PostFlagParsingInit() { #endif // GTEST_CAN_STREAM_RESULTS_ #if GTEST_HAS_ABSL - if (GTEST_FLAG(install_failure_signal_handler)) { + if (GTEST_FLAG_GET(install_failure_signal_handler)) { absl::FailureSignalHandlerOptions options; absl::InstallFailureSignalHandler(options); } @@ -5796,14 +5812,15 @@ bool UnitTestImpl::RunAllTests() { : IGNORE_SHARDING_PROTOCOL) > 0; // Lists the tests and exits if the --gtest_list_tests flag was specified. - if (GTEST_FLAG(list_tests)) { + if (GTEST_FLAG_GET(list_tests)) { // This must be called *after* FilterTests() has been called. ListTestsMatchingFilter(); return true; } - random_seed_ = GTEST_FLAG(shuffle) ? - GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; + random_seed_ = GTEST_FLAG_GET(shuffle) + ? GetRandomSeedFromFlag(GTEST_FLAG_GET(random_seed)) + : 0; // True if and only if at least one test has failed. bool failed = false; @@ -5815,7 +5832,7 @@ bool UnitTestImpl::RunAllTests() { // How many times to repeat the tests? We don't want to repeat them // when we are inside the subprocess of a death test. - const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); + const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG_GET(repeat); // Repeats forever if the repeat count is negative. const bool gtest_repeat_forever = repeat < 0; @@ -5827,7 +5844,8 @@ bool UnitTestImpl::RunAllTests() { // resources that are external to this process. Without this check there would // be no way to clean up those external resources automatically. const bool recreate_environments_when_repeating = - GTEST_FLAG(recreate_environments_when_repeating) || gtest_repeat_forever; + GTEST_FLAG_GET(recreate_environments_when_repeating) || + gtest_repeat_forever; for (int i = 0; gtest_repeat_forever || i != repeat; i++) { // We want to preserve failures generated by ad-hoc test @@ -5837,7 +5855,7 @@ bool UnitTestImpl::RunAllTests() { Timer timer; // Shuffles test suites and tests if requested. - if (has_tests_to_run && GTEST_FLAG(shuffle)) { + if (has_tests_to_run && GTEST_FLAG_GET(shuffle)) { random()->Reseed(static_cast(random_seed_)); // This should be done before calling OnTestIterationStart(), // such that a test event listener can see the actual test order @@ -5878,7 +5896,7 @@ bool UnitTestImpl::RunAllTests() { for (int test_index = 0; test_index < total_test_suite_count(); test_index++) { GetMutableSuiteCase(test_index)->Run(); - if (GTEST_FLAG(fail_fast) && + if (GTEST_FLAG_GET(fail_fast) && GetMutableSuiteCase(test_index)->Failed()) { for (int j = test_index + 1; j < total_test_suite_count(); j++) { GetMutableSuiteCase(j)->Skip(); @@ -5925,7 +5943,7 @@ bool UnitTestImpl::RunAllTests() { // (it's always safe to unshuffle the tests). UnshuffleTests(); - if (GTEST_FLAG(shuffle)) { + if (GTEST_FLAG_GET(shuffle)) { // Picks a new random seed for each iteration. random_seed_ = GetNextRandomSeed(random_seed_); } @@ -6082,7 +6100,7 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { test_info->matches_filter_ = matches_filter; const bool is_runnable = - (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && + (GTEST_FLAG_GET(also_run_disabled_tests) || !is_disabled) && matches_filter; const bool is_in_another_shard = @@ -6293,13 +6311,14 @@ bool SkipPrefix(const char* prefix, const char** pstr) { // part can be omitted. // // Returns the value of the flag, or NULL if the parsing failed. -static const char* ParseFlagValue(const char* str, const char* flag, +static const char* ParseFlagValue(const char* str, const char* flag_name, bool def_optional) { // str and flag must not be NULL. - if (str == nullptr || flag == nullptr) return nullptr; + if (str == nullptr || flag_name == nullptr) return nullptr; // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. - const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; + const std::string flag_str = + std::string("--") + GTEST_FLAG_PREFIX_ + flag_name; const size_t flag_len = flag_str.length(); if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; @@ -6330,9 +6349,9 @@ static const char* ParseFlagValue(const char* str, const char* flag, // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. -static bool ParseBoolFlag(const char* str, const char* flag, bool* value) { +static bool ParseFlag(const char* str, const char* flag_name, bool* value) { // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, true); + const char* const value_str = ParseFlagValue(str, flag_name, true); // Aborts if the parsing failed. if (value_str == nullptr) return false; @@ -6346,16 +6365,16 @@ static bool ParseBoolFlag(const char* str, const char* flag, bool* value) { // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. -bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) { +bool ParseFlag(const char* str, const char* flag_name, int32_t* value) { // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); + const char* const value_str = ParseFlagValue(str, flag_name, false); // Aborts if the parsing failed. if (value_str == nullptr) return false; // Sets *value to the value of the flag. - return ParseInt32(Message() << "The value of flag --" << flag, - value_str, value); + return ParseInt32(Message() << "The value of flag --" << flag_name, value_str, + value); } // Parses a string for a string flag, in the form of "--flag=value". @@ -6363,9 +6382,9 @@ bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) { // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. template -static bool ParseStringFlag(const char* str, const char* flag, String* value) { +static bool ParseFlag(const char* str, const char* flag_name, String* value) { // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); + const char* const value_str = ParseFlagValue(str, flag_name, false); // Aborts if the parsing failed. if (value_str == nullptr) return false; @@ -6530,43 +6549,44 @@ static const char kColorEncodedHelpMessage[] = "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; static bool ParseGoogleTestFlag(const char* const arg) { - return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, - >EST_FLAG(also_run_disabled_tests)) || - ParseBoolFlag(arg, kBreakOnFailureFlag, - >EST_FLAG(break_on_failure)) || - ParseBoolFlag(arg, kCatchExceptionsFlag, - >EST_FLAG(catch_exceptions)) || - ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || - ParseStringFlag(arg, kDeathTestStyleFlag, - >EST_FLAG(death_test_style)) || - ParseBoolFlag(arg, kDeathTestUseFork, - >EST_FLAG(death_test_use_fork)) || - ParseBoolFlag(arg, kFailFast, >EST_FLAG(fail_fast)) || - ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || - ParseStringFlag(arg, kInternalRunDeathTestFlag, - >EST_FLAG(internal_run_death_test)) || - ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || - ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || - ParseBoolFlag(arg, kBriefFlag, >EST_FLAG(brief)) || - ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || - ParseBoolFlag(arg, kPrintUTF8Flag, >EST_FLAG(print_utf8)) || - ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || - ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || - ParseBoolFlag(arg, kRecreateEnvironmentsWhenRepeatingFlag, - >EST_FLAG(recreate_environments_when_repeating)) || - ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || - ParseInt32Flag(arg, kStackTraceDepthFlag, - >EST_FLAG(stack_trace_depth)) || - ParseStringFlag(arg, kStreamResultToFlag, - >EST_FLAG(stream_result_to)) || - ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure)); +#define GTEST_INTERNAL_PARSE_FLAG(flag_name) \ + do { \ + auto value = GTEST_FLAG_GET(flag_name); \ + if (ParseFlag(arg, #flag_name, &value)) { \ + GTEST_FLAG_SET(flag_name, value); \ + return true; \ + } \ + } while (false) + + GTEST_INTERNAL_PARSE_FLAG(also_run_disabled_tests); + GTEST_INTERNAL_PARSE_FLAG(break_on_failure); + GTEST_INTERNAL_PARSE_FLAG(catch_exceptions); + GTEST_INTERNAL_PARSE_FLAG(color); + GTEST_INTERNAL_PARSE_FLAG(death_test_style); + GTEST_INTERNAL_PARSE_FLAG(death_test_use_fork); + GTEST_INTERNAL_PARSE_FLAG(fail_fast); + GTEST_INTERNAL_PARSE_FLAG(filter); + GTEST_INTERNAL_PARSE_FLAG(internal_run_death_test); + GTEST_INTERNAL_PARSE_FLAG(list_tests); + GTEST_INTERNAL_PARSE_FLAG(output); + GTEST_INTERNAL_PARSE_FLAG(brief); + GTEST_INTERNAL_PARSE_FLAG(print_time); + GTEST_INTERNAL_PARSE_FLAG(print_utf8); + GTEST_INTERNAL_PARSE_FLAG(random_seed); + GTEST_INTERNAL_PARSE_FLAG(repeat); + GTEST_INTERNAL_PARSE_FLAG(recreate_environments_when_repeating); + GTEST_INTERNAL_PARSE_FLAG(shuffle); + GTEST_INTERNAL_PARSE_FLAG(stack_trace_depth); + GTEST_INTERNAL_PARSE_FLAG(stream_result_to); + GTEST_INTERNAL_PARSE_FLAG(throw_on_failure); + return false; } #if GTEST_USE_OWN_FLAGFILE_FLAG_ static void LoadFlagsFromFile(const std::string& path) { FILE* flagfile = posix::FOpen(path.c_str(), "r"); if (!flagfile) { - GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile) + GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG_GET(flagfile) << "\""; } std::string contents(ReadEntireFile(flagfile)); @@ -6587,20 +6607,20 @@ static void LoadFlagsFromFile(const std::string& path) { // instantiated to either char or wchar_t. template void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { + std::string flagfile_value; for (int i = 1; i < *argc; i++) { const std::string arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); - using internal::ParseBoolFlag; - using internal::ParseInt32Flag; - using internal::ParseStringFlag; + using internal::ParseFlag; bool remove_flag = false; if (ParseGoogleTestFlag(arg)) { remove_flag = true; #if GTEST_USE_OWN_FLAGFILE_FLAG_ - } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) { - LoadFlagsFromFile(GTEST_FLAG(flagfile)); + } else if (ParseFlag(arg, "flagfile", &flagfile_value)) { + GTEST_FLAG_SET(flagfile, flagfile_value); + LoadFlagsFromFile(flagfile_value); remove_flag = true; #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ } else if (arg_string == "--help" || arg_string == "-h" || diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc index c0b3d1f21d..e7e0cd7016 100644 --- a/googletest/test/googletest-death-test-test.cc +++ b/googletest/test/googletest-death-test-test.cc @@ -370,14 +370,14 @@ TEST_F(TestForDeathTest, SwitchStatement) { // Tests that a static member function can be used in a "fast" style // death test. TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember"); } // Tests that a method of the test fixture can be used in a "fast" // style death test. TEST_F(TestForDeathTest, MemberFunctionFastStyle) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); should_die_ = true; EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction"); } @@ -387,7 +387,7 @@ void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); } // Tests that death tests work even if the current directory has been // changed. TEST_F(TestForDeathTest, FastDeathTestInChangedDir) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); ChangeToRootDir(); EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); @@ -432,7 +432,7 @@ void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) { // Tests that death tests work when SIGPROF handler and timer are set. TEST_F(TestForDeathTest, FastSigprofActionSet) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); SetSigprofActionAndTimer(); EXPECT_DEATH(_exit(1), ""); struct sigaction old_signal_action; @@ -441,7 +441,7 @@ TEST_F(TestForDeathTest, FastSigprofActionSet) { } TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; + GTEST_FLAG_SET(death_test_style, "threadsafe"); SetSigprofActionAndTimer(); EXPECT_DEATH(_exit(1), ""); struct sigaction old_signal_action; @@ -453,25 +453,25 @@ TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { // Repeats a representative sample of death tests in the "threadsafe" style: TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; + GTEST_FLAG_SET(death_test_style, "threadsafe"); ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember"); } TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; + GTEST_FLAG_SET(death_test_style, "threadsafe"); should_die_ = true; EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction"); } TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; + GTEST_FLAG_SET(death_test_style, "threadsafe"); for (int i = 0; i < 3; ++i) EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i; } TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; + GTEST_FLAG_SET(death_test_style, "threadsafe"); ChangeToRootDir(); EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); @@ -481,9 +481,9 @@ TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) { } TEST_F(TestForDeathTest, MixedStyles) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; + GTEST_FLAG_SET(death_test_style, "threadsafe"); EXPECT_DEATH(_exit(1), ""); - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_DEATH(_exit(1), ""); } @@ -496,8 +496,8 @@ void SetPthreadFlag() { } TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { - if (!testing::GTEST_FLAG(death_test_use_fork)) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; + if (!GTEST_FLAG_GET(death_test_use_fork)) { + GTEST_FLAG_SET(death_test_style, "threadsafe"); pthread_flag = false; ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, nullptr, nullptr)); ASSERT_DEATH(_exit(1), ""); @@ -740,10 +740,12 @@ TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { "any pop-up dialogs.\n"); fflush(stdout); - EXPECT_DEATH({ - testing::GTEST_FLAG(catch_exceptions) = false; - abort(); - }, ""); + EXPECT_DEATH( + { + GTEST_FLAG_SET(catch_exceptions, false); + abort(); + }, + ""); } # endif // GTEST_OS_WINDOWS @@ -874,19 +876,19 @@ TEST_F(TestForDeathTest, ExitMacros) { } TEST_F(TestForDeathTest, ExitMacrosUsingFork) { - testing::GTEST_FLAG(death_test_use_fork) = true; + GTEST_FLAG_SET(death_test_use_fork, true); TestExitMacros(); } TEST_F(TestForDeathTest, InvalidStyle) { - testing::GTEST_FLAG(death_test_style) = "rococo"; + GTEST_FLAG_SET(death_test_style, "rococo"); EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_DEATH(_exit(0), "") << "This failure is expected."; }, "This failure is expected."); } TEST_F(TestForDeathTest, DeathTestFailedOutput) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_NONFATAL_FAILURE( EXPECT_DEATH(DieWithMessage("death\n"), "expected message"), @@ -895,7 +897,7 @@ TEST_F(TestForDeathTest, DeathTestFailedOutput) { } TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_NONFATAL_FAILURE( EXPECT_DEATH({ fprintf(stderr, "returning\n"); @@ -908,7 +910,7 @@ TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) { } TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_NONFATAL_FAILURE( EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"), testing::ExitedWithCode(3), @@ -920,7 +922,7 @@ TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) { } TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_NONFATAL_FAILURE( EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"), "line 1\nxyz\nline 3\n"), @@ -931,7 +933,7 @@ TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) { } TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"), "line 1\nline 2\nline 3\n"); } @@ -1358,7 +1360,7 @@ TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) { } TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { - testing::GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_FALSE(InDeathTestChild()); EXPECT_DEATH({ fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); @@ -1368,7 +1370,7 @@ TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { } TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { - testing::GTEST_FLAG(death_test_style) = "threadsafe"; + GTEST_FLAG_SET(death_test_style, "threadsafe"); EXPECT_FALSE(InDeathTestChild()); EXPECT_DEATH({ fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc index 7219680d07..bbacc8ae88 100644 --- a/googletest/test/googletest-death-test_ex_test.cc +++ b/googletest/test/googletest-death-test_ex_test.cc @@ -53,7 +53,7 @@ TEST(CxxExceptionDeathTest, ExceptionIsFailure) { } catch (...) { // NOLINT FAIL() << "An exception escaped a death test macro invocation " << "with catch_exceptions " - << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); + << (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled"); } } @@ -79,7 +79,7 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), "") << "with catch_exceptions " - << (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled"); + << (GTEST_FLAG_GET(catch_exceptions) ? "enabled" : "disabled"); } # endif @@ -87,6 +87,6 @@ TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) { int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); - testing::GTEST_FLAG(catch_exceptions) = GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0; + GTEST_FLAG_SET(catch_exceptions, GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0); return RUN_ALL_TESTS(); } diff --git a/googletest/test/googletest-env-var-test_.cc b/googletest/test/googletest-env-var-test_.cc index 52f95864e1..0ff015228f 100644 --- a/googletest/test/googletest-env-var-test_.cc +++ b/googletest/test/googletest-env-var-test_.cc @@ -48,67 +48,67 @@ TEST(GTestEnvVarTest, Dummy) { void PrintFlag(const char* flag) { if (strcmp(flag, "break_on_failure") == 0) { - cout << GTEST_FLAG(break_on_failure); + cout << GTEST_FLAG_GET(break_on_failure); return; } if (strcmp(flag, "catch_exceptions") == 0) { - cout << GTEST_FLAG(catch_exceptions); + cout << GTEST_FLAG_GET(catch_exceptions); return; } if (strcmp(flag, "color") == 0) { - cout << GTEST_FLAG(color); + cout << GTEST_FLAG_GET(color); return; } if (strcmp(flag, "death_test_style") == 0) { - cout << GTEST_FLAG(death_test_style); + cout << GTEST_FLAG_GET(death_test_style); return; } if (strcmp(flag, "death_test_use_fork") == 0) { - cout << GTEST_FLAG(death_test_use_fork); + cout << GTEST_FLAG_GET(death_test_use_fork); return; } if (strcmp(flag, "fail_fast") == 0) { - cout << GTEST_FLAG(fail_fast); + cout << GTEST_FLAG_GET(fail_fast); return; } if (strcmp(flag, "filter") == 0) { - cout << GTEST_FLAG(filter); + cout << GTEST_FLAG_GET(filter); return; } if (strcmp(flag, "output") == 0) { - cout << GTEST_FLAG(output); + cout << GTEST_FLAG_GET(output); return; } if (strcmp(flag, "brief") == 0) { - cout << GTEST_FLAG(brief); + cout << GTEST_FLAG_GET(brief); return; } if (strcmp(flag, "print_time") == 0) { - cout << GTEST_FLAG(print_time); + cout << GTEST_FLAG_GET(print_time); return; } if (strcmp(flag, "repeat") == 0) { - cout << GTEST_FLAG(repeat); + cout << GTEST_FLAG_GET(repeat); return; } if (strcmp(flag, "stack_trace_depth") == 0) { - cout << GTEST_FLAG(stack_trace_depth); + cout << GTEST_FLAG_GET(stack_trace_depth); return; } if (strcmp(flag, "throw_on_failure") == 0) { - cout << GTEST_FLAG(throw_on_failure); + cout << GTEST_FLAG_GET(throw_on_failure); return; } diff --git a/googletest/test/googletest-listener-test.cc b/googletest/test/googletest-listener-test.cc index 10457afe39..9d6c9caba3 100644 --- a/googletest/test/googletest-listener-test.cc +++ b/googletest/test/googletest-listener-test.cc @@ -284,7 +284,7 @@ int main(int argc, char **argv) { GTEST_CHECK_(events.size() == 0) << "AddGlobalTestEnvironment should not generate any events itself."; - ::testing::GTEST_FLAG(repeat) = 2; + GTEST_FLAG_SET(repeat, 2); int ret_val = RUN_ALL_TESTS(); #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index 11fb1f2246..cd386ff23d 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -61,29 +61,29 @@ FilePath GetAbsolutePathOf(const FilePath& relative_path) { // Testing UnitTestOptions::GetOutputFormat/GetOutputFile. TEST(XmlOutputTest, GetOutputFormatDefault) { - GTEST_FLAG(output) = ""; + GTEST_FLAG_SET(output, ""); EXPECT_STREQ("", UnitTestOptions::GetOutputFormat().c_str()); } TEST(XmlOutputTest, GetOutputFormat) { - GTEST_FLAG(output) = "xml:filename"; + GTEST_FLAG_SET(output, "xml:filename"); EXPECT_STREQ("xml", UnitTestOptions::GetOutputFormat().c_str()); } TEST(XmlOutputTest, GetOutputFileDefault) { - GTEST_FLAG(output) = ""; + GTEST_FLAG_SET(output, ""); EXPECT_EQ(GetAbsolutePathOf(FilePath("test_detail.xml")).string(), UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST(XmlOutputTest, GetOutputFileSingleFile) { - GTEST_FLAG(output) = "xml:filename.abc"; + GTEST_FLAG_SET(output, "xml:filename.abc"); EXPECT_EQ(GetAbsolutePathOf(FilePath("filename.abc")).string(), UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) { - GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; + GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_); const std::string expected_output_file = GetAbsolutePathOf( FilePath(std::string("path") + GTEST_PATH_SEP_ + @@ -144,28 +144,28 @@ class XmlOutputChangeDirTest : public Test { }; TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) { - GTEST_FLAG(output) = ""; + GTEST_FLAG_SET(output, ""); EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml")).string(), UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) { - GTEST_FLAG(output) = "xml"; + GTEST_FLAG_SET(output, "xml"); EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, FilePath("test_detail.xml")).string(), UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) { - GTEST_FLAG(output) = "xml:filename.abc"; + GTEST_FLAG_SET(output, "xml:filename.abc"); EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_, FilePath("filename.abc")).string(), UnitTestOptions::GetAbsolutePathToOutputFile()); } TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { - GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_; + GTEST_FLAG_SET(output, "xml:path" GTEST_PATH_SEP_); const std::string expected_output_file = FilePath::ConcatPaths( original_working_dir_, @@ -182,11 +182,11 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) { TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) { #if GTEST_OS_WINDOWS - GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc"; + GTEST_FLAG_SET(output, "xml:c:\\tmp\\filename.abc"); EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(), UnitTestOptions::GetAbsolutePathToOutputFile()); #else - GTEST_FLAG(output) ="xml:/tmp/filename.abc"; + GTEST_FLAG_SET(output, "xml:/tmp/filename.abc"); EXPECT_EQ(FilePath("/tmp/filename.abc").string(), UnitTestOptions::GetAbsolutePathToOutputFile()); #endif @@ -199,7 +199,7 @@ TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) { const std::string path = "/tmp/"; #endif - GTEST_FLAG(output) = "xml:" + path; + GTEST_FLAG_SET(output, "xml:" + path); const std::string expected_output_file = path + GetCurrentExecutableName().string() + ".xml"; const std::string& output_file = diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 074f64ef62..9e5465c975 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -1066,7 +1066,7 @@ class BarEnvironment : public testing::Environment { // of them are intended to fail), and then compare the test results // with the "golden" file. int main(int argc, char **argv) { - testing::GTEST_FLAG(print_time) = false; + GTEST_FLAG_SET(print_time, false); // We just run the tests, knowing some of them are intended to fail. // We will use a separate Python script to compare the output of @@ -1081,7 +1081,7 @@ int main(int argc, char **argv) { std::string("internal_skip_environment_and_ad_hoc_tests")) > 0; #if GTEST_HAS_DEATH_TEST - if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") { + if (GTEST_FLAG_GET(internal_run_death_test) != "") { // Skip the usual output capturing if we're running as the child // process of an threadsafe-style death test. # if GTEST_OS_WINDOWS diff --git a/googletest/test/gtest_environment_test.cc b/googletest/test/gtest_environment_test.cc index 064bfc50b9..c7facf5a39 100644 --- a/googletest/test/gtest_environment_test.cc +++ b/googletest/test/gtest_environment_test.cc @@ -35,10 +35,6 @@ #include "gtest/gtest.h" #include "src/gtest-internal-inl.h" -namespace testing { -GTEST_DECLARE_string_(filter); -} - namespace { enum FailureType { @@ -174,7 +170,7 @@ int main(int argc, char **argv) { // Verifies that RUN_ALL_TESTS() doesn't do global set-up or // tear-down when there is no test to run. - testing::GTEST_FLAG(filter) = "-*"; + GTEST_FLAG_SET(filter, "-*"); Check(RunAllTests(env, NO_FAILURE) == 0, "RUN_ALL_TESTS() should return zero, as there is no test to run."); Check(!env->set_up_was_run(), diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc index 7da4a15ea1..c7af3efb6d 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -35,18 +35,6 @@ #include "gtest/gtest.h" #include "src/gtest-internal-inl.h" -namespace testing { - -GTEST_DECLARE_string_(death_test_style); -GTEST_DECLARE_string_(filter); -GTEST_DECLARE_int32_(repeat); - -} // namespace testing - -using testing::GTEST_FLAG(death_test_style); -using testing::GTEST_FLAG(filter); -using testing::GTEST_FLAG(repeat); - namespace { // We need this when we are testing Google Test itself and therefore @@ -103,10 +91,10 @@ int g_death_test_count = 0; TEST(BarDeathTest, ThreadSafeAndFast) { g_death_test_count++; - GTEST_FLAG(death_test_style) = "threadsafe"; + GTEST_FLAG_SET(death_test_style, "threadsafe"); EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), ""); - GTEST_FLAG(death_test_style) = "fast"; + GTEST_FLAG_SET(death_test_style, "fast"); EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), ""); } @@ -153,7 +141,7 @@ void TestRepeatUnspecified() { // Tests the behavior of Google Test when --gtest_repeat has the given value. void TestRepeat(int repeat) { - GTEST_FLAG(repeat) = repeat; + GTEST_FLAG_SET(repeat, repeat); ResetCounts(); GTEST_CHECK_INT_EQ_(repeat > 0 ? 1 : 0, RUN_ALL_TESTS()); @@ -163,8 +151,8 @@ void TestRepeat(int repeat) { // Tests using --gtest_repeat when --gtest_filter specifies an empty // set of tests. void TestRepeatWithEmptyFilter(int repeat) { - GTEST_FLAG(repeat) = repeat; - GTEST_FLAG(filter) = "None"; + GTEST_FLAG_SET(repeat, repeat); + GTEST_FLAG_SET(filter, "None"); ResetCounts(); GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS()); @@ -174,8 +162,8 @@ void TestRepeatWithEmptyFilter(int repeat) { // Tests using --gtest_repeat when --gtest_filter specifies a set of // successful tests. void TestRepeatWithFilterForSuccessfulTests(int repeat) { - GTEST_FLAG(repeat) = repeat; - GTEST_FLAG(filter) = "*-*ShouldFail"; + GTEST_FLAG_SET(repeat, repeat); + GTEST_FLAG_SET(filter, "*-*ShouldFail"); ResetCounts(); GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS()); @@ -190,8 +178,8 @@ void TestRepeatWithFilterForSuccessfulTests(int repeat) { // Tests using --gtest_repeat when --gtest_filter specifies a set of // failed tests. void TestRepeatWithFilterForFailedTests(int repeat) { - GTEST_FLAG(repeat) = repeat; - GTEST_FLAG(filter) = "*ShouldFail"; + GTEST_FLAG_SET(repeat, repeat); + GTEST_FLAG_SET(filter, "*ShouldFail"); ResetCounts(); GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS()); diff --git a/googletest/test/gtest_throw_on_failure_ex_test.cc b/googletest/test/gtest_throw_on_failure_ex_test.cc index 1d95adbf53..aeead13feb 100644 --- a/googletest/test/gtest_throw_on_failure_ex_test.cc +++ b/googletest/test/gtest_throw_on_failure_ex_test.cc @@ -50,7 +50,7 @@ void Fail(const char* msg) { // Tests that an assertion failure throws a subclass of // std::runtime_error. void TestFailureThrowsRuntimeError() { - testing::GTEST_FLAG(throw_on_failure) = true; + GTEST_FLAG_SET(throw_on_failure, true); // A successful assertion shouldn't throw. try { diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 402bb6d2af..3f2f082fe7 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -37,23 +37,19 @@ // code once "gtest.h" has been #included. // Do not move it after other gtest #includes. TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { - bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) || - testing::GTEST_FLAG(break_on_failure) || - testing::GTEST_FLAG(catch_exceptions) || - testing::GTEST_FLAG(color) != "unknown" || - testing::GTEST_FLAG(fail_fast) || - testing::GTEST_FLAG(filter) != "unknown" || - testing::GTEST_FLAG(list_tests) || - testing::GTEST_FLAG(output) != "unknown" || - testing::GTEST_FLAG(brief) || testing::GTEST_FLAG(print_time) || - testing::GTEST_FLAG(random_seed) || - testing::GTEST_FLAG(repeat) > 0 || - testing::GTEST_FLAG(recreate_environments_when_repeating) || - testing::GTEST_FLAG(show_internal_stack_frames) || - testing::GTEST_FLAG(shuffle) || - testing::GTEST_FLAG(stack_trace_depth) > 0 || - testing::GTEST_FLAG(stream_result_to) != "unknown" || - testing::GTEST_FLAG(throw_on_failure); + bool dummy = + GTEST_FLAG_GET(also_run_disabled_tests) || + GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) || + GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) || + GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) || + GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) || + GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) || + GTEST_FLAG_GET(repeat) > 0 || + GTEST_FLAG_GET(recreate_environments_when_repeating) || + GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) || + GTEST_FLAG_GET(stack_trace_depth) > 0 || + GTEST_FLAG_GET(stream_result_to) != "unknown" || + GTEST_FLAG_GET(throw_on_failure); EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused. } @@ -200,25 +196,6 @@ using testing::DoubleLE; using testing::EmptyTestEventListener; using testing::Environment; using testing::FloatLE; -using testing::GTEST_FLAG(also_run_disabled_tests); -using testing::GTEST_FLAG(break_on_failure); -using testing::GTEST_FLAG(catch_exceptions); -using testing::GTEST_FLAG(color); -using testing::GTEST_FLAG(death_test_use_fork); -using testing::GTEST_FLAG(fail_fast); -using testing::GTEST_FLAG(filter); -using testing::GTEST_FLAG(list_tests); -using testing::GTEST_FLAG(output); -using testing::GTEST_FLAG(brief); -using testing::GTEST_FLAG(print_time); -using testing::GTEST_FLAG(random_seed); -using testing::GTEST_FLAG(repeat); -using testing::GTEST_FLAG(recreate_environments_when_repeating); -using testing::GTEST_FLAG(show_internal_stack_frames); -using testing::GTEST_FLAG(shuffle); -using testing::GTEST_FLAG(stack_trace_depth); -using testing::GTEST_FLAG(stream_result_to); -using testing::GTEST_FLAG(throw_on_failure); using testing::IsNotSubstring; using testing::IsSubstring; using testing::kMaxStackTraceDepth; @@ -267,7 +244,7 @@ using testing::internal::kTestTypeIdInGoogleTest; using testing::internal::NativeArray; using testing::internal::OsStackTraceGetter; using testing::internal::OsStackTraceGetterInterface; -using testing::internal::ParseInt32Flag; +using testing::internal::ParseFlag; using testing::internal::RelationToSourceCopy; using testing::internal::RelationToSourceReference; using testing::internal::ShouldRunTestOnShard; @@ -1599,24 +1576,24 @@ class GTestFlagSaverTest : public Test { static void SetUpTestSuite() { saver_ = new GTestFlagSaver; - GTEST_FLAG(also_run_disabled_tests) = false; - GTEST_FLAG(break_on_failure) = false; - GTEST_FLAG(catch_exceptions) = false; - GTEST_FLAG(death_test_use_fork) = false; - GTEST_FLAG(color) = "auto"; - GTEST_FLAG(fail_fast) = false; - GTEST_FLAG(filter) = ""; - GTEST_FLAG(list_tests) = false; - GTEST_FLAG(output) = ""; - GTEST_FLAG(brief) = false; - GTEST_FLAG(print_time) = true; - GTEST_FLAG(random_seed) = 0; - GTEST_FLAG(repeat) = 1; - GTEST_FLAG(recreate_environments_when_repeating) = true; - GTEST_FLAG(shuffle) = false; - GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; - GTEST_FLAG(stream_result_to) = ""; - GTEST_FLAG(throw_on_failure) = false; + GTEST_FLAG_SET(also_run_disabled_tests, false); + GTEST_FLAG_SET(break_on_failure, false); + GTEST_FLAG_SET(catch_exceptions, false); + GTEST_FLAG_SET(death_test_use_fork, false); + GTEST_FLAG_SET(color, "auto"); + GTEST_FLAG_SET(fail_fast, false); + GTEST_FLAG_SET(filter, ""); + GTEST_FLAG_SET(list_tests, false); + GTEST_FLAG_SET(output, ""); + GTEST_FLAG_SET(brief, false); + GTEST_FLAG_SET(print_time, true); + GTEST_FLAG_SET(random_seed, 0); + GTEST_FLAG_SET(repeat, 1); + GTEST_FLAG_SET(recreate_environments_when_repeating, true); + GTEST_FLAG_SET(shuffle, false); + GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth); + GTEST_FLAG_SET(stream_result_to, ""); + GTEST_FLAG_SET(throw_on_failure, false); } // Restores the Google Test flags that the tests have modified. This will @@ -1629,43 +1606,43 @@ class GTestFlagSaverTest : public Test { // Verifies that the Google Test flags have their default values, and then // modifies each of them. void VerifyAndModifyFlags() { - EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests)); - EXPECT_FALSE(GTEST_FLAG(break_on_failure)); - EXPECT_FALSE(GTEST_FLAG(catch_exceptions)); - EXPECT_STREQ("auto", GTEST_FLAG(color).c_str()); - EXPECT_FALSE(GTEST_FLAG(death_test_use_fork)); - EXPECT_FALSE(GTEST_FLAG(fail_fast)); - EXPECT_STREQ("", GTEST_FLAG(filter).c_str()); - EXPECT_FALSE(GTEST_FLAG(list_tests)); - EXPECT_STREQ("", GTEST_FLAG(output).c_str()); - EXPECT_FALSE(GTEST_FLAG(brief)); - EXPECT_TRUE(GTEST_FLAG(print_time)); - EXPECT_EQ(0, GTEST_FLAG(random_seed)); - EXPECT_EQ(1, GTEST_FLAG(repeat)); - EXPECT_TRUE(GTEST_FLAG(recreate_environments_when_repeating)); - EXPECT_FALSE(GTEST_FLAG(shuffle)); - EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth)); - EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str()); - EXPECT_FALSE(GTEST_FLAG(throw_on_failure)); - - GTEST_FLAG(also_run_disabled_tests) = true; - GTEST_FLAG(break_on_failure) = true; - GTEST_FLAG(catch_exceptions) = true; - GTEST_FLAG(color) = "no"; - GTEST_FLAG(death_test_use_fork) = true; - GTEST_FLAG(fail_fast) = true; - GTEST_FLAG(filter) = "abc"; - GTEST_FLAG(list_tests) = true; - GTEST_FLAG(output) = "xml:foo.xml"; - GTEST_FLAG(brief) = true; - GTEST_FLAG(print_time) = false; - GTEST_FLAG(random_seed) = 1; - GTEST_FLAG(repeat) = 100; - GTEST_FLAG(recreate_environments_when_repeating) = false; - GTEST_FLAG(shuffle) = true; - GTEST_FLAG(stack_trace_depth) = 1; - GTEST_FLAG(stream_result_to) = "localhost:1234"; - GTEST_FLAG(throw_on_failure) = true; + EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests)); + EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure)); + EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions)); + EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str()); + EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork)); + EXPECT_FALSE(GTEST_FLAG_GET(fail_fast)); + EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str()); + EXPECT_FALSE(GTEST_FLAG_GET(list_tests)); + EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str()); + EXPECT_FALSE(GTEST_FLAG_GET(brief)); + EXPECT_TRUE(GTEST_FLAG_GET(print_time)); + EXPECT_EQ(0, GTEST_FLAG_GET(random_seed)); + EXPECT_EQ(1, GTEST_FLAG_GET(repeat)); + EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating)); + EXPECT_FALSE(GTEST_FLAG_GET(shuffle)); + EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth)); + EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str()); + EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure)); + + GTEST_FLAG_SET(also_run_disabled_tests, true); + GTEST_FLAG_SET(break_on_failure, true); + GTEST_FLAG_SET(catch_exceptions, true); + GTEST_FLAG_SET(color, "no"); + GTEST_FLAG_SET(death_test_use_fork, true); + GTEST_FLAG_SET(fail_fast, true); + GTEST_FLAG_SET(filter, "abc"); + GTEST_FLAG_SET(list_tests, true); + GTEST_FLAG_SET(output, "xml:foo.xml"); + GTEST_FLAG_SET(brief, true); + GTEST_FLAG_SET(print_time, false); + GTEST_FLAG_SET(random_seed, 1); + GTEST_FLAG_SET(repeat, 100); + GTEST_FLAG_SET(recreate_environments_when_repeating, false); + GTEST_FLAG_SET(shuffle, true); + GTEST_FLAG_SET(stack_trace_depth, 1); + GTEST_FLAG_SET(stream_result_to, "localhost:1234"); + GTEST_FLAG_SET(throw_on_failure, true); } private: @@ -1781,29 +1758,29 @@ TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) { } #endif // !GTEST_OS_WINDOWS_MOBILE -// Tests ParseInt32Flag(). +// Tests ParseFlag(). // Tests that ParseInt32Flag() returns false and doesn't change the // output value when the flag has wrong format TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { int32_t value = 123; - EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value)); + EXPECT_FALSE(ParseFlag("--a=100", "b", &value)); EXPECT_EQ(123, value); - EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value)); + EXPECT_FALSE(ParseFlag("a=100", "a", &value)); EXPECT_EQ(123, value); } -// Tests that ParseInt32Flag() returns false and doesn't change the +// Tests that ParseFlag() returns false and doesn't change the // output value when the flag overflows as an Int32. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { printf("(expecting 2 warnings)\n"); int32_t value = 123; - EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value)); + EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value)); EXPECT_EQ(123, value); - EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value)); + EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value)); EXPECT_EQ(123, value); } @@ -1814,10 +1791,10 @@ TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { printf("(expecting 2 warnings)\n"); int32_t value = 123; - EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value)); + EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value)); EXPECT_EQ(123, value); - EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value)); + EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value)); EXPECT_EQ(123, value); } @@ -1826,11 +1803,10 @@ TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { // the range of an Int32. TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) { int32_t value = 123; - EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); + EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); EXPECT_EQ(456, value); - EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789", - "abc", &value)); + EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value)); EXPECT_EQ(-789, value); } @@ -5756,23 +5732,23 @@ class ParseFlagsTest : public Test { protected: // Clears the flags before each test. void SetUp() override { - GTEST_FLAG(also_run_disabled_tests) = false; - GTEST_FLAG(break_on_failure) = false; - GTEST_FLAG(catch_exceptions) = false; - GTEST_FLAG(death_test_use_fork) = false; - GTEST_FLAG(fail_fast) = false; - GTEST_FLAG(filter) = ""; - GTEST_FLAG(list_tests) = false; - GTEST_FLAG(output) = ""; - GTEST_FLAG(brief) = false; - GTEST_FLAG(print_time) = true; - GTEST_FLAG(random_seed) = 0; - GTEST_FLAG(repeat) = 1; - GTEST_FLAG(recreate_environments_when_repeating) = true; - GTEST_FLAG(shuffle) = false; - GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; - GTEST_FLAG(stream_result_to) = ""; - GTEST_FLAG(throw_on_failure) = false; + GTEST_FLAG_SET(also_run_disabled_tests, false); + GTEST_FLAG_SET(break_on_failure, false); + GTEST_FLAG_SET(catch_exceptions, false); + GTEST_FLAG_SET(death_test_use_fork, false); + GTEST_FLAG_SET(fail_fast, false); + GTEST_FLAG_SET(filter, ""); + GTEST_FLAG_SET(list_tests, false); + GTEST_FLAG_SET(output, ""); + GTEST_FLAG_SET(brief, false); + GTEST_FLAG_SET(print_time, true); + GTEST_FLAG_SET(random_seed, 0); + GTEST_FLAG_SET(repeat, 1); + GTEST_FLAG_SET(recreate_environments_when_repeating, true); + GTEST_FLAG_SET(shuffle, false); + GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth); + GTEST_FLAG_SET(stream_result_to, ""); + GTEST_FLAG_SET(throw_on_failure, false); } // Asserts that two narrow or wide string arrays are equal. @@ -5789,25 +5765,26 @@ class ParseFlagsTest : public Test { // Verifies that the flag values match the expected values. static void CheckFlags(const Flags& expected) { EXPECT_EQ(expected.also_run_disabled_tests, - GTEST_FLAG(also_run_disabled_tests)); - EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure)); - EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions)); - EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork)); - EXPECT_EQ(expected.fail_fast, GTEST_FLAG(fail_fast)); - EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str()); - EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests)); - EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str()); - EXPECT_EQ(expected.brief, GTEST_FLAG(brief)); - EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time)); - EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed)); - EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat)); + GTEST_FLAG_GET(also_run_disabled_tests)); + EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure)); + EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions)); + EXPECT_EQ(expected.death_test_use_fork, + GTEST_FLAG_GET(death_test_use_fork)); + EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast)); + EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str()); + EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests)); + EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str()); + EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief)); + EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time)); + EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed)); + EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat)); EXPECT_EQ(expected.recreate_environments_when_repeating, - GTEST_FLAG(recreate_environments_when_repeating)); - EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle)); - EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth)); + GTEST_FLAG_GET(recreate_environments_when_repeating)); + EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle)); + EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth)); EXPECT_STREQ(expected.stream_result_to, - GTEST_FLAG(stream_result_to).c_str()); - EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure)); + GTEST_FLAG_GET(stream_result_to).c_str()); + EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure)); } // Parses a command line (specified by argc1 and argv1), then @@ -6639,7 +6616,7 @@ TEST(StreamingAssertionsTest, AnyThrow) { // Tests that Google Test correctly decides whether to use colors in the output. TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { - GTEST_FLAG(color) = "yes"; + GTEST_FLAG_SET(color, "yes"); SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. @@ -6653,18 +6630,18 @@ TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { SetEnv("TERM", "dumb"); // TERM doesn't support colors. - GTEST_FLAG(color) = "True"; + GTEST_FLAG_SET(color, "True"); EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. - GTEST_FLAG(color) = "t"; + GTEST_FLAG_SET(color, "t"); EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. - GTEST_FLAG(color) = "1"; + GTEST_FLAG_SET(color, "1"); EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. } TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { - GTEST_FLAG(color) = "no"; + GTEST_FLAG_SET(color, "no"); SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. @@ -6678,18 +6655,18 @@ TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { SetEnv("TERM", "xterm"); // TERM supports colors. - GTEST_FLAG(color) = "F"; + GTEST_FLAG_SET(color, "F"); EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - GTEST_FLAG(color) = "0"; + GTEST_FLAG_SET(color, "0"); EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. - GTEST_FLAG(color) = "unknown"; + GTEST_FLAG_SET(color, "unknown"); EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. } TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { - GTEST_FLAG(color) = "auto"; + GTEST_FLAG_SET(color, "auto"); SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. @@ -6697,7 +6674,7 @@ TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { } TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { - GTEST_FLAG(color) = "auto"; + GTEST_FLAG_SET(color, "auto"); #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW // On Windows, we ignore the TERM variable as it's usually not set. From 8306020a3e9eceafec65508868d7ab5c63bb41f7 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 7 Jul 2021 10:28:06 -0400 Subject: [PATCH 016/472] Googletest export Add `Conditional` wrapper to gtest This follows an initial proposal for an 'EqIff` matcher. `Conditional` was considered more precise as an EqIff() matcher may suffer from `Iff` not being universally understood. PiperOrigin-RevId: 383407665 --- CONTRIBUTORS | 1 + docs/reference/matchers.md | 1 + googlemock/include/gmock/gmock-matchers.h | 36 +++++++++++++++++++++++ googlemock/test/gmock-matchers_test.cc | 28 ++++++++++++++++++ 4 files changed, 66 insertions(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 76db0b40ff..d9bc587b1b 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -34,6 +34,7 @@ Manuel Klimek Mario Tanev Mark Paskin Markus Heule +Martijn Vels Matthew Simmons Mika Raento Mike Bland diff --git a/docs/reference/matchers.md b/docs/reference/matchers.md index 0d8f81be14..1a60b4c0dc 100644 --- a/docs/reference/matchers.md +++ b/docs/reference/matchers.md @@ -238,6 +238,7 @@ You can make a matcher from one or more other matchers: | `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | | `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | | `Not(m)` | `argument` doesn't match matcher `m`. | +| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evalutes to true, else matches `m2`.| ## Adapters for Matchers diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index e1a7606326..f1bb22caa9 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -1405,6 +1405,30 @@ class AnyOfMatcherImpl : public MatcherInterface { template using AnyOfMatcher = VariadicMatcher; +// ConditionalMatcher is the implementation of Conditional(cond, m1, m2) +template +class ConditionalMatcher { + public: + ConditionalMatcher(bool condition, MatcherTrue matcher_true, + MatcherFalse matcher_false) + : condition_(condition), + matcher_true_(std::move(matcher_true)), + matcher_false_(std::move(matcher_false)) {} + + template + operator Matcher() const { // NOLINT(runtime/explicit) + return condition_ ? SafeMatcherCast(matcher_true_) + : SafeMatcherCast(matcher_false_); + } + + private: + bool condition_; + MatcherTrue matcher_true_; + MatcherFalse matcher_false_; + + GTEST_DISALLOW_ASSIGN_(ConditionalMatcher); +}; + // Wrapper for implementation of Any/AllOfArray(). template