Compare commits

..

3 Commits

Author SHA1 Message Date
Derek Mauro
b514bdc898
Update version strings to 1.15.2 (#4583) 2024-07-31 09:34:46 -04:00
Derek Mauro
075196ca06
Remove auto-detection of Python toolchain from MODULE.bazel (#4582)
since it affects downstream users

The correct solution appears to be
https://rules-python.readthedocs.io/en/stable/toolchains.html#library-modules-with-dev-only-python-usage

This change also includes a workaround for the new mechanism creating
paths that are too long for Windows to handle.

Backport of 3e3b44c300b21eb996a2957782421bc0f157af18
2024-07-30 20:25:53 -04:00
Derek Mauro
e397860881
Prepare for v1.15.0 (#4574) 2024-07-15 13:46:49 -04:00
88 changed files with 1565 additions and 3986 deletions

View File

@ -30,8 +30,6 @@
#
# Bazel Build for Google C++ Testing Framework(Google Test)
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
@ -85,10 +83,6 @@ cc_library(
)
# Google Test including Google Mock
# For an actual test, use `gtest` and also `gtest_main` if you depend on gtest's
# main(). For a library, use `gtest_for_library` instead if the library can be
# testonly.
cc_library(
name = "gtest",
srcs = glob(
@ -144,16 +138,19 @@ cc_library(
}),
deps = select({
":has_absl": [
"@abseil-cpp//absl/container:flat_hash_set",
"@abseil-cpp//absl/debugging:failure_signal_handler",
"@abseil-cpp//absl/debugging:stacktrace",
"@abseil-cpp//absl/debugging:symbolize",
"@abseil-cpp//absl/flags:flag",
"@abseil-cpp//absl/flags:parse",
"@abseil-cpp//absl/flags:reflection",
"@abseil-cpp//absl/flags:usage",
"@abseil-cpp//absl/strings",
"@re2",
"@com_google_absl//absl/container:flat_hash_set",
"@com_google_absl//absl/debugging:failure_signal_handler",
"@com_google_absl//absl/debugging:stacktrace",
"@com_google_absl//absl/debugging:symbolize",
"@com_google_absl//absl/flags:flag",
"@com_google_absl//absl/flags:parse",
"@com_google_absl//absl/flags:reflection",
"@com_google_absl//absl/flags:usage",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/types:any",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:variant",
"@com_googlesource_code_re2//:re2",
],
"//conditions:default": [],
}) + select({
@ -163,22 +160,13 @@ cc_library(
# Otherwise, builds targeting Fuchsia would fail to compile.
":fuchsia": [
"@fuchsia_sdk//pkg/fdio",
"@fuchsia_sdk//pkg/syslog",
"@fuchsia_sdk//pkg/zx",
],
"//conditions:default": [],
}),
)
# `gtest`, but testonly. See guidance on `gtest` for when to use this.
alias(
name = "gtest_for_library",
testonly = True,
actual = ":gtest",
)
# Implements main() for tests using gtest. Prefer to depend on `gtest` as well
# to ensure compliance with the layering_check Bazel feature where only the
# direct hdrs values are available.
cc_library(
name = "gtest_main",
srcs = ["googlemock/src/gmock_main.cc"],

View File

@ -1,10 +1,10 @@
# Note: CMake support is community-based. The maintainers do not use CMake
# internally.
cmake_minimum_required(VERSION 3.16)
cmake_minimum_required(VERSION 3.13)
project(googletest-distribution)
set(GOOGLETEST_VERSION 1.16.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)

View File

@ -32,50 +32,38 @@
module(
name = "googletest",
version = "head",
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 = "20250814.0",
)
bazel_dep(
name = "platforms",
version = "0.0.11",
)
bazel_dep(
name = "re2",
version = "2024-07-02.bcr.1",
)
bazel_dep(name = "abseil-cpp",
version = "20240116.2",
repo_name = "com_google_absl")
bazel_dep(
name = "rules_cc",
version = "0.2.8"
)
bazel_dep(name = "platforms",
version = "0.0.10")
bazel_dep(
name = "rules_python",
version = "1.3.0",
dev_dependency = True,
)
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(
ignore_root_user_error = True,
is_default = True,
python_version = "3.12",
dev_dependency = True
)
# See fake_fuchsia_sdk.bzl for instructions on how to override this with a real SDK, if needed.
fuchsia_sdk = use_extension("//:fake_fuchsia_sdk.bzl", "fuchsia_sdk")
fuchsia_sdk.create_fake()
use_repo(fuchsia_sdk, "fuchsia_sdk")
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")

View File

@ -2,19 +2,27 @@
### Announcements
#### Live at Head
GoogleTest now follows the
[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
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.15.0`).
#### Documentation Updates
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.17.0
#### Release 1.15.0
[Release 1.17.0](https://github.com/google/googletest/releases/tag/v1.17.0) is
[Release 1.15.0](https://github.com/google/googletest/releases/tag/v1.15.0) is
now available.
The 1.17.x branch
[requires at least C++17](https://opensource.google/documentation/policies/cplusplus-support#c_language_standard).
The 1.15.x branch requires at least C++14.
#### Continuous Integration

View File

@ -1,34 +1,4 @@
# 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.
workspace(name = "googletest")
workspace(name = "com_google_googletest")
load("//:googletest_deps.bzl", "googletest_deps")
googletest_deps()
@ -36,26 +6,27 @@ googletest_deps()
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rules_python",
sha256 = "2cc26bbd53854ceb76dd42a834b1002cd4ba7f8df35440cf03482e045affc244",
strip_prefix = "rules_python-1.3.0",
url = "https://github.com/bazelbuild/rules_python/releases/download/1.3.0/rules_python-1.3.0.tar.gz",
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/1.1.0
# https://github.com/bazelbuild/rules_python/releases/tag/0.29.0
load("@rules_python//python:repositories.bzl", "py_repositories")
py_repositories()
http_archive(
name = "platforms",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.11/platforms-0.0.11.tar.gz",
"https://github.com/bazelbuild/platforms/releases/download/0.0.11/platforms-0.0.11.tar.gz",
],
sha256 = "29742e87275809b5e598dc2f04d86960cc7a55b3067d97221c9abbc9926bff0f",
name = "bazel_skylib",
sha256 = "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94",
urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz"],
)
load("@bazel_features//:deps.bzl", "bazel_features_deps")
bazel_features_deps()
load("@rules_cc//cc:extensions.bzl", "compatibility_proxy_repo")
compatibility_proxy_repo()
http_archive(
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",
)

View File

@ -31,91 +31,62 @@
set -euox pipefail
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20250430"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20250430"
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
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi
# Use Bazel Vendor mode to reduce reliance on external dependencies.
# See https://bazel.build/external/vendor and the Dockerfile for
# an explaination of how this works.
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" ]]; then
DOCKER_EXTRA_ARGS="--mount type=bind,source=${KOKORO_GFILE_DIR}/distdir,target=/distdir,readonly --env=BAZEL_VENDOR_ARCHIVE=/distdir/googletest_vendor.tar.gz ${DOCKER_EXTRA_ARGS:-}"
BAZEL_EXTRA_ARGS="--vendor_dir=/googletest_vendor ${BAZEL_EXTRA_ARGS:-}"
fi
if [[ -z ${STD:-} ]]; then
STD="c++17 c++20 c++23"
STD="c++14 c++17 c++20"
fi
# Test CMake + GCC
for cmake_off_on in OFF ON; do
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--tmpfs="/build:exec" \
--workdir="/build" \
--rm \
--env="CC=/usr/local/bin/gcc" \
--env=CXXFLAGS="-Werror -Wdeprecated" \
${LINUX_LATEST_CONTAINER} \
/bin/bash -c "
cmake /src \
-DCMAKE_CXX_STANDARD=17 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on} && \
make -j$(nproc) && \
ctest -j$(nproc) --output-on-failure"
done
# Test CMake + Clang
for cmake_off_on in OFF ON; do
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--tmpfs="/build:exec" \
--workdir="/build" \
--rm \
--env="CC=/opt/llvm/clang/bin/clang" \
--env=CXXFLAGS="-Werror -Wdeprecated --gcc-toolchain=/usr/local" \
${LINUX_LATEST_CONTAINER} \
/bin/bash -c "
cmake /src \
-DCMAKE_CXX_STANDARD=17 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on} && \
make -j$(nproc) && \
ctest -j$(nproc) --output-on-failure"
# Test the CMake build
for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
for cmake_off_on in OFF ON; do
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--tmpfs="/build:exec" \
--workdir="/build" \
--rm \
--env="CC=${cc}" \
--env=CXXFLAGS="-Werror -Wdeprecated" \
${LINUX_LATEST_CONTAINER} \
/bin/bash -c "
cmake /src \
-DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on} && \
make -j$(nproc) && \
ctest -j$(nproc) --output-on-failure"
done
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" \
--rm \
--env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=c++17" \
${DOCKER_EXTRA_ARGS:-} \
--env="BAZEL_CXXOPTS=-std=c++14" \
${LINUX_GCC_FLOOR_CONTAINER} \
/bin/bash --login -c "
/usr/local/bin/bazel test ... \
--copt=\"-Wall\" \
--copt=\"-Werror\" \
--copt=\"-Wuninitialized\" \
--copt=\"-Wundef\" \
--copt=\"-Wno-error=pragmas\" \
--enable_bzlmod=false \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wundef" \
--copt="-Wno-error=pragmas" \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors \
${BAZEL_EXTRA_ARGS:-}"
--test_output=errors
# Test GCC
for std in ${STD}; do
@ -126,21 +97,18 @@ for std in ${STD}; do
--rm \
--env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=${std}" \
${DOCKER_EXTRA_ARGS:-} \
${LINUX_LATEST_CONTAINER} \
/bin/bash --login -c "
/usr/local/bin/bazel test ... \
--copt=\"-Wall\" \
--copt=\"-Werror\" \
--copt=\"-Wuninitialized\" \
--copt=\"-Wundef\" \
--define=\"absl=${absl}\" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors \
${BAZEL_EXTRA_ARGS:-}"
/usr/local/bin/bazel test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors
done
done
@ -153,22 +121,19 @@ for std in ${STD}; do
--rm \
--env="CC=/opt/llvm/clang/bin/clang" \
--env="BAZEL_CXXOPTS=-std=${std}" \
${DOCKER_EXTRA_ARGS:-} \
${LINUX_LATEST_CONTAINER} \
/bin/bash --login -c "
/usr/local/bin/bazel test ... \
--copt=\"--gcc-toolchain=/usr/local\" \
--copt=\"-Wall\" \
--copt=\"-Werror\" \
--copt=\"-Wuninitialized\" \
--copt=\"-Wundef\" \
--define=\"absl=${absl}\" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--linkopt=\"--gcc-toolchain=/usr/local\" \
--show_timestamps \
--test_output=errors \
${BAZEL_EXTRA_ARGS:-}"
/usr/local/bin/bazel test ... \
--copt="--gcc-toolchain=/usr/local" \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--linkopt="--gcc-toolchain=/usr/local" \
--show_timestamps \
--test_output=errors
done
done

View File

@ -31,9 +31,6 @@
set -euox pipefail
# Use Xcode 16.0
sudo xcode-select -s /Applications/Xcode_16.0.app/Contents/Developer
if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi
@ -43,20 +40,20 @@ for cmake_off_on in OFF ON; do
BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)
cd ${BUILD_DIR}
time cmake ${GTEST_ROOT} \
-DCMAKE_CXX_STANDARD=17 \
-DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on}
time make -j$(nproc)
time make
time ctest -j$(nproc) --output-on-failure
done
# Test the Bazel build
# If we are running on Kokoro, check for a versioned Bazel binary.
KOKORO_GFILE_BAZEL_BIN="bazel-8.2.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}
@ -64,24 +61,17 @@ else
BAZEL_BIN="bazel"
fi
# Use Bazel Vendor mode to reduce reliance on external dependencies.
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" ]]; then
tar -xf "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" -C "${HOME}/"
BAZEL_EXTRA_ARGS="--vendor_dir=${HOME}/googletest_vendor ${BAZEL_EXTRA_ARGS:-}"
fi
cd ${GTEST_ROOT}
for absl in 0 1; do
${BAZEL_BIN} test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wundef" \
--cxxopt="-std=c++17" \
--cxxopt="-std=c++14" \
--define="absl=${absl}" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors \
${BAZEL_EXTRA_ARGS:-}
--test_output=errors
done

View File

@ -1,6 +1,6 @@
SETLOCAL ENABLEDELAYEDEXPANSION
SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-8.2.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
@ -11,18 +11,21 @@ SET CTEST_OUTPUT_ON_FAILURE=1
SET CMAKE_BUILD_PARALLEL_LEVEL=16
SET CTEST_PARALLEL_LEVEL=16
SET GTEST_ROOT=%~dp0\..
IF EXIST git\googletest (
CD git\googletest
) ELSE IF EXIST github\googletest (
CD github\googletest
)
IF %errorlevel% neq 0 EXIT /B 1
:: ----------------------------------------------------------------------------
:: CMake
SET CMAKE_BUILD_PATH=cmake_msvc2022
MKDIR %CMAKE_BUILD_PATH%
CD %CMAKE_BUILD_PATH%
MKDIR cmake_msvc2022
CD cmake_msvc2022
%CMAKE_BIN% %GTEST_ROOT% ^
%CMAKE_BIN% .. ^
-G "Visual Studio 17 2022" ^
-DCMAKE_CXX_STANDARD=17 ^
-DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^
-DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^
-DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^
@ -37,8 +40,8 @@ IF %errorlevel% neq 0 EXIT /B 1
%CTEST_BIN% -C Debug --timeout 600
IF %errorlevel% neq 0 EXIT /B 1
CD %GTEST_ROOT%
RMDIR /S /Q %CMAKE_BUILD_PATH%
CD ..
RMDIR /S /Q cmake_msvc2022
:: ----------------------------------------------------------------------------
:: Bazel
@ -47,39 +50,14 @@ RMDIR /S /Q %CMAKE_BUILD_PATH%
:: 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
:: Use Bazel Vendor mode to reduce reliance on external dependencies.
IF EXIST "%KOKORO_GFILE_DIR%\distdir\googletest_vendor.tar.gz" (
tar --force-local -xf "%KOKORO_GFILE_DIR%\distdir\googletest_vendor.tar.gz" -C c:
SET VENDOR_FLAG=--vendor_dir=c:\googletest_vendor
) ELSE (
SET VENDOR_FLAG=
)
:: C++17
%BAZEL_EXE% ^
--output_user_root=C:\tmp ^
test ... ^
--compilation_mode=dbg ^
--copt=/std:c++17 ^
--copt=/std:c++14 ^
--copt=/WX ^
--enable_bzlmod=true ^
--keep_going ^
--test_output=errors ^
--test_tag_filters=-no_test_msvc2017 ^
%VENDOR_FLAG%
IF %errorlevel% neq 0 EXIT /B 1
:: C++20
%BAZEL_EXE% ^
--output_user_root=C:\tmp ^
test ... ^
--compilation_mode=dbg ^
--copt=/std:c++20 ^
--copt=/WX ^
--enable_bzlmod=true ^
--keep_going ^
--test_output=errors ^
--test_tag_filters=-no_test_msvc2017 ^
%VENDOR_FLAG%
--test_tag_filters=-no_test_msvc2017
IF %errorlevel% neq 0 EXIT /B 1

View File

@ -7,15 +7,15 @@
{% seo %}
<link rel="stylesheet" href="{{ "/assets/css/style.css?v=" | append: site.github.build_revision | relative_url }}">
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-9PTP6FW1M5"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-9PTP6FW1M5');
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-197576187-1', { 'storage': 'none' });
ga('set', 'referrer', document.referrer.split('?')[0]);
ga('set', 'location', window.location.href.split('?')[0]);
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
</head>
<body>
<div class="sidebar">

View File

@ -286,7 +286,7 @@ For example:
```c++
TEST(SkipTest, DoesSkip) {
GTEST_SKIP() << "Skipping single test";
FAIL(); // Won't fail; it won't be executed
EXPECT_EQ(0, 1); // Won't fail; it won't be executed
}
class SkipFixture : public ::testing::Test {
@ -298,7 +298,7 @@ class SkipFixture : public ::testing::Test {
// Tests for SkipFixture won't be executed.
TEST_F(SkipFixture, SkipsOneTest) {
FAIL(); // Won't fail; it won't be executed
EXPECT_EQ(5, 7); // Won't fail
}
```
@ -349,8 +349,7 @@ void AbslStringify(Sink& sink, EnumWithStringify e) {
{: .callout .note}
Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its
string. For more information about supported operations on `AbslStringify()`'s
sink, see
[the `AbslStringify()` documentation](https://abseil.io/docs/cpp/guides/abslstringify).
sink, see go/abslstringify.
`AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier
within its own format strings to perform type deduction. `Point` above could be
@ -404,53 +403,7 @@ EXPECT_TRUE(IsCorrectPointIntVector(point_ints))
```
For more details regarding `AbslStringify()` and its integration with other
libraries, see
[the documentation](https://abseil.io/docs/cpp/guides/abslstringify).
## Regular Expression Syntax
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](https://pubs.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](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
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period
(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular
expressions.):
Expression | Meaning
---------- | --------------------------------------------------------------
`c` | matches any literal character `c`
`\\d` | matches any decimal digit
`\\D` | matches any character that's not a decimal digit
`\\f` | matches `\f`
`\\n` | matches `\n`
`\\r` | matches `\r`
`\\s` | matches any ASCII whitespace, including `\n`
`\\S` | matches any character that's not a whitespace
`\\t` | matches `\t`
`\\v` | matches `\v`
`\\w` | matches any letter, `_`, or decimal digit
`\\W` | matches any character that `\\w` doesn't match
`\\c` | matches any literal character `c`, which must be a punctuation
`.` | matches any single character except `\n`
`A?` | matches 0 or 1 occurrences of `A`
`A*` | matches 0 or many occurrences of `A`
`A+` | matches 1 or many occurrences of `A`
`^` | matches the beginning of a string (not that of each line)
`$` | matches the end of a string (not that of each line)
`xy` | matches `x` followed by `y`
To help you determine which capability is available on your system, GoogleTest
defines macros to govern which regular expression it is using. The macros are:
`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
tests to work in all cases, you can either `#if` on these macros or use the more
limited syntax only.
libraries, see go/abslstringify.
## Death Tests
@ -463,7 +416,7 @@ corruption, security holes, or worse. Hence it is vitally important to test that
such assertion statements work as expected.
Since these precondition checks cause the processes to die, we call such tests
*death tests*. More generally, any test that checks that a program terminates
_death tests_. More generally, any test that checks that a program terminates
(except by throwing an exception) in an expected fashion is also a death test.
Note that if a piece of code throws an exception, we don't consider it "death"
@ -509,12 +462,6 @@ verifies that:
exit with exit code 0, and
* calling `KillProcess()` kills the process with signal `SIGKILL`.
{: .callout .warning}
Warning: If your death test contains mocks and is expecting a specific exit
code, then you must allow the mock objects to be leaked via `Mock::AllowLeak`.
This is because the mock leak detector will exit with its own error code if it
detects a leak.
The test function body may contain other assertions and statements as well, if
necessary.
@ -556,6 +503,51 @@ TEST_F(FooDeathTest, DoesThat) {
}
```
### Regular Expression Syntax
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](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](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
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period
(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular
expressions.):
Expression | Meaning
---------- | --------------------------------------------------------------
`c` | matches any literal character `c`
`\\d` | matches any decimal digit
`\\D` | matches any character that's not a decimal digit
`\\f` | matches `\f`
`\\n` | matches `\n`
`\\r` | matches `\r`
`\\s` | matches any ASCII whitespace, including `\n`
`\\S` | matches any character that's not a whitespace
`\\t` | matches `\t`
`\\v` | matches `\v`
`\\w` | matches any letter, `_`, or decimal digit
`\\W` | matches any character that `\\w` doesn't match
`\\c` | matches any literal character `c`, which must be a punctuation
`.` | matches any single character except `\n`
`A?` | matches 0 or 1 occurrences of `A`
`A*` | matches 0 or many occurrences of `A`
`A+` | matches 1 or many occurrences of `A`
`^` | matches the beginning of a string (not that of each line)
`$` | matches the end of a string (not that of each line)
`xy` | matches `x` followed by `y`
To help you determine which capability is available on your system, GoogleTest
defines macros to govern which regular expression it is using. The macros are:
`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
tests to work in all cases, you can either `#if` on these macros or use the more
limited syntax only.
### How It Works
See [Death Assertions](reference/assertions.md#death) in the Assertions
@ -735,7 +727,7 @@ Some tips on using `SCOPED_TRACE`:
### Propagating Fatal Failures
A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
when they fail they only abort the *current function*, not the entire test. For
when they fail they only abort the _current function_, not the entire test. For
example, the following test will segfault:
```c++
@ -1450,19 +1442,17 @@ are two cases to consider:
To test them, we use the following special techniques:
* Both static functions and definitions/declarations in an unnamed namespace
are only visible within the same translation unit. To test them, move the
private code into the `foo::internal` namespace, where `foo` is the
namespace your project normally uses, and put the private declarations in a
`*-internal.h` file. Your production `.cc` files and your tests are allowed
to include this internal header, but your clients are not. This way, you can
fully test your internal implementation without leaking it to your clients.
are only visible within the same translation unit. To test them, you can
`#include` the entire `.cc` file being tested in your `*_test.cc` file.
(#including `.cc` files is not a good way to reuse code - you should not do
this in production code!)
{: .callout .note}
NOTE: It is also technically *possible* to `#include` the entire `.cc` file
being tested in your `*_test.cc` file to test static functions and
definitions/declarations in an unnamed namespace. However, this technique is
**not recommended** by this documentation and it is only presented here for the
sake of completeness.
However, a better approach is to move the private code into the
`foo::internal` namespace, where `foo` is the namespace your project
normally uses, and put the private declarations in a `*-internal.h` file.
Your production `.cc` files and your tests are allowed to include this
internal header, but your clients are not. This way, you can fully test your
internal implementation without leaking it to your clients.
* Private class members are only accessible from within the class or by
friends. To access a class' private members, you can declare your test
@ -1475,7 +1465,10 @@ sake of completeness.
Another way to test private members is to refactor them into an
implementation class, which is then declared in a `*-internal.h` file. Your
clients aren't allowed to include this header but your tests can.
clients aren't allowed to include this header but your tests can. Such is
called the
[Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/)
(Private Implementation) idiom.
Or, you can declare an individual test as a friend of your class by adding
this line in the class body:
@ -1930,35 +1923,6 @@ the `--gtest_also_run_disabled_tests` flag or set the
You can combine this with the `--gtest_filter` flag to further select which
disabled tests to run.
### Enforcing Having At Least One Test Case
A not uncommon programmer mistake is to write a test program that has no test
case linked in. This can happen, for example, when you put test case definitions
in a library and the library is not marked as "always link".
To catch such mistakes, run the test program with the
`--gtest_fail_if_no_test_linked` flag or set the `GTEST_FAIL_IF_NO_TEST_LINKED`
environment variable to a value other than `0`. Now the program will fail if no
test case is linked in.
Note that *any* test case linked in makes the program valid for the purpose of
this check. In particular, even a disabled test case suffices.
### Enforcing Running At Least One Test Case
In addition to enforcing that tests are defined in the binary with
`--gtest_fail_if_no_test_linked`, it is also possible to enforce that a test
case was actually executed to ensure that resources are not consumed by tests
that do nothing.
To catch such optimization opportunities, run the test program with the
`--gtest_fail_if_no_test_selected` flag or set the
`GTEST_FAIL_IF_NO_TEST_SELECTED` environment variable to a value other than `0`.
A test is considered selected if it begins to run, even if it is later skipped
via `GTEST_SKIP`. Thus, `DISABLED` tests do not count as selected and neither do
tests that are not matched by `--gtest_filter`.
### Repeating the Tests
Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it
@ -2418,7 +2382,7 @@ IMPORTANT: The exact format of the JSON document is subject to change.
#### Detecting Test Premature Exit
Google Test implements the *premature-exit-file* protocol for test runners to
Google Test implements the _premature-exit-file_ protocol for test runners to
catch any kind of unexpected exits of test programs. Upon start, Google Test
creates the file which will be automatically deleted after all work has been
finished. Then, the test runner can check if this file exists. In case the file

View File

@ -511,6 +511,19 @@ However, there are cases where you have to define your own:
list of the constructor. (Early versions of `gcc` doesn't force you to
initialize the const member. It's a bug that has been fixed in `gcc 4`.)
## Why does ASSERT_DEATH complain about previous threads that were already joined?
With the Linux pthread library, there is no turning back once you cross the line
from a single thread to multiple threads. The first time you create a thread, a
manager thread is created in addition, so you get 3, not 2, threads. Later when
the thread you create joins the main thread, the thread count decrements by 1,
but the manager thread will never be killed, so you still have 2 threads, which
means you cannot safely run a death test.
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`?
GoogleTest does not interleave tests from different test suites. That is, it

View File

@ -130,7 +130,7 @@ TEST(BarTest, DoesThis) {
## Setting Default Actions {#OnCall}
gMock has a **built-in default action** for any function that returns `void`,
`bool`, a numeric value, or a pointer. In C++11, it additionally returns
`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
the default-constructed value, if one exists for the given type.
To customize the default action for functions with return type `T`, use

View File

@ -177,7 +177,7 @@ class StackInterface {
template <typename Elem>
class MockStack : public StackInterface<Elem> {
...
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(int, GetSize, (), (override));
MOCK_METHOD(void, Push, (const Elem& x), (override));
};
```
@ -900,16 +900,15 @@ using ::testing::Not;
Matchers are function objects, and parametrized matchers can be composed just
like any other function. However because their types can be long and rarely
provide meaningful information, it can be easier to express them with template
parameters and `auto`. For example,
provide meaningful information, it can be easier to express them with C++14
generic lambdas to avoid specifying types. For example,
```cpp
using ::testing::Contains;
using ::testing::Property;
template <typename SubMatcher>
inline constexpr auto HasFoo(const SubMatcher& sub_matcher) {
return Property("foo", &MyClass::foo, Contains(sub_matcher));
inline constexpr auto HasFoo = [](const auto& f) {
return Property("foo", &MyClass::foo, Contains(f));
};
...
EXPECT_THAT(x, HasFoo("blah"));
@ -937,8 +936,8 @@ casts a matcher `m` to type `Matcher<T>`. To ensure safety, gMock checks that
floating-point numbers), the conversion from `T` to `U` is not lossy (in
other words, any value representable by `T` can also be represented by `U`);
and
3. When `U` is a non-const reference, `T` must also be a reference (as the
underlying matcher may be interested in the address of the `U` value).
3. When `U` is a reference, `T` must also be a reference (as the underlying
matcher may be interested in the address of the `U` value).
The code won't compile if any of these conditions isn't met.
@ -3388,9 +3387,9 @@ With this definition, the above assertion will give a better message:
#### Using EXPECT_ Statements in Matchers
You can also use `EXPECT_...` 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:
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, "") {
@ -3420,14 +3419,14 @@ itself, as gMock already prints it for you.
#### 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 any type where
the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the
`Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`,
`arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be
`unsigned long`; and so on.
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
any type where the value of `(arg % 7) == 0` can be implicitly converted to a
`bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an
`int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will
be `unsigned long`; and so on.
### Writing New Parameterized Matchers Quickly
@ -3568,15 +3567,10 @@ just based on the number of parameters).
### Writing New Monomorphic Matchers
A matcher of type `testing::Matcher<T>` implements the matcher interface for `T`
and does two things: it tests whether a value of type `T` matches the matcher,
and can describe what kind of values it matches. The latter ability is used for
generating readable error messages when expectations are violated. Some matchers
can even explain why it matches or doesn't match a certain value, which can be
helpful when the reason isn't obvious.
Because a matcher of type `testing::Matcher<T>` for a particular type `T` can
only be used to match a value of type `T`, we call it "monomorphic."
A matcher of argument type `T` implements the matcher interface for `T` and does
two things: it tests whether a value of type `T` matches the matcher, and can
describe what kind of values it matches. The latter ability is used for
generating readable error messages when expectations are violated.
A matcher of `T` must declare a typedef like:
@ -3668,16 +3662,8 @@ instead of `std::ostream*`.
### Writing New Polymorphic Matchers
Unlike a monomorphic matcher, which can only be used to match a value of a
particular type, a *polymorphic* matcher is one that can be used to match values
of multiple types. For example, `Eq(5)` is a polymorhpic matcher as it can be
used to match an `int`, a `double`, a `float`, and so on. You should think of a
polymorphic matcher as a *matcher factory* as opposed to a
`testing::Matcher<SomeType>` - itself is not an actual matcher, but can be
implicitly converted to a `testing::Matcher<SomeType>` depending on the context.
Expanding what we learned above to polymorphic matchers is now as simple as
adding templates in the right place.
Expanding what we learned above to *polymorphic* matchers is now just as simple
as adding templates in the right place.
```cpp
@ -3803,26 +3789,6 @@ virtual.
Like in a monomorphic matcher, you may explain the match result by streaming
additional information to the `listener` argument in `MatchAndExplain()`.
### Implementing Composite Matchers {#CompositeMatchers}
Sometimes we want to define a matcher that takes other matchers as parameters.
For example, `DistanceFrom(target, m)` is a polymorphic matcher that takes a
matcher `m` as a parameter. It tests that the distance from `target` to the
value being matched satisfies sub-matcher `m`.
If you are implementing such a composite matcher, you'll need to generate the
description of the matcher based on the description(s) of its sub-matcher(s).
You can see the implementation of `DistanceFrom()` in
`googlemock/include/gmock/gmock-matchers.h` for an example. In particular, pay
attention to `DistanceFromMatcherImpl`. Notice that it stores the sub-matcher as
a `const Matcher<const Distance&> distance_matcher_` instead of a polymorphic
matcher - this allows it to call `distance_matcher_.DescribeTo(os)` to describe
the sub-matcher. If the sub-matcher is stored as a polymorphic matcher instead,
it would not be possible to get its description as in general polymorphic
matchers don't know how to describe themselves - they are matcher factories
instead of actual matchers; only after being converted to `Matcher<SomeType>`
can they be described.
### Writing New Cardinalities
A cardinality is used in `Times()` to tell gMock how many times you expect a

View File

@ -73,8 +73,8 @@ Meaning
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
[istqb test case]: https://glossary.istqb.org/en_US/term/test-case
[istqb test suite]: https://glossary.istqb.org/en_US/term/test-suite
[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

View File

@ -9,9 +9,9 @@ we recommend this tutorial as a starting point.
To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++17.
* [Bazel](https://bazel.build/) 7.0 or higher, the preferred build system used
by the GoogleTest team.
* A compatible C++ compiler that supports at least C++14.
* [Bazel](https://bazel.build/), the preferred build system used by the
GoogleTest team.
See [Supported Platforms](platforms.md) for more information about platforms
compatible with GoogleTest.
@ -28,7 +28,7 @@ A
[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace)
is a directory on your filesystem that you use to manage source files for the
software you want to build. Each workspace directory has a text file named
`MODULE.bazel` which may be empty, or may contain references to external
`WORKSPACE` which may be empty, or may contain references to external
dependencies required to build the outputs.
First, create a directory for your workspace:
@ -37,20 +37,30 @@ First, create a directory for your workspace:
$ mkdir my_workspace && cd my_workspace
```
Next, youll create the `MODULE.bazel` file to specify dependencies. As of Bazel
7.0, the recommended way to consume GoogleTest is through the
[Bazel Central Registry](https://registry.bazel.build/modules/googletest). To do
this, create a `MODULE.bazel` file in the root directory of your Bazel workspace
with the following content:
Next, youll create the `WORKSPACE` file to specify dependencies. A common and
recommended way to depend on GoogleTest is to use a
[Bazel external dependency](https://docs.bazel.build/versions/main/external.html)
via the
[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive).
To do this, in the root directory of your workspace (`my_workspace/`), create a
file named `WORKSPACE` with the following contents:
```
# MODULE.bazel
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# Choose the most recent version available at
# https://registry.bazel.build/modules/googletest
bazel_dep(name = "googletest", version = "1.17.0")
http_archive(
name = "com_google_googletest",
urls = ["https://github.com/google/googletest/archive/5ab508a01f9eb089207ee87fd547d290da39d015.zip"],
strip_prefix = "googletest-5ab508a01f9eb089207ee87fd547d290da39d015",
)
```
The above configuration declares a dependency on GoogleTest which is downloaded
as a ZIP archive from GitHub. In the above example,
`5ab508a01f9eb089207ee87fd547d290da39d015` is the Git commit hash of the
GoogleTest version to use; we recommend updating the hash often to point to the
latest version. Use a recent hash on the `main` branch.
Now you're ready to build C++ code that uses GoogleTest.
## Create and run a binary
@ -82,33 +92,30 @@ following contents:
```
cc_test(
name = "hello_test",
size = "small",
srcs = ["hello_test.cc"],
deps = [
"@googletest//:gtest",
"@googletest//:gtest_main",
],
name = "hello_test",
size = "small",
srcs = ["hello_test.cc"],
deps = ["@com_google_googletest//:gtest_main"],
)
```
This `cc_test` rule declares the C++ test binary you want to build, and links to
the GoogleTest library (`@googletest//:gtest"`) and the GoogleTest `main()`
function (`@googletest//:gtest_main`). For more information about Bazel `BUILD`
files, see the
GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE`
file (`@com_google_googletest`). For more information about Bazel `BUILD` files,
see the
[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html).
{: .callout .note}
NOTE: In the example below, we assume Clang or GCC and set `--cxxopt=-std=c++17`
to ensure that GoogleTest is compiled as C++17 instead of the compiler's default
setting. For MSVC, the equivalent would be `--cxxopt=/std:c++17`. See
[Supported Platforms](platforms.md) for more details on supported language
versions.
NOTE: In the example below, we assume Clang or GCC and set `--cxxopt=-std=c++14`
to ensure that GoogleTest is compiled as C++14 instead of the compiler's default
setting (which could be C++11). For MSVC, the equivalent would be
`--cxxopt=/std:c++14`. See [Supported Platforms](platforms.md) for more details
on supported language versions.
Now you can build and run your test:
<pre>
<strong>$ bazel test --cxxopt=-std=c++17 --test_output=all //:hello_test</strong>
<strong>my_workspace$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test</strong>
INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
INFO: Found 1 test target...
INFO: From Testing //:hello_test:

View File

@ -10,7 +10,7 @@ this tutorial as a starting point. If your project uses Bazel, see the
To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++17.
* A compatible C++ compiler that supports at least C++14.
* [CMake](https://cmake.org/) and a compatible build tool for building the
project.
* Compatible build tools include
@ -52,8 +52,8 @@ To do this, in your project directory (`my_project`), create a file named
cmake_minimum_required(VERSION 3.14)
project(my_project)
# GoogleTest requires at least C++17
set(CMAKE_CXX_STANDARD 17)
# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(FetchContent)

View File

@ -24,8 +24,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace.
| :--------------------------------- | :-------------------------------------- |
| `Assign(&variable, value)` | Assign `value` to variable. |
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer` by copy-assignment. |
| `SaveArgByMove<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer` by move-assignment. |
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
| `SetArgReferee<N>(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. |
| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. |
@ -48,8 +47,8 @@ functor, or lambda.
| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. |
| `InvokeArgument<N>(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. |
The return value of the invoked function (except `InvokeArgument`) is used as
the return value of the action.
The return value of the invoked function is used as the return value of the
action.
When defining a callable to be used with `Invoke*()`, you can declare any unused
parameters as `Unused`:

View File

@ -276,8 +276,7 @@ Units in the Last Place (ULPs). To learn more about ULPs, see the article
`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)`
Verifies that the two `float` values *`val1`* and *`val2`* are approximately
equal, to within 4 ULPs from each other. Infinity and the largest finite float
value are considered to be one ULP apart.
equal, to within 4 ULPs from each other.
### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ}
@ -285,8 +284,7 @@ value are considered to be one ULP apart.
`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)`
Verifies that the two `double` values *`val1`* and *`val2`* are approximately
equal, to within 4 ULPs from each other. Infinity and the largest finite double
value are considered to be one ULP apart.
equal, to within 4 ULPs from each other.
### EXPECT_NEAR {#EXPECT_NEAR}
@ -296,11 +294,6 @@ value are considered to be one ULP apart.
Verifies that the difference between *`val1`* and *`val2`* does not exceed the
absolute error bound *`abs_error`*.
If *`val`* and *`val2`* are both infinity of the same sign, the difference is
considered to be 0. Otherwise, if either value is infinity, the difference is
considered to be infinity. All non-NaN values (including infinity) are
considered to not exceed an *`abs_error`* of infinity.
## Exception Assertions {#exceptions}
The following assertions verify that a piece of code throws, or does not throw,

View File

@ -42,14 +42,11 @@ Matcher | Description
| `Lt(value)` | `argument < value` |
| `Ne(value)` | `argument != value` |
| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. |
| `DistanceFrom(target, m)` | The distance between `argument` and `target` (computed by `abs(argument - target)`) matches `m`. |
| `DistanceFrom(target, get_distance, m)` | The distance between `argument` and `target` (computed by `get_distance(argument, target)`) matches `m`. |
| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. |
| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). |
| `NotNull()` | `argument` is a non-null pointer (raw or smart). |
| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)|
| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |
| `AnyWith<T>(m)` | `argument` is `any<>` that holds a value of type T with a value matching `m`. |
| `Ref(variable)` | `argument` is a reference to `variable`. |
| `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. |
@ -112,33 +109,6 @@ use the regular expression syntax defined
[here](../advanced.md#regular-expression-syntax). All of these matchers, except
`ContainsRegex()` and `MatchesRegex()` work for wide strings as well.
## Exception Matchers
| Matcher | Description |
| :---------------------------------------- | :------------------------------- |
| `Throws<E>()` | The `argument` is a callable object that, when called, throws an exception of the expected type `E`. |
| `Throws<E>(m)` | The `argument` is a callable object that, when called, throws an exception of type `E` that satisfies the matcher `m`. |
| `ThrowsMessage<E>(m)` | The `argument` is a callable object that, when called, throws an exception of type `E` with a message that satisfies the matcher `m`. |
Examples:
```cpp
auto argument = [] { throw std::runtime_error("error msg"); };
// Checks if the lambda throws a `std::runtime_error`.
EXPECT_THAT(argument, Throws<std::runtime_error>());
// Checks if the lambda throws a `std::runtime_error` with a specific message
// that matches "error msg".
EXPECT_THAT(argument,
Throws<std::runtime_error>(Property(&std::runtime_error::what,
Eq("error msg"))));
// Checks if the lambda throws a `std::runtime_error` with a message that
// contains "msg".
EXPECT_THAT(argument, ThrowsMessage<std::runtime_error>(HasSubstr("msg")));
```
## Container Matchers
Most STL-style containers support `==`, so you can use `Eq(expected_container)`
@ -201,11 +171,6 @@ messages, you can use:
| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. |
| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message.
{: .callout .warning}
Warning: Don't use `Property()` against member functions that you do not own,
because taking addresses of functions is fragile and generally not part of the
contract of the function.
**Notes:**
* You can use `FieldsAre()` to match any type that supports structured
@ -224,6 +189,10 @@ contract of the function.
EXPECT_THAT(s, FieldsAre(42, "aloha"));
```
* Don't use `Property()` against member functions that you do not own, because
taking addresses of functions is fragile and generally not part of the
contract of the function.
## Matching the Result of a Function, Functor, or Callback
| Matcher | Description |

View File

@ -110,7 +110,7 @@ namespace:
| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. |
| `Bool()` | Yields sequence `{false, true}`. |
| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. |
| `ConvertGenerator<T>(g)` or `ConvertGenerator(g, func)` | Yields values generated by generator `g`, `static_cast` from `T`. (Note: `T` might not be what you expect. See [*Using ConvertGenerator*](#using-convertgenerator) below.) The second overload uses `func` to perform the conversion. |
| `ConvertGenerator<T>(g)` | Yields values generated by generator `g`, `static_cast` to `T`. |
The optional last argument *`name_generator`* is a function or functor that
generates custom test name suffixes based on the test parameters. The function
@ -137,103 +137,6 @@ For more information, see
See also
[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST).
###### Using `ConvertGenerator`
The functions listed in the table above appear to return generators that create
values of the desired types, but this is not generally the case. Rather, they
typically return factory objects that convert to the the desired generators.
This affords some flexibility in allowing you to specify values of types that
are different from, yet implicitly convertible to, the actual parameter type
required by your fixture class.
For example, you can do the following with a fixture that requires an `int`
parameter:
```cpp
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
testing::Values(1, 1.2)); // Yes, Values() supports heterogeneous argument types.
```
It might seem obvious that `1.2` &mdash; a `double` &mdash; will be converted to
an `int` but in actuality it requires some template gymnastics involving the
indirection described in the previous paragraph.
What if your parameter type is not implicitly convertible from the generated
type but is *explicitly* convertible? There will be no automatic conversion, but
you can force it by applying `ConvertGenerator<T>`. The compiler can
automatically deduce the target type (your fixture's parameter type), but
because of the aforementioned indirection it cannot decide what the generated
type should be. You need to tell it, by providing the type `T` explicitly. Thus
`T` should not be your fixture's parameter type, but rather an intermediate type
that is supported by the factory object, and which can be `static_cast` to the
fixture's parameter type:
```cpp
// The fixture's parameter type.
class MyParam {
public:
// Explicit converting ctor.
explicit MyParam(const std::tuple<int, bool>& t);
...
};
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
ConvertGenerator<std::tuple<int, bool>>(Combine(Values(0.1, 1.2), Bool())));
```
In this example `Combine` supports the generation of `std::tuple<int, bool>>`
objects (even though the provided values for the first tuple element are
`double`s) and those `tuple`s get converted into `MyParam` objects by virtue of
the call to `ConvertGenerator`.
For parameter types that are not convertible from the generated types you can
provide a callable that does the conversion. The callable accepts an object of
the generated type and returns an object of the fixture's parameter type. The
generated type can often be deduced by the compiler from the callable's call
signature so you do not usually need specify it explicitly (but see a caveat
below).
```cpp
// The fixture's parameter type.
class MyParam {
public:
MyParam(int, bool);
...
};
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
ConvertGenerator(Combine(Values(1, 1.2), Bool()),
[](const std::tuple<int, bool>& t){
const auto [i, b] = t;
return MyParam(i, b);
}));
```
The callable may be anything that can be used to initialize a `std::function`
with the appropriate call signature. Note the callable's return object gets
`static_cast` to the fixture's parameter type, so it does not have to be of that
exact type, only convertible to it.
**Caveat:** Consider the following example.
```cpp
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
ConvertGenerator(Values(std::string("s")), [](std::string_view s) { ... }));
```
The `string` argument gets copied into the factory object returned by `Values`.
Then, because the generated type deduced from the lambda is `string_view`, the
factory object spawns a generator that holds a `string_view` referencing that
`string`. Unfortunately, by the time this generator gets invoked, the factory
object is gone and the `string_view` is dangling.
To overcome this problem you can specify the generated type explicitly:
`ConvertGenerator<std::string>(Values(std::string("s")), [](std::string_view s)
{ ... })`. Alternatively, you can change the lambda's signature to take a
`std::string` or a `const std::string&` (the latter will not leave you with a
dangling reference because the type deduction strips off the reference and the
`const`).
### TYPED_TEST_SUITE {#TYPED_TEST_SUITE}
`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)`

View File

@ -1,20 +1,10 @@
"""Provides a fake @fuchsia_sdk implementation that's used when the real one isn't available.
GoogleTest can be used with the [Fuchsia](https://fuchsia.dev/) SDK. However,
because the Fuchsia SDK does not yet support bzlmod, GoogleTest's `MODULE.bazel`
file by default provides a "fake" Fuchsia SDK.
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.
To override this and use the real Fuchsia SDK, you can add the following to your
project's `MODULE.bazel` file:
fake_fuchsia_sdk_extension =
use_extension("@com_google_googletest//:fake_fuchsia_sdk.bzl", "fuchsia_sdk")
override_repo(fake_fuchsia_sdk_extension, "fuchsia_sdk")
NOTE: The `override_repo` built-in is only available in Bazel 8.0 and higher.
See https://github.com/google/googletest/issues/4472 for more details of why the
fake Fuchsia SDK is needed.
See https://github.com/google/googletest/issues/4472.
"""
def _fake_fuchsia_sdk_impl(repo_ctx):
@ -41,21 +31,3 @@ fake_fuchsia_sdk = repository_rule(
),
},
)
_create_fake = tag_class()
def _fuchsia_sdk_impl(module_ctx):
create_fake_sdk = False
for mod in module_ctx.modules:
for _ in mod.tags.create_fake:
create_fake_sdk = True
if create_fake_sdk:
fake_fuchsia_sdk(name = "fuchsia_sdk")
return module_ctx.extension_metadata(reproducible = True)
fuchsia_sdk = module_extension(
implementation = _fuchsia_sdk_impl,
tag_classes = {"create_fake": _create_fake},
)

View File

@ -196,7 +196,7 @@ struct BuiltInDefaultValueGetter<T, false> {
// other type T, the built-in default T value is undefined, and the
// function will abort the process.
template <typename T>
class [[nodiscard]] BuiltInDefaultValue {
class BuiltInDefaultValue {
public:
// This function returns true if and only if type T has a built-in default
// value.
@ -211,7 +211,7 @@ class [[nodiscard]] BuiltInDefaultValue {
// This partial specialization says that we use the same built-in
// default value for T and const T.
template <typename T>
class [[nodiscard]] BuiltInDefaultValue<const T> {
class BuiltInDefaultValue<const T> {
public:
static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
static T Get() { return BuiltInDefaultValue<T>::Get(); }
@ -220,7 +220,7 @@ class [[nodiscard]] BuiltInDefaultValue<const T> {
// This partial specialization defines the default values for pointer
// types.
template <typename T>
class [[nodiscard]] BuiltInDefaultValue<T*> {
class BuiltInDefaultValue<T*> {
public:
static bool Exists() { return true; }
static T* Get() { return nullptr; }
@ -383,7 +383,7 @@ typename std::add_const<T>::type& as_const(T& t) {
// Specialized for function types below.
template <typename F>
class [[nodiscard]] OnceAction;
class OnceAction;
// An action that can only be used once.
//
@ -421,7 +421,7 @@ class [[nodiscard]] OnceAction;
// A less-contrived example would be an action that returns an arbitrary type,
// whose &&-qualified call operator is capable of dealing with move-only types.
template <typename Result, typename... Args>
class [[nodiscard]] OnceAction<Result(Args...)> final {
class OnceAction<Result(Args...)> final {
private:
// True iff we can use the given callable type (or lvalue reference) directly
// via StdFunctionAdaptor.
@ -574,7 +574,7 @@ class [[nodiscard]] OnceAction<Result(Args...)> final {
// // Sets the default value for type T to be foo.
// DefaultValue<T>::Set(foo);
template <typename T>
class [[nodiscard]] DefaultValue {
class DefaultValue {
public:
// Sets the default value for type T; requires T to be
// copy-constructable and have a public destructor.
@ -651,7 +651,7 @@ class [[nodiscard]] DefaultValue {
// This partial specialization allows a user to set default values for
// reference types.
template <typename T>
class [[nodiscard]] DefaultValue<T&> {
class DefaultValue<T&> {
public:
// Sets the default value for type T&.
static void Set(T& x) { // NOLINT
@ -685,7 +685,7 @@ class [[nodiscard]] DefaultValue<T&> {
// This specialization allows DefaultValue<void>::Get() to
// compile.
template <>
class [[nodiscard]] DefaultValue<void> {
class DefaultValue<void> {
public:
static bool Exists() { return true; }
static void Get() {}
@ -701,7 +701,7 @@ T* DefaultValue<T&>::address_ = nullptr;
// Implement this interface to define an action for function type F.
template <typename F>
class [[nodiscard]] ActionInterface {
class ActionInterface {
public:
typedef typename internal::Function<F>::Result Result;
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
@ -721,7 +721,7 @@ class [[nodiscard]] ActionInterface {
};
template <typename F>
class [[nodiscard]] Action;
class Action;
// An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment)
// object that represents an action to be taken when a mock function of type
@ -730,7 +730,7 @@ class [[nodiscard]] Action;
// can view an object implementing ActionInterface<F> as a concrete action
// (including its current state), and an Action<F> object as a handle to it.
template <typename R, typename... Args>
class [[nodiscard]] Action<R(Args...)> {
class Action<R(Args...)> {
private:
using F = R(Args...);
@ -835,10 +835,6 @@ class [[nodiscard]] Action<R(Args...)> {
Result operator()(const InArgs&...) const {
return function_impl();
}
template <typename... InArgs>
Result operator()(const InArgs&...) {
return function_impl();
}
FunctionImpl function_impl;
};
@ -869,7 +865,7 @@ class [[nodiscard]] Action<R(Args...)> {
// the definition of Return(void) and SetArgumentPointee<N>(value) for
// complete examples.
template <typename Impl>
class [[nodiscard]] PolymorphicAction {
class PolymorphicAction {
public:
explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
@ -929,7 +925,7 @@ struct ByMoveWrapper {
// The general implementation of Return(R). Specializations follow below.
template <typename R>
class [[nodiscard]] ReturnAction final {
class ReturnAction final {
public:
explicit ReturnAction(R value) : value_(std::move(value)) {}
@ -1095,7 +1091,7 @@ class [[nodiscard]] ReturnAction final {
// the const call operator, checking at runtime that it isn't called more than
// once, since the user has declared their intent to do so by using ByMove.
template <typename T>
class [[nodiscard]] ReturnAction<ByMoveWrapper<T>> final {
class ReturnAction<ByMoveWrapper<T>> final {
public:
explicit ReturnAction(ByMoveWrapper<T> wrapper)
: state_(new State(std::move(wrapper.payload))) {}
@ -1122,7 +1118,7 @@ class [[nodiscard]] ReturnAction<ByMoveWrapper<T>> final {
};
// Implements the ReturnNull() action.
class [[nodiscard]] ReturnNullAction {
class ReturnNullAction {
public:
// Allows ReturnNull() to be used in any pointer-returning function. In C++11
// this is enforced by returning nullptr, and in non-C++11 by asserting a
@ -1134,7 +1130,7 @@ class [[nodiscard]] ReturnNullAction {
};
// Implements the Return() action.
class [[nodiscard]] ReturnVoidAction {
class ReturnVoidAction {
public:
// Allows Return() to be used in any void-returning function.
template <typename Result, typename ArgumentTuple>
@ -1147,7 +1143,7 @@ class [[nodiscard]] ReturnVoidAction {
// in any function that returns a reference to the type of x,
// regardless of the argument types.
template <typename T>
class [[nodiscard]] ReturnRefAction {
class ReturnRefAction {
public:
// Constructs a ReturnRefAction object from the reference to be returned.
explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
@ -1188,7 +1184,7 @@ class [[nodiscard]] ReturnRefAction {
// used in any function that returns a reference to the type of x,
// regardless of the argument types.
template <typename T>
class [[nodiscard]] ReturnRefOfCopyAction {
class ReturnRefOfCopyAction {
public:
// Constructs a ReturnRefOfCopyAction object from the reference to
// be returned.
@ -1229,7 +1225,7 @@ class [[nodiscard]] ReturnRefOfCopyAction {
// Implements the polymorphic ReturnRoundRobin(v) action, which can be
// used in any function that returns the element_type of v.
template <typename T>
class [[nodiscard]] ReturnRoundRobinAction {
class ReturnRoundRobinAction {
public:
explicit ReturnRoundRobinAction(std::vector<T> values) {
GTEST_CHECK_(!values.empty())
@ -1257,7 +1253,7 @@ class [[nodiscard]] ReturnRoundRobinAction {
};
// Implements the polymorphic DoDefault() action.
class [[nodiscard]] DoDefaultAction {
class DoDefaultAction {
public:
// This template type conversion operator allows DoDefault() to be
// used in any function.
@ -1270,7 +1266,7 @@ class [[nodiscard]] DoDefaultAction {
// Implements the Assign action to set a given pointer referent to a
// particular value.
template <typename T1, typename T2>
class [[nodiscard]] AssignAction {
class AssignAction {
public:
AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
@ -1289,7 +1285,7 @@ class [[nodiscard]] AssignAction {
// Implements the SetErrnoAndReturn action to simulate return from
// various system calls and libc functions.
template <typename T>
class [[nodiscard]] SetErrnoAndReturnAction {
class SetErrnoAndReturnAction {
public:
SetErrnoAndReturnAction(int errno_value, T result)
: errno_(errno_value), result_(result) {}
@ -1397,7 +1393,7 @@ class IgnoreResultAction {
void Perform(const ArgumentTuple& args) override {
// Performs the action and ignores its result.
(void)action_.Perform(args);
action_.Perform(args);
}
private:
@ -1455,30 +1451,6 @@ struct WithArgsAction {
return OA{std::move(inner_action)};
}
// As above, but in the case where we want to create a OnceAction from a const
// WithArgsAction. This is fine as long as the inner action doesn't need to
// move any of its state to create a OnceAction.
template <
typename R, typename... Args,
typename std::enable_if<
std::is_convertible<const InnerAction&,
OnceAction<R(internal::TupleElement<
I, std::tuple<Args...>>...)>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() const& { // NOLINT
struct OA {
OnceAction<InnerSignature<R, Args...>> inner_action;
R operator()(Args&&... args) && {
return std::move(inner_action)
.Call(std::get<I>(
std::forward_as_tuple(std::forward<Args>(args)...))...);
}
};
return OA{inner_action};
}
template <
typename R, typename... Args,
typename std::enable_if<
@ -1503,11 +1475,11 @@ struct WithArgsAction {
};
template <typename... Actions>
class [[nodiscard]] DoAllAction;
class DoAllAction;
// Base case: only a single action.
template <typename FinalAction>
class [[nodiscard]] DoAllAction<FinalAction> {
class DoAllAction<FinalAction> {
public:
struct UserConstructorTag {};
@ -1521,7 +1493,6 @@ class [[nodiscard]] DoAllAction<FinalAction> {
// providing a call operator because even with a particular set of arguments
// they don't have a fixed return type.
// We support conversion to OnceAction whenever the sub-action does.
template <typename R, typename... Args,
typename std::enable_if<
std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,
@ -1530,21 +1501,6 @@ class [[nodiscard]] DoAllAction<FinalAction> {
return std::move(final_action_);
}
// We also support conversion to OnceAction whenever the sub-action supports
// conversion to Action (since any Action can also be a OnceAction).
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<
negation<
std::is_convertible<FinalAction, OnceAction<R(Args...)>>>,
std::is_convertible<FinalAction, Action<R(Args...)>>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
return Action<R(Args...)>(std::move(final_action_));
}
// We support conversion to Action whenever the sub-action does.
template <
typename R, typename... Args,
typename std::enable_if<
@ -1561,7 +1517,7 @@ class [[nodiscard]] DoAllAction<FinalAction> {
// Recursive case: support N actions by calling the initial action and then
// calling through to the base class containing N-1 actions.
template <typename InitialAction, typename... OtherActions>
class [[nodiscard]] DoAllAction<InitialAction, OtherActions...>
class DoAllAction<InitialAction, OtherActions...>
: private DoAllAction<OtherActions...> {
private:
using Base = DoAllAction<OtherActions...>;
@ -1624,16 +1580,16 @@ class [[nodiscard]] DoAllAction<InitialAction, OtherActions...>
: Base({}, std::forward<U>(other_actions)...),
initial_action_(std::forward<T>(initial_action)) {}
// We support conversion to OnceAction whenever both the initial action and
// the rest support conversion to OnceAction.
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<std::is_convertible<
InitialAction,
OnceAction<void(InitialActionArgType<Args>...)>>,
std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
int>::type = 0>
template <typename R, typename... Args,
typename std::enable_if<
conjunction<
// Both the initial action and the rest must support
// conversion to OnceAction.
std::is_convertible<
InitialAction,
OnceAction<void(InitialActionArgType<Args>...)>>,
std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
// Return an action that first calls the initial action with arguments
// filtered through InitialActionArgType, then forwards arguments directly
@ -1656,34 +1612,12 @@ class [[nodiscard]] DoAllAction<InitialAction, OtherActions...>
};
}
// We also support conversion to OnceAction whenever the initial action
// supports conversion to Action (since any Action can also be a OnceAction).
//
// The remaining sub-actions must also be compatible, but we don't need to
// special case them because the base class deals with them.
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<
negation<std::is_convertible<
InitialAction,
OnceAction<void(InitialActionArgType<Args>...)>>>,
std::is_convertible<InitialAction,
Action<void(InitialActionArgType<Args>...)>>,
std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
return DoAll(
Action<void(InitialActionArgType<Args>...)>(std::move(initial_action_)),
std::move(static_cast<Base&>(*this)));
}
// We support conversion to Action whenever both the initial action and the
// rest support conversion to Action.
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<
// Both the initial action and the rest must support conversion to
// Action.
std::is_convertible<const InitialAction&,
Action<void(InitialActionArgType<Args>...)>>,
std::is_convertible<const Base&, Action<R(Args...)>>>::value,
@ -1747,16 +1681,6 @@ struct SaveArgAction {
}
};
template <size_t k, typename Ptr>
struct SaveArgByMoveAction {
Ptr pointer;
template <typename... Args>
void operator()(Args&&... args) const {
*pointer = std::move(std::get<k>(std::tie(args...)));
}
};
template <size_t k, typename Ptr>
struct SaveArgPointeeAction {
Ptr pointer;
@ -1796,24 +1720,11 @@ struct SetArrayArgumentAction {
};
template <size_t k>
class [[nodiscard]] DeleteArgAction {
public:
struct DeleteArgAction {
template <typename... Args>
void operator()(const Args&... args) const {
DoDelete(std::get<k>(std::tie(args...)));
delete std::get<k>(std::tie(args...));
}
private:
template <typename T>
static void DoDelete(T* ptr) {
delete ptr;
}
template <typename T>
[[deprecated(
"DeleteArg<N> used for a non-pointer argument, it was likely migrated "
"to a smart pointer type. This action should be removed.")]]
static void DoDelete(T&) {}
};
template <typename Ptr>
@ -1879,13 +1790,6 @@ struct RethrowAction {
// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
typedef internal::IgnoredValue Unused;
// Deprecated single-argument DoAll.
template <typename Action>
GTEST_INTERNAL_DEPRECATE_AND_INLINE("Avoid using DoAll() for single actions")
typename std::decay<Action>::type DoAll(Action&& action) {
return std::forward<Action>(action);
}
// Creates an action that does actions a1, a2, ..., sequentially in
// each invocation. All but the last action will have a readonly view of the
// arguments.
@ -2051,11 +1955,10 @@ PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(
// Various overloads for Invoke().
// Legacy function.
// Actions can now be implicitly constructed from callables. No need to create
// wrapper objects.
// This function exists for backwards compatibility.
template <typename FunctionImpl>
GTEST_INTERNAL_DEPRECATE_AND_INLINE(
"Actions can now be implicitly constructed from callables. No need to "
"create wrapper objects using Invoke().")
typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
return std::forward<FunctionImpl>(function_impl);
}
@ -2128,13 +2031,6 @@ internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
return {pointer};
}
// Action SaveArgByMove<k>(pointer) moves the k-th (0-based) argument of the
// mock function into *pointer.
template <size_t k, typename Ptr>
internal::SaveArgByMoveAction<k, Ptr> SaveArgByMove(Ptr pointer) {
return {pointer};
}
// Action SaveArgPointee<k>(pointer) saves the value pointed to
// by the k-th (0-based) argument of the mock function to *pointer.
template <size_t k, typename Ptr>
@ -2278,9 +2174,9 @@ template <typename F, typename Impl>
}
#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
, [[maybe_unused]] const arg##i##_type& arg##i
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
[[maybe_unused]] const args_type& args 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
@ -2345,8 +2241,8 @@ template <typename F, typename Impl>
std::shared_ptr<const gmock_Impl> impl_; \
}; \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
[[nodiscard]] inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)); \
inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
@ -2381,7 +2277,7 @@ template <typename F, typename Impl>
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
}; \
}; \
[[nodiscard]] inline name##Action name(); \
inline name##Action name() GTEST_MUST_USE_RESULT_; \
inline name##Action name() { return name##Action(); } \
template <typename function_type, typename return_type, typename args_type, \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \

View File

@ -63,7 +63,7 @@ namespace testing {
// management as Cardinality objects can now be copied like plain values.
// The implementation of a cardinality.
class [[nodiscard]] CardinalityInterface {
class CardinalityInterface {
public:
virtual ~CardinalityInterface() = default;
@ -88,7 +88,7 @@ class [[nodiscard]] CardinalityInterface {
// object that specifies how many times a mock function is expected to
// be called. The implementation of Cardinality is just a std::shared_ptr
// to const CardinalityInterface. Don't inherit from Cardinality!
class GTEST_API_ [[nodiscard]] Cardinality {
class GTEST_API_ Cardinality {
public:
// Constructs a null cardinality. Needed for storing Cardinality
// objects in STL containers.

File diff suppressed because it is too large Load Diff

View File

@ -521,8 +521,9 @@
GMOCK_INTERNAL_DECL_##value_params) \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
= default; \
, : impl_(std::make_shared<gmock_Impl>( \
GMOCK_INTERNAL_LIST_##value_params)){}) \
, \
: impl_(std::make_shared<gmock_Impl>( \
GMOCK_INTERNAL_LIST_##value_params)){}) \
GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \
name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \
##value_params \
@ -550,10 +551,10 @@
}; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
[[nodiscard]] GMOCK_ACTION_CLASS_( \
GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> \
name(GMOCK_INTERNAL_DECL_##value_params); \
name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
inline GMOCK_ACTION_CLASS_( \
@ -600,10 +601,9 @@ template <std::size_t index, typename... Params>
struct InvokeArgumentAction {
template <typename... Args,
typename = typename std::enable_if<(index < sizeof...(Args))>::type>
auto operator()(Args &&...args) const
-> decltype(internal::InvokeArgument(
std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
std::declval<const Params &>()...)) {
auto operator()(Args &&...args) const -> decltype(internal::InvokeArgument(
std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
std::declval<const Params &>()...)) {
internal::FlatTuple<Args &&...> args_tuple(FlatTupleConstructTag{},
std::forward<Args>(args)...);
return params.Apply([&](const Params &...unpacked_params) {

View File

@ -61,7 +61,7 @@ namespace internal {
// Implements the polymorphic IsEmpty matcher, which
// can be used as a Matcher<T> as long as T is either a container that defines
// empty() and size() (e.g. std::vector or std::string), or a C-style string.
class [[nodiscard]] IsEmptyMatcher {
class IsEmptyMatcher {
public:
// Matches anything that defines empty() and size().
template <typename MatcheeContainerType>

View File

@ -71,11 +71,11 @@
namespace testing {
template <class MockClass>
class [[nodiscard]] NiceMock;
class NiceMock;
template <class MockClass>
class [[nodiscard]] NaggyMock;
class NaggyMock;
template <class MockClass>
class [[nodiscard]] StrictMock;
class StrictMock;
namespace internal {
template <typename T>
@ -108,7 +108,7 @@ constexpr bool HasStrictnessModifier() {
#endif
template <typename Base>
class [[nodiscard]] NiceMockImpl {
class NiceMockImpl {
public:
NiceMockImpl() {
::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this));
@ -120,7 +120,7 @@ class [[nodiscard]] NiceMockImpl {
};
template <typename Base>
class [[nodiscard]] NaggyMockImpl {
class NaggyMockImpl {
public:
NaggyMockImpl() {
::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this));
@ -132,7 +132,7 @@ class [[nodiscard]] NaggyMockImpl {
};
template <typename Base>
class [[nodiscard]] StrictMockImpl {
class StrictMockImpl {
public:
StrictMockImpl() {
::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this));
@ -146,7 +146,7 @@ class [[nodiscard]] StrictMockImpl {
} // namespace internal
template <class MockClass>
class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
: private internal::NiceMockImpl<MockClass>,
public MockClass {
public:
@ -187,7 +187,7 @@ class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
};
template <class MockClass>
class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
: private internal::NaggyMockImpl<MockClass>,
public MockClass {
static_assert(!internal::HasStrictnessModifier<MockClass>(),
@ -229,7 +229,7 @@ class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
};
template <class MockClass>
class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
: private internal::StrictMockImpl<MockClass>,
public MockClass {
public:

View File

@ -868,7 +868,7 @@ class GTEST_API_ ExpectationBase {
Clause last_clause_;
mutable bool action_count_checked_; // Under mutex_.
mutable Mutex mutex_; // Protects action_count_checked_.
}; // class ExpectationBase
}; // class ExpectationBase
template <typename F>
class TypedExpectation;
@ -1292,10 +1292,10 @@ class MockSpec {
: function_mocker_(function_mocker), matchers_(matchers) {}
// Adds a new default action spec to the function mocker and returns
// the newly created spec. .WillByDefault() must be called on the returned
// object.
[[nodiscard]] internal::OnCallSpec<F>& InternalDefaultActionSetAt(
const char* file, int line, const char* obj, const char* call) {
// the newly created spec.
internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file,
int line, const char* obj,
const char* call) {
LogWithLocation(internal::kInfo, file, line,
std::string("ON_CALL(") + obj + ", " + call + ") invoked");
return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
@ -1467,7 +1467,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
// function have been satisfied. If not, it will report Google Test
// non-fatal failures for the violations.
~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
VerifyAndClearExpectationsLocked();
Mock::UnregisterLocked(this);
ClearDefaultActionsLocked();
@ -1530,7 +1530,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
UntypedOnCallSpecs specs_to_delete;
untyped_on_call_specs_.swap(specs_to_delete);
g_gmock_mutex.unlock();
g_gmock_mutex.Unlock();
for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
it != specs_to_delete.end(); ++it) {
delete static_cast<const OnCallSpec<F>*>(*it);
@ -1538,7 +1538,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
// Lock the mutex again, since the caller expects it to be locked when we
// return.
g_gmock_mutex.lock();
g_gmock_mutex.Lock();
}
// Returns the result of invoking this mock function with the given
@ -1646,7 +1646,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
const ArgumentTuple& args =
*static_cast<const ArgumentTuple*>(untyped_args);
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
if (exp == nullptr) { // A match wasn't found.
this->FormatUnexpectedCallMessageLocked(args, what, why);
@ -1838,8 +1838,9 @@ R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
// Doing so slows down compilation dramatically because the *constructor* of
// std::function<T> is re-instantiated with different template
// parameters each time.
const UninterestingCallCleanupHandler report_uninteresting_call = {reaction,
ss};
const UninterestingCallCleanupHandler report_uninteresting_call = {
reaction, ss
};
return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
}
@ -1889,7 +1890,8 @@ R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
// std::function<T> is re-instantiated with different template
// parameters each time.
const FailureCleanupHandler handle_failures = {
ss, why, loc, untyped_expectation, found, is_excessive};
ss, why, loc, untyped_expectation, found, is_excessive
};
return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
ss);

View File

@ -220,7 +220,7 @@ using LosslessArithmeticConvertible =
// This interface knows how to report a Google Mock failure (either
// non-fatal or fatal).
class [[nodiscard]] FailureReporterInterface {
class FailureReporterInterface {
public:
// The type of a failure (either non-fatal or fatal).
enum FailureType { kNonfatal, kFatal };
@ -296,14 +296,10 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
//
// ON_CALL(mock, Method({}, nullptr))...
//
class [[nodiscard]] WithoutMatchers {
class WithoutMatchers {
private:
WithoutMatchers() = default;
friend
#ifdef GTEST_OS_WINDOWS
GTEST_API_
#endif
WithoutMatchers GetWithoutMatchers();
WithoutMatchers() {}
friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
};
// Internal use only: access the singleton instance of WithoutMatchers.
@ -344,7 +340,7 @@ inline T Invalid() {
// This generic version is used when RawContainer itself is already an
// STL-style container.
template <class RawContainer>
class [[nodiscard]] StlContainerView {
class StlContainerView {
public:
typedef RawContainer type;
typedef const type& const_reference;
@ -359,7 +355,7 @@ class [[nodiscard]] StlContainerView {
// This specialization is used when RawContainer is a native array type.
template <typename Element, size_t N>
class [[nodiscard]] StlContainerView<Element[N]> {
class StlContainerView<Element[N]> {
public:
typedef typename std::remove_const<Element>::type RawElement;
typedef internal::NativeArray<RawElement> type;
@ -383,7 +379,7 @@ class [[nodiscard]] StlContainerView<Element[N]> {
// This specialization is used when RawContainer is a native array
// represented as a (pointer, size) tuple.
template <typename ElementPointer, typename Size>
class [[nodiscard]] StlContainerView< ::std::tuple<ElementPointer, Size> > {
class StlContainerView< ::std::tuple<ElementPointer, Size> > {
public:
typedef typename std::remove_const<
typename std::pointer_traits<ElementPointer>::element_type>::type
@ -471,6 +467,11 @@ struct Function<R(Args...)> {
using MakeResultIgnoredValue = IgnoredValue(Args...);
};
#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
template <typename R, typename... Args>
constexpr size_t Function<R(Args...)>::ArgumentCount;
#endif
// Workaround for MSVC error C2039: 'type': is not a member of 'std'
// when std::tuple_element is used.
// See: https://github.com/google/googletest/issues/3931

View File

@ -42,7 +42,6 @@
#include <assert.h>
#include <stdlib.h>
#include <cstdint>
#include <iostream>

View File

@ -53,12 +53,12 @@ class BetweenCardinalityImpl : public CardinalityInterface {
: min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) {
std::stringstream ss;
if (min < 0) {
ss << "The invocation lower bound must be >= 0, " << "but is actually "
<< min << ".";
ss << "The invocation lower bound must be >= 0, "
<< "but is actually " << min << ".";
internal::Expect(false, __FILE__, __LINE__, ss.str());
} else if (max < 0) {
ss << "The invocation upper bound must be >= 0, " << "but is actually "
<< max << ".";
ss << "The invocation upper bound must be >= 0, "
<< "but is actually " << max << ".";
internal::Expect(false, __FILE__, __LINE__, ss.str());
} else if (min > max) {
ss << "The invocation upper bound (" << max

View File

@ -156,7 +156,7 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
if (!LogIsVisible(severity)) return;
// Ensures that logs from different threads don't interleave.
MutexLock l(g_log_mutex);
MutexLock l(&g_log_mutex);
if (severity == kWarning) {
// Prints a GMOCK WARNING marker to make the warnings easily searchable.

View File

@ -212,7 +212,7 @@ void ExpectationBase::CheckActionCountIfNotDone() const
GTEST_LOCK_EXCLUDED_(mutex_) {
bool should_check = false;
{
MutexLock l(mutex_);
MutexLock l(&mutex_);
if (!action_count_checked_) {
action_count_checked_ = true;
should_check = true;
@ -293,7 +293,7 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
Log(kWarning,
msg +
"\nNOTE: You can safely ignore the above warning unless this "
"call should not happen. Do not suppress it by adding "
"call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See "
"https://github.com/google/googletest/blob/main/docs/"
@ -318,7 +318,7 @@ UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;
void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
{
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
mock_obj_ = mock_obj;
}
Mock::Register(mock_obj, this);
@ -332,7 +332,7 @@ void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
// We protect name_ under g_gmock_mutex in case this mock function
// is called from two threads concurrently.
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
mock_obj_ = mock_obj;
name_ = name;
}
@ -345,7 +345,7 @@ const void* UntypedFunctionMockerBase::MockObject() const
{
// We protect mock_obj_ under g_gmock_mutex in case this mock
// function is called from two threads concurrently.
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
Assert(mock_obj_ != nullptr, __FILE__, __LINE__,
"MockObject() must not be called before RegisterOwner() or "
"SetOwnerAndName() has been called.");
@ -362,7 +362,7 @@ const char* UntypedFunctionMockerBase::Name() const
{
// We protect name_ under g_gmock_mutex in case this mock
// function is called from two threads concurrently.
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
Assert(name_ != nullptr, __FILE__, __LINE__,
"Name() must not be called before SetOwnerAndName() has "
"been called.");
@ -436,9 +436,9 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
UntypedExpectations expectations_to_delete;
untyped_expectations_.swap(expectations_to_delete);
g_gmock_mutex.unlock();
g_gmock_mutex.Unlock();
expectations_to_delete.clear();
g_gmock_mutex.lock();
g_gmock_mutex.Lock();
return expectations_met;
}
@ -490,7 +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);
internal::MutexLock l(&internal::g_gmock_mutex);
int leaked_count = 0;
for (StateMap::const_iterator it = states_.begin(); it != states_.end();
@ -559,7 +559,7 @@ UninterestingCallReactionMap() {
void SetReactionOnUninterestingCalls(uintptr_t mock_obj,
internal::CallReaction reaction)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
UninterestingCallReactionMap()[mock_obj] = reaction;
}
@ -590,7 +590,7 @@ void Mock::FailUninterestingCalls(uintptr_t mock_obj)
// entry in the call-reaction table should be removed.
void Mock::UnregisterCallReaction(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj));
}
@ -598,7 +598,7 @@ void Mock::UnregisterCallReaction(uintptr_t mock_obj)
// made on the given mock object.
internal::CallReaction Mock::GetReactionOnUninterestingCalls(
const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
return (UninterestingCallReactionMap().count(
reinterpret_cast<uintptr_t>(mock_obj)) == 0)
? internal::intToCallReaction(
@ -611,7 +611,7 @@ internal::CallReaction Mock::GetReactionOnUninterestingCalls(
// objects.
void Mock::AllowLeak(const void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
g_mock_object_registry.states()[mock_obj].leakable = true;
}
@ -620,7 +620,7 @@ void Mock::AllowLeak(const void* mock_obj)
// Test non-fatal failures and returns false.
bool Mock::VerifyAndClearExpectations(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
return VerifyAndClearExpectationsLocked(mock_obj);
}
@ -629,7 +629,7 @@ bool Mock::VerifyAndClearExpectations(void* mock_obj)
// verification was successful.
bool Mock::VerifyAndClear(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
ClearDefaultActionsLocked(mock_obj);
return VerifyAndClearExpectationsLocked(mock_obj);
}
@ -679,7 +679,7 @@ bool Mock::IsStrict(void* mock_obj)
void Mock::Register(const void* mock_obj,
internal::UntypedFunctionMockerBase* mocker)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
}
@ -689,7 +689,7 @@ void Mock::Register(const void* mock_obj,
void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
const char* file, int line)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
MockObjectState& state = g_mock_object_registry.states()[mock_obj];
if (state.first_used_file == nullptr) {
state.first_used_file = file;

View File

@ -30,7 +30,6 @@
#
# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
load("@rules_python//python:defs.bzl", "py_library", "py_test")
licenses(["notice"])

View File

@ -188,7 +188,7 @@ TEST(TypeTraits, IsInvocableRV) {
struct C {
int operator()() const { return 0; }
void operator()(int) & {}
std::string operator()(int) && { return ""; }
std::string operator()(int) && { return ""; };
};
// The first overload is callable for const and non-const rvalues and lvalues.
@ -222,8 +222,8 @@ TEST(TypeTraits, IsInvocableRV) {
// In C++17 and above, where it's guaranteed that functions can return
// non-moveable objects, everything should work fine for non-moveable rsult
// types too.
// TODO(b/396121064) - Fix this test under MSVC
#ifndef _MSC_VER
#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
{
struct NonMoveable {
NonMoveable() = default;
@ -244,7 +244,7 @@ TEST(TypeTraits, IsInvocableRV) {
static_assert(!internal::is_callable_r<int, Callable>::value);
static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);
}
#endif // _MSC_VER
#endif // C++17 and above
// Nothing should choke when we try to call other arguments besides directly
// callable objects, but they should not show up as callable.
@ -441,8 +441,8 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_EQ(0, DefaultValue<int>::Get());
EXPECT_DEATH_IF_SUPPORTED(
{ DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
"");
}
TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
@ -505,8 +505,8 @@ TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
EXPECT_DEATH_IF_SUPPORTED(
{ DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
"");
}
// Tests that ActionInterface can be implemented by defining the
@ -1030,7 +1030,8 @@ void VoidFunc(bool /* flag */) {}
TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
MockClass mock;
EXPECT_CALL(mock, IntFunc(_)).WillRepeatedly(DoAll(VoidFunc, DoDefault()));
EXPECT_CALL(mock, IntFunc(_))
.WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));
// Ideally we should verify the error message as well. Sadly,
// EXPECT_DEATH() can only capture stderr, while Google Mock's
@ -1281,7 +1282,7 @@ int ReturnOne() {
TEST(IgnoreResultTest, MonomorphicAction) {
g_done = false;
Action<void()> a = IgnoreResult(&ReturnOne);
Action<void()> a = IgnoreResult(Invoke(ReturnOne));
a.Perform(std::make_tuple());
EXPECT_TRUE(g_done);
}
@ -1296,7 +1297,7 @@ MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
TEST(IgnoreResultTest, ActionReturningClass) {
g_done = false;
Action<void(int)> a =
IgnoreResult(&ReturnMyNonDefaultConstructible); // NOLINT
IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
a.Perform(std::make_tuple(2));
EXPECT_TRUE(g_done);
}
@ -1476,50 +1477,9 @@ TEST(DoAll, SupportsTypeErasedActions) {
}
}
// A multi-action DoAll action should be convertible to a OnceAction, even when
// its component sub-actions are user-provided types that define only an Action
// conversion operator. If they supposed being called more than once then they
// also support being called at most once.
//
// Single-arg DoAll just returns its argument, so will prefer the Action<F>
// overload for WillOnce.
TEST(DoAll, ConvertibleToOnceActionWithUserProvidedActionConversion) {
// Final action.
struct CustomFinal final {
operator Action<int()>() { // NOLINT
return Return(17);
}
operator Action<int(int, char)>() { // NOLINT
return Return(19);
}
};
// Sub-actions.
struct CustomInitial final {
operator Action<void()>() { // NOLINT
return [] {};
}
operator Action<void(int, char)>() { // NOLINT
return [] {};
}
};
{
OnceAction<int()> action = DoAll(CustomInitial{}, CustomFinal{});
EXPECT_EQ(17, std::move(action).Call());
}
{
OnceAction<int(int, char)> action = DoAll(CustomInitial{}, CustomFinal{});
EXPECT_EQ(19, std::move(action).Call(0, 0));
}
}
// Tests using WithArgs and with an action that takes 1 argument.
TEST(WithArgsTest, OneArg) {
Action<bool(double x, int n)> a = WithArgs<1>(Unary);
Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT
EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));
EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));
}
@ -1527,7 +1487,7 @@ TEST(WithArgsTest, OneArg) {
// Tests using WithArgs with an action that takes 2 arguments.
TEST(WithArgsTest, TwoArgs) {
Action<const char*(const char* s, double x, short n)> a = // NOLINT
WithArgs<0, 2>(Binary);
WithArgs<0, 2>(Invoke(Binary));
const char s[] = "Hello";
EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
}
@ -1543,7 +1503,7 @@ struct ConcatAll {
// Tests using WithArgs with an action that takes 10 arguments.
TEST(WithArgsTest, TenArgs) {
Action<std::string(const char*, const char*, const char*, const char*)> a =
WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(ConcatAll{});
WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
EXPECT_EQ("0123210123",
a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
CharPtr("3"))));
@ -1568,21 +1528,21 @@ TEST(WithArgsTest, NonInvokeAction) {
// Tests using WithArgs to pass all original arguments in the original order.
TEST(WithArgsTest, Identity) {
Action<int(int x, char y, short z)> a = // NOLINT
WithArgs<0, 1, 2>(Ternary);
WithArgs<0, 1, 2>(Invoke(Ternary));
EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));
}
// Tests using WithArgs with repeated arguments.
TEST(WithArgsTest, RepeatedArguments) {
Action<int(bool, int m, int n)> a = // NOLINT
WithArgs<1, 1, 1, 1>(SumOf4);
WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));
}
// Tests using WithArgs with reversed argument order.
TEST(WithArgsTest, ReversedArgumentOrder) {
Action<const char*(short n, const char* input)> a = // NOLINT
WithArgs<1, 0>(Binary);
WithArgs<1, 0>(Invoke(Binary));
const char s[] = "Hello";
EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));
}
@ -1590,14 +1550,14 @@ TEST(WithArgsTest, ReversedArgumentOrder) {
// Tests using WithArgs with compatible, but not identical, argument types.
TEST(WithArgsTest, ArgsOfCompatibleTypes) {
Action<long(short x, char y, double z, char c)> a = // NOLINT
WithArgs<0, 1, 3>(Ternary);
WithArgs<0, 1, 3>(Invoke(Ternary));
EXPECT_EQ(123,
a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));
}
// Tests using WithArgs with an action that returns void.
TEST(WithArgsTest, VoidAction) {
Action<void(double x, char c, int n)> a = WithArgs<2, 1>(VoidBinary);
Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
g_done = false;
a.Perform(std::make_tuple(1.5, 'a', 3));
EXPECT_TRUE(g_done);
@ -1637,22 +1597,6 @@ TEST(WithArgsTest, RefQualifiedInnerAction) {
EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
}
// It should be fine to provide an lvalue WithArgsAction to WillOnce, even when
// the inner action only wants to convert to OnceAction.
TEST(WithArgsTest, ProvideAsLvalueToWillOnce) {
struct SomeAction {
operator OnceAction<int(int)>() const { // NOLINT
return [](const int arg) { return arg + 2; };
}
};
const auto wa = WithArg<1>(SomeAction{});
MockFunction<int(int, int)> mock;
EXPECT_CALL(mock, Call).WillOnce(wa);
EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
}
#ifndef GTEST_OS_WINDOWS_MOBILE
class SetErrnoAndReturnTest : public testing::Test {
@ -1822,7 +1766,7 @@ std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
MockClass mock;
std::unique_ptr<int> i = std::make_unique<int>(19);
std::unique_ptr<int> i(new int(19));
EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
EXPECT_CALL(mock, MakeVectorUnique())
.WillOnce(Return(ByMove(VectorUniquePtrSource())));
@ -1845,7 +1789,7 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
testing::MockFunction<void()> mock_function;
MockClass mock;
std::unique_ptr<int> i = std::make_unique<int>(19);
std::unique_ptr<int> i(new int(19));
EXPECT_CALL(mock_function, Call());
EXPECT_CALL(mock, MakeUnique())
.WillOnce(DoAll(InvokeWithoutArgs(&mock_function,
@ -1864,8 +1808,9 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
[] { return std::make_unique<int>(42); });
EXPECT_EQ(42, *mock.MakeUnique());
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(UniquePtrSource);
EXPECT_CALL(mock, MakeVectorUnique()).WillRepeatedly(VectorUniquePtrSource);
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
EXPECT_CALL(mock, MakeVectorUnique())
.WillRepeatedly(Invoke(VectorUniquePtrSource));
std::unique_ptr<int> result1 = mock.MakeUnique();
EXPECT_EQ(19, *result1);
std::unique_ptr<int> result2 = mock.MakeUnique();
@ -1887,7 +1832,7 @@ TEST(MockMethodTest, CanTakeMoveOnlyValue) {
});
// DoAll() does not compile, since it would move from its arguments twice.
// EXPECT_CALL(mock, TakeUnique(_, _))
// .WillRepeatedly(DoAll([](std::unique_ptr<int> j) {})),
// .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
// Return(1)));
EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
.WillOnce(Return(-7))
@ -2170,7 +2115,7 @@ TEST(FunctorActionTest, TypeConversion) {
EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
// Ensure creation of an empty action succeeds.
(void)Action<void(int)>(nullptr);
Action<void(int)>(nullptr);
}
TEST(FunctorActionTest, UnusedArguments) {

View File

@ -133,7 +133,7 @@ TEST(AnyNumberTest, HasCorrectBounds) {
TEST(AtLeastTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)AtLeast(-1);
AtLeast(-1);
},
"The invocation lower bound must be >= 0");
}
@ -186,7 +186,7 @@ TEST(AtLeastTest, HasCorrectBounds) {
TEST(AtMostTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)AtMost(-1);
AtMost(-1);
},
"The invocation upper bound must be >= 0");
}
@ -239,7 +239,7 @@ TEST(AtMostTest, HasCorrectBounds) {
TEST(BetweenTest, OnNegativeStart) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)Between(-1, 2);
Between(-1, 2);
},
"The invocation lower bound must be >= 0, but is actually -1");
}
@ -247,7 +247,7 @@ TEST(BetweenTest, OnNegativeStart) {
TEST(BetweenTest, OnNegativeEnd) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)Between(1, -2);
Between(1, -2);
},
"The invocation upper bound must be >= 0, but is actually -2");
}
@ -255,7 +255,7 @@ TEST(BetweenTest, OnNegativeEnd) {
TEST(BetweenTest, OnStartBiggerThanEnd) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)Between(2, 1);
Between(2, 1);
},
"The invocation upper bound (1) must be >= "
"the invocation lower bound (2)");
@ -340,7 +340,7 @@ TEST(BetweenTest, HasCorrectBounds) {
TEST(ExactlyTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)Exactly(-1);
Exactly(-1);
},
"The invocation lower bound must be >= 0");
}

View File

@ -91,7 +91,7 @@ class FooInterface {
virtual bool TakesNonConstReference(int& n) = 0; // NOLINT
virtual std::string TakesConstReference(const int& n) = 0;
virtual bool TakesConst(int x) = 0;
virtual bool TakesConst(const int x) = 0;
virtual int OverloadedOnArgumentNumber() = 0;
virtual int OverloadedOnArgumentNumber(int n) = 0;
@ -325,8 +325,8 @@ TYPED_TEST(FunctionMockerTest, MocksBinaryFunction) {
// Tests mocking a decimal function.
TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(this->mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100),
5U, nullptr, "hi"))
EXPECT_CALL(this->mock_foo_,
Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(5));
EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));

View File

@ -545,7 +545,7 @@ TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
void OnCallLogger() {
DummyMock mock;
(void)ON_CALL(mock, TestMethod());
ON_CALL(mock, TestMethod());
}
// Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
@ -568,7 +568,7 @@ TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
void OnCallAnyArgumentLogger() {
DummyMock mock;
(void)ON_CALL(mock, TestMethodArg(_));
ON_CALL(mock, TestMethodArg(_));
}
// Verifies that ON_CALL prints provided _ argument.

View File

@ -34,12 +34,9 @@
#include <cmath>
#include <limits>
#include <memory>
#include <ostream>
#include <string>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter
@ -399,188 +396,6 @@ TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
EXPECT_EQ("are an almost-equal pair", Describe(m));
}
// Tests that DistanceFrom() can describe itself properly.
TEST(DistanceFrom, CanDescribeSelf) {
Matcher<double> m = DistanceFrom(1.5, Lt(0.1));
EXPECT_EQ(Describe(m), "is < 0.1 away from 1.5");
m = DistanceFrom(2.5, Gt(0.2));
EXPECT_EQ(Describe(m), "is > 0.2 away from 2.5");
}
// Tests that DistanceFrom() can explain match failure.
TEST(DistanceFrom, CanExplainMatchFailure) {
Matcher<double> m = DistanceFrom(1.5, Lt(0.1));
EXPECT_EQ(Explain(m, 2.0), "which is 0.5 away from 1.5");
}
// Tests that DistanceFrom() matches a double that is within the given range of
// the given value.
TEST(DistanceFrom, MatchesDoubleWithinRange) {
const Matcher<double> m = DistanceFrom(0.5, Le(0.1));
EXPECT_TRUE(m.Matches(0.45));
EXPECT_TRUE(m.Matches(0.5));
EXPECT_TRUE(m.Matches(0.55));
EXPECT_FALSE(m.Matches(0.39));
EXPECT_FALSE(m.Matches(0.61));
}
// Tests that DistanceFrom() matches a double reference that is within the given
// range of the given value.
TEST(DistanceFrom, MatchesDoubleRefWithinRange) {
const Matcher<const double&> m = DistanceFrom(0.5, Le(0.1));
EXPECT_TRUE(m.Matches(0.45));
EXPECT_TRUE(m.Matches(0.5));
EXPECT_TRUE(m.Matches(0.55));
EXPECT_FALSE(m.Matches(0.39));
EXPECT_FALSE(m.Matches(0.61));
}
// Tests that DistanceFrom() can be implicitly converted to a matcher depending
// on the type of the argument.
TEST(DistanceFrom, CanBeImplicitlyConvertedToMatcher) {
EXPECT_THAT(0.58, DistanceFrom(0.5, Le(0.1)));
EXPECT_THAT(0.2, Not(DistanceFrom(0.5, Le(0.1))));
EXPECT_THAT(0.58f, DistanceFrom(0.5f, Le(0.1f)));
EXPECT_THAT(0.7f, Not(DistanceFrom(0.5f, Le(0.1f))));
}
// Tests that DistanceFrom() can be used on compatible types (i.e. not
// everything has to be of the same type).
TEST(DistanceFrom, CanBeUsedOnCompatibleTypes) {
EXPECT_THAT(0.58, DistanceFrom(0.5, Le(0.1f)));
EXPECT_THAT(0.2, Not(DistanceFrom(0.5, Le(0.1f))));
EXPECT_THAT(0.58, DistanceFrom(0.5f, Le(0.1)));
EXPECT_THAT(0.2, Not(DistanceFrom(0.5f, Le(0.1))));
EXPECT_THAT(0.58, DistanceFrom(0.5f, Le(0.1f)));
EXPECT_THAT(0.2, Not(DistanceFrom(0.5f, Le(0.1f))));
EXPECT_THAT(0.58f, DistanceFrom(0.5, Le(0.1)));
EXPECT_THAT(0.2f, Not(DistanceFrom(0.5, Le(0.1))));
EXPECT_THAT(0.58f, DistanceFrom(0.5, Le(0.1f)));
EXPECT_THAT(0.2f, Not(DistanceFrom(0.5, Le(0.1f))));
EXPECT_THAT(0.58f, DistanceFrom(0.5f, Le(0.1)));
EXPECT_THAT(0.2f, Not(DistanceFrom(0.5f, Le(0.1))));
}
// A 2-dimensional point. For testing using DistanceFrom() with a custom type
// that doesn't have a built-in distance function.
class Point {
public:
Point(double x, double y) : x_(x), y_(y) {}
double x() const { return x_; }
double y() const { return y_; }
private:
double x_;
double y_;
};
// Returns the distance between two points.
double PointDistance(const Point& lhs, const Point& rhs) {
return std::sqrt(std::pow(lhs.x() - rhs.x(), 2) +
std::pow(lhs.y() - rhs.y(), 2));
}
// Tests that DistanceFrom() can be used on a type with a custom distance
// function.
TEST(DistanceFrom, CanBeUsedOnTypeWithCustomDistanceFunction) {
const Matcher<Point> m =
DistanceFrom(Point(0.5, 0.5), PointDistance, Le(0.1));
EXPECT_THAT(Point(0.45, 0.45), m);
EXPECT_THAT(Point(0.2, 0.45), Not(m));
}
// A wrapper around a double value. For testing using DistanceFrom() with a
// custom type that has neither a built-in distance function nor a built-in
// distance comparator.
class Double {
public:
explicit Double(double value) : value_(value) {}
Double(const Double& other) = default;
double value() const { return value_; }
// Defines how to print a Double value. We don't use the AbslStringify API
// because googletest doesn't require absl yet.
friend void PrintTo(const Double& value, std::ostream* os) {
*os << "Double(" << value.value() << ")";
}
private:
double value_;
};
// Returns the distance between two Double values.
Double DoubleDistance(Double lhs, Double rhs) {
return Double(std::abs(lhs.value() - rhs.value()));
}
MATCHER_P(DoubleLe, rhs, (negation ? "is > " : "is <= ") + PrintToString(rhs)) {
return arg.value() <= rhs.value();
}
// Tests that DistanceFrom() can describe itself properly for a type with a
// custom printer.
TEST(DistanceFrom, CanDescribeWithCustomPrinter) {
const Matcher<Double> m =
DistanceFrom(Double(0.5), DoubleDistance, DoubleLe(Double(0.1)));
EXPECT_EQ(Describe(m), "is <= Double(0.1) away from Double(0.5)");
EXPECT_EQ(DescribeNegation(m), "is > Double(0.1) away from Double(0.5)");
}
// Tests that DistanceFrom() can be used with a custom distance function and
// comparator.
TEST(DistanceFrom, CanCustomizeDistanceAndComparator) {
const Matcher<Double> m =
DistanceFrom(Double(0.5), DoubleDistance, DoubleLe(Double(0.1)));
EXPECT_TRUE(m.Matches(Double(0.45)));
EXPECT_TRUE(m.Matches(Double(0.5)));
EXPECT_FALSE(m.Matches(Double(0.39)));
EXPECT_FALSE(m.Matches(Double(0.61)));
}
// For testing using DistanceFrom() with a type that supports both - and abs.
class Float {
public:
explicit Float(float value) : value_(value) {}
Float(const Float& other) = default;
float value() const { return value_; }
private:
float value_ = 0.0f;
};
// Returns the difference between two Float values. This must be defined in the
// same namespace as Float.
Float operator-(const Float& lhs, const Float& rhs) {
return Float(lhs.value() - rhs.value());
}
// Returns the absolute value of a Float value. This must be defined in the
// same namespace as Float.
Float abs(Float value) { return Float(std::abs(value.value())); }
// Returns true if and only if the first Float value is less than the second
// Float value. This must be defined in the same namespace as Float.
bool operator<(const Float& lhs, const Float& rhs) {
return lhs.value() < rhs.value();
}
// Tests that DistanceFrom() can be used with a type that supports both - and
// abs.
TEST(DistanceFrom, CanBeUsedWithTypeThatSupportsBothMinusAndAbs) {
const Matcher<Float> m = DistanceFrom(Float(0.5f), Lt(Float(0.1f)));
EXPECT_TRUE(m.Matches(Float(0.45f)));
EXPECT_TRUE(m.Matches(Float(0.55f)));
EXPECT_FALSE(m.Matches(Float(0.39f)));
EXPECT_FALSE(m.Matches(Float(0.61f)));
}
// Tests that Not(m) matches any value that doesn't match m.
TEST(NotTest, NegatesMatcher) {
Matcher<int> m;
@ -720,6 +535,7 @@ TEST(AllOfTest, CanDescribeNegation) {
m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
Ne(10), Ne(11));
AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
AllOfMatches(11, m);
}
@ -743,9 +559,10 @@ TEST_P(AllOfTestP, ExplainsResult) {
Matcher<int> m;
// Successful match. Both matchers need to explain. The second
// matcher doesn't give an explanation, so the matcher description is used.
// matcher doesn't give an explanation, so only the first matcher's
// explanation is printed.
m = AllOf(GreaterThan(10), Lt(30));
EXPECT_EQ("which is 15 more than 10, and is < 30", Explain(m, 25));
EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
// Successful match. Both matchers need to explain.
m = AllOf(GreaterThan(10), GreaterThan(20));
@ -755,9 +572,8 @@ TEST_P(AllOfTestP, ExplainsResult) {
// Successful match. All matchers need to explain. The second
// matcher doesn't given an explanation.
m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
EXPECT_EQ(
"which is 15 more than 10, and is < 30, and which is 5 more than 20",
Explain(m, 25));
EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
Explain(m, 25));
// Successful match. All matchers need to explain.
m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
@ -769,14 +585,13 @@ TEST_P(AllOfTestP, ExplainsResult) {
// Failed match. The first matcher, which failed, needs to
// explain.
m = AllOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
Explain(m, 5));
EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
// Failed match. The second matcher, which failed, needs to
// explain. Since it doesn't given an explanation, the matcher text is
// explain. Since it doesn't given an explanation, nothing is
// printed.
m = AllOf(GreaterThan(10), Lt(30));
EXPECT_EQ("which doesn't match (is < 30)", Explain(m, 40));
EXPECT_EQ("", Explain(m, 40));
// Failed match. The second matcher, which failed, needs to
// explain.
@ -959,43 +774,45 @@ TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
TEST_P(AnyOfTestP, ExplainsResult) {
Matcher<int> m;
// Failed match. The second matcher have no explanation (description is used).
// Failed match. Both matchers need to explain. The second
// matcher doesn't give an explanation, so only the first matcher's
// explanation is printed.
m = AnyOf(GreaterThan(10), Lt(0));
EXPECT_EQ("which is 5 less than 10, and isn't < 0", Explain(m, 5));
EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
// Failed match. Both matchers have explanations.
// Failed match. Both matchers need to explain.
m = AnyOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
Explain(m, 5));
// Failed match. The middle matcher have no explanation.
// Failed match. All matchers need to explain. The second
// matcher doesn't given an explanation.
m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
EXPECT_EQ(
"which is 5 less than 10, and isn't > 20, and which is 25 less than 30",
Explain(m, 5));
EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
Explain(m, 5));
// Failed match. All three matchers have explanations.
// Failed match. All matchers need to explain.
m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
EXPECT_EQ(
"which is 5 less than 10, and which is 15 less than 20, "
"and which is 25 less than 30",
Explain(m, 5));
// Successful match. The first macher succeeded and has explanation.
// Successful match. The first matcher, which succeeded, needs to
// explain.
m = AnyOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
// Successful match. The second matcher succeeded and has explanation.
// Successful match. The second matcher, which succeeded, needs to
// explain. Since it doesn't given an explanation, nothing is
// printed.
m = AnyOf(GreaterThan(10), Lt(30));
EXPECT_EQ("", Explain(m, 0));
// Successful match. The second matcher, which succeeded, needs to
// explain.
m = AnyOf(GreaterThan(30), GreaterThan(20));
EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
// Successful match. The first matcher succeeded and has no explanation.
m = AnyOf(Gt(10), Lt(20));
EXPECT_EQ("which matches (is > 10)", Explain(m, 15));
// Successful match. The second matcher succeeded and has no explanation.
m = AnyOf(Gt(30), Gt(20));
EXPECT_EQ("which matches (is > 20)", Explain(m, 25));
}
// The following predicate function and predicate functor are for
@ -1625,7 +1442,7 @@ TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
}
TEST(NotTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, Pointee(Eq(3)));
EXPECT_THAT(p, Not(Pointee(Eq(2))));
}
@ -1681,13 +1498,13 @@ TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
} // namespace adl_test
TEST(AllOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
}
TEST(AnyOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
}

View File

@ -33,19 +33,17 @@
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
namespace testing {
namespace gmock_matchers_test {
namespace {
@ -412,27 +410,9 @@ class IntValue {
int value_;
};
// For testing casting matchers between compatible types. This is similar to
// IntValue, but takes a non-const reference to the value, showing MatcherCast
// works with such types (and doesn't, for example, use a const ref internally).
class MutableIntView {
public:
// An int& can be statically (although not implicitly) cast to a
// MutableIntView.
explicit MutableIntView(int& a_value) : value_(a_value) {}
int& value() const { return value_; }
private:
int& value_;
};
// For testing casting matchers between compatible types.
bool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; }
// For testing casting matchers between compatible types.
bool IsPositiveMutableIntView(MutableIntView foo) { return foo.value() > 0; }
// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
// can be statically converted to U.
TEST(MatcherCastTest, FromCompatibleType) {
@ -448,34 +428,14 @@ TEST(MatcherCastTest, FromCompatibleType) {
// predicate.
EXPECT_TRUE(m4.Matches(1));
EXPECT_FALSE(m4.Matches(0));
Matcher<MutableIntView> m5 = Truly(IsPositiveMutableIntView);
Matcher<int> m6 = MatcherCast<int>(m5);
// In the following, the arguments 1 and 0 are statically converted to
// MutableIntView objects, and then tested by the IsPositiveMutableIntView()
// predicate.
EXPECT_TRUE(m6.Matches(1));
EXPECT_FALSE(m6.Matches(0));
}
// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest, FromConstReferenceToNonReference) {
int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<const int&> m1 = Eq(0);
Matcher<int> m2 = MatcherCast<int>(m1);
int n1 = 0;
EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
}
// Tests that MatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest, FromConstReferenceToReference) {
int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<int&> m2 = MatcherCast<int&>(m1);
int n1 = 0;
EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
}
// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
@ -484,12 +444,6 @@ TEST(MatcherCastTest, FromReferenceToNonReference) {
Matcher<int> m2 = MatcherCast<int>(m1);
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
// Of course, reference identity isn't preserved since a copy is required.
int n = 0;
Matcher<int&> m3 = Ref(n);
Matcher<int> m4 = MatcherCast<int>(m3);
EXPECT_FALSE(m4.Matches(n));
}
// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
@ -622,42 +576,15 @@ struct IntReferenceWrapper {
const int* value;
};
// Compared the contained values
bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
return *a.value == *b.value;
return a.value == b.value;
}
TEST(MatcherCastTest, ValueIsCopied) {
{
// When an IntReferenceWrapper is passed.
int n = 42;
Matcher<IntReferenceWrapper> m =
MatcherCast<IntReferenceWrapper>(IntReferenceWrapper(n));
{
int value = 42;
EXPECT_TRUE(m.Matches(value));
value = 10;
EXPECT_FALSE(m.Matches(value));
// This changes the stored reference.
n = 10;
EXPECT_TRUE(m.Matches(value));
}
}
{
// When an int is passed.
int n = 42;
Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
{
int value = 42;
EXPECT_TRUE(m.Matches(value));
value = 10;
EXPECT_FALSE(m.Matches(value));
// This does not change the stored int.
n = 10;
EXPECT_FALSE(m.Matches(value));
}
}
TEST(MatcherCastTest, ValueIsNotCopied) {
int n = 42;
Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
// Verify that the matcher holds a reference to n, not to its temporary copy.
EXPECT_TRUE(m.Matches(n));
}
class Base {
@ -721,16 +648,6 @@ TEST(SafeMatcherCastTest, FromBaseClass) {
EXPECT_FALSE(m4.Matches(d2));
}
// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest, FromConstReferenceToNonReference) {
int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<int> m2 = SafeMatcherCast<int>(m1);
int n1 = 0;
EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
}
// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
int n = 0;
@ -2389,19 +2306,22 @@ PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
return MakePolymorphicMatcher(DivisibleByImpl(n));
}
// Tests that when AllOf() fails, all failing matchers are asked to explain why.
// Tests that when AllOf() fails, only the first failing matcher is
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_False_False) {
const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
EXPECT_EQ("which is 1 modulo 4, and which is 2 modulo 3", Explain(m, 5));
EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
}
// Tests that when AllOf() fails, all failing matchers are asked to explain why.
// Tests that when AllOf() fails, only the first failing matcher is
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_False_True) {
const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
}
// Tests that when AllOf() fails, all failing matchers are asked to explain why.
// Tests that when AllOf() fails, only the first failing matcher is
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_True_False) {
const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
@ -2414,79 +2334,9 @@ TEST(ExplainMatchResultTest, AllOf_True_True) {
EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
}
// Tests that when AllOf() succeeds, but matchers have no explanation,
// the matcher description is used.
TEST(ExplainMatchResultTest, AllOf_True_True_2) {
const Matcher<int> m = AllOf(Ge(2), Le(3));
EXPECT_EQ("is >= 2, and is <= 3", Explain(m, 2));
}
// A matcher that records whether the listener was interested.
template <typename T>
class CountingMatcher : public MatcherInterface<T> {
public:
explicit CountingMatcher(const Matcher<T>& base_matcher,
std::vector<bool>* listener_interested)
: base_matcher_(base_matcher),
listener_interested_(listener_interested) {}
bool MatchAndExplain(T x, MatchResultListener* listener) const override {
listener_interested_->push_back(listener->IsInterested());
return base_matcher_.MatchAndExplain(x, listener);
}
void DescribeTo(ostream* os) const override { base_matcher_.DescribeTo(os); }
private:
Matcher<T> base_matcher_;
std::vector<bool>* listener_interested_;
};
TEST(AllOfTest, DoesNotFormatChildMatchersWhenNotInterested) {
std::vector<bool> listener_interested;
Matcher<int> matcher =
MakeMatcher(new CountingMatcher<int>(Eq(1), &listener_interested));
EXPECT_TRUE(matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
Matcher<int> all_of_matcher = AllOf(matcher, matcher);
EXPECT_TRUE(all_of_matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false, false));
listener_interested.clear();
EXPECT_FALSE(all_of_matcher.Matches(0));
EXPECT_THAT(listener_interested, ElementsAre(false));
}
TEST(AnyOfTest, DoesNotFormatChildMatchersWhenNotInterested) {
std::vector<bool> listener_interested;
Matcher<int> matcher =
MakeMatcher(new CountingMatcher<int>(Eq(1), &listener_interested));
EXPECT_TRUE(matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
Matcher<int> any_of_matcher = AnyOf(matcher, matcher);
EXPECT_TRUE(any_of_matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
EXPECT_FALSE(any_of_matcher.Matches(0));
EXPECT_THAT(listener_interested, ElementsAre(false, false));
}
TEST(OptionalTest, DoesNotFormatChildMatcherWhenNotInterested) {
std::vector<bool> listener_interested;
Matcher<int> matcher =
MakeMatcher(new CountingMatcher<int>(Eq(1), &listener_interested));
EXPECT_TRUE(matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
Matcher<std::optional<int>> optional_matcher = Optional(matcher);
EXPECT_FALSE(optional_matcher.Matches(std::nullopt));
EXPECT_THAT(listener_interested, ElementsAre());
EXPECT_TRUE(optional_matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
EXPECT_FALSE(matcher.Matches(0));
EXPECT_THAT(listener_interested, ElementsAre(false));
EXPECT_EQ("", Explain(m, 2));
}
INSTANTIATE_GTEST_MATCHER_TEST_P(ExplainmatcherResultTest);

View File

@ -33,7 +33,6 @@
#include <algorithm>
#include <array>
#include <cstddef>
#include <deque>
#include <forward_list>
#include <iterator>
@ -44,14 +43,14 @@
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#include "test/gmock-matchers_test.h"
namespace testing {
namespace gmock_matchers_test {
namespace {
@ -217,7 +216,7 @@ TEST(PointeeTest, ReferenceToNonConstRawPointer) {
TEST(PointeeTest, SmartPointer) {
const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
std::unique_ptr<int> n = std::make_unique<int>(1);
std::unique_ptr<int> n(new int(1));
EXPECT_TRUE(m.Matches(n));
}
@ -254,7 +253,7 @@ TEST(PointerTest, RawPointerToConst) {
}
TEST(PointerTest, SmartPointer) {
std::unique_ptr<int> n = std::make_unique<int>(10);
std::unique_ptr<int> n(new int(10));
int* raw_n = n.get();
const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
@ -1047,8 +1046,8 @@ TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
// a NULL function pointer.
TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
EXPECT_DEATH_IF_SUPPORTED(
(void)ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
Eq(std::string("foo"))),
ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
Eq(std::string("foo"))),
"NULL function pointer is passed into ResultOf\\(\\)\\.");
}
@ -1205,16 +1204,13 @@ TEST(SizeIsTest, ExplainsResult) {
vector<int> container;
EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
EXPECT_EQ("whose size 0 matches", Explain(m2, container));
EXPECT_EQ("whose size 0 matches, which matches (is equal to 0)",
Explain(m3, container));
EXPECT_EQ("whose size 0 matches", Explain(m3, container));
EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
container.push_back(0);
container.push_back(0);
EXPECT_EQ("whose size 2 matches", Explain(m1, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
EXPECT_EQ(
"whose size 2 doesn't match, isn't equal to 0, and isn't equal to 3",
Explain(m3, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
EXPECT_EQ("whose size 2 matches", Explain(m4, container));
}
@ -1272,11 +1268,10 @@ TEST(WhenSortedByTest, CanDescribeSelf) {
TEST(WhenSortedByTest, ExplainsMatchResult) {
const int a[] = {2, 1};
EXPECT_EQ(
Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a),
"which is { 1, 2 } when sorted, whose element #0 (1) isn't equal to 2");
EXPECT_EQ(Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a),
"which is { 1, 2 } when sorted");
EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
EXPECT_EQ("which is { 1, 2 } when sorted",
Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
}
// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
@ -1480,10 +1475,8 @@ TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
Explain(m1, container));
EXPECT_EQ("whose distance between begin() and end() 0 matches",
Explain(m2, container));
EXPECT_EQ(
"whose distance between begin() and end() 0 matches, which matches (is "
"equal to 0)",
Explain(m3, container));
EXPECT_EQ("whose distance between begin() and end() 0 matches",
Explain(m3, container));
EXPECT_EQ(
"whose distance between begin() and end() 0 doesn't match, which is 1 "
"less than 1",
@ -1494,10 +1487,8 @@ TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
Explain(m1, container));
EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
Explain(m2, container));
EXPECT_EQ(
"whose distance between begin() and end() 2 doesn't match, isn't equal "
"to 0, and isn't equal to 3",
Explain(m3, container));
EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
Explain(m3, container));
EXPECT_EQ(
"whose distance between begin() and end() 2 matches, which is 1 more "
"than 1",
@ -1777,295 +1768,6 @@ TEST(IsSubsetOfTest, WorksWithMoveOnly) {
helper.Call(MakeUniquePtrs({2}));
}
// A container whose iterator returns a temporary. This can iterate over the
// characters in a string.
class CharString {
public:
using value_type = char;
class const_iterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = char;
using difference_type = std::ptrdiff_t;
using pointer = const char*;
using reference = const char&;
// Create an iterator that points to the given character.
explicit const_iterator(const char* ptr) : ptr_(ptr) {}
// Returns the current character. IMPORTANT: this must return a temporary,
// not a reference, to test that ElementsAre() works with containers whose
// iterators return temporaries.
char operator*() const { return *ptr_; }
// Advances to the next character.
const_iterator& operator++() {
++ptr_;
return *this;
}
// Compares two iterators.
bool operator==(const const_iterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const const_iterator& other) const {
return ptr_ != other.ptr_;
}
private:
const char* ptr_ = nullptr;
};
// Creates a CharString that contains the given string.
explicit CharString(const std::string& s) : s_(s) {}
// Returns an iterator pointing to the first character in the string.
const_iterator begin() const { return const_iterator(s_.c_str()); }
// Returns an iterator pointing past the last character in the string.
const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }
private:
std::string s_;
};
// Tests using ElementsAre() with a container whose iterator returns a
// temporary.
TEST(ElementsAreTest, WorksWithContainerThatReturnsTempInIterator) {
CharString s("abc");
EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));
EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));
}
// Tests using ElementsAreArray() with a container whose iterator returns a
// temporary.
TEST(ElementsAreArrayTest, WorksWithContainerThatReturnsTempInIterator) {
CharString s("abc");
EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));
EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));
}
// A container whose iterator returns a temporary and is not copy-assignable.
// This simulates the behavior of the proxy object returned by absl::StrSplit().
class CharString2 {
public:
using value_type = char;
class const_iterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = char;
using difference_type = std::ptrdiff_t;
using pointer = const char*;
using reference = const char&;
// Make const_iterator copy-constructible but not copy-assignable,
// simulating the behavior of the proxy object returned by absl::StrSplit().
const_iterator(const const_iterator&) = default;
const_iterator& operator=(const const_iterator&) = delete;
// Create an iterator that points to the given character.
explicit const_iterator(const char* ptr) : ptr_(ptr) {}
// Returns the current character. IMPORTANT: this must return a temporary,
// not a reference, to test that ElementsAre() works with containers whose
// iterators return temporaries.
char operator*() const { return *ptr_; }
// Advances to the next character.
const_iterator& operator++() {
++ptr_;
return *this;
}
// Compares two iterators.
bool operator==(const const_iterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const const_iterator& other) const {
return ptr_ != other.ptr_;
}
private:
const char* ptr_ = nullptr;
};
// Creates a CharString that contains the given string.
explicit CharString2(const std::string& s) : s_(s) {}
// Returns an iterator pointing to the first character in the string.
const_iterator begin() const { return const_iterator(s_.c_str()); }
// Returns an iterator pointing past the last character in the string.
const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }
private:
std::string s_;
};
// Tests using ElementsAre() with a container whose iterator returns a
// temporary and is not copy-assignable.
TEST(ElementsAreTest, WorksWithContainerThatReturnsTempInUnassignableIterator) {
CharString2 s("abc");
EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));
EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));
}
// Tests using ElementsAreArray() with a container whose iterator returns a
// temporary and is not copy-assignable.
TEST(ElementsAreArrayTest,
WorksWithContainerThatReturnsTempInUnassignableIterator) {
CharString2 s("abc");
EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));
EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));
}
// A container whose iterator returns a temporary and is neither
// copy-constructible nor copy-assignable.
class CharString3 {
public:
using value_type = char;
class const_iterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = char;
using difference_type = std::ptrdiff_t;
using pointer = const char*;
using reference = const char&;
// Make const_iterator neither copy-constructible nor copy-assignable.
const_iterator(const const_iterator&) = delete;
const_iterator& operator=(const const_iterator&) = delete;
// Create an iterator that points to the given character.
explicit const_iterator(const char* ptr) : ptr_(ptr) {}
// Returns the current character. IMPORTANT: this must return a temporary,
// not a reference, to test that ElementsAre() works with containers whose
// iterators return temporaries.
char operator*() const { return *ptr_; }
// Advances to the next character.
const_iterator& operator++() {
++ptr_;
return *this;
}
// Compares two iterators.
bool operator==(const const_iterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const const_iterator& other) const {
return ptr_ != other.ptr_;
}
private:
const char* ptr_ = nullptr;
};
// Creates a CharString that contains the given string.
explicit CharString3(const std::string& s) : s_(s) {}
// Returns an iterator pointing to the first character in the string.
const_iterator begin() const { return const_iterator(s_.c_str()); }
// Returns an iterator pointing past the last character in the string.
const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }
private:
std::string s_;
};
// Tests using ElementsAre() with a container whose iterator returns a
// temporary and is neither copy-constructible nor copy-assignable.
TEST(ElementsAreTest, WorksWithContainerThatReturnsTempInUncopyableIterator) {
CharString3 s("abc");
EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));
EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));
}
// Tests using ElementsAreArray() with a container whose iterator returns a
// temporary and is neither copy-constructible nor copy-assignable.
TEST(ElementsAreArrayTest,
WorksWithContainerThatReturnsTempInUncopyableIterator) {
CharString3 s("abc");
EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));
EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));
}
// A container whose iterator returns a temporary, is neither
// copy-constructible nor copy-assignable, and has no member types.
class CharString4 {
public:
using value_type = char;
class const_iterator {
public:
// Do not define difference_type, etc.
// Make const_iterator neither copy-constructible nor copy-assignable.
const_iterator(const const_iterator&) = delete;
const_iterator& operator=(const const_iterator&) = delete;
// Create an iterator that points to the given character.
explicit const_iterator(const char* ptr) : ptr_(ptr) {}
// Returns the current character. IMPORTANT: this must return a temporary,
// not a reference, to test that ElementsAre() works with containers whose
// iterators return temporaries.
char operator*() const { return *ptr_; }
// Advances to the next character.
const_iterator& operator++() {
++ptr_;
return *this;
}
// Compares two iterators.
bool operator==(const const_iterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const const_iterator& other) const {
return ptr_ != other.ptr_;
}
private:
const char* ptr_ = nullptr;
};
// Creates a CharString that contains the given string.
explicit CharString4(const std::string& s) : s_(s) {}
// Returns an iterator pointing to the first character in the string.
const_iterator begin() const { return const_iterator(s_.c_str()); }
// Returns an iterator pointing past the last character in the string.
const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }
private:
std::string s_;
};
// Tests using ElementsAre() with a container whose iterator returns a
// temporary, is neither copy-constructible nor copy-assignable, and has no
// member types.
TEST(ElementsAreTest, WorksWithContainerWithIteratorWithNoMemberTypes) {
CharString4 s("abc");
EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));
EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));
}
// Tests using ElementsAreArray() with a container whose iterator returns a
// temporary, is neither copy-constructible nor copy-assignable, and has no
// member types.
TEST(ElementsAreArrayTest, WorksWithContainerWithIteratorWithNoMemberTypes) {
CharString4 s("abc");
EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));
EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));
}
// Tests using ElementsAre() and ElementsAreArray() with stream-like
// "containers".
@ -2446,7 +2148,7 @@ TEST_P(EachTestP, ExplainsMatchResultCorrectly) {
Matcher<set<int>> m = Each(2);
EXPECT_EQ("", Explain(m, a));
Matcher<const int (&)[1]> n = Each(1); // NOLINT
Matcher<const int(&)[1]> n = Each(1); // NOLINT
const int b[1] = {1};
EXPECT_EQ("", Explain(n, b));
@ -2581,7 +2283,7 @@ TEST(PointwiseTest, MakesCopyOfRhs) {
rhs.push_back(4);
int lhs[] = {1, 2};
const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs);
EXPECT_THAT(lhs, m);
// Changing rhs now shouldn't affect m, which made a copy of rhs.
@ -2709,7 +2411,7 @@ TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
rhs.push_back(4);
int lhs[] = {2, 1};
const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
EXPECT_THAT(lhs, m);
// Changing rhs now shouldn't affect m, which made a copy of rhs.
@ -2796,7 +2498,7 @@ TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
}
TEST(PointeeTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, Pointee(Eq(3)));
EXPECT_THAT(p, Not(Pointee(Eq(2))));
}
@ -2960,11 +2662,11 @@ TEST_P(ElementsAreTestP, CanExplainMismatchRightSize) {
vector<int> v;
v.push_back(2);
v.push_back(1);
EXPECT_EQ(Explain(m, v), "whose element #0 (2) isn't equal to 1");
EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
v[0] = 1;
EXPECT_EQ(Explain(m, v),
"whose element #1 (1) is <= 5, which is 4 less than 5");
EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
Explain(m, v));
}
TEST(ElementsAreTest, MatchesOneElementVector) {
@ -3364,7 +3066,7 @@ TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
TEST_P(ContainsTestP, ExplainsMatchResultCorrectly) {
const int a[2] = {1, 2};
Matcher<const int (&)[2]> m = Contains(2);
Matcher<const int(&)[2]> m = Contains(2);
EXPECT_EQ("whose element #1 matches", Explain(m, a));
m = Contains(3);

View File

@ -32,7 +32,6 @@
// This file tests some commonly used argument matchers.
#include <array>
#include <cstdint>
#include <memory>
#include <ostream>
#include <string>
@ -40,14 +39,14 @@
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#include "test/gmock-matchers_test.h"
namespace testing {
namespace gmock_matchers_test {
namespace {
@ -79,7 +78,7 @@ TEST(AddressTest, Const) {
}
TEST(AddressTest, MatcherDoesntCopy) {
std::unique_ptr<int> n = std::make_unique<int>(1);
std::unique_ptr<int> n(new int(1));
const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
EXPECT_TRUE(m.Matches(n));
@ -202,7 +201,7 @@ TEST(IsTrueTest, IsTrueIsFalse) {
EXPECT_THAT(nullptr, Not(IsTrue()));
EXPECT_THAT(nullptr, IsFalse());
std::unique_ptr<int> null_unique;
std::unique_ptr<int> nonnull_unique = std::make_unique<int>(0);
std::unique_ptr<int> nonnull_unique(new int(0));
EXPECT_THAT(null_unique, Not(IsTrue()));
EXPECT_THAT(null_unique, IsFalse());
EXPECT_THAT(nonnull_unique, IsTrue());
@ -675,8 +674,6 @@ TEST_P(MatcherTupleTestP, ExplainsMatchFailure) {
// explanation.
}
#if GTEST_HAS_TYPED_TEST
// Sample optional type implementation with minimal requirements for use with
// Optional matcher.
template <typename T>
@ -694,94 +691,38 @@ class SampleOptional {
bool has_value_;
};
// Sample optional type implementation with alternative minimal requirements for
// use with Optional matcher. In particular, while it doesn't have a bool
// conversion operator, it does have a has_value() method.
template <typename T>
class SampleOptionalWithoutBoolConversion {
public:
using value_type = T;
explicit SampleOptionalWithoutBoolConversion(T value)
: value_(std::move(value)), has_value_(true) {}
SampleOptionalWithoutBoolConversion() : value_(), has_value_(false) {}
bool has_value() const { return has_value_; }
const T& operator*() const { return value_; }
private:
T value_;
bool has_value_;
};
template <typename T>
class OptionalTest : public testing::Test {};
using OptionalTestTypes =
testing::Types<SampleOptional<int>,
SampleOptionalWithoutBoolConversion<int>>;
TYPED_TEST_SUITE(OptionalTest, OptionalTestTypes);
TYPED_TEST(OptionalTest, DescribesSelf) {
const Matcher<TypeParam> m = Optional(Eq(1));
TEST(OptionalTest, DescribesSelf) {
const Matcher<SampleOptional<int>> m = Optional(Eq(1));
EXPECT_EQ("value is equal to 1", Describe(m));
}
TYPED_TEST(OptionalTest, ExplainsSelf) {
const Matcher<TypeParam> m = Optional(Eq(1));
EXPECT_EQ("whose value 1 matches", Explain(m, TypeParam(1)));
EXPECT_EQ("whose value 2 doesn't match", Explain(m, TypeParam(2)));
TEST(OptionalTest, ExplainsSelf) {
const Matcher<SampleOptional<int>> m = Optional(Eq(1));
EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
}
TYPED_TEST(OptionalTest, MatchesNonEmptyOptional) {
const Matcher<TypeParam> m1 = Optional(1);
const Matcher<TypeParam> m2 = Optional(Eq(2));
const Matcher<TypeParam> m3 = Optional(Lt(3));
TypeParam opt(1);
TEST(OptionalTest, MatchesNonEmptyOptional) {
const Matcher<SampleOptional<int>> m1 = Optional(1);
const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
SampleOptional<int> opt(1);
EXPECT_TRUE(m1.Matches(opt));
EXPECT_FALSE(m2.Matches(opt));
EXPECT_TRUE(m3.Matches(opt));
}
TYPED_TEST(OptionalTest, DoesNotMatchNullopt) {
const Matcher<TypeParam> m = Optional(1);
TypeParam empty;
TEST(OptionalTest, DoesNotMatchNullopt) {
const Matcher<SampleOptional<int>> m = Optional(1);
SampleOptional<int> empty;
EXPECT_FALSE(m.Matches(empty));
}
TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersTakingReferences) {
const Matcher<const int&> eq1 = Eq(1);
const Matcher<const int&> eq2 = Eq(2);
TypeParam opt(1);
EXPECT_THAT(opt, Optional(eq1));
EXPECT_THAT(opt, Optional(Not(eq2)));
EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2))));
TEST(OptionalTest, WorksWithMoveOnly) {
Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
}
TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersRequiringConversion) {
const Matcher<int64_t> eq1 = Eq(1);
const Matcher<int64_t> eq2 = Eq(2);
TypeParam opt(1);
EXPECT_THAT(opt, Optional(eq1));
EXPECT_THAT(opt, Optional(Not(eq2)));
EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2))));
}
template <typename T>
class MoveOnlyOptionalTest : public testing::Test {};
using MoveOnlyOptionalTestTypes =
testing::Types<SampleOptional<std::unique_ptr<int>>,
SampleOptionalWithoutBoolConversion<std::unique_ptr<int>>>;
TYPED_TEST_SUITE(MoveOnlyOptionalTest, MoveOnlyOptionalTestTypes);
TYPED_TEST(MoveOnlyOptionalTest, WorksWithMoveOnly) {
Matcher<TypeParam> m = Optional(Eq(nullptr));
EXPECT_TRUE(m.Matches(TypeParam(nullptr)));
}
#endif // GTEST_HAS_TYPED_TEST
class SampleVariantIntString {
public:
SampleVariantIntString(int i) : i_(i), has_int_(true) {}
@ -1635,10 +1576,10 @@ TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {
const Matcher<int> m1 = AnyOfArray(v1);
const Matcher<int> m2 = AnyOfArray(v2);
EXPECT_EQ("", Explain(m0, 0));
EXPECT_EQ("which matches (is equal to 1)", Explain(m1, 1));
EXPECT_EQ("isn't equal to 1", Explain(m1, 2));
EXPECT_EQ("which matches (is equal to 3)", Explain(m2, 3));
EXPECT_EQ("isn't equal to 2, and isn't equal to 3", Explain(m2, 4));
EXPECT_EQ("", Explain(m1, 1));
EXPECT_EQ("", Explain(m1, 2));
EXPECT_EQ("", Explain(m2, 3));
EXPECT_EQ("", Explain(m2, 4));
EXPECT_EQ("()", Describe(m0));
EXPECT_EQ("(is equal to 1)", Describe(m1));
EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
@ -1665,7 +1606,7 @@ MATCHER(IsNotNull, "") { return arg != nullptr; }
// Verifies that a matcher defined using MATCHER() can work on
// move-only types.
TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, IsNotNull());
EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
}
@ -1675,7 +1616,7 @@ MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
// Verifies that a matcher defined using MATCHER_P*() can work on
// move-only types.
TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, UniquePointee(3));
EXPECT_THAT(p, Not(UniquePointee(2)));
}

View File

@ -59,7 +59,6 @@ using testing::Invoke;
using testing::ReturnArg;
using testing::ReturnPointee;
using testing::SaveArg;
using testing::SaveArgByMove;
using testing::SaveArgPointee;
using testing::SetArgReferee;
using testing::Unused;
@ -202,45 +201,45 @@ class Foo {
// Tests using Invoke() with a nullary function.
TEST(InvokeTest, Nullary) {
Action<int()> a = &Nullary;
Action<int()> a = Invoke(Nullary); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple()));
}
// Tests using Invoke() with a unary function.
TEST(InvokeTest, Unary) {
Action<bool(int)> a = &Unary;
Action<bool(int)> a = Invoke(Unary); // NOLINT
EXPECT_FALSE(a.Perform(std::make_tuple(1)));
EXPECT_TRUE(a.Perform(std::make_tuple(-1)));
}
// Tests using Invoke() with a binary function.
TEST(InvokeTest, Binary) {
Action<const char*(const char*, short)> a = &Binary; // NOLINT
Action<const char*(const char*, short)> a = Invoke(Binary); // NOLINT
const char* p = "Hello";
EXPECT_EQ(p + 2, a.Perform(std::make_tuple(p, Short(2))));
}
// Tests using Invoke() with a ternary function.
TEST(InvokeTest, Ternary) {
Action<int(int, char, short)> a = &Ternary; // NOLINT
Action<int(int, char, short)> a = Invoke(Ternary); // NOLINT
EXPECT_EQ(6, a.Perform(std::make_tuple(1, '\2', Short(3))));
}
// Tests using Invoke() with a 4-argument function.
TEST(InvokeTest, FunctionThatTakes4Arguments) {
Action<int(int, int, int, int)> a = &SumOf4;
Action<int(int, int, int, int)> a = Invoke(SumOf4); // NOLINT
EXPECT_EQ(1234, a.Perform(std::make_tuple(1000, 200, 30, 4)));
}
// Tests using Invoke() with a 5-argument function.
TEST(InvokeTest, FunctionThatTakes5Arguments) {
Action<int(int, int, int, int, int)> a = &SumOf5;
Action<int(int, int, int, int, int)> a = Invoke(SumOf5); // NOLINT
EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5)));
}
// Tests using Invoke() with a 6-argument function.
TEST(InvokeTest, FunctionThatTakes6Arguments) {
Action<int(int, int, int, int, int, int)> a = &SumOf6;
Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6); // NOLINT
EXPECT_EQ(123456,
a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6)));
}
@ -253,7 +252,7 @@ inline const char* CharPtr(const char* s) { return s; }
TEST(InvokeTest, FunctionThatTakes7Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*)>
a = &Concat7;
a = Invoke(Concat7);
EXPECT_EQ("1234567",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
@ -264,7 +263,7 @@ TEST(InvokeTest, FunctionThatTakes7Arguments) {
TEST(InvokeTest, FunctionThatTakes8Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*)>
a = &Concat8;
a = Invoke(Concat8);
EXPECT_EQ("12345678",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
@ -276,7 +275,7 @@ TEST(InvokeTest, FunctionThatTakes9Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*,
const char*)>
a = &Concat9;
a = Invoke(Concat9);
EXPECT_EQ("123456789", a.Perform(std::make_tuple(
CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
@ -288,7 +287,7 @@ TEST(InvokeTest, FunctionThatTakes10Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*,
const char*, const char*)>
a = &Concat10;
a = Invoke(Concat10);
EXPECT_EQ("1234567890",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
@ -298,12 +297,12 @@ TEST(InvokeTest, FunctionThatTakes10Arguments) {
// Tests using Invoke() with functions with parameters declared as Unused.
TEST(InvokeTest, FunctionWithUnusedParameters) {
Action<int(int, int, double, const std::string&)> a1 = &SumOfFirst2;
Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2);
std::tuple<int, int, double, std::string> dummy =
std::make_tuple(10, 2, 5.6, std::string("hi"));
EXPECT_EQ(12, a1.Perform(dummy));
Action<int(int, int, bool, int*)> a2 = &SumOfFirst2;
Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2);
EXPECT_EQ(
23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr))));
}
@ -320,13 +319,13 @@ TEST(InvokeTest, MethodWithUnusedParameters) {
// Tests using Invoke() with a functor.
TEST(InvokeTest, Functor) {
Action<long(long, int)> a = plus<long>(); // NOLINT
Action<long(long, int)> a = Invoke(plus<long>()); // NOLINT
EXPECT_EQ(3L, a.Perform(std::make_tuple(1, 2)));
}
// Tests using Invoke(f) as an action of a compatible type.
TEST(InvokeTest, FunctionWithCompatibleType) {
Action<long(int, short, char, bool)> a = &SumOf4; // NOLINT
Action<long(int, short, char, bool)> a = Invoke(SumOf4); // NOLINT
EXPECT_EQ(4321, a.Perform(std::make_tuple(4000, Short(300), Char(20), true)));
}
@ -447,13 +446,13 @@ TEST(InvokeMethodTest, MethodWithCompatibleType) {
// Tests using WithoutArgs with an action that takes no argument.
TEST(WithoutArgsTest, NoArg) {
Action<int(int n)> a = WithoutArgs(&Nullary); // NOLINT
Action<int(int n)> a = WithoutArgs(Invoke(Nullary)); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
}
// Tests using WithArg with an action that takes 1 argument.
TEST(WithArgTest, OneArg) {
Action<bool(double x, int n)> b = WithArg<1>(&Unary); // NOLINT
Action<bool(double x, int n)> b = WithArg<1>(Invoke(Unary)); // NOLINT
EXPECT_TRUE(b.Perform(std::make_tuple(1.5, -1)));
EXPECT_FALSE(b.Perform(std::make_tuple(1.5, 1)));
}
@ -493,34 +492,6 @@ TEST(SaveArgActionTest, WorksForCompatibleType) {
EXPECT_EQ('a', result);
}
struct MoveOnly {
explicit MoveOnly(int v) : i(v) {}
MoveOnly(MoveOnly&& o) {
i = o.i;
o.i = -1;
}
MoveOnly& operator=(MoveOnly&& o) {
i = o.i;
o.i = -1;
return *this;
}
int i;
};
TEST(SaveArgByMoveActionTest, WorksForSameType) {
MoveOnly result{0};
const Action<void(MoveOnly v)> a1 = SaveArgByMove<0>(&result);
a1.Perform(std::make_tuple(MoveOnly{5}));
EXPECT_EQ(5, result.i);
}
TEST(SaveArgByMoveActionTest, WorksForCompatibleType) {
MoveOnly result{0};
const Action<void(bool, MoveOnly)> a1 = SaveArgByMove<1>(&result);
a1.Perform(std::make_tuple(true, MoveOnly{7}));
EXPECT_EQ(7, result.i);
}
TEST(SaveArgPointeeActionTest, WorksForSameType) {
int result = 0;
const int value = 5;
@ -785,34 +756,34 @@ TEST(InvokeArgumentTest, Functor6) {
// Tests using InvokeArgument with a 7-ary function.
TEST(InvokeArgumentTest, Function7) {
Action<std::string(std::string (*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*))>
Action<std::string(std::string(*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*))>
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7)));
}
// Tests using InvokeArgument with a 8-ary function.
TEST(InvokeArgumentTest, Function8) {
Action<std::string(std::string (*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*, const char*))>
Action<std::string(std::string(*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*, const char*))>
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8)));
}
// Tests using InvokeArgument with a 9-ary function.
TEST(InvokeArgumentTest, Function9) {
Action<std::string(std::string (*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*, const char*, const char*))>
Action<std::string(std::string(*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*, const char*, const char*))>
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9)));
}
// Tests using InvokeArgument with a 10-ary function.
TEST(InvokeArgumentTest, Function10) {
Action<std::string(std::string (*)(
Action<std::string(std::string(*)(
const char*, const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*, const char*))>
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");

View File

@ -70,7 +70,7 @@ static_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y) == 2, "");
static_assert(GMOCK_PP_INTERNAL_VAR_TEST(silly) == 1, "");
static_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y, z) == 3, "");
// TODO(iserna): The following asserts fail in --config=windows.
// TODO(iserna): The following asserts fail in --config=lexan.
#define GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1
static_assert(GMOCK_PP_IS_EMPTY(GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1), "");
static_assert(GMOCK_PP_IS_EMPTY(), "");

View File

@ -160,7 +160,7 @@ class MockCC : public CC {
// Tests that a method with expanded name compiles.
TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
MockCC cc;
(void)ON_CALL(cc, Method());
ON_CALL(cc, Method());
}
// Tests that the method with expanded name not only compiles but runs
@ -193,7 +193,7 @@ TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
MockA a;
MockA* pa = &a;
(void)ON_CALL(*pa++, DoA(_));
ON_CALL(*pa++, DoA(_));
EXPECT_EQ(&a + 1, pa);
}
@ -201,7 +201,7 @@ TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
MockA a;
int n = 0;
(void)ON_CALL(a, DoA(n++));
ON_CALL(a, DoA(n++));
EXPECT_EQ(1, n);
}
@ -232,7 +232,7 @@ TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
EXPECT_DEATH_IF_SUPPORTED(
{
(void)ON_CALL(a, DoA(5));
ON_CALL(a, DoA(5));
a.DoA(5);
},
"");
@ -804,8 +804,9 @@ TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
"to be called at least once");
}
// TODO(b/396121064) - Fix this test under MSVC
#ifndef _MSC_VER
#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
// It should be possible to return a non-moveable type from a mock action in
// C++17 and above, where it's guaranteed that such a type can be initialized
// from a prvalue returned from a function.
@ -846,7 +847,7 @@ TEST(ExpectCallTest, NonMoveableType) {
EXPECT_EQ(17, mock.AsStdFunction()().x);
}
#endif // _MSC_VER
#endif // C++17 and above
// Tests that the n-th action is taken for the n-th matching
// invocation.
@ -2045,7 +2046,7 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
NaggyMock<MockA> a;
const std::string note =
"NOTE: You can safely ignore the above warning unless this "
"call should not happen. Do not suppress it by adding "
"call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See "
"https://github.com/google/googletest/blob/main/docs/"

View File

@ -186,8 +186,8 @@ using testing::SetErrnoAndReturn;
#endif
#if GTEST_HAS_EXCEPTIONS
using testing::Rethrow;
using testing::Throw;
using testing::Rethrow;
#endif
using testing::ContainsRegex;

View File

@ -79,14 +79,14 @@ GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: Bar2(0, 1)
Returns: false
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
[ OK ] GMockOutputTest.UninterestingCall
[ RUN ] GMockOutputTest.UninterestingCallToVoidFunction
GMOCK WARNING:
Uninteresting mock function call - returning directly.
Function call: Bar3(0, 1)
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure
@ -283,14 +283,14 @@ Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(2, 2)
Returns: true
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(1, 1)
Returns: false
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction

View File

@ -132,6 +132,9 @@ if(GTEST_HAS_ABSL)
absl::flags_reflection
absl::flags_usage
absl::strings
absl::any
absl::optional
absl::variant
re2::re2
)
endif()

View File

@ -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.17.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
@ -124,9 +124,9 @@ match the project in which it is included.
#### C++ Standard Version
An environment that supports C++17 is required in order to successfully build
An environment that supports C++14 is required in order to successfully build
GoogleTest. One way to ensure this is to specify the standard in the top-level
project, for example by using the `set(CMAKE_CXX_STANDARD 17)` command along
project, for example by using the `set(CMAKE_CXX_STANDARD 14)` command along
with `set(CMAKE_CXX_STANDARD_REQUIRED ON)`. If this is not feasible, for example
in a C project using GoogleTest for validation, then it can be specified by
adding it to the options for cmake via the`-DCMAKE_CXX_FLAGS` option.
@ -145,9 +145,9 @@ We list the most frequently used macros below. For a complete list, see file
### Multi-threaded Tests
GoogleTest is thread-safe where the pthread library is available. After
`#include <gtest/gtest.h>`, you can check the `GTEST_IS_THREADSAFE` macro to see
whether this is the case (yes if the macro is `#defined` to 1, no if it's
undefined.).
`#include <gtest/gtest.h>`, you can check the
`GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is
`#defined` to 1, no if it's undefined.).
If GoogleTest doesn't correctly detect whether pthread is available in your
environment, you can force it with

View File

@ -195,7 +195,7 @@ function(cxx_library_with_type name type cxx_flags)
target_link_libraries(${name} PUBLIC Threads::Threads)
endif()
target_compile_features(${name} PUBLIC cxx_std_17)
target_compile_features(${name} PUBLIC cxx_std_14)
endfunction()
########################################################################

View File

@ -129,15 +129,8 @@ namespace testing {
//
// Expected: Foo() is even
// Actual: it's 5
//
// Returned AssertionResult objects may not be ignored.
// Note: Disabled for SWIG as it doesn't parse attributes correctly.
#if !defined(SWIG)
class [[nodiscard]] AssertionResult;
#endif // !SWIG
class GTEST_API_ [[nodiscard]] AssertionResult {
class GTEST_API_ AssertionResult {
public:
// Copy constructor.
// Used in EXPECT_TRUE/FALSE(assertion_result).

View File

@ -192,7 +192,7 @@ GTEST_API_ bool InDeathTestChild();
// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
// Tests that an exit code describes a normal exit with a given exit code.
class GTEST_API_ [[nodiscard]] ExitedWithCode {
class GTEST_API_ ExitedWithCode {
public:
explicit ExitedWithCode(int exit_code);
ExitedWithCode(const ExitedWithCode&) = default;
@ -206,7 +206,7 @@ class GTEST_API_ [[nodiscard]] ExitedWithCode {
#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
// Tests that an exit code describes an exit due to termination by a
// given signal.
class GTEST_API_ [[nodiscard]] KilledBySignal {
class GTEST_API_ KilledBySignal {
public:
explicit KilledBySignal(int signum);
bool operator()(int exit_status) const;
@ -317,7 +317,7 @@ class GTEST_API_ [[nodiscard]] KilledBySignal {
GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \
<< "Statement '" #statement "' cannot be verified."; \
} else if (::testing::internal::AlwaysFalse()) { \
(void)::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
terminator; \
} else \

View File

@ -67,15 +67,15 @@ namespace testing {
// To implement a matcher Foo for type T, define:
// 1. a class FooMatcherMatcher that implements the matcher interface:
// using is_gtest_matcher = void;
// bool MatchAndExplain(const T&, std::ostream*) const;
// bool MatchAndExplain(const T&, std::ostream*);
// (MatchResultListener* can also be used instead of std::ostream*)
// void DescribeTo(std::ostream*) const;
// void DescribeNegationTo(std::ostream*) const;
// void DescribeTo(std::ostream*);
// void DescribeNegationTo(std::ostream*);
//
// 2. a factory function that creates a Matcher<T> object from a
// FooMatcherMatcher.
class [[nodiscard]] MatchResultListener {
class MatchResultListener {
public:
// Creates a listener object with the given underlying ostream. The
// listener does not own the ostream, and does not dereference it
@ -111,7 +111,7 @@ inline MatchResultListener::~MatchResultListener() = default;
// An instance of a subclass of this knows how to describe itself as a
// matcher.
class GTEST_API_ [[nodiscard]] MatcherDescriberInterface {
class GTEST_API_ MatcherDescriberInterface {
public:
virtual ~MatcherDescriberInterface() = default;
@ -137,7 +137,7 @@ class GTEST_API_ [[nodiscard]] MatcherDescriberInterface {
// The implementation of a matcher.
template <typename T>
class [[nodiscard]] MatcherInterface : public MatcherDescriberInterface {
class MatcherInterface : public MatcherDescriberInterface {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener' if necessary (see the next paragraph), in
@ -180,7 +180,7 @@ class [[nodiscard]] MatcherInterface : public MatcherDescriberInterface {
namespace internal {
// A match result listener that ignores the explanation.
class [[nodiscard]] DummyMatchResultListener : public MatchResultListener {
class DummyMatchResultListener : public MatchResultListener {
public:
DummyMatchResultListener() : MatchResultListener(nullptr) {}
@ -192,7 +192,7 @@ class [[nodiscard]] DummyMatchResultListener : public MatchResultListener {
// A match result listener that forwards the explanation to a given
// ostream. The difference between this and MatchResultListener is
// that the former is concrete.
class [[nodiscard]] StreamMatchResultListener : public MatchResultListener {
class StreamMatchResultListener : public MatchResultListener {
public:
explicit StreamMatchResultListener(::std::ostream* os)
: MatchResultListener(os) {}
@ -225,7 +225,7 @@ struct SharedPayload : SharedPayloadBase {
// from it. We put functionalities common to all Matcher<T>
// specializations here to avoid code duplication.
template <typename T>
class [[nodiscard]] MatcherBase : private MatcherDescriberInterface {
class MatcherBase : private MatcherDescriberInterface {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener'.
@ -296,12 +296,12 @@ class [[nodiscard]] MatcherBase : private MatcherDescriberInterface {
return *this;
}
MatcherBase(MatcherBase&& other) noexcept
MatcherBase(MatcherBase&& other)
: vtable_(other.vtable_), buffer_(other.buffer_) {
other.vtable_ = nullptr;
}
MatcherBase& operator=(MatcherBase&& other) noexcept {
MatcherBase& operator=(MatcherBase&& other) {
if (this == &other) return *this;
Destroy();
vtable_ = other.vtable_;
@ -460,7 +460,7 @@ class [[nodiscard]] MatcherBase : private MatcherDescriberInterface {
// implementation of Matcher<T> is just a std::shared_ptr to const
// MatcherInterface<T>. Don't inherit from Matcher!
template <typename T>
class [[nodiscard]] Matcher : public internal::MatcherBase<T> {
class Matcher : public internal::MatcherBase<T> {
public:
// Constructs a null matcher. Needed for storing Matcher objects in STL
// containers. A default-constructed matcher is not yet initialized. You
@ -491,8 +491,8 @@ class [[nodiscard]] Matcher : public internal::MatcherBase<T> {
// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
// matcher is expected.
template <>
class GTEST_API_ [[nodiscard]]
Matcher<const std::string&> : public internal::MatcherBase<const std::string&> {
class GTEST_API_ Matcher<const std::string&>
: public internal::MatcherBase<const std::string&> {
public:
Matcher() = default;
@ -513,8 +513,8 @@ Matcher<const std::string&> : public internal::MatcherBase<const std::string&> {
};
template <>
class GTEST_API_ [[nodiscard]]
Matcher<std::string> : public internal::MatcherBase<std::string> {
class GTEST_API_ Matcher<std::string>
: public internal::MatcherBase<std::string> {
public:
Matcher() = default;
@ -541,7 +541,7 @@ Matcher<std::string> : public internal::MatcherBase<std::string> {
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
// matcher is expected.
template <>
class GTEST_API_ [[nodiscard]] Matcher<const internal::StringView&>
class GTEST_API_ Matcher<const internal::StringView&>
: public internal::MatcherBase<const internal::StringView&> {
public:
Matcher() = default;
@ -567,7 +567,7 @@ class GTEST_API_ [[nodiscard]] Matcher<const internal::StringView&>
};
template <>
class GTEST_API_ [[nodiscard]] Matcher<internal::StringView>
class GTEST_API_ Matcher<internal::StringView>
: public internal::MatcherBase<internal::StringView> {
public:
Matcher() = default;
@ -614,7 +614,7 @@ std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
//
// See the definition of NotNull() for a complete example.
template <class Impl>
class [[nodiscard]] PolymorphicMatcher {
class PolymorphicMatcher {
public:
explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
@ -689,7 +689,7 @@ namespace internal {
// The following template definition assumes that the Rhs parameter is
// a "bare" type (i.e. neither 'const T' nor 'T&').
template <typename D, typename Rhs, typename Op>
class [[nodiscard]] ComparisonBase {
class ComparisonBase {
public:
explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
@ -722,8 +722,7 @@ class [[nodiscard]] ComparisonBase {
};
template <typename Rhs>
class [[nodiscard]] EqMatcher
: public ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>> {
class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>> {
public:
explicit EqMatcher(const Rhs& rhs)
: ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>>(rhs) {}
@ -731,7 +730,7 @@ class [[nodiscard]] EqMatcher
static const char* NegatedDesc() { return "isn't equal to"; }
};
template <typename Rhs>
class [[nodiscard]] NeMatcher
class NeMatcher
: public ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>> {
public:
explicit NeMatcher(const Rhs& rhs)
@ -740,8 +739,7 @@ class [[nodiscard]] NeMatcher
static const char* NegatedDesc() { return "is equal to"; }
};
template <typename Rhs>
class [[nodiscard]] LtMatcher
: public ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>> {
class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>> {
public:
explicit LtMatcher(const Rhs& rhs)
: ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>>(rhs) {}
@ -749,8 +747,7 @@ class [[nodiscard]] LtMatcher
static const char* NegatedDesc() { return "isn't <"; }
};
template <typename Rhs>
class [[nodiscard]] GtMatcher
: public ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>> {
class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>> {
public:
explicit GtMatcher(const Rhs& rhs)
: ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>>(rhs) {}
@ -758,7 +755,7 @@ class [[nodiscard]] GtMatcher
static const char* NegatedDesc() { return "isn't >"; }
};
template <typename Rhs>
class [[nodiscard]] LeMatcher
class LeMatcher
: public ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>> {
public:
explicit LeMatcher(const Rhs& rhs)
@ -767,7 +764,7 @@ class [[nodiscard]] LeMatcher
static const char* NegatedDesc() { return "isn't <="; }
};
template <typename Rhs>
class [[nodiscard]] GeMatcher
class GeMatcher
: public ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>> {
public:
explicit GeMatcher(const Rhs& rhs)
@ -776,35 +773,6 @@ class [[nodiscard]] GeMatcher
static const char* NegatedDesc() { return "isn't >="; }
};
// Same as `EqMatcher<Rhs>`, except that the `rhs` is stored as `StoredRhs` and
// must be implicitly convertible to `Rhs`.
template <typename Rhs, typename StoredRhs>
class [[nodiscard]] ImplicitCastEqMatcher {
public:
explicit ImplicitCastEqMatcher(const StoredRhs& rhs) : stored_rhs_(rhs) {}
using is_gtest_matcher = void;
template <typename Lhs>
bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
return lhs == rhs();
}
void DescribeTo(std::ostream* os) const {
*os << "is equal to ";
UniversalPrint(rhs(), os);
}
void DescribeNegationTo(std::ostream* os) const {
*os << "isn't equal to ";
UniversalPrint(rhs(), os);
}
private:
Rhs rhs() const { return ImplicitCast_<Rhs>(stored_rhs_); }
StoredRhs stored_rhs_;
};
template <typename T, typename = typename std::enable_if<
std::is_constructible<std::string, T>::value>::type>
using StringLike = T;
@ -812,7 +780,7 @@ using StringLike = T;
// Implements polymorphic matchers MatchesRegex(regex) and
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
// T can be converted to a string.
class [[nodiscard]] MatchesRegexMatcher {
class MatchesRegexMatcher {
public:
MatchesRegexMatcher(const RE* regex, bool full_match)
: regex_(regex), full_match_(full_match) {}

View File

@ -174,7 +174,6 @@ TEST_P(DerivedTest, DoesBlah) {
#endif // 0
#include <functional>
#include <iterator>
#include <utility>
@ -414,8 +413,7 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
// Synopsis:
// ConvertGenerator<T>(gen)
// - returns a generator producing the same elements as generated by gen, but
// each T-typed element is static_cast to a type deduced from the interface
// that accepts this generator, and then returned
// each element is static_cast to type T before being returned
//
// It is useful when using the Combine() function to get the generated
// parameters in a custom type instead of std::tuple
@ -443,65 +441,10 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
// Combine(Values("cat", "dog"),
// Values(BLACK, WHITE))));
//
template <typename RequestedT>
internal::ParamConverterGenerator<RequestedT> ConvertGenerator(
internal::ParamGenerator<RequestedT> gen) {
return internal::ParamConverterGenerator<RequestedT>(std::move(gen));
}
// As above, but takes a callable as a second argument. The callable converts
// the generated parameter to the test fixture's parameter type. This allows you
// to use a parameter type that does not have a converting constructor from the
// generated type.
//
// Example:
//
// This will instantiate tests in test suite AnimalTest each one with
// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
// tuple("dog", BLACK), and tuple("dog", WHITE):
//
// enum Color { BLACK, GRAY, WHITE };
// struct ParamType {
// std::string animal;
// Color color;
// };
// class AnimalTest
// : public testing::TestWithParam<ParamType> {...};
//
// TEST_P(AnimalTest, AnimalLooksNice) {...}
//
// INSTANTIATE_TEST_SUITE_P(
// AnimalVariations, AnimalTest,
// ConvertGenerator(Combine(Values("cat", "dog"), Values(BLACK, WHITE)),
// [](std::tuple<std::string, Color> t) {
// return ParamType{.animal = std::get<0>(t),
// .color = std::get<1>(t)};
// }));
//
template <typename T, int&... ExplicitArgumentBarrier, typename Gen,
typename Func,
typename StdFunction = decltype(std::function(std::declval<Func>()))>
internal::ParamConverterGenerator<T, StdFunction> ConvertGenerator(Gen&& gen,
Func&& f) {
return internal::ParamConverterGenerator<T, StdFunction>(
std::forward<Gen>(gen), std::forward<Func>(f));
}
// As above, but infers the T from the supplied std::function instead of
// having the caller specify it.
template <int&... ExplicitArgumentBarrier, typename Gen, typename Func,
typename StdFunction = decltype(std::function(std::declval<Func>()))>
auto ConvertGenerator(Gen&& gen, Func&& f) {
constexpr bool is_single_arg_std_function =
internal::IsSingleArgStdFunction<StdFunction>::value;
if constexpr (is_single_arg_std_function) {
return ConvertGenerator<
typename internal::FuncSingleParamType<StdFunction>::type>(
std::forward<Gen>(gen), std::forward<Func>(f));
} else {
static_assert(is_single_arg_std_function,
"The call signature must contain a single argument.");
}
template <typename T>
internal::ParamConverterGenerator<T> ConvertGenerator(
internal::ParamGenerator<T> gen) {
return internal::ParamConverterGenerator<T>(gen);
}
#define TEST_P(test_suite_name, test_name) \
@ -526,7 +469,7 @@ auto ConvertGenerator(Gen&& gen, Func&& f) {
::testing::internal::CodeLocation(__FILE__, __LINE__)); \
return 0; \
} \
[[maybe_unused]] static int gtest_registering_dummy_; \
GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static int gtest_registering_dummy_; \
}; \
int GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)::gtest_registering_dummy_ = \
@ -550,38 +493,39 @@ auto ConvertGenerator(Gen&& gen, Func&& f) {
#define GTEST_GET_FIRST_(first, ...) first
#define GTEST_GET_SECOND_(first, second, ...) second
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
gtest_##prefix##test_suite_name##_EvalGenerator_() { \
return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
} \
static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
if (::testing::internal::AlwaysFalse()) { \
::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))); \
auto t = std::make_tuple(__VA_ARGS__); \
static_assert(std::tuple_size<decltype(t)>::value <= 2, \
"Too Many Args!"); \
} \
return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))))(info); \
} \
[[maybe_unused]] static int gtest_##prefix##test_suite_name##_dummy_ = \
::testing::UnitTest::GetInstance() \
->parameterized_test_registry() \
.GetTestSuitePatternHolder<test_suite_name>( \
GTEST_STRINGIFY_(test_suite_name), \
::testing::internal::CodeLocation(__FILE__, __LINE__)) \
->AddTestSuiteInstantiation( \
GTEST_STRINGIFY_(prefix), \
&gtest_##prefix##test_suite_name##_EvalGenerator_, \
&gtest_##prefix##test_suite_name##_EvalGenerateName_, __FILE__, \
__LINE__)
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
gtest_##prefix##test_suite_name##_EvalGenerator_() { \
return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
} \
static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
if (::testing::internal::AlwaysFalse()) { \
::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))); \
auto t = std::make_tuple(__VA_ARGS__); \
static_assert(std::tuple_size<decltype(t)>::value <= 2, \
"Too Many Args!"); \
} \
return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))))(info); \
} \
GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static int \
gtest_##prefix##test_suite_name##_dummy_ = \
::testing::UnitTest::GetInstance() \
->parameterized_test_registry() \
.GetTestSuitePatternHolder<test_suite_name>( \
GTEST_STRINGIFY_(test_suite_name), \
::testing::internal::CodeLocation(__FILE__, __LINE__)) \
->AddTestSuiteInstantiation( \
GTEST_STRINGIFY_(prefix), \
&gtest_##prefix##test_suite_name##_EvalGenerator_, \
&gtest_##prefix##test_suite_name##_EvalGenerateName_, \
__FILE__, __LINE__)
// Allow Marking a Parameterized test class as not needing to be instantiated.
#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \

View File

@ -104,19 +104,15 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#include <any>
#include <functional>
#include <memory>
#include <optional>
#include <ostream> // NOLINT
#include <sstream>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <variant>
#include <vector>
#ifdef GTEST_HAS_ABSL
@ -130,10 +126,6 @@
#include <span> // NOLINT
#endif // GTEST_INTERNAL_HAS_STD_SPAN
#if GTEST_INTERNAL_HAS_COMPARE_LIB
#include <compare> // NOLINT
#endif // GTEST_INTERNAL_HAS_COMPARE_LIB
namespace testing {
// Definitions in the internal* namespaces are subject to change without notice.
@ -249,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;
@ -382,7 +374,7 @@ void PrintWithFallback(const T& value, ::std::ostream* os) {
// The default case.
template <typename ToPrint, typename OtherOperand>
class [[nodiscard]] FormatForComparison {
class FormatForComparison {
public:
static ::std::string Format(const ToPrint& value) {
return ::testing::PrintToString(value);
@ -391,7 +383,7 @@ class [[nodiscard]] FormatForComparison {
// Array.
template <typename ToPrint, size_t N, typename OtherOperand>
class [[nodiscard]] FormatForComparison<ToPrint[N], OtherOperand> {
class FormatForComparison<ToPrint[N], OtherOperand> {
public:
static ::std::string Format(const ToPrint* value) {
return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
@ -477,7 +469,7 @@ std::string FormatForComparisonFailureMessage(const T1& value,
// function template), as we need to partially specialize it for
// reference types, which cannot be done with function templates.
template <typename T>
class [[nodiscard]] UniversalPrinter;
class UniversalPrinter;
// Prints the given value using the << operator if it has one;
// otherwise prints the bytes in it. This is what
@ -525,15 +517,11 @@ GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
inline void PrintTo(char16_t c, ::std::ostream* os) {
// TODO(b/418738869): Incorrect for values not representing valid codepoints.
// Also see https://github.com/google/googletest/issues/4762.
PrintTo(static_cast<char32_t>(c), os);
PrintTo(ImplicitCast_<char32_t>(c), os);
}
#ifdef __cpp_lib_char8_t
inline void PrintTo(char8_t c, ::std::ostream* os) {
// TODO(b/418738869): Incorrect for values not representing valid codepoints.
// Also see https://github.com/google/googletest/issues/4762.
PrintTo(static_cast<char32_t>(c), os);
PrintTo(ImplicitCast_<char32_t>(c), os);
}
#endif
@ -703,63 +691,44 @@ void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
}
}
// Overloads for ::std::string and ::std::string_view
GTEST_API_ void PrintStringTo(::std::string_view s, ::std::ostream* os);
// Overloads for ::std::string.
GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os);
inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
PrintStringTo(s, os);
}
inline void PrintTo(::std::string_view s, ::std::ostream* os) {
PrintStringTo(s, os);
}
// Overloads for ::std::u8string and ::std::u8string_view
// Overloads for ::std::u8string
#ifdef __cpp_lib_char8_t
GTEST_API_ void PrintU8StringTo(::std::u8string_view s, ::std::ostream* os);
GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
PrintU8StringTo(s, os);
}
inline void PrintTo(::std::u8string_view s, ::std::ostream* os) {
PrintU8StringTo(s, os);
}
#endif
// Overloads for ::std::u16string and ::std::u16string_view
GTEST_API_ void PrintU16StringTo(::std::u16string_view s, ::std::ostream* os);
// Overloads for ::std::u16string
GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
PrintU16StringTo(s, os);
}
inline void PrintTo(::std::u16string_view s, ::std::ostream* os) {
PrintU16StringTo(s, os);
}
// Overloads for ::std::u32string and ::std::u32string_view
GTEST_API_ void PrintU32StringTo(::std::u32string_view s, ::std::ostream* os);
// Overloads for ::std::u32string
GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
PrintU32StringTo(s, os);
}
inline void PrintTo(::std::u32string_view s, ::std::ostream* os) {
PrintU32StringTo(s, os);
}
// Overloads for ::std::wstring and ::std::wstring_view
// Overloads for ::std::wstring.
#if GTEST_HAS_STD_WSTRING
GTEST_API_ void PrintWideStringTo(::std::wstring_view s, ::std::ostream* os);
GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os);
inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
PrintWideStringTo(s, os);
}
inline void PrintTo(::std::wstring_view s, ::std::ostream* os) {
PrintWideStringTo(s, os);
}
#endif // GTEST_HAS_STD_WSTRING
#if GTEST_INTERNAL_HAS_STRING_VIEW
// Overload for internal::StringView. Needed for build configurations where
// internal::StringView is an alias for absl::string_view, but absl::string_view
// is a distinct type from std::string_view.
template <int&... ExplicitArgumentBarrier, typename T = internal::StringView,
std::enable_if_t<!std::is_same_v<T, ::std::string_view>, int> = 0>
// Overload for internal::StringView.
inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
PrintStringTo(sp, os);
PrintTo(::std::string(sp), os);
}
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
@ -813,41 +782,6 @@ void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
(PrintSmartPointer<T>)(ptr, os, 0);
}
#if GTEST_INTERNAL_HAS_COMPARE_LIB
template <typename T>
void PrintOrderingHelper(T ordering, std::ostream* os) {
if (ordering == T::less) {
*os << "(less)";
} else if (ordering == T::greater) {
*os << "(greater)";
} else if (ordering == T::equivalent) {
*os << "(equivalent)";
} else {
*os << "(unknown ordering)";
}
}
inline void PrintTo(std::strong_ordering ordering, std::ostream* os) {
if (ordering == std::strong_ordering::equal) {
*os << "(equal)";
} else {
PrintOrderingHelper(ordering, os);
}
}
inline void PrintTo(std::partial_ordering ordering, std::ostream* os) {
if (ordering == std::partial_ordering::unordered) {
*os << "(unordered)";
} else {
PrintOrderingHelper(ordering, os);
}
}
inline void PrintTo(std::weak_ordering ordering, std::ostream* os) {
PrintOrderingHelper(ordering, os);
}
#endif
// Helper function for printing a tuple. T must be instantiated with
// a tuple type.
template <typename T>
@ -889,7 +823,7 @@ void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
// Implements printing a non-reference type T by letting the compiler
// pick the right overload of PrintTo() for T.
template <typename T>
class [[nodiscard]] UniversalPrinter {
class UniversalPrinter {
public:
// MSVC warns about adding const to a function type, so we want to
// disable the warning.
@ -915,13 +849,16 @@ class [[nodiscard]] UniversalPrinter {
// Remove any const-qualifiers before passing a type to UniversalPrinter.
template <typename T>
class [[nodiscard]] UniversalPrinter<const T> : public UniversalPrinter<T> {};
class UniversalPrinter<const T> : public UniversalPrinter<T> {};
#if GTEST_INTERNAL_HAS_ANY
// Printer for std::any / absl::any
// Printer for std::any
template <>
class [[nodiscard]] UniversalPrinter<std::any> {
class UniversalPrinter<Any> {
public:
static void Print(const std::any& value, ::std::ostream* os) {
static void Print(const Any& value, ::std::ostream* os) {
if (value.has_value()) {
*os << "value of type " << GetTypeName(value);
} else {
@ -930,7 +867,7 @@ class [[nodiscard]] UniversalPrinter<std::any> {
}
private:
static std::string GetTypeName(const std::any& value) {
static std::string GetTypeName(const Any& value) {
#if GTEST_HAS_RTTI
return internal::GetTypeName(value.type());
#else
@ -940,11 +877,16 @@ class [[nodiscard]] UniversalPrinter<std::any> {
}
};
// Printer for std::optional
#endif // GTEST_INTERNAL_HAS_ANY
#if GTEST_INTERNAL_HAS_OPTIONAL
// Printer for std::optional / absl::optional
template <typename T>
class [[nodiscard]] UniversalPrinter<std::optional<T>> {
class UniversalPrinter<Optional<T>> {
public:
static void Print(const std::optional<T>& value, ::std::ostream* os) {
static void Print(const Optional<T>& value, ::std::ostream* os) {
*os << '(';
if (!value) {
*os << "nullopt";
@ -956,18 +898,29 @@ class [[nodiscard]] UniversalPrinter<std::optional<T>> {
};
template <>
class [[nodiscard]] UniversalPrinter<std::nullopt_t> {
class UniversalPrinter<decltype(Nullopt())> {
public:
static void Print(std::nullopt_t, ::std::ostream* os) { *os << "(nullopt)"; }
static void Print(decltype(Nullopt()), ::std::ostream* os) {
*os << "(nullopt)";
}
};
// Printer for std::variant
#endif // GTEST_INTERNAL_HAS_OPTIONAL
#if GTEST_INTERNAL_HAS_VARIANT
// Printer for std::variant / absl::variant
template <typename... T>
class [[nodiscard]] UniversalPrinter<std::variant<T...>> {
class UniversalPrinter<Variant<T...>> {
public:
static void Print(const std::variant<T...>& value, ::std::ostream* os) {
static void Print(const Variant<T...>& value, ::std::ostream* os) {
*os << '(';
#ifdef GTEST_HAS_ABSL
absl::visit(Visitor{os, value.index()}, value);
#else
std::visit(Visitor{os, value.index()}, value);
#endif // GTEST_HAS_ABSL
*os << ')';
}
@ -984,6 +937,8 @@ class [[nodiscard]] UniversalPrinter<std::variant<T...>> {
};
};
#endif // GTEST_INTERNAL_HAS_VARIANT
// UniversalPrintArray(begin, len, os) prints an array of 'len'
// elements, starting at address 'begin'.
template <typename T>
@ -1031,7 +986,7 @@ GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,
// Implements printing an array type T[N].
template <typename T, size_t N>
class [[nodiscard]] UniversalPrinter<T[N]> {
class UniversalPrinter<T[N]> {
public:
// Prints the given array, omitting some elements when there are too
// many.
@ -1042,7 +997,7 @@ class [[nodiscard]] UniversalPrinter<T[N]> {
// Implements printing a reference type T&.
template <typename T>
class [[nodiscard]] UniversalPrinter<T&> {
class UniversalPrinter<T&> {
public:
// MSVC warns about adding const to a function type, so we want to
// disable the warning.
@ -1065,35 +1020,35 @@ class [[nodiscard]] UniversalPrinter<T&> {
// NUL-terminated string (but not the pointer) is printed.
template <typename T>
class [[nodiscard]] UniversalTersePrinter {
class UniversalTersePrinter {
public:
static void Print(const T& value, ::std::ostream* os) {
UniversalPrint(value, os);
}
};
template <typename T>
class [[nodiscard]] UniversalTersePrinter<T&> {
class UniversalTersePrinter<T&> {
public:
static void Print(const T& value, ::std::ostream* os) {
UniversalPrint(value, os);
}
};
template <typename T>
class [[nodiscard]] UniversalTersePrinter<std::reference_wrapper<T>> {
class UniversalTersePrinter<std::reference_wrapper<T>> {
public:
static void Print(std::reference_wrapper<T> value, ::std::ostream* os) {
UniversalTersePrinter<T>::Print(value.get(), os);
}
};
template <typename T, size_t N>
class [[nodiscard]] UniversalTersePrinter<T[N]> {
class UniversalTersePrinter<T[N]> {
public:
static void Print(const T (&value)[N], ::std::ostream* os) {
UniversalPrinter<T[N]>::Print(value, os);
}
};
template <>
class [[nodiscard]] UniversalTersePrinter<const char*> {
class UniversalTersePrinter<const char*> {
public:
static void Print(const char* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1104,12 +1059,12 @@ class [[nodiscard]] UniversalTersePrinter<const char*> {
}
};
template <>
class [[nodiscard]]
UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {};
class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
};
#ifdef __cpp_lib_char8_t
template <>
class [[nodiscard]] UniversalTersePrinter<const char8_t*> {
class UniversalTersePrinter<const char8_t*> {
public:
static void Print(const char8_t* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1120,12 +1075,12 @@ class [[nodiscard]] UniversalTersePrinter<const char8_t*> {
}
};
template <>
class [[nodiscard]] UniversalTersePrinter<char8_t*>
class UniversalTersePrinter<char8_t*>
: public UniversalTersePrinter<const char8_t*> {};
#endif
template <>
class [[nodiscard]] UniversalTersePrinter<const char16_t*> {
class UniversalTersePrinter<const char16_t*> {
public:
static void Print(const char16_t* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1136,11 +1091,11 @@ class [[nodiscard]] UniversalTersePrinter<const char16_t*> {
}
};
template <>
class [[nodiscard]] UniversalTersePrinter<char16_t*>
class UniversalTersePrinter<char16_t*>
: public UniversalTersePrinter<const char16_t*> {};
template <>
class [[nodiscard]] UniversalTersePrinter<const char32_t*> {
class UniversalTersePrinter<const char32_t*> {
public:
static void Print(const char32_t* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1151,12 +1106,12 @@ class [[nodiscard]] UniversalTersePrinter<const char32_t*> {
}
};
template <>
class [[nodiscard]] UniversalTersePrinter<char32_t*>
class UniversalTersePrinter<char32_t*>
: public UniversalTersePrinter<const char32_t*> {};
#if GTEST_HAS_STD_WSTRING
template <>
class [[nodiscard]] UniversalTersePrinter<const wchar_t*> {
class UniversalTersePrinter<const wchar_t*> {
public:
static void Print(const wchar_t* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1169,7 +1124,7 @@ class [[nodiscard]] UniversalTersePrinter<const wchar_t*> {
#endif
template <>
class [[nodiscard]] UniversalTersePrinter<wchar_t*> {
class UniversalTersePrinter<wchar_t*> {
public:
static void Print(wchar_t* str, ::std::ostream* os) {
UniversalTersePrinter<const wchar_t*>::Print(str, os);

View File

@ -51,7 +51,7 @@ namespace testing {
// generated in the same thread that created this object or it can intercept
// all generated failures. The scope of this mock object can be controlled with
// the second argument to the two arguments constructor.
class GTEST_API_ [[nodiscard]] ScopedFakeTestPartResultReporter
class GTEST_API_ ScopedFakeTestPartResultReporter
: public TestPartResultReporterInterface {
public:
// The two possible mocking modes of this object.
@ -100,7 +100,7 @@ namespace internal {
// TestPartResultArray contains exactly one failure that has the given
// type and contains the given substring. If that's not the case, a
// non-fatal failure will be generated.
class GTEST_API_ [[nodiscard]] SingleFailureChecker {
class GTEST_API_ SingleFailureChecker {
public:
// The constructor remembers the arguments.
SingleFailureChecker(const TestPartResultArray* results,

View File

@ -51,7 +51,7 @@ namespace testing {
// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
//
// Don't inherit from TestPartResult as its destructor is not virtual.
class GTEST_API_ [[nodiscard]] TestPartResult {
class GTEST_API_ TestPartResult {
public:
// The possible outcomes of a test part (i.e. an assertion or an
// explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
@ -131,7 +131,7 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
//
// Don't inherit from TestPartResultArray as its destructor is not
// virtual.
class GTEST_API_ [[nodiscard]] TestPartResultArray {
class GTEST_API_ TestPartResultArray {
public:
TestPartResultArray() = default;
@ -152,7 +152,7 @@ class GTEST_API_ [[nodiscard]] TestPartResultArray {
};
// This interface knows how to report a test part result.
class GTEST_API_ [[nodiscard]] TestPartResultReporterInterface {
class GTEST_API_ TestPartResultReporterInterface {
public:
virtual ~TestPartResultReporterInterface() = default;
@ -167,7 +167,7 @@ namespace internal {
// reported, it only delegates the reporting to the former result reporter.
// The original result reporter is restored in the destructor.
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
class GTEST_API_ [[nodiscard]] HasNewFatalFailureHelper
class GTEST_API_ HasNewFatalFailureHelper
: public TestPartResultReporterInterface {
public:
HasNewFatalFailureHelper();

View File

@ -45,18 +45,18 @@
// First, define a fixture class template. It should be parameterized
// by a type. Remember to derive it from testing::Test.
template <typename T>
class [[nodiscard]] FooTest : public testing::Test {
class FooTest : public testing::Test {
public:
...
using List = ::std::list<T>;
typedef std::list<T> List;
static T shared_;
T value_;
};
// Next, associate a list of types with the test suite, which will be
// repeated for each type in the list. The using-declaration is necessary for
// repeated for each type in the list. The typedef is necessary for
// the macro to parse correctly.
using MyTypes = ::testing::Types<char, int, unsigned int>;
typedef testing::Types<char, int, unsigned int> MyTypes;
TYPED_TEST_SUITE(FooTest, MyTypes);
// If the type list contains only one type, you can write that type
@ -123,7 +123,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... }
// First, define a fixture class template. It should be parameterized
// by a type. Remember to derive it from testing::Test.
template <typename T>
class [[nodiscard]] FooTest : public testing::Test {
class FooTest : public testing::Test {
...
};
@ -157,7 +157,7 @@ REGISTER_TYPED_TEST_SUITE_P(FooTest,
// argument to the INSTANTIATE_* macro is a prefix that will be added
// to the actual test suite name. Remember to pick unique prefixes for
// different instances.
using MyTypes = ::testing::Types<char, int, unsigned int>;
typedef testing::Types<char, int, unsigned int> MyTypes;
INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
// If the type list contains only one type, you can write that type
@ -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 <typename gtest_TypeParam_> \
class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
: public CaseName<gtest_TypeParam_> { \
private: \
typedef CaseName<gtest_TypeParam_> TestFixture; \
typedef gtest_TypeParam_ TypeParam; \
void TestBody() override; \
}; \
[[maybe_unused]] static bool gtest_##CaseName##_##TestName##_registered_ = \
::testing::internal::TypeParameterizedTest< \
CaseName, \
::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
TestName)>, \
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 <typename gtest_TypeParam_> \
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 <typename gtest_TypeParam_> \
class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
: public CaseName<gtest_TypeParam_> { \
private: \
typedef CaseName<gtest_TypeParam_> 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_TEST_CLASS_NAME_( \
CaseName, TestName)>, \
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 <typename gtest_TypeParam_> \
void GTEST_TEST_CLASS_NAME_(CaseName, \
TestName)<gtest_TypeParam_>::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 <typename gtest_TypeParam_> \
class TestName : public SuiteName<gtest_TypeParam_> { \
private: \
typedef SuiteName<gtest_TypeParam_> TestFixture; \
typedef gtest_TypeParam_ TypeParam; \
void TestBody() override; \
}; \
[[maybe_unused]] static bool gtest_##TestName##_defined_ = \
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
__FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
GTEST_STRINGIFY_(TestName)); \
} \
template <typename gtest_TypeParam_> \
void GTEST_SUITE_NAMESPACE_( \
#define TYPED_TEST_P(SuiteName, TestName) \
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
template <typename gtest_TypeParam_> \
class TestName : public SuiteName<gtest_TypeParam_> { \
private: \
typedef SuiteName<gtest_TypeParam_> 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 <typename gtest_TypeParam_> \
void GTEST_SUITE_NAMESPACE_( \
SuiteName)::TestName<gtest_TypeParam_>::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_; \
} \
[[maybe_unused]] static const char* const GTEST_REGISTERED_TEST_NAMES_( \
SuiteName) = \
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"); \
[[maybe_unused]] static bool gtest_##Prefix##_##SuiteName = \
::testing::internal::TypeParameterizedTestSuite< \
SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
::testing::internal::GenerateTypeList<Types>::type>:: \
Register(GTEST_STRINGIFY_(Prefix), \
::testing::internal::CodeLocation(__FILE__, __LINE__), \
&GTEST_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<Types>::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<Types>::type>:: \
Register( \
GTEST_STRINGIFY_(Prefix), \
::testing::internal::CodeLocation(__FILE__, __LINE__), \
&GTEST_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<Types>::type>())
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_

View File

@ -193,7 +193,7 @@ std::set<std::string>* GetIgnoredParameterizedTestSuites();
// A base class that prevents subclasses from being copyable.
// We do this instead of using '= delete' so as to avoid triggering warnings
// inside user code regarding any of our declarations.
class [[nodiscard]] GTestNonCopyable {
class GTestNonCopyable {
public:
GTestNonCopyable() = default;
GTestNonCopyable(const GTestNonCopyable&) = delete;
@ -206,15 +206,15 @@ class [[nodiscard]] GTestNonCopyable {
// The friend relationship of some of these classes is cyclic.
// If we don't forward declare them the compiler might confuse the classes
// in friendship clauses with same named classes on the scope.
class [[nodiscard]] Test;
class [[nodiscard]] TestSuite;
class Test;
class TestSuite;
// Old API is still available but deprecated
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
using TestCase = TestSuite;
#endif
class [[nodiscard]] TestInfo;
class [[nodiscard]] UnitTest;
class TestInfo;
class UnitTest;
// The abstract class that all tests inherit from.
//
@ -239,7 +239,7 @@ class [[nodiscard]] UnitTest;
// TEST_F(FooTest, Baz) { ... }
//
// Test is not copyable.
class GTEST_API_ [[nodiscard]] Test {
class GTEST_API_ Test {
public:
friend class TestInfo;
@ -366,7 +366,7 @@ typedef internal::TimeInMillis TimeInMillis;
// output as a key/value string pair.
//
// Don't inherit from TestProperty as its destructor is not virtual.
class [[nodiscard]] TestProperty {
class TestProperty {
public:
// C'tor. TestProperty does NOT have a default constructor.
// Always use this constructor (with parameters) to create a
@ -396,7 +396,7 @@ class [[nodiscard]] TestProperty {
// the Test.
//
// TestResult is not copyable.
class GTEST_API_ [[nodiscard]] TestResult {
class GTEST_API_ TestResult {
public:
// Creates an empty TestResult.
TestResult();
@ -530,7 +530,7 @@ class GTEST_API_ [[nodiscard]] TestResult {
// The constructor of TestInfo registers itself with the UnitTest
// singleton such that the RUN_ALL_TESTS() macro knows which tests to
// run.
class GTEST_API_ [[nodiscard]] TestInfo {
class GTEST_API_ TestInfo {
public:
// Destructs a TestInfo object. This function is not virtual, so
// don't inherit from TestInfo.
@ -669,7 +669,7 @@ class GTEST_API_ [[nodiscard]] TestInfo {
// A test suite, which consists of a vector of TestInfos.
//
// TestSuite is not copyable.
class GTEST_API_ [[nodiscard]] TestSuite {
class GTEST_API_ TestSuite {
public:
// Creates a TestSuite with the given name.
//
@ -890,7 +890,7 @@ class GTEST_API_ [[nodiscard]] TestSuite {
// available.
// 2. You cannot use ASSERT_* directly in a constructor or
// destructor.
class [[nodiscard]] Environment {
class Environment {
public:
// The d'tor is virtual as we need to subclass Environment.
virtual ~Environment() = default;
@ -911,7 +911,7 @@ class [[nodiscard]] Environment {
#if GTEST_HAS_EXCEPTIONS
// Exception which can be thrown from TestEventListener::OnTestPartResult.
class GTEST_API_ [[nodiscard]] AssertionException
class GTEST_API_ AssertionException
: public internal::GoogleTestFailureException {
public:
explicit AssertionException(const TestPartResult& result)
@ -922,7 +922,7 @@ class GTEST_API_ [[nodiscard]] AssertionException
// The interface for tracing execution of tests. The methods are organized in
// the order the corresponding events are fired.
class [[nodiscard]] TestEventListener {
class TestEventListener {
public:
virtual ~TestEventListener() = default;
@ -989,7 +989,7 @@ class [[nodiscard]] TestEventListener {
// the methods they override will not be caught during the build. For
// comments about each method please see the definition of TestEventListener
// above.
class [[nodiscard]] EmptyTestEventListener : public TestEventListener {
class EmptyTestEventListener : public TestEventListener {
public:
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
void OnTestIterationStart(const UnitTest& /*unit_test*/,
@ -1019,7 +1019,7 @@ class [[nodiscard]] EmptyTestEventListener : public TestEventListener {
};
// TestEventListeners lets users add listeners to track events in Google Test.
class GTEST_API_ [[nodiscard]] TestEventListeners {
class GTEST_API_ TestEventListeners {
public:
TestEventListeners();
~TestEventListeners();
@ -1110,7 +1110,7 @@ class GTEST_API_ [[nodiscard]] TestEventListeners {
//
// This class is thread-safe as long as the methods are called
// according to their specification.
class GTEST_API_ [[nodiscard]] UnitTest {
class GTEST_API_ UnitTest {
public:
// Gets the singleton UnitTest object. The first time this method
// is called, a UnitTest object is constructed and returned.
@ -1123,7 +1123,7 @@ class GTEST_API_ [[nodiscard]] UnitTest {
// This method can only be called from the main thread.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
[[nodiscard]] int Run();
int Run() GTEST_MUST_USE_RESULT_;
// Returns the working directory when the first TEST() or TEST_F()
// was executed. The UnitTest object owns the string.
@ -1398,7 +1398,7 @@ AssertionResult CmpHelperEQ(const char* lhs_expression,
return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
}
class [[nodiscard]] EqHelper {
class EqHelper {
public:
// This templatized version is for the general case.
template <
@ -1610,11 +1610,9 @@ GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
double val1, double val2,
double abs_error);
using GoogleTest_NotSupported_OnFunctionReturningNonVoid = void;
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// A class that enables one to stream messages to assertion macros
class GTEST_API_ [[nodiscard]] AssertHelper {
class GTEST_API_ AssertHelper {
public:
// Constructor.
AssertHelper(TestPartResult::Type type, const char* file, int line,
@ -1623,8 +1621,7 @@ class GTEST_API_ [[nodiscard]] AssertHelper {
// Message assignment is a semantic trick to enable assertion
// streaming; see the GTEST_MESSAGE_ macro below.
GoogleTest_NotSupported_OnFunctionReturningNonVoid operator=(
const Message& message) const;
void operator=(const Message& message) const;
private:
// We put our data in a struct so that the size of the AssertHelper class can
@ -1689,14 +1686,14 @@ class GTEST_API_ [[nodiscard]] AssertHelper {
// INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
template <typename T>
class [[nodiscard]] WithParamInterface {
class WithParamInterface {
public:
typedef T ParamType;
virtual ~WithParamInterface() = default;
// The current parameter value. Is also available in the test fixture's
// constructor.
[[nodiscard]] static const ParamType& GetParam() {
static const ParamType& GetParam() {
GTEST_CHECK_(parameter_ != nullptr)
<< "GetParam() can only be called inside a value-parameterized test "
<< "-- did you intend to write TEST_P instead of TEST_F?";
@ -1723,8 +1720,7 @@ const T* WithParamInterface<T>::parameter_ = nullptr;
// WithParamInterface, and can just inherit from ::testing::TestWithParam.
template <typename T>
class [[nodiscard]] TestWithParam : public Test,
public WithParamInterface<T> {};
class TestWithParam : public Test, public WithParamInterface<T> {};
// Macros for indicating success/failure in test code.
@ -2072,7 +2068,7 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
// Example:
// testing::ScopedTrace trace("file.cc", 123, "message");
//
class GTEST_API_ [[nodiscard]] ScopedTrace {
class GTEST_API_ ScopedTrace {
public:
// The c'tor pushes the given source file location and message onto
// a trace stack maintained by Google Test.
@ -2333,7 +2329,7 @@ TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
//
// This function was formerly a macro; thus, it is in the global
// namespace and has an all-caps name.
[[nodiscard]] int RUN_ALL_TESTS();
int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); }

View File

@ -96,7 +96,7 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
// by wait(2)
// exit code: The integer code passed to exit(3), _Exit(2), or
// returned from main()
class GTEST_API_ [[nodiscard]] DeathTest {
class GTEST_API_ DeathTest {
public:
// Create returns false if there was an error determining the
// appropriate action to take for the current death test; for example,
@ -172,7 +172,7 @@ class GTEST_API_ [[nodiscard]] DeathTest {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// Factory interface for death tests. May be mocked out for testing.
class [[nodiscard]] DeathTestFactory {
class DeathTestFactory {
public:
virtual ~DeathTestFactory() = default;
virtual bool Create(const char* statement,
@ -181,7 +181,7 @@ class [[nodiscard]] DeathTestFactory {
};
// A concrete DeathTestFactory implementation for normal use.
class [[nodiscard]] DefaultDeathTestFactory : public DeathTestFactory {
class DefaultDeathTestFactory : public DeathTestFactory {
public:
bool Create(const char* statement, Matcher<const std::string&> matcher,
const char* file, int line, DeathTest** test) override;
@ -256,19 +256,19 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
// must accept a streamed message even though the message is never printed.
// The regex object is not evaluated, but it is used to prevent "unused"
// warnings and to avoid an expression that doesn't compile in debug mode.
#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} else if (!::testing::internal::AlwaysTrue()) { \
(void)::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
} else \
#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} else if (!::testing::internal::AlwaysTrue()) { \
::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
} else \
::testing::Message()
// A class representing the parsed contents of the
// --gtest_internal_run_death_test flag, as it existed when
// RUN_ALL_TESTS was called.
class [[nodiscard]] InternalRunDeathTestFlag {
class InternalRunDeathTestFlag {
public:
InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index,
int a_write_fd)

View File

@ -67,7 +67,7 @@ namespace internal {
// Names are NOT checked for syntax correctness -- no checking for illegal
// characters, malformed paths, etc.
class GTEST_API_ [[nodiscard]] FilePath {
class GTEST_API_ FilePath {
public:
FilePath() : pathname_("") {}
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {}

View File

@ -95,7 +95,7 @@
#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
namespace proto2 {
class [[nodiscard]] MessageLite;
class MessageLite;
}
namespace testing {
@ -115,15 +115,15 @@ template <typename T>
namespace internal {
struct TraceInfo; // Information about a trace point.
class [[nodiscard]] TestInfoImpl; // Opaque implementation of TestInfo
class [[nodiscard]] UnitTestImpl; // Opaque implementation of UnitTest
class TestInfoImpl; // Opaque implementation of TestInfo
class UnitTestImpl; // Opaque implementation of UnitTest
// The text used in failure messages to indicate the start of the
// stack trace.
GTEST_API_ extern const char kStackTraceMarker[];
// An IgnoredValue object can be implicitly constructed from ANY value.
class [[nodiscard]] IgnoredValue {
class IgnoredValue {
struct Sink {};
public:
@ -155,8 +155,7 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(
// errors presumably detectable only at run time. Since
// std::runtime_error inherits from std::exception, many testing
// frameworks know how to extract and print the message inside it.
class GTEST_API_ [[nodiscard]] GoogleTestFailureException
: public ::std::runtime_error {
class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
public:
explicit GoogleTestFailureException(const TestPartResult& failure);
};
@ -243,7 +242,7 @@ GTEST_API_ std::string GetBoolAssertionFailureMessage(
//
// RawType: the raw floating-point type (either float or double)
template <typename RawType>
class [[nodiscard]] FloatingPoint {
class FloatingPoint {
public:
// Defines the unsigned integer type that has the same size as the
// floating point number.
@ -291,17 +290,17 @@ class [[nodiscard]] FloatingPoint {
// around may change its bits, although the new value is guaranteed
// to be also a NAN. Therefore, don't expect this constructor to
// preserve the bits in x when x is a NAN.
explicit FloatingPoint(RawType x) { memcpy(&bits_, &x, sizeof(x)); }
explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
// Static methods
// Reinterprets a bit pattern as a floating-point number.
//
// This function is needed to test the AlmostEquals() method.
static RawType ReinterpretBits(Bits bits) {
RawType fp;
memcpy(&fp, &bits, sizeof(fp));
return fp;
static RawType ReinterpretBits(const Bits bits) {
FloatingPoint fp(0);
fp.u_.bits_ = bits;
return fp.u_.value_;
}
// Returns the floating-point number that represent positive infinity.
@ -310,16 +309,16 @@ class [[nodiscard]] FloatingPoint {
// Non-static methods
// Returns the bits that represents this number.
const Bits& bits() const { return bits_; }
const Bits& bits() const { return u_.bits_; }
// Returns the exponent bits of this number.
Bits exponent_bits() const { return kExponentBitMask & bits_; }
Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
// Returns the fraction bits of this number.
Bits fraction_bits() const { return kFractionBitMask & bits_; }
Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
// Returns the sign bit of this number.
Bits sign_bit() const { return kSignBitMask & bits_; }
Bits sign_bit() const { return kSignBitMask & u_.bits_; }
// Returns true if and only if this is NAN (not a number).
bool is_nan() const {
@ -333,16 +332,23 @@ class [[nodiscard]] FloatingPoint {
//
// - returns false if either number is (or both are) NAN.
// - treats really large numbers as almost equal to infinity.
// - thinks +0.0 and -0.0 are 0 ULP's apart.
// - thinks +0.0 and -0.0 are 0 DLP's apart.
bool AlmostEquals(const FloatingPoint& rhs) const {
// The IEEE standard says that any comparison operation involving
// a NAN must return false.
if (is_nan() || rhs.is_nan()) return false;
return DistanceBetweenSignAndMagnitudeNumbers(bits_, rhs.bits_) <= kMaxUlps;
return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <=
kMaxUlps;
}
private:
// The data type used to store the actual floating-point number.
union FloatingPointUnion {
RawType value_; // The raw floating-point number.
Bits bits_; // The bits that represent the number.
};
// Converts an integer from the sign-and-magnitude representation to
// the biased representation. More precisely, let N be 2 to the
// power of (kBitCount - 1), an integer x is represented by the
@ -358,7 +364,7 @@ class [[nodiscard]] FloatingPoint {
//
// Read https://en.wikipedia.org/wiki/Signed_number_representations
// for more details on signed number representations.
static Bits SignAndMagnitudeToBiased(Bits sam) {
static Bits SignAndMagnitudeToBiased(const Bits& sam) {
if (kSignBitMask & sam) {
// sam represents a negative number.
return ~sam + 1;
@ -370,13 +376,14 @@ class [[nodiscard]] FloatingPoint {
// Given two numbers in the sign-and-magnitude representation,
// returns the distance between them as an unsigned number.
static Bits DistanceBetweenSignAndMagnitudeNumbers(Bits sam1, Bits sam2) {
static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits& sam1,
const Bits& sam2) {
const Bits biased1 = SignAndMagnitudeToBiased(sam1);
const Bits biased2 = SignAndMagnitudeToBiased(sam2);
return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
}
Bits bits_; // The bits that represent the number.
FloatingPointUnion u_;
};
// Typedefs the instances of the FloatingPoint template class that we
@ -393,7 +400,7 @@ typedef FloatingPoint<double> Double;
typedef const void* TypeId;
template <typename T>
class [[nodiscard]] TypeIdHelper {
class TypeIdHelper {
public:
// dummy_ must not have a const type. Otherwise an overly eager
// compiler (e.g. MSVC 7.1 & 8.0) may try to merge
@ -425,7 +432,7 @@ GTEST_API_ TypeId GetTestTypeId();
// Defines the abstract factory interface that creates instances
// of a Test object.
class [[nodiscard]] TestFactoryBase {
class TestFactoryBase {
public:
virtual ~TestFactoryBase() = default;
@ -444,7 +451,7 @@ class [[nodiscard]] TestFactoryBase {
// This class provides implementation of TestFactoryBase interface.
// It is used in TEST and TEST_F macros.
template <class TestClass>
class [[nodiscard]] TestFactoryImpl : public TestFactoryBase {
class TestFactoryImpl : public TestFactoryBase {
public:
Test* CreateTest() override { return new TestClass; }
};
@ -571,7 +578,7 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
// State of the definition of a type-parameterized test suite.
class GTEST_API_ [[nodiscard]] TypedTestSuitePState {
class GTEST_API_ TypedTestSuitePState {
public:
TypedTestSuitePState() : registered_(false) {}
@ -686,7 +693,7 @@ std::vector<std::string> GenerateNames() {
// Implementation note: The GTEST_TEMPLATE_ macro declares a template
// template parameter. It's defined in gtest-type-util.h.
template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
class [[nodiscard]] TypeParameterizedTest {
class TypeParameterizedTest {
public:
// 'index' is the index of the test in the type list 'Types'
// specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
@ -724,7 +731,7 @@ class [[nodiscard]] TypeParameterizedTest {
// The base case for the compile time recursion.
template <GTEST_TEMPLATE_ Fixture, class TestSel>
class [[nodiscard]] TypeParameterizedTest<Fixture, TestSel, internal::None> {
class TypeParameterizedTest<Fixture, TestSel, internal::None> {
public:
static bool Register(const char* /*prefix*/, CodeLocation,
const char* /*case_name*/, const char* /*test_names*/,
@ -745,7 +752,7 @@ GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
// Test. The return value is insignificant - we just need to return
// something such that we can call this function in a namespace scope.
template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
class [[nodiscard]] TypeParameterizedTestSuite {
class TypeParameterizedTestSuite {
public:
static bool Register(const char* prefix, CodeLocation code_location,
const TypedTestSuitePState* state, const char* case_name,
@ -783,7 +790,7 @@ class [[nodiscard]] TypeParameterizedTestSuite {
// The base case for the compile time recursion.
template <GTEST_TEMPLATE_ Fixture, typename Types>
class [[nodiscard]] TypeParameterizedTestSuite<Fixture, internal::None, Types> {
class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
public:
static bool Register(const char* /*prefix*/, const CodeLocation&,
const TypedTestSuitePState* /*state*/,
@ -839,7 +846,7 @@ struct TrueWithString {
// doesn't use global state (and therefore can't interfere with user
// code). Unlike rand_r(), it's portable. An LCG isn't very random,
// but it's good enough for our purposes.
class GTEST_API_ [[nodiscard]] Random {
class GTEST_API_ Random {
public:
static const uint32_t kMaxRange = 1u << 31;
@ -865,7 +872,7 @@ class GTEST_API_ [[nodiscard]] Random {
// that's true if and only if T has methods DebugString() and ShortDebugString()
// that return std::string.
template <typename T>
class [[nodiscard]] HasDebugStringAndShortDebugString {
class HasDebugStringAndShortDebugString {
private:
template <typename C>
static auto CheckDebugString(C*) -> typename std::is_same<
@ -887,6 +894,11 @@ class [[nodiscard]] HasDebugStringAndShortDebugString {
HasDebugStringType::value && HasShortDebugStringType::value;
};
#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
template <typename T>
constexpr bool HasDebugStringAndShortDebugString<T>::value;
#endif
// When the compiler sees expression IsContainerTest<C>(0), if C is an
// STL-style container class, the first overload of IsContainerTest
// will be viable (since both C::iterator* and C::const_iterator* are
@ -1065,7 +1077,7 @@ struct RelationToSourceCopy {};
// this requirement. Element can be an array type itself (hence
// multi-dimensional arrays are supported).
template <typename Element>
class [[nodiscard]] NativeArray {
class NativeArray {
public:
// STL-style container typedefs.
typedef Element value_type;
@ -1151,7 +1163,7 @@ struct ElemFromList {
struct FlatTupleConstructTag {};
template <typename... T>
class [[nodiscard]] FlatTuple;
class FlatTuple;
template <typename Derived, size_t I>
struct FlatTupleElemBase;
@ -1210,7 +1222,7 @@ struct FlatTupleBase<FlatTuple<T...>, std::index_sequence<Idx...>>
// std::make_index_sequence, on the other hand, it is recursive but with an
// instantiation depth of O(ln(N)).
template <typename... T>
class [[nodiscard]] FlatTuple
class FlatTuple
: private FlatTupleBase<FlatTuple<T...>,
std::make_index_sequence<sizeof...(T)>> {
using Indices =
@ -1229,40 +1241,30 @@ class [[nodiscard]] FlatTuple
// Utility functions to be called with static_assert to induce deprecation
// warnings.
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"INSTANTIATE_TEST_CASE_P is deprecated, please use "
"INSTANTIATE_TEST_SUITE_P")]]
constexpr bool InstantiateTestCase_P_IsDeprecated() {
return true;
}
"INSTANTIATE_TEST_SUITE_P")
constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"TYPED_TEST_CASE_P is deprecated, please use "
"TYPED_TEST_SUITE_P")]]
constexpr bool TypedTestCase_P_IsDeprecated() {
return true;
}
"TYPED_TEST_SUITE_P")
constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"TYPED_TEST_CASE is deprecated, please use "
"TYPED_TEST_SUITE")]]
constexpr bool TypedTestCaseIsDeprecated() {
return true;
}
"TYPED_TEST_SUITE")
constexpr bool TypedTestCaseIsDeprecated() { return true; }
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
"REGISTER_TYPED_TEST_SUITE_P")]]
constexpr bool RegisterTypedTestCase_P_IsDeprecated() {
return true;
}
"REGISTER_TYPED_TEST_SUITE_P")
constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
"INSTANTIATE_TYPED_TEST_SUITE_P")]]
constexpr bool InstantiateTypedTestCase_P_IsDeprecated() {
return true;
}
"INSTANTIATE_TYPED_TEST_SUITE_P")
constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
} // namespace internal
} // namespace testing
@ -1318,7 +1320,7 @@ struct tuple_size<testing::internal::FlatTuple<Ts...>>
namespace testing {
namespace internal {
class [[nodiscard]] NeverThrown {
class NeverThrown {
public:
const char* what() const noexcept {
return "this exception should never be thrown";
@ -1499,7 +1501,8 @@ class [[nodiscard]] NeverThrown {
\
private: \
void TestBody() override; \
[[maybe_unused]] static ::testing::TestInfo* const test_info_; \
GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static ::testing::TestInfo* const \
test_info_; \
}; \
\
::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \

View File

@ -39,7 +39,6 @@
#include <ctype.h>
#include <cassert>
#include <functional>
#include <iterator>
#include <map>
#include <memory>
@ -90,14 +89,14 @@ GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
const CodeLocation& code_location);
template <typename>
class [[nodiscard]] ParamGeneratorInterface;
class ParamGeneratorInterface;
template <typename>
class [[nodiscard]] ParamGenerator;
class ParamGenerator;
// Interface for iterating over elements provided by an implementation
// of ParamGeneratorInterface<T>.
template <typename T>
class [[nodiscard]] ParamIteratorInterface {
class ParamIteratorInterface {
public:
virtual ~ParamIteratorInterface() = default;
// A pointer to the base generator instance.
@ -127,7 +126,7 @@ class [[nodiscard]] ParamIteratorInterface {
// ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
// and implements the const forward iterator concept.
template <typename T>
class [[nodiscard]] ParamIterator {
class ParamIterator {
public:
typedef T value_type;
typedef const T& reference;
@ -169,7 +168,7 @@ class [[nodiscard]] ParamIterator {
// ParamGeneratorInterface<T> is the binary interface to access generators
// defined in other translation units.
template <typename T>
class [[nodiscard]] ParamGeneratorInterface {
class ParamGeneratorInterface {
public:
typedef T ParamType;
@ -186,7 +185,7 @@ class [[nodiscard]] ParamGeneratorInterface {
// ParamGeneratorInterface<T> instance is shared among all copies
// of the original object. This is possible because that instance is immutable.
template <typename T>
class [[nodiscard]] ParamGenerator {
class ParamGenerator {
public:
typedef ParamIterator<T> iterator;
@ -210,7 +209,7 @@ class [[nodiscard]] ParamGenerator {
// operator<().
// This class is used in the Range() function.
template <typename T, typename IncrementT>
class [[nodiscard]] RangeGenerator : public ParamGeneratorInterface<T> {
class RangeGenerator : public ParamGeneratorInterface<T> {
public:
RangeGenerator(T begin, T end, IncrementT step)
: begin_(begin),
@ -296,8 +295,7 @@ class [[nodiscard]] RangeGenerator : public ParamGeneratorInterface<T> {
// since the source can be located on the stack, and the generator
// is likely to persist beyond that stack frame.
template <typename T>
class [[nodiscard]] ValuesInIteratorRangeGenerator
: public ParamGeneratorInterface<T> {
class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
public:
template <typename ForwardIterator>
ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
@ -397,7 +395,7 @@ void TestNotEmpty(const T&) {}
// Stores a parameter value and later creates tests parameterized with that
// value.
template <class TestClass>
class [[nodiscard]] ParameterizedTestFactory : public TestFactoryBase {
class ParameterizedTestFactory : public TestFactoryBase {
public:
typedef typename TestClass::ParamType ParamType;
explicit ParameterizedTestFactory(ParamType parameter)
@ -419,7 +417,7 @@ class [[nodiscard]] ParameterizedTestFactory : public TestFactoryBase {
// TestMetaFactoryBase is a base class for meta-factories that create
// test factories for passing into MakeAndRegisterTestInfo function.
template <class ParamType>
class [[nodiscard]] TestMetaFactoryBase {
class TestMetaFactoryBase {
public:
virtual ~TestMetaFactoryBase() = default;
@ -435,7 +433,7 @@ class [[nodiscard]] TestMetaFactoryBase {
// it for each Test/Parameter value combination. Thus it needs meta factory
// creator class.
template <class TestSuite>
class [[nodiscard]] TestMetaFactory
class TestMetaFactory
: public TestMetaFactoryBase<typename TestSuite::ParamType> {
public:
using ParamType = typename TestSuite::ParamType;
@ -461,7 +459,7 @@ class [[nodiscard]] TestMetaFactory
// in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
// a collection of pointers to the ParameterizedTestSuiteInfo objects
// and calls RegisterTests() on each of them when asked.
class [[nodiscard]] ParameterizedTestSuiteInfoBase {
class ParameterizedTestSuiteInfoBase {
public:
virtual ~ParameterizedTestSuiteInfoBase() = default;
@ -504,8 +502,7 @@ GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
// test suite. It registers tests with all values generated by all
// generators when asked.
template <class TestSuite>
class [[nodiscard]] ParameterizedTestSuiteInfo
: public ParameterizedTestSuiteInfoBase {
class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
public:
// ParamType and GeneratorCreationFunc are private types but are required
// for declarations of public methods AddTestPattern() and
@ -532,7 +529,8 @@ class [[nodiscard]] ParameterizedTestSuiteInfo
// 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*, const char* test_base_name,
void AddTestPattern(const char*,
const char* test_base_name,
TestMetaFactoryBase<ParamType>* meta_factory,
CodeLocation code_location) {
tests_.emplace_back(
@ -690,7 +688,7 @@ using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
// ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
// and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
// ParameterizedTestSuiteInfo descriptors.
class [[nodiscard]] ParameterizedTestSuiteRegistry {
class ParameterizedTestSuiteRegistry {
public:
ParameterizedTestSuiteRegistry() = default;
~ParameterizedTestSuiteRegistry() {
@ -764,7 +762,7 @@ class [[nodiscard]] ParameterizedTestSuiteRegistry {
// Keep track of what type-parameterized test suite are defined and
// where as well as which are intatiated. This allows susequently
// identifying suits that are defined but never used.
class [[nodiscard]] TypeParameterizedTestSuiteRegistry {
class TypeParameterizedTestSuiteRegistry {
public:
// Add a suite definition
void RegisterTestSuite(const char* test_suite_name,
@ -803,7 +801,7 @@ namespace internal {
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
template <typename... Ts>
class [[nodiscard]] ValueArray {
class ValueArray {
public:
explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
@ -824,7 +822,7 @@ class [[nodiscard]] ValueArray {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
template <typename... T>
class [[nodiscard]] CartesianProductGenerator
class CartesianProductGenerator
: public ParamGeneratorInterface<::std::tuple<T...>> {
public:
typedef ::std::tuple<T...> ParamType;
@ -941,7 +939,7 @@ class [[nodiscard]] CartesianProductGenerator
};
template <class... Gen>
class [[nodiscard]] CartesianProductHolder {
class CartesianProductHolder {
public:
CartesianProductHolder(const Gen&... g) : generators_(g...) {}
template <typename... T>
@ -954,12 +952,11 @@ class [[nodiscard]] CartesianProductHolder {
std::tuple<Gen...> generators_;
};
template <typename From, typename To, typename Func>
class [[nodiscard]] ParamGeneratorConverter
: public ParamGeneratorInterface<To> {
template <typename From, typename To>
class ParamGeneratorConverter : public ParamGeneratorInterface<To> {
public:
ParamGeneratorConverter(ParamGenerator<From> gen, Func converter) // NOLINT
: generator_(std::move(gen)), converter_(std::move(converter)) {}
ParamGeneratorConverter(ParamGenerator<From> gen) // NOLINT
: generator_(std::move(gen)) {}
ParamIteratorInterface<To>* Begin() const override {
return new Iterator(this, generator_.begin(), generator_.end());
@ -968,21 +965,13 @@ class [[nodiscard]] ParamGeneratorConverter
return new Iterator(this, generator_.end(), generator_.end());
}
// Returns the std::function wrapping the user-supplied converter callable. It
// is used by the iterator (see class Iterator below) to convert the object
// (of type FROM) returned by the ParamGenerator to an object of a type that
// can be static_cast to type TO.
const Func& TypeConverter() const { return converter_; }
private:
class Iterator : public ParamIteratorInterface<To> {
public:
Iterator(const ParamGeneratorConverter* base, ParamIterator<From> it,
Iterator(const ParamGeneratorInterface<To>* base, ParamIterator<From> it,
ParamIterator<From> end)
: base_(base), it_(it), end_(end) {
if (it_ != end_)
value_ =
std::make_shared<To>(static_cast<To>(base->TypeConverter()(*it_)));
if (it_ != end_) value_ = std::make_shared<To>(static_cast<To>(*it_));
}
~Iterator() override = default;
@ -991,9 +980,7 @@ class [[nodiscard]] ParamGeneratorConverter
}
void Advance() override {
++it_;
if (it_ != end_)
value_ =
std::make_shared<To>(static_cast<To>(base_->TypeConverter()(*it_)));
if (it_ != end_) value_ = std::make_shared<To>(static_cast<To>(*it_));
}
ParamIteratorInterface<To>* Clone() const override {
return new Iterator(*this);
@ -1013,54 +1000,30 @@ class [[nodiscard]] ParamGeneratorConverter
private:
Iterator(const Iterator& other) = default;
const ParamGeneratorConverter* const base_;
const ParamGeneratorInterface<To>* const base_;
ParamIterator<From> it_;
ParamIterator<From> end_;
std::shared_ptr<To> value_;
}; // class ParamGeneratorConverter::Iterator
ParamGenerator<From> generator_;
Func converter_;
}; // class ParamGeneratorConverter
template <class GeneratedT,
typename StdFunction =
std::function<const GeneratedT&(const GeneratedT&)>>
class [[nodiscard]] ParamConverterGenerator {
template <class Gen>
class ParamConverterGenerator {
public:
ParamConverterGenerator(ParamGenerator<GeneratedT> g) // NOLINT
: generator_(std::move(g)), converter_(Identity) {}
ParamConverterGenerator(ParamGenerator<GeneratedT> g, StdFunction converter)
: generator_(std::move(g)), converter_(std::move(converter)) {}
ParamConverterGenerator(ParamGenerator<Gen> g) // NOLINT
: generator_(std::move(g)) {}
template <typename T>
operator ParamGenerator<T>() const { // NOLINT
return ParamGenerator<T>(
new ParamGeneratorConverter<GeneratedT, T, StdFunction>(generator_,
converter_));
return ParamGenerator<T>(new ParamGeneratorConverter<Gen, T>(generator_));
}
private:
static const GeneratedT& Identity(const GeneratedT& v) { return v; }
ParamGenerator<GeneratedT> generator_;
StdFunction converter_;
ParamGenerator<Gen> generator_;
};
// Template to determine the param type of a single-param std::function.
template <typename T>
struct FuncSingleParamType;
template <typename R, typename P>
struct FuncSingleParamType<std::function<R(P)>> {
using type = std::remove_cv_t<std::remove_reference_t<P>>;
};
template <typename T>
struct IsSingleArgStdFunction : public std::false_type {};
template <typename R, typename P>
struct IsSingleArgStdFunction<std::function<R(P)>> : public std::true_type {};
} // namespace internal
} // namespace testing

View File

@ -194,12 +194,26 @@
//
// Macros for basic C++ coding:
// GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
// 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).
// GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
// is suppressed.
// GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
// UniversalPrinter<absl::any> specializations.
// Always defined to 0 or 1.
// GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
// or
// UniversalPrinter<absl::optional>
// specializations. Always defined to 0 or 1.
// GTEST_INTERNAL_HAS_STD_SPAN - for enabling UniversalPrinter<std::span>
// specializations. Always defined to 0 or 1
// GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
// Matcher<absl::string_view>
// specializations. Always defined to 0 or 1.
// GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
// UniversalPrinter<absl::variant>
// specializations. Always defined to 0 or 1.
// GTEST_USE_OWN_FLAGFILE_FLAG_ - Always defined to 0 or 1.
// GTEST_HAS_CXXABI_H_ - Always defined to 0 or 1.
// GTEST_CAN_STREAM_RESULTS_ - Always defined to 0 or 1.
@ -246,6 +260,11 @@
// BoolFromGTestEnv() - parses a bool environment variable.
// Int32FromGTestEnv() - parses an int32_t environment variable.
// StringFromGTestEnv() - parses a string environment variable.
//
// Deprecation warnings:
// GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as
// deprecated; calling a marked function
// should generate a compiler warning
// The definition of GTEST_INTERNAL_CPLUSPLUS_LANG comes first because it can
// potentially be used as an #include guard.
@ -256,8 +275,8 @@
#endif
#if !defined(GTEST_INTERNAL_CPLUSPLUS_LANG) || \
GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L
#error C++ versions less than C++17 are not supported.
GTEST_INTERNAL_CPLUSPLUS_LANG < 201402L
#error C++ versions less than C++14 are not supported.
#endif
// MSVC >= 19.11 (VS 2017 Update 3) supports __has_include.
@ -269,14 +288,10 @@
// 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.
//
// GCC15 warns that <ciso646> is deprecated in C++17 and suggests using
// <version> instead, even though <version> is not available in C++17 mode prior
// to GCC9.
#if GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L || \
GTEST_INTERNAL_HAS_INCLUDE(<version>)
#include <version> // C++20 or <version> support.
#else
#if GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L && \
(!defined(__has_include) || GTEST_INTERNAL_HAS_INCLUDE(<version>))
#include <version> // C++20 and later
#elif (!defined(__has_include) || GTEST_INTERNAL_HAS_INCLUDE(<ciso646>))
#include <ciso646> // Pre-C++20
#endif
@ -757,6 +772,25 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#define GTEST_HAVE_FEATURE_(x) 0
#endif
// Use this annotation after a variable or parameter declaration to tell the
// compiler the variable/parameter may be used.
// Example:
//
// 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_INTERNAL_ATTRIBUTE_MAYBE_UNUSED
#endif
// Use this annotation before a function that takes a printf format string.
#if GTEST_HAVE_ATTRIBUTE_(format) && defined(__MINGW_PRINTF_FORMAT)
// MinGW has two different printf implementations. Ensure the format macro
@ -771,6 +805,17 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)
#endif
// Tell the compiler to warn about unused return values for functions declared
// with this macro. The macro should be used on function declarations
// following the argument list:
//
// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;
#if GTEST_HAVE_ATTRIBUTE_(warn_unused_result)
#define GTEST_MUST_USE_RESULT_ __attribute__((warn_unused_result))
#else
#define GTEST_MUST_USE_RESULT_
#endif
// MS C++ compiler emits warning when a conditional expression is compile time
// constant. In some contexts this warning is false positive and needs to be
// suppressed. Use the following two macros in such cases:
@ -827,8 +872,6 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#elif defined(GTEST_CREATE_SHARED_LIBRARY) && GTEST_CREATE_SHARED_LIBRARY
#define GTEST_API_ __declspec(dllexport)
#endif
#elif GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE(gnu::visibility)
#define GTEST_API_ [[gnu::visibility("default")]]
#elif GTEST_HAVE_ATTRIBUTE_(visibility)
#define GTEST_API_ __attribute__((visibility("default")))
#endif // _MSC_VER
@ -919,7 +962,7 @@ namespace internal {
// A secret type that Google Test users don't know about. It has no
// accessible constructors on purpose. Therefore it's impossible to create a
// Secret object, which is what we want.
class [[nodiscard]] Secret {
class Secret {
Secret(const Secret&) = delete;
};
@ -934,7 +977,7 @@ GTEST_API_ bool IsTrue(bool condition);
// This is almost `using RE = ::RE2`, except it is copy-constructible, and it
// needs to disambiguate the `std::string`, `absl::string_view`, and `const
// char*` constructors.
class GTEST_API_ [[nodiscard]] RE {
class GTEST_API_ RE {
public:
RE(absl::string_view regex) : regex_(regex) {} // NOLINT
RE(const char* regex) : RE(absl::string_view(regex)) {} // NOLINT
@ -960,7 +1003,7 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
// A simple C++ wrapper for <regex.h>. It uses the POSIX Extended
// Regular Expression syntax.
class GTEST_API_ [[nodiscard]] RE {
class GTEST_API_ RE {
public:
// A copy constructor is required by the Standard to initialize object
// references from r-values.
@ -1029,7 +1072,7 @@ enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL };
// Formats log entry severity, provides a stream object for streaming the
// log message, and terminates the message with a newline when going out of
// scope.
class GTEST_API_ [[nodiscard]] GTestLog {
class GTEST_API_ GTestLog {
public:
GTestLog(GTestLogSeverity severity, const char* file, int line);
@ -1192,7 +1235,7 @@ void ClearInjectableArgvs();
#ifdef GTEST_OS_WINDOWS
// Provides leak-safe Windows kernel handle ownership.
// Used in death tests and in threading support.
class GTEST_API_ [[nodiscard]] AutoHandle {
class GTEST_API_ AutoHandle {
public:
// Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to
// avoid including <windows.h> in this header file. Including <windows.h> is
@ -1236,7 +1279,7 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
// This class is only for testing Google Test's own constructs. Do not
// use it in user tests, either directly or indirectly.
// TODO(b/203539622): Replace unconditionally with absl::Notification.
class GTEST_API_ [[nodiscard]] Notification {
class GTEST_API_ Notification {
public:
Notification() : notified_(false) {}
Notification(const Notification&) = delete;
@ -1275,7 +1318,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// in order to call its Run(). Introducing ThreadWithParamBase as a
// non-templated base class for ThreadWithParam allows us to bypass this
// problem.
class [[nodiscard]] ThreadWithParamBase {
class ThreadWithParamBase {
public:
virtual ~ThreadWithParamBase() = default;
virtual void Run() = 0;
@ -1305,7 +1348,7 @@ extern "C" inline void* ThreadFuncWithCLinkage(void* thread) {
// These classes are only for testing Google Test's own constructs. Do
// not use them in user tests, either directly or indirectly.
template <typename T>
class [[nodiscard]] ThreadWithParam : public ThreadWithParamBase {
class ThreadWithParam : public ThreadWithParamBase {
public:
typedef void UserThreadFunc(T);
@ -1371,7 +1414,7 @@ class [[nodiscard]] ThreadWithParam : public ThreadWithParamBase {
// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);
//
// (A non-static Mutex is defined/declared in the usual way).
class GTEST_API_ [[nodiscard]] Mutex {
class GTEST_API_ Mutex {
public:
enum MutexType { kStatic = 0, kDynamic = 1 };
// We rely on kStaticMutex being 0 as it is to what the linker initializes
@ -1387,9 +1430,9 @@ class GTEST_API_ [[nodiscard]] Mutex {
Mutex();
~Mutex();
void lock();
void Lock();
void unlock();
void Unlock();
// Does nothing if the current thread holds the mutex. Otherwise, crashes
// with high probability.
@ -1424,13 +1467,14 @@ class GTEST_API_ [[nodiscard]] Mutex {
// platforms. That macro is used as a defensive measure to prevent against
// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
// "MutexLock l(&mu)". Hence the typedef trick below.
class [[nodiscard]] GTestMutexLock {
class GTestMutexLock {
public:
explicit GTestMutexLock(Mutex& mutex) : mutex_(mutex) { mutex_.lock(); }
~GTestMutexLock() { mutex_.unlock(); }
explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); }
~GTestMutexLock() { mutex_->Unlock(); }
private:
Mutex& mutex_;
Mutex* const mutex_;
GTestMutexLock(const GTestMutexLock&) = delete;
GTestMutexLock& operator=(const GTestMutexLock&) = delete;
@ -1440,14 +1484,14 @@ typedef GTestMutexLock MutexLock;
// Base class for ValueHolder<T>. Allows a caller to hold and delete a value
// without knowing its type.
class [[nodiscard]] ThreadLocalValueHolderBase {
class ThreadLocalValueHolderBase {
public:
virtual ~ThreadLocalValueHolderBase() {}
};
// Provides a way for a thread to send notifications to a ThreadLocal
// regardless of its parameter type.
class [[nodiscard]] ThreadLocalBase {
class ThreadLocalBase {
public:
// Creates a new ValueHolder<T> object holding a default value passed to
// this ThreadLocal<T>'s constructor and returns it. It is the caller's
@ -1467,7 +1511,7 @@ class [[nodiscard]] ThreadLocalBase {
// Maps a thread to a set of ThreadLocals that have values instantiated on that
// thread and notifies them when the thread exits. A ThreadLocal instance is
// expected to persist until all threads it has values on have terminated.
class GTEST_API_ [[nodiscard]] ThreadLocalRegistry {
class GTEST_API_ ThreadLocalRegistry {
public:
// Registers thread_local_instance as having value on the current thread.
// Returns a value that can be used to identify the thread from other threads.
@ -1479,7 +1523,7 @@ class GTEST_API_ [[nodiscard]] ThreadLocalRegistry {
const ThreadLocalBase* thread_local_instance);
};
class GTEST_API_ [[nodiscard]] ThreadWithParamBase {
class GTEST_API_ ThreadWithParamBase {
public:
void Join();
@ -1499,7 +1543,7 @@ class GTEST_API_ [[nodiscard]] ThreadWithParamBase {
// Helper class for testing Google Test's multi-threading constructs.
template <typename T>
class [[nodiscard]] ThreadWithParam : public ThreadWithParamBase {
class ThreadWithParam : public ThreadWithParamBase {
public:
typedef void UserThreadFunc(T);
@ -1554,7 +1598,7 @@ class [[nodiscard]] ThreadWithParam : public ThreadWithParamBase {
// object managed by Google Test will be leaked as long as all threads
// using Google Test have exited when main() returns.
template <typename T>
class [[nodiscard]] ThreadLocal : public ThreadLocalBase {
class ThreadLocal : public ThreadLocalBase {
public:
ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}
explicit ThreadLocal(const T& value)
@ -1639,17 +1683,17 @@ class [[nodiscard]] ThreadLocal : public ThreadLocalBase {
#elif GTEST_HAS_PTHREAD
// MutexBase and Mutex implement mutex on pthreads-based platforms.
class [[nodiscard]] MutexBase {
class MutexBase {
public:
// Acquires this mutex.
void lock() {
void Lock() {
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));
owner_ = pthread_self();
has_owner_ = true;
}
// Releases this mutex.
void unlock() {
void Unlock() {
// Since the lock is being released the owner_ field should no longer be
// considered valid. We don't protect writing to has_owner_ here, as it's
// the caller's responsibility to ensure that the current thread holds the
@ -1697,7 +1741,7 @@ class [[nodiscard]] MutexBase {
// The Mutex class can only be used for mutexes created at runtime. It
// shares its API with MutexBase otherwise.
class [[nodiscard]] Mutex : public MutexBase {
class Mutex : public MutexBase {
public:
Mutex() {
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));
@ -1715,13 +1759,14 @@ class [[nodiscard]] Mutex : public MutexBase {
// platforms. That macro is used as a defensive measure to prevent against
// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
// "MutexLock l(&mu)". Hence the typedef trick below.
class [[nodiscard]] GTestMutexLock {
class GTestMutexLock {
public:
explicit GTestMutexLock(MutexBase& mutex) : mutex_(mutex) { mutex_.lock(); }
~GTestMutexLock() { mutex_.unlock(); }
explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); }
~GTestMutexLock() { mutex_->Unlock(); }
private:
MutexBase& mutex_;
MutexBase* const mutex_;
GTestMutexLock(const GTestMutexLock&) = delete;
GTestMutexLock& operator=(const GTestMutexLock&) = delete;
@ -1735,7 +1780,7 @@ typedef GTestMutexLock MutexLock;
// C-linkage. Therefore it cannot be templatized to access
// ThreadLocal<T>. Hence the need for class
// ThreadLocalValueHolderBase.
class GTEST_API_ [[nodiscard]] ThreadLocalValueHolderBase {
class GTEST_API_ ThreadLocalValueHolderBase {
public:
virtual ~ThreadLocalValueHolderBase() = default;
};
@ -1748,7 +1793,7 @@ extern "C" inline void DeleteThreadLocalValue(void* value_holder) {
// Implements thread-local storage on pthreads-based systems.
template <typename T>
class GTEST_API_ [[nodiscard]] ThreadLocal {
class GTEST_API_ ThreadLocal {
public:
ThreadLocal()
: key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}
@ -1861,11 +1906,11 @@ class GTEST_API_ [[nodiscard]] ThreadLocal {
// mutex is not supported - using Google Test in multiple threads is not
// supported on such platforms.
class [[nodiscard]] Mutex {
class Mutex {
public:
Mutex() {}
void lock() {}
void unlock() {}
void Lock() {}
void Unlock() {}
void AssertHeld() const {}
};
@ -1879,15 +1924,15 @@ class [[nodiscard]] Mutex {
// platforms. That macro is used as a defensive measure to prevent against
// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than
// "MutexLock l(&mu)". Hence the typedef trick below.
class [[nodiscard]] GTestMutexLock {
class GTestMutexLock {
public:
explicit GTestMutexLock(Mutex&) {} // NOLINT
explicit GTestMutexLock(Mutex*) {} // NOLINT
};
typedef GTestMutexLock MutexLock;
template <typename T>
class GTEST_API_ [[nodiscard]] ThreadLocal {
class GTEST_API_ ThreadLocal {
public:
ThreadLocal() : value_() {}
explicit ThreadLocal(const T& value) : value_(value) {}
@ -2195,7 +2240,7 @@ constexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)();
// needs. Other types can be easily added in the future if need
// arises.
template <size_t size>
class [[nodiscard]] TypeWithSize {
class TypeWithSize {
public:
// This prevents the user from using TypeWithSize<N> with incorrect
// values of N.
@ -2204,7 +2249,7 @@ class [[nodiscard]] TypeWithSize {
// The specialization for size 4.
template <>
class [[nodiscard]] TypeWithSize<4> {
class TypeWithSize<4> {
public:
using Int = std::int32_t;
using UInt = std::uint32_t;
@ -2212,7 +2257,7 @@ class [[nodiscard]] TypeWithSize<4> {
// The specialization for size 8.
template <>
class [[nodiscard]] TypeWithSize<8> {
class TypeWithSize<8> {
public:
using Int = std::int64_t;
using UInt = std::uint64_t;
@ -2322,11 +2367,91 @@ const char* StringFromGTestEnv(const char* flag, const char* default_val);
} // namespace internal
} // namespace testing
#if GTEST_INTERNAL_HAVE_CPP_ATTRIBUTE(clang::annotate)
#define GTEST_INTERNAL_DEPRECATE_AND_INLINE(msg) \
[[deprecated(msg), clang::annotate("inline-me")]]
#if !defined(GTEST_INTERNAL_DEPRECATED)
// Internal Macro to mark an API deprecated, for googletest usage only
// Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or
// GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of
// a deprecated entity will trigger a warning when compiled with
// `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler).
// For msvc /W3 option will need to be used
// Note that for 'other' compilers this macro evaluates to nothing to prevent
// compilations errors.
#if defined(_MSC_VER)
#define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message))
#elif defined(__GNUC__)
#define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message)))
#else
#define GTEST_INTERNAL_DEPRECATE_AND_INLINE(msg) [[deprecated(msg)]]
#define GTEST_INTERNAL_DEPRECATED(message)
#endif
#endif // !defined(GTEST_INTERNAL_DEPRECATED)
#ifdef GTEST_HAS_ABSL
// Always use absl::any for UniversalPrinter<> specializations if googletest
// is built with absl support.
#define GTEST_INTERNAL_HAS_ANY 1
#include "absl/types/any.h"
namespace testing {
namespace internal {
using Any = ::absl::any;
} // namespace internal
} // namespace testing
#else
#if defined(__cpp_lib_any) || (GTEST_INTERNAL_HAS_INCLUDE(<any>) && \
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
#include <any>
namespace testing {
namespace internal {
using Any = ::std::any;
} // namespace internal
} // namespace testing
// The case where absl is configured NOT to alias std::any is not
// supported.
#endif // __cpp_lib_any
#endif // GTEST_HAS_ABSL
#ifndef GTEST_INTERNAL_HAS_ANY
#define GTEST_INTERNAL_HAS_ANY 0
#endif
#ifdef GTEST_HAS_ABSL
// Always use absl::optional for UniversalPrinter<> specializations if
// googletest is built with absl support.
#define GTEST_INTERNAL_HAS_OPTIONAL 1
#include "absl/types/optional.h"
namespace testing {
namespace internal {
template <typename T>
using Optional = ::absl::optional<T>;
inline ::absl::nullopt_t Nullopt() { return ::absl::nullopt; }
} // namespace internal
} // namespace testing
#else
#if defined(__cpp_lib_optional) || (GTEST_INTERNAL_HAS_INCLUDE(<optional>) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L)
// Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
// specializations.
#define GTEST_INTERNAL_HAS_OPTIONAL 1
#include <optional>
namespace testing {
namespace internal {
template <typename T>
using Optional = ::std::optional<T>;
inline ::std::nullopt_t Nullopt() { return ::std::nullopt; }
} // namespace internal
} // namespace testing
// The case where absl is configured NOT to alias std::optional is not
// supported.
#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(<span>) && \
@ -2370,12 +2495,42 @@ using StringView = ::std::string_view;
#define GTEST_INTERNAL_HAS_STRING_VIEW 0
#endif
#if (defined(__cpp_lib_three_way_comparison) || \
(GTEST_INTERNAL_HAS_INCLUDE(<compare>) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201907L))
#define GTEST_INTERNAL_HAS_COMPARE_LIB 1
#ifdef GTEST_HAS_ABSL
// Always use absl::variant for UniversalPrinter<> specializations if googletest
// is built with absl support.
#define GTEST_INTERNAL_HAS_VARIANT 1
#include "absl/types/variant.h"
namespace testing {
namespace internal {
template <typename... T>
using Variant = ::absl::variant<T...>;
} // namespace internal
} // namespace testing
#else
#define GTEST_INTERNAL_HAS_COMPARE_LIB 0
#if defined(__cpp_lib_variant) || (GTEST_INTERNAL_HAS_INCLUDE(<variant>) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L)
// Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
// specializations.
#define GTEST_INTERNAL_HAS_VARIANT 1
#include <variant>
namespace testing {
namespace internal {
template <typename... T>
using Variant = ::std::variant<T...>;
} // namespace internal
} // namespace testing
// The case where absl is configured NOT to alias std::variant is not supported.
#endif // __cpp_lib_variant
#endif // GTEST_HAS_ABSL
#ifndef GTEST_INTERNAL_HAS_VARIANT
#define GTEST_INTERNAL_HAS_VARIANT 0
#endif
#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
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_

View File

@ -60,7 +60,7 @@ namespace testing {
namespace internal {
// String - an abstract class holding static string utilities.
class GTEST_API_ [[nodiscard]] String {
class GTEST_API_ String {
public:
// Static utility methods
@ -166,7 +166,7 @@ class GTEST_API_ [[nodiscard]] String {
private:
String(); // Not meant to be instantiated.
}; // class String
}; // class String
// Gets the content of the stringstream's buffer as an std::string. Each '\0'
// character in the buffer is replaced with "\\0".

View File

@ -826,10 +826,6 @@ class GTEST_API_ UnitTestImpl {
bool catch_exceptions() const { return catch_exceptions_; }
private:
// Returns true if a warning should be issued if no tests match the test
// filter flag.
bool ShouldWarnIfNoTestsMatchFilter() const;
struct CompareTestSuitesByPointer {
bool operator()(const TestSuite* lhs, const TestSuite* rhs) const {
return lhs->name_ < rhs->name_;

View File

@ -320,13 +320,13 @@ Mutex::~Mutex() {
}
}
void Mutex::lock() {
void Mutex::Lock() {
ThreadSafeLazyInit();
::EnterCriticalSection(critical_section_);
owner_thread_id_ = ::GetCurrentThreadId();
}
void Mutex::unlock() {
void Mutex::Unlock() {
ThreadSafeLazyInit();
// We don't protect writing to owner_thread_id_ here, as it's the
// caller's responsibility to ensure that the current thread holds the
@ -499,7 +499,7 @@ class ThreadLocalRegistryImpl {
MemoryIsNotDeallocated memory_is_not_deallocated;
#endif // _MSC_VER
DWORD current_thread = ::GetCurrentThreadId();
MutexLock lock(mutex_);
MutexLock lock(&mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked();
ThreadIdToThreadLocals::iterator thread_local_pos =
@ -532,7 +532,7 @@ class ThreadLocalRegistryImpl {
// Clean up the ThreadLocalValues data structure while holding the lock, but
// defer the destruction of the ThreadLocalValueHolderBases.
{
MutexLock lock(mutex_);
MutexLock lock(&mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked();
for (ThreadIdToThreadLocals::iterator it =
@ -559,7 +559,7 @@ class ThreadLocalRegistryImpl {
// Clean up the ThreadIdToThreadLocals data structure while holding the
// lock, but defer the destruction of the ThreadLocalValueHolderBases.
{
MutexLock lock(mutex_);
MutexLock lock(&mutex_);
ThreadIdToThreadLocals* const thread_to_thread_locals =
GetThreadLocalsMapLocked();
ThreadIdToThreadLocals::iterator thread_local_pos =

View File

@ -50,7 +50,7 @@
#include <iomanip>
#include <ios>
#include <ostream> // NOLINT
#include <string_view>
#include <string>
#include <type_traits>
#include "gtest/internal/gtest-port.h"
@ -333,14 +333,14 @@ void PrintTo(__int128_t v, ::std::ostream* os) {
// Prints the given array of characters to the ostream. CharType must be either
// char, char8_t, char16_t, char32_t, or wchar_t.
// The array starts at begin (which may be nullptr) and contains len characters.
// The array may include '\0' characters and may not be NUL-terminated.
// The array starts at begin, the length is len, it may include '\0' characters
// and may not be NUL-terminated.
template <typename CharType>
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat
PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) {
const char* const quote_prefix = GetCharWidthPrefix(CharType());
const char* const quote_prefix = GetCharWidthPrefix(*begin);
*os << quote_prefix << "\"";
bool is_previous_hex = false;
CharFormat print_format = kAsIs;
@ -516,13 +516,13 @@ bool IsValidUTF8(const char* str, size_t length) {
void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
if (!ContainsUnprintableControlCodes(str, length) &&
IsValidUTF8(str, length)) {
*os << "\n As Text: \"" << ::std::string_view(str, length) << "\"";
*os << "\n As Text: \"" << str << "\"";
}
}
} // anonymous namespace
void PrintStringTo(::std::string_view s, ostream* os) {
void PrintStringTo(const ::std::string& s, ostream* os) {
if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
if (GTEST_FLAG_GET(print_utf8)) {
ConditionalPrintAsText(s.data(), s.size(), os);
@ -531,21 +531,21 @@ void PrintStringTo(::std::string_view s, ostream* os) {
}
#ifdef __cpp_lib_char8_t
void PrintU8StringTo(::std::u8string_view s, ostream* os) {
void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif
void PrintU16StringTo(::std::u16string_view s, ostream* os) {
void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
void PrintU32StringTo(::std::u32string_view s, ostream* os) {
void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(::std::wstring_view s, ostream* os) {
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_STD_WSTRING

View File

@ -192,17 +192,12 @@ static const char kDefaultOutputFormat[] = "xml";
// The default output file.
static const char kDefaultOutputFile[] = "test_detail";
// These environment variables are set by Bazel.
// https://bazel.build/reference/test-encyclopedia#initial-conditions
//
// The environment variable name for the test shard index.
static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
// The environment variable name for the total number of test shards.
static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
// The environment variable name for the test shard status file.
static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
// The environment variable name for the test output warnings file.
static const char kTestWarningsOutputFile[] = "TEST_WARNINGS_OUTPUT_FILE";
namespace internal {
@ -263,19 +258,6 @@ GTEST_DEFINE_bool_(
testing::GetDefaultFailFast()),
"True if and only if a test failure should stop further test execution.");
GTEST_DEFINE_bool_(
fail_if_no_test_linked,
testing::internal::BoolFromGTestEnv("fail_if_no_test_linked", false),
"True if and only if the test should fail if no test case (including "
"disabled test cases) is linked.");
GTEST_DEFINE_bool_(
fail_if_no_test_selected,
testing::internal::BoolFromGTestEnv("fail_if_no_test_selected", false),
"True if and only if the test should fail if no test case is selected to "
"run. A test case is selected to run if it is not disabled and is matched "
"by the filter flag so that it starts executing.");
GTEST_DEFINE_bool_(
also_run_disabled_tests,
testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false),
@ -713,7 +695,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
const char* const gtest_output_flag = s.c_str();
std::string format = GetOutputFormat();
if (format.empty()) format = kDefaultOutputFormat;
if (format.empty()) format = std::string(kDefaultOutputFormat);
const char* const colon = strchr(gtest_output_flag, ':');
if (colon == nullptr)
@ -1086,14 +1068,14 @@ void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
// Returns the global test part result reporter.
TestPartResultReporterInterface*
UnitTestImpl::GetGlobalTestPartResultReporter() {
internal::MutexLock lock(global_test_part_result_reporter_mutex_);
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
return global_test_part_result_reporter_;
}
// Sets the global test part result reporter.
void UnitTestImpl::SetGlobalTestPartResultReporter(
TestPartResultReporterInterface* reporter) {
internal::MutexLock lock(global_test_part_result_reporter_mutex_);
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
global_test_part_result_reporter_ = reporter;
}
@ -1495,17 +1477,17 @@ class Hunk {
// Print a unified diff header for one hunk.
// The format is
// "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
// where the left/right lengths are omitted if unnecessary.
// where the left/right parts are omitted if unnecessary.
void PrintHeader(std::ostream* ss) const {
size_t left_length = removes_ + common_;
size_t right_length = adds_ + common_;
*ss << "@@ " << "-" << left_start_;
if (left_length != 1) {
*ss << "," << left_length;
*ss << "@@ ";
if (removes_) {
*ss << "-" << left_start_ << "," << (removes_ + common_);
}
*ss << " " << "+" << right_start_;
if (right_length != 1) {
*ss << "," << right_length;
if (removes_ && adds_) {
*ss << " ";
}
if (adds_) {
*ss << "+" << right_start_ << "," << (adds_ + common_);
}
*ss << " @@\n";
}
@ -1678,25 +1660,10 @@ std::string GetBoolAssertionFailureMessage(
return msg.GetString();
}
// Helper function for implementing ASSERT_NEAR. Treats infinity as a specific
// value, such that comparing infinity to infinity is equal, the distance
// between -infinity and +infinity is infinity, and infinity <= infinity is
// true.
// Helper function for implementing ASSERT_NEAR.
AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
const char* abs_error_expr, double val1,
double val2, double abs_error) {
// We want to return success when the two values are infinity and at least
// one of the following is true:
// * The values are the same-signed infinity.
// * The error limit itself is infinity.
// This is done here so that we don't end up with a NaN when calculating the
// difference in values.
if (std::isinf(val1) && std::isinf(val2) &&
(std::signbit(val1) == std::signbit(val2) ||
(abs_error > 0.0 && std::isinf(abs_error)))) {
return AssertionSuccess();
}
const double diff = fabs(val1 - val2);
if (diff <= abs_error) return AssertionSuccess();
@ -2347,7 +2314,7 @@ void TestResult::RecordProperty(const std::string& xml_element,
if (!ValidateTestProperty(xml_element, test_property)) {
return;
}
internal::MutexLock lock(test_properties_mutex_);
internal::MutexLock lock(&test_properties_mutex_);
const std::vector<TestProperty>::iterator property_with_matching_key =
std::find_if(test_properties_.begin(), test_properties_.end(),
internal::TestPropertyKeyIs(test_property.key()));
@ -3305,7 +3272,6 @@ bool ShouldUseColor(bool stdout_is_tty) {
const bool term_supports_color =
term != nullptr && (String::CStringEquals(term, "xterm") ||
String::CStringEquals(term, "xterm-color") ||
String::CStringEquals(term, "xterm-ghostty") ||
String::CStringEquals(term, "xterm-kitty") ||
String::CStringEquals(term, "alacritty") ||
String::CStringEquals(term, "screen") ||
@ -4008,12 +3974,6 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener {
static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
const TestResult& result);
// Streams a test case XML stanza containing the given test result.
//
// Requires: result.Failed()
static void OutputXmlTestCaseForTestResult(::std::ostream* stream,
const TestResult& result);
// Streams an XML representation of a TestResult object.
static void OutputXmlTestResult(::std::ostream* stream,
const TestResult& result);
@ -4031,11 +3991,16 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener {
static void PrintXmlUnitTest(::std::ostream* stream,
const UnitTest& unit_test);
// Produces a string representing the test properties in a result as space
// delimited XML attributes based on the property key="value" pairs.
// When the std::string is not empty, it includes a space at the beginning,
// to delimit this attribute from prior attributes.
static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
// Streams an XML representation of the test properties of a TestResult
// object.
static void OutputXmlTestProperties(std::ostream* stream,
const TestResult& result,
const std::string& indent);
const TestResult& result);
// The output file.
const std::string output_file_;
@ -4256,15 +4221,6 @@ void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
*stream << ">";
OutputXmlTestCaseForTestResult(stream, result);
// Complete the test suite.
*stream << " </testsuite>\n";
}
// Streams a test case XML stanza containing the given test result.
void XmlUnitTestResultPrinter::OutputXmlTestCaseForTestResult(
::std::ostream* stream, const TestResult& result) {
// Output the boilerplate for a minimal test case with a single test.
*stream << " <testcase";
OutputXmlAttribute(stream, "testcase", "name", "");
@ -4279,6 +4235,9 @@ void XmlUnitTestResultPrinter::OutputXmlTestCaseForTestResult(
// Output the actual test result.
OutputXmlTestResult(stream, result);
// Complete the test suite.
*stream << " </testsuite>\n";
}
// Prints an XML representation of a TestInfo object.
@ -4355,8 +4314,8 @@ void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
internal::FormatCompilerIndependentFileLocation(part.file_name(),
part.line_number());
const std::string summary = location + "\n" + part.summary();
*stream << " <skipped message=\"" << EscapeXmlAttribute(summary)
<< "\">";
*stream << " <skipped message=\""
<< EscapeXmlAttribute(summary.c_str()) << "\">";
const std::string detail = location + "\n" + part.message();
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
*stream << "</skipped>\n";
@ -4369,7 +4328,7 @@ void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
if (failures == 0 && skips == 0) {
*stream << ">\n";
}
OutputXmlTestProperties(stream, result, /*indent=*/" ");
OutputXmlTestProperties(stream, result);
*stream << " </testcase>\n";
}
}
@ -4398,18 +4357,13 @@ void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
OutputXmlAttribute(
stream, kTestsuite, "timestamp",
FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));
*stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());
}
*stream << ">\n";
OutputXmlTestProperties(stream, test_suite.ad_hoc_test_result(),
/*indent=*/" ");
for (int i = 0; i < test_suite.total_test_count(); ++i) {
if (test_suite.GetTestInfo(i)->is_reportable())
OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
}
if (test_suite.ad_hoc_test_result().Failed()) {
OutputXmlTestCaseForTestResult(stream, test_suite.ad_hoc_test_result());
}
*stream << " </" << kTestsuite << ">\n";
}
@ -4439,12 +4393,11 @@ void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
OutputXmlAttribute(stream, kTestsuites, "random_seed",
StreamableToString(unit_test.random_seed()));
}
*stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
*stream << ">\n";
OutputXmlTestProperties(stream, unit_test.ad_hoc_test_result(),
/*indent=*/" ");
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
@ -4481,8 +4434,21 @@ void XmlUnitTestResultPrinter::PrintXmlTestsList(
*stream << "</" << kTestsuites << ">\n";
}
// Produces a string representing the test properties in a result as space
// delimited XML attributes based on the property key="value" pairs.
std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
const TestResult& result) {
Message attributes;
for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i);
attributes << " " << property.key() << "=" << "\""
<< EscapeXmlAttribute(property.value()) << "\"";
}
return attributes.GetString();
}
void XmlUnitTestResultPrinter::OutputXmlTestProperties(
std::ostream* stream, const TestResult& result, const std::string& indent) {
std::ostream* stream, const TestResult& result) {
const std::string kProperties = "properties";
const std::string kProperty = "property";
@ -4490,15 +4456,15 @@ void XmlUnitTestResultPrinter::OutputXmlTestProperties(
return;
}
*stream << indent << "<" << kProperties << ">\n";
*stream << " <" << kProperties << ">\n";
for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i);
*stream << indent << " <" << kProperty;
*stream << " <" << kProperty;
*stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\"";
*stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\"";
*stream << "/>\n";
}
*stream << indent << "</" << kProperties << ">\n";
*stream << " </" << kProperties << ">\n";
}
// End XmlUnitTestResultPrinter
@ -4537,12 +4503,6 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener {
static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
const TestResult& result);
// Streams a test case JSON stanza containing the given test result.
//
// Requires: result.Failed()
static void OutputJsonTestCaseForTestResult(::std::ostream* stream,
const TestResult& result);
// Streams a JSON representation of a TestResult object.
static void OutputJsonTestResult(::std::ostream* stream,
const TestResult& result);
@ -4713,15 +4673,6 @@ void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
}
*stream << Indent(6) << "\"testsuite\": [\n";
OutputJsonTestCaseForTestResult(stream, result);
// Finish the test suite.
*stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
}
// Streams a test case JSON stanza containing the given test result.
void JsonUnitTestResultPrinter::OutputJsonTestCaseForTestResult(
::std::ostream* stream, const TestResult& result) {
// Output the boilerplate for a new test case.
*stream << Indent(8) << "{\n";
OutputJsonKey(stream, "testcase", "name", "", Indent(10));
@ -4738,6 +4689,9 @@ void JsonUnitTestResultPrinter::OutputJsonTestCaseForTestResult(
// Output the actual test result.
OutputJsonTestResult(stream, result);
// Finish the test suite.
*stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
}
// Prints a JSON representation of a TestInfo object.
@ -4882,16 +4836,6 @@ void JsonUnitTestResultPrinter::PrintJsonTestSuite(
OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));
}
}
// If there was a failure in the test suite setup or teardown include that in
// the output.
if (test_suite.ad_hoc_test_result().Failed()) {
if (comma) {
*stream << ",\n";
}
OutputJsonTestCaseForTestResult(stream, test_suite.ad_hoc_test_result());
}
*stream << "\n" << kIndent << "]\n" << Indent(4) << "}";
}
@ -5088,7 +5032,7 @@ std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)
void* caller_frame = nullptr;
{
MutexLock lock(mutex_);
MutexLock lock(&mutex_);
caller_frame = caller_frame_;
}
@ -5127,7 +5071,7 @@ void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {
caller_frame = nullptr;
}
MutexLock lock(mutex_);
MutexLock lock(&mutex_);
caller_frame_ = caller_frame;
#endif // GTEST_HAS_ABSL
}
@ -5390,13 +5334,13 @@ void UnitTest::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_);
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_);
internal::MutexLock lock(&mutex_);
impl_->set_current_test_info(a_current_test_info);
}
@ -5435,7 +5379,7 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
Message msg;
msg << message;
internal::MutexLock lock(mutex_);
internal::MutexLock lock(&mutex_);
if (!impl_->gtest_trace_stack().empty()) {
msg << "\n" << GTEST_NAME_ << " trace:";
@ -5618,7 +5562,7 @@ const char* UnitTest::original_working_dir() const {
// or NULL if no test is running.
const TestSuite* UnitTest::current_test_suite() const
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(mutex_);
internal::MutexLock lock(&mutex_);
return impl_->current_test_suite();
}
@ -5626,7 +5570,7 @@ const TestSuite* UnitTest::current_test_suite() const
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const TestCase* UnitTest::current_test_case() const
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(mutex_);
internal::MutexLock lock(&mutex_);
return impl_->current_test_suite();
}
#endif
@ -5635,7 +5579,7 @@ const TestCase* UnitTest::current_test_case() const
// or NULL if no test is running.
const TestInfo* UnitTest::current_test_info() const
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(mutex_);
internal::MutexLock lock(&mutex_);
return impl_->current_test_info();
}
@ -5659,13 +5603,13 @@ UnitTest::~UnitTest() { delete impl_; }
// Google Test trace stack.
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(mutex_);
internal::MutexLock lock(&mutex_);
impl_->gtest_trace_stack().push_back(trace);
}
// Pops a trace from the per-thread Google Test trace stack.
void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(mutex_);
internal::MutexLock lock(&mutex_);
impl_->gtest_trace_stack().pop_back();
}
@ -5888,23 +5832,6 @@ TestSuite* UnitTestImpl::GetTestSuite(
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
// If the environment variable TEST_WARNINGS_OUTPUT_FILE was provided, appends
// `str` to the file, creating the file if necessary.
#if GTEST_HAS_FILE_SYSTEM
static void AppendToTestWarningsOutputFile(const std::string& str) {
const char* const filename = posix::GetEnv(kTestWarningsOutputFile);
if (filename == nullptr) {
return;
}
auto* const file = posix::FOpen(filename, "a");
if (file == nullptr) {
return;
}
GTEST_CHECK_(fwrite(str.data(), 1, str.size(), file) == str.size());
GTEST_CHECK_(posix::FClose(file) == 0);
}
#endif // GTEST_HAS_FILE_SYSTEM
// Runs all tests in this UnitTest object, prints the result, and
// returns true if all tests are successful. If any exception is
// thrown during a test, the test is considered to be failed, but the
@ -5926,28 +5853,6 @@ bool UnitTestImpl::RunAllTests() {
// user didn't call InitGoogleTest.
PostFlagParsingInit();
// Handle the case where the program has no tests linked.
// Sometimes this is a programmer mistake, but sometimes it is intended.
if (total_test_count() == 0) {
constexpr char kNoTestLinkedMessage[] =
"This test program does NOT link in any test case.";
constexpr char kNoTestLinkedFatal[] =
"This is INVALID. Please make sure to link in at least one test case.";
constexpr char kNoTestLinkedWarning[] =
"Please make sure this is intended.";
const bool fail_if_no_test_linked = GTEST_FLAG_GET(fail_if_no_test_linked);
ColoredPrintf(
GTestColor::kRed, "%s %s\n", kNoTestLinkedMessage,
fail_if_no_test_linked ? kNoTestLinkedFatal : kNoTestLinkedWarning);
if (fail_if_no_test_linked) {
return false;
}
#if GTEST_HAS_FILE_SYSTEM
AppendToTestWarningsOutputFile(std::string(kNoTestLinkedMessage) + ' ' +
kNoTestLinkedWarning + '\n');
#endif // GTEST_HAS_FILE_SYSTEM
}
#if GTEST_HAS_FILE_SYSTEM
// Even if sharding is not on, test runners may want to use the
// GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
@ -6087,20 +5992,6 @@ bool UnitTestImpl::RunAllTests() {
TearDownEnvironment);
repeater->OnEnvironmentsTearDownEnd(*parent_);
}
} else if (GTEST_FLAG_GET(fail_if_no_test_selected)) {
// If there were no tests to run, bail if we were requested to be
// strict.
constexpr char kNoTestsSelectedMessage[] =
"No tests ran. Check that tests exist and are not disabled or "
"filtered out.\n\n"
"For sharded runs, this error indicates an empty shard. This can "
"happen if you have more shards than tests, or if --gtest_filter "
"leaves a shard with no tests.\n\n"
"To permit empty shards (e.g., when debugging with a filter), "
"specify \n"
"--gtest_fail_if_no_test_selected=false.";
ColoredPrintf(GTestColor::kRed, "%s\n", kNoTestsSelectedMessage);
return false;
}
elapsed_time_ = timer.Elapsed();
@ -6135,17 +6026,6 @@ bool UnitTestImpl::RunAllTests() {
environments_.clear();
}
// Try to warn the user if no tests matched the test filter.
if (ShouldWarnIfNoTestsMatchFilter()) {
const std::string filter_warning =
std::string("filter \"") + GTEST_FLAG_GET(filter) +
"\" did not match any test; no tests were run\n";
ColoredPrintf(GTestColor::kRed, "WARNING: %s", filter_warning.c_str());
#if GTEST_HAS_FILE_SYSTEM
AppendToTestWarningsOutputFile(filter_warning);
#endif // GTEST_HAS_FILE_SYSTEM
}
if (!gtest_is_initialized_before_run_all_tests) {
ColoredPrintf(
GTestColor::kRed,
@ -6314,30 +6194,6 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
return num_selected_tests;
}
// Returns true if a warning should be issued if no tests match the test filter
// flag. We can't simply count the number of tests that ran because, for
// instance, test sharding and death tests might mean no tests are expected to
// run in this process, but will run in another process.
bool UnitTestImpl::ShouldWarnIfNoTestsMatchFilter() const {
if (total_test_count() == 0) {
// No tests were linked in to program.
// This case is handled by a different warning.
return false;
}
const PositiveAndNegativeUnitTestFilter gtest_flag_filter(
GTEST_FLAG_GET(filter));
for (auto* test_suite : test_suites_) {
const std::string& test_suite_name = test_suite->name_;
for (TestInfo* test_info : test_suite->test_info_list()) {
const std::string& test_name = test_info->name_;
if (gtest_flag_filter.MatchesTest(test_suite_name, test_name)) {
return false;
}
}
}
return true;
}
// Prints the given C-string on a single line by replacing all '\n'
// characters with string "\\n". If the output takes more than
// max_length characters, only prints the first max_length characters
@ -6784,8 +6640,6 @@ static bool ParseGoogleTestFlag(const char* const arg) {
GTEST_INTERNAL_PARSE_FLAG(death_test_style);
GTEST_INTERNAL_PARSE_FLAG(death_test_use_fork);
GTEST_INTERNAL_PARSE_FLAG(fail_fast);
GTEST_INTERNAL_PARSE_FLAG(fail_if_no_test_linked);
GTEST_INTERNAL_PARSE_FLAG(fail_if_no_test_selected);
GTEST_INTERNAL_PARSE_FLAG(filter);
GTEST_INTERNAL_PARSE_FLAG(internal_run_death_test);
GTEST_INTERNAL_PARSE_FLAG(list_tests);

View File

@ -30,7 +30,6 @@
#
# Bazel BUILD for The Google C++ Testing Framework (Google Test)
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
load("@rules_python//python:defs.bzl", "py_library", "py_test")
licenses(["notice"])
@ -46,38 +45,36 @@ cc_test(
"gtest-*.cc",
"googletest-*.cc",
"*.h",
"googletest/include/gtest/**/*.h",
],
exclude = [
# go/keep-sorted start
"googletest-break-on-failure-unittest_.cc",
"googletest-catch-exceptions-test_.cc",
"googletest-color-test_.cc",
"googletest-death-test_ex_test.cc",
"googletest-env-var-test_.cc",
"googletest-fail-if-no-test-linked-test-with-disabled-test_.cc",
"googletest-fail-if-no-test-linked-test-with-enabled-test_.cc",
"googletest-failfast-unittest_.cc",
"googletest-filter-unittest_.cc",
"googletest-global-environment-unittest_.cc",
"googletest-list-tests-unittest_.cc",
"googletest-listener-test.cc",
"googletest-message-test.cc",
"googletest-output-test_.cc",
"googletest-param-test-invalid-name1-test_.cc",
"googletest-param-test-invalid-name2-test_.cc",
"googletest-param-test-test",
"googletest-param-test-test.cc",
"googletest-param-test2-test.cc",
"googletest-setuptestsuite-test_.cc",
"googletest-shuffle-test_.cc",
"googletest-throw-on-failure-test_.cc",
"googletest-uninitialized-test_.cc",
"gtest-unittest-api_test.cc",
"googletest/src/gtest-all.cc",
"gtest_all_test.cc",
"gtest-death-test_ex_test.cc",
"gtest-listener_test.cc",
"gtest-unittest-api_test.cc",
"gtest_all_test.cc",
# go/keep-sorted end
"googletest-param-test-test.cc",
"googletest-param-test2-test.cc",
"googletest-catch-exceptions-test_.cc",
"googletest-color-test_.cc",
"googletest-env-var-test_.cc",
"googletest-failfast-unittest_.cc",
"googletest-filter-unittest_.cc",
"googletest-global-environment-unittest_.cc",
"googletest-break-on-failure-unittest_.cc",
"googletest-listener-test.cc",
"googletest-message-test.cc",
"googletest-output-test_.cc",
"googletest-list-tests-unittest_.cc",
"googletest-shuffle-test_.cc",
"googletest-setuptestsuite-test_.cc",
"googletest-uninitialized-test_.cc",
"googletest-death-test_ex_test.cc",
"googletest-param-test-test",
"googletest-throw-on-failure-test_.cc",
"googletest-param-test-invalid-name1-test_.cc",
"googletest-param-test-invalid-name2-test_.cc",
],
) + select({
"//:windows": [],
@ -327,26 +324,6 @@ cc_binary(
deps = ["//:gtest"],
)
cc_binary(
name = "googletest-fail-if-no-test-linked-test-without-test_",
testonly = 1,
deps = ["//:gtest_main"],
)
cc_binary(
name = "googletest-fail-if-no-test-linked-test-with-disabled-test_",
testonly = 1,
srcs = ["googletest-fail-if-no-test-linked-test-with-disabled-test_.cc"],
deps = ["//:gtest_main"],
)
cc_binary(
name = "googletest-fail-if-no-test-linked-test-with-enabled-test_",
testonly = 1,
srcs = ["googletest-fail-if-no-test-linked-test-with-enabled-test_.cc"],
deps = ["//:gtest_main"],
)
cc_test(
name = "gtest_skip_test",
size = "small",
@ -387,18 +364,6 @@ py_test(
deps = [":gtest_test_utils"],
)
py_test(
name = "googletest-fail-if-no-test-linked-test",
size = "small",
srcs = ["googletest-fail-if-no-test-linked-test.py"],
data = [
":googletest-fail-if-no-test-linked-test-with-disabled-test_",
":googletest-fail-if-no-test-linked-test-with-enabled-test_",
":googletest-fail-if-no-test-linked-test-without-test_",
],
deps = [":gtest_test_utils"],
)
cc_binary(
name = "googletest-shuffle-test_",
srcs = ["googletest-shuffle-test_.cc"],

View File

@ -79,7 +79,6 @@ class GTestColorTest(gtest_test_utils.TestCase):
self.assertTrue(UsesColor('cygwin', None, None))
self.assertTrue(UsesColor('xterm', None, None))
self.assertTrue(UsesColor('xterm-color', None, None))
self.assertTrue(UsesColor('xterm-ghostty', None, None))
self.assertTrue(UsesColor('xterm-kitty', None, None))
self.assertTrue(UsesColor('alacritty', None, None))
self.assertTrue(UsesColor('xterm-256color', None, None))

View File

@ -291,7 +291,7 @@ 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__ <= 23)
#if !(defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ <= 21)
EXPECT_PRED1(pred_segv, status_segv);
#endif
EXPECT_PRED1(pred_kill, status_kill);

View File

@ -1,38 +0,0 @@
// Copyright 2025, 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.
// Unit test for Google Test's --gtest_fail_if_no_test_linked flag.
//
// This program will be invoked from a Python test.
// Don't run it directly.
#include "gtest/gtest.h"
// A dummy test that is disabled.
TEST(SomeTest, DISABLED_Test1) {}

View File

@ -1,38 +0,0 @@
// Copyright 2025, 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.
// Unit test for Google Test's --gtest_fail_if_no_test_linked flag.
//
// This program will be invoked from a Python test.
// Don't run it directly.
#include "gtest/gtest.h"
// A dummy test that is enabled.
TEST(SomeTest, Test1) {}

View File

@ -1,165 +0,0 @@
#!/usr/bin/env python3 # pylint: disable=g-interpreter-mismatch
#
# Copyright 2025, 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.
"""Tests for Google Test's --gtest_fail_if_no_test_linked flag."""
import os
from googletest.test import gtest_test_utils
# The command line flag for enabling the fail-if-no-test-linked behavior.
FAIL_IF_NO_TEST_LINKED_FLAG = "gtest_fail_if_no_test_linked"
# The environment variable for the test output warnings file.
TEST_WARNINGS_OUTPUT_FILE = "TEST_WARNINGS_OUTPUT_FILE"
class GTestFailIfNoTestLinkedTest(gtest_test_utils.TestCase):
"""Tests the --gtest_fail_if_no_test_linked flag."""
def Run(self, program_name, flag=None, env=None):
"""Run the given program with the given flag.
Args:
program_name: Name of the program to run.
flag: The command line flag to pass to the program, or None.
env: Dictionary with environment to pass to the subprocess.
Returns:
True if the program exits with code 0, false otherwise.
"""
exe_path = gtest_test_utils.GetTestExecutablePath(program_name)
args = [exe_path]
if flag is not None:
args += [flag]
process = gtest_test_utils.Subprocess(args, capture_stderr=False, env=env)
return process.exited and process.exit_code == 0
def testSucceedsIfNoTestLinkedAndFlagNotSpecified(self):
"""Tests the behavior of no test linked and flag not specified."""
self.assertTrue(
self.Run("googletest-fail-if-no-test-linked-test-without-test_")
)
def testSucceedsIfNoTestLinkedAndFlagNotSpecifiedWithWarningFile(self):
"""Tests that no test linked results in warning file output."""
warning_file = os.path.join(gtest_test_utils.GetTempDir(), "NO_TEST_LINKED")
self.assertTrue(
self.Run(
"googletest-fail-if-no-test-linked-test-without-test_",
env={TEST_WARNINGS_OUTPUT_FILE: warning_file},
)
)
warning_file_contents = open(warning_file, "r").read()
self.assertIn("does NOT link", warning_file_contents)
def testFailsIfNoTestLinkedAndFlagSpecified(self):
"""Tests the behavior of no test linked and flag specified."""
warning_file = os.path.join(
gtest_test_utils.GetTempDir(), "SHOULD_NOT_EXIST"
)
self.assertFalse(
self.Run(
"googletest-fail-if-no-test-linked-test-without-test_",
f"--{FAIL_IF_NO_TEST_LINKED_FLAG}",
env={TEST_WARNINGS_OUTPUT_FILE: warning_file},
)
)
with self.assertRaises(FileNotFoundError):
open(warning_file, "r")
def testSucceedsIfEnabledTestLinkedAndFlagNotSpecified(self):
"""Tests the behavior of enabled test linked and flag not specified."""
warning_file = os.path.join(
gtest_test_utils.GetTempDir(), "SHOULD_NOT_EXIST"
)
self.assertTrue(
self.Run(
"googletest-fail-if-no-test-linked-test-with-enabled-test_",
env={TEST_WARNINGS_OUTPUT_FILE: warning_file},
)
)
with self.assertRaises(FileNotFoundError):
open(warning_file, "r")
def testSucceedsIfEnabledTestLinkedAndFlagSpecified(self):
"""Tests the behavior of enabled test linked and flag specified."""
warning_file = os.path.join(
gtest_test_utils.GetTempDir(), "SHOULD_NOT_EXIST"
)
self.assertTrue(
self.Run(
"googletest-fail-if-no-test-linked-test-with-enabled-test_",
f"--{FAIL_IF_NO_TEST_LINKED_FLAG}",
env={TEST_WARNINGS_OUTPUT_FILE: warning_file},
)
)
with self.assertRaises(FileNotFoundError):
open(warning_file, "r")
def testSucceedsIfDisabledTestLinkedAndFlagNotSpecified(self):
"""Tests the behavior of disabled test linked and flag not specified."""
warning_file = os.path.join(
gtest_test_utils.GetTempDir(), "SHOULD_NOT_EXIST"
)
self.assertTrue(
self.Run(
"googletest-fail-if-no-test-linked-test-with-disabled-test_",
env={TEST_WARNINGS_OUTPUT_FILE: warning_file},
)
)
with self.assertRaises(FileNotFoundError):
open(warning_file, "r")
def testSucceedsIfDisabledTestLinkedAndFlagSpecified(self):
"""Tests the behavior of disabled test linked and flag specified."""
warning_file = os.path.join(
gtest_test_utils.GetTempDir(), "SHOULD_NOT_EXIST"
)
self.assertTrue(
self.Run(
"googletest-fail-if-no-test-linked-test-with-disabled-test_",
f"--{FAIL_IF_NO_TEST_LINKED_FLAG}",
env={TEST_WARNINGS_OUTPUT_FILE: warning_file},
)
)
with self.assertRaises(FileNotFoundError):
open(warning_file, "r")
if __name__ == "__main__":
gtest_test_utils.Main()

View File

@ -1,91 +0,0 @@
#!/usr/bin/env python3 # pylint: disable=g-interpreter-mismatch
#
# Copyright 2025, 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.
"""Tests for Google Test's --gtest_fail_if_no_test_selected flag."""
from googletest.test import gtest_test_utils
# The command line flag for enabling the fail-if-no-test-selected behavior.
FAIL_IF_NO_TEST_SELECTED_FLAG = "gtest_fail_if_no_test_selected"
# The environment variable for the test output warnings file.
TEST_WARNINGS_OUTPUT_FILE = "TEST_WARNINGS_OUTPUT_FILE"
class GTestFailIfNoTestSelectedTest(gtest_test_utils.TestCase):
"""Tests the --gtest_fail_if_no_test_selected flag."""
def Run(self, program_name, flags=None, env=None):
"""Run the given program with the given flag.
Args:
program_name: Name of the program to run.
flags: The command line flags to pass to the program, or None.
env: Dictionary with environment to pass to the subprocess.
Returns:
True if the program exits with code 0, false otherwise.
"""
exe_path = gtest_test_utils.GetTestExecutablePath(program_name)
args = [exe_path]
if flags is not None:
args.extend(flags)
process = gtest_test_utils.Subprocess(args, capture_stderr=False, env=env)
return process.exited and process.exit_code == 0
def testSucceedsWhenFlagIsNotSetAndOnlyDisabledTestsPresent(self):
"""Tests that no test selected results in success without the flag set."""
self.assertTrue(
self.Run("googletest-fail-if-no-test-linked-test-with-disabled-test_"),
)
def testFailsWhenFlagIsSetAndOnlyDisabledTestsPresent(self):
"""Tests that no test selected results in failure with the flag set."""
self.assertFalse(
self.Run(
"googletest-fail-if-no-test-linked-test-with-disabled-test_",
flags=[f"--{FAIL_IF_NO_TEST_SELECTED_FLAG}"],
),
)
def testSucceedsWhenFlagIsSetAndEnabledTestsPresent(self):
"""Tests that a test running still succeeds when the flag is set."""
self.assertTrue(
self.Run(
"googletest-fail-if-no-test-linked-test-with-enabled-test_",
flags=[f"--{FAIL_IF_NO_TEST_SELECTED_FLAG}"],
),
)
if __name__ == "__main__":
gtest_test_utils.Main()

View File

@ -97,9 +97,6 @@ TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE'
# The environment variable for the test warnings output file.
TEST_WARNINGS_OUTPUT_FILE = 'TEST_WARNINGS_OUTPUT_FILE'
# The command line flag for specifying the test filters.
FILTER_FLAG = 'gtest_filter'
@ -422,22 +419,6 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase):
self.RunAndVerify('BadFilter', [])
self.RunAndVerifyAllowingDisabled('BadFilter', [])
def testBadFilterWithWarningFile(self):
"""Tests the warning file when a filter that matches nothing."""
warning_file = os.path.join(
gtest_test_utils.GetTempDir(), 'testBadFilterWithWarningFile'
)
extra_env = {TEST_WARNINGS_OUTPUT_FILE: warning_file}
args = ['--%s=%s' % (FILTER_FLAG, 'BadFilter')]
InvokeWithModifiedEnv(extra_env, RunAndReturnOutput, args)
with open(warning_file, 'r') as f:
warning_file_contents = f.read()
self.assertEqual(
warning_file_contents,
'filter "BadFilter" did not match any test; no tests were run\n',
)
def testFullName(self):
"""Tests filtering by full name."""

View File

@ -57,7 +57,7 @@ else:
STACK_TRACE_TEMPLATE = '\n'
EXPECTED_NON_EMPTY = {
'tests': 28,
'tests': 26,
'failures': 5,
'disabled': 2,
'errors': 0,
@ -323,14 +323,12 @@ EXPECTED_NON_EMPTY = {
'time': '*',
'timestamp': '*',
'SetUpTestSuite': 'yes',
'SetUpTestSuite (with whitespace)': 'yes and yes',
'TearDownTestSuite': 'aye',
'TearDownTestSuite (with whitespace)': 'aye and aye',
'testsuite': [
{
'name': 'OneProperty',
'file': 'gtest_xml_output_unittest_.cc',
'line': 125,
'line': 121,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -341,7 +339,7 @@ EXPECTED_NON_EMPTY = {
{
'name': 'IntValuedProperty',
'file': 'gtest_xml_output_unittest_.cc',
'line': 129,
'line': 125,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -352,7 +350,7 @@ EXPECTED_NON_EMPTY = {
{
'name': 'ThreeProperties',
'file': 'gtest_xml_output_unittest_.cc',
'line': 133,
'line': 129,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -365,7 +363,7 @@ EXPECTED_NON_EMPTY = {
{
'name': 'TwoValuesForOneKeyUsesLastValue',
'file': 'gtest_xml_output_unittest_.cc',
'line': 139,
'line': 135,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -387,7 +385,7 @@ EXPECTED_NON_EMPTY = {
{
'name': 'RecordProperty',
'file': 'gtest_xml_output_unittest_.cc',
'line': 144,
'line': 140,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -398,7 +396,7 @@ EXPECTED_NON_EMPTY = {
{
'name': 'ExternalUtilityThatCallsRecordIntValuedProperty',
'file': 'gtest_xml_output_unittest_.cc',
'line': 157,
'line': 153,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -411,7 +409,7 @@ EXPECTED_NON_EMPTY = {
'ExternalUtilityThatCallsRecordStringValuedProperty'
),
'file': 'gtest_xml_output_unittest_.cc',
'line': 161,
'line': 157,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -421,83 +419,6 @@ EXPECTED_NON_EMPTY = {
},
],
},
{
'name': 'SetupFailTest',
'tests': 1,
'failures': 0,
'disabled': 0,
'errors': 0,
'time': '*',
'timestamp': '*',
'testsuite': [
{
'name': 'NoopPassingTest',
'file': 'gtest_xml_output_unittest_.cc',
'line': 172,
'status': 'RUN',
'result': 'SKIPPED',
'timestamp': '*',
'time': '*',
'classname': 'SetupFailTest',
'skipped': [
{'message': 'gtest_xml_output_unittest_.cc:*\n'}
],
},
{
'name': '',
'status': 'RUN',
'result': 'COMPLETED',
'timestamp': '*',
'time': '*',
'classname': '',
'failures': [{
'failure': (
'gtest_xml_output_unittest_.cc:*\nExpected equality'
' of these values:\n 1\n 2'
+ STACK_TRACE_TEMPLATE
),
'type': '',
}],
},
],
},
{
'name': 'TearDownFailTest',
'tests': 1,
'failures': 0,
'disabled': 0,
'errors': 0,
'timestamp': '*',
'time': '*',
'testsuite': [
{
'name': 'NoopPassingTest',
'file': 'gtest_xml_output_unittest_.cc',
'line': 179,
'status': 'RUN',
'result': 'COMPLETED',
'timestamp': '*',
'time': '*',
'classname': 'TearDownFailTest',
},
{
'name': '',
'status': 'RUN',
'result': 'COMPLETED',
'timestamp': '*',
'time': '*',
'classname': '',
'failures': [{
'failure': (
'gtest_xml_output_unittest_.cc:*\nExpected equality'
' of these values:\n 1\n 2'
+ STACK_TRACE_TEMPLATE
),
'type': '',
}],
},
],
},
{
'name': 'TypedTest/0',
'tests': 1,
@ -510,7 +431,7 @@ EXPECTED_NON_EMPTY = {
'name': 'HasTypeParamAttribute',
'type_param': 'int',
'file': 'gtest_xml_output_unittest_.cc',
'line': 193,
'line': 173,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -530,7 +451,7 @@ EXPECTED_NON_EMPTY = {
'name': 'HasTypeParamAttribute',
'type_param': 'long',
'file': 'gtest_xml_output_unittest_.cc',
'line': 193,
'line': 173,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -550,7 +471,7 @@ EXPECTED_NON_EMPTY = {
'name': 'HasTypeParamAttribute',
'type_param': 'int',
'file': 'gtest_xml_output_unittest_.cc',
'line': 200,
'line': 180,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -570,7 +491,7 @@ EXPECTED_NON_EMPTY = {
'name': 'HasTypeParamAttribute',
'type_param': 'long',
'file': 'gtest_xml_output_unittest_.cc',
'line': 200,
'line': 180,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -591,7 +512,7 @@ EXPECTED_NON_EMPTY = {
'name': 'HasValueParamAttribute/0',
'value_param': '33',
'file': 'gtest_xml_output_unittest_.cc',
'line': 184,
'line': 164,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -602,7 +523,7 @@ EXPECTED_NON_EMPTY = {
'name': 'HasValueParamAttribute/1',
'value_param': '42',
'file': 'gtest_xml_output_unittest_.cc',
'line': 184,
'line': 164,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -613,7 +534,7 @@ EXPECTED_NON_EMPTY = {
'name': 'AnotherTestThatHasValueParamAttribute/0',
'value_param': '33',
'file': 'gtest_xml_output_unittest_.cc',
'line': 185,
'line': 165,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',
@ -624,7 +545,7 @@ EXPECTED_NON_EMPTY = {
'name': 'AnotherTestThatHasValueParamAttribute/1',
'value_param': '42',
'file': 'gtest_xml_output_unittest_.cc',
'line': 185,
'line': 165,
'status': 'RUN',
'result': 'COMPLETED',
'time': '*',

View File

@ -62,7 +62,7 @@ Expected equality of these values:
Which is: "\"Line\0 1\"\nLine 2"
"Line 2"
With diff:
@@ -1,2 +1 @@
@@ -1,2 @@
-\"Line\0 1\"
Line 2

View File

@ -35,17 +35,12 @@
#include "test/googletest-param-test-test.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#include <list>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <vector>
#include "gtest/gtest.h"
@ -588,71 +583,6 @@ TEST(ConvertTest, NonDefaultConstructAssign) {
EXPECT_TRUE(it == gen.end());
}
TEST(ConvertTest, WithConverterLambdaAndDeducedType) {
const ParamGenerator<ConstructFromT<int8_t>> gen =
ConvertGenerator(Values("0", std::string("1")), [](const std::string& s) {
size_t pos;
int64_t value = std::stoll(s, &pos);
EXPECT_EQ(pos, s.size());
return value;
});
ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
ConstructFromT<int8_t>(1)};
VerifyGenerator(gen, expected_values);
}
TEST(ConvertTest, WithConverterLambdaAndExplicitType) {
auto convert_generator = ConvertGenerator<std::string>(
Values("0", std::string("1")), [](std::string_view s) {
size_t pos;
int64_t value = std::stoll(std::string(s), &pos);
EXPECT_EQ(pos, s.size());
return value;
});
constexpr bool is_correct_type = std::is_same_v<
decltype(convert_generator),
testing::internal::ParamConverterGenerator<
std::string, std::function<int64_t(std::string_view)>>>;
EXPECT_TRUE(is_correct_type);
const ParamGenerator<ConstructFromT<int8_t>> gen = convert_generator;
ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
ConstructFromT<int8_t>(1)};
VerifyGenerator(gen, expected_values);
}
TEST(ConvertTest, WithConverterFunctionPointer) {
int64_t (*func_ptr)(const std::string&) = [](const std::string& s) {
size_t pos;
int64_t value = std::stoll(s, &pos);
EXPECT_EQ(pos, s.size());
return value;
};
const ParamGenerator<ConstructFromT<int8_t>> gen =
ConvertGenerator(Values("0", std::string("1")), func_ptr);
ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
ConstructFromT<int8_t>(1)};
VerifyGenerator(gen, expected_values);
}
TEST(ConvertTest, WithConverterFunctionReference) {
int64_t (*func_ptr)(const std::string&) = [](const std::string& s) {
size_t pos;
int64_t value = std::stoll(s, &pos);
EXPECT_EQ(pos, s.size());
return value;
};
int64_t (&func_ref)(const std::string&) = *func_ptr;
const ParamGenerator<ConstructFromT<int8_t>> gen =
ConvertGenerator(Values("0", std::string("1")), func_ref);
ConstructFromT<int8_t> expected_values[] = {ConstructFromT<int8_t>(0),
ConstructFromT<int8_t>(1)};
VerifyGenerator(gen, expected_values);
}
// Tests that an generator produces correct sequence after being
// assigned from another generator.
TEST(ParamGeneratorTest, AssignmentWorks) {
@ -696,7 +626,7 @@ class TestGenerationEnvironment : public ::testing::Environment {
msg << "TestsExpandedAndRun/" << i;
if (UnitTestOptions::FilterMatchesTest(
"TestExpansionModule/MultipleTestGenerationTest",
msg.GetString())) {
msg.GetString().c_str())) {
perform_check = true;
}
}
@ -1174,7 +1104,7 @@ TEST_P(ParameterizedDerivedTest, SeesSequence) {
class ParameterizedDeathTest : public ::testing::TestWithParam<int> {};
TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {
EXPECT_DEATH_IF_SUPPORTED((void)GetParam(), ".* value-parameterized test .*");
EXPECT_DEATH_IF_SUPPORTED(GetParam(), ".* value-parameterized test .*");
}
INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest,

View File

@ -288,8 +288,8 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
defined(GTEST_OS_OPENBSD) || defined(GTEST_OS_GNU_HURD)
void* ThreadFunc(void* data) {
internal::Mutex* mutex = static_cast<internal::Mutex*>(data);
mutex->lock();
mutex->unlock();
mutex->Lock();
mutex->Unlock();
return nullptr;
}
@ -308,7 +308,7 @@ TEST(GetThreadCountTest, ReturnsCorrectValue) {
internal::Mutex mutex;
{
internal::MutexLock lock(mutex);
internal::MutexLock lock(&mutex);
pthread_attr_t attr;
ASSERT_EQ(0, pthread_attr_init(&attr));
ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
@ -1028,9 +1028,7 @@ TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
EXPECT_DEATH_IF_SUPPORTED(
{
Mutex m;
{
MutexLock lock(m);
}
{ MutexLock lock(&m); }
m.AssertHeld();
},
"thread .*hold");
@ -1038,13 +1036,13 @@ TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
Mutex m;
MutexLock lock(m);
MutexLock lock(&m);
m.AssertHeld();
}
class AtomicCounterWithMutex {
public:
explicit AtomicCounterWithMutex(Mutex& mutex)
explicit AtomicCounterWithMutex(Mutex* mutex)
: value_(0), mutex_(mutex), random_(42) {}
void Increment() {
@ -1085,7 +1083,7 @@ class AtomicCounterWithMutex {
private:
volatile int value_;
Mutex& mutex_; // Protects value_.
Mutex* const mutex_; // Protects value_.
Random random_;
};
@ -1096,7 +1094,7 @@ void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
// Tests that the mutex only lets one thread at a time to lock it.
TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
Mutex mutex;
AtomicCounterWithMutex locked_counter(mutex);
AtomicCounterWithMutex locked_counter(&mutex);
typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
const int kCycleCount = 20;

View File

@ -32,7 +32,6 @@
// This file tests the universal value printer.
#include <algorithm>
#include <any>
#include <cctype>
#include <cstdint>
#include <cstring>
@ -43,17 +42,14 @@
#include <list>
#include <map>
#include <memory>
#include <optional>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <variant>
#include <vector>
#include "gtest/gtest-printers.h"
@ -66,11 +62,7 @@
#if GTEST_INTERNAL_HAS_STD_SPAN
#include <span> // NOLINT
#endif // GTEST_INTERNAL_HAS_STD_SPAN
#if GTEST_INTERNAL_HAS_COMPARE_LIB
#include <compare> // NOLINT
#endif // GTEST_INTERNAL_HAS_COMPARE_LIB
#endif // GTEST_INTERNAL_HAS_STD_SPAN
// Some user-defined types for testing the universal value printer.
@ -125,9 +117,6 @@ class UnprintableTemplateInGlobal {
// A user-defined streamable type in the global namespace.
class StreamableInGlobal {
public:
StreamableInGlobal() = default;
StreamableInGlobal(const StreamableInGlobal&) = default;
StreamableInGlobal& operator=(const StreamableInGlobal&) = default;
virtual ~StreamableInGlobal() = default;
};
@ -579,8 +568,6 @@ TEST(PrintU8StringTest, Null) {
}
// Tests that u8 strings are escaped properly.
// TODO(b/396121064) - Fix this test under MSVC
#ifndef _MSC_VER
TEST(PrintU8StringTest, EscapesProperly) {
const char8_t* p = u8"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
EXPECT_EQ(PrintPointer(p) +
@ -588,8 +575,7 @@ TEST(PrintU8StringTest, EscapesProperly) {
"hello \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
Print(p));
}
#endif // _MSC_VER
#endif // __cpp_lib_char8_t
#endif
// const char16_t*.
TEST(PrintU16StringTest, Const) {
@ -800,7 +786,7 @@ struct Foo {
TEST(PrintPointerTest, MemberVariablePointer) {
EXPECT_TRUE(HasPrefix(Print(&Foo::value),
Print(sizeof(&Foo::value)) + "-byte object "));
int Foo::* p = NULL; // NOLINT
int Foo::*p = NULL; // NOLINT
EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
}
@ -927,7 +913,7 @@ TEST(PrintArrayTest, BigArray) {
PrintArrayHelper(a));
}
// Tests printing ::std::string and ::string_view.
// Tests printing ::string and ::std::string.
// ::std::string.
TEST(PrintStringTest, StringInStdNamespace) {
@ -937,13 +923,6 @@ TEST(PrintStringTest, StringInStdNamespace) {
Print(str));
}
TEST(PrintStringTest, StringViewInStdNamespace) {
const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
const ::std::string_view str(s, sizeof(s));
EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
Print(str));
}
TEST(PrintStringTest, StringAmbiguousHex) {
// "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
// '\x6', '\x6B', or '\x6BA'.
@ -961,7 +940,7 @@ TEST(PrintStringTest, StringAmbiguousHex) {
EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
}
// Tests printing ::std::wstring and ::std::wstring_view.
// Tests printing ::std::wstring.
#if GTEST_HAS_STD_WSTRING
// ::std::wstring.
TEST(PrintWideStringTest, StringInStdNamespace) {
@ -973,15 +952,6 @@ TEST(PrintWideStringTest, StringInStdNamespace) {
Print(str));
}
TEST(PrintWideStringTest, StringViewInStdNamespace) {
const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
const ::std::wstring_view str(s, sizeof(s) / sizeof(wchar_t));
EXPECT_EQ(
"L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
"\\xD3\\x576\\x8D3\\xC74D a\\0\"",
Print(str));
}
TEST(PrintWideStringTest, StringAmbiguousHex) {
// same for wide strings.
EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12"
@ -1000,12 +970,6 @@ TEST(PrintStringTest, U8String) {
EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
EXPECT_EQ("u8\"Hello, \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", Print(str));
}
TEST(PrintStringTest, U8StringView) {
std::u8string_view str = u8"Hello, 世界";
EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
EXPECT_EQ("u8\"Hello, \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", Print(str));
}
#endif
TEST(PrintStringTest, U16String) {
@ -1014,24 +978,12 @@ TEST(PrintStringTest, U16String) {
EXPECT_EQ("u\"Hello, \\x4E16\\x754C\"", Print(str));
}
TEST(PrintStringTest, U16StringView) {
std::u16string_view str = u"Hello, 世界";
EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
EXPECT_EQ("u\"Hello, \\x4E16\\x754C\"", Print(str));
}
TEST(PrintStringTest, U32String) {
std::u32string str = U"Hello, 🗺️";
EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type
EXPECT_EQ("U\"Hello, \\x1F5FA\\xFE0F\"", Print(str));
}
TEST(PrintStringTest, U32StringView) {
std::u32string_view str = U"Hello, 🗺️";
EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type
EXPECT_EQ("U\"Hello, \\x1F5FA\\xFE0F\"", Print(str));
}
// Tests printing types that support generic streaming (i.e. streaming
// to std::basic_ostream<Char, CharTraits> for any valid Char and
// CharTraits types).
@ -1491,7 +1443,7 @@ TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
// Tests that the universal printer prints a member variable pointer
// passed by reference.
TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
int Foo::* p = &Foo::value; // NOLINT
int Foo::*p = &Foo::value; // NOLINT
EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " +
Print(sizeof(p)) + "-byte object "));
}
@ -1699,7 +1651,7 @@ TEST(PrintToStringTest, ContainsNonLatin) {
EXPECT_PRINT_TO_STRING_(non_ascii_str,
"\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
" As Text: \"오전 4:30\"");
non_ascii_str = "From ä — ẑ";
non_ascii_str = ::std::string("From ä — ẑ");
EXPECT_PRINT_TO_STRING_(non_ascii_str,
"\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
"\n As Text: \"From ä — ẑ\"");
@ -1929,22 +1881,6 @@ TEST(UniversalPrintTest, SmartPointers) {
PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));
}
TEST(UniversalPrintTest, StringViewNonZeroTerminated) {
// Craft a non-ASCII UTF-8 input (to trigger a special path in
// `ConditionalPrintAsText`). Use array notation instead of the string
// literal syntax, to avoid placing a terminating 0 at the end of the input.
const char s[] = {'\357', '\243', '\242', 'X'};
// Only include the first 3 bytes in the `string_view` and leave the last one
// ('X') outside. This way, if the code tries to use `str.data()` with
// `strlen` instead of `str.size()`, it will include 'X' and cause a visible
// difference (in addition to ASAN tests detecting a buffer overflow due to
// the missing 0 at the end).
const ::std::string_view str(s, 3);
::std::stringstream ss;
UniversalPrint(str, &ss);
EXPECT_EQ("\"\\xEF\\xA3\\xA2\"\n As Text: \"\xEF\xA3\xA2\"", ss.str());
}
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
EXPECT_EQ(0u, result.size());
@ -1974,6 +1910,7 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
EXPECT_EQ("\"a\"", result[1]);
}
#if GTEST_INTERNAL_HAS_ANY
class PrintAnyTest : public ::testing::Test {
protected:
template <typename T>
@ -1987,12 +1924,12 @@ class PrintAnyTest : public ::testing::Test {
};
TEST_F(PrintAnyTest, Empty) {
std::any any;
internal::Any any;
EXPECT_EQ("no value", PrintToString(any));
}
TEST_F(PrintAnyTest, NonEmpty) {
std::any any;
internal::Any any;
constexpr int val1 = 10;
const std::string val2 = "content";
@ -2003,23 +1940,27 @@ TEST_F(PrintAnyTest, NonEmpty) {
EXPECT_EQ("value of type " + ExpectedTypeName<std::string>(),
PrintToString(any));
}
#endif // GTEST_INTERNAL_HAS_ANY
#if GTEST_INTERNAL_HAS_OPTIONAL
TEST(PrintOptionalTest, Basic) {
EXPECT_EQ("(nullopt)", PrintToString(std::nullopt));
std::optional<int> value;
EXPECT_EQ("(nullopt)", PrintToString(internal::Nullopt()));
internal::Optional<int> value;
EXPECT_EQ("(nullopt)", PrintToString(value));
value = {7};
EXPECT_EQ("(7)", PrintToString(value));
EXPECT_EQ("(1.1)", PrintToString(std::optional<double>{1.1}));
EXPECT_EQ("(\"A\")", PrintToString(std::optional<std::string>{"A"}));
EXPECT_EQ("(1.1)", PrintToString(internal::Optional<double>{1.1}));
EXPECT_EQ("(\"A\")", PrintToString(internal::Optional<std::string>{"A"}));
}
#endif // GTEST_INTERNAL_HAS_OPTIONAL
#if GTEST_INTERNAL_HAS_VARIANT
struct NonPrintable {
unsigned char contents = 17;
};
TEST(PrintOneofTest, Basic) {
using Type = std::variant<int, StreamableInGlobal, NonPrintable>;
using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;
EXPECT_EQ("('int(index = 0)' with value 7)", PrintToString(Type(7)));
EXPECT_EQ("('StreamableInGlobal(index = 1)' with value StreamableInGlobal)",
PrintToString(Type(StreamableInGlobal{})));
@ -2028,26 +1969,7 @@ TEST(PrintOneofTest, Basic) {
"1-byte object <11>)",
PrintToString(Type(NonPrintable{})));
}
#if GTEST_INTERNAL_HAS_COMPARE_LIB
TEST(PrintOrderingTest, Basic) {
EXPECT_EQ("(less)", PrintToString(std::strong_ordering::less));
EXPECT_EQ("(greater)", PrintToString(std::strong_ordering::greater));
// equal == equivalent for strong_ordering.
EXPECT_EQ("(equal)", PrintToString(std::strong_ordering::equivalent));
EXPECT_EQ("(equal)", PrintToString(std::strong_ordering::equal));
EXPECT_EQ("(less)", PrintToString(std::weak_ordering::less));
EXPECT_EQ("(greater)", PrintToString(std::weak_ordering::greater));
EXPECT_EQ("(equivalent)", PrintToString(std::weak_ordering::equivalent));
EXPECT_EQ("(less)", PrintToString(std::partial_ordering::less));
EXPECT_EQ("(greater)", PrintToString(std::partial_ordering::greater));
EXPECT_EQ("(equivalent)", PrintToString(std::partial_ordering::equivalent));
EXPECT_EQ("(unordered)", PrintToString(std::partial_ordering::unordered));
}
#endif
#endif // GTEST_INTERNAL_HAS_VARIANT
namespace {
class string_ref;

View File

@ -31,14 +31,14 @@
class SetupFailTest : public ::testing::Test {
protected:
static void SetUpTestSuite() { ASSERT_STREQ("", "SET_UP_FAIL"); }
static void SetUpTestSuite() { ASSERT_EQ("", "SET_UP_FAIL"); }
};
TEST_F(SetupFailTest, NoopPassingTest) {}
class TearDownFailTest : public ::testing::Test {
protected:
static void TearDownTestSuite() { ASSERT_STREQ("", "TEAR_DOWN_FAIL"); }
static void TearDownTestSuite() { ASSERT_EQ("", "TEAR_DOWN_FAIL"); }
};
TEST_F(TearDownFailTest, NoopPassingTest) {}

View File

@ -95,9 +95,9 @@ void ManyAsserts(int id) {
// RecordProperty() should interact safely with other threads as well.
// The shared_key forces property updates.
Test::RecordProperty(IdToKey(id, "string"), IdToString(id));
Test::RecordProperty(IdToKey(id, "string").c_str(), IdToString(id).c_str());
Test::RecordProperty(IdToKey(id, "int").c_str(), id);
Test::RecordProperty("shared_key", IdToString(id));
Test::RecordProperty("shared_key", IdToString(id).c_str());
// This assertion should fail kThreadCount times per thread. It
// is for testing whether Google Test can handle failed assertions in a

View File

@ -195,7 +195,7 @@ class TestEventListenersAccessor {
class UnitTestRecordPropertyTestHelper : public Test {
protected:
UnitTestRecordPropertyTestHelper() = default;
UnitTestRecordPropertyTestHelper() {}
// Forwards to UnitTest::RecordProperty() to bypass access controls.
void UnitTestRecordProperty(const char* key, const std::string& value) {
@ -2163,7 +2163,7 @@ class UnitTestRecordPropertyTestEnvironment : public Environment {
};
// This will test property recording outside of any test or test case.
[[maybe_unused]] static Environment* record_property_env =
GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static Environment* record_property_env =
AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
@ -2649,8 +2649,8 @@ TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
// Tests that IsSubstring returns the correct result when the input
// argument type is ::std::string.
TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_TRUE(IsSubstring("", "", "hello", "ahellob"));
EXPECT_FALSE(IsSubstring("", "", "hello", "world"));
EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
}
#if GTEST_HAS_STD_WSTRING
@ -2707,8 +2707,8 @@ TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
// Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::string.
TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_FALSE(IsNotSubstring("", "", "hello", "ahellob"));
EXPECT_TRUE(IsNotSubstring("", "", "hello", "world"));
EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
}
// Tests that IsNotSubstring() generates the correct message when the input
@ -2719,7 +2719,8 @@ TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
" Actual: \"needle\"\n"
"Expected: not a substring of haystack_expr\n"
"Which is: \"two needles\"",
IsNotSubstring("needle_expr", "haystack_expr", "needle", "two needles")
IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"),
"two needles")
.failure_message());
}
@ -2869,8 +2870,6 @@ TEST_F(FloatTest, LargeDiff) {
// This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large.
TEST_F(FloatTest, Infinity) {
EXPECT_FLOAT_EQ(values_.infinity, values_.infinity);
EXPECT_FLOAT_EQ(-values_.infinity, -values_.infinity);
EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
@ -2895,11 +2894,6 @@ TEST_F(FloatTest, NaN) {
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2");
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, v.nan1, 1.0f), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, v.nan1, v.infinity), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(v.infinity, v.nan1, 1.0f), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(v.infinity, v.nan1, v.infinity),
"v.nan1");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity");
}
@ -2923,28 +2917,11 @@ TEST_F(FloatTest, Commutative) {
// Tests EXPECT_NEAR.
TEST_F(FloatTest, EXPECT_NEAR) {
static const FloatTest::TestValues& v = this->values_;
EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
EXPECT_NEAR(2.0f, 3.0f, 1.0f);
EXPECT_NEAR(v.infinity, v.infinity, 0.0f);
EXPECT_NEAR(-v.infinity, -v.infinity, 0.0f);
EXPECT_NEAR(0.0f, 1.0f, v.infinity);
EXPECT_NEAR(v.infinity, -v.infinity, v.infinity);
EXPECT_NEAR(-v.infinity, v.infinity, v.infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
"The difference between 1.0f and 1.5f is 0.5, "
"which exceeds 0.25f");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(v.infinity, -v.infinity, 0.0f), // NOLINT
"The difference between v.infinity and -v.infinity "
"is inf, which exceeds 0.0f");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(-v.infinity, v.infinity, 0.0f), // NOLINT
"The difference between -v.infinity and v.infinity "
"is inf, which exceeds 0.0f");
EXPECT_NONFATAL_FAILURE(
EXPECT_NEAR(v.infinity, v.close_to_infinity, v.further_from_infinity),
"The difference between v.infinity and v.close_to_infinity is inf, which "
"exceeds v.further_from_infinity");
}
// Tests ASSERT_NEAR.
@ -3051,8 +3028,6 @@ TEST_F(DoubleTest, LargeDiff) {
// This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large.
TEST_F(DoubleTest, Infinity) {
EXPECT_DOUBLE_EQ(values_.infinity, values_.infinity);
EXPECT_DOUBLE_EQ(-values_.infinity, -values_.infinity);
EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
@ -3072,12 +3047,6 @@ TEST_F(DoubleTest, NaN) {
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, v.nan1, 1.0), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, v.nan1, v.infinity), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(v.infinity, v.nan1, 1.0), "v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(v.infinity, v.nan1, v.infinity),
"v.nan1");
EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity");
}
@ -3100,28 +3069,11 @@ TEST_F(DoubleTest, Commutative) {
// Tests EXPECT_NEAR.
TEST_F(DoubleTest, EXPECT_NEAR) {
static const DoubleTest::TestValues& v = this->values_;
EXPECT_NEAR(-1.0, -1.1, 0.2);
EXPECT_NEAR(2.0, 3.0, 1.0);
EXPECT_NEAR(v.infinity, v.infinity, 0.0);
EXPECT_NEAR(-v.infinity, -v.infinity, 0.0);
EXPECT_NEAR(0.0, 1.0, v.infinity);
EXPECT_NEAR(v.infinity, -v.infinity, v.infinity);
EXPECT_NEAR(-v.infinity, v.infinity, v.infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(v.infinity, -v.infinity, 0.0),
"The difference between v.infinity and -v.infinity "
"is inf, which exceeds 0.0");
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(-v.infinity, v.infinity, 0.0),
"The difference between -v.infinity and v.infinity "
"is inf, which exceeds 0.0");
EXPECT_NONFATAL_FAILURE(
EXPECT_NEAR(v.infinity, v.close_to_infinity, v.further_from_infinity),
"The difference between v.infinity and v.close_to_infinity is inf, which "
"exceeds v.further_from_infinity");
// At this magnitude adjacent doubles are 512.0 apart, so this triggers a
// slightly different failure reporting path.
EXPECT_NONFATAL_FAILURE(
@ -3578,13 +3530,13 @@ TEST(EditDistance, TestSuites) {
{__LINE__, "A", "A", " ", ""},
{__LINE__, "ABCDE", "ABCDE", " ", ""},
// Simple adds.
{__LINE__, "X", "XA", " +", "@@ -1 +1,2 @@\n X\n+A\n"},
{__LINE__, "X", "XABCD", " ++++", "@@ -1 +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
{__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
{__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
// Simple removes.
{__LINE__, "XA", "X", " -", "@@ -1,2 +1 @@\n X\n-A\n"},
{__LINE__, "XABCD", "X", " ----", "@@ -1,5 +1 @@\n X\n-A\n-B\n-C\n-D\n"},
{__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
{__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
// Simple replaces.
{__LINE__, "A", "a", "/", "@@ -1 +1 @@\n-A\n+a\n"},
{__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
{__LINE__, "ABCD", "abcd", "////",
"@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
// Path finding.
@ -3654,7 +3606,8 @@ TEST(AssertionTest, EqFailure) {
msg4.c_str());
const std::string msg5(
EqFailure("foo", "bar", "\"x\"", "\"y\"", true).failure_message());
EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true)
.failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" foo\n"
@ -6715,9 +6668,6 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
SetEnv("TERM", "xterm-color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-ghostty"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-kitty"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
@ -6755,8 +6705,9 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
// Verifies that StaticAssertTypeEq works in a namespace scope.
[[maybe_unused]] static bool dummy1 = StaticAssertTypeEq<bool, bool>();
[[maybe_unused]] static bool dummy2 =
GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy1 =
StaticAssertTypeEq<bool, bool>();
GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy2 =
StaticAssertTypeEq<const int, const int>();
// Verifies that StaticAssertTypeEq works in a class.

View File

@ -29,14 +29,14 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for the gtest_xml_output module."""
"""Unit test for the gtest_xml_output module"""
import datetime
import errno
import os
import re
import sys
from xml.dom import minidom
from xml.dom import minidom, Node
from googletest.test import gtest_test_utils
from googletest.test import gtest_xml_test_utils
@ -67,10 +67,7 @@ else:
sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="28" failures="5" disabled="2" errors="0" time="*" timestamp="*" name="AllTests">
<properties>
<property name="ad_hoc_property" value="42"/>
</properties>
<testsuites tests="26" failures="5" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="53" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
@ -135,91 +132,64 @@ It is good practice to tell why you skip a test.
</testcase>
</testsuite>
<testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<properties>
<property name="SetUpTestSuite" value="yes"/>
<property name="SetUpTestSuite (with whitespace)" value="yes and yes"/>
<property name="TearDownTestSuite" value="aye"/>
<property name="TearDownTestSuite (with whitespace)" value="aye and aye"/>
</properties>
<testcase name="OneProperty" file="gtest_xml_output_unittest_.cc" line="125" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
<testcase name="OneProperty" file="gtest_xml_output_unittest_.cc" line="121" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
<property name="key_1" value="1"/>
</properties>
</testcase>
<testcase name="IntValuedProperty" file="gtest_xml_output_unittest_.cc" line="129" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<testcase name="IntValuedProperty" file="gtest_xml_output_unittest_.cc" line="125" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
<property name="key_int" value="1"/>
</properties>
</testcase>
<testcase name="ThreeProperties" file="gtest_xml_output_unittest_.cc" line="133" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<testcase name="ThreeProperties" file="gtest_xml_output_unittest_.cc" line="129" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
<property name="key_1" value="1"/>
<property name="key_2" value="2"/>
<property name="key_3" value="3"/>
</properties>
</testcase>
<testcase name="TwoValuesForOneKeyUsesLastValue" file="gtest_xml_output_unittest_.cc" line="139" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<testcase name="TwoValuesForOneKeyUsesLastValue" file="gtest_xml_output_unittest_.cc" line="135" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
<property name="key_1" value="2"/>
</properties>
</testcase>
</testsuite>
<testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="RecordProperty" file="gtest_xml_output_unittest_.cc" line="144" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
<testcase name="RecordProperty" file="gtest_xml_output_unittest_.cc" line="140" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
<properties>
<property name="key" value="1"/>
</properties>
</testcase>
<testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" file="gtest_xml_output_unittest_.cc" line="157" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
<testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" file="gtest_xml_output_unittest_.cc" line="153" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
<properties>
<property name="key_for_utility_int" value="1"/>
</properties>
</testcase>
<testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" file="gtest_xml_output_unittest_.cc" line="161" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
<testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" file="gtest_xml_output_unittest_.cc" line="157" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
<properties>
<property name="key_for_utility_string" value="1"/>
</properties>
</testcase>
</testsuite>
<testsuite name="SetupFailTest" tests="1" failures="0" disabled="0" skipped="1" errors="0" time="*" timestamp="*">
<testcase name="NoopPassingTest" file="gtest_xml_output_unittest_.cc" line="172" status="run" result="skipped" time="*" timestamp="*" classname="SetupFailTest">
<skipped message="gtest_xml_output_unittest_.cc:*&#x0A;"><![CDATA[gtest_xml_output_unittest_.cc:*
]]></skipped>
</testcase>
<testcase name="" status="run" result="completed" classname="" time="*" timestamp="*">
<failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
1
2%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="TearDownFailTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="NoopPassingTest" file="gtest_xml_output_unittest_.cc" line="179" status="run" result="completed" time="*" timestamp="*" classname="TearDownFailTest"/>
<testcase name="" status="run" result="completed" classname="" time="*" timestamp="*">
<failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2%(stack_entity)s" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
1
2%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="184" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="HasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="184" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="185" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="185" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="HasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="164" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="HasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="164" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="165" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/1" file="gtest_xml_output_unittest_.cc" line="165" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
</testsuite>
<testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="193" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" />
<testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="173" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" />
</testsuite>
<testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="193" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" />
<testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="173" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" />
</testsuite>
<testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="200" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
<testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="180" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
</testsuite>
<testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="200" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
<testcase name="HasTypeParamAttribute" file="gtest_xml_output_unittest_.cc" line="180" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
</testsuite>
</testsuites>""" % {
'stack': STACK_TRACE_TEMPLATE,
@ -227,10 +197,8 @@ Expected equality of these values:
}
EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
<properties>
<property name="ad_hoc_property" value="42"/>
</properties>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*"
timestamp="*" name="AllTests" ad_hoc_property="42">
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0"
errors="0" time="*" timestamp="*">
<testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="53" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
@ -238,28 +206,19 @@ EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
</testsuites>"""
EXPECTED_SHARDED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
<properties>
<property name="ad_hoc_property" value="42"/>
</properties>
<testsuites tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Succeeds" file="gtest_xml_output_unittest_.cc" line="53" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
<testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<properties>
<property name="SetUpTestSuite" value="yes"/>
<property name="SetUpTestSuite (with whitespace)" value="yes and yes"/>
<property name="TearDownTestSuite" value="aye"/>
<property name="TearDownTestSuite (with whitespace)" value="aye and aye"/>
</properties>
<testcase name="IntValuedProperty" file="gtest_xml_output_unittest_.cc" line="129" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
<testcase name="IntValuedProperty" file="gtest_xml_output_unittest_.cc" line="125" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
<property name="key_int" value="1"/>
</properties>
</testcase>
</testsuite>
<testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" type_param="*" file="gtest_xml_output_unittest_.cc" line="200" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
<testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasValueParamAttribute/0" file="gtest_xml_output_unittest_.cc" line="164" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
</testsuite>
</testsuites>"""

View File

@ -112,12 +112,8 @@ TEST(InvalidCharactersTest, InvalidCharactersInMessage) {
class PropertyRecordingTest : public Test {
public:
static void SetUpTestSuite() {
RecordProperty("SetUpTestSuite (with whitespace)", "yes and yes");
RecordProperty("SetUpTestSuite", "yes");
}
static void SetUpTestSuite() { RecordProperty("SetUpTestSuite", "yes"); }
static void TearDownTestSuite() {
RecordProperty("TearDownTestSuite (with whitespace)", "aye and aye");
RecordProperty("TearDownTestSuite", "aye");
}
};
@ -162,22 +158,6 @@ TEST(NoFixtureTest, ExternalUtilityThatCallsRecordStringValuedProperty) {
ExternalUtilityThatCallsRecordProperty("key_for_utility_string", "1");
}
// Ensures that SetUpTestSuite and TearDownTestSuite failures are reported in
// the XML output.
class SetupFailTest : public ::testing::Test {
protected:
static void SetUpTestSuite() { ASSERT_EQ(1, 2); }
};
TEST_F(SetupFailTest, NoopPassingTest) {}
class TearDownFailTest : public ::testing::Test {
protected:
static void TearDownTestSuite() { ASSERT_EQ(1, 2); }
};
TEST_F(TearDownFailTest, NoopPassingTest) {}
// Verifies that the test parameter value is output in the 'value_param'
// XML attribute for value-parameterized tests.
class ValueParamTest : public TestWithParam<int> {};

View File

@ -6,36 +6,20 @@ 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("re2"):
if not native.existing_rule("com_googlesource_code_re2"):
http_archive(
name = "re2",
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("abseil-cpp"):
if not native.existing_rule("com_google_absl"):
http_archive(
name = "abseil-cpp",
sha256 = "9b2b72d4e8367c0b843fa2bcfa2b08debbe3cee34f7aaa27de55a6cbb3e843db",
strip_prefix = "abseil-cpp-20250814.0",
urls = ["https://github.com/abseil/abseil-cpp/releases/download/20250814.0/abseil-cpp-20250814.0.tar.gz"],
)
if not native.existing_rule("bazel_features"):
http_archive(
name = "bazel_features",
sha256 = "9390b391a68d3b24aef7966bce8556d28003fe3f022a5008efc7807e8acaaf1a",
strip_prefix = "bazel_features-1.36.0",
url = "https://github.com/bazel-contrib/bazel_features/releases/download/v1.36.0/bazel_features-v1.36.0.tar.gz",
)
if not native.existing_rule("rules_cc"):
http_archive(
name = "rules_cc",
sha256 = "207ea073dd20a705f9e8bc5ac02f5203e9621fc672774bb1a0935aefab7aebfa",
strip_prefix = "rules_cc-0.2.8",
url = "https://github.com/bazelbuild/rules_cc/releases/download/0.2.8/rules_cc-0.2.8.tar.gz",
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"):