From 14f7077fed7d82046bdcbe347004132f08aba886 Mon Sep 17 00:00:00 2001 From: Enji Cooper Date: Sat, 28 Sep 2024 09:57:32 -0700 Subject: [PATCH] vendor/googletest: import 1.15.2 The changes between the two versions can be found in this diff of the two release tags: https://github.com/google/googletest/compare/v1.14.0...v1.15.2 One notable change is that GoogleTest 1.15.x requires C++-14 (1.14.x required C++-11).. --- BUILD.bazel | 17 + CMakeLists.txt | 13 +- CONTRIBUTING.md | 8 +- CONTRIBUTORS | 1 + MODULE.bazel | 69 ++++ README.md | 22 +- WORKSPACE | 35 ++- WORKSPACE.bzlmod | 35 +++ ci/linux-presubmit.sh | 10 +- ci/macos-presubmit.sh | 3 +- ci/windows-presubmit.bat | 11 +- docs/advanced.md | 36 ++- docs/faq.md | 57 ++-- docs/gmock_cook_book.md | 41 ++- docs/gmock_for_dummies.md | 6 +- docs/primer.md | 39 ++- docs/reference/assertions.md | 2 +- docs/reference/mocking.md | 3 +- docs/reference/testing.md | 29 +- fake_fuchsia_sdk.bzl | 33 ++ googlemock/CMakeLists.txt | 27 +- googlemock/README.md | 6 +- googlemock/include/gmock/gmock-actions.h | 44 ++- .../include/gmock/gmock-function-mocker.h | 9 +- googlemock/include/gmock/gmock-matchers.h | 179 +++++------ googlemock/include/gmock/gmock-more-actions.h | 7 +- googlemock/include/gmock/gmock.h | 15 +- .../gmock/internal/gmock-internal-utils.h | 14 +- .../include/gmock/internal/gmock-port.h | 8 +- googlemock/src/gmock-internal-utils.cc | 5 +- googlemock/src/gmock-matchers.cc | 29 +- googlemock/src/gmock-spec-builders.cc | 3 +- .../test/gmock-matchers-comparisons_test.cc | 9 + .../test/gmock-matchers-containers_test.cc | 17 +- googlemock/test/gmock-more-actions_test.cc | 40 ++- googlemock/test/gmock-spec-builders_test.cc | 2 +- googlemock/test/gmock_link_test.h | 9 + googletest/CMakeLists.txt | 28 +- googletest/README.md | 4 +- googletest/cmake/Config.cmake.in | 4 + googletest/cmake/internal_utils.cmake | 42 +-- .../include/gtest/gtest-assertion-result.h | 2 +- googletest/include/gtest/gtest-death-test.h | 8 +- googletest/include/gtest/gtest-message.h | 19 +- googletest/include/gtest/gtest-param-test.h | 8 +- googletest/include/gtest/gtest-printers.h | 90 ++++-- googletest/include/gtest/gtest-typed-test.h | 126 ++++---- googletest/include/gtest/gtest.h | 55 ++-- .../internal/gtest-death-test-internal.h | 51 ++- .../include/gtest/internal/gtest-filepath.h | 8 +- .../include/gtest/internal/gtest-internal.h | 99 ++---- .../include/gtest/internal/gtest-param-util.h | 152 ++++----- .../include/gtest/internal/gtest-port-arch.h | 2 + .../include/gtest/internal/gtest-port.h | 141 ++++++--- .../include/gtest/internal/gtest-type-util.h | 6 +- googletest/src/gtest-death-test.cc | 36 ++- googletest/src/gtest-filepath.cc | 2 +- googletest/src/gtest-internal-inl.h | 46 ++- googletest/src/gtest-port.cc | 98 ++++-- googletest/src/gtest.cc | 294 +++++++++++------- googletest/test/googletest-color-test.py | 1 + googletest/test/googletest-death-test-test.cc | 78 ++--- .../test/googletest-json-output-unittest.py | 15 + googletest/test/googletest-options-test.cc | 5 +- .../googletest-output-test-golden-lin.txt | 5 - googletest/test/googletest-port-test.cc | 6 +- googletest/test/googletest-printers-test.cc | 16 + googletest/test/gtest_environment_test.cc | 154 ++++----- googletest/test/gtest_help_test.py | 64 ++-- googletest/test/gtest_json_test_utils.py | 3 + googletest/test/gtest_repeat_test.cc | 4 +- googletest/test/gtest_unittest.cc | 46 ++- googletest/test/gtest_xml_output_unittest.py | 15 +- googletest_deps.bzl | 22 +- 74 files changed, 1595 insertions(+), 1053 deletions(-) create mode 100644 MODULE.bazel create mode 100644 WORKSPACE.bzlmod create mode 100644 fake_fuchsia_sdk.bzl diff --git a/BUILD.bazel b/BUILD.bazel index b1e3b7fba89a..e407ae29f44c 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -56,6 +56,12 @@ config_setting( constraint_values = ["@platforms//os:openbsd"], ) +# NOTE: Fuchsia is not an officially supported platform. +config_setting( + name = "fuchsia", + constraint_values = ["@platforms//os:fuchsia"], +) + config_setting( name = "msvc_compiler", flag_values = { @@ -147,6 +153,17 @@ cc_library( "@com_googlesource_code_re2//:re2", ], "//conditions:default": [], + }) + select({ + # `gtest-death-test.cc` has `EXPECT_DEATH` that spawns a process, + # expects it to crash and inspects its logs with the given matcher, + # so that's why these libraries are needed. + # Otherwise, builds targeting Fuchsia would fail to compile. + ":fuchsia": [ + "@fuchsia_sdk//pkg/fdio", + "@fuchsia_sdk//pkg/syslog", + "@fuchsia_sdk//pkg/zx", + ], + "//conditions:default": [], }), ) diff --git a/CMakeLists.txt b/CMakeLists.txt index 089ac987fb60..512e5c3d480f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,7 +4,7 @@ cmake_minimum_required(VERSION 3.13) project(googletest-distribution) -set(GOOGLETEST_VERSION 1.14.0) +set(GOOGLETEST_VERSION 1.15.2) if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) set(CMAKE_CXX_EXTENSIONS OFF) @@ -15,11 +15,20 @@ enable_testing() include(CMakeDependentOption) include(GNUInstallDirs) -#Note that googlemock target already builds googletest +# Note that googlemock target already builds googletest. option(BUILD_GMOCK "Builds the googlemock subproject" ON) option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF) +if(GTEST_HAS_ABSL) + if(NOT TARGET absl::base) + find_package(absl REQUIRED) + endif() + if(NOT TARGET re2::re2) + find_package(re2 REQUIRED) + endif() +endif() + if(BUILD_GMOCK) add_subdirectory( googlemock ) else() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8bed14b2666d..ab5a47bf5530 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,11 +47,11 @@ PR is acceptable as an alternative. ## The Google Test and Google Mock Communities The Google Test community exists primarily through the -[discussion group](http://groups.google.com/group/googletestframework) and the +[discussion group](https://groups.google.com/group/googletestframework) and the GitHub repository. Likewise, the Google Mock community exists primarily through -their own [discussion group](http://groups.google.com/group/googlemock). You are -definitely encouraged to contribute to the discussion and you can also help us -to keep the effectiveness of the group high by following and promoting the +their own [discussion group](https://groups.google.com/group/googlemock). You +are definitely encouraged to contribute to the discussion and you can also help +us to keep the effectiveness of the group high by following and promoting the guidelines listed here. ### Please Be Friendly diff --git a/CONTRIBUTORS b/CONTRIBUTORS index 77397a5b53fe..ccea41ea810b 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -55,6 +55,7 @@ Russ Cox Russ Rufer Sean Mcafee Sigurður Ásgeirsson +Soyeon Kim Sverre Sundsdal Szymon Sobik Takeshi Yoshino diff --git a/MODULE.bazel b/MODULE.bazel new file mode 100644 index 000000000000..61d5e2223512 --- /dev/null +++ b/MODULE.bazel @@ -0,0 +1,69 @@ +# Copyright 2024 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# https://bazel.build/external/overview#bzlmod + +module( + name = "googletest", + version = "1.15.2", + compatibility_level = 1, +) + +# Only direct dependencies need to be listed below. +# Please keep the versions in sync with the versions in the WORKSPACE file. + +bazel_dep(name = "abseil-cpp", + version = "20240116.2", + repo_name = "com_google_absl") + +bazel_dep(name = "platforms", + version = "0.0.10") + +bazel_dep(name = "re2", + repo_name = "com_googlesource_code_re2", + version = "2024-07-02") + +bazel_dep(name = "rules_python", + version = "0.34.0", + dev_dependency = True) + +# https://rules-python.readthedocs.io/en/stable/toolchains.html#library-modules-with-dev-only-python-usage +python = use_extension( + "@rules_python//python/extensions:python.bzl", + "python", + dev_dependency = True +) + +python.toolchain(python_version = "3.12", + is_default = True, + ignore_root_user_error = True) + +fake_fuchsia_sdk = use_repo_rule("//:fake_fuchsia_sdk.bzl", "fake_fuchsia_sdk") +fake_fuchsia_sdk(name = "fuchsia_sdk") diff --git a/README.md b/README.md index 443e02069581..f50c670534d5 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ GoogleTest now follows the We recommend [updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it). We do publish occasional semantic versions, tagged with -`v${major}.${minor}.${patch}` (e.g. `v1.13.0`). +`v${major}.${minor}.${patch}` (e.g. `v1.15.0`). #### Documentation Updates @@ -17,25 +17,21 @@ 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.13.0 +#### Release 1.15.0 -[Release 1.13.0](https://github.com/google/googletest/releases/tag/v1.13.0) is +[Release 1.15.0](https://github.com/google/googletest/releases/tag/v1.15.0) is now available. -The 1.13.x branch requires at least C++14. +The 1.15.x branch requires at least C++14. #### Continuous Integration -We use Google's internal systems for continuous integration. \ -GitHub Actions were added for the convenience of open-source contributors. They -are exclusively maintained by the open-source community and not used by the -GoogleTest team. +We use Google's internal systems for continuous integration. #### Coming Soon * We are planning to take a dependency on [Abseil](https://github.com/abseil/abseil-cpp). -* More documentation improvements are planned. ## Welcome to **GoogleTest**, Google's C++ test framework! @@ -100,12 +96,12 @@ tools. In addition to many internal projects at Google, GoogleTest is also used by the following notable projects: -* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser - and Chrome OS). -* The [LLVM](http://llvm.org/) compiler. +* The [Chromium projects](https://www.chromium.org/) (behind the Chrome + browser and Chrome OS). +* The [LLVM](https://llvm.org/) compiler. * [Protocol Buffers](https://github.com/google/protobuf), Google's data interchange format. -* The [OpenCV](http://opencv.org/) computer vision library. +* The [OpenCV](https://opencv.org/) computer vision library. ## Related Open Source Projects diff --git a/WORKSPACE b/WORKSPACE index f819ffe61b35..218e6c2e8c2b 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -6,22 +6,27 @@ googletest_deps() load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( - name = "rules_python", # 2023-07-31T20:39:27Z - sha256 = "1250b59a33c591a1c4ba68c62e95fc88a84c334ec35a2e23f46cbc1b9a5a8b55", - strip_prefix = "rules_python-e355becc30275939d87116a4ec83dad4bb50d9e1", - urls = ["https://github.com/bazelbuild/rules_python/archive/e355becc30275939d87116a4ec83dad4bb50d9e1.zip"], + name = "rules_python", + sha256 = "d71d2c67e0bce986e1c5a7731b4693226867c45bfe0b7c5e0067228a536fc580", + strip_prefix = "rules_python-0.29.0", + urls = ["https://github.com/bazelbuild/rules_python/releases/download/0.29.0/rules_python-0.29.0.tar.gz"], +) + +# https://github.com/bazelbuild/rules_python/releases/tag/0.29.0 +load("@rules_python//python:repositories.bzl", "py_repositories") +py_repositories() + +http_archive( + name = "bazel_skylib", + sha256 = "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94", + urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz"], ) http_archive( - name = "bazel_skylib", # 2023-05-31T19:24:07Z - sha256 = "08c0386f45821ce246bbbf77503c973246ed6ee5c3463e41efc197fa9bc3a7f4", - strip_prefix = "bazel-skylib-288731ef9f7f688932bd50e704a91a45ec185f9b", - urls = ["https://github.com/bazelbuild/bazel-skylib/archive/288731ef9f7f688932bd50e704a91a45ec185f9b.zip"], -) - -http_archive( - name = "platforms", # 2023-07-28T19:44:27Z - sha256 = "40eb313613ff00a5c03eed20aba58890046f4d38dec7344f00bb9a8867853526", - strip_prefix = "platforms-4ad40ef271da8176d4fc0194d2089b8a76e19d7b", - urls = ["https://github.com/bazelbuild/platforms/archive/4ad40ef271da8176d4fc0194d2089b8a76e19d7b.zip"], + name = "platforms", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.10/platforms-0.0.10.tar.gz", + "https://github.com/bazelbuild/platforms/releases/download/0.0.10/platforms-0.0.10.tar.gz", + ], + sha256 = "218efe8ee736d26a3572663b374a253c012b716d8af0c07e842e82f238a0a7ee", ) diff --git a/WORKSPACE.bzlmod b/WORKSPACE.bzlmod new file mode 100644 index 000000000000..381432c5d0cb --- /dev/null +++ b/WORKSPACE.bzlmod @@ -0,0 +1,35 @@ +# Copyright 2024 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# https://bazel.build/external/migration#workspace.bzlmod +# +# This file is intentionally empty. When bzlmod is enabled and this +# file exists, the content of WORKSPACE is ignored. This prevents +# bzlmod builds from unintentionally depending on the WORKSPACE file. diff --git a/ci/linux-presubmit.sh b/ci/linux-presubmit.sh index 6bac88787ff2..6d2b3fb573a0 100644 --- a/ci/linux-presubmit.sh +++ b/ci/linux-presubmit.sh @@ -31,7 +31,7 @@ set -euox pipefail -readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20230217" +readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20240523" readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20230120" if [[ -z ${GTEST_ROOT:-} ]]; then @@ -67,6 +67,9 @@ for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do done # Do one test with an older version of GCC +# TODO(googletest-team): This currently uses Bazel 5. When upgrading to a +# version of Bazel that supports Bzlmod, add --enable_bzlmod=false to keep test +# coverage for the old WORKSPACE dependency management. time docker run \ --volume="${GTEST_ROOT}:/src:ro" \ --workdir="/src" \ @@ -80,7 +83,6 @@ time docker run \ --copt="-Wuninitialized" \ --copt="-Wundef" \ --copt="-Wno-error=pragmas" \ - --distdir="/bazel-distdir" \ --features=external_include_paths \ --keep_going \ --show_timestamps \ @@ -102,7 +104,7 @@ for std in ${STD}; do --copt="-Wuninitialized" \ --copt="-Wundef" \ --define="absl=${absl}" \ - --distdir="/bazel-distdir" \ + --enable_bzlmod=true \ --features=external_include_paths \ --keep_going \ --show_timestamps \ @@ -127,7 +129,7 @@ for std in ${STD}; do --copt="-Wuninitialized" \ --copt="-Wundef" \ --define="absl=${absl}" \ - --distdir="/bazel-distdir" \ + --enable_bzlmod=true \ --features=external_include_paths \ --keep_going \ --linkopt="--gcc-toolchain=/usr/local" \ diff --git a/ci/macos-presubmit.sh b/ci/macos-presubmit.sh index 681ebc2a91d9..70eaa74fb490 100644 --- a/ci/macos-presubmit.sh +++ b/ci/macos-presubmit.sh @@ -53,7 +53,7 @@ done # Test the Bazel build # If we are running on Kokoro, check for a versioned Bazel binary. -KOKORO_GFILE_BAZEL_BIN="bazel-5.1.1-darwin-x86_64" +KOKORO_GFILE_BAZEL_BIN="bazel-7.0.0-darwin-x86_64" if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}" chmod +x ${BAZEL_BIN} @@ -69,6 +69,7 @@ for absl in 0 1; do --copt="-Wundef" \ --cxxopt="-std=c++14" \ --define="absl=${absl}" \ + --enable_bzlmod=true \ --features=external_include_paths \ --keep_going \ --show_timestamps \ diff --git a/ci/windows-presubmit.bat b/ci/windows-presubmit.bat index 48962eb9e086..1adc1a16ffa8 100644 --- a/ci/windows-presubmit.bat +++ b/ci/windows-presubmit.bat @@ -1,6 +1,6 @@ SETLOCAL ENABLEDELAYEDEXPANSION -SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-5.1.1-windows-x86_64.exe +SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-7.0.0-windows-x86_64.exe SET PATH=C:\Python34;%PATH% SET BAZEL_PYTHON=C:\python34\python.exe @@ -46,12 +46,17 @@ RMDIR /S /Q cmake_msvc2022 :: ---------------------------------------------------------------------------- :: Bazel +:: The default home directory on Kokoro is a long path which causes errors +:: because of Windows limitations on path length. +:: --output_user_root=C:\tmp causes Bazel to use a shorter path. SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community -%BAZEL_EXE% test ... ^ +%BAZEL_EXE% ^ + --output_user_root=C:\tmp ^ + test ... ^ --compilation_mode=dbg ^ --copt=/std:c++14 ^ --copt=/WX ^ - --features=external_include_paths ^ + --enable_bzlmod=true ^ --keep_going ^ --test_output=errors ^ --test_tag_filters=-no_test_msvc2017 diff --git a/docs/advanced.md b/docs/advanced.md index 3871db13b797..240588a83b4e 100644 --- a/docs/advanced.md +++ b/docs/advanced.md @@ -508,9 +508,9 @@ TEST_F(FooDeathTest, DoesThat) { When built with Bazel and using Abseil, GoogleTest uses the [RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX systems (Linux, Cygwin, Mac), GoogleTest uses the -[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) +[POSIX extended regular expression](https://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) syntax. To learn about POSIX syntax, you may want to read this -[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended). +[Wikipedia entry](https://en.wikipedia.org/wiki/Regular_expression#POSIX_extended). On Windows, GoogleTest uses its own simple regular expression implementation. It lacks many features. For example, we don't support union (`"x|y"`), grouping @@ -899,10 +899,10 @@ also supports per-test-suite set-up/tear-down. To use it: variables to hold the shared resources. 2. Outside your test fixture class (typically just below it), define those member variables, optionally giving them initial values. -3. In the same test fixture class, define a `static void SetUpTestSuite()` - function (remember not to spell it as **`SetupTestSuite`** with a small - `u`!) to set up the shared resources and a `static void TearDownTestSuite()` - function to tear them down. +3. In the same test fixture class, define a public member function `static void + SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a + small `u`!) to set up the shared resources and a `static void + TearDownTestSuite()` function to tear them down. That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the *first test* in the `FooTest` test suite (i.e. before creating the first @@ -1004,11 +1004,21 @@ calling the `::testing::AddGlobalTestEnvironment()` function: Environment* AddGlobalTestEnvironment(Environment* env); ``` -Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of -each environment object, then runs the tests if none of the environments -reported fatal failures and `GTEST_SKIP()` was not called. `RUN_ALL_TESTS()` -always calls `TearDown()` with each environment object, regardless of whether or -not the tests were run. +Now, when `RUN_ALL_TESTS()` is invoked, it first calls the `SetUp()` method. The +tests are then executed, provided that none of the environments have reported +fatal failures and `GTEST_SKIP()` has not been invoked. Finally, `TearDown()` is +called. + +Note that `SetUp()` and `TearDown()` are only invoked if there is at least one +test to be performed. Importantly, `TearDown()` is executed even if the test is +not run due to a fatal failure or `GTEST_SKIP()`. + +Calling `SetUp()` and `TearDown()` for each iteration depends on the flag +`gtest_recreate_environments_when_repeating`. `SetUp()` and `TearDown()` are +called for each environment object when the object is recreated for each +iteration. However, if test environments are not recreated for each iteration, +`SetUp()` is called only on the first iteration, and `TearDown()` is called only +on the last iteration. It's OK to register multiple environment objects. In this suite, their `SetUp()` will be called in the order they are registered, and their `TearDown()` will be @@ -1804,7 +1814,7 @@ and/or command line flags. For the flags to work, your programs must call `::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. To see a list of supported flags and their usage, please run your test program -with the `--help` flag. You can also use `-h`, `-?`, or `/?` for short. +with the `--help` flag. If an option is specified both by an environment variable and by a flag, the latter takes precedence. @@ -2171,7 +2181,7 @@ The report format conforms to the following JSON Schema: ```json { - "$schema": "http://json-schema.org/schema#", + "$schema": "https://json-schema.org/schema#", "type": "object", "definitions": { "TestCase": { diff --git a/docs/faq.md b/docs/faq.md index 1928097292a2..c7d10b5006ba 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -3,7 +3,7 @@ ## Why should test suite names and test names not contain underscore? {: .callout .note} -Note: GoogleTest reserves underscore (`_`) for special purpose keywords, such as +Note: GoogleTest reserves underscore (`_`) for special-purpose keywords, such as [the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition to the following rationale. @@ -33,9 +33,9 @@ contains `_`? `TestSuiteName_Bar__Test`, which is invalid. So clearly `TestSuiteName` and `TestName` cannot start or end with `_` -(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't -followed by an upper-case letter. But that's getting complicated. So for -simplicity we just say that it cannot start with `_`.). +(Actually, `TestSuiteName` can start with `_`—as long as the `_` isn't followed +by an upper-case letter. But that's getting complicated. So for simplicity we +just say that it cannot start with `_`.). It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the middle. However, consider this: @@ -128,30 +128,9 @@ both approaches a try. Practice is a much better way to grasp the subtle differences between the two tools. Once you have some concrete experience, you can much more easily decide which one to use the next time. -## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help! - -{: .callout .note} -**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated* -now. Please use `EqualsProto`, etc instead. - -`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and -are now less tolerant of invalid protocol buffer definitions. In particular, if -you have a `foo.proto` that doesn't fully qualify the type of a protocol message -it references (e.g. `message` where it should be `message`), you -will now get run-time errors like: - -``` -... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto": -... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined. -``` - -If you see this, your `.proto` file is broken and needs to be fixed by making -the types fully qualified. The new definition of `ProtocolMessageEquals` and -`ProtocolMessageEquiv` just happen to reveal your bug. - ## My death test modifies some state, but the change seems lost after the death test finishes. Why? -Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the +Death tests (`EXPECT_DEATH`, etc.) are executed in a sub-process s.t. the expected crash won't kill the test program (i.e. the parent process). As a result, any in-memory side effects they incur are observable in their respective sub-processes, but not in the parent process. You can think of them as running @@ -192,16 +171,16 @@ class Foo { }; ``` -You also need to define it *outside* of the class body in `foo.cc`: +you also need to define it *outside* of the class body in `foo.cc`: ```c++ const int Foo::kBar; // No initializer here. ``` Otherwise your code is **invalid C++**, and may break in unexpected ways. In -particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will -generate an "undefined reference" linker error. The fact that "it used to work" -doesn't mean it's valid. It just means that you were lucky. :-) +particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc.) +will generate an "undefined reference" linker error. The fact that "it used to +work" doesn't mean it's valid. It just means that you were lucky. :-) If the declaration of the static data member is `constexpr` then it is implicitly an `inline` definition, and a separate definition in `foo.cc` is not @@ -311,7 +290,7 @@ a **fresh** test fixture object, immediately call `SetUp()`, run the test body, call `TearDown()`, and then delete the test fixture object. When you need to write per-test set-up and tear-down logic, you have the choice -between using the test fixture constructor/destructor or `SetUp()/TearDown()`. +between using the test fixture constructor/destructor or `SetUp()`/`TearDown()`. The former is usually preferred, as it has the following benefits: * By initializing a member variable in the constructor, we have the option to @@ -352,7 +331,7 @@ You may still want to use `SetUp()/TearDown()` in the following cases: GoogleTest assertions in a destructor if your code could run on such a platform. -## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? +## The compiler complains "no matching function to call" when I use `ASSERT_PRED*`. How do I fix it? See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions Reference. @@ -410,7 +389,7 @@ C++ is case-sensitive. Did you spell it as `Setup()`? Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and wonder why it's never called. -## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. +## I have several test suites which share the same test fixture logic; do I have to define a new test fixture class for each of them? This seems pretty tedious. You don't have to. Instead of @@ -545,7 +524,7 @@ The new NPTL thread library doesn't suffer from this problem, as it doesn't create a manager thread. However, if you don't control which machine your test runs on, you shouldn't depend on this. -## Why does GoogleTest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? +## Why does GoogleTest require the entire test suite, instead of individual tests, to be named `*DeathTest` when it uses `ASSERT_DEATH`? GoogleTest does not interleave tests from different test suites. That is, it runs all tests in one test suite first, and then runs all tests in the next test @@ -570,7 +549,7 @@ interleave tests from different test suites, we need to run all tests in the `FooTest` case before running any test in the `BarTest` case. This contradicts with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. -## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do? +## But I don't like calling my entire test suite `*DeathTest` when it contains both death tests and non-death tests. What do I do? You don't have to, but if you like, you may split up the test suite into `FooTest` and `FooDeathTest`, where the names make it clear that they are @@ -607,7 +586,7 @@ defined such that we can print a value of `FooType`. In addition, if `FooType` is declared in a name space, the `<<` operator also needs to be defined in the *same* name space. See -[Tip of the Week #49](http://abseil.io/tips/49) for details. +[Tip of the Week #49](https://abseil.io/tips/49) for details. ## How do I suppress the memory leak messages on Windows? @@ -628,10 +607,10 @@ mistake in production. Such cleverness also leads to advise against the practice, and GoogleTest doesn't provide a way to do it. In general, the recommended way to cause the code to behave differently under -test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject +test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject different functionality from the test and from the production code. Since your production code doesn't link in the for-test logic at all (the -[`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure +[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure that), there is no danger in accidentally running it. However, if you *really*, *really*, *really* have no choice, and if you follow @@ -654,7 +633,7 @@ the `--gtest_also_run_disabled_tests` flag. Yes. The rule is **all test methods in the same test suite must use the same fixture -class.** This means that the following is **allowed** because both tests use the +class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`). ```c++ diff --git a/docs/gmock_cook_book.md b/docs/gmock_cook_book.md index da10918c9659..f1b10b472d27 100644 --- a/docs/gmock_cook_book.md +++ b/docs/gmock_cook_book.md @@ -1927,6 +1927,12 @@ class MockFoo : public Foo { action_n)); ``` +The return value of the last action **must** match the return type of the mocked +method. In the example above, `action_n` could be `Return(true)`, or a lambda +that returns a `bool`, but not `SaveArg`, which returns `void`. Otherwise the +signature of `DoAll` would not match the signature expected by `WillOnce`, which +is the signature of the mocked method, and it wouldn't compile. + ### Verifying Complex Arguments {#SaveArgVerify} If you want to verify that a method is called with a particular argument but the @@ -3306,7 +3312,7 @@ For convenience, we allow the description string to be empty (`""`), in which case gMock will use the sequence of words in the matcher name as the description. -For example: +#### Basic Example ```cpp MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } @@ -3344,6 +3350,8 @@ If the above assertions fail, they will print something like: where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are automatically calculated from the matcher name `IsDivisibleBy7`. +#### Adding Custom Failure Messages + As you may have noticed, the auto-generated descriptions (especially those for the negation) may not be so great. You can always override them with a `string` expression of your own: @@ -3377,14 +3385,41 @@ With this definition, the above assertion will give a better message: Actual: 27 (the remainder is 6) ``` +#### Using EXPECT_ Statements in Matchers + +You can also use `EXPECT_...` (and `ASSERT_...`) statements inside custom +matcher definitions. In many cases, this allows you to write your matcher more +concisely while still providing an informative error message. For example: + +```cpp +MATCHER(IsDivisibleBy7, "") { + const auto remainder = arg % 7; + EXPECT_EQ(remainder, 0); + return true; +} +``` + +If you write a test that includes the line `EXPECT_THAT(27, IsDivisibleBy7());`, +you will get an error something like the following: + +```shell +Expected equality of these values: + remainder + Which is: 6 + 0 +``` + +#### `MatchAndExplain` + You should let `MatchAndExplain()` print *any additional information* that can help a user understand the match result. Note that it should explain why the match succeeds in case of a success (unless it's obvious) - this is useful when the matcher is used inside `Not()`. There is no need to print the argument value itself, as gMock already prints it for you. -{: .callout .note} -NOTE: The type of the value being matched (`arg_type`) is determined by the +#### Argument Types + +The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match diff --git a/docs/gmock_for_dummies.md b/docs/gmock_for_dummies.md index 43f907aaa5da..ed2297c2f796 100644 --- a/docs/gmock_for_dummies.md +++ b/docs/gmock_for_dummies.md @@ -90,14 +90,14 @@ gMock is bundled with googletest. ## A Case for Mock Turtles Let's look at an example. Suppose you are developing a graphics program that -relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like +relies on a [LOGO](https://en.wikipedia.org/wiki/Logo_programming_language)-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about -[Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing +[Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) and know the right thing to do: instead of having your application talk to the system API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: @@ -261,6 +261,8 @@ happen. Therefore it's a good idea to turn on the heap checker in your tests when you allocate mocks on the heap. You get that automatically if you use the `gtest_main` library already. +###### Expectation Ordering + **Important note:** gMock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. Do not alternate between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set diff --git a/docs/primer.md b/docs/primer.md index f2a97a7269b7..61806be6ef86 100644 --- a/docs/primer.md +++ b/docs/primer.md @@ -50,7 +50,7 @@ terms *Test*, *Test Case* and *Test Suite*, so beware of misunderstanding these. Historically, GoogleTest started to use the term *Test Case* for grouping related tests, whereas current publications, including International Software -Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and +Testing Qualifications Board ([ISTQB](https://www.istqb.org/)) materials and various textbooks on software quality, use the term *[Test Suite][istqb test suite]* for this. @@ -68,13 +68,13 @@ deprecated and refactored away. So please be aware of the different definitions of the terms: -Meaning | GoogleTest Term | [ISTQB](http://www.istqb.org/) Term +Meaning | GoogleTest Term | [ISTQB](https://www.istqb.org/) Term :----------------------------------------------------------------------------------- | :---------------------- | :---------------------------------- Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case] -[istqb test case]: http://glossary.istqb.org/en/search/test%20case -[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite +[istqb test case]: https://glossary.istqb.org/en_US/term/test-case-2 +[istqb test suite]: https://glossary.istqb.org/en_US/term/test-suite-1-3 ## Basic Concepts @@ -210,7 +210,7 @@ objects for several different tests. To create a fixture: -1. Derive a class from `::testing::Test` . Start its body with `protected:`, as +1. Derive a class from `testing::Test` . Start its body with `protected:`, as we'll want to access fixture members from sub-classes. 2. Inside the class, declare any objects you plan to use. 3. If necessary, write a default constructor or `SetUp()` function to prepare @@ -271,16 +271,16 @@ First, define a fixture class. By convention, you should give it the name `FooTest` where `Foo` is the class being tested. ```c++ -class QueueTest : public ::testing::Test { +class QueueTest : public testing::Test { protected: - void SetUp() override { + QueueTest() { // q0_ remains empty q1_.Enqueue(1); q2_.Enqueue(2); q2_.Enqueue(3); } - // void TearDown() override {} + // ~QueueTest() override = default; Queue q0_; Queue q1_; @@ -288,8 +288,9 @@ class QueueTest : public ::testing::Test { }; ``` -In this case, `TearDown()` is not needed since we don't have to clean up after -each test, other than what's already done by the destructor. +In this case, we don't need to define a destructor or a `TearDown()` method, +because the implicit destructor generated by the compiler will perform all of +the necessary cleanup. Now we'll write tests using `TEST_F()` and this fixture. @@ -326,11 +327,9 @@ would lead to a segfault when `n` is `NULL`. When these tests run, the following happens: 1. GoogleTest constructs a `QueueTest` object (let's call it `t1`). -2. `t1.SetUp()` initializes `t1`. -3. The first test (`IsEmptyInitially`) runs on `t1`. -4. `t1.TearDown()` cleans up after the test finishes. -5. `t1` is destructed. -6. The above steps are repeated on another `QueueTest` object, this time +2. The first test (`IsEmptyInitially`) runs on `t1`. +3. `t1` is destructed. +4. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test. **Availability**: Linux, Windows, Mac. @@ -402,7 +401,7 @@ namespace project { namespace { // The fixture for testing class Foo. -class FooTest : public ::testing::Test { +class FooTest : public testing::Test { protected: // You can remove any or all of the following functions if their bodies would // be empty. @@ -450,14 +449,14 @@ TEST_F(FooTest, DoesXyz) { } // namespace my int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); + testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } ``` -The `::testing::InitGoogleTest()` function parses the command line for -GoogleTest flags, and removes all recognized flags. This allows the user to -control a test program's behavior via various flags, which we'll cover in the +The `testing::InitGoogleTest()` function parses the command line for GoogleTest +flags, and removes all recognized flags. This allows the user to control a test +program's behavior via various flags, which we'll cover in the [AdvancedGuide](advanced.md). You **must** call this function before calling `RUN_ALL_TESTS()`, or the flags won't be properly initialized. diff --git a/docs/reference/assertions.md b/docs/reference/assertions.md index aa1dbc04bd19..492ff5ef6937 100644 --- a/docs/reference/assertions.md +++ b/docs/reference/assertions.md @@ -1,7 +1,7 @@ # Assertions Reference This page lists the assertion macros provided by GoogleTest for verifying code -behavior. To use them, include the header `gtest/gtest.h`. +behavior. To use them, add `#include `. The majority of the macros listed below come as a pair with an `EXPECT_` variant and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal diff --git a/docs/reference/mocking.md b/docs/reference/mocking.md index e414ffbd0dea..ab37ebf36231 100644 --- a/docs/reference/mocking.md +++ b/docs/reference/mocking.md @@ -1,8 +1,7 @@ # Mocking Reference This page lists the facilities provided by GoogleTest for creating and working -with mock objects. To use them, include the header -`gmock/gmock.h`. +with mock objects. To use them, add `#include `. ## Macros {#macros} diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 17225a682f51..3ed521111787 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -3,7 +3,7 @@ This page lists the facilities provided by GoogleTest for writing test programs. -To use them, include the header `gtest/gtest.h`. +To use them, add `#include `. ## Macros @@ -94,7 +94,8 @@ Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with The argument *`InstantiationName`* is a unique name for the instantiation of the test suite, to distinguish between multiple instantiations. In test output, the instantiation name is added as a prefix to the test suite name -*`TestSuiteName`*. +*`TestSuiteName`*. If *`InstantiationName`* is empty +(`INSTANTIATE_TEST_SUITE_P(, ...)`), no prefix is added. The argument *`param_generator`* is one of the following GoogleTest-provided functions that generate the test parameters, all defined in the `::testing` @@ -139,6 +140,7 @@ See also ### TYPED_TEST_SUITE {#TYPED_TEST_SUITE} `TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)` +`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`,`*`NameGenerator`*`)` Defines a typed test suite based on the test fixture *`TestFixtureName`*. The test suite name is *`TestFixtureName`*. @@ -168,6 +170,22 @@ TYPED_TEST_SUITE(MyFixture, MyTypes); The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` macro to parse correctly. +The optional third argument *`NameGenerator`* allows specifying a class that +exposes a templated static function `GetName(int)`. For example: + +```cpp +class NameGenerator { + public: + template + static std::string GetName(int) { + if constexpr (std::is_same_v) return "char"; + if constexpr (std::is_same_v) return "int"; + if constexpr (std::is_same_v) return "unsignedInt"; + } +}; +TYPED_TEST_SUITE(MyFixture, MyTypes, NameGenerator); +``` + See also [`TYPED_TEST`](#TYPED_TEST) and [Typed Tests](../advanced.md#typed-tests) for more information. @@ -277,7 +295,8 @@ must be registered with The argument *`InstantiationName`* is a unique name for the instantiation of the test suite, to distinguish between multiple instantiations. In test output, the instantiation name is added as a prefix to the test suite name -*`TestSuiteName`*. +*`TestSuiteName`*. If *`InstantiationName`* is empty +(`INSTANTIATE_TYPED_TEST_SUITE_P(, ...)`), no prefix is added. The argument *`Types`* is a [`Types`](#Types) object representing the list of types to run the tests on, for example: @@ -1317,7 +1336,9 @@ tests. Initializes GoogleTest. This must be called before calling [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it -is removed from `argv`, and `*argc` is decremented. +is removed from `argv`, and `*argc` is decremented. Keep in mind that `argv` +must terminate with a `NULL` pointer (i.e. `argv[argc]` is `NULL`), which is +already the case with the default `argv` passed to `main`. No value is returned. Instead, the GoogleTest flag variables are updated. diff --git a/fake_fuchsia_sdk.bzl b/fake_fuchsia_sdk.bzl new file mode 100644 index 000000000000..2024dc6c4d03 --- /dev/null +++ b/fake_fuchsia_sdk.bzl @@ -0,0 +1,33 @@ +"""Provides a fake @fuchsia_sdk implementation that's used when the real one isn't available. + +This is needed since bazel queries on targets that depend on //:gtest (eg: +`bazel query "deps(set(//googletest/test:gtest_all_test))"`) will fail if @fuchsia_sdk is not +defined when bazel is evaluating the transitive closure of the query target. + +See https://github.com/google/googletest/issues/4472. +""" + +def _fake_fuchsia_sdk_impl(repo_ctx): + for stub_target in repo_ctx.attr._stub_build_targets: + stub_package = stub_target + stub_target_name = stub_target.split("/")[-1] + repo_ctx.file("%s/BUILD.bazel" % stub_package, """ +filegroup( + name = "%s", +) +""" % stub_target_name) + +fake_fuchsia_sdk = repository_rule( + doc = "Used to create a fake @fuchsia_sdk repository with stub build targets.", + implementation = _fake_fuchsia_sdk_impl, + attrs = { + "_stub_build_targets": attr.string_list( + doc = "The stub build targets to initialize.", + default = [ + "pkg/fdio", + "pkg/syslog", + "pkg/zx", + ], + ), + }, +) diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt index a9aa0723fbf1..99b2411f36d1 100644 --- a/googlemock/CMakeLists.txt +++ b/googlemock/CMakeLists.txt @@ -5,7 +5,7 @@ # CMake build script for Google Mock. # # To run the tests for Google Mock itself on Linux, use 'make test' or -# ctest. You can select which tests to run using 'ctest -R regex'. +# ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. option(gmock_build_tests "Build all of Google Mock's own tests." OFF) @@ -44,7 +44,7 @@ if (COMMAND set_up_hermetic_build) endif() # Instructs CMake to process Google Test's CMakeLists.txt and add its -# targets to the current scope. We are placing Google Test's binary +# targets to the current scope. We are placing Google Test's binary # directory in a subdirectory of our own as VC compilation may break # if they are the same (the default). add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}") @@ -60,25 +60,26 @@ else() endif() # Although Google Test's CMakeLists.txt calls this function, the -# changes there don't affect the current scope. Therefore we have to +# changes there don't affect the current scope. Therefore we have to # call it again here. -config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake +config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake # Adds Google Mock's and Google Test's header directories to the search path. +# Get Google Test's include dirs from the target, gtest_SOURCE_DIR is broken +# when using fetch-content with the name "GTest". +get_target_property(gtest_include_dirs gtest INCLUDE_DIRECTORIES) set(gmock_build_include_dirs "${gmock_SOURCE_DIR}/include" "${gmock_SOURCE_DIR}" - "${gtest_SOURCE_DIR}/include" - # This directory is needed to build directly from Google Test sources. - "${gtest_SOURCE_DIR}") + "${gtest_include_dirs}") include_directories(${gmock_build_include_dirs}) ######################################################################## # -# Defines the gmock & gmock_main libraries. User tests should link +# Defines the gmock & gmock_main libraries. User tests should link # with one of them. -# Google Mock libraries. We build them using more strict warnings than what +# Google Mock libraries. We build them using more strict warnings than what # are used for other targets, to ensure that Google Mock can be compiled by # a user aggressive about warnings. if (MSVC) @@ -111,7 +112,7 @@ target_include_directories(gmock_main SYSTEM INTERFACE ######################################################################## # -# Install rules +# Install rules. install_project(gmock gmock_main) ######################################################################## @@ -121,8 +122,8 @@ install_project(gmock gmock_main) # You can skip this section if you aren't interested in testing # Google Mock itself. # -# The tests are not built by default. To build them, set the -# gmock_build_tests option to ON. You can do it by running ccmake +# The tests are not built by default. To build them, set the +# gmock_build_tests option to ON. You can do it by running ccmake # or specifying the -Dgmock_build_tests=ON flag when running cmake. if (gmock_build_tests) @@ -187,7 +188,7 @@ if (gmock_build_tests) cxx_shared_library(shared_gmock_main "${cxx_default}" "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) - # Tests that a binary can be built with Google Mock as a shared library. On + # Tests that a binary can be built with Google Mock as a shared library. On # some system configurations, it may not possible to run the binary without # knowing more details about the system configurations. We do not try to run # this binary. To get a more robust shared library coverage, configure with diff --git a/googlemock/README.md b/googlemock/README.md index 7da60655dba8..e1103b16bbfc 100644 --- a/googlemock/README.md +++ b/googlemock/README.md @@ -8,8 +8,8 @@ derive better designs of your system and write better tests. It is inspired by: * [jMock](http://www.jmock.org/) -* [EasyMock](http://www.easymock.org/) -* [Hamcrest](http://code.google.com/p/hamcrest/) +* [EasyMock](https://easymock.org/) +* [Hamcrest](https://code.google.com/p/hamcrest/) It is designed with C++'s specifics in mind. @@ -36,5 +36,5 @@ Details and examples can be found here: * [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html) GoogleMock is a part of -[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a +[GoogleTest C++ testing framework](https://github.com/google/googletest/) and a subject to the same requirements. diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index bd9ba73ee634..cd12996955b6 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -135,6 +135,7 @@ #endif #include +#include #include #include #include @@ -175,9 +176,15 @@ struct BuiltInDefaultValueGetter { static T Get() { Assert(false, __FILE__, __LINE__, "Default action undefined for the function return type."); - return internal::Invalid(); +#if defined(__GNUC__) || defined(__clang__) + __builtin_unreachable(); +#elif defined(_MSC_VER) + __assume(0); +#else + return Invalid(); // The above statement will never be reached, but is required in // order for this function to compile. +#endif } }; @@ -1740,6 +1747,13 @@ struct ThrowAction { return [copy](Args...) -> R { throw copy; }; } }; +struct RethrowAction { + std::exception_ptr exception; + template + operator Action() const { // NOLINT + return [ex = exception](Args...) -> R { std::rethrow_exception(ex); }; + } +}; #endif // GTEST_HAS_EXCEPTIONS } // namespace internal @@ -2056,13 +2070,23 @@ internal::ReturnPointeeAction ReturnPointee(Ptr pointer) { return {pointer}; } -// Action Throw(exception) can be used in a mock function of any type -// to throw the given exception. Any copyable value can be thrown. #if GTEST_HAS_EXCEPTIONS +// Action Throw(exception) can be used in a mock function of any type +// to throw the given exception. Any copyable value can be thrown, +// except for std::exception_ptr, which is likely a mistake if +// thrown directly. template -internal::ThrowAction::type> Throw(T&& exception) { +typename std::enable_if< + !std::is_base_of::type>::value, + internal::ThrowAction::type>>::type +Throw(T&& exception) { return {std::forward(exception)}; } +// Action Rethrow(exception_ptr) can be used in a mock function of any type +// to rethrow any exception_ptr. Note that the same object is thrown each time. +inline internal::RethrowAction Rethrow(std::exception_ptr exception) { + return {std::move(exception)}; +} #endif // GTEST_HAS_EXCEPTIONS namespace internal { @@ -2111,13 +2135,13 @@ struct ActionImpl : ImplBase::type { R operator()(Args&&... arg) const { static constexpr size_t kMaxArgs = sizeof...(Args) <= 10 ? sizeof...(Args) : 10; - return Apply(MakeIndexSequence{}, - MakeIndexSequence<10 - kMaxArgs>{}, + return Apply(std::make_index_sequence{}, + std::make_index_sequence<10 - kMaxArgs>{}, args_type{std::forward(arg)...}); } template - R Apply(IndexSequence, IndexSequence, + R Apply(std::index_sequence, std::index_sequence, const args_type& args) const { // Impl need not be specific to the signature of action being implemented; // only the implementing function body needs to have all of the specific @@ -2150,9 +2174,9 @@ template } #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ - , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ -#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ - const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \ + , GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const arg##i##_type& arg##i +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const args_type& args GMOCK_PP_REPEAT( \ GMOCK_INTERNAL_ARG_UNUSED, , 10) #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h index 1a1f126e492f..d2cb13cd8347 100644 --- a/googlemock/include/gmock/gmock-function-mocker.h +++ b/googlemock/include/gmock/gmock-function-mocker.h @@ -37,6 +37,7 @@ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ +#include #include // IWYU pragma: keep #include // IWYU pragma: keep @@ -69,22 +70,22 @@ constexpr bool PrefixOf(const char* a, const char* b) { return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); } -template +template constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { return N <= M && internal::PrefixOf(prefix, str); } -template +template constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { return N <= M && internal::PrefixOf(suffix, str + M - N); } -template +template constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { return N == M && internal::PrefixOf(a, b); } -template +template constexpr bool ValidateSpec(const char (&spec)[N]) { return internal::Equals("const", spec) || internal::Equals("override", spec) || diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 0f67713776a6..063ee6ca25e7 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -490,12 +490,12 @@ class MatcherBaseImpl> { template operator ::testing::Matcher() const { // NOLINT(runtime/explicit) - return Apply(MakeIndexSequence{}); + return Apply(std::make_index_sequence{}); } private: template - ::testing::Matcher Apply(IndexSequence) const { + ::testing::Matcher Apply(std::index_sequence) const { return ::testing::Matcher( new typename Derived::template gmock_Impl( std::get(params_)...)); @@ -1048,7 +1048,7 @@ class StartsWithMatcher { template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { - const StringType& s2(s); + const StringType s2(s); return s2.length() >= prefix_.length() && s2.substr(0, prefix_.length()) == prefix_; } @@ -1102,7 +1102,7 @@ class EndsWithMatcher { template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { - const StringType& s2(s); + const StringType s2(s); return s2.length() >= suffix_.length() && s2.substr(s2.length() - suffix_.length()) == suffix_; } @@ -2920,26 +2920,27 @@ class EachMatcher { const M inner_matcher_; }; -struct Rank1 {}; -struct Rank0 : Rank1 {}; +// Use go/ranked-overloads for dispatching. +struct Rank0 {}; +struct Rank1 : Rank0 {}; namespace pair_getters { using std::get; template -auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT +auto First(T& x, Rank0) -> decltype(get<0>(x)) { // NOLINT return get<0>(x); } template -auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT +auto First(T& x, Rank1) -> decltype((x.first)) { // NOLINT return x.first; } template -auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT +auto Second(T& x, Rank0) -> decltype(get<1>(x)) { // NOLINT return get<1>(x); } template -auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT +auto Second(T& x, Rank1) -> decltype((x.second)) { // NOLINT return x.second; } } // namespace pair_getters @@ -2965,7 +2966,7 @@ class KeyMatcherImpl : public MatcherInterface { MatchResultListener* listener) const override { StringMatchResultListener inner_listener; const bool match = inner_matcher_.MatchAndExplain( - pair_getters::First(key_value, Rank0()), &inner_listener); + pair_getters::First(key_value, Rank1()), &inner_listener); const std::string explanation = inner_listener.str(); if (!explanation.empty()) { *listener << "whose first field is a value " << explanation; @@ -3087,18 +3088,18 @@ class PairMatcherImpl : public MatcherInterface { if (!listener->IsInterested()) { // If the listener is not interested, we don't need to construct the // explanation. - return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) && - second_matcher_.Matches(pair_getters::Second(a_pair, Rank0())); + return first_matcher_.Matches(pair_getters::First(a_pair, Rank1())) && + second_matcher_.Matches(pair_getters::Second(a_pair, Rank1())); } StringMatchResultListener first_inner_listener; - if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()), + if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank1()), &first_inner_listener)) { *listener << "whose first field does not match"; PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); return false; } StringMatchResultListener second_inner_listener; - if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()), + if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank1()), &second_inner_listener)) { *listener << "whose second field does not match"; PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); @@ -3151,8 +3152,8 @@ class PairMatcher { }; template -auto UnpackStructImpl(const T& t, IndexSequence, int) - -> decltype(std::tie(get(t)...)) { +auto UnpackStructImpl(const T& t, std::index_sequence, + int) -> decltype(std::tie(get(t)...)) { static_assert(std::tuple_size::value == sizeof...(I), "Number of arguments doesn't match the number of fields."); return std::tie(get(t)...); @@ -3160,97 +3161,97 @@ auto UnpackStructImpl(const T& t, IndexSequence, int) #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606 template -auto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<1>, char) { const auto& [a] = t; return std::tie(a); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<2>, char) { const auto& [a, b] = t; return std::tie(a, b); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<3>, char) { const auto& [a, b, c] = t; return std::tie(a, b, c); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<4>, char) { const auto& [a, b, c, d] = t; return std::tie(a, b, c, d); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<5>, char) { const auto& [a, b, c, d, e] = t; return std::tie(a, b, c, d, e); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<6>, char) { const auto& [a, b, c, d, e, f] = t; return std::tie(a, b, c, d, e, f); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<7>, char) { const auto& [a, b, c, d, e, f, g] = t; return std::tie(a, b, c, d, e, f, g); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<8>, char) { const auto& [a, b, c, d, e, f, g, h] = t; return std::tie(a, b, c, d, e, f, g, h); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<9>, char) { const auto& [a, b, c, d, e, f, g, h, i] = t; return std::tie(a, b, c, d, e, f, g, h, i); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<10>, char) { const auto& [a, b, c, d, e, f, g, h, i, j] = t; return std::tie(a, b, c, d, e, f, g, h, i, j); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<11>, char) { const auto& [a, b, c, d, e, f, g, h, i, j, k] = t; return std::tie(a, b, c, d, e, f, g, h, i, j, k); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<12>, char) { const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t; return std::tie(a, b, c, d, e, f, g, h, i, j, k, l); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<13>, char) { const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t; return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<14>, char) { const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t; return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<15>, char) { const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t; return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<16>, char) { const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t; return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<17>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<17>, char) { const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q] = t; return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<18>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<18>, char) { const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r] = t; return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r); } template -auto UnpackStructImpl(const T& t, MakeIndexSequence<19>, char) { +auto UnpackStructImpl(const T& t, std::make_index_sequence<19>, char) { const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s] = t; return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s); } @@ -3258,8 +3259,8 @@ auto UnpackStructImpl(const T& t, MakeIndexSequence<19>, char) { template auto UnpackStruct(const T& t) - -> decltype((UnpackStructImpl)(t, MakeIndexSequence{}, 0)) { - return (UnpackStructImpl)(t, MakeIndexSequence{}, 0); + -> decltype((UnpackStructImpl)(t, std::make_index_sequence{}, 0)) { + return (UnpackStructImpl)(t, std::make_index_sequence{}, 0); } // Helper function to do comma folding in C++11. @@ -3272,7 +3273,7 @@ template class FieldsAreMatcherImpl; template -class FieldsAreMatcherImpl> +class FieldsAreMatcherImpl> : public MatcherInterface { using UnpackedType = decltype(UnpackStruct(std::declval())); @@ -3354,8 +3355,8 @@ class FieldsAreMatcher { template operator Matcher() const { // NOLINT return Matcher( - new FieldsAreMatcherImpl>( - matchers_)); + new FieldsAreMatcherImpl>(matchers_)); } private: @@ -5444,47 +5445,47 @@ PolymorphicMatcher> ThrowsMessage( ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) // MATCHER* macros itself are listed below. -#define MATCHER(name, description) \ - class name##Matcher \ - : public ::testing::internal::MatcherBaseImpl { \ - public: \ - template \ - class gmock_Impl : public ::testing::MatcherInterface { \ - public: \ - gmock_Impl() {} \ - bool MatchAndExplain( \ - const arg_type& arg, \ - ::testing::MatchResultListener* result_listener) const override; \ - void DescribeTo(::std::ostream* gmock_os) const override { \ - *gmock_os << FormatDescription(false); \ - } \ - void DescribeNegationTo(::std::ostream* gmock_os) const override { \ - *gmock_os << FormatDescription(true); \ - } \ - \ - private: \ - ::std::string FormatDescription(bool negation) const { \ - /* NOLINTNEXTLINE readability-redundant-string-init */ \ - ::std::string gmock_description = (description); \ - if (!gmock_description.empty()) { \ - return gmock_description; \ - } \ - return ::testing::internal::FormatMatcherDescription(negation, #name, \ - {}, {}); \ - } \ - }; \ - }; \ - inline name##Matcher GMOCK_INTERNAL_WARNING_PUSH() \ - GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-function") \ - GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \ - name GMOCK_INTERNAL_WARNING_POP()() { \ - return {}; \ - } \ - template \ - bool name##Matcher::gmock_Impl::MatchAndExplain( \ - const arg_type& arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \ - const +#define MATCHER(name, description) \ + class name##Matcher \ + : public ::testing::internal::MatcherBaseImpl { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl() {} \ + bool MatchAndExplain( \ + const arg_type& arg, \ + ::testing::MatchResultListener* result_listener) const override; \ + void DescribeTo(::std::ostream* gmock_os) const override { \ + *gmock_os << FormatDescription(false); \ + } \ + void DescribeNegationTo(::std::ostream* gmock_os) const override { \ + *gmock_os << FormatDescription(true); \ + } \ + \ + private: \ + ::std::string FormatDescription(bool negation) const { \ + /* NOLINTNEXTLINE readability-redundant-string-init */ \ + ::std::string gmock_description = (description); \ + if (!gmock_description.empty()) { \ + return gmock_description; \ + } \ + return ::testing::internal::FormatMatcherDescription(negation, #name, \ + {}, {}); \ + } \ + }; \ + }; \ + inline name##Matcher GMOCK_INTERNAL_WARNING_PUSH() \ + GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-function") \ + GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \ + name GMOCK_INTERNAL_WARNING_POP()() { \ + return {}; \ + } \ + template \ + bool name##Matcher::gmock_Impl::MatchAndExplain( \ + const arg_type& arg, \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED ::testing::MatchResultListener* \ + result_listener) const #define MATCHER_P(name, p0, description) \ GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (#p0), (p0)) @@ -5566,11 +5567,11 @@ PolymorphicMatcher> ThrowsMessage( } \ template \ template \ - bool full_name::gmock_Impl< \ - arg_type>::MatchAndExplain(const arg_type& arg, \ - ::testing::MatchResultListener* \ - result_listener GTEST_ATTRIBUTE_UNUSED_) \ - const + bool full_name:: \ + gmock_Impl::MatchAndExplain( \ + const arg_type& arg, \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED ::testing:: \ + MatchResultListener* result_listener) const #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \ GMOCK_PP_TAIL( \ @@ -5605,8 +5606,8 @@ PolymorphicMatcher> ThrowsMessage( #define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args)) -#define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \ - , gmock_p##i +#define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg) \ + , ::std::forward(gmock_p##i) // To prevent ADL on certain functions we put them on a separate namespace. using namespace no_adl; // NOLINT diff --git a/googlemock/include/gmock/gmock-more-actions.h b/googlemock/include/gmock/gmock-more-actions.h index 40300766f084..e341d47fca94 100644 --- a/googlemock/include/gmock/gmock-more-actions.h +++ b/googlemock/include/gmock/gmock-more-actions.h @@ -592,8 +592,9 @@ namespace internal { // Overloads for other custom-callables are provided in the // internal/custom/gmock-generated-actions.h header. template -auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) { - return f(args...); +auto InvokeArgument(F &&f, + Args... args) -> decltype(std::forward(f)(args...)) { + return std::forward(f)(args...); } template @@ -606,7 +607,7 @@ struct InvokeArgumentAction { internal::FlatTuple args_tuple(FlatTupleConstructTag{}, std::forward(args)...); return params.Apply([&](const Params &...unpacked_params) { - auto &&callable = args_tuple.template Get(); + auto &&callable = std::move(args_tuple.template Get()); return internal::InvokeArgument( std::forward(callable), unpacked_params...); }); diff --git a/googlemock/include/gmock/gmock.h b/googlemock/include/gmock/gmock.h index 568c8c71d785..c78fb8ee597d 100644 --- a/googlemock/include/gmock/gmock.h +++ b/googlemock/include/gmock/gmock.h @@ -53,13 +53,14 @@ // // where all clauses are optional and WillOnce() can be repeated. -#include "gmock/gmock-actions.h" -#include "gmock/gmock-cardinalities.h" -#include "gmock/gmock-function-mocker.h" -#include "gmock/gmock-matchers.h" -#include "gmock/gmock-more-actions.h" -#include "gmock/gmock-more-matchers.h" -#include "gmock/gmock-nice-strict.h" +#include "gmock/gmock-actions.h" // IWYU pragma: export +#include "gmock/gmock-cardinalities.h" // IWYU pragma: export +#include "gmock/gmock-function-mocker.h" // IWYU pragma: export +#include "gmock/gmock-matchers.h" // IWYU pragma: export +#include "gmock/gmock-more-actions.h" // IWYU pragma: export +#include "gmock/gmock-more-matchers.h" // IWYU pragma: export +#include "gmock/gmock-nice-strict.h" // IWYU pragma: export +#include "gmock/gmock-spec-builders.h" // IWYU pragma: export #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index ead6d7c805e9..b7685f573001 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -44,6 +44,7 @@ #include // NOLINT #include #include +#include #include #include "gmock/internal/gmock-port.h" @@ -420,7 +421,7 @@ struct RemoveConstFromKey > { GTEST_API_ void IllegalDoDefault(const char* file, int line); template -auto ApplyImpl(F&& f, Tuple&& args, IndexSequence) +auto ApplyImpl(F&& f, Tuple&& args, std::index_sequence) -> decltype(std::forward(f)( std::get(std::forward(args))...)) { return std::forward(f)(std::get(std::forward(args))...); @@ -428,12 +429,13 @@ auto ApplyImpl(F&& f, Tuple&& args, IndexSequence) // Apply the function to a tuple of arguments. template -auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl( - std::forward(f), std::forward(args), - MakeIndexSequence::type>::value>())) { +auto Apply(F&& f, Tuple&& args) + -> decltype(ApplyImpl( + std::forward(f), std::forward(args), + std::make_index_sequence::type>::value>())) { return ApplyImpl(std::forward(f), std::forward(args), - MakeIndexSequence::type>::value>()); } diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h index 55ddfb6c6a3b..e9d9e32a7a80 100644 --- a/googlemock/include/gmock/internal/gmock-port.h +++ b/googlemock/include/gmock/internal/gmock-port.h @@ -56,7 +56,7 @@ #include "gmock/internal/custom/gmock-port.h" #include "gtest/internal/gtest-port.h" -#ifdef GTEST_HAS_ABSL +#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) #include "absl/flags/declare.h" #include "absl/flags/flag.h" #endif @@ -73,7 +73,7 @@ #define GMOCK_FLAG(name) FLAGS_gmock_##name // Pick a command line flags implementation. -#ifdef GTEST_HAS_ABSL +#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) // Macros for defining flags. #define GMOCK_DEFINE_bool_(name, default_val, doc) \ @@ -95,7 +95,7 @@ #define GMOCK_FLAG_SET(name, value) \ (void)(::absl::SetFlag(&GMOCK_FLAG(name), value)) -#else // GTEST_HAS_ABSL +#else // defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) // Macros for defining flags. #define GMOCK_DEFINE_bool_(name, default_val, doc) \ @@ -134,6 +134,6 @@ #define GMOCK_FLAG_GET(name) ::testing::GMOCK_FLAG(name) #define GMOCK_FLAG_SET(name, value) (void)(::testing::GMOCK_FLAG(name) = value) -#endif // GTEST_HAS_ABSL +#endif // defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ diff --git a/googlemock/src/gmock-internal-utils.cc b/googlemock/src/gmock-internal-utils.cc index 5c2ce0d57eb6..96c7e306ec11 100644 --- a/googlemock/src/gmock-internal-utils.cc +++ b/googlemock/src/gmock-internal-utils.cc @@ -44,6 +44,7 @@ #include #include // NOLINT #include +#include #include #include "gmock/gmock.h" @@ -211,14 +212,14 @@ constexpr char UnBase64Impl(char c, const char* const base64, char carry) { } template -constexpr std::array UnBase64Impl(IndexSequence, +constexpr std::array UnBase64Impl(std::index_sequence, const char* const base64) { return { {UnBase64Impl(UndoWebSafeEncoding(static_cast(I)), base64, 0)...}}; } constexpr std::array UnBase64(const char* const base64) { - return UnBase64Impl(MakeIndexSequence<256>{}, base64); + return UnBase64Impl(std::make_index_sequence<256>{}, base64); } static constexpr char kBase64[] = diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc index 07bba4f0103d..277add6b622d 100644 --- a/googlemock/src/gmock-matchers.cc +++ b/googlemock/src/gmock-matchers.cc @@ -120,7 +120,7 @@ GTEST_API_ std::string FormatMatcherDescription( // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method". // "Introduction to Algorithms (Second ed.)", pp. 651-664. // [2] "Ford-Fulkerson algorithm", Wikipedia, -// 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm' +// 'https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm' class MaxBipartiteMatchState { public: explicit MaxBipartiteMatchState(const MatchMatrix& graph) @@ -236,9 +236,8 @@ static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs, os << "{"; const char* sep = ""; for (Iter it = pairs.begin(); it != pairs.end(); ++it) { - os << sep << "\n (" - << "element #" << it->first << ", " - << "matcher #" << it->second << ")"; + os << sep << "\n (" << "element #" << it->first << ", " << "matcher #" + << it->second << ")"; sep = ","; } os << "\n}"; @@ -374,20 +373,20 @@ bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix( return true; } - if (match_flags() == UnorderedMatcherRequire::ExactMatch) { - if (matrix.LhsSize() != matrix.RhsSize()) { - // The element count doesn't match. If the container is empty, - // there's no need to explain anything as Google Mock already - // prints the empty container. Otherwise we just need to show - // how many elements there actually are. - if (matrix.LhsSize() != 0 && listener->IsInterested()) { - *listener << "which has " << Elements(matrix.LhsSize()); - } - return false; + const bool is_exact_match_with_size_discrepency = + match_flags() == UnorderedMatcherRequire::ExactMatch && + matrix.LhsSize() != matrix.RhsSize(); + if (is_exact_match_with_size_discrepency) { + // The element count doesn't match. If the container is empty, + // there's no need to explain anything as Google Mock already + // prints the empty container. Otherwise we just need to show + // how many elements there actually are. + if (matrix.LhsSize() != 0 && listener->IsInterested()) { + *listener << "which has " << Elements(matrix.LhsSize()) << "\n"; } } - bool result = true; + bool result = !is_exact_match_with_size_discrepency; ::std::vector element_matched(matrix.LhsSize(), 0); ::std::vector matcher_matched(matrix.RhsSize(), 0); diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index de8947163586..ffdf03dd45e5 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -490,6 +490,7 @@ class MockObjectRegistry { // failure, unless the user explicitly asked us to ignore it. ~MockObjectRegistry() { if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return; + internal::MutexLock l(&internal::g_gmock_mutex); int leaked_count = 0; for (StateMap::const_iterator it = states_.begin(); it != states_.end(); @@ -530,7 +531,7 @@ class MockObjectRegistry { #ifdef GTEST_OS_QURT qurt_exception_raise_fatal(); #else - _exit(1); // We cannot call exit() as it is not reentrant and + _Exit(1); // We cannot call exit() as it is not reentrant and // may already have been called. #endif } diff --git a/googlemock/test/gmock-matchers-comparisons_test.cc b/googlemock/test/gmock-matchers-comparisons_test.cc index b2ce99e18d4f..5b75b457be04 100644 --- a/googlemock/test/gmock-matchers-comparisons_test.cc +++ b/googlemock/test/gmock-matchers-comparisons_test.cc @@ -1769,6 +1769,15 @@ TEST(StartsWithTest, CanDescribeSelf) { EXPECT_EQ("starts with \"Hi\"", Describe(m)); } +TEST(StartsWithTest, WorksWithStringMatcherOnStringViewMatchee) { +#if GTEST_INTERNAL_HAS_STRING_VIEW + EXPECT_THAT(internal::StringView("talk to me goose"), + StartsWith(std::string("talk"))); +#else + GTEST_SKIP() << "Not applicable without internal::StringView."; +#endif // GTEST_INTERNAL_HAS_STRING_VIEW +} + // Tests EndsWith(s). TEST(EndsWithTest, MatchesStringWithGivenSuffix) { diff --git a/googlemock/test/gmock-matchers-containers_test.cc b/googlemock/test/gmock-matchers-containers_test.cc index 38fd9a5dd76f..acea4ec357e0 100644 --- a/googlemock/test/gmock-matchers-containers_test.cc +++ b/googlemock/test/gmock-matchers-containers_test.cc @@ -2014,7 +2014,14 @@ TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) { StringMatchResultListener listener; EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) << listener.str(); - EXPECT_THAT(listener.str(), Eq("which has 1 element")); + EXPECT_THAT(listener.str(), + Eq("which has 1 element\n" + "where the following matchers don't match any elements:\n" + "matcher #0: is equal to 1,\n" + "matcher #1: is equal to 2,\n" + "matcher #2: is equal to 3\n" + "and where the following elements don't match any matchers:\n" + "element #0: 4")); } TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { @@ -2022,7 +2029,11 @@ TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { StringMatchResultListener listener; EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) << listener.str(); - EXPECT_THAT(listener.str(), Eq("")); + EXPECT_THAT(listener.str(), + Eq("where the following matchers don't match any elements:\n" + "matcher #0: is equal to 1,\n" + "matcher #1: is equal to 2,\n" + "matcher #2: is equal to 3")); } TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) { @@ -2438,7 +2449,7 @@ TEST(UnorderedPointwiseTest, RejectsWrongSize) { const double lhs[2] = {1, 2}; const int rhs[1] = {0}; EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); - EXPECT_EQ("which has 2 elements", + EXPECT_EQ("which has 2 elements\n", Explain(UnorderedPointwise(Gt(), rhs), lhs)); const int rhs2[3] = {0, 1, 2}; diff --git a/googlemock/test/gmock-more-actions_test.cc b/googlemock/test/gmock-more-actions_test.cc index 9980f3bc4567..354a79b192c8 100644 --- a/googlemock/test/gmock-more-actions_test.cc +++ b/googlemock/test/gmock-more-actions_test.cc @@ -85,6 +85,16 @@ struct UnaryFunctor { int operator()(bool x) { return x ? 1 : -1; } }; +struct UnaryMoveOnlyFunctor : UnaryFunctor { + UnaryMoveOnlyFunctor() = default; + UnaryMoveOnlyFunctor(const UnaryMoveOnlyFunctor&) = delete; + UnaryMoveOnlyFunctor(UnaryMoveOnlyFunctor&&) = default; +}; + +struct OneShotUnaryFunctor { + int operator()(bool x) && { return x ? 1 : -1; } +}; + const char* Binary(const char* input, short n) { return input + n; } // NOLINT int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT @@ -698,12 +708,24 @@ TEST(InvokeArgumentTest, Function0) { EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary))); } -// Tests using InvokeArgument with a unary function. +// Tests using InvokeArgument with a unary functor. TEST(InvokeArgumentTest, Functor1) { Action a = InvokeArgument<0>(true); // NOLINT EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor()))); } +// Tests using InvokeArgument with a unary move-only functor. +TEST(InvokeArgumentTest, Functor1MoveOnly) { + Action a = InvokeArgument<0>(true); // NOLINT + EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryMoveOnlyFunctor()))); +} + +// Tests using InvokeArgument with a one-shot unary functor. +TEST(InvokeArgumentTest, OneShotFunctor1) { + Action a = InvokeArgument<0>(true); // NOLINT + EXPECT_EQ(1, a.Perform(std::make_tuple(OneShotUnaryFunctor()))); +} + // Tests using InvokeArgument with a 5-ary function. TEST(InvokeArgumentTest, Function5) { Action a = // NOLINT @@ -806,6 +828,22 @@ TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) { EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); } +TEST(InvokeArgumentTest, MoveOnlyType) { + struct Marker {}; + struct { + // Method takes a unique_ptr (to a type we don't care about), and an + // invocable type. + MOCK_METHOD(bool, MockMethod, + (std::unique_ptr, std::function), ()); + } mock; + + ON_CALL(mock, MockMethod(_, _)).WillByDefault(InvokeArgument<1>()); + + // This compiles, but is a little opaque as a workaround: + ON_CALL(mock, MockMethod(_, _)) + .WillByDefault(WithArg<1>(InvokeArgument<0>())); +} + // Tests DoAll(a1, a2). TEST(DoAllTest, TwoActions) { int n = 0; diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 221de2d20b3d..aaf88d74ee79 100644 --- a/googlemock/test/gmock-spec-builders_test.cc +++ b/googlemock/test/gmock-spec-builders_test.cc @@ -906,7 +906,7 @@ TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) { " - returning default value.")); } -TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) { +TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) { MockB b; std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1)); diff --git a/googlemock/test/gmock_link_test.h b/googlemock/test/gmock_link_test.h index db11c2d24d1a..cf0a985b6320 100644 --- a/googlemock/test/gmock_link_test.h +++ b/googlemock/test/gmock_link_test.h @@ -187,6 +187,7 @@ using testing::SetErrnoAndReturn; #if GTEST_HAS_EXCEPTIONS using testing::Throw; +using testing::Rethrow; #endif using testing::ContainsRegex; @@ -416,6 +417,14 @@ TEST(LinkTest, TestThrow) { EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42)); EXPECT_THROW(mock.VoidFromString(nullptr), int); } +// Tests the linkage of the Rethrow action. +TEST(LinkTest, TestRethrow) { + Mock mock; + + EXPECT_CALL(mock, VoidFromString(_)) + .WillOnce(Rethrow(std::make_exception_ptr(42))); + EXPECT_THROW(mock.VoidFromString(nullptr), int); +} #endif // GTEST_HAS_EXCEPTIONS // The ACTION*() macros trigger warning C4100 (unreferenced formal diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index caafa8c76853..dce6a7c9ee6f 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -5,7 +5,7 @@ # CMake build script for Google Test. # # To run the tests for Google Test itself on Linux, use 'make test' or -# ctest. You can select which tests to run using 'ctest -R regex'. +# ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. # When other libraries are using a shared version of runtime libraries, @@ -35,7 +35,7 @@ endif() ######################################################################## # -# Project-wide settings +# Project-wide settings. # Name of the project. # @@ -44,7 +44,7 @@ endif() # ${gtest_BINARY_DIR}. # Language "C" is required for find_package(Threads). -# Project version: +# Project version. cmake_minimum_required(VERSION 3.13) project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) @@ -53,7 +53,7 @@ if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() -# These commands only run if this is the main project +# These commands only run if this is the main project. if(CMAKE_PROJECT_NAME STREQUAL "gtest" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to @@ -83,7 +83,7 @@ include(cmake/internal_utils.cmake) config_compiler_and_linker() # Defined in internal_utils.cmake. # Needed to set the namespace for both the export targets and the -# alias libraries +# alias libraries. set(cmake_package_name GTest CACHE INTERNAL "") # Create the CMake package file descriptors. @@ -114,10 +114,10 @@ include_directories(${gtest_build_include_dirs}) ######################################################################## # -# Defines the gtest & gtest_main libraries. User tests should link +# Defines the gtest & gtest_main libraries. User tests should link # with one of them. -# Google Test libraries. We build them using more strict warnings than what +# Google Test libraries. We build them using more strict warnings than what # are used for other targets, to ensure that gtest can be compiled by a user # aggressive about warnings. cxx_library(gtest "${cxx_strict}" src/gtest-all.cc) @@ -147,22 +147,22 @@ target_include_directories(gtest SYSTEM INTERFACE target_include_directories(gtest_main SYSTEM INTERFACE "$" "$/${CMAKE_INSTALL_INCLUDEDIR}>") -if(CMAKE_SYSTEM_NAME MATCHES "QNX") +if(CMAKE_SYSTEM_NAME MATCHES "QNX" AND CMAKE_SYSTEM_VERSION VERSION_GREATER_EQUAL 7.1) target_link_libraries(gtest PUBLIC regex) endif() target_link_libraries(gtest_main PUBLIC gtest) ######################################################################## # -# Install rules +# Install rules. install_project(gtest gtest_main) ######################################################################## # # Samples on how to link user tests with gtest or gtest_main. # -# They are not built by default. To build them, set the -# gtest_build_samples option to ON. You can do it by running ccmake +# They are not built by default. To build them, set the +# gtest_build_samples option to ON. You can do it by running ccmake # or specifying the -Dgtest_build_samples=ON flag when running cmake. if (gtest_build_samples) @@ -185,8 +185,8 @@ endif() # You can skip this section if you aren't interested in testing # Google Test itself. # -# The tests are not built by default. To build them, set the -# gtest_build_tests option to ON. You can do it by running ccmake +# The tests are not built by default. To build them, set the +# gtest_build_tests option to ON. You can do it by running ccmake # or specifying the -Dgtest_build_tests=ON flag when running cmake. if (gtest_build_tests) @@ -268,7 +268,7 @@ if (gtest_build_tests) py_test(gtest_skip_environment_check_output_test) # Visual Studio .NET 2003 does not support STL with exceptions disabled. - if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003 + if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003 cxx_executable_with_flags( googletest-catch-exceptions-no-ex-test_ "${cxx_no_exception}" diff --git a/googletest/README.md b/googletest/README.md index 815f3fc02bab..a7d9aa32589f 100644 --- a/googletest/README.md +++ b/googletest/README.md @@ -12,7 +12,7 @@ GoogleTest comes with a CMake build script ([CMakeLists.txt](https://github.com/google/googletest/blob/main/CMakeLists.txt)) that can be used on a wide range of platforms ("C" stands for cross-platform.). If you don't have CMake installed already, you can download it for free from -. +. CMake works by generating native makefiles or build projects that can be used in the compiler environment of your choice. You can either build GoogleTest as a @@ -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 v1.13.0 +git clone https://github.com/google/googletest.git -b v1.15.0 cd googletest # Main directory of the cloned repository. mkdir build # Create a directory to hold the build output. cd build diff --git a/googletest/cmake/Config.cmake.in b/googletest/cmake/Config.cmake.in index 12be4498b1a0..3f706612b24f 100644 --- a/googletest/cmake/Config.cmake.in +++ b/googletest/cmake/Config.cmake.in @@ -4,6 +4,10 @@ if (@GTEST_HAS_PTHREAD@) set(THREADS_PREFER_PTHREAD_FLAG @THREADS_PREFER_PTHREAD_FLAG@) find_dependency(Threads) endif() +if (@GTEST_HAS_ABSL@) + find_dependency(absl) + find_dependency(re2) +endif() include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake") check_required_components("@project_name@") diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake index 64fa340fd9eb..580ac1cbc381 100644 --- a/googletest/cmake/internal_utils.cmake +++ b/googletest/cmake/internal_utils.cmake @@ -29,7 +29,7 @@ macro(fix_default_compiler_settings_) CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt) # When Google Test is built as a shared library, it should also use - # shared runtime libraries. Otherwise, it may end up with multiple + # shared runtime libraries. Otherwise, it may end up with multiple # copies of runtime library data in different modules, resulting in # hard-to-find crashes. When it is built as a static library, it is # preferable to use CRT as static libraries, as we don't have to rely @@ -55,11 +55,11 @@ macro(fix_default_compiler_settings_) endmacro() # Defines the compiler/linker flags used to build Google Test and -# Google Mock. You can tweak these definitions to suit your need. A +# Google Mock. You can tweak these definitions to suit your need. A # variable's value is empty before it's explicitly assigned to. macro(config_compiler_and_linker) # Note: pthreads on MinGW is not supported, even if available - # instead, we use windows threading primitives + # instead, we use windows threading primitives. unset(GTEST_HAS_PTHREAD) if (NOT gtest_disable_pthreads AND NOT MINGW) # Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT. @@ -79,8 +79,8 @@ macro(config_compiler_and_linker) set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1") set(cxx_no_exception_flags "-EHs-c- -D_HAS_EXCEPTIONS=0") set(cxx_no_rtti_flags "-GR-") - # Suppress "unreachable code" warning - # http://stackoverflow.com/questions/3232669 explains the issue. + # Suppress "unreachable code" warning, + # https://stackoverflow.com/questions/3232669 explains the issue. set(cxx_base_flags "${cxx_base_flags} -wd4702") # Ensure MSVC treats source files as UTF-8 encoded. if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") @@ -110,7 +110,7 @@ macro(config_compiler_and_linker) set(cxx_exception_flags "-fexceptions") set(cxx_no_exception_flags "-fno-exceptions") # Until version 4.3.2, GCC doesn't define a macro to indicate - # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI + # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # explicitly. set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0") set(cxx_strict_flags @@ -127,7 +127,7 @@ macro(config_compiler_and_linker) set(cxx_exception_flags "-qeh") set(cxx_no_exception_flags "-qnoeh") # Until version 9.0, Visual Age doesn't define a macro to indicate - # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI + # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # explicitly. set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "HP") @@ -157,7 +157,7 @@ macro(config_compiler_and_linker) set(cxx_strict "${cxx_default} ${cxx_strict_flags}") endmacro() -# Defines the gtest & gtest_main libraries. User tests should link +# Defines the gtest & gtest_main libraries. User tests should link # with one of them. function(cxx_library_with_type name type cxx_flags) # type can be either STATIC or SHARED to denote a static or shared library. @@ -167,7 +167,7 @@ function(cxx_library_with_type name type cxx_flags) set_target_properties(${name} PROPERTIES COMPILE_FLAGS "${cxx_flags}") - # Set the output directory for build artifacts + # Set the output directory for build artifacts. set_target_properties(${name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" @@ -175,7 +175,7 @@ function(cxx_library_with_type name type cxx_flags) ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") - # make PDBs match library name + # Make PDBs match library name. get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX) set_target_properties(${name} PROPERTIES @@ -212,7 +212,7 @@ endfunction() # cxx_executable_with_flags(name cxx_flags libs srcs...) # -# creates a named C++ executable that depends on the given libraries and +# Creates a named C++ executable that depends on the given libraries and # is built from the given source files with the given compiler flags. function(cxx_executable_with_flags name cxx_flags libs) add_executable(${name} ${ARGN}) @@ -239,19 +239,21 @@ endfunction() # cxx_executable(name dir lib srcs...) # -# creates a named target that depends on the given libs and is built -# from the given source files. dir/name.cc is implicitly included in +# Creates a named target that depends on the given libs and is built +# from the given source files. dir/name.cc is implicitly included in # the source file list. function(cxx_executable name dir libs) cxx_executable_with_flags( ${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN}) endfunction() -find_package(Python3) +if(gtest_build_tests) + find_package(Python3) +endif() # cxx_test_with_flags(name cxx_flags libs srcs...) # -# creates a named C++ test that depends on the given libs and is built +# Creates a named C++ test that depends on the given libs and is built # from the given source files with the given compiler flags. function(cxx_test_with_flags name cxx_flags libs) cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN}) @@ -260,8 +262,8 @@ endfunction() # cxx_test(name libs srcs...) # -# creates a named test target that depends on the given libs and is -# built from the given source files. Unlike cxx_test_with_flags, +# Creates a named test target that depends on the given libs and is +# built from the given source files. Unlike cxx_test_with_flags, # test/name.cc is already implicitly included in the source file list. function(cxx_test name libs) cxx_test_with_flags("${name}" "${cxx_default}" "${libs}" @@ -270,8 +272,8 @@ endfunction() # py_test(name) # -# creates a Python test with the given name whose main module is in -# test/name.py. It does nothing if Python is not installed. +# Creates a Python test with the given name whose main module is in +# test/name.py. It does nothing if Python is not installed. function(py_test name) if (NOT Python3_Interpreter_FOUND) return() @@ -307,7 +309,7 @@ function(install_project) ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") - # Install PDBs + # Install PDBs. foreach(t ${ARGN}) get_target_property(t_pdb_name ${t} COMPILE_PDB_NAME) get_target_property(t_pdb_name_debug ${t} COMPILE_PDB_NAME_DEBUG) diff --git a/googletest/include/gtest/gtest-assertion-result.h b/googletest/include/gtest/gtest-assertion-result.h index 56fe128f2a5a..74eb2b1f3c71 100644 --- a/googletest/include/gtest/gtest-assertion-result.h +++ b/googletest/include/gtest/gtest-assertion-result.h @@ -129,7 +129,7 @@ namespace testing { // // Expected: Foo() is even // Actual: it's 5 -// + class GTEST_API_ AssertionResult { public: // Copy constructor. diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 08fef8c7d346..3c61909726f3 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -293,8 +293,8 @@ class GTEST_API_ KilledBySignal { // statement is compiled but not executed, to ensure that // EXPECT_DEATH_IF_SUPPORTED compiles with a certain // parameter if and only if EXPECT_DEATH compiles with it. -// regex - A regex that a macro such as EXPECT_DEATH would use to test -// the output of statement. This parameter has to be +// regex_or_matcher - A regex that a macro such as EXPECT_DEATH would use +// to test the output of statement. This parameter has to be // compiled but not evaluated by this macro, to ensure that // this macro only accepts expressions that a macro such as // EXPECT_DEATH would accept. @@ -311,13 +311,13 @@ class GTEST_API_ KilledBySignal { // statement unconditionally returns or throws. The Message constructor at // the end allows the syntax of streaming additional messages into the // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. -#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \ +#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex_or_matcher, terminator) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \ << "Statement '" #statement "' cannot be verified."; \ } else if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::RE::PartialMatch(".*", (regex)); \ + ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ terminator; \ } else \ diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index 59b805e4e462..448ac6b7ee2e 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -59,7 +59,7 @@ #ifdef GTEST_HAS_ABSL #include -#include "absl/strings/internal/has_absl_stringify.h" +#include "absl/strings/has_absl_stringify.h" #include "absl/strings/str_cat.h" #endif // GTEST_HAS_ABSL @@ -121,14 +121,14 @@ class GTEST_API_ Message { // Streams a non-pointer value to this object. If building a version of // GoogleTest with ABSL, this overload is only enabled if the value does not // have an AbslStringify definition. - template ::value, // NOLINT - int>::type = 0 + , + typename std::enable_if::value, // NOLINT + int>::type = 0 #endif // GTEST_HAS_ABSL - > + > inline Message& operator<<(const T& val) { // Some libraries overload << for STL containers. These // overloads are defined in the global namespace instead of ::std. @@ -153,9 +153,8 @@ class GTEST_API_ Message { // Streams a non-pointer value with an AbslStringify definition to this // object. template ::value, // NOLINT - int>::type = 0> + typename std::enable_if::value, // NOLINT + int>::type = 0> inline Message& operator<<(const T& val) { // ::operator<< is needed here for a similar reason as with the non-Abseil // version above diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index 49a47ead03b7..55ee088b93fb 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -178,7 +178,7 @@ TEST_P(DerivedTest, DoesBlah) { #include #include "gtest/internal/gtest-internal.h" -#include "gtest/internal/gtest-param-util.h" +#include "gtest/internal/gtest-param-util.h" // IWYU pragma: export #include "gtest/internal/gtest-port.h" namespace testing { @@ -469,7 +469,7 @@ internal::ParamConverterGenerator ConvertGenerator( ::testing::internal::CodeLocation(__FILE__, __LINE__)); \ return 0; \ } \ - static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static int gtest_registering_dummy_; \ }; \ int GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)::gtest_registering_dummy_ = \ @@ -514,8 +514,8 @@ internal::ParamConverterGenerator ConvertGenerator( ::testing::internal::DefaultParamName, \ DUMMY_PARAM_))))(info); \ } \ - static int gtest_##prefix##test_suite_name##_dummy_ \ - GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static int \ + gtest_##prefix##test_suite_name##_dummy_ = \ ::testing::UnitTest::GetInstance() \ ->parameterized_test_registry() \ .GetTestSuitePatternHolder( \ diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index d1766e640f28..b2822bcde23c 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -116,12 +116,16 @@ #include #ifdef GTEST_HAS_ABSL -#include "absl/strings/internal/has_absl_stringify.h" +#include "absl/strings/has_absl_stringify.h" #include "absl/strings/str_cat.h" #endif // GTEST_HAS_ABSL #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" +#if GTEST_INTERNAL_HAS_STD_SPAN +#include // NOLINT +#endif // GTEST_INTERNAL_HAS_STD_SPAN + namespace testing { // Definitions in the internal* namespaces are subject to change without notice. @@ -131,13 +135,32 @@ namespace internal { template void UniversalPrint(const T& value, ::std::ostream* os); +template +struct IsStdSpan { + static constexpr bool value = false; +}; + +#if GTEST_INTERNAL_HAS_STD_SPAN +template +struct IsStdSpan> { + static constexpr bool value = true; +}; +#endif // GTEST_INTERNAL_HAS_STD_SPAN + // Used to print an STL-style container when the user doesn't define // a PrintTo() for it. +// +// NOTE: Since std::span does not have const_iterator until C++23, it would +// fail IsContainerTest before C++23. However, IsContainerTest only uses +// the presence of const_iterator to avoid treating iterators as containers +// because of iterator::iterator. Which means std::span satisfies the *intended* +// condition of IsContainerTest. struct ContainerPrinter { template (0)) == sizeof(IsContainer)) && - !IsRecursiveContainer::value>::type> + ((sizeof(IsContainerTest(0)) == sizeof(IsContainer)) && + !IsRecursiveContainer::value) || + IsStdSpan::value>::type> static void PrintValue(const T& container, std::ostream* os) { const size_t kMaxCount = 32; // The maximum number of elements to print. *os << '{'; @@ -218,8 +241,8 @@ struct StreamPrinter { // ADL (possibly involving implicit conversions). // (Use SFINAE via return type, because it seems GCC < 12 doesn't handle name // lookup properly when we do it in the template parameter list.) - static auto PrintValue(const T& value, ::std::ostream* os) - -> decltype((void)(*os << value)) { + static auto PrintValue(const T& value, + ::std::ostream* os) -> decltype((void)(*os << value)) { // Call streaming operator found by ADL, possibly with implicit conversions // of the arguments. *os << value; @@ -269,10 +292,9 @@ struct ConvertibleToStringViewPrinter { #ifdef GTEST_HAS_ABSL struct ConvertibleToAbslStringifyPrinter { - template < - typename T, - typename = typename std::enable_if< - absl::strings_internal::HasAbslStringify::value>::type> // NOLINT + template ::value>::type> // NOLINT static void PrintValue(const T& value, ::std::ostream* os) { *os << absl::StrCat(value); } @@ -530,49 +552,63 @@ int AppropriateResolution(FloatType val) { int full = std::numeric_limits::max_digits10; if (val < 0) val = -val; +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif if (val < 1000000) { FloatType mulfor6 = 1e10; - if (val >= 100000.0) { // 100,000 to 999,999 + // Without these static casts, the template instantiation for float would + // fail to compile when -Wdouble-promotion is enabled, as the arithmetic and + // comparison logic would promote floats to doubles. + if (val >= static_cast(100000.0)) { // 100,000 to 999,999 mulfor6 = 1.0; - } else if (val >= 10000.0) { + } else if (val >= static_cast(10000.0)) { mulfor6 = 1e1; - } else if (val >= 1000.0) { + } else if (val >= static_cast(1000.0)) { mulfor6 = 1e2; - } else if (val >= 100.0) { + } else if (val >= static_cast(100.0)) { mulfor6 = 1e3; - } else if (val >= 10.0) { + } else if (val >= static_cast(10.0)) { mulfor6 = 1e4; - } else if (val >= 1.0) { + } else if (val >= static_cast(1.0)) { mulfor6 = 1e5; - } else if (val >= 0.1) { + } else if (val >= static_cast(0.1)) { mulfor6 = 1e6; - } else if (val >= 0.01) { + } else if (val >= static_cast(0.01)) { mulfor6 = 1e7; - } else if (val >= 0.001) { + } else if (val >= static_cast(0.001)) { mulfor6 = 1e8; - } else if (val >= 0.0001) { + } else if (val >= static_cast(0.0001)) { mulfor6 = 1e9; } - if (static_cast(static_cast(val * mulfor6 + 0.5)) / + if (static_cast(static_cast( + val * mulfor6 + (static_cast(0.5)))) / mulfor6 == val) return 6; - } else if (val < 1e10) { - FloatType divfor6 = 1.0; - if (val >= 1e9) { // 1,000,000,000 to 9,999,999,999 + } else if (val < static_cast(1e10)) { + FloatType divfor6 = static_cast(1.0); + if (val >= static_cast(1e9)) { // 1,000,000,000 to 9,999,999,999 divfor6 = 10000; - } else if (val >= 1e8) { // 100,000,000 to 999,999,999 + } else if (val >= + static_cast(1e8)) { // 100,000,000 to 999,999,999 divfor6 = 1000; - } else if (val >= 1e7) { // 10,000,000 to 99,999,999 + } else if (val >= + static_cast(1e7)) { // 10,000,000 to 99,999,999 divfor6 = 100; - } else if (val >= 1e6) { // 1,000,000 to 9,999,999 + } else if (val >= static_cast(1e6)) { // 1,000,000 to 9,999,999 divfor6 = 10; } - if (static_cast(static_cast(val / divfor6 + 0.5)) * + if (static_cast(static_cast( + val / divfor6 + (static_cast(0.5)))) * divfor6 == val) return 6; } +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif return full; } diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 72de536bceec..305b0b50dd4c 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -194,33 +194,34 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ GTEST_NAME_GENERATOR_(CaseName) -#define TYPED_TEST(CaseName, TestName) \ - static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ - "test-name must not be empty"); \ - template \ - class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ - : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - void TestBody() override; \ - }; \ - static bool gtest_##CaseName##_##TestName##_registered_ \ - GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \ - CaseName, \ - ::testing::internal::TemplateSel, \ - GTEST_TYPE_PARAMS_( \ - CaseName)>::Register("", \ - ::testing::internal::CodeLocation( \ - __FILE__, __LINE__), \ - GTEST_STRINGIFY_(CaseName), \ - GTEST_STRINGIFY_(TestName), 0, \ - ::testing::internal::GenerateNames< \ - GTEST_NAME_GENERATOR_(CaseName), \ - GTEST_TYPE_PARAMS_(CaseName)>()); \ - template \ - void GTEST_TEST_CLASS_NAME_(CaseName, \ +#define TYPED_TEST(CaseName, TestName) \ + static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ + "test-name must not be empty"); \ + template \ + class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ + : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + void TestBody() override; \ + }; \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool \ + gtest_##CaseName##_##TestName##_registered_ = \ + ::testing::internal::TypeParameterizedTest< \ + CaseName, \ + ::testing::internal::TemplateSel, \ + GTEST_TYPE_PARAMS_( \ + CaseName)>::Register("", \ + ::testing::internal::CodeLocation( \ + __FILE__, __LINE__), \ + GTEST_STRINGIFY_(CaseName), \ + GTEST_STRINGIFY_(TestName), 0, \ + ::testing::internal::GenerateNames< \ + GTEST_NAME_GENERATOR_(CaseName), \ + GTEST_TYPE_PARAMS_(CaseName)>()); \ + template \ + void GTEST_TEST_CLASS_NAME_(CaseName, \ TestName)::TestBody() // Legacy API is deprecated but still available @@ -267,22 +268,23 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define TYPED_TEST_P(SuiteName, TestName) \ - namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ - template \ - class TestName : public SuiteName { \ - private: \ - typedef SuiteName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - void TestBody() override; \ - }; \ - static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ - __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \ - GTEST_STRINGIFY_(TestName)); \ - } \ - template \ - void GTEST_SUITE_NAMESPACE_( \ +#define TYPED_TEST_P(SuiteName, TestName) \ + namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ + template \ + class TestName : public SuiteName { \ + private: \ + typedef SuiteName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + void TestBody() override; \ + }; \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool \ + gtest_##TestName##_defined_ = \ + GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ + __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \ + GTEST_STRINGIFY_(TestName)); \ + } \ + template \ + void GTEST_SUITE_NAMESPACE_( \ SuiteName)::TestName::TestBody() // Note: this won't work correctly if the trailing arguments are macros. @@ -290,8 +292,8 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \ } \ - static const char* const GTEST_REGISTERED_TEST_NAMES_( \ - SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static const char* const \ + GTEST_REGISTERED_TEST_NAMES_(SuiteName) = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__) @@ -303,22 +305,24 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); REGISTER_TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ - static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ - "test-suit-prefix must not be empty"); \ - static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTestSuite< \ - SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ - ::testing::internal::GenerateTypeList::type>:: \ - Register(GTEST_STRINGIFY_(Prefix), \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ - GTEST_STRINGIFY_(SuiteName), \ - GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ - ::testing::internal::GenerateNames< \ - ::testing::internal::NameGeneratorSelector< \ - __VA_ARGS__>::type, \ - ::testing::internal::GenerateTypeList::type>()) +#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ + static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ + "test-suit-prefix must not be empty"); \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool \ + gtest_##Prefix##_##SuiteName = \ + ::testing::internal::TypeParameterizedTestSuite< \ + SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ + ::testing::internal::GenerateTypeList::type>:: \ + Register( \ + GTEST_STRINGIFY_(Prefix), \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ + GTEST_STRINGIFY_(SuiteName), \ + GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ + ::testing::internal::GenerateNames< \ + ::testing::internal::NameGeneratorSelector< \ + __VA_ARGS__>::type, \ + ::testing::internal::GenerateTypeList::type>()) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index de7d528fc687..c89966952033 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -51,7 +51,6 @@ #include #include -#include #include #include #include @@ -61,16 +60,16 @@ #include #include -#include "gtest/gtest-assertion-result.h" -#include "gtest/gtest-death-test.h" -#include "gtest/gtest-matchers.h" -#include "gtest/gtest-message.h" -#include "gtest/gtest-param-test.h" -#include "gtest/gtest-printers.h" -#include "gtest/gtest-test-part.h" -#include "gtest/gtest-typed-test.h" -#include "gtest/gtest_pred_impl.h" -#include "gtest/gtest_prod.h" +#include "gtest/gtest-assertion-result.h" // IWYU pragma: export +#include "gtest/gtest-death-test.h" // IWYU pragma: export +#include "gtest/gtest-matchers.h" // IWYU pragma: export +#include "gtest/gtest-message.h" // IWYU pragma: export +#include "gtest/gtest-param-test.h" // IWYU pragma: export +#include "gtest/gtest-printers.h" // IWYU pragma: export +#include "gtest/gtest-test-part.h" // IWYU pragma: export +#include "gtest/gtest-typed-test.h" // IWYU pragma: export +#include "gtest/gtest_pred_impl.h" // IWYU pragma: export +#include "gtest/gtest_prod.h" // IWYU pragma: export #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" @@ -608,7 +607,7 @@ class GTEST_API_ TestInfo { friend class internal::UnitTestImpl; friend class internal::StreamingListenerTest; friend TestInfo* internal::MakeAndRegisterTestInfo( - const char* test_suite_name, const char* name, const char* type_param, + std::string test_suite_name, const char* name, const char* type_param, const char* value_param, internal::CodeLocation code_location, internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc, @@ -616,7 +615,7 @@ class GTEST_API_ TestInfo { // Constructs a TestInfo object. The newly constructed instance assumes // ownership of the factory object. - TestInfo(const std::string& test_suite_name, const std::string& name, + TestInfo(std::string test_suite_name, std::string name, const char* a_type_param, // NULL if not a type-parameterized test const char* a_value_param, // NULL if not a value-parameterized test internal::CodeLocation a_code_location, @@ -684,7 +683,7 @@ class GTEST_API_ TestSuite { // this is not a type-parameterized test. // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite - TestSuite(const char* name, const char* a_type_param, + TestSuite(const std::string& name, const char* a_type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc); @@ -1263,6 +1262,20 @@ class GTEST_API_ UnitTest { // total_test_suite_count() - 1. If i is not in that range, returns NULL. TestSuite* GetMutableTestSuite(int i); + // Invokes OsStackTrackGetterInterface::UponLeavingGTest. UponLeavingGTest() + // should be called immediately before Google Test calls user code. It saves + // some information about the current stack that CurrentStackTrace() will use + // to find and hide Google Test stack frames. + void UponLeavingGTest(); + + // Sets the TestSuite object for the test that's currently running. + void set_current_test_suite(TestSuite* a_current_test_suite) + GTEST_LOCK_EXCLUDED_(mutex_); + + // Sets the TestInfo object for the test that's currently running. + void set_current_test_info(TestInfo* a_current_test_info) + GTEST_LOCK_EXCLUDED_(mutex_); + // Accessors for the implementation object. internal::UnitTestImpl* impl() { return impl_; } const internal::UnitTestImpl* impl() const { return impl_; } @@ -1271,6 +1284,8 @@ class GTEST_API_ UnitTest { // members of UnitTest. friend class ScopedTrace; friend class Test; + friend class TestInfo; + friend class TestSuite; friend class internal::AssertHelper; friend class internal::StreamingListenerTest; friend class internal::UnitTestRecordPropertyTestHelper; @@ -1574,12 +1589,12 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, } ::std::stringstream lhs_ss; - lhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << lhs_value; + lhs_ss.precision(std::numeric_limits::digits10 + 2); + lhs_ss << lhs_value; ::std::stringstream rhs_ss; - rhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << rhs_value; + rhs_ss.precision(std::numeric_limits::digits10 + 2); + rhs_ss << rhs_value; return EqFailure(lhs_expression, rhs_expression, StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss), @@ -1752,6 +1767,7 @@ class TestWithParam : public Test, public WithParamInterface {}; // generic name and clashes with some other libraries. #if !(defined(GTEST_DONT_DEFINE_FAIL) && GTEST_DONT_DEFINE_FAIL) #define FAIL() GTEST_FAIL() +#define FAIL_AT(file, line) GTEST_FAIL_AT(file, line) #endif // Generates a success with a generic message. @@ -2308,7 +2324,8 @@ TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, // tests are successful, or 1 otherwise. // // RUN_ALL_TESTS() should be invoked after the command line has been -// parsed by InitGoogleTest(). +// parsed by InitGoogleTest(). RUN_ALL_TESTS will tear down and delete any +// installed environments and should only be called once per binary. // // This function was formerly a macro; thus, it is in the global // namespace and has an all-caps name. diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 8e9c988b98ce..b363259ec602 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -46,17 +46,38 @@ #include "gtest/gtest-matchers.h" #include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-port.h" GTEST_DECLARE_string_(internal_run_death_test); namespace testing { namespace internal { -// Names of the flags (needed for parsing Google Test flags). -const char kDeathTestStyleFlag[] = "death_test_style"; -const char kDeathTestUseFork[] = "death_test_use_fork"; +// Name of the flag (needed for parsing Google Test flag). const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; +// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads +// and interpreted as a regex (rather than an Eq matcher) for legacy +// compatibility. +inline Matcher MakeDeathTestMatcher( + ::testing::internal::RE regex) { + return ContainsRegex(regex.pattern()); +} +inline Matcher MakeDeathTestMatcher(const char* regex) { + return ContainsRegex(regex); +} +inline Matcher MakeDeathTestMatcher( + const ::std::string& regex) { + return ContainsRegex(regex); +} + +// If a Matcher is passed to EXPECT_DEATH (etc.), it's +// used directly. +inline Matcher MakeDeathTestMatcher( + Matcher matcher) { + return matcher; +} + #ifdef GTEST_HAS_DEATH_TEST GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ @@ -73,7 +94,7 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ // // exit status: The integer exit information in the format specified // by wait(2) -// exit code: The integer code passed to exit(3), _exit(2), or +// exit code: The integer code passed to exit(3), _Exit(2), or // returned from main() class GTEST_API_ DeathTest { public: @@ -170,28 +191,6 @@ class DefaultDeathTestFactory : public DeathTestFactory { // by a signal, or exited normally with a nonzero exit code. GTEST_API_ bool ExitedUnsuccessfully(int exit_status); -// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads -// and interpreted as a regex (rather than an Eq matcher) for legacy -// compatibility. -inline Matcher MakeDeathTestMatcher( - ::testing::internal::RE regex) { - return ContainsRegex(regex.pattern()); -} -inline Matcher MakeDeathTestMatcher(const char* regex) { - return ContainsRegex(regex); -} -inline Matcher MakeDeathTestMatcher( - const ::std::string& regex) { - return ContainsRegex(regex); -} - -// If a Matcher is passed to EXPECT_DEATH (etc.), it's -// used directly. -inline Matcher MakeDeathTestMatcher( - Matcher matcher) { - return matcher; -} - // Traps C++ exceptions escaping statement and reports them as test // failures. Note that trapping SEH exceptions is not implemented here. #if GTEST_HAS_EXCEPTIONS diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h index 5189c81dabfa..6dc47be54ad3 100644 --- a/googletest/include/gtest/internal/gtest-filepath.h +++ b/googletest/include/gtest/internal/gtest-filepath.h @@ -43,6 +43,7 @@ #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #include +#include #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-string.h" @@ -70,8 +71,9 @@ class GTEST_API_ FilePath { public: FilePath() : pathname_("") {} FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {} + FilePath(FilePath&& rhs) noexcept : pathname_(std::move(rhs.pathname_)) {} - explicit FilePath(const std::string& pathname) : pathname_(pathname) { + explicit FilePath(std::string pathname) : pathname_(std::move(pathname)) { Normalize(); } @@ -79,6 +81,10 @@ class GTEST_API_ FilePath { Set(rhs); return *this; } + FilePath& operator=(FilePath&& rhs) noexcept { + pathname_ = std::move(rhs.pathname_); + return *this; + } void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; } diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index a04a9201c616..7e55dc605cb9 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -58,7 +58,6 @@ #include #include -#include #include #include #include @@ -79,7 +78,7 @@ // // will result in the token foo__LINE__, instead of foo followed by // the current line number. For more details, see -// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 +// https://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar @@ -170,7 +169,7 @@ namespace edit_distance { // All edits cost the same, with replace having lower priority than // add/remove. // Simple implementation of the Wagner-Fischer algorithm. -// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm +// See https://en.wikipedia.org/wiki/Wagner-Fischer_algorithm enum EditType { kMatch, kAdd, kRemove, kReplace }; GTEST_API_ std::vector CalculateOptimalEdits( const std::vector& left, const std::vector& right); @@ -237,7 +236,7 @@ GTEST_API_ std::string GetBoolAssertionFailureMessage( // For double, there are 11 exponent bits and 52 fraction bits. // // More details can be found at -// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. +// https://en.wikipedia.org/wiki/IEEE_floating-point_standard. // // Template parameter: // @@ -282,7 +281,7 @@ class FloatingPoint { // bits. Therefore, 4 should be enough for ordinary use. // // See the following article for more details on ULP: - // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + // https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ static const uint32_t kMaxUlps = 4; // Constructs a FloatingPoint from a raw floating-point number. @@ -363,7 +362,7 @@ class FloatingPoint { // N - 1 (the biggest number representable using // sign-and-magnitude) is represented by 2N - 1. // - // Read http://en.wikipedia.org/wiki/Signed_number_representations + // Read https://en.wikipedia.org/wiki/Signed_number_representations // for more details on signed number representations. static Bits SignAndMagnitudeToBiased(const Bits& sam) { if (kSignBitMask & sam) { @@ -475,8 +474,8 @@ using SetUpTestSuiteFunc = void (*)(); using TearDownTestSuiteFunc = void (*)(); struct CodeLocation { - CodeLocation(const std::string& a_file, int a_line) - : file(a_file), line(a_line) {} + CodeLocation(std::string a_file, int a_line) + : file(std::move(a_file)), line(a_line) {} std::string file; int line; @@ -556,7 +555,7 @@ struct SuiteApiResolver : T { // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // value_param: text representation of the test's value parameter, -// or NULL if this is not a type-parameterized test. +// or NULL if this is not a value-parameterized test. // code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test suite @@ -565,7 +564,7 @@ struct SuiteApiResolver : T { // The newly created TestInfo instance will assume // ownership of the factory object. GTEST_API_ TestInfo* MakeAndRegisterTestInfo( - const char* test_suite_name, const char* name, const char* type_param, + std::string test_suite_name, const char* name, const char* type_param, const char* value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory); @@ -596,8 +595,7 @@ class GTEST_API_ TypedTestSuitePState { fflush(stderr); posix::Abort(); } - registered_tests_.insert( - ::std::make_pair(test_name, CodeLocation(file, line))); + registered_tests_.emplace(test_name, CodeLocation(file, line)); return true; } @@ -701,7 +699,7 @@ class TypeParameterizedTest { // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite, // Types). Valid values for 'index' are [0, N - 1] where N is the // length of Types. - static bool Register(const char* prefix, const CodeLocation& code_location, + static bool Register(const char* prefix, CodeLocation code_location, const char* case_name, const char* test_names, int index, const std::vector& type_names = GenerateNames()) { @@ -713,8 +711,7 @@ class TypeParameterizedTest { // list. MakeAndRegisterTestInfo( (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + - "/" + type_names[static_cast(index)]) - .c_str(), + "/" + type_names[static_cast(index)]), StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), GetTypeName().c_str(), nullptr, // No value parameter. @@ -726,13 +723,9 @@ class TypeParameterizedTest { new TestFactoryImpl); // Next, recurses (at compile time) with the tail of the type list. - return TypeParameterizedTest::Register(prefix, - code_location, - case_name, - test_names, - index + 1, - type_names); + return TypeParameterizedTest:: + Register(prefix, std::move(code_location), case_name, test_names, + index + 1, type_names); } }; @@ -740,7 +733,7 @@ class TypeParameterizedTest { template class TypeParameterizedTest { public: - static bool Register(const char* /*prefix*/, const CodeLocation&, + static bool Register(const char* /*prefix*/, CodeLocation, const char* /*case_name*/, const char* /*test_names*/, int /*index*/, const std::vector& = @@ -787,7 +780,8 @@ class TypeParameterizedTestSuite { // Next, recurses (at compile time) with the tail of the test list. return TypeParameterizedTestSuite::Register(prefix, code_location, + Types>::Register(prefix, + std::move(code_location), state, case_name, SkipComma(test_names), type_names); @@ -1143,40 +1137,6 @@ class NativeArray { void (NativeArray::*clone_)(const Element*, size_t); }; -// Backport of std::index_sequence. -template -struct IndexSequence { - using type = IndexSequence; -}; - -// Double the IndexSequence, and one if plus_one is true. -template -struct DoubleSequence; -template -struct DoubleSequence, sizeofT> { - using type = IndexSequence; -}; -template -struct DoubleSequence, sizeofT> { - using type = IndexSequence; -}; - -// Backport of std::make_index_sequence. -// It uses O(ln(N)) instantiation depth. -template -struct MakeIndexSequenceImpl - : DoubleSequence::type, - N / 2>::type {}; - -template <> -struct MakeIndexSequenceImpl<0> : IndexSequence<> {}; - -template -using MakeIndexSequence = typename MakeIndexSequenceImpl::type; - -template -using IndexSequenceFor = typename MakeIndexSequence::type; - template struct Ignore { Ignore(...); // NOLINT @@ -1185,7 +1145,7 @@ struct Ignore { template struct ElemFromListImpl; template -struct ElemFromListImpl> { +struct ElemFromListImpl> { // We make Ignore a template to solve a problem with MSVC. // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but // MSVC doesn't understand how to deal with that pack expansion. @@ -1196,9 +1156,8 @@ struct ElemFromListImpl> { template struct ElemFromList { - using type = - decltype(ElemFromListImpl::type>::Apply( - static_cast(nullptr)...)); + using type = decltype(ElemFromListImpl>::Apply( + static_cast(nullptr)...)); }; struct FlatTupleConstructTag {}; @@ -1223,9 +1182,9 @@ template struct FlatTupleBase; template -struct FlatTupleBase, IndexSequence> +struct FlatTupleBase, std::index_sequence> : FlatTupleElemBase, Idx>... { - using Indices = IndexSequence; + using Indices = std::index_sequence; FlatTupleBase() = default; template explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args) @@ -1260,14 +1219,15 @@ struct FlatTupleBase, IndexSequence> // implementations. // FlatTuple and ElemFromList are not recursive and have a fixed depth // regardless of T... -// MakeIndexSequence, on the other hand, it is recursive but with an +// std::make_index_sequence, on the other hand, it is recursive but with an // instantiation depth of O(ln(N)). template class FlatTuple : private FlatTupleBase, - typename MakeIndexSequence::type> { - using Indices = typename FlatTupleBase< - FlatTuple, typename MakeIndexSequence::type>::Indices; + std::make_index_sequence> { + using Indices = + typename FlatTupleBase, + std::make_index_sequence>::Indices; public: FlatTuple() = default; @@ -1541,7 +1501,8 @@ class NeverThrown { \ private: \ void TestBody() override; \ - static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static ::testing::TestInfo* const \ + test_info_; \ }; \ \ ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index 6a81c37fa6af..cc7ea531738c 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -47,6 +47,7 @@ #include #include #include +#include #include #include @@ -85,7 +86,7 @@ namespace internal { // TEST_P macro is used to define two tests with the same name // but in different namespaces. GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name, - CodeLocation code_location); + const CodeLocation& code_location); template class ParamGeneratorInterface; @@ -379,9 +380,7 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { // integer test parameter index. template std::string DefaultParamName(const TestParamInfo& info) { - Message name_stream; - name_stream << info.index; - return name_stream.GetString(); + return std::to_string(info.index); } template @@ -513,9 +512,10 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { typedef ParamGenerator(GeneratorCreationFunc)(); using ParamNameGeneratorFunc = std::string(const TestParamInfo&); - explicit ParameterizedTestSuiteInfo(const char* name, + explicit ParameterizedTestSuiteInfo(std::string name, CodeLocation code_location) - : test_suite_name_(name), code_location_(code_location) {} + : test_suite_name_(std::move(name)), + code_location_(std::move(code_location)) {} // Test suite base name for display purposes. const std::string& GetTestSuiteName() const override { @@ -529,20 +529,21 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { // prefix). test_base_name is the name of an individual test without // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is // test suite base name and DoBar is test base name. - void AddTestPattern(const char* test_suite_name, const char* test_base_name, + void AddTestPattern(const char*, + const char* test_base_name, TestMetaFactoryBase* meta_factory, CodeLocation code_location) { - tests_.push_back(std::shared_ptr(new TestInfo( - test_suite_name, test_base_name, meta_factory, code_location))); + tests_.emplace_back( + new TestInfo(test_base_name, meta_factory, std::move(code_location))); } // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information // about a generator. - int AddTestSuiteInstantiation(const std::string& instantiation_name, + int AddTestSuiteInstantiation(std::string instantiation_name, GeneratorCreationFunc* func, ParamNameGeneratorFunc* name_func, const char* file, int line) { - instantiations_.push_back( - InstantiationInfo(instantiation_name, func, name_func, file, line)); + instantiations_.emplace_back(std::move(instantiation_name), func, name_func, + file, line); return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test suite @@ -553,60 +554,61 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { void RegisterTests() override { bool generated_instantiations = false; - for (typename TestInfoContainer::iterator test_it = tests_.begin(); - test_it != tests_.end(); ++test_it) { - std::shared_ptr test_info = *test_it; - for (typename InstantiationContainer::iterator gen_it = - instantiations_.begin(); - gen_it != instantiations_.end(); ++gen_it) { - const std::string& instantiation_name = gen_it->name; - ParamGenerator generator((*gen_it->generator)()); - ParamNameGeneratorFunc* name_func = gen_it->name_func; - const char* file = gen_it->file; - int line = gen_it->line; + std::string test_suite_name; + std::string test_name; + for (const std::shared_ptr& test_info : tests_) { + for (const InstantiationInfo& instantiation : instantiations_) { + const std::string& instantiation_name = instantiation.name; + ParamGenerator generator((*instantiation.generator)()); + ParamNameGeneratorFunc* name_func = instantiation.name_func; + const char* file = instantiation.file; + int line = instantiation.line; - std::string test_suite_name; if (!instantiation_name.empty()) test_suite_name = instantiation_name + "/"; - test_suite_name += test_info->test_suite_base_name; + else + test_suite_name.clear(); + test_suite_name += test_suite_name_; size_t i = 0; std::set test_param_names; - for (typename ParamGenerator::iterator param_it = - generator.begin(); - param_it != generator.end(); ++param_it, ++i) { + for (const auto& param : generator) { generated_instantiations = true; - Message test_name_stream; + test_name.clear(); std::string param_name = - name_func(TestParamInfo(*param_it, i)); + name_func(TestParamInfo(param, i)); GTEST_CHECK_(IsValidParamName(param_name)) << "Parameterized test name '" << param_name - << "' is invalid, in " << file << " line " << line << std::endl; + << "' is invalid (contains spaces, dashes, or any " + "non-alphanumeric characters other than underscores), in " + << file << " line " << line << "" << std::endl; GTEST_CHECK_(test_param_names.count(param_name) == 0) << "Duplicate parameterized test name '" << param_name << "', in " << file << " line " << line << std::endl; - test_param_names.insert(param_name); - if (!test_info->test_base_name.empty()) { - test_name_stream << test_info->test_base_name << "/"; + test_name.append(test_info->test_base_name).append("/"); } - test_name_stream << param_name; + test_name += param_name; + + test_param_names.insert(std::move(param_name)); + MakeAndRegisterTestInfo( - test_suite_name.c_str(), test_name_stream.GetString().c_str(), + test_suite_name, test_name.c_str(), nullptr, // No type parameter. - PrintToString(*param_it).c_str(), test_info->code_location, + PrintToString(param).c_str(), test_info->code_location, GetTestSuiteTypeId(), SuiteApiResolver::GetSetUpCaseOrSuite(file, line), SuiteApiResolver::GetTearDownCaseOrSuite(file, line), - test_info->test_meta_factory->CreateTestFactory(*param_it)); - } // for param_it - } // for gen_it - } // for test_it + test_info->test_meta_factory->CreateTestFactory(param)); + ++i; + } // for param + } // for instantiation + } // for test_info if (!generated_instantiations) { // There are no generaotrs, or they all generate nothing ... @@ -619,15 +621,13 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { - TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name, + TestInfo(const char* a_test_base_name, TestMetaFactoryBase* a_test_meta_factory, CodeLocation a_code_location) - : test_suite_base_name(a_test_suite_base_name), - test_base_name(a_test_base_name), + : test_base_name(a_test_base_name), test_meta_factory(a_test_meta_factory), - code_location(a_code_location) {} + code_location(std::move(a_code_location)) {} - const std::string test_suite_base_name; const std::string test_base_name; const std::unique_ptr> test_meta_factory; const CodeLocation code_location; @@ -637,11 +637,10 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { // struct InstantiationInfo { - InstantiationInfo(const std::string& name_in, - GeneratorCreationFunc* generator_in, + InstantiationInfo(std::string name_in, GeneratorCreationFunc* generator_in, ParamNameGeneratorFunc* name_func_in, const char* file_in, int line_in) - : name(name_in), + : name(std::move(name_in)), generator(generator_in), name_func(name_func_in), file(file_in), @@ -702,29 +701,32 @@ class ParameterizedTestSuiteRegistry { // tests and instantiations of a particular test suite. template ParameterizedTestSuiteInfo* GetTestSuitePatternHolder( - const char* test_suite_name, CodeLocation code_location) { + std::string test_suite_name, CodeLocation code_location) { ParameterizedTestSuiteInfo* typed_test_info = nullptr; - for (auto& test_suite_info : test_suite_infos_) { - if (test_suite_info->GetTestSuiteName() == test_suite_name) { - if (test_suite_info->GetTestSuiteTypeId() != GetTypeId()) { - // Complain about incorrect usage of Google Test facilities - // and terminate the program since we cannot guaranty correct - // test suite setup and tear-down in this case. - ReportInvalidTestSuiteType(test_suite_name, code_location); - posix::Abort(); - } else { - // At this point we are sure that the object we found is of the same - // type we are looking for, so we downcast it to that type - // without further checks. - typed_test_info = CheckedDowncastToActualType< - ParameterizedTestSuiteInfo>(test_suite_info); - } - break; + + auto item_it = suite_name_to_info_index_.find(test_suite_name); + if (item_it != suite_name_to_info_index_.end()) { + auto* test_suite_info = test_suite_infos_[item_it->second]; + if (test_suite_info->GetTestSuiteTypeId() != GetTypeId()) { + // Complain about incorrect usage of Google Test facilities + // and terminate the program since we cannot guaranty correct + // test suite setup and tear-down in this case. + ReportInvalidTestSuiteType(test_suite_name.c_str(), code_location); + posix::Abort(); + } else { + // At this point we are sure that the object we found is of the same + // type we are looking for, so we downcast it to that type + // without further checks. + typed_test_info = + CheckedDowncastToActualType>( + test_suite_info); } } if (typed_test_info == nullptr) { typed_test_info = new ParameterizedTestSuiteInfo( - test_suite_name, code_location); + test_suite_name, std::move(code_location)); + suite_name_to_info_index_.emplace(std::move(test_suite_name), + test_suite_infos_.size()); test_suite_infos_.push_back(typed_test_info); } return typed_test_info; @@ -738,8 +740,9 @@ class ParameterizedTestSuiteRegistry { #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ template ParameterizedTestCaseInfo* GetTestCasePatternHolder( - const char* test_case_name, CodeLocation code_location) { - return GetTestSuitePatternHolder(test_case_name, code_location); + std::string test_case_name, CodeLocation code_location) { + return GetTestSuitePatternHolder(std::move(test_case_name), + std::move(code_location)); } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ @@ -748,6 +751,7 @@ class ParameterizedTestSuiteRegistry { using TestSuiteInfoContainer = ::std::vector; TestSuiteInfoContainer test_suite_infos_; + ::std::unordered_map suite_name_to_info_index_; ParameterizedTestSuiteRegistry(const ParameterizedTestSuiteRegistry&) = delete; @@ -774,7 +778,7 @@ class TypeParameterizedTestSuiteRegistry { private: struct TypeParameterizedTestSuiteInfo { explicit TypeParameterizedTestSuiteInfo(CodeLocation c) - : code_location(c), instantiated(false) {} + : code_location(std::move(c)), instantiated(false) {} CodeLocation code_location; bool instantiated; @@ -803,12 +807,12 @@ class ValueArray { template operator ParamGenerator() const { // NOLINT - return ValuesIn(MakeVector(MakeIndexSequence())); + return ValuesIn(MakeVector(std::make_index_sequence())); } private: template - std::vector MakeVector(IndexSequence) const { + std::vector MakeVector(std::index_sequence) const { return std::vector{static_cast(v_.template Get())...}; } @@ -838,7 +842,7 @@ class CartesianProductGenerator template class IteratorImpl; template - class IteratorImpl> + class IteratorImpl> : public ParamIteratorInterface { public: IteratorImpl(const ParamGeneratorInterface* base, @@ -929,7 +933,7 @@ class CartesianProductGenerator std::shared_ptr current_value_; }; - using Iterator = IteratorImpl::type>; + using Iterator = IteratorImpl>; std::tuple...> generators_; }; diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h index 3162f2b1cbd2..7ec968f312e4 100644 --- a/googletest/include/gtest/internal/gtest-port-arch.h +++ b/googletest/include/gtest/internal/gtest-port-arch.h @@ -56,6 +56,8 @@ #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE) #define GTEST_OS_WINDOWS_PHONE 1 #define GTEST_OS_WINDOWS_TV_TITLE 1 +#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_GAMES) +#define GTEST_OS_WINDOWS_GAMES 1 #else // WINAPI_FAMILY defined but no known partition matched. // Default to desktop. diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index b887e24edcd0..8d27c2c4f72f 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -194,8 +194,6 @@ // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. -// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a -// variable don't have to be used. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // suppressed (constant conditional). @@ -208,6 +206,8 @@ // or // UniversalPrinter // specializations. Always defined to 0 or 1. +// GTEST_INTERNAL_HAS_STD_SPAN - for enabling UniversalPrinter +// specializations. Always defined to 0 or 1 // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher or // Matcher // specializations. Always defined to 0 or 1. @@ -279,6 +279,22 @@ #error C++ versions less than C++14 are not supported. #endif +// MSVC >= 19.11 (VS 2017 Update 3) supports __has_include. +#ifdef __has_include +#define GTEST_INTERNAL_HAS_INCLUDE __has_include +#else +#define GTEST_INTERNAL_HAS_INCLUDE(...) 0 +#endif + +// Detect C++ feature test macros as gracefully as possible. +// MSVC >= 19.15, Clang >= 3.4.1, and GCC >= 4.1.2 support feature test macros. +#if GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L && \ + (!defined(__has_include) || GTEST_INTERNAL_HAS_INCLUDE()) +#include // C++20 and later +#elif (!defined(__has_include) || GTEST_INTERNAL_HAS_INCLUDE()) +#include // Pre-C++20 +#endif + #include // for isspace, etc #include // for ptrdiff_t #include @@ -320,7 +336,8 @@ #define GTEST_HAS_NOTIFICATION_ 0 #endif -#ifdef GTEST_HAS_ABSL +#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) +#define GTEST_INTERNAL_HAS_ABSL_FLAGS // Used only in this file. #include "absl/flags/declare.h" #include "absl/flags/flag.h" #include "absl/flags/reflection.h" @@ -590,7 +607,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; defined(GTEST_OS_NETBSD) || defined(GTEST_OS_FUCHSIA) || \ defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_GNU_KFREEBSD) || \ defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_HAIKU) || \ - defined(GTEST_OS_GNU_HURD)) + defined(GTEST_OS_GNU_HURD) || defined(GTEST_OS_SOLARIS) || \ + defined(GTEST_OS_AIX) || defined(GTEST_OS_ZOS)) #define GTEST_HAS_PTHREAD 1 #else #define GTEST_HAS_PTHREAD 0 @@ -609,7 +627,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Determines whether clone(2) is supported. // Usually it will only be available on Linux, excluding // Linux on the Itanium architecture. -// Also see http://linux.die.net/man/2/clone. +// Also see https://linux.die.net/man/2/clone. #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. @@ -640,9 +658,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // platforms except known mobile / embedded ones. Also, if the port doesn't have // a file system, stream redirection is not supported. #if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \ - defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \ - defined(GTEST_OS_XTENSA) || defined(GTEST_OS_QURT) || \ - !GTEST_HAS_FILE_SYSTEM + defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_WINDOWS_GAMES) || \ + defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \ + defined(GTEST_OS_QURT) || !GTEST_HAS_FILE_SYSTEM #define GTEST_HAS_STREAM_REDIRECTION 0 #else #define GTEST_HAS_STREAM_REDIRECTION 1 @@ -652,7 +670,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Determines whether to support death tests. // pops up a dialog window that cannot be suppressed programmatically. #if (defined(GTEST_OS_LINUX) || defined(GTEST_OS_CYGWIN) || \ - defined(GTEST_OS_SOLARIS) || \ + defined(GTEST_OS_SOLARIS) || defined(GTEST_OS_ZOS) || \ (defined(GTEST_OS_MAC) && !defined(GTEST_OS_IOS)) || \ (defined(GTEST_OS_WINDOWS_DESKTOP) && _MSC_VER) || \ defined(GTEST_OS_WINDOWS_MINGW) || defined(GTEST_OS_AIX) || \ @@ -730,6 +748,20 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #define GTEST_HAVE_ATTRIBUTE_(x) 0 #endif +// GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE +// +// A function-like feature checking macro that accepts C++11 style attributes. +// It's a wrapper around `__has_cpp_attribute`, defined by ISO C++ SD-6 +// (https://en.cppreference.com/w/cpp/experimental/feature_test). If we don't +// find `__has_cpp_attribute`, will evaluate to 0. +#if defined(__has_cpp_attribute) +// NOTE: requiring __cplusplus above should not be necessary, but +// works around https://bugs.llvm.org/show_bug.cgi?id=23435. +#define GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +#define GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE(x) 0 +#endif + // GTEST_HAVE_FEATURE_ // // A function-like feature checking macro that is a wrapper around @@ -741,14 +773,22 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif // Use this annotation after a variable or parameter declaration to tell the -// compiler the variable/parameter does not have to be used. +// compiler the variable/parameter may be used. // Example: // -// GTEST_ATTRIBUTE_UNUSED_ int foo = bar(); -#if GTEST_HAVE_ATTRIBUTE_(unused) -#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) +// GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED int foo = bar(); +// +// This can be removed once we only support only C++17 or newer and +// [[maybe_unused]] is available on all supported platforms. +#if GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE(maybe_unused) +#define GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED [[maybe_unused]] +#elif GTEST_HAVE_ATTRIBUTE_(unused) +// This is inferior to [[maybe_unused]] as it can produce a +// -Wused-but-marked-unused warning on optionally used symbols, but it is all we +// have. +#define GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED __attribute__((__unused__)) #else -#define GTEST_ATTRIBUTE_UNUSED_ +#define GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED #endif // Use this annotation before a function that takes a printf format string. @@ -827,9 +867,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #ifndef GTEST_API_ #ifdef _MSC_VER -#if GTEST_LINKED_AS_SHARED_LIBRARY +#if defined(GTEST_LINKED_AS_SHARED_LIBRARY) && GTEST_LINKED_AS_SHARED_LIBRARY #define GTEST_API_ __declspec(dllimport) -#elif GTEST_CREATE_SHARED_LIBRARY +#elif defined(GTEST_CREATE_SHARED_LIBRARY) && GTEST_CREATE_SHARED_LIBRARY #define GTEST_API_ __declspec(dllexport) #endif #elif GTEST_HAVE_ATTRIBUTE_(visibility) @@ -1987,7 +2027,9 @@ inline std::string StripTrailingSpaces(std::string str) { namespace posix { // File system porting. -#if GTEST_HAS_FILE_SYSTEM +// Note: Not every I/O-related function is related to file systems, so don't +// just disable all of them here. For example, fileno() and isatty(), etc. must +// always be available in order to detect if a pipe points to a terminal. #ifdef GTEST_OS_WINDOWS typedef struct _stat StatStruct; @@ -1998,27 +2040,32 @@ inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } // time and thus not defined there. #else inline int FileNo(FILE* file) { return _fileno(file); } +#if GTEST_HAS_FILE_SYSTEM inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } +#endif #endif // GTEST_OS_WINDOWS_MOBILE #elif defined(GTEST_OS_ESP8266) typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } +#if GTEST_HAS_FILE_SYSTEM inline int Stat(const char* path, StatStruct* buf) { // stat function not implemented on ESP8266 return 0; } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } +#endif #else typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } +#if GTEST_HAS_FILE_SYSTEM inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } #ifdef GTEST_OS_QURT // QuRT doesn't support any directory functions, including rmdir @@ -2027,9 +2074,9 @@ inline int RmDir(const char*) { return 0; } inline int RmDir(const char* dir) { return rmdir(dir); } #endif inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } +#endif #endif // GTEST_OS_WINDOWS -#endif // GTEST_HAS_FILE_SYSTEM // Other functions with a different name on Windows. @@ -2082,8 +2129,9 @@ GTEST_DISABLE_MSC_DEPRECATED_PUSH_() // defined there. #if GTEST_HAS_FILE_SYSTEM #if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \ - !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_ESP8266) && \ - !defined(GTEST_OS_XTENSA) && !defined(GTEST_OS_QURT) + !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_GAMES) && \ + !defined(GTEST_OS_ESP8266) && !defined(GTEST_OS_XTENSA) && \ + !defined(GTEST_OS_QURT) inline int ChDir(const char* dir) { return chdir(dir); } #endif inline FILE* FOpen(const char* path, const char* mode) { @@ -2227,7 +2275,7 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. #endif // !defined(GTEST_FLAG) // Pick a command line flags implementation. -#ifdef GTEST_HAS_ABSL +#ifdef GTEST_INTERNAL_HAS_ABSL_FLAGS // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ @@ -2252,7 +2300,8 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. (void)(::absl::SetFlag(>EST_FLAG(name), value)) #define GTEST_USE_OWN_FLAGFILE_FLAG_ 0 -#else // GTEST_HAS_ABSL +#undef GTEST_INTERNAL_HAS_ABSL_FLAGS +#else // ndef GTEST_INTERNAL_HAS_ABSL_FLAGS // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ @@ -2294,7 +2343,7 @@ using TimeInMillis = int64_t; // Represents time in milliseconds. #define GTEST_FLAG_SET(name, value) (void)(::testing::GTEST_FLAG(name) = value) #define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 -#endif // GTEST_HAS_ABSL +#endif // GTEST_INTERNAL_HAS_ABSL_FLAGS // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) @@ -2349,9 +2398,9 @@ using Any = ::absl::any; } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L && \ - (!defined(_MSC_VER) || GTEST_HAS_RTTI) +#if defined(__cpp_lib_any) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L && \ + (!defined(_MSC_VER) || GTEST_HAS_RTTI)) // Otherwise for C++17 and higher use std::any for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_ANY 1 @@ -2363,8 +2412,7 @@ using Any = ::std::any; } // namespace testing // The case where absl is configured NOT to alias std::any is not // supported. -#endif // __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L -#endif // __has_include +#endif // __cpp_lib_any #endif // GTEST_HAS_ABSL #ifndef GTEST_INTERNAL_HAS_ANY @@ -2384,8 +2432,8 @@ inline ::absl::nullopt_t Nullopt() { return ::absl::nullopt; } } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L +#if defined(__cpp_lib_optional) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L) // Otherwise for C++17 and higher use std::optional for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_OPTIONAL 1 @@ -2399,14 +2447,22 @@ inline ::std::nullopt_t Nullopt() { return ::std::nullopt; } } // namespace testing // The case where absl is configured NOT to alias std::optional is not // supported. -#endif // __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L -#endif // __has_include +#endif // __cpp_lib_optional #endif // GTEST_HAS_ABSL #ifndef GTEST_INTERNAL_HAS_OPTIONAL #define GTEST_INTERNAL_HAS_OPTIONAL 0 #endif +#if defined(__cpp_lib_span) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L) +#define GTEST_INTERNAL_HAS_STD_SPAN 1 +#endif // __cpp_lib_span + +#ifndef GTEST_INTERNAL_HAS_STD_SPAN +#define GTEST_INTERNAL_HAS_STD_SPAN 0 +#endif + #ifdef GTEST_HAS_ABSL // Always use absl::string_view for Matcher<> specializations if googletest // is built with absl support. @@ -2418,8 +2474,9 @@ using StringView = ::absl::string_view; } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L +#if defined(__cpp_lib_string_view) || \ + (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L) // Otherwise for C++17 and higher use std::string_view for Matcher<> // specializations. #define GTEST_INTERNAL_HAS_STRING_VIEW 1 @@ -2431,9 +2488,7 @@ using StringView = ::std::string_view; } // namespace testing // The case where absl is configured NOT to alias std::string_view is not // supported. -#endif // __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= - // 201703L -#endif // __has_include +#endif // __cpp_lib_string_view #endif // GTEST_HAS_ABSL #ifndef GTEST_INTERNAL_HAS_STRING_VIEW @@ -2452,8 +2507,8 @@ using Variant = ::absl::variant; } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L +#if defined(__cpp_lib_variant) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L) // Otherwise for C++17 and higher use std::variant for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_VARIANT 1 @@ -2465,16 +2520,16 @@ using Variant = ::std::variant; } // namespace internal } // namespace testing // The case where absl is configured NOT to alias std::variant is not supported. -#endif // __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L -#endif // __has_include +#endif // __cpp_lib_variant #endif // GTEST_HAS_ABSL #ifndef GTEST_INTERNAL_HAS_VARIANT #define GTEST_INTERNAL_HAS_VARIANT 0 #endif -#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ - GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L +#if (defined(__cpp_constexpr) && !defined(__cpp_inline_variables)) || \ + (defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ + GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L) #define GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL 1 #endif diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index f94cf614ade7..78da05316d6b 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -71,7 +71,7 @@ inline std::string CanonicalizeForStdLibVersioning(std::string s) { // Strip redundant spaces in typename to match MSVC // For example, std::pair -> std::pair static const char to_search[] = ", "; - static const char replace_str[] = ","; + const char replace_char = ','; size_t pos = 0; while (true) { // Get the next occurrence from the current position @@ -80,8 +80,8 @@ inline std::string CanonicalizeForStdLibVersioning(std::string s) { break; } // Replace this occurrence of substring - s.replace(pos, strlen(to_search), replace_str); - pos += strlen(replace_str); + s.replace(pos, strlen(to_search), 1, replace_char); + ++pos; } return s; } diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 0eb6e38b2a96..15472f1a7929 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -32,6 +32,8 @@ #include "gtest/gtest-death-test.h" +#include + #include #include #include @@ -115,7 +117,7 @@ GTEST_DEFINE_string_( GTEST_DEFINE_bool_( death_test_use_fork, testing::internal::BoolFromGTestEnv("death_test_use_fork", false), - "Instructs to use fork()/_exit() instead of clone() in death tests. " + "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 " "those do not support clone(). Valgrind 3.3.1 will just fail if " @@ -299,7 +301,7 @@ enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; fputc(kDeathTestInternalError, parent); fprintf(parent, "%s", message.c_str()); fflush(parent); - _exit(1); + _Exit(1); } else { fprintf(stderr, "%s", message.c_str()); fflush(stderr); @@ -511,7 +513,7 @@ std::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); } // Signals that the death test code which should have exited, didn't. // Should be called only in a death test child process. // Writes a status byte to the child's status file descriptor, then -// calls _exit(1). +// calls _Exit(1). void DeathTestImpl::Abort(AbortReason reason) { // The parent process considers the death test to be a failure if // it finds any data in our pipe. So, here we write a single flag byte @@ -523,13 +525,13 @@ void DeathTestImpl::Abort(AbortReason reason) { GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); // We are leaking the descriptor here because on some platforms (i.e., // when built as Windows DLL), destructors of global objects will still - // run after calling _exit(). On such systems, write_fd_ will be + // run after calling _Exit(). On such systems, write_fd_ will be // indirectly closed from the destructor of UnitTestImpl, causing double // close if it is also closed here. On debug configurations, double close // may assert. As there are no in-process buffers to flush here, we are // relying on the OS to close the descriptor after the process terminates // when the destructors are not run. - _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) + _Exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) } // Returns an indented copy of stderr output for a death test. @@ -628,13 +630,13 @@ bool DeathTestImpl::Passed(bool status_ok) { #ifndef GTEST_OS_WINDOWS // Note: The return value points into args, so the return value's lifetime is // bound to that of args. -static std::unique_ptr CreateArgvFromArgs( - std::vector& args) { - auto result = std::make_unique(args.size() + 1); - for (size_t i = 0; i < args.size(); ++i) { - result[i] = &args[i][0]; +static std::vector CreateArgvFromArgs(std::vector& args) { + std::vector result; + result.reserve(args.size() + 1); + for (auto& arg : args) { + result.push_back(&arg[0]); } - result[args.size()] = nullptr; // extra null terminator + result.push_back(nullptr); // Extra null terminator. return result; } #endif @@ -783,7 +785,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { 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. + // See https://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. "|" + StreamableToString(reinterpret_cast(write_handle)) + "|" + StreamableToString(reinterpret_cast(event_handle_.Get())); @@ -1034,8 +1036,8 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { // "Fuchsia Test Component" which contains a "Fuchsia Component Manifest") // Launching processes is a privileged operation in Fuchsia, and the // declaration indicates that the ability is required for the component. - std::unique_ptr argv = CreateArgvFromArgs(args); - status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, argv[0], argv.get(), + std::vector argv = CreateArgvFromArgs(args); + status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, argv[0], argv.data(), nullptr, 2, spawn_actions, child_process_.reset_and_get_address(), nullptr); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); @@ -1333,7 +1335,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { #endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { - _exit(ExecDeathTestChildMain(&args)); + _Exit(ExecDeathTestChildMain(&args)); } #endif // GTEST_OS_QNX #ifdef GTEST_OS_LINUX @@ -1386,8 +1388,8 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { // is necessary. FlushInfoLog(); - std::unique_ptr argv = CreateArgvFromArgs(args); - const pid_t child_pid = ExecDeathTestSpawnChild(argv.get(), pipe_fd[0]); + std::vector argv = CreateArgvFromArgs(args); + const pid_t child_pid = ExecDeathTestSpawnChild(argv.data(), pipe_fd[0]); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_child_pid(child_pid); set_read_fd(pipe_fd[0]); diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index 513e947f5703..902d8c7f64b7 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -336,7 +336,7 @@ bool FilePath::CreateDirectoriesRecursively() const { return false; } - if (pathname_.length() == 0 || this->DirectoryExists()) { + if (pathname_.empty() || this->DirectoryExists()) { return true; } diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 5b7fcbd06509..cc6f00488f96 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -46,6 +46,7 @@ #include #include #include +#include #include #include "gtest/internal/gtest-port.h" @@ -312,7 +313,7 @@ void ShuffleRange(internal::Random* random, int begin, int end, << begin << ", " << size << "]."; // Fisher-Yates shuffle, from - // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle + // https://en.wikipedia.org/wiki/Fisher-Yates_shuffle for (int range_width = end - begin; range_width >= 2; range_width--) { const int last_in_range = begin + range_width - 1; const int selected = @@ -649,13 +650,15 @@ class GTEST_API_ UnitTestImpl { // this is not a typed or a type-parameterized test. // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite - TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param, + TestSuite* GetTestSuite(const std::string& test_suite_name, + const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc); // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - TestCase* GetTestCase(const char* test_case_name, const char* type_param, + TestCase* GetTestCase(const std::string& test_case_name, + const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) { return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc); @@ -681,13 +684,13 @@ class GTEST_API_ UnitTestImpl { // AddTestInfo(), which is called to register a TEST or TEST_F // before main() is reached. if (original_working_dir_.IsEmpty()) { - original_working_dir_.Set(FilePath::GetCurrentDir()); + original_working_dir_ = FilePath::GetCurrentDir(); GTEST_CHECK_(!original_working_dir_.IsEmpty()) << "Failed to get the current working directory."; } #endif // GTEST_HAS_FILE_SYSTEM - GetTestSuite(test_info->test_suite_name(), test_info->type_param(), + GetTestSuite(test_info->test_suite_name_, test_info->type_param(), set_up_tc, tear_down_tc) ->AddTestInfo(test_info); } @@ -709,18 +712,6 @@ class GTEST_API_ UnitTestImpl { return type_parameterized_test_registry_; } - // Sets the TestSuite object for the test that's currently running. - void set_current_test_suite(TestSuite* a_current_test_suite) { - current_test_suite_ = a_current_test_suite; - } - - // Sets the TestInfo object for the test that's currently running. If - // current_test_info is NULL, the assertion results will be stored in - // ad_hoc_test_result_. - void set_current_test_info(TestInfo* a_current_test_info) { - current_test_info_ = a_current_test_info; - } - // Registers all parameterized tests defined using TEST_P and // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter // combination. This method can be called more then once; it has guards @@ -835,12 +826,30 @@ class GTEST_API_ UnitTestImpl { bool catch_exceptions() const { return catch_exceptions_; } private: + struct CompareTestSuitesByPointer { + bool operator()(const TestSuite* lhs, const TestSuite* rhs) const { + return lhs->name_ < rhs->name_; + } + }; + friend class ::testing::UnitTest; // Used by UnitTest::Run() to capture the state of // GTEST_FLAG(catch_exceptions) at the moment it starts. void set_catch_exceptions(bool value) { catch_exceptions_ = value; } + // Sets the TestSuite object for the test that's currently running. + void set_current_test_suite(TestSuite* a_current_test_suite) { + current_test_suite_ = a_current_test_suite; + } + + // Sets the TestInfo object for the test that's currently running. If + // current_test_info is NULL, the assertion results will be stored in + // ad_hoc_test_result_. + void set_current_test_info(TestInfo* a_current_test_info) { + current_test_info_ = a_current_test_info; + } + // The UnitTest object that owns this implementation object. UnitTest* const parent_; @@ -873,6 +882,9 @@ class GTEST_API_ UnitTestImpl { // elements in the vector. std::vector test_suites_; + // The set of TestSuites by name. + std::unordered_map test_suites_by_name_; + // Provides a level of indirection for the test suite list to allow // easy shuffling and restoring the test suite order. The i-th // element of this vector is the index of the i-th test suite in the diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index 2aaf2bcc26c1..1038ad7bf602 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -158,13 +158,13 @@ size_t GetThreadCount() { // we cannot detect it. size_t GetThreadCount() { int mib[] = { - CTL_KERN, - KERN_PROC, - KERN_PROC_PID, - getpid(), + CTL_KERN, + KERN_PROC, + KERN_PROC_PID, + getpid(), #ifdef GTEST_OS_NETBSD - sizeof(struct kinfo_proc), - 1, + sizeof(struct kinfo_proc), + 1, #endif }; u_int miblen = sizeof(mib) / sizeof(mib[0]); @@ -587,9 +587,11 @@ class ThreadLocalRegistryImpl { // thread's ID. typedef std::map ThreadIdToThreadLocals; - // Holds the thread id and thread handle that we pass from - // StartWatcherThreadFor to WatcherThreadFunc. - typedef std::pair ThreadIdAndHandle; + struct WatcherThreadParams { + DWORD thread_id; + HANDLE handle; + Notification has_initialized; + }; static void StartWatcherThreadFor(DWORD thread_id) { // The returned handle will be kept in thread_map and closed by @@ -597,15 +599,20 @@ class ThreadLocalRegistryImpl { HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id); GTEST_CHECK_(thread != nullptr); + + WatcherThreadParams* watcher_thread_params = new WatcherThreadParams; + watcher_thread_params->thread_id = thread_id; + watcher_thread_params->handle = thread; + // We need to pass a valid thread ID pointer into CreateThread for it // to work correctly under Win98. DWORD watcher_thread_id; - HANDLE watcher_thread = ::CreateThread( - nullptr, // Default security. - 0, // Default stack size - &ThreadLocalRegistryImpl::WatcherThreadFunc, - reinterpret_cast(new ThreadIdAndHandle(thread_id, thread)), - CREATE_SUSPENDED, &watcher_thread_id); + HANDLE watcher_thread = + ::CreateThread(nullptr, // Default security. + 0, // Default stack size + &ThreadLocalRegistryImpl::WatcherThreadFunc, + reinterpret_cast(watcher_thread_params), + CREATE_SUSPENDED, &watcher_thread_id); GTEST_CHECK_(watcher_thread != nullptr) << "CreateThread failed with error " << ::GetLastError() << "."; // Give the watcher thread the same priority as ours to avoid being @@ -614,17 +621,25 @@ class ThreadLocalRegistryImpl { ::GetThreadPriority(::GetCurrentThread())); ::ResumeThread(watcher_thread); ::CloseHandle(watcher_thread); + + // Wait for the watcher thread to start to avoid race conditions. + // One specific race condition that can happen is that we have returned + // from main and have started to tear down, the newly spawned watcher + // thread may access already-freed variables, like global shared_ptrs. + watcher_thread_params->has_initialized.WaitForNotification(); } // Monitors exit from a given thread and notifies those // ThreadIdToThreadLocals about thread termination. static DWORD WINAPI WatcherThreadFunc(LPVOID param) { - const ThreadIdAndHandle* tah = - reinterpret_cast(param); - GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); - OnThreadExit(tah->first); - ::CloseHandle(tah->second); - delete tah; + WatcherThreadParams* watcher_thread_params = + reinterpret_cast(param); + watcher_thread_params->has_initialized.Notify(); + GTEST_CHECK_(::WaitForSingleObject(watcher_thread_params->handle, + INFINITE) == WAIT_OBJECT_0); + OnThreadExit(watcher_thread_params->thread_id); + ::CloseHandle(watcher_thread_params->handle); + delete watcher_thread_params; return 0; } @@ -697,13 +712,24 @@ bool RE::PartialMatch(const char* str, const RE& re) { void RE::Init(const char* regex) { pattern_ = regex; + // NetBSD (and Android, which takes its regex implemntation from NetBSD) does + // not include the GNU regex extensions (such as Perl style character classes + // like \w) in REG_EXTENDED. REG_EXTENDED is only specified to include the + // [[:alpha:]] style character classes. Enable REG_GNU wherever it is defined + // so users can use those extensions. +#if defined(REG_GNU) + constexpr int reg_flags = REG_EXTENDED | REG_GNU; +#else + constexpr int reg_flags = REG_EXTENDED; +#endif + // Reserves enough bytes to hold the regular expression used for a // full match. const size_t full_regex_len = strlen(regex) + 10; char* const full_pattern = new char[full_regex_len]; snprintf(full_pattern, full_regex_len, "^(%s)$", regex); - is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; + is_valid_ = regcomp(&full_regex_, full_pattern, reg_flags) == 0; // We want to call regcomp(&partial_regex_, ...) even if the // previous expression returns false. Otherwise partial_regex_ may // not be properly initialized can may cause trouble when it's @@ -714,7 +740,7 @@ void RE::Init(const char* regex) { // regex. We change it to an equivalent form "()" to be safe. if (is_valid_) { const char* const partial_regex = (*regex == '\0') ? "()" : regex; - is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; + is_valid_ = regcomp(&partial_regex_, partial_regex, reg_flags) == 0; } EXPECT_TRUE(is_valid_) << "Regular expression \"" << regex @@ -1022,11 +1048,21 @@ GTestLog::~GTestLog() { } } +#if GTEST_HAS_STREAM_REDIRECTION + // Disable Microsoft deprecation warnings for POSIX functions called from // this class (creat, dup, dup2, and close) GTEST_DISABLE_MSC_DEPRECATED_PUSH_() -#if GTEST_HAS_STREAM_REDIRECTION +namespace { + +#if defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_IOS) +bool EndsWithPathSeparator(const std::string& path) { + return !path.empty() && path.back() == GTEST_PATH_SEP_[0]; +} +#endif + +} // namespace // Object that captures an output stream (stdout/stderr). class CapturedStream { @@ -1064,7 +1100,13 @@ class CapturedStream { // The location /data/local/tmp is directly accessible from native code. // '/sdcard' and other variants cannot be relied on, as they are not // guaranteed to be mounted, or may have a delay in mounting. - name_template = "/data/local/tmp/"; + // + // However, prefer using the TMPDIR environment variable if set, as newer + // devices may have /data/local/tmp read-only. + name_template = TempDir(); + if (!EndsWithPathSeparator(name_template)) + name_template.push_back(GTEST_PATH_SEP_[0]); + #elif defined(GTEST_OS_IOS) char user_temp_dir[PATH_MAX + 1]; @@ -1084,7 +1126,7 @@ class CapturedStream { ::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir, sizeof(user_temp_dir)); name_template = user_temp_dir; - if (name_template.back() != GTEST_PATH_SEP_[0]) + if (!EndsWithPathSeparator(name_template)) name_template.push_back(GTEST_PATH_SEP_[0]); #else name_template = "/tmp/"; @@ -1306,8 +1348,8 @@ bool ParseInt32(const Message& src_text, const char* str, int32_t* value) { ) { Message msg; msg << "WARNING: " << src_text - << " is expected to be a 32-bit integer, but actually" - << " has value " << str << ", which overflows.\n"; + << " is expected to be a 32-bit integer, but actually" << " has value " + << str << ", which overflows.\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 30a5cc3f83a7..6662a13ce145 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -43,6 +43,7 @@ #include #include // NOLINT #include +#include // NOLINT: raise(3) is used on some platforms #include #include #include @@ -161,6 +162,10 @@ #define GTEST_HAS_BUILTIN(x) 0 #endif // defined(__has_builtin) +#if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) +#define GTEST_HAS_ABSL_FLAGS +#endif + namespace testing { using internal::CountIf; @@ -374,7 +379,7 @@ GTEST_DEFINE_string_( 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."); + "Linux and macOS."); GTEST_DEFINE_bool_( throw_on_failure, @@ -446,6 +451,19 @@ static bool ShouldRunTestSuite(const TestSuite* test_suite) { return test_suite->should_run(); } +namespace { + +// Returns true if test part results of type `type` should include a stack +// trace. +bool ShouldEmitStackTraceForResultType(TestPartResult::Type type) { + // Suppress emission of the stack trace for SUCCEED() since it likely never + // requires investigation, and GTEST_SKIP() since skipping is an intentional + // act by the developer rather than a failure requiring investigation. + return type != TestPartResult::kSuccess && type != TestPartResult::kSkip; +} + +} // namespace + // AssertHelper constructor. AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) @@ -458,7 +476,9 @@ void AssertHelper::operator=(const Message& message) const { UnitTest::GetInstance()->AddTestPartResult( data_->type, data_->file, data_->line, AppendUserMessage(data_->message, message), - UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1) + ShouldEmitStackTraceForResultType(data_->type) + ? UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1) + : "" // Skips the stack frame for this function itself. ); // NOLINT } @@ -516,7 +536,8 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location, if (ignored.find(name) != ignored.end()) return; const char kMissingInstantiation[] = // - " is defined via TEST_P, but never instantiated. None of the test cases " + " is defined via TEST_P, but never instantiated. None of the test " + "cases " "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only " "ones provided expand to nothing." "\n\n" @@ -557,7 +578,7 @@ void InsertSyntheticTestCase(const std::string& name, CodeLocation location, void RegisterTypeParameterizedTestSuite(const char* test_suite_name, CodeLocation code_location) { GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite( - test_suite_name, code_location); + test_suite_name, std::move(code_location)); } void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { @@ -568,7 +589,7 @@ void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( const char* test_suite_name, CodeLocation code_location) { suites_.emplace(std::string(test_suite_name), - TypeParameterizedTestSuiteInfo(code_location)); + TypeParameterizedTestSuiteInfo(std::move(code_location))); } void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( @@ -595,10 +616,12 @@ void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() { "\n\n" "Ideally, TYPED_TEST_P definitions should only ever be included as " "part of binaries that intend to use them. (As opposed to, for " - "example, being placed in a library that may be linked in to get other " + "example, being placed in a library that may be linked in to get " + "other " "utilities.)" "\n\n" - "To suppress this error for this test suite, insert the following line " + "To suppress this error for this test suite, insert the following " + "line " "(in a non-header) in the namespace it is defined in:" "\n\n" "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + @@ -638,11 +661,14 @@ static ::std::vector g_argvs; FilePath GetCurrentExecutableName() { FilePath result; + auto args = GetArgvs(); + if (!args.empty()) { #if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2) - result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); + result.Set(FilePath(args[0]).RemoveExtension("exe")); #else - result.Set(FilePath(GetArgvs()[0])); + result.Set(FilePath(args[0])); #endif // GTEST_OS_WINDOWS + } return result.RemoveDirectoryName(); } @@ -778,7 +804,7 @@ class UnitTestFilter { // Returns true if and only if name matches at least one of the patterns in // the filter. bool MatchesName(const std::string& name) const { - return exact_match_patterns_.count(name) > 0 || + return exact_match_patterns_.find(name) != exact_match_patterns_.end() || std::any_of(glob_patterns_.begin(), glob_patterns_.end(), [&name](const std::string& pattern) { return PatternMatchesString( @@ -879,7 +905,7 @@ int UnitTestOptions::GTestProcessSEH(DWORD seh_code, const char* location) { // apparently). // // SEH exception code for C++ exceptions. - // (see http://support.microsoft.com/kb/185294 for more information). + // (see https://support.microsoft.com/kb/185294 for more information). const DWORD kCxxExceptionCode = 0xe06d7363; if (!GTEST_FLAG_GET(catch_exceptions) || seh_code == kCxxExceptionCode || @@ -2317,7 +2343,7 @@ static const char* const kReservedTestCaseAttributes[] = { "type_param", "value_param", "file", "line"}; // Use a slightly different set for allowed output to ensure existing tests can -// still RecordProperty("result") or "RecordProperty(timestamp") +// still RecordProperty("result") or RecordProperty("timestamp") static const char* const kReservedOutputTestCaseAttributes[] = { "classname", "name", "status", "time", "type_param", "value_param", "file", "line", "result", "timestamp"}; @@ -2717,18 +2743,16 @@ bool Test::IsSkipped() { // Constructs a TestInfo object. It assumes ownership of the test factory // object. -TestInfo::TestInfo(const std::string& a_test_suite_name, - const std::string& a_name, const char* a_type_param, - const char* a_value_param, +TestInfo::TestInfo(std::string a_test_suite_name, std::string a_name, + const char* a_type_param, const char* a_value_param, internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) - : test_suite_name_(a_test_suite_name), - // begin()/end() is MSVC 17.3.3 ASAN crash workaround (GitHub issue #3997) - name_(a_name.begin(), a_name.end()), + : test_suite_name_(std::move(a_test_suite_name)), + name_(std::move(a_name)), type_param_(a_type_param ? new std::string(a_type_param) : nullptr), value_param_(a_value_param ? new std::string(a_value_param) : nullptr), - location_(a_code_location), + location_(std::move(a_code_location)), fixture_class_id_(fixture_class_id), should_run_(false), is_disabled_(false), @@ -2761,19 +2785,19 @@ namespace internal { // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo( - const char* test_suite_name, const char* name, const char* type_param, + std::string test_suite_name, const char* name, const char* type_param, const char* value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) { TestInfo* const test_info = - new TestInfo(test_suite_name, name, type_param, value_param, - code_location, fixture_class_id, factory); + new TestInfo(std::move(test_suite_name), name, type_param, value_param, + std::move(code_location), fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } void ReportInvalidTestSuiteType(const char* test_suite_name, - CodeLocation code_location) { + const CodeLocation& code_location) { Message errors; errors << "Attempted redefinition of test suite " << test_suite_name << ".\n" @@ -2813,14 +2837,13 @@ void TestInfo::Run() { } // Tells UnitTest where to store test result. - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_info(this); + UnitTest::GetInstance()->set_current_test_info(this); // Notifies the unit test event listeners that a test is about to start. repeater->OnTestStart(*this); result_.set_start_timestamp(internal::GetTimeInMillis()); internal::Timer timer; - impl->os_stack_trace_getter()->UponLeavingGTest(); + UnitTest::GetInstance()->UponLeavingGTest(); // Creates the test object. Test* const test = internal::HandleExceptionsInMethodIfSupported( @@ -2838,7 +2861,7 @@ void TestInfo::Run() { if (test != nullptr) { // Deletes the test object. - impl->os_stack_trace_getter()->UponLeavingGTest(); + UnitTest::GetInstance()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( test, &Test::DeleteSelf_, "the test fixture's destructor"); } @@ -2850,15 +2873,14 @@ void TestInfo::Run() { // Tells UnitTest to stop associating assertion results to this // test. - impl->set_current_test_info(nullptr); + UnitTest::GetInstance()->set_current_test_info(nullptr); } // Skip and records a skipped test result for this object. void TestInfo::Skip() { if (!should_run_) return; - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_info(this); + UnitTest::GetInstance()->set_current_test_info(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); @@ -2867,12 +2889,13 @@ void TestInfo::Skip() { const TestPartResult test_part_result = TestPartResult(TestPartResult::kSkip, this->file(), this->line(), ""); - impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult( - test_part_result); + internal::GetUnitTestImpl() + ->GetTestPartResultReporterForCurrentThread() + ->ReportTestPartResult(test_part_result); // Notifies the unit test event listener that a test has just finished. repeater->OnTestEnd(*this); - impl->set_current_test_info(nullptr); + UnitTest::GetInstance()->set_current_test_info(nullptr); } // class TestSuite @@ -2926,7 +2949,7 @@ int TestSuite::total_test_count() const { // this is not a typed or a type-parameterized test suite. // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite -TestSuite::TestSuite(const char* a_name, const char* a_type_param, +TestSuite::TestSuite(const std::string& a_name, const char* a_type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) : name_(a_name), @@ -2968,8 +2991,7 @@ void TestSuite::AddTestInfo(TestInfo* test_info) { void TestSuite::Run() { if (!should_run_) return; - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_suite(this); + UnitTest::GetInstance()->set_current_test_suite(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); @@ -2999,7 +3021,7 @@ void TestSuite::Run() { repeater->OnTestCaseStart(*this); #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - impl->os_stack_trace_getter()->UponLeavingGTest(); + UnitTest::GetInstance()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()"); @@ -3024,7 +3046,7 @@ void TestSuite::Run() { } elapsed_time_ = timer.Elapsed(); - impl->os_stack_trace_getter()->UponLeavingGTest(); + UnitTest::GetInstance()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()"); @@ -3035,15 +3057,14 @@ void TestSuite::Run() { repeater->OnTestCaseEnd(*this); #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - impl->set_current_test_suite(nullptr); + UnitTest::GetInstance()->set_current_test_suite(nullptr); } // Skips all tests under this TestSuite. void TestSuite::Skip() { if (!should_run_) return; - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_suite(this); + UnitTest::GetInstance()->set_current_test_suite(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); @@ -3065,7 +3086,7 @@ void TestSuite::Skip() { repeater->OnTestCaseEnd(*this); #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - impl->set_current_test_suite(nullptr); + UnitTest::GetInstance()->set_current_test_suite(nullptr); } // Clears the results of all tests in this test suite. @@ -3166,9 +3187,9 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) { } // class PrettyUnitTestResultPrinter -#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \ - !defined(GTEST_OS_WINDOWS_PHONE) && !defined(GTEST_OS_WINDOWS_RT) && \ - !defined(GTEST_OS_WINDOWS_MINGW) +#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \ + !defined(GTEST_OS_WINDOWS_GAMES) && !defined(GTEST_OS_WINDOWS_PHONE) && \ + !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_MINGW) // Returns the character attribute for the given color. static WORD GetColorAttribute(GTestColor color) { @@ -3228,7 +3249,8 @@ static const char* GetAnsiColorCode(GTestColor color) { case GTestColor::kYellow: return "3"; default: - return nullptr; + assert(false); + return "9"; } } @@ -3251,6 +3273,7 @@ bool ShouldUseColor(bool stdout_is_tty) { term != nullptr && (String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-kitty") || + String::CStringEquals(term, "alacritty") || String::CStringEquals(term, "screen") || String::CStringEquals(term, "tmux") || String::CStringEquals(term, "rxvt-unicode") || @@ -3281,11 +3304,9 @@ static void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_start(args, fmt); static const bool in_color_mode = -#if GTEST_HAS_FILE_SYSTEM + // We don't condition this on GTEST_HAS_FILE_SYSTEM because we still need + // to be able to detect terminal I/O regardless. ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); -#else - false; -#endif // GTEST_HAS_FILE_SYSTEM const bool use_color = in_color_mode && (color != GTestColor::kDefault); @@ -3295,9 +3316,9 @@ static void ColoredPrintf(GTestColor color, const char* fmt, ...) { return; } -#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \ - !defined(GTEST_OS_WINDOWS_PHONE) && !defined(GTEST_OS_WINDOWS_RT) && \ - !defined(GTEST_OS_WINDOWS_MINGW) +#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \ + !defined(GTEST_OS_WINDOWS_GAMES) && !defined(GTEST_OS_WINDOWS_PHONE) && \ + !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_MINGW) const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. @@ -4420,8 +4441,8 @@ std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); - attributes << " " << property.key() << "=" - << "\"" << EscapeXmlAttribute(property.value()) << "\""; + attributes << " " << property.key() << "=" << "\"" + << EscapeXmlAttribute(property.value()) << "\""; } return attributes.GetString(); } @@ -4725,28 +4746,53 @@ void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, const TestResult& result) { const std::string kIndent = Indent(10); - int failures = 0; - for (int i = 0; i < result.total_part_count(); ++i) { - const TestPartResult& part = result.GetTestPartResult(i); - if (part.failed()) { - *stream << ",\n"; - if (++failures == 1) { - *stream << kIndent << "\"" - << "failures" - << "\": [\n"; + { + int failures = 0; + for (int i = 0; i < result.total_part_count(); ++i) { + const TestPartResult& part = result.GetTestPartResult(i); + if (part.failed()) { + *stream << ",\n"; + if (++failures == 1) { + *stream << kIndent << "\"" << "failures" << "\": [\n"; + } + const std::string location = + internal::FormatCompilerIndependentFileLocation(part.file_name(), + part.line_number()); + const std::string message = + EscapeJson(location + "\n" + part.message()); + *stream << kIndent << " {\n" + << kIndent << " \"failure\": \"" << message << "\",\n" + << kIndent << " \"type\": \"\"\n" + << kIndent << " }"; } - const std::string location = - internal::FormatCompilerIndependentFileLocation(part.file_name(), - part.line_number()); - const std::string message = EscapeJson(location + "\n" + part.message()); - *stream << kIndent << " {\n" - << kIndent << " \"failure\": \"" << message << "\",\n" - << kIndent << " \"type\": \"\"\n" - << kIndent << " }"; } + + if (failures > 0) *stream << "\n" << kIndent << "]"; + } + + { + int skipped = 0; + for (int i = 0; i < result.total_part_count(); ++i) { + const TestPartResult& part = result.GetTestPartResult(i); + if (part.skipped()) { + *stream << ",\n"; + if (++skipped == 1) { + *stream << kIndent << "\"" << "skipped" << "\": [\n"; + } + const std::string location = + internal::FormatCompilerIndependentFileLocation(part.file_name(), + part.line_number()); + const std::string message = + EscapeJson(location + "\n" + part.message()); + *stream << kIndent << " {\n" + << kIndent << " \"message\": \"" << message << "\"\n" + << kIndent << " }"; + } + } + + if (skipped > 0) *stream << "\n" << kIndent << "]"; } - if (failures > 0) *stream << "\n" << kIndent << "]"; *stream << "\n" << Indent(8) << "}"; } @@ -4883,8 +4929,8 @@ std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << ",\n" - << indent << "\"" << property.key() << "\": " - << "\"" << EscapeJson(property.value()) << "\""; + << indent << "\"" << property.key() << "\": " << "\"" + << EscapeJson(property.value()) << "\""; } return attributes.GetString(); } @@ -5282,6 +5328,22 @@ TestSuite* UnitTest::GetMutableTestSuite(int i) { return impl()->GetMutableSuiteCase(i); } +void UnitTest::UponLeavingGTest() { + impl()->os_stack_trace_getter()->UponLeavingGTest(); +} + +// Sets the TestSuite object for the test that's currently running. +void UnitTest::set_current_test_suite(TestSuite* a_current_test_suite) { + internal::MutexLock lock(&mutex_); + impl_->set_current_test_suite(a_current_test_suite); +} + +// Sets the TestInfo object for the test that's currently running. +void UnitTest::set_current_test_info(TestInfo* a_current_test_info) { + internal::MutexLock lock(&mutex_); + impl_->set_current_test_info(a_current_test_info); +} + // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); } @@ -5399,7 +5461,7 @@ void UnitTest::RecordProperty(const std::string& key, int UnitTest::Run() { #ifdef GTEST_HAS_DEATH_TEST const bool in_death_test_child_process = - GTEST_FLAG_GET(internal_run_death_test).length() > 0; + !GTEST_FLAG_GET(internal_run_death_test).empty(); // Google Test implements this protocol for catching that a test // program exits before returning control to Google Test: @@ -5441,7 +5503,7 @@ int UnitTest::Run() { // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { #if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \ - !defined(GTEST_OS_WINDOWS_RT) + !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_GAMES) // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); @@ -5711,29 +5773,6 @@ void UnitTestImpl::PostFlagParsingInit() { } } -// A predicate that checks the name of a TestSuite against a known -// value. -// -// This is used for implementation of the UnitTest class only. We put -// it in the anonymous namespace to prevent polluting the outer -// namespace. -// -// TestSuiteNameIs is copyable. -class TestSuiteNameIs { - public: - // Constructor. - explicit TestSuiteNameIs(const std::string& name) : name_(name) {} - - // Returns true if and only if the name of test_suite matches name_. - bool operator()(const TestSuite* test_suite) const { - return test_suite != nullptr && - strcmp(test_suite->name(), name_.c_str()) == 0; - } - - private: - std::string name_; -}; - // Finds and returns a TestSuite with the given name. If one doesn't // exist, creates one and returns it. It's the CALLER'S // RESPONSIBILITY to ensure that this function is only called WHEN THE @@ -5747,19 +5786,27 @@ class TestSuiteNameIs { // set_up_tc: pointer to the function that sets up the test suite // tear_down_tc: pointer to the function that tears down the test suite TestSuite* UnitTestImpl::GetTestSuite( - const char* test_suite_name, const char* type_param, + const std::string& test_suite_name, const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) { - // Can we find a TestSuite with the given name? - const auto test_suite = - std::find_if(test_suites_.rbegin(), test_suites_.rend(), - TestSuiteNameIs(test_suite_name)); + // During initialization, all TestInfos for a given suite are added in + // sequence. To optimize this case, see if the most recently added suite is + // the one being requested now. + if (!test_suites_.empty() && + (*test_suites_.rbegin())->name_ == test_suite_name) { + return *test_suites_.rbegin(); + } - if (test_suite != test_suites_.rend()) return *test_suite; + // Fall back to searching the collection. + auto item_it = test_suites_by_name_.find(test_suite_name); + if (item_it != test_suites_by_name_.end()) { + return item_it->second; + } - // No. Let's create one. + // Not found. Create a new instance. auto* const new_test_suite = new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc); + test_suites_by_name_.emplace(test_suite_name, new_test_suite); const UnitTestFilter death_test_suite_filter(kDeathTestSuiteFilter); // Is this a death test suite? @@ -5972,6 +6019,12 @@ bool UnitTestImpl::RunAllTests() { } repeater->OnTestProgramEnd(*parent_); + // Destroy environments in normal code, not in static teardown. + bool delete_environment_on_teardown = true; + if (delete_environment_on_teardown) { + ForEach(environments_, internal::Delete); + environments_.clear(); + } if (!gtest_is_initialized_before_run_all_tests) { ColoredPrintf( @@ -6105,12 +6158,11 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { int num_runnable_tests = 0; int num_selected_tests = 0; for (auto* test_suite : test_suites_) { - const std::string& test_suite_name = test_suite->name(); + const std::string& test_suite_name = test_suite->name_; test_suite->set_should_run(false); - for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { - TestInfo* const test_info = test_suite->test_info_list()[j]; - const std::string test_name(test_info->name()); + for (TestInfo* test_info : test_suite->test_info_list()) { + const std::string& test_name = test_info->name_; // A test is disabled if test suite name or test name matches // kDisableTestFilter. const bool is_disabled = @@ -6201,8 +6253,8 @@ void UnitTestImpl::ListTestsMatchingFilter() { #if GTEST_HAS_FILE_SYSTEM const std::string& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml" || output_format == "json") { - FILE* fileout = OpenFileForWriting( - UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); + FILE* fileout = + OpenFileForWriting(UnitTestOptions::GetAbsolutePathToOutputFile()); std::stringstream stream; if (output_format == "xml") { XmlUnitTestResultPrinter( @@ -6651,17 +6703,17 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { } if (remove_flag) { - // Shift the remainder of the argv list left by one. Note - // that argv has (*argc + 1) elements, the last one always being - // NULL. The following loop moves the trailing NULL element as - // well. - for (int j = i; j != *argc; j++) { - argv[j] = argv[j + 1]; + // Shift the remainder of the argv list left by one. + for (int j = i + 1; j < *argc; ++j) { + argv[j - 1] = argv[j]; } // Decrements the argument count. (*argc)--; + // Terminate the array with nullptr. + argv[*argc] = nullptr; + // We also need to decrement the iterator as we just removed // an element. i--; @@ -6683,7 +6735,7 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { // remain in place. Unrecognized flags are not reported and do not cause the // program to exit. void ParseGoogleTestFlagsOnly(int* argc, char** argv) { -#ifdef GTEST_HAS_ABSL +#ifdef GTEST_HAS_ABSL_FLAGS if (*argc <= 0) return; std::vector positional_args; @@ -6769,11 +6821,13 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { #ifdef GTEST_HAS_ABSL absl::InitializeSymbolizer(g_argvs[0].c_str()); +#ifdef GTEST_HAS_ABSL_FLAGS // When using the Abseil Flags library, set the program usage message to the // help message, but remove the color-encoding from the message first. absl::SetProgramUsageMessage(absl::StrReplaceAll( kColorEncodedHelpMessage, {{"@D", ""}, {"@R", ""}, {"@G", ""}, {"@Y", ""}, {"@@", "@"}})); +#endif // GTEST_HAS_ABSL_FLAGS #endif // GTEST_HAS_ABSL ParseGoogleTestFlagsOnly(argc, argv); diff --git a/googletest/test/googletest-color-test.py b/googletest/test/googletest-color-test.py index 8926a48155b2..8968cf1f688b 100755 --- a/googletest/test/googletest-color-test.py +++ b/googletest/test/googletest-color-test.py @@ -80,6 +80,7 @@ class GTestColorTest(gtest_test_utils.TestCase): self.assertTrue(UsesColor('xterm', None, None)) self.assertTrue(UsesColor('xterm-color', None, None)) self.assertTrue(UsesColor('xterm-kitty', None, None)) + self.assertTrue(UsesColor('alacritty', None, None)) self.assertTrue(UsesColor('xterm-256color', None, None)) def testFlagOnly(self): diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc index 4cc81b723e4a..44b80464834d 100644 --- a/googletest/test/googletest-death-test-test.cc +++ b/googletest/test/googletest-death-test-test.cc @@ -30,6 +30,8 @@ // // Tests for death tests. +#include + #include "gtest/gtest-death-test.h" #include "gtest/gtest.h" #include "gtest/internal/gtest-filepath.h" @@ -111,15 +113,15 @@ void DieWithMessage(const ::std::string& message) { fprintf(stderr, "%s", message.c_str()); fflush(stderr); // Make sure the text is printed before the process exits. - // We call _exit() instead of exit(), as the former is a direct + // We call _Exit() instead of exit(), as the former is a direct // system call and thus safer in the presence of threads. exit() // will invoke user-defined exit-hooks, which may do dangerous // things that conflict with death tests. // - // Some compilers can recognize that _exit() never returns and issue the + // Some compilers can recognize that _Exit() never returns and issue the // 'unreachable code' warning for code following this function, unless // fooled by a fake condition. - if (AlwaysTrue()) _exit(1); + if (AlwaysTrue()) _Exit(1); } void DieInside(const ::std::string& function) { @@ -238,13 +240,13 @@ TEST(ExitStatusPredicateTest, ExitedWithCode) { #else -// Returns the exit status of a process that calls _exit(2) with a +// Returns the exit status of a process that calls _Exit(2) with a // given exit code. This is a helper function for the // ExitStatusPredicateTest test suite. static int NormalExitStatus(int exit_code) { pid_t child_pid = fork(); if (child_pid == 0) { - _exit(exit_code); + _Exit(exit_code); } int status; waitpid(child_pid, &status, 0); @@ -260,7 +262,7 @@ static int KilledExitStatus(int signum) { pid_t child_pid = fork(); if (child_pid == 0) { raise(signum); - _exit(1); + _Exit(1); } int status; waitpid(child_pid, &status, 0); @@ -289,7 +291,9 @@ TEST(ExitStatusPredicateTest, KilledBySignal) { const int status_kill = KilledExitStatus(SIGKILL); const testing::KilledBySignal pred_segv(SIGSEGV); const testing::KilledBySignal pred_kill(SIGKILL); +#if !(defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ <= 21) EXPECT_PRED1(pred_segv, status_segv); +#endif EXPECT_PRED1(pred_kill, status_kill); EXPECT_FALSE(pred_segv(status_kill)); EXPECT_FALSE(pred_kill(status_segv)); @@ -313,7 +317,7 @@ TEST_F(TestForDeathTest, SingleStatement) { ASSERT_DEATH(return, ""); if (AlwaysTrue()) - EXPECT_DEATH(_exit(1), ""); + EXPECT_DEATH(_Exit(1), ""); else // This empty "else" branch is meant to ensure that EXPECT_DEATH // doesn't expand into an "if" statement without an "else" @@ -324,7 +328,7 @@ TEST_F(TestForDeathTest, SingleStatement) { if (AlwaysFalse()) ; else - EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3; + EXPECT_DEATH(_Exit(1), "") << 1 << 2 << 3; } #ifdef __GNUC__ #pragma GCC diagnostic pop @@ -339,11 +343,11 @@ TEST_F(TestForDeathTest, SwitchStatement) { switch (0) default: - ASSERT_DEATH(_exit(1), "") << "exit in default switch handler"; + ASSERT_DEATH(_Exit(1), "") << "exit in default switch handler"; switch (0) case 0: - EXPECT_DEATH(_exit(1), "") << "exit in switch case"; + EXPECT_DEATH(_Exit(1), "") << "exit in switch case"; GTEST_DISABLE_MSC_WARNINGS_POP_() } @@ -371,10 +375,10 @@ TEST_F(TestForDeathTest, FastDeathTestInChangedDir) { GTEST_FLAG_SET(death_test_style, "fast"); ChangeToRootDir(); - EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); + EXPECT_EXIT(_Exit(1), testing::ExitedWithCode(1), ""); ChangeToRootDir(); - ASSERT_DEATH(_exit(1), ""); + ASSERT_DEATH(_Exit(1), ""); } #ifdef GTEST_OS_LINUX @@ -416,7 +420,7 @@ void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) { TEST_F(TestForDeathTest, FastSigprofActionSet) { GTEST_FLAG_SET(death_test_style, "fast"); SetSigprofActionAndTimer(); - EXPECT_DEATH(_exit(1), ""); + EXPECT_DEATH(_Exit(1), ""); struct sigaction old_signal_action; DisableSigprofActionAndTimer(&old_signal_action); EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); @@ -425,7 +429,7 @@ TEST_F(TestForDeathTest, FastSigprofActionSet) { TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { GTEST_FLAG_SET(death_test_style, "threadsafe"); SetSigprofActionAndTimer(); - EXPECT_DEATH(_exit(1), ""); + EXPECT_DEATH(_Exit(1), ""); struct sigaction old_signal_action; DisableSigprofActionAndTimer(&old_signal_action); EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); @@ -449,24 +453,24 @@ TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) { GTEST_FLAG_SET(death_test_style, "threadsafe"); for (int i = 0; i < 3; ++i) - EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i; + EXPECT_EXIT(_Exit(i), testing::ExitedWithCode(i), "") << ": i = " << i; } TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) { GTEST_FLAG_SET(death_test_style, "threadsafe"); ChangeToRootDir(); - EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); + EXPECT_EXIT(_Exit(1), testing::ExitedWithCode(1), ""); ChangeToRootDir(); - ASSERT_DEATH(_exit(1), ""); + ASSERT_DEATH(_Exit(1), ""); } TEST_F(TestForDeathTest, MixedStyles) { GTEST_FLAG_SET(death_test_style, "threadsafe"); - EXPECT_DEATH(_exit(1), ""); + EXPECT_DEATH(_Exit(1), ""); GTEST_FLAG_SET(death_test_style, "fast"); - EXPECT_DEATH(_exit(1), ""); + EXPECT_DEATH(_Exit(1), ""); } #if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD @@ -480,7 +484,7 @@ TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { GTEST_FLAG_SET(death_test_style, "threadsafe"); pthread_flag = false; ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, nullptr, nullptr)); - ASSERT_DEATH(_exit(1), ""); + ASSERT_DEATH(_Exit(1), ""); ASSERT_FALSE(pthread_flag); } } @@ -805,8 +809,8 @@ TEST_F(TestForDeathTest, AssertDebugDeathAborts10) { // Tests the *_EXIT family of macros, using a variety of predicates. static void TestExitMacros() { - EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), ""); - ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), ""); + EXPECT_EXIT(_Exit(1), testing::ExitedWithCode(1), ""); + ASSERT_EXIT(_Exit(42), testing::ExitedWithCode(42), ""); #ifdef GTEST_OS_WINDOWS @@ -823,7 +827,7 @@ static void TestExitMacros() { EXPECT_FATAL_FAILURE( { // NOLINT - ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "") + ASSERT_EXIT(_Exit(0), testing::KilledBySignal(SIGSEGV), "") << "This failure is expected, too."; }, "This failure is expected, too."); @@ -849,7 +853,7 @@ TEST_F(TestForDeathTest, InvalidStyle) { GTEST_FLAG_SET(death_test_style, "rococo"); EXPECT_NONFATAL_FAILURE( { // NOLINT - EXPECT_DEATH(_exit(0), "") << "This failure is expected."; + EXPECT_DEATH(_Exit(0), "") << "This failure is expected."; }, "This failure is expected."); } @@ -1140,7 +1144,7 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { // This time there are two calls to Abort: one since the test didn't // die, and another from the ReturnSentinel when it's destroyed. The // sentinel normally isn't destroyed if a test doesn't die, since - // _exit(2) is called in that case by ForkingDeathTest, but not by + // _Exit(2) is called in that case by ForkingDeathTest, but not by // our MockDeathTest. ASSERT_EQ(2U, factory_->AbortCalls()); EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0)); @@ -1152,21 +1156,21 @@ TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { // Tests that a successful death test does not register a successful // test part. TEST(SuccessRegistrationDeathTest, NoSuccessPart) { - EXPECT_DEATH(_exit(1), ""); + EXPECT_DEATH(_Exit(1), ""); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } TEST(StreamingAssertionsDeathTest, DeathTest) { - EXPECT_DEATH(_exit(1), "") << "unexpected failure"; - ASSERT_DEATH(_exit(1), "") << "unexpected failure"; + EXPECT_DEATH(_Exit(1), "") << "unexpected failure"; + ASSERT_DEATH(_Exit(1), "") << "unexpected failure"; EXPECT_NONFATAL_FAILURE( { // NOLINT - EXPECT_DEATH(_exit(0), "") << "expected failure"; + EXPECT_DEATH(_Exit(0), "") << "expected failure"; }, "expected failure"); EXPECT_FATAL_FAILURE( { // NOLINT - ASSERT_DEATH(_exit(0), "") << "expected failure"; + ASSERT_DEATH(_Exit(0), "") << "expected failure"; }, "expected failure"); } @@ -1330,7 +1334,7 @@ TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { { fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); fflush(stderr); - _exit(1); + _Exit(1); }, "Inside"); } @@ -1342,7 +1346,7 @@ TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { { fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); fflush(stderr); - _exit(1); + _Exit(1); }, "Inside"); } @@ -1350,7 +1354,7 @@ TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { void DieWithMessage(const char* message) { fputs(message, stderr); fflush(stderr); // Make sure the text is printed before the process exits. - _exit(1); + _Exit(1); } TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) { @@ -1466,7 +1470,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) { ASSERT_DEATH_IF_SUPPORTED(return, ""); if (AlwaysTrue()) - EXPECT_DEATH_IF_SUPPORTED(_exit(1), ""); + EXPECT_DEATH_IF_SUPPORTED(_Exit(1), ""); else // This empty "else" branch is meant to ensure that EXPECT_DEATH // doesn't expand into an "if" statement without an "else" @@ -1477,7 +1481,7 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) { if (AlwaysFalse()) ; // NOLINT else - EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3; + EXPECT_DEATH_IF_SUPPORTED(_Exit(1), "") << 1 << 2 << 3; } #ifdef __GNUC__ #pragma GCC diagnostic pop @@ -1492,11 +1496,11 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { switch (0) default: - ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in default switch handler"; + ASSERT_DEATH_IF_SUPPORTED(_Exit(1), "") << "exit in default switch handler"; switch (0) case 0: - EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case"; + EXPECT_DEATH_IF_SUPPORTED(_Exit(1), "") << "exit in switch case"; GTEST_DISABLE_MSC_WARNINGS_POP_() } diff --git a/googletest/test/googletest-json-output-unittest.py b/googletest/test/googletest-json-output-unittest.py index cb976945202a..d3338e3d2f90 100644 --- a/googletest/test/googletest-json-output-unittest.py +++ b/googletest/test/googletest-json-output-unittest.py @@ -150,6 +150,9 @@ EXPECTED_NON_EMPTY = { 'time': '*', 'timestamp': '*', 'classname': 'SkippedTest', + 'skipped': [ + {'message': 'gtest_xml_output_unittest_.cc:*\n\n'} + ], }, { 'name': 'SkippedWithMessage', @@ -160,6 +163,12 @@ EXPECTED_NON_EMPTY = { 'time': '*', 'timestamp': '*', 'classname': 'SkippedTest', + 'skipped': [{ + 'message': ( + 'gtest_xml_output_unittest_.cc:*\n' + 'It is good practice to tell why you skip a test.\n' + ) + }], }, { 'name': 'SkippedAfterFailure', @@ -179,6 +188,12 @@ EXPECTED_NON_EMPTY = { ), 'type': '', }], + 'skipped': [{ + 'message': ( + 'gtest_xml_output_unittest_.cc:*\n' + 'It is good practice to tell why you skip a test.\n' + ) + }], }, ], }, diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index b712c06fa3fb..91d06a509755 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -115,11 +115,14 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { strcasecmp("gtest_dll_test", exe_str.c_str()) == 0; #elif defined(GTEST_OS_FUCHSIA) const bool success = exe_str == "app"; +#elif defined(__EMSCRIPTEN__) + const bool success = exe_str == "patched_googletest-options-test.js"; #else const bool success = exe_str == "googletest-options-test" || exe_str == "gtest_all_test" || exe_str == "lt-gtest_all_test" || exe_str == "gtest_dll_test"; -#endif // GTEST_OS_WINDOWS +#endif // platform ifdefs + if (!success) FAIL() << "GetCurrentExecutableName() returns " << exe_str; } diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index 6ddf822ffb47..533eb8c6e079 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -696,7 +696,6 @@ Expected: 1 fatal failure Actual: googletest-output-test_.cc:#: Success: Succeeded -Stack trace: (omitted) Stack trace: (omitted) @@ -733,7 +732,6 @@ Expected: 1 non-fatal failure Actual: googletest-output-test_.cc:#: Success: Succeeded -Stack trace: (omitted) Stack trace: (omitted) @@ -770,7 +768,6 @@ Expected: 1 fatal failure Actual: googletest-output-test_.cc:#: Success: Succeeded -Stack trace: (omitted) Stack trace: (omitted) @@ -807,7 +804,6 @@ Expected: 1 non-fatal failure Actual: googletest-output-test_.cc:#: Success: Succeeded -Stack trace: (omitted) Stack trace: (omitted) @@ -970,7 +966,6 @@ googletest-output-test_.cc:#: Skipped [----------] 1 test from TestSuiteThatSkipsInSetUp googletest-output-test_.cc:#: Skipped Skip entire test suite -Stack trace: (omitted) [ RUN ] TestSuiteThatSkipsInSetUp.ShouldNotRun googletest-output-test_.cc:#: Skipped diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 32a2a7b4d642..9f05a0199334 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -296,7 +296,7 @@ void* ThreadFunc(void* data) { TEST(GetThreadCountTest, ReturnsCorrectValue) { size_t starting_count; size_t thread_count_after_create; - size_t thread_count_after_join; + size_t thread_count_after_join = 0; // We can't guarantee that no other thread was created or destroyed between // any two calls to GetThreadCount(). We make multiple attempts, hoping that @@ -316,9 +316,9 @@ TEST(GetThreadCountTest, ReturnsCorrectValue) { const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); ASSERT_EQ(0, pthread_attr_destroy(&attr)); ASSERT_EQ(0, status); - } - thread_count_after_create = GetThreadCount(); + thread_count_after_create = GetThreadCount(); + } void* dummy; ASSERT_EQ(0, pthread_join(thread_id, &dummy)); diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index bee0ca4abe10..d5061bef26d7 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -54,11 +54,16 @@ #include "gtest/gtest-printers.h" #include "gtest/gtest.h" +#include "gtest/internal/gtest-port.h" #ifdef GTEST_HAS_ABSL #include "absl/strings/str_format.h" #endif +#if GTEST_INTERNAL_HAS_STD_SPAN +#include // NOLINT +#endif // GTEST_INTERNAL_HAS_STD_SPAN + // Some user-defined types for testing the universal value printer. // An anonymous enum type. @@ -1179,6 +1184,17 @@ TEST(PrintStlContainerTest, Vector) { EXPECT_EQ("{ 1, 2 }", Print(v)); } +TEST(PrintStlContainerTest, StdSpan) { +#if GTEST_INTERNAL_HAS_STD_SPAN + int a[] = {3, 6, 5}; + std::span s = a; + + EXPECT_EQ("{ 3, 6, 5 }", Print(s)); +#else + GTEST_SKIP() << "Does not have std::span."; +#endif // GTEST_INTERNAL_HAS_STD_SPAN +} + TEST(PrintStlContainerTest, LongSequence) { const int a[100] = {1, 2, 3}; const vector v(a, a + 100); diff --git a/googletest/test/gtest_environment_test.cc b/googletest/test/gtest_environment_test.cc index 122eaf3ca802..03657c7d89f1 100644 --- a/googletest/test/gtest_environment_test.cc +++ b/googletest/test/gtest_environment_test.cc @@ -40,16 +40,21 @@ namespace { enum FailureType { NO_FAILURE, NON_FATAL_FAILURE, FATAL_FAILURE }; +// Was SetUp run? +bool set_up_was_run; +// Was TearDown run? +bool tear_down_was_run; +// Was the TEST run? +bool test_was_run; + // For testing using global test environments. class MyEnvironment : public testing::Environment { public: - MyEnvironment() { Reset(); } - // Depending on the value of failure_in_set_up_, SetUp() will // generate a non-fatal failure, generate a fatal failure, or // succeed. void SetUp() override { - set_up_was_run_ = true; + set_up_was_run = true; switch (failure_in_set_up_) { case NON_FATAL_FAILURE: @@ -65,36 +70,18 @@ class MyEnvironment : public testing::Environment { // Generates a non-fatal failure. void TearDown() override { - tear_down_was_run_ = true; + tear_down_was_run = true; ADD_FAILURE() << "Expected non-fatal failure in global tear-down."; } - // Resets the state of the environment s.t. it can be reused. - void Reset() { - failure_in_set_up_ = NO_FAILURE; - set_up_was_run_ = false; - tear_down_was_run_ = false; - } - // We call this function to set the type of failure SetUp() should // generate. void set_failure_in_set_up(FailureType type) { failure_in_set_up_ = type; } - // Was SetUp() run? - bool set_up_was_run() const { return set_up_was_run_; } - - // Was TearDown() run? - bool tear_down_was_run() const { return tear_down_was_run_; } - private: FailureType failure_in_set_up_; - bool set_up_was_run_; - bool tear_down_was_run_; }; -// Was the TEST run? -bool test_was_run; - // The sole purpose of this TEST is to enable us to check whether it // was run. TEST(FooTest, Bar) { test_was_run = true; } @@ -112,67 +99,88 @@ void Check(bool condition, const char* msg) { // The 'failure' parameter specifies the type of failure that should // be generated by the global set-up. int RunAllTests(MyEnvironment* env, FailureType failure) { - env->Reset(); - env->set_failure_in_set_up(failure); + set_up_was_run = false; + tear_down_was_run = false; test_was_run = false; + env->set_failure_in_set_up(failure); testing::internal::GetUnitTestImpl()->ClearAdHocTestResult(); return RUN_ALL_TESTS(); } +// Registers a global test environment, and verifies that the +// registration function returns its argument. +MyEnvironment* RegisterTestEnv() { + MyEnvironment* const env = new MyEnvironment; + Check(testing::AddGlobalTestEnvironment(env) == env, + "AddGlobalTestEnvironment() should return its argument."); + return env; +} + +// Verifies that RUN_ALL_TESTS() runs the tests when the global +// set-up is successful. +void TestGlobalSetUp() { + MyEnvironment* const env = RegisterTestEnv(); + Check(RunAllTests(env, NO_FAILURE) != 0, + "RUN_ALL_TESTS() should return non-zero, as the global tear-down " + "should generate a failure."); + Check(test_was_run, + "The tests should run, as the global set-up should generate no " + "failure"); + Check(tear_down_was_run, + "The global tear-down should run, as the global set-up was run."); +} + +// Verifies that RUN_ALL_TESTS() runs the tests when the global +// set-up generates no fatal failure. +void TestTestsRun() { + MyEnvironment* const env = RegisterTestEnv(); + Check(RunAllTests(env, NON_FATAL_FAILURE) != 0, + "RUN_ALL_TESTS() should return non-zero, as both the global set-up " + "and the global tear-down should generate a non-fatal failure."); + Check(test_was_run, + "The tests should run, as the global set-up should generate no " + "fatal failure."); + Check(tear_down_was_run, + "The global tear-down should run, as the global set-up was run."); +} + +// Verifies that RUN_ALL_TESTS() runs no test when the global set-up +// generates a fatal failure. +void TestNoTestsRunSetUpFailure() { + MyEnvironment* const env = RegisterTestEnv(); + Check(RunAllTests(env, FATAL_FAILURE) != 0, + "RUN_ALL_TESTS() should return non-zero, as the global set-up " + "should generate a fatal failure."); + Check(!test_was_run, + "The tests should not run, as the global set-up should generate " + "a fatal failure."); + Check(tear_down_was_run, + "The global tear-down should run, as the global set-up was run."); +} + +// Verifies that RUN_ALL_TESTS() doesn't do global set-up or +// tear-down when there is no test to run. +void TestNoTestsSkipsSetUp() { + MyEnvironment* const env = RegisterTestEnv(); + GTEST_FLAG_SET(filter, "-*"); + Check(RunAllTests(env, NO_FAILURE) == 0, + "RUN_ALL_TESTS() should return zero, as there is no test to run."); + Check(!set_up_was_run, + "The global set-up should not run, as there is no test to run."); + Check(!tear_down_was_run, + "The global tear-down should not run, " + "as the global set-up was not run."); +} + } // namespace int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); - // Registers a global test environment, and verifies that the - // registration function returns its argument. - MyEnvironment* const env = new MyEnvironment; - Check(testing::AddGlobalTestEnvironment(env) == env, - "AddGlobalTestEnvironment() should return its argument."); - - // Verifies that RUN_ALL_TESTS() runs the tests when the global - // set-up is successful. - Check(RunAllTests(env, NO_FAILURE) != 0, - "RUN_ALL_TESTS() should return non-zero, as the global tear-down " - "should generate a failure."); - Check(test_was_run, - "The tests should run, as the global set-up should generate no " - "failure"); - Check(env->tear_down_was_run(), - "The global tear-down should run, as the global set-up was run."); - - // Verifies that RUN_ALL_TESTS() runs the tests when the global - // set-up generates no fatal failure. - Check(RunAllTests(env, NON_FATAL_FAILURE) != 0, - "RUN_ALL_TESTS() should return non-zero, as both the global set-up " - "and the global tear-down should generate a non-fatal failure."); - Check(test_was_run, - "The tests should run, as the global set-up should generate no " - "fatal failure."); - Check(env->tear_down_was_run(), - "The global tear-down should run, as the global set-up was run."); - - // Verifies that RUN_ALL_TESTS() runs no test when the global set-up - // generates a fatal failure. - Check(RunAllTests(env, FATAL_FAILURE) != 0, - "RUN_ALL_TESTS() should return non-zero, as the global set-up " - "should generate a fatal failure."); - Check(!test_was_run, - "The tests should not run, as the global set-up should generate " - "a fatal failure."); - Check(env->tear_down_was_run(), - "The global tear-down should run, as the global set-up was run."); - - // Verifies that RUN_ALL_TESTS() doesn't do global set-up or - // tear-down when there is no test to run. - 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(), - "The global set-up should not run, as there is no test to run."); - Check(!env->tear_down_was_run(), - "The global tear-down should not run, " - "as the global set-up was not run."); + TestGlobalSetUp(); + TestTestsRun(); + TestNoTestsRunSetUpFailure(); + TestNoTestsSkipsSetUp(); printf("PASS\n"); return 0; diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py index 85a0c33c982c..38fc90ff1f09 100755 --- a/googletest/test/gtest_help_test.py +++ b/googletest/test/gtest_help_test.py @@ -43,11 +43,22 @@ import sys from googletest.test import gtest_test_utils +FREEBSD = ('FreeBSD', 'GNU/kFreeBSD') +NETBSD = ('NetBSD',) +OPENBSD = ('OpenBSD',) + + +def is_bsd_based_os() -> bool: + """Determine whether or not the OS is BSD-based.""" + if os.name != 'posix': + return False + + return os.uname()[0] in (FREEBSD + NETBSD + OPENBSD) + + IS_DARWIN = os.name == 'posix' and os.uname()[0] == 'Darwin' 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_OPENBSD = os.name == 'posix' and os.uname()[0] == 'OpenBSD' IS_WINDOWS = os.name == 'nt' PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_') @@ -96,7 +107,7 @@ HELP_REGEX = re.compile( ) -def RunWithFlag(flag): +def run_with_flag(flag): """Runs gtest_help_test_ with the given flag. Returns: @@ -116,17 +127,14 @@ def RunWithFlag(flag): class GTestHelpTest(gtest_test_utils.TestCase): """Tests the --help flag and its equivalent forms.""" - def TestHelpFlag(self, flag): + def test_prints_help_with_full_flag(self): """Verifies correct behavior when help flag is specified. The right message must be printed and the tests must skipped when the given flag is specified. - - Args: - flag: A flag to pass to the binary or None. """ - exit_code, output = RunWithFlag(flag) + exit_code, output = run_with_flag('--help') if HAS_ABSL_FLAGS: # The Abseil flags library prints the ProgramUsageMessage() with # --help and returns 1. @@ -136,7 +144,7 @@ class GTestHelpTest(gtest_test_utils.TestCase): self.assertTrue(HELP_REGEX.search(output), output) - if IS_DARWIN or IS_LINUX or IS_GNUHURD or IS_GNUKFREEBSD or IS_OPENBSD: + if IS_DARWIN or IS_LINUX or IS_GNUHURD or is_bsd_based_os(): self.assertIn(STREAM_RESULT_TO_FLAG, output) else: self.assertNotIn(STREAM_RESULT_TO_FLAG, output) @@ -146,53 +154,27 @@ class GTestHelpTest(gtest_test_utils.TestCase): else: self.assertNotIn(DEATH_TEST_STYLE_FLAG, output) - def TestUnknownFlagWithAbseil(self, flag): - """Verifies correct behavior when an unknown flag is specified. - - The right message must be printed and the tests must - skipped when the given flag is specified. - - Args: - flag: A flag to pass to the binary or None. - """ - exit_code, output = RunWithFlag(flag) - self.assertEqual(1, exit_code) - self.assertIn('ERROR: Unknown command line flag', output) - - def TestNonHelpFlag(self, flag): + def test_runs_tests_without_help_flag(self): """Verifies correct behavior when no help flag is specified. Verifies that when no help flag is specified, the tests are run and the help message is not printed. - - Args: - flag: A flag to pass to the binary or None. """ - exit_code, output = RunWithFlag(flag) + exit_code, output = run_with_flag(None) self.assertNotEqual(exit_code, 0) self.assertFalse(HELP_REGEX.search(output), output) - def testPrintsHelpWithFullFlag(self): - self.TestHelpFlag('--help') - - def testRunsTestsWithoutHelpFlag(self): - """Verifies correct behavior when no help flag is specified. - - Verifies that when no help flag is specified, the tests are run - and the help message is not printed. - """ - - self.TestNonHelpFlag(None) - - def testRunsTestsWithGtestInternalFlag(self): + def test_runs_tests_with_gtest_internal_flag(self): """Verifies correct behavior when internal testing flag is specified. Verifies that the tests are run and no help message is printed when a flag starting with Google Test prefix and 'internal_' is supplied. """ - self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING) + exit_code, output = run_with_flag(INTERNAL_FLAG_FOR_TESTING) + self.assertNotEqual(exit_code, 0) + self.assertFalse(HELP_REGEX.search(output), output) if __name__ == '__main__': diff --git a/googletest/test/gtest_json_test_utils.py b/googletest/test/gtest_json_test_utils.py index 86a5925b079e..694a7a60db87 100644 --- a/googletest/test/gtest_json_test_utils.py +++ b/googletest/test/gtest_json_test_utils.py @@ -51,6 +51,9 @@ def normalize(obj): elif key == 'failure': value = re.sub(r'^.*[/\\](.*:)\d+\n', '\\1*\n', value) return re.sub(r'Stack trace:\n(.|\n)*', 'Stack trace:\n*', value) + elif key == 'message': + value = re.sub(r'^.*[/\\](.*:)\d+\n', '\\1*\n', value) + return re.sub(r'Stack trace:\n(.|\n)*', 'Stack trace:\n*', value) elif key == 'file': return re.sub(r'^.*[/\\](.*)', '\\1', value) else: diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc index f67b7886e1a3..55103d0e77f8 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -61,7 +61,6 @@ int g_environment_tear_down_count = 0; class MyEnvironment : public testing::Environment { public: - MyEnvironment() = default; void SetUp() override { g_environment_set_up_count++; } void TearDown() override { g_environment_tear_down_count++; } }; @@ -117,6 +116,7 @@ void ResetCounts() { g_should_pass_count = 0; g_death_test_count = 0; g_param_test_count = 0; + testing::AddGlobalTestEnvironment(new MyEnvironment); } // Checks that the count for each test is expected. @@ -197,8 +197,6 @@ void TestRepeatWithFilterForFailedTests(int repeat) { int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); - testing::AddGlobalTestEnvironment(new MyEnvironment); - TestRepeatUnspecified(); TestRepeat(0); TestRepeat(1); diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 6caa03fd34d9..5ded865074df 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -422,11 +422,14 @@ TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) { EXPECT_EQ("-1234567.89", FormatTimeInMillisAsSeconds(-1234567890)); } +// TODO: b/287046337 - In emscripten, local time zone modification is not +// supported. +#if !defined(__EMSCRIPTEN__) // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion // for particular dates below was verified in Python using // datetime.datetime.fromutctimestamp(/1000). -// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we +// FormatEpochTimeInMillisAsIso8601 depends on the local timezone, so we // have to set up a particular timezone to obtain predictable results. class FormatEpochTimeInMillisAsIso8601Test : public Test { public: @@ -445,9 +448,8 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test { } GTEST_DISABLE_MSC_DEPRECATED_POP_() - // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We - // cannot use the local time zone because the function's output depends - // on the time zone. + // Set the local time zone for FormatEpochTimeInMillisAsIso8601 to be + // a fixed time zone for reproducibility purposes. SetTimeZone("UTC+00"); } @@ -514,6 +516,8 @@ TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0)); } +#endif // __EMSCRIPTEN__ + #ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" #pragma option push -w-ccc -w-rch @@ -2159,7 +2163,7 @@ class UnitTestRecordPropertyTestEnvironment : public Environment { }; // This will test property recording outside of any test or test case. -static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ = +GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static Environment* record_property_env = AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment); // This group of tests is for predicate assertions (ASSERT_PRED*, etc) @@ -4113,7 +4117,7 @@ TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { EXPECT_THROW(throw 1, int); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), ""); - EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), ""); + EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw n, const char*), ""); EXPECT_NO_THROW(n++); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), ""); EXPECT_ANY_THROW(throw 1); @@ -4168,8 +4172,8 @@ TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { #endif TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) - EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. " - << "It's a compilation test only."; + EXPECT_NO_FATAL_FAILURE(FAIL()) + << "This should never be executed. " << "It's a compilation test only."; else ; // NOLINT @@ -6667,6 +6671,9 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { SetEnv("TERM", "xterm-kitty"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + SetEnv("TERM", "alacritty"); // TERM supports colors. + EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. + SetEnv("TERM", "xterm-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. @@ -6691,15 +6698,16 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { SetEnv("TERM", "linux"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. - SetEnv("TERM", "cygwin"); // TERM supports colors. + SetEnv("TERM", "cygwin"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. #endif // GTEST_OS_WINDOWS } // Verifies that StaticAssertTypeEq works in a namespace scope. -static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq(); -static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ = +GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy1 = + StaticAssertTypeEq(); +GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy2 = StaticAssertTypeEq(); // Verifies that StaticAssertTypeEq works in a class. @@ -7475,22 +7483,6 @@ TEST(NativeArrayTest, WorksForTwoDimensionalArray) { EXPECT_EQ(a, na.begin()); } -// IndexSequence -TEST(IndexSequence, MakeIndexSequence) { - using testing::internal::IndexSequence; - using testing::internal::MakeIndexSequence; - EXPECT_TRUE( - (std::is_same, MakeIndexSequence<0>::type>::value)); - EXPECT_TRUE( - (std::is_same, MakeIndexSequence<1>::type>::value)); - EXPECT_TRUE( - (std::is_same, MakeIndexSequence<2>::type>::value)); - EXPECT_TRUE(( - std::is_same, MakeIndexSequence<3>::type>::value)); - EXPECT_TRUE( - (std::is_base_of, MakeIndexSequence<3>>::value)); -} - // ElemFromList TEST(ElemFromList, Basic) { using testing::internal::ElemFromList; diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py index 422569e48398..c3fea2c0a3a1 100755 --- a/googletest/test/gtest_xml_output_unittest.py +++ b/googletest/test/gtest_xml_output_unittest.py @@ -112,20 +112,23 @@ Invalid characters in brackets []%(stack)s]]> - + - + - + diff --git a/googletest_deps.bzl b/googletest_deps.bzl index e25f5a1ada6d..65fc48c364ed 100644 --- a/googletest_deps.bzl +++ b/googletest_deps.bzl @@ -1,22 +1,28 @@ """Load dependencies needed to use the googletest library as a 3rd-party consumer.""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") +load("//:fake_fuchsia_sdk.bzl", "fake_fuchsia_sdk") def googletest_deps(): """Loads common dependencies needed to use the googletest library.""" if not native.existing_rule("com_googlesource_code_re2"): http_archive( - name = "com_googlesource_code_re2", # 2023-03-17T11:36:51Z - sha256 = "cb8b5312a65f2598954545a76e8bce913f35fbb3a21a5c88797a4448e9f9b9d9", - strip_prefix = "re2-578843a516fd1da7084ae46209a75f3613b6065e", - urls = ["https://github.com/google/re2/archive/578843a516fd1da7084ae46209a75f3613b6065e.zip"], + name = "com_googlesource_code_re2", + sha256 = "eb2df807c781601c14a260a507a5bb4509be1ee626024cb45acbd57cb9d4032b", + strip_prefix = "re2-2024-07-02", + urls = ["https://github.com/google/re2/releases/download/2024-07-02/re2-2024-07-02.tar.gz"], ) if not native.existing_rule("com_google_absl"): http_archive( - name = "com_google_absl", # 2023-08-01T14:59:13Z - sha256 = "d2c09bf3b3aba57ad87a56082020bee2948445407756e92ddaf3595396086853", - strip_prefix = "abseil-cpp-22091f4c0d6626b3ef40446ce3d4ccab19425ca3", - urls = ["https://github.com/abseil/abseil-cpp/archive/22091f4c0d6626b3ef40446ce3d4ccab19425ca3.zip"], + name = "com_google_absl", + sha256 = "733726b8c3a6d39a4120d7e45ea8b41a434cdacde401cba500f14236c49b39dc", + strip_prefix = "abseil-cpp-20240116.2", + urls = ["https://github.com/abseil/abseil-cpp/releases/download/20240116.2/abseil-cpp-20240116.2.tar.gz"], + ) + + if not native.existing_rule("fuchsia_sdk"): + fake_fuchsia_sdk( + name = "fuchsia_sdk", )