Compare commits

..
Author SHA1 Message Date
Derek Mauro 58d77fa807 Updates the version number in CMakeLists.txt to 1.12.1 (#3919)
Due to an oversight version 1.12.0 didn't update the version in
CMakeLists.txt. A patch release will fix this issue.

I've also added a note to instructions for creating a release to check
for this issue.
2022-06-27 13:14:55 -04:00
156 changed files with 3838 additions and 5436 deletions
+43
View File
@@ -0,0 +1,43 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'bug'
assignees: ''
---
**Describe the bug**
Include a clear and concise description of what the problem is, including what
you expected to happen, and what actually happened.
**Steps to reproduce the bug**
It's important that we are able to reproduce the problem that you are
experiencing. Please provide all code and relevant steps to reproduce the
problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links
to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the
problem are also helpful.
**Does the bug persist in the most recent commit?**
We recommend using the latest commit in the master branch in your projects.
**What operating system and version are you using?**
If you are using a Linux distribution please include the name and version of the
distribution as well.
**What compiler and version are you using?**
Please include the output of `gcc -v` or `clang -v`, or the equivalent for your
compiler.
**What build system are you using?**
Please include the output of `bazel --version` or `cmake --version`, or the
equivalent for your build system.
**Additional context**
Add any other context about the problem here.
-53
View File
@@ -1,53 +0,0 @@
name: Bug Report
description: Let us know that something does not work as expected.
title: "[Bug]: Please title this bug report"
body:
- type: textarea
id: what-happened
attributes:
label: Describe the issue
description: What happened, and what did you expect to happen?
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce the problem
description: It is important that we are able to reproduce the problem that you are experiencing. Please provide all code and relevant steps to reproduce the problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the problem are also helpful.
validations:
required: true
- type: textarea
id: version
attributes:
label: What version of GoogleTest are you using?
description: Please include the output of `git rev-parse HEAD` or the GoogleTest release version number that you are using.
validations:
required: true
- type: textarea
id: os
attributes:
label: What operating system and version are you using?
description: If you are using a Linux distribution please include the name and version of the distribution as well.
validations:
required: true
- type: textarea
id: compiler
attributes:
label: What compiler and version are you using?
description: Please include the output of `gcc -v` or `clang -v`, or the equivalent for your compiler.
validations:
required: true
- type: textarea
id: buildsystem
attributes:
label: What build system are you using?
description: Please include the output of `bazel --version` or `cmake --version`, or the equivalent for your build system.
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional context
description: Add any other context about the problem here.
validations:
required: false
@@ -0,0 +1,24 @@
---
name: Feature request
about: Propose a new feature
title: ''
labels: 'enhancement'
assignees: ''
---
**Does the feature exist in the most recent commit?**
We recommend using the latest commit from GitHub in your projects.
**Why do we need this feature?**
Ideally, explain why a combination of existing features cannot be used instead.
**Describe the proposal**
Include a detailed description of the feature, with usage examples.
**Is the feature specific to an operating system, compiler, or build system version?**
If it is, please specify which versions.
@@ -1,33 +0,0 @@
name: Feature request
description: Propose a new feature.
title: "[FR]: Please title this feature request"
labels: "enhancement"
body:
- type: textarea
id: version
attributes:
label: Does the feature exist in the most recent commit?
description: We recommend using the latest commit from GitHub in your projects.
validations:
required: true
- type: textarea
id: why
attributes:
label: Why do we need this feature?
description: Ideally, explain why a combination of existing features cannot be used instead.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Describe the proposal.
description: Include a detailed description of the feature, with usage examples.
validations:
required: true
- type: textarea
id: platform
attributes:
label: Is the feature specific to an operating system, compiler, or build system version?
description: If it is, please specify which versions.
validations:
required: true
-4
View File
@@ -1,5 +1 @@
blank_issues_enabled: false
contact_links:
- name: Get Help
url: https://github.com/google/googletest/discussions
about: Please ask and answer questions here.
+7 -10
View File
@@ -4,40 +4,37 @@ on:
push:
pull_request:
env:
BAZEL_CXXOPTS: -std=c++14
jobs:
Linux:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Tests
run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ...
run: bazel test --test_output=errors //...
macOS:
MacOs:
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Tests
run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ...
run: bazel test --test_output=errors //...
Windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Tests
run: bazel test --cxxopt=/std:c++14 --features=external_include_paths --test_output=errors ...
run: bazel test --test_output=errors //...
-4
View File
@@ -24,10 +24,6 @@ Win32-Release/
x64-Debug/
x64-Release/
# VSCode files
.cache/
cmake-variants.yaml
# Ignore autoconf / automake files
Makefile.in
aclocal.m4
-1
View File
@@ -132,7 +132,6 @@ cc_library(
}),
deps = select({
":has_absl": [
"@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",
+10 -3
View File
@@ -1,10 +1,18 @@
# Note: CMake support is community-based. The maintainers do not use CMake
# internally.
cmake_minimum_required(VERSION 3.13)
cmake_minimum_required(VERSION 3.5)
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
endif (POLICY CMP0048)
if (POLICY CMP0077)
cmake_policy(SET CMP0077 NEW)
endif (POLICY CMP0077)
project(googletest-distribution)
set(GOOGLETEST_VERSION 1.14.0)
set(GOOGLETEST_VERSION 1.12.1)
if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
set(CMAKE_CXX_EXTENSIONS OFF)
@@ -18,7 +26,6 @@ include(GNUInstallDirs)
#Note that googlemock target already builds googletest
option(BUILD_GMOCK "Builds the googlemock subproject" ON)
option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON)
option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF)
if(BUILD_GMOCK)
add_subdirectory( googlemock )
+11 -21
View File
@@ -80,15 +80,15 @@ fairly rigid coding style, as defined by the
[google-styleguide](https://github.com/google/styleguide) project. All patches
will be expected to conform to the style outlined
[here](https://google.github.io/styleguide/cppguide.html). Use
[.clang-format](https://github.com/google/googletest/blob/main/.clang-format) to
check your formatting.
[.clang-format](https://github.com/google/googletest/blob/master/.clang-format)
to check your formatting.
## Requirements for Contributors
If you plan to contribute a patch, you need to build Google Test, Google Mock,
and their own tests from a git checkout, which has further requirements:
* [Python](https://www.python.org/) v3.6 or newer (for running some of the
* [Python](https://www.python.org/) v2.3 or newer (for running some of the
tests and re-generating certain source files from templates)
* [CMake](https://cmake.org/) v2.8.12 or newer
@@ -102,40 +102,30 @@ To make sure your changes work as intended and don't break existing
functionality, you'll want to compile and run Google Test and GoogleMock's own
tests. For that you can use CMake:
```
mkdir mybuild
cd mybuild
cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR}
```
mkdir mybuild
cd mybuild
cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR}
To choose between building only Google Test or Google Mock, you may modify your
cmake command to be one of each
```
cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests
cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests
```
cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests
cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests
Make sure you have Python installed, as some of Google Test's tests are written
in Python. If the cmake command complains about not being able to find Python
(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it
explicitly where your Python executable can be found:
```
cmake -DPYTHON_EXECUTABLE=path/to/python ...
```
cmake -DPYTHON_EXECUTABLE=path/to/python ...
Next, you can build Google Test and / or Google Mock and all desired tests. On
\*nix, this is usually done by
```
make
```
make
To run the tests, do
```
make test
```
make test
All tests should pass.
+47 -52
View File
@@ -8,8 +8,6 @@ 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.13.0`).
#### Documentation Updates
@@ -17,19 +15,10 @@ Our documentation is now live on GitHub Pages at
https://google.github.io/googletest/. We recommend browsing the documentation on
GitHub Pages rather than directly in the repository.
#### Release 1.13.0
#### Release 1.11.0
[Release 1.13.0](https://github.com/google/googletest/releases/tag/v1.13.0) is
now available.
The 1.13.x branch requires at least C++14.
#### Continuous Integration
We use Google's internal systems for continuous integration. \
GitHub Actions were added for the convenience of open-source contributors. They
are exclusively maintained by the open-source community and not used by the
GoogleTest team.
[Release 1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0)
is now available.
#### Coming Soon
@@ -54,46 +43,52 @@ More information about building GoogleTest can be found at
## Features
* xUnit test framework: \
Googletest is based on the [xUnit](https://en.wikipedia.org/wiki/XUnit)
testing framework, a popular architecture for unit testing
* Test discovery: \
Googletest automatically discovers and runs your tests, eliminating the need
to manually register your tests
* Rich set of assertions: \
Googletest provides a variety of assertions, such as equality, inequality,
exceptions, and more, making it easy to test your code
* User-defined assertions: \
You can define your own assertions with Googletest, making it simple to
write tests that are specific to your code
* Death tests: \
Googletest supports death tests, which verify that your code exits in a
certain way, making it useful for testing error-handling code
* Fatal and non-fatal failures: \
You can specify whether a test failure should be treated as fatal or
non-fatal with Googletest, allowing tests to continue running even if a
failure occurs
* Value-parameterized tests: \
Googletest supports value-parameterized tests, which run multiple times with
different input values, making it useful for testing functions that take
different inputs
* Type-parameterized tests: \
Googletest also supports type-parameterized tests, which run with different
data types, making it useful for testing functions that work with different
data types
* Various options for running tests: \
Googletest provides many options for running tests including running
individual tests, running tests in a specific order and running tests in
parallel
* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework.
* Test discovery.
* A rich set of assertions.
* User-defined assertions.
* Death tests.
* Fatal and non-fatal failures.
* Value-parameterized tests.
* Type-parameterized tests.
* Various options for running the tests.
* XML test report generation.
## Supported Platforms
GoogleTest follows Google's
[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See
[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
for a list of currently supported versions of compilers, platforms, and build
tools.
GoogleTest requires a codebase and compiler compliant with the C++11 standard or
newer.
The GoogleTest code is officially supported on the following platforms.
Operating systems or tools not listed below are community-supported. For
community-supported platforms, patches that do not complicate the code may be
considered.
If you notice any problems on your platform, please file an issue on the
[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
Pull requests containing fixes are welcome!
### Operating Systems
* Linux
* macOS
* Windows
### Compilers
* gcc 5.0+
* clang 5.0+
* MSVC 2015+
**macOS users:** Xcode 9.3+ provides clang 5.0+.
### Build Systems
* [Bazel](https://bazel.build/)
* [CMake](https://cmake.org/)
**Note:** Bazel is the build system used by the team internally and in tests.
CMake is supported on a best-effort basis and by the community.
## Who Is Using GoogleTest?
@@ -140,7 +135,7 @@ that generates stub code for GoogleTest.
## Contributing Changes
Please read
[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/main/CONTRIBUTING.md)
[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/master/CONTRIBUTING.md)
for details on how to contribute to this project.
Happy testing!
+27 -15
View File
@@ -1,27 +1,39 @@
workspace(name = "com_google_googletest")
load("//:googletest_deps.bzl", "googletest_deps")
googletest_deps()
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rules_python", # 2023-07-31T20:39:27Z
sha256 = "1250b59a33c591a1c4ba68c62e95fc88a84c334ec35a2e23f46cbc1b9a5a8b55",
strip_prefix = "rules_python-e355becc30275939d87116a4ec83dad4bb50d9e1",
urls = ["https://github.com/bazelbuild/rules_python/archive/e355becc30275939d87116a4ec83dad4bb50d9e1.zip"],
name = "com_google_absl",
sha256 = "1a1745b5ee81392f5ea4371a4ca41e55d446eeaee122903b2eaffbd8a3b67a2b",
strip_prefix = "abseil-cpp-01cc6567cff77738e416a7ddc17de2d435a780ce",
urls = ["https://github.com/abseil/abseil-cpp/archive/01cc6567cff77738e416a7ddc17de2d435a780ce.zip"], # 2022-06-21T19:28:27Z
)
# Note this must use a commit from the `abseil` branch of the RE2 project.
# https://github.com/google/re2/tree/abseil
http_archive(
name = "com_googlesource_code_re2",
sha256 = "0a890c2aa0bb05b2ce906a15efb520d0f5ad4c7d37b8db959c43772802991887",
strip_prefix = "re2-a427f10b9fb4622dd6d8643032600aa1b50fbd12",
urls = ["https://github.com/google/re2/archive/a427f10b9fb4622dd6d8643032600aa1b50fbd12.zip"], # 2022-06-09
)
http_archive(
name = "bazel_skylib", # 2023-05-31T19:24:07Z
sha256 = "08c0386f45821ce246bbbf77503c973246ed6ee5c3463e41efc197fa9bc3a7f4",
strip_prefix = "bazel-skylib-288731ef9f7f688932bd50e704a91a45ec185f9b",
urls = ["https://github.com/bazelbuild/bazel-skylib/archive/288731ef9f7f688932bd50e704a91a45ec185f9b.zip"],
name = "rules_python",
sha256 = "0b460f17771258341528753b1679335b629d1d25e3af28eda47d009c103a6e15",
strip_prefix = "rules_python-aef17ad72919d184e5edb7abf61509eb78e57eda",
urls = ["https://github.com/bazelbuild/rules_python/archive/aef17ad72919d184e5edb7abf61509eb78e57eda.zip"], # 2022-06-21T23:44:47Z
)
http_archive(
name = "platforms", # 2023-07-28T19:44:27Z
sha256 = "40eb313613ff00a5c03eed20aba58890046f4d38dec7344f00bb9a8867853526",
strip_prefix = "platforms-4ad40ef271da8176d4fc0194d2089b8a76e19d7b",
urls = ["https://github.com/bazelbuild/platforms/archive/4ad40ef271da8176d4fc0194d2089b8a76e19d7b.zip"],
name = "bazel_skylib",
urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz"],
sha256 = "f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728",
)
http_archive(
name = "platforms",
sha256 = "a879ea428c6d56ab0ec18224f976515948822451473a80d06c2e50af0bbe5121",
strip_prefix = "platforms-da5541f26b7de1dc8e04c075c99df5351742a4a2",
urls = ["https://github.com/bazelbuild/platforms/archive/da5541f26b7de1dc8e04c075c99df5351742a4a2.zip"], # 2022-05-27
)
+5 -12
View File
@@ -31,15 +31,15 @@
set -euox pipefail
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20230217"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20230120"
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20220217"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20220621"
if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi
if [[ -z ${STD:-} ]]; then
STD="c++14 c++17 c++20"
STD="c++11 c++14 c++17 c++20"
fi
# Test the CMake build
@@ -51,11 +51,11 @@ for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
--workdir="/build" \
--rm \
--env="CC=${cc}" \
--env=CXXFLAGS="-Werror -Wdeprecated" \
--env="CXX_FLAGS=\"-Werror -Wdeprecated\"" \
${LINUX_LATEST_CONTAINER} \
/bin/bash -c "
cmake /src \
-DCMAKE_CXX_STANDARD=14 \
-DCMAKE_CXX_STANDARD=11 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
@@ -72,16 +72,13 @@ time docker run \
--workdir="/src" \
--rm \
--env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=c++14" \
${LINUX_GCC_FLOOR_CONTAINER} \
/usr/local/bin/bazel test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wundef" \
--copt="-Wno-error=pragmas" \
--distdir="/bazel-distdir" \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors
@@ -100,10 +97,8 @@ for std in ${STD}; do
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \
--distdir="/bazel-distdir" \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors
@@ -125,10 +120,8 @@ for std in ${STD}; do
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \
--distdir="/bazel-distdir" \
--features=external_include_paths \
--keep_going \
--linkopt="--gcc-toolchain=/usr/local" \
--show_timestamps \
+2 -5
View File
@@ -40,7 +40,7 @@ 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=14 \
-DCMAKE_CXX_STANDARD=11 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
@@ -53,7 +53,7 @@ done
# Test the Bazel build
# If we are running on Kokoro, check for a versioned Bazel binary.
KOKORO_GFILE_BAZEL_BIN="bazel-5.1.1-darwin-x86_64"
KOKORO_GFILE_BAZEL_BIN="bazel-3.7.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}
@@ -66,10 +66,7 @@ for absl in 0 1; do
${BAZEL_BIN} test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wundef" \
--cxxopt="-std=c++14" \
--define="absl=${absl}" \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors
-58
View File
@@ -1,58 +0,0 @@
SETLOCAL ENABLEDELAYEDEXPANSION
SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-5.1.1-windows-x86_64.exe
SET PATH=C:\Python34;%PATH%
SET BAZEL_PYTHON=C:\python34\python.exe
SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe
SET CMAKE_BIN="cmake.exe"
SET CTEST_BIN="ctest.exe"
SET CTEST_OUTPUT_ON_FAILURE=1
SET CMAKE_BUILD_PARALLEL_LEVEL=16
SET CTEST_PARALLEL_LEVEL=16
IF EXIST git\googletest (
CD git\googletest
) ELSE IF EXIST github\googletest (
CD github\googletest
)
IF %errorlevel% neq 0 EXIT /B 1
:: ----------------------------------------------------------------------------
:: CMake
MKDIR cmake_msvc2022
CD cmake_msvc2022
%CMAKE_BIN% .. ^
-G "Visual Studio 17 2022" ^
-DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^
-DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^
-DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^
-Dgtest_build_samples=ON ^
-Dgtest_build_tests=ON ^
-Dgmock_build_tests=ON
IF %errorlevel% neq 0 EXIT /B 1
%CMAKE_BIN% --build . --target ALL_BUILD --config Debug -- -maxcpucount
IF %errorlevel% neq 0 EXIT /B 1
%CTEST_BIN% -C Debug --timeout 600
IF %errorlevel% neq 0 EXIT /B 1
CD ..
RMDIR /S /Q cmake_msvc2022
:: ----------------------------------------------------------------------------
:: Bazel
SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community
%BAZEL_EXE% test ... ^
--compilation_mode=dbg ^
--copt=/std:c++14 ^
--copt=/WX ^
--features=external_include_paths ^
--keep_going ^
--test_output=errors ^
--test_tag_filters=-no_test_msvc2017
IF %errorlevel% neq 0 EXIT /B 1
+1 -1
View File
@@ -48,7 +48,7 @@
<div class="footer">
GoogleTest &middot;
<a href="https://github.com/google/googletest">GitHub Repository</a> &middot;
<a href="https://github.com/google/googletest/blob/main/LICENSE">License</a> &middot;
<a href="https://github.com/google/googletest/blob/master/LICENSE">License</a> &middot;
<a href="https://policies.google.com/privacy">Privacy Policy</a>
</div>
</div>
+119 -157
View File
@@ -1,9 +1,9 @@
# Advanced GoogleTest Topics
# Advanced googletest Topics
## Introduction
Now that you have read the [GoogleTest Primer](primer.md) and learned how to
write tests using GoogleTest, it's time to learn some new tricks. This document
Now that you have read the [googletest Primer](primer.md) and learned how to
write tests using googletest, it's time to learn some new tricks. This document
will show you more assertions as well as how to construct complex failure
messages, propagate fatal failures, reuse and speed up your test fixtures, and
use various flags with your tests.
@@ -25,7 +25,7 @@ Reference.
### Predicate Assertions for Better Error Messages
Even though GoogleTest has a rich set of assertions, they can never be complete,
Even though googletest has a rich set of assertions, they can never be complete,
as it's impossible (nor a good idea) to anticipate all scenarios a user might
run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a
complex expression, for lack of a better macro. This has the problem of not
@@ -35,7 +35,7 @@ failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
is awkward especially when the expression has side-effects or is expensive to
evaluate.
GoogleTest gives you three different options to solve this problem:
googletest gives you three different options to solve this problem:
#### Using an Existing Boolean Function
@@ -304,9 +304,9 @@ TEST_F(SkipFixture, SkipsOneTest) {
As with assertion macros, you can stream a custom message into `GTEST_SKIP()`.
## Teaching GoogleTest How to Print Your Values
## Teaching googletest How to Print Your Values
When a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument
When a test assertion such as `EXPECT_EQ` fails, googletest prints the argument
values to help you debug. It does this using a user-extensible value printer.
This printer knows how to print built-in C++ types, native arrays, STL
@@ -315,96 +315,73 @@ prints the raw bytes in the value and hopes that you the user can figure it out.
As mentioned earlier, the printer is *extensible*. That means you can teach it
to do a better job at printing your particular type than to dump the bytes. To
do that, define an `AbslStringify()` overload as a `friend` function template
for your type:
```cpp
namespace foo {
class Point { // We want GoogleTest to be able to print instances of this.
...
// Provide a friend overload.
template <typename Sink>
friend void AbslStringify(Sink& sink, const Point& point) {
absl::Format(&sink, "(%d, %d)", point.x, point.y);
}
int x;
int y;
};
// If you can't declare the function in the class it's important that the
// AbslStringify overload is defined in the SAME namespace that defines Point.
// C++'s look-up rules rely on that.
enum class EnumWithStringify { kMany = 0, kChoices = 1 };
template <typename Sink>
void AbslStringify(Sink& sink, EnumWithStringify e) {
absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices");
}
} // namespace foo
```
{: .callout .note}
Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its
string. For more information about supported operations on `AbslStringify()`'s
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
formatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`.
Sometimes, `AbslStringify()` might not be an option: your team may wish to print
types with extra debugging information for testing purposes only. If so, you can
instead define a `PrintTo()` function like this:
do that, define `<<` for your type:
```c++
#include <ostream>
namespace foo {
class Point {
...
friend void PrintTo(const Point& point, std::ostream* os) {
*os << "(" << point.x << "," << point.y << ")";
class Bar { // We want googletest to be able to print instances of this.
...
// Create a free inline friend function.
friend std::ostream& operator<<(std::ostream& os, const Bar& bar) {
return os << bar.DebugString(); // whatever needed to print bar to os
}
int x;
int y;
};
// If you can't declare the function in the class it's important that PrintTo()
// is defined in the SAME namespace that defines Point. C++'s look-up rules
// rely on that.
void PrintTo(const Point& point, std::ostream* os) {
*os << "(" << point.x << "," << point.y << ")";
// If you can't declare the function in the class it's important that the
// << operator is defined in the SAME namespace that defines Bar. C++'s look-up
// rules rely on that.
std::ostream& operator<<(std::ostream& os, const Bar& bar) {
return os << bar.DebugString(); // whatever needed to print bar to os
}
} // namespace foo
```
If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be
used by GoogleTest. This allows you to customize how the value appears in
GoogleTest's output without affecting code that relies on the behavior of
`AbslStringify()`.
Sometimes, this might not be an option: your team may consider it bad style to
have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that
doesn't do what you want (and you cannot change it). If so, you can instead
define a `PrintTo()` function like this:
If you have an existing `<<` operator and would like to define an
`AbslStringify()`, the latter will be used for GoogleTest printing.
```c++
#include <ostream>
If you want to print a value `x` using GoogleTest's value printer yourself, just
namespace foo {
class Bar {
...
friend void PrintTo(const Bar& bar, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os
}
};
// If you can't declare the function in the class it's important that PrintTo()
// is defined in the SAME namespace that defines Bar. C++'s look-up rules rely
// on that.
void PrintTo(const Bar& bar, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os
}
} // namespace foo
```
If you have defined both `<<` and `PrintTo()`, the latter will be used when
googletest is concerned. This allows you to customize how the value appears in
googletest's output without affecting code that relies on the behavior of its
`<<` operator.
If you want to print a value `x` using googletest's value printer yourself, just
call `::testing::PrintToString(x)`, which returns an `std::string`:
```c++
vector<pair<Point, int> > point_ints = GetPointIntVector();
vector<pair<Bar, int> > bar_ints = GetBarIntVector();
EXPECT_TRUE(IsCorrectPointIntVector(point_ints))
<< "point_ints = " << testing::PrintToString(point_ints);
EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
<< "bar_ints = " << testing::PrintToString(bar_ints);
```
For more details regarding `AbslStringify()` and its integration with other
libraries, see go/abslstringify.
## Death Tests
In many applications, there are assertions that can cause application failure if
@@ -474,7 +451,7 @@ Note that a death test only cares about three things:
3. does the stderr output match `matcher`?
In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it
will **not** cause the death test to fail, as GoogleTest assertions don't abort
will **not** cause the death test to fail, as googletest assertions don't abort
the process.
### Death Test Naming
@@ -505,14 +482,14 @@ TEST_F(FooDeathTest, DoesThat) {
### Regular Expression Syntax
When built with Bazel and using Abseil, GoogleTest uses the
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
systems (Linux, Cygwin, Mac), googletest uses the
[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
syntax. To learn about POSIX syntax, you may want to read this
[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended).
[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
On Windows, GoogleTest uses its own simple regular expression implementation. It
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
@@ -542,7 +519,7 @@ Expression | Meaning
`$` | 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
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
@@ -562,7 +539,7 @@ arrange that kind of environment. For example, statically-initialized modules
may start threads before main is ever reached. Once threads have been created,
it may be difficult or impossible to clean them up.
GoogleTest has three features intended to raise awareness of threading issues.
googletest has three features intended to raise awareness of threading issues.
1. A warning is emitted if multiple threads are running when a death test is
encountered.
@@ -585,7 +562,7 @@ The automated testing framework does not set the style flag. You can choose a
particular style of death tests by setting the flag programmatically:
```c++
GTEST_FLAG_SET(death_test_style, "threadsafe");
GTEST_FLAG_SET(death_test_style, "threadsafe")
```
You can do this in `main()` to set the style for all death tests in the binary,
@@ -615,7 +592,7 @@ TEST(MyDeathTest, TestTwo) {
The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If
it leaves the current function via a `return` statement or by throwing an
exception, the death test is considered to have failed. Some GoogleTest macros
exception, the death test is considered to have failed. Some googletest macros
may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid
them in `statement`.
@@ -749,7 +726,7 @@ TEST(FooTest, Bar) {
}
```
To alleviate this, GoogleTest provides three different solutions. You could use
To alleviate this, googletest provides three different solutions. You could use
either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
`HasFatalFailure()` function. They are described in the following two
subsections.
@@ -783,7 +760,7 @@ in it, the test will continue after the subroutine returns. This may not be what
you want.
Often people want fatal failures to propagate like exceptions. For that
GoogleTest offers the following macros:
googletest offers the following macros:
Fatal assertion | Nonfatal assertion | Verifies
------------------------------------- | ------------------------------------- | --------
@@ -875,7 +852,7 @@ will output XML like this:
> needs to be prefixed with `::testing::Test::` if used outside of the
> `TEST` body and the test fixture class.
> * *`key`* must be a valid XML attribute name, and cannot conflict with the
> ones already used by GoogleTest (`name`, `status`, `time`, `classname`,
> ones already used by googletest (`name`, `status`, `time`, `classname`,
> `type_param`, and `value_param`).
> * Calling `RecordProperty()` outside of the lifespan of a test is allowed.
> If it's called outside of a test but between a test suite's
@@ -886,13 +863,13 @@ will output XML like this:
## Sharing Resources Between Tests in the Same Test Suite
GoogleTest creates a new test fixture object for each test in order to make
googletest creates a new test fixture object for each test in order to make
tests independent and easier to debug. However, sometimes tests use resources
that are expensive to set up, making the one-copy-per-test model prohibitively
expensive.
If the tests don't change the resource, there's no harm in their sharing a
single resource copy. So, in addition to per-test set-up/tear-down, GoogleTest
single resource copy. So, in addition to per-test set-up/tear-down, googletest
also supports per-test-suite set-up/tear-down. To use it:
1. In your test fixture class (say `FooTest` ), declare as `static` some member
@@ -904,7 +881,7 @@ also supports per-test-suite set-up/tear-down. To use it:
`u`!) to set up the shared resources and a `static void TearDownTestSuite()`
function to tear them down.
That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the
That's it! googletest automatically calls `SetUpTestSuite()` before running the
*first test* in the `FooTest` test suite (i.e. before creating the first
`FooTest` object), and calls `TearDownTestSuite()` after running the *last test*
in it (i.e. after deleting the last `FooTest` object). In between, the tests can
@@ -919,8 +896,7 @@ Note that `SetUpTestSuite()` may be called multiple times for a test fixture
class that has derived classes, so you should not expect code in the function
body to be run only once. Also, derived classes still have access to shared
resources defined as static members, so careful consideration is needed when
managing shared resources to avoid memory leaks if shared resources are not
properly cleaned up in `TearDownTestSuite()`.
managing shared resources to avoid memory leaks.
Here's an example of per-test-suite set-up and tear-down:
@@ -931,15 +907,10 @@ class FooTest : public testing::Test {
// Called before the first test in this test suite.
// Can be omitted if not needed.
static void SetUpTestSuite() {
shared_resource_ = new ...;
// If `shared_resource_` is **not deleted** in `TearDownTestSuite()`,
// reallocation should be prevented because `SetUpTestSuite()` may be called
// in subclasses of FooTest and lead to memory leak.
//
// if (shared_resource_ == nullptr) {
// shared_resource_ = new ...;
// }
// Avoid reallocating static objects if called in subclasses of FooTest.
if (shared_resource_ == nullptr) {
shared_resource_ = new ...;
}
}
// Per-test-suite tear-down.
@@ -997,7 +968,7 @@ class Environment : public ::testing::Environment {
};
```
Then, you register an instance of your environment class with GoogleTest by
Then, you register an instance of your environment class with googletest by
calling the `::testing::AddGlobalTestEnvironment()` function:
```c++
@@ -1014,7 +985,7 @@ It's OK to register multiple environment objects. In this suite, their `SetUp()`
will be called in the order they are registered, and their `TearDown()` will be
called in the reverse order.
Note that GoogleTest takes ownership of the registered environment objects.
Note that googletest takes ownership of the registered environment objects.
Therefore **do not delete them** by yourself.
You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called,
@@ -1066,7 +1037,7 @@ they must be declared **public** rather than **protected** in order to use
```c++
class FooTest :
public testing::TestWithParam<absl::string_view> {
public testing::TestWithParam<const char*> {
// You can implement all the usual fixture class members here.
// To access the test parameter, call GetParam() from class
// TestWithParam<T>.
@@ -1077,7 +1048,7 @@ class BaseTest : public testing::Test {
...
};
class BarTest : public BaseTest,
public testing::WithParamInterface<absl::string_view> {
public testing::WithParamInterface<const char*> {
...
};
```
@@ -1124,11 +1095,6 @@ instantiation of the test suite. The next argument is the name of the test
pattern, and the last is the
[parameter generator](reference/testing.md#param-generators).
The parameter generator expression is not evaluated until GoogleTest is
initialized (via `InitGoogleTest()`). Any prior initialization done in the
`main` function will be accessible from the parameter generator, for example,
the results of flag parsing.
You can instantiate a test pattern more than once, so to distinguish different
instances of the pattern, the instantiation name is added as a prefix to the
actual test suite name. Remember to pick unique prefixes for different
@@ -1148,8 +1114,8 @@ with parameter values `"cat"` and `"dog"` using the
[`ValuesIn`](reference/testing.md#param-generators) parameter generator:
```c++
constexpr absl::string_view kPets[] = {"cat", "dog"};
INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets));
const char* pets[] = {"cat", "dog"};
INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets));
```
The tests from the instantiation above will have these names:
@@ -1176,8 +1142,8 @@ GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);
You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples.
[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example"
[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
[sample7_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample7_unittest.cc "Parameterized Test example"
[sample8_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
### Creating Value-Parameterized Abstract Tests
@@ -1328,7 +1294,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... }
You can see [sample6_unittest.cc] for a complete example.
[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example"
[sample6_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample6_unittest.cc "Typed Test example"
## Type-Parameterized Tests
@@ -1524,12 +1490,12 @@ To test them, we use the following special techniques:
## "Catching" Failures
If you are building a testing utility on top of GoogleTest, you'll want to test
your utility. What framework would you use to test it? GoogleTest, of course.
If you are building a testing utility on top of googletest, you'll want to test
your utility. What framework would you use to test it? googletest, of course.
The challenge is to verify that your testing utility reports failures correctly.
In frameworks that report a failure by throwing an exception, you could catch
the exception and assert on it. But GoogleTest doesn't use exceptions, so how do
the exception and assert on it. But googletest doesn't use exceptions, so how do
we test that a piece of code generates an expected failure?
`"gtest/gtest-spi.h"` contains some constructs to do this.
@@ -1672,9 +1638,9 @@ particular, you cannot find the test suite name in `SetUpTestSuite()`,
`TearDownTestSuite()` (where you know the test suite name implicitly), or
functions called from them.
## Extending GoogleTest by Handling Test Events
## Extending googletest by Handling Test Events
GoogleTest provides an **event listener API** to let you receive notifications
googletest provides an **event listener API** to let you receive notifications
about the progress of a test program and test failures. The events you can
listen to include the start and end of the test program, a test suite, or a test
method, among others. You may use this API to augment or replace the standard
@@ -1735,7 +1701,7 @@ Here's an example:
### Using Event Listeners
To use the event listener you have defined, add an instance of it to the
GoogleTest event listener list (represented by class
googletest event listener list (represented by class
[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s"
at the end of the name) in your `main()` function, before calling
`RUN_ALL_TESTS()`:
@@ -1746,7 +1712,7 @@ int main(int argc, char** argv) {
// Gets hold of the event listener list.
testing::TestEventListeners& listeners =
testing::UnitTest::GetInstance()->listeners();
// Adds a listener to the end. GoogleTest takes the ownership.
// Adds a listener to the end. googletest takes the ownership.
listeners.Append(new MinimalistPrinter);
return RUN_ALL_TESTS();
}
@@ -1767,7 +1733,7 @@ You can do so by adding one line:
Now, sit back and enjoy a completely different output from your tests. For more
details, see [sample9_unittest.cc].
[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example"
[sample9_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample9_unittest.cc "Event listener example"
You may append more than one listener to the list. When an `On*Start()` or
`OnTestPartResult()` event is fired, the listeners will receive it in the order
@@ -1794,11 +1760,11 @@ by the former.
See [sample10_unittest.cc] for an example of a failure-raising listener.
[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
[sample10_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
## Running Test Programs: Advanced Options
GoogleTest test programs are ordinary executables. Once built, you can run them
googletest test programs are ordinary executables. Once built, you can run them
directly and affect their behavior via the following environment variables
and/or command line flags. For the flags to work, your programs must call
`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
@@ -1831,10 +1797,10 @@ corresponding environment variable for this flag.
#### Running a Subset of the Tests
By default, a GoogleTest program runs all tests the user has defined. Sometimes,
By default, a googletest program runs all tests the user has defined. Sometimes,
you want to run only a subset of the tests (e.g. for debugging or quickly
verifying a change). If you set the `GTEST_FILTER` environment variable or the
`--gtest_filter` flag to a filter string, GoogleTest will only run the tests
`--gtest_filter` flag to a filter string, googletest will only run the tests
whose full names (in the form of `TestSuiteName.TestName`) match the filter.
The format of a filter is a '`:`'-separated list of wildcard patterns (called
@@ -1865,7 +1831,7 @@ For example:
#### Stop test execution upon first failure
By default, a GoogleTest program runs all tests the user has defined. In some
By default, a googletest program runs all tests the user has defined. In some
cases (e.g. iterative test development & execution) it may be desirable stop
test execution upon first failure (trading improved latency for completeness).
If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,
@@ -1882,7 +1848,7 @@ If you need to disable all tests in a test suite, you can either add `DISABLED_`
to the front of the name of each test, or alternatively add it to the front of
the test suite name.
For example, the following tests won't be run by GoogleTest, even though they
For example, the following tests won't be run by googletest, even though they
will still be compiled:
```c++
@@ -1897,7 +1863,7 @@ TEST_F(DISABLED_BarTest, DoesXyz) { ... }
{: .callout .note}
NOTE: This feature should only be used for temporary pain-relief. You still have
to fix the disabled tests at a later date. As a reminder, GoogleTest will print
to fix the disabled tests at a later date. As a reminder, googletest will print
a banner warning you if a test program contains any disabled tests.
{: .callout .tip}
@@ -1942,12 +1908,8 @@ Repeat the tests whose name matches the filter 1000 times.
If your test program contains
[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be
repeated in each iteration as well, as the flakiness may be in it. To avoid
repeating global set-up/tear-down, specify
`--gtest_recreate_environments_when_repeating=false`{.nowrap}.
You can also specify the repeat count by setting the `GTEST_REPEAT` environment
variable.
repeated in each iteration as well, as the flakiness may be in it. You can also
specify the repeat count by setting the `GTEST_REPEAT` environment variable.
### Shuffling the Tests
@@ -1955,16 +1917,16 @@ You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
environment variable to `1`) to run the tests in a program in a random order.
This helps to reveal bad dependencies between tests.
By default, GoogleTest uses a random seed calculated from the current time.
By default, googletest uses a random seed calculated from the current time.
Therefore you'll get a different order every time. The console output includes
the random seed value, such that you can reproduce an order-related test failure
later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED`
flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an
integer in the range [0, 99999]. The seed value 0 is special: it tells
GoogleTest to do the default behavior of calculating the seed from the current
googletest to do the default behavior of calculating the seed from the current
time.
If you combine this with `--gtest_repeat=N`, GoogleTest will pick a different
If you combine this with `--gtest_repeat=N`, googletest will pick a different
random seed and re-shuffle the tests in each iteration.
### Distributing Test Functions to Multiple Machines
@@ -2023,7 +1985,7 @@ shards, but here's one possible scenario:
#### Colored Terminal Output
GoogleTest can use colors in its terminal output to make it easier to spot the
googletest can use colors in its terminal output to make it easier to spot the
important information:
<pre>...
@@ -2048,25 +2010,25 @@ important information:
You can set the `GTEST_COLOR` environment variable or the `--gtest_color`
command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
disable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest
disable colors, or let googletest decide. When the value is `auto`, googletest
will use colors if and only if the output goes to a terminal and (on non-Windows
platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.
#### Suppressing test passes
By default, GoogleTest prints 1 line of output for each test, indicating if it
By default, googletest prints 1 line of output for each test, indicating if it
passed or failed. To show only test failures, run the test program with
`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.
#### Suppressing the Elapsed Time
By default, GoogleTest prints the time it takes to run each test. To disable
By default, googletest prints the time it takes to run each test. To disable
that, run the test program with the `--gtest_print_time=0` command line flag, or
set the GTEST_PRINT_TIME environment variable to `0`.
#### Suppressing UTF-8 Text Output
In case of assertion failures, GoogleTest prints expected and actual values of
In case of assertion failures, googletest prints expected and actual values of
type `string` both as hex-encoded strings as well as in readable UTF-8 text if
they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8
text because, for example, you don't have an UTF-8 compatible output medium, run
@@ -2075,7 +2037,7 @@ environment variable to `0`.
#### Generating an XML Report
GoogleTest can emit a detailed XML report to a file in addition to its normal
googletest can emit a detailed XML report to a file in addition to its normal
textual output. The report contains the duration of each test, and thus can help
you identify slow tests.
@@ -2086,15 +2048,15 @@ in which case the output can be found in the `test_detail.xml` file in the
current directory.
If you specify a directory (for example, `"xml:output/directory/"` on Linux or
`"xml:output\directory\"` on Windows), GoogleTest will create the XML file in
`"xml:output\directory\"` on Windows), googletest will create the XML file in
that directory, named after the test executable (e.g. `foo_test.xml` for test
program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
over from a previous run), GoogleTest will pick a different name (e.g.
over from a previous run), googletest will pick a different name (e.g.
`foo_test_1.xml`) to avoid overwriting it.
The report is based on the `junitreport` Ant task. Since that format was
originally intended for Java, a little interpretation is required to make it
apply to GoogleTest tests, as shown here:
apply to googletest tests, as shown here:
```xml
<testsuites name="AllTests" ...>
@@ -2109,8 +2071,8 @@ apply to GoogleTest tests, as shown here:
```
* The root `<testsuites>` element corresponds to the entire test program.
* `<testsuite>` elements correspond to GoogleTest test suites.
* `<testcase>` elements correspond to GoogleTest test functions.
* `<testsuite>` elements correspond to googletest test suites.
* `<testcase>` elements correspond to googletest test functions.
For instance, the following program
@@ -2143,7 +2105,7 @@ could generate this report:
Things to note:
* The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how
many test functions the GoogleTest program or test suite contains, while the
many test functions the googletest program or test suite contains, while the
`failures` attribute tells how many of them failed.
* The `time` attribute expresses the duration of the test, test suite, or
@@ -2155,12 +2117,12 @@ Things to note:
* The `file` and `line` attributes record the source file location, where the
test was defined.
* Each `<failure>` element corresponds to a single failed GoogleTest
* Each `<failure>` element corresponds to a single failed googletest
assertion.
#### Generating a JSON Report
GoogleTest can also emit a JSON report as an alternative format to XML. To
googletest can also emit a JSON report as an alternative format to XML. To
generate the JSON report, set the `GTEST_OUTPUT` environment variable or the
`--gtest_output` flag to the string `"json:path_to_output_file"`, which will
create the file at the given location. You can also just use the string
@@ -2385,7 +2347,7 @@ variable has been set.
When running test programs under a debugger, it's very convenient if the
debugger can catch an assertion failure and automatically drop into interactive
mode. GoogleTest's *break-on-failure* mode supports this behavior.
mode. googletest's *break-on-failure* mode supports this behavior.
To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
other than `0`. Alternatively, you can use the `--gtest_break_on_failure`
@@ -2393,9 +2355,9 @@ command line flag.
#### Disabling Catching Test-Thrown Exceptions
GoogleTest can be used either with or without exceptions enabled. If a test
googletest can be used either with or without exceptions enabled. If a test
throws a C++ exception or (on Windows) a structured exception (SEH), by default
GoogleTest catches it, reports it as a test failure, and continues with the next
googletest catches it, reports it as a test failure, and continues with the next
test method. This maximizes the coverage of a test run. Also, on Windows an
uncaught exception will cause a pop-up window, so catching the exceptions allows
you to run the tests automatically.
@@ -2433,4 +2395,4 @@ void __tsan_on_report() {
```
After compiling your project with one of the sanitizers enabled, if a particular
test triggers a sanitizer error, GoogleTest will report that it failed.
test triggers a sanitizer error, googletest will report that it failed.
+1 -1
View File
@@ -267,7 +267,7 @@ If necessary, you can continue to derive test fixtures from a derived fixture.
GoogleTest has no limit on how deep the hierarchy can be.
For a complete example using derived test fixtures, see
[sample5_unittest.cc](https://github.com/google/googletest/blob/main/googletest/samples/sample5_unittest.cc).
[sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc).
## My compiler complains "void value not ignored as it ought to be." What does this mean?
+2 -2
View File
@@ -20,7 +20,7 @@ class Foo {
(note that `~Foo()` **must** be virtual) we can define its mock as
```cpp
#include <gmock/gmock.h>
#include "gmock/gmock.h"
class MockFoo : public Foo {
public:
@@ -140,7 +140,7 @@ To customize the default action for functions with return type `T`, use
// Sets the default action for return type std::unique_ptr<Buzz> to
// creating a new Buzz every time.
DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
[] { return std::make_unique<Buzz>(AccessLevel::kInternal); });
[] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
// When this fires, the default action of MakeBuzz() will run, which
// will return a new Buzz object.
+56 -58
View File
@@ -285,10 +285,6 @@ If you are concerned about the performance overhead incurred by virtual
functions, and profiling confirms your concern, you can combine this with the
recipe for [mocking non-virtual methods](#MockingNonVirtualMethods).
Alternatively, instead of introducing a new interface, you can rewrite your code
to accept a std::function instead of the free function, and then use
[MockFunction](#MockFunction) to mock the std::function.
### Old-Style `MOCK_METHODn` Macros
Before the generic `MOCK_METHOD` macro
@@ -697,9 +693,9 @@ TEST(AbcTest, Xyz) {
EXPECT_CALL(foo, DoThat(_, _));
int n = 0;
EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked.
EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked.
foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked.
EXPECT_EQ(n, 2);
EXPECT_EQ(2, n);
}
```
@@ -908,7 +904,7 @@ using ::testing::Contains;
using ::testing::Property;
inline constexpr auto HasFoo = [](const auto& f) {
return Property("foo", &MyClass::foo, Contains(f));
return Property(&MyClass::foo, Contains(f));
};
...
EXPECT_THAT(x, HasFoo("blah"));
@@ -1129,11 +1125,11 @@ using STL's `<functional>` header is just painful). For example, here's a
predicate that's satisfied by any number that is >= 0, <= 100, and != 50:
```cpp
using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
using ::testing::Matches;
using ::testing::Ne;
using testing::AllOf;
using testing::Ge;
using testing::Le;
using testing::Matches;
using testing::Ne;
...
Matches(AllOf(Ge(0), Le(100), Ne(50)))
```
@@ -1162,7 +1158,7 @@ int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
```
Note that the predicate function / functor doesn't have to return `bool`. It
works as long as the return value can be used as the condition in the statement
works as long as the return value can be used as the condition in in statement
`if (condition) ...`.
### Matching Arguments that Are Not Copyable
@@ -1349,7 +1345,7 @@ class BarPlusBazEqMatcher {
...
Foo foo;
EXPECT_THAT(foo, BarPlusBazEq(5))...;
EXPECT_CALL(foo, BarPlusBazEq(5))...;
```
### Matching Containers
@@ -1428,12 +1424,11 @@ Use `Pair` when comparing maps or other associative containers.
{% raw %}
```cpp
using ::testing::UnorderedElementsAre;
using ::testing::Pair;
using testing::ElementsAre;
using testing::Pair;
...
absl::flat_hash_map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
EXPECT_THAT(m, UnorderedElementsAre(
Pair("a", 1), Pair("b", 2), Pair("c", 3)));
std::map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
EXPECT_THAT(m, ElementsAre(Pair("a", 1), Pair("b", 2), Pair("c", 3)));
```
{% endraw %}
@@ -1450,8 +1445,8 @@ using ::testing::Pair;
* If the container is passed by pointer instead of by reference, just write
`Pointee(ElementsAre*(...))`.
* The order of elements *matters* for `ElementsAre*()`. If you are using it
with containers whose element order are undefined (such as a
`std::unordered_map`) you should use `UnorderedElementsAre`.
with containers whose element order are undefined (e.g. `hash_map`) you
should use `WhenSorted` around `ElementsAre`.
### Sharing Matchers
@@ -1861,7 +1856,7 @@ error. So, what shall you do?
Though you may be tempted, DO NOT use `std::ref()`:
```cpp
using ::testing::Return;
using testing::Return;
class MockFoo : public Foo {
public:
@@ -1873,7 +1868,7 @@ class MockFoo : public Foo {
EXPECT_CALL(foo, GetValue())
.WillRepeatedly(Return(std::ref(x))); // Wrong!
x = 42;
EXPECT_EQ(foo.GetValue(), 42);
EXPECT_EQ(42, foo.GetValue());
```
Unfortunately, it doesn't work here. The above code will fail with error:
@@ -1895,20 +1890,20 @@ the expectation is set, and `Return(std::ref(x))` will always return 0.
returns the value pointed to by `pointer` at the time the action is *executed*:
```cpp
using ::testing::ReturnPointee;
using testing::ReturnPointee;
...
int x = 0;
MockFoo foo;
EXPECT_CALL(foo, GetValue())
.WillRepeatedly(ReturnPointee(&x)); // Note the & here.
x = 42;
EXPECT_EQ(foo.GetValue(), 42); // This will succeed now.
EXPECT_EQ(42, foo.GetValue()); // This will succeed now.
```
### Combining Actions
Want to do more than one thing when a function is called? That's fine. `DoAll()`
allows you to do a sequence of actions every time. Only the return value of the
allow you to do sequence of actions every time. Only the return value of the
last action in the sequence will be used.
```cpp
@@ -2264,7 +2259,7 @@ TEST_F(FooTest, Test) {
EXPECT_CALL(foo, DoThis(2))
.WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5)));
EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2).
EXPECT_EQ('+', foo.DoThis(2)); // Invokes SignOfSum(5, 2).
}
```
@@ -2640,8 +2635,8 @@ action will exhibit different behaviors. Example:
.WillRepeatedly(IncrementCounter(0));
foo.DoThis(); // Returns 1.
foo.DoThis(); // Returns 2.
foo.DoThat(); // Returns 1 - DoThat() uses a different
// counter than DoThis()'s.
foo.DoThat(); // Returns 1 - Blah() uses a different
// counter than Bar()'s.
```
versus
@@ -2771,33 +2766,36 @@ returns a null `unique_ptr`, that’s what you’ll get if you don’t specify a
action:
```cpp
using ::testing::IsNull;
...
// Use the default action.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));
// Triggers the previous EXPECT_CALL.
EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull());
EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello"));
```
If you are not happy with the default action, you can tweak it as usual; see
[Setting Default Actions](#OnCall).
If you just need to return a move-only value, you can use it in combination with
`WillOnce`. For example:
If you just need to return a pre-defined move-only value, you can use the
`Return(ByMove(...))` action:
```cpp
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"))
.WillOnce(Return(std::make_unique<Buzz>(AccessLevel::kInternal)));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello"));
// When this fires, the unique_ptr<> specified by ByMove(...) will
// be returned.
EXPECT_CALL(mock_buzzer_, MakeBuzz("world"))
.WillOnce(Return(ByMove(MakeUnique<Buzz>(AccessLevel::kInternal))));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world"));
```
Quiz time! What do you think will happen if a `Return` action is performed more
than once (e.g. you write `... .WillRepeatedly(Return(std::move(...)));`)? Come
think of it, after the first time the action runs, the source value will be
consumed (since it’s a move-only value), so the next time around, there’s no
value to move from -- you’ll get a run-time error that `Return(std::move(...))`
can only be run once.
Note that `ByMove()` is essential here - if you drop it, the code won’t compile.
Quiz time! What do you think will happen if a `Return(ByMove(...))` action is
performed more than once (e.g. you write `...
.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time
the action runs, the source value will be consumed (since it’s a move-only
value), so the next time around, there’s no value to move from -- you’ll get a
run-time error that `Return(ByMove(...))` can only be run once.
If you need your mock method to do more than just moving a pre-defined value,
remember that you can always use a lambda or a callable object, which can do
@@ -2806,7 +2804,7 @@ pretty much anything you want:
```cpp
EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
.WillRepeatedly([](StringPiece text) {
return std::make_unique<Buzz>(AccessLevel::kInternal);
return MakeUnique<Buzz>(AccessLevel::kInternal);
});
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
@@ -2814,7 +2812,7 @@ pretty much anything you want:
```
Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created
and returned. You cannot do this with `Return(std::make_unique<...>(...))`.
and returned. You cannot do this with `Return(ByMove(...))`.
That covers returning move-only values; but how do we work with methods
accepting move-only arguments? The answer is that they work normally, although
@@ -2825,7 +2823,7 @@ can always use `Return`, or a [lambda or functor](#FunctionsAsActions):
using ::testing::Unused;
EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true));
EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal)),
EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal)),
0);
EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce(
@@ -2869,7 +2867,7 @@ method:
// When one calls ShareBuzz() on the MockBuzzer like this, the call is
// forwarded to DoShareBuzz(), which is mocked. Therefore this statement
// will trigger the above EXPECT_CALL.
mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal), 0);
mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0);
```
### Making the Compilation Faster
@@ -3194,11 +3192,11 @@ You can unlock this power by running your test with the `--gmock_verbose=info`
flag. For example, given the test program:
```cpp
#include <gmock/gmock.h>
#include "gmock/gmock.h"
using ::testing::_;
using ::testing::HasSubstr;
using ::testing::Return;
using testing::_;
using testing::HasSubstr;
using testing::Return;
class MockFoo {
public:
@@ -3819,15 +3817,15 @@ If the built-in actions don't work for you, you can easily define your own one.
All you need is a call operator with a signature compatible with the mocked
function. So you can use a lambda:
```cpp
```
MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; });
EXPECT_EQ(mock.AsStdFunction()(2), 14);
EXPECT_EQ(14, mock.AsStdFunction()(2));
```
Or a struct with a call operator (even a templated one):
```cpp
```
struct MultiplyBy {
template <typename T>
T operator()(T arg) { return arg * multiplier; }
@@ -3842,16 +3840,16 @@ struct MultiplyBy {
It's also fine for the callable to take no arguments, ignoring the arguments
supplied to the mock function:
```cpp
```
MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([] { return 17; });
EXPECT_EQ(mock.AsStdFunction()(0), 17);
EXPECT_EQ(17, mock.AsStdFunction()(0));
```
When used with `WillOnce`, the callable can assume it will be called at most
once and is allowed to be a move-only type:
```cpp
```
// An action that contains move-only types and has an &&-qualified operator,
// demanding in the type system that it be called at most once. This can be
// used with WillOnce, but the compiler will reject it if handed to
@@ -4295,7 +4293,7 @@ particular type than to dump the bytes.
### Mock std::function {#MockFunction}
`std::function` is a general function type introduced in C++11. It is a
preferred way of passing callbacks to new interfaces. Functions are copyable,
preferred way of passing callbacks to new interfaces. Functions are copiable,
and are not usually passed around by pointer, which makes them tricky to mock.
But fear not - `MockFunction` can help you with that.
+3 -3
View File
@@ -164,7 +164,7 @@ follow:
After the process, you should have something like:
```cpp
#include <gmock/gmock.h> // Brings in gMock.
#include "gmock/gmock.h" // Brings in gMock.
class MockTurtle : public Turtle {
public:
@@ -224,8 +224,8 @@ Here's an example:
```cpp
#include "path/to/mock-turtle.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::AtLeast; // #1
+9 -5
View File
@@ -19,15 +19,19 @@ examples here we assume you want to compile the sample
Using `pkg-config` in CMake is fairly easy:
```cmake
cmake_minimum_required(VERSION 3.0)
cmake_policy(SET CMP0048 NEW)
project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX)
find_package(PkgConfig)
pkg_search_module(GTEST REQUIRED gtest_main)
add_executable(testapp)
target_sources(testapp PRIVATE samples/sample3_unittest.cc)
target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS})
target_compile_options(testapp PRIVATE ${GTEST_CFLAGS})
add_executable(testapp samples/sample3_unittest.cc)
target_link_libraries(testapp ${GTEST_LDFLAGS})
target_compile_options(testapp PUBLIC ${GTEST_CFLAGS})
enable_testing()
include(CTest)
add_test(first_and_only_test testapp)
```
+33 -6
View File
@@ -1,8 +1,35 @@
# Supported Platforms
GoogleTest follows Google's
[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See
[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
for a list of currently supported versions compilers, platforms, and build
tools.
GoogleTest requires a codebase and compiler compliant with the C++11 standard or
newer.
The GoogleTest code is officially supported on the following platforms.
Operating systems or tools not listed below are community-supported. For
community-supported platforms, patches that do not complicate the code may be
considered.
If you notice any problems on your platform, please file an issue on the
[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
Pull requests containing fixes are welcome!
### Operating systems
* Linux
* macOS
* Windows
### Compilers
* gcc 5.0+
* clang 5.0+
* MSVC 2015+
**macOS users:** Xcode 9.3+ provides clang 5.0+.
### Build systems
* [Bazel](https://bazel.build/)
* [CMake](https://cmake.org/)
Bazel is the build system used by the team internally and in tests. CMake is
supported on a best-effort basis and by the community.
+48 -49
View File
@@ -1,74 +1,74 @@
# GoogleTest Primer
# Googletest Primer
## Introduction: Why GoogleTest?
## Introduction: Why googletest?
*GoogleTest* helps you write better C++ tests.
*googletest* helps you write better C++ tests.
GoogleTest is a testing framework developed by the Testing Technology team with
googletest is a testing framework developed by the Testing Technology team with
Google's specific requirements and constraints in mind. Whether you work on
Linux, Windows, or a Mac, if you write C++ code, GoogleTest can help you. And it
Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it
supports *any* kind of tests, not just unit tests.
So what makes a good test, and how does GoogleTest fit in? We believe:
So what makes a good test, and how does googletest fit in? We believe:
1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
that succeeds or fails as a result of other tests. GoogleTest isolates the
that succeeds or fails as a result of other tests. googletest isolates the
tests by running each of them on a different object. When a test fails,
GoogleTest allows you to run it in isolation for quick debugging.
googletest allows you to run it in isolation for quick debugging.
2. Tests should be well *organized* and reflect the structure of the tested
code. GoogleTest groups related tests into test suites that can share data
code. googletest groups related tests into test suites that can share data
and subroutines. This common pattern is easy to recognize and makes tests
easy to maintain. Such consistency is especially helpful when people switch
projects and start to work on a new code base.
3. Tests should be *portable* and *reusable*. Google has a lot of code that is
platform-neutral; its tests should also be platform-neutral. GoogleTest
platform-neutral; its tests should also be platform-neutral. googletest
works on different OSes, with different compilers, with or without
exceptions, so GoogleTest tests can work with a variety of configurations.
exceptions, so googletest tests can work with a variety of configurations.
4. When tests fail, they should provide as much *information* about the problem
as possible. GoogleTest doesn't stop at the first test failure. Instead, it
as possible. googletest doesn't stop at the first test failure. Instead, it
only stops the current test and continues with the next. You can also set up
tests that report non-fatal failures after which the current test continues.
Thus, you can detect and fix multiple bugs in a single run-edit-compile
cycle.
5. The testing framework should liberate test writers from housekeeping chores
and let them focus on the test *content*. GoogleTest automatically keeps
and let them focus on the test *content*. googletest automatically keeps
track of all tests defined, and doesn't require the user to enumerate them
in order to run them.
6. Tests should be *fast*. With GoogleTest, you can reuse shared resources
6. Tests should be *fast*. With googletest, you can reuse shared resources
across tests and pay for the set-up/tear-down only once, without making
tests depend on each other.
Since GoogleTest is based on the popular xUnit architecture, you'll feel right
Since googletest is based on the popular xUnit architecture, you'll feel right
at home if you've used JUnit or PyUnit before. If not, it will take you about 10
minutes to learn the basics and get started. So let's go!
## Beware of the Nomenclature
## Beware of the nomenclature
{: .callout .note}
*Note:* There might be some confusion arising from different definitions of the
terms *Test*, *Test Case* and *Test Suite*, so beware of misunderstanding these.
_Note:_ There might be some confusion arising from different definitions of the
terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
Historically, GoogleTest started to use the term *Test Case* for grouping
Historically, googletest started to use the term _Test Case_ for grouping
related tests, whereas current publications, including International Software
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
various textbooks on software quality, use the term
*[Test Suite][istqb test suite]* for this.
_[Test Suite][istqb test suite]_ for this.
The related term *Test*, as it is used in GoogleTest, corresponds to the term
*[Test Case][istqb test case]* of ISTQB and others.
The related term _Test_, as it is used in googletest, corresponds to the term
_[Test Case][istqb test case]_ of ISTQB and others.
The term *Test* is commonly of broad enough sense, including ISTQB's definition
of *Test Case*, so it's not much of a problem here. But the term *Test Case* as
The term _Test_ is commonly of broad enough sense, including ISTQB's definition
of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as
was used in Google Test is of contradictory sense and thus confusing.
GoogleTest recently started replacing the term *Test Case* with *Test Suite*.
googletest recently started replacing the term _Test Case_ with _Test Suite_.
The preferred API is *TestSuite*. The older TestCase API is being slowly
deprecated and refactored away.
So please be aware of the different definitions of the terms:
Meaning | GoogleTest Term | [ISTQB](http://www.istqb.org/) Term
Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
:----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
@@ -78,7 +78,7 @@ Exercise a particular program path with specific input values and verify the res
## Basic Concepts
When using GoogleTest, you start by writing *assertions*, which are statements
When using googletest, you start by writing *assertions*, which are statements
that check whether a condition is true. An assertion's result can be *success*,
*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
current function; otherwise the program continues normally.
@@ -98,11 +98,11 @@ assertion level and building up to tests and test suites.
## Assertions
GoogleTest assertions are macros that resemble function calls. You test a class
googletest assertions are macros that resemble function calls. You test a class
or function by making assertions about its behavior. When an assertion fails,
GoogleTest prints the assertion's source file and line number location, along
googletest prints the assertion's source file and line number location, along
with a failure message. You may also supply a custom failure message which will
be appended to GoogleTest's message.
be appended to googletest's message.
The assertions come in pairs that test the same thing but have different effects
on the current function. `ASSERT_*` versions generate fatal failures when they
@@ -149,7 +149,7 @@ To create a test:
1. Use the `TEST()` macro to define and name a test function. These are
ordinary C++ functions that don't return a value.
2. In this function, along with any valid C++ statements you want to include,
use the various GoogleTest assertions to check values.
use the various googletest assertions to check values.
3. The test's result is determined by the assertions; if any assertion in the
test fails (either fatally or non-fatally), or if the test crashes, the
entire test fails. Otherwise, it succeeds.
@@ -190,7 +190,7 @@ TEST(FactorialTest, HandlesPositiveInput) {
}
```
GoogleTest groups the test results by test suites, so logically related tests
googletest groups the test results by test suites, so logically related tests
should be in the same test suite; in other words, the first argument to their
`TEST()` should be the same. In the above example, we have two tests,
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
@@ -227,14 +227,14 @@ When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
access objects and subroutines in the test fixture:
```c++
TEST_F(TestFixtureClassName, TestName) {
TEST_F(TestFixtureName, TestName) {
... test body ...
}
```
Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test
fixture class. (`_F` stands for "Fixture"). No test suite name is specified for
this macro.
Like `TEST()`, the first argument is the test suite name, but for `TEST_F()`
this must be the name of the test fixture class. You've probably guessed: `_F`
is for fixture.
Unfortunately, the C++ macro system does not allow us to create a single macro
that can handle both types of tests. Using the wrong macro causes a compiler
@@ -244,12 +244,12 @@ Also, you must first define a test fixture class before using it in a
`TEST_F()`, or you'll get the compiler error "`virtual outside class
declaration`".
For each test defined with `TEST_F()`, GoogleTest will create a *fresh* test
For each test defined with `TEST_F()`, googletest will create a *fresh* test
fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean
up by calling `TearDown()`, and then delete the test fixture. Note that
different tests in the same test suite have different test fixture objects, and
GoogleTest always deletes a test fixture before it creates the next one.
GoogleTest does **not** reuse the same test fixture for multiple tests. Any
googletest always deletes a test fixture before it creates the next one.
googletest does **not** reuse the same test fixture for multiple tests. Any
changes one test makes to the fixture do not affect other tests.
As an example, let's write tests for a FIFO queue class named `Queue`, which has
@@ -274,7 +274,6 @@ First, define a fixture class. By convention, you should give it the name
class QueueTest : public ::testing::Test {
protected:
void SetUp() override {
// q0_ remains empty
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
@@ -325,7 +324,7 @@ would lead to a segfault when `n` is `NULL`.
When these tests run, the following happens:
1. GoogleTest constructs a `QueueTest` object (let's call it `t1`).
1. googletest constructs a `QueueTest` object (let's call it `t1`).
2. `t1.SetUp()` initializes `t1`.
3. The first test (`IsEmptyInitially`) runs on `t1`.
4. `t1.TearDown()` cleans up after the test finishes.
@@ -337,7 +336,7 @@ When these tests run, the following happens:
## Invoking the Tests
`TEST()` and `TEST_F()` implicitly register their tests with GoogleTest. So,
`TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
unlike with many other C++ testing frameworks, you don't have to re-list all
your defined tests in order to run them.
@@ -348,7 +347,7 @@ test suites, or even different source files.
When invoked, the `RUN_ALL_TESTS()` macro:
* Saves the state of all GoogleTest flags.
* Saves the state of all googletest flags.
* Creates a test fixture object for the first test.
@@ -360,7 +359,7 @@ When invoked, the `RUN_ALL_TESTS()` macro:
* Deletes the fixture.
* Restores the state of all GoogleTest flags.
* Restores the state of all googletest flags.
* Repeats the above steps for the next test, until all tests have run.
@@ -374,14 +373,14 @@ If a fatal failure happens the subsequent steps will be skipped.
> return the value of `RUN_ALL_TESTS()`.
>
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
> once conflicts with some advanced GoogleTest features (e.g., thread-safe
> once conflicts with some advanced googletest features (e.g., thread-safe
> [death tests](advanced.md#death-tests)) and thus is not supported.
**Availability**: Linux, Windows, Mac.
## Writing the main() Function
Most users should *not* need to write their own `main` function and instead link
Most users should _not_ need to write their own `main` function and instead link
with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry
point. See the end of this section for details. The remainder of this section
should only apply when you need to do something custom before the tests run that
@@ -395,7 +394,7 @@ You can start from this boilerplate:
```c++
#include "this/package/foo.h"
#include <gtest/gtest.h>
#include "gtest/gtest.h"
namespace my {
namespace project {
@@ -456,7 +455,7 @@ int main(int argc, char **argv) {
```
The `::testing::InitGoogleTest()` function parses the command line for
GoogleTest flags, and removes all recognized flags. This allows the user to
googletest flags, and removes all recognized flags. This allows the user to
control a test program's behavior via various flags, which we'll cover in the
[AdvancedGuide](advanced.md). You **must** call this function before calling
`RUN_ALL_TESTS()`, or the flags won't be properly initialized.
@@ -476,7 +475,7 @@ NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
* Google Test is designed to be thread-safe. The implementation is thread-safe
on systems where the `pthreads` library is available. It is currently
*unsafe* to use Google Test assertions from two threads concurrently on
_unsafe_ to use Google Test assertions from two threads concurrently on
other systems (e.g. Windows). In most tests this is not an issue as usually
the assertions are done in the main thread. If you want to help, you can
volunteer to implement the necessary synchronization primitives in
+10 -16
View File
@@ -9,7 +9,7 @@ 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++14.
* A compatible C++ compiler that supports at least C++11.
* [Bazel](https://bazel.build/), the preferred build system used by the
GoogleTest team.
@@ -17,10 +17,11 @@ See [Supported Platforms](platforms.md) for more information about platforms
compatible with GoogleTest.
If you don't already have Bazel installed, see the
[Bazel installation guide](https://bazel.build/install).
[Bazel installation guide](https://docs.bazel.build/versions/main/install.html).
{: .callout .note} Note: The terminal commands in this tutorial show a Unix
shell prompt, but the commands work on the Windows command line as well.
{: .callout .note}
Note: The terminal commands in this tutorial show a Unix shell prompt, but the
commands work on the Windows command line as well.
## Set up a Bazel workspace
@@ -50,16 +51,16 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "com_google_googletest",
urls = ["https://github.com/google/googletest/archive/5ab508a01f9eb089207ee87fd547d290da39d015.zip"],
strip_prefix = "googletest-5ab508a01f9eb089207ee87fd547d290da39d015",
urls = ["https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip"],
strip_prefix = "googletest-609281088cfefc76f9d0ce82e1ff6c30cc3591e5",
)
```
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
`609281088cfefc76f9d0ce82e1ff6c30cc3591e5` 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.
latest version.
Now you're ready to build C++ code that uses GoogleTest.
@@ -105,17 +106,10 @@ 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++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>my_workspace$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test</strong>
<strong>my_workspace$ bazel test --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:
+6 -7
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++14.
* A compatible C++ compiler that supports at least C++11.
* [CMake](https://cmake.org/) and a compatible build tool for building the
project.
* Compatible build tools include
@@ -52,14 +52,13 @@ 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++14
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# GoogleTest requires at least C++11
set(CMAKE_CXX_STANDARD 11)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
@@ -67,7 +66,7 @@ FetchContent_MakeAvailable(googletest)
```
The above configuration declares a dependency on GoogleTest which is downloaded
from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is
from GitHub. In the above example, `609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is
the Git commit hash of the GoogleTest version to use; we recommend updating the
hash often to point to the latest version.
@@ -109,7 +108,7 @@ add_executable(
)
target_link_libraries(
hello_test
GTest::gtest_main
gtest_main
)
include(GoogleTest)
+2 -2
View File
@@ -88,7 +88,7 @@ For example, the following code verifies that the string `value1` starts with
10:
```cpp
#include <gmock/gmock.h>
#include "gmock/gmock.h"
using ::testing::AllOf;
using ::testing::Gt;
@@ -515,7 +515,7 @@ Verifies that *`expression`* is a success `HRESULT`.
### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED}
`EXPECT_HRESULT_FAILED(`*`expression`*`)` \
`ASSERT_HRESULT_FAILED(`*`expression`*`)`
`EXPECT_HRESULT_FAILED(`*`expression`*`)`
Verifies that *`expression`* is a failure `HRESULT`.
+1 -13
View File
@@ -102,7 +102,7 @@ The `argument` can be either a C string or a C++ string object:
| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. |
| `StrEq(string)` | `argument` is equal to `string`. |
| `StrNe(string)` | `argument` is not equal to `string`. |
| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. The web-safe format from [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648#section-5) is supported. |
| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. |
`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
use the regular expression syntax defined
@@ -288,15 +288,3 @@ which must be a permanent callback.
return ExplainMatchResult(matcher, arg.nested().property(), result_listener);
}
```
5. You can use `DescribeMatcher<>` to describe another matcher. For example:
```cpp
MATCHER_P(XAndYThat, matcher,
"X that " + DescribeMatcher<int>(matcher, negation) +
(negation ? " or" : " and") + " Y that " +
DescribeMatcher<double>(matcher, negation)) {
return ExplainMatchResult(matcher, arg.x(), result_listener) &&
ExplainMatchResult(matcher, arg.y(), result_listener);
}
```
+35 -36
View File
@@ -109,7 +109,6 @@ 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)` | 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
@@ -122,8 +121,8 @@ custom function can be used for more control:
```cpp
INSTANTIATE_TEST_SUITE_P(
MyInstantiation, MyTestSuite,
testing::Values(...),
[](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
::testing::Values(...),
[](const ::testing::TestParamInfo<MyTestSuite::ParamType>& info) {
// Can use info.param here to generate the test suffix
std::string name = ...
return name;
@@ -148,7 +147,7 @@ type, for example:
```cpp
template <typename T>
class MyFixture : public testing::Test {
class MyFixture : public ::testing::Test {
public:
...
using List = std::list<T>;
@@ -324,7 +323,7 @@ Then the test code should look like:
```cpp
namespace my_namespace {
class MyClassTest : public testing::Test {
class MyClassTest : public ::testing::Test {
...
};
@@ -387,7 +386,7 @@ GoogleTest defines the following classes and types to help with writing tests.
### AssertionResult {#AssertionResult}
`testing::AssertionResult`
`::testing::AssertionResult`
A class for indicating whether an assertion was successful.
@@ -401,14 +400,14 @@ To create an instance of this class, use one of the factory functions
### AssertionException {#AssertionException}
`testing::AssertionException`
`::testing::AssertionException`
Exception which can be thrown from
[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult).
### EmptyTestEventListener {#EmptyTestEventListener}
`testing::EmptyTestEventListener`
`::testing::EmptyTestEventListener`
Provides an empty implementation of all methods in the
[`TestEventListener`](#TestEventListener) interface, such that a subclass only
@@ -416,7 +415,7 @@ needs to override the methods it cares about.
### Environment {#Environment}
`testing::Environment`
`::testing::Environment`
Represents a global test environment. See
[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down).
@@ -437,7 +436,7 @@ Override this to define how to tear down the environment.
### ScopedTrace {#ScopedTrace}
`testing::ScopedTrace`
`::testing::ScopedTrace`
An instance of this class causes a trace to be included in every test failure
message generated by code in the scope of the lifetime of the `ScopedTrace`
@@ -453,7 +452,7 @@ ScopedTrace(const char* file, int line, const T& message)
Example usage:
```cpp
testing::ScopedTrace trace("file.cc", 123, "message");
::testing::ScopedTrace trace("file.cc", 123, "message");
```
The resulting trace includes the given source file path and line number, and the
@@ -464,7 +463,7 @@ See also [`SCOPED_TRACE`](#SCOPED_TRACE).
### Test {#Test}
`testing::Test`
`::testing::Test`
The abstract class that all tests inherit from. `Test` is not copyable.
@@ -552,7 +551,7 @@ after running each individual test.
### TestWithParam {#TestWithParam}
`testing::TestWithParam<T>`
`::testing::TestWithParam<T>`
A convenience class which inherits from both [`Test`](#Test) and
[`WithParamInterface<T>`](#WithParamInterface).
@@ -672,7 +671,7 @@ during execution of `SetUpTestSuite` and `TearDownTestSuite`.
### TestInfo {#TestInfo}
`testing::TestInfo`
`::testing::TestInfo`
Stores information about a test.
@@ -751,7 +750,7 @@ Returns the result of the test. See [`TestResult`](#TestResult).
### TestParamInfo {#TestParamInfo}
`testing::TestParamInfo<T>`
`::testing::TestParamInfo<T>`
Describes a parameter to a value-parameterized test. The type `T` is the type of
the parameter.
@@ -761,7 +760,7 @@ and its integer index respectively.
### UnitTest {#UnitTest}
`testing::UnitTest`
`::testing::UnitTest`
This class contains information about the test program.
@@ -929,7 +928,7 @@ GoogleTest. See [`TestEventListeners`](#TestEventListeners).
### TestEventListener {#TestEventListener}
`testing::TestEventListener`
`::testing::TestEventListener`
The interface for tracing execution of tests. The methods below are listed in
the order the corresponding events are fired.
@@ -1027,7 +1026,7 @@ Fired after all test activities have ended.
### TestEventListeners {#TestEventListeners}
`testing::TestEventListeners`
`::testing::TestEventListeners`
Lets users add listeners to track events in GoogleTest.
@@ -1072,7 +1071,7 @@ the caller and makes this function return `NULL` the next time.
### TestPartResult {#TestPartResult}
`testing::TestPartResult`
`::testing::TestPartResult`
A copyable object representing the result of a test part (i.e. an assertion or
an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`).
@@ -1154,7 +1153,7 @@ Returns true if and only if the test part failed.
### TestProperty {#TestProperty}
`testing::TestProperty`
`::testing::TestProperty`
A copyable object representing a user-specified test property which can be
output as a key/value string pair.
@@ -1181,7 +1180,7 @@ Sets a new value, overriding the previous one.
### TestResult {#TestResult}
`testing::TestResult`
`::testing::TestResult`
Contains information about the result of a single test.
@@ -1262,20 +1261,20 @@ range, aborts the program.
### TimeInMillis {#TimeInMillis}
`testing::TimeInMillis`
`::testing::TimeInMillis`
An integer type representing time in milliseconds.
### Types {#Types}
`testing::Types<T...>`
`::testing::Types<T...>`
Represents a list of types for use in typed tests and type-parameterized tests.
The template argument `T...` can be any number of types, for example:
```
testing::Types<char, int, unsigned int>
::testing::Types<char, int, unsigned int>
```
See [Typed Tests](../advanced.md#typed-tests) and
@@ -1284,7 +1283,7 @@ information.
### WithParamInterface {#WithParamInterface}
`testing::WithParamInterface<T>`
`::testing::WithParamInterface<T>`
The pure interface class that all value-parameterized tests inherit from.
@@ -1310,9 +1309,9 @@ tests.
### InitGoogleTest {#InitGoogleTest}
`void testing::InitGoogleTest(int* argc, char** argv)` \
`void testing::InitGoogleTest(int* argc, wchar_t** argv)` \
`void testing::InitGoogleTest()`
`void ::testing::InitGoogleTest(int* argc, char** argv)` \
`void ::testing::InitGoogleTest(int* argc, wchar_t** argv)` \
`void ::testing::InitGoogleTest()`
Initializes GoogleTest. This must be called before calling
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line
@@ -1329,7 +1328,7 @@ platforms where there is no `argc`/`argv`.
### AddGlobalTestEnvironment {#AddGlobalTestEnvironment}
`Environment* testing::AddGlobalTestEnvironment(Environment* env)`
`Environment* ::testing::AddGlobalTestEnvironment(Environment* env)`
Adds a test environment to the test program. Must be called before
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See
@@ -1342,7 +1341,7 @@ See also [`Environment`](#Environment).
```cpp
template <typename Factory>
TestInfo* testing::RegisterTest(const char* test_suite_name, const char* test_name,
TestInfo* ::testing::RegisterTest(const char* test_suite_name, const char* test_name,
const char* type_param, const char* value_param,
const char* file, int line, Factory factory)
```
@@ -1381,27 +1380,27 @@ an all-caps name.
### AssertionSuccess {#AssertionSuccess}
`AssertionResult testing::AssertionSuccess()`
`AssertionResult ::testing::AssertionSuccess()`
Creates a successful assertion result. See
[`AssertionResult`](#AssertionResult).
### AssertionFailure {#AssertionFailure}
`AssertionResult testing::AssertionFailure()`
`AssertionResult ::testing::AssertionFailure()`
Creates a failed assertion result. Use the `<<` operator to store a failure
message:
```cpp
testing::AssertionFailure() << "My failure message";
::testing::AssertionFailure() << "My failure message";
```
See [`AssertionResult`](#AssertionResult).
### StaticAssertTypeEq {#StaticAssertTypeEq}
`testing::StaticAssertTypeEq<T1, T2>()`
`::testing::StaticAssertTypeEq<T1, T2>()`
Compile-time assertion for type equality. Compiles if and only if `T1` and `T2`
are the same type. The value it returns is irrelevant.
@@ -1410,7 +1409,7 @@ See [Type Assertions](../advanced.md#type-assertions) for more information.
### PrintToString {#PrintToString}
`std::string testing::PrintToString(x)`
`std::string ::testing::PrintToString(x)`
Prints any value `x` using GoogleTest's value printer.
@@ -1420,7 +1419,7 @@ for more information.
### PrintToStringParamName {#PrintToStringParamName}
`std::string testing::PrintToStringParamName(TestParamInfo<T>& info)`
`std::string ::testing::PrintToStringParamName(TestParamInfo<T>& info)`
A built-in parameterized test name generator which returns the result of
[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the
+1 -1
View File
@@ -1,7 +1,7 @@
# Googletest Samples
If you're like us, you'd like to look at
[googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples)
[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples)
The sample directory has a number of well-commented samples showing how to use a
variety of googletest features.
+19 -10
View File
@@ -36,7 +36,8 @@ endif()
# as ${gmock_SOURCE_DIR} and to the root binary directory as
# ${gmock_BINARY_DIR}.
# Language "C" is required for find_package(Threads).
cmake_minimum_required(VERSION 3.13)
cmake_minimum_required(VERSION 3.5)
cmake_policy(SET CMP0048 NEW)
project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
if (COMMAND set_up_hermetic_build)
@@ -100,14 +101,18 @@ else()
target_link_libraries(gmock_main PUBLIC gmock)
set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
endif()
string(REPLACE ";" "$<SEMICOLON>" dirs "${gmock_build_include_dirs}")
target_include_directories(gmock SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gmock_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
# If the CMake version supports it, attach header directory information
# to the targets for when we are part of a parent build (ie being pulled
# in via add_subdirectory() rather than being a standalone build).
if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
string(REPLACE ";" "$<SEMICOLON>" dirs "${gmock_build_include_dirs}")
target_include_directories(gmock SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gmock_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
endif()
########################################################################
#
@@ -131,7 +136,11 @@ if (gmock_build_tests)
enable_testing()
if (MINGW OR CYGWIN)
add_compile_options("-Wa,-mbig-obj")
if (CMAKE_VERSION VERSION_LESS "2.8.12")
add_compile_options("-Wa,-mbig-obj")
else()
add_definitions("-Wa,-mbig-obj")
endif()
endif()
############################################################
+36 -35
View File
@@ -122,7 +122,7 @@
// MORE INFORMATION:
//
// To learn more about using these macros, please search for 'ACTION' on
// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md
// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
@@ -146,7 +146,10 @@
#include "gmock/internal/gmock-port.h"
#include "gmock/internal/gmock-pp.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
namespace testing {
@@ -611,7 +614,7 @@ class DefaultValue {
private:
class ValueProducer {
public:
virtual ~ValueProducer() = default;
virtual ~ValueProducer() {}
virtual T Produce() = 0;
};
@@ -699,8 +702,8 @@ class ActionInterface {
typedef typename internal::Function<F>::Result Result;
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
ActionInterface() = default;
virtual ~ActionInterface() = default;
ActionInterface() {}
virtual ~ActionInterface() {}
// Performs the action. This method is not const, as in general an
// action can have side effects and be stateful. For example, a
@@ -749,7 +752,7 @@ class Action<R(Args...)> {
// Constructs a null Action. Needed for storing Action objects in
// STL containers.
Action() = default;
Action() {}
// Construct an Action from a specified callable.
// This cannot take std::function directly, because then Action would not be
@@ -1273,7 +1276,7 @@ class AssignAction {
const T2 value_;
};
#ifndef GTEST_OS_WINDOWS_MOBILE
#if !GTEST_OS_WINDOWS_MOBILE
// Implements the SetErrnoAndReturn action to simulate return from
// various system calls and libc functions.
@@ -1417,19 +1420,17 @@ struct WithArgsAction {
// providing a call operator because even with a particular set of arguments
// they don't have a fixed return type.
template <
typename R, typename... Args,
typename std::enable_if<
std::is_convertible<InnerAction,
// Unfortunately we can't use the InnerSignature
// alias here; MSVC complains about the I
// parameter pack not being expanded (error C3520)
// despite it being expanded in the type alias.
// TupleElement is also an MSVC workaround.
// See its definition for details.
OnceAction<R(internal::TupleElement<
I, std::tuple<Args...>>...)>>::value,
int>::type = 0>
template <typename R, typename... Args,
typename std::enable_if<
std::is_convertible<
InnerAction,
// Unfortunately we can't use the InnerSignature alias here;
// MSVC complains about the I parameter pack not being
// expanded (error C3520) despite it being expanded in the
// type alias.
OnceAction<R(typename std::tuple_element<
I, std::tuple<Args...>>::type...)>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
struct OA {
OnceAction<InnerSignature<R, Args...>> inner_action;
@@ -1444,19 +1445,17 @@ struct WithArgsAction {
return OA{std::move(inner_action)};
}
template <
typename R, typename... Args,
typename std::enable_if<
std::is_convertible<const InnerAction&,
// Unfortunately we can't use the InnerSignature
// alias here; MSVC complains about the I
// parameter pack not being expanded (error C3520)
// despite it being expanded in the type alias.
// TupleElement is also an MSVC workaround.
// See its definition for details.
Action<R(internal::TupleElement<
I, std::tuple<Args...>>...)>>::value,
int>::type = 0>
template <typename R, typename... Args,
typename std::enable_if<
std::is_convertible<
const InnerAction&,
// Unfortunately we can't use the InnerSignature alias here;
// MSVC complains about the I parameter pack not being
// expanded (error C3520) despite it being expanded in the
// type alias.
Action<R(typename std::tuple_element<
I, std::tuple<Args...>>::type...)>>::value,
int>::type = 0>
operator Action<R(Args...)>() const { // NOLINT
Action<InnerSignature<R, Args...>> converted(inner_action);
@@ -1926,7 +1925,7 @@ PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {
return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
}
#ifndef GTEST_OS_WINDOWS_MOBILE
#if !GTEST_OS_WINDOWS_MOBILE
// Creates an action that sets errno and returns the appropriate error.
template <typename T>
@@ -2292,6 +2291,8 @@ template <typename F, typename Impl>
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
@@ -65,7 +65,7 @@ namespace testing {
// The implementation of a cardinality.
class CardinalityInterface {
public:
virtual ~CardinalityInterface() = default;
virtual ~CardinalityInterface() {}
// Conservative estimate on the lower/upper bound of the number of
// calls allowed.
@@ -92,7 +92,7 @@ class GTEST_API_ Cardinality {
public:
// Constructs a null cardinality. Needed for storing Cardinality
// objects in STL containers.
Cardinality() = default;
Cardinality() {}
// Constructs a Cardinality from its implementation.
explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
@@ -34,8 +34,8 @@
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
#include <type_traits> // IWYU pragma: keep
#include <utility> // IWYU pragma: keep
@@ -108,11 +108,8 @@ constexpr bool ValidateSpec(const char (&spec)[N]) {
using internal::FunctionMocker;
} // namespace testing
#define MOCK_METHOD(...) \
GMOCK_INTERNAL_WARNING_PUSH() \
GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \
GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) \
GMOCK_INTERNAL_WARNING_POP()
#define MOCK_METHOD(...) \
GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
@@ -180,9 +177,8 @@ using internal::FunctionMocker;
_Signature)>::Result \
GMOCK_INTERNAL_EXPAND(_CallType) \
_MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
GMOCK_PP_IF(_Constness, const, ) \
_RefSpec _NoexceptSpec GMOCK_PP_IF(_Override, override, ) \
GMOCK_PP_IF(_Final, final, ) { \
GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \
GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \
GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.SetOwnerAndName(this, #_MethodName); \
return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
@@ -515,4 +511,4 @@ using internal::FunctionMocker;
#define GMOCK_MOCKER_(arity, constness, Method) \
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
+34 -47
View File
@@ -240,7 +240,7 @@
//
// To learn more about using these macros, please search for 'MATCHER'
// on
// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md
// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
//
// This file also implements some commonly used argument matchers. More
// matchers can be defined by the user implementing the
@@ -257,10 +257,7 @@
#include <algorithm>
#include <cmath>
#include <exception>
#include <functional>
#include <initializer_list>
#include <ios>
#include <iterator>
#include <limits>
#include <memory>
@@ -564,7 +561,7 @@ namespace internal {
// If the explanation is not empty, prints it to the ostream.
inline void PrintIfNotEmpty(const std::string& explanation,
::std::ostream* os) {
if (!explanation.empty() && os != nullptr) {
if (explanation != "" && os != nullptr) {
*os << ", " << explanation;
}
}
@@ -1201,27 +1198,27 @@ class PairMatchBase {
};
};
class Eq2Matcher : public PairMatchBase<Eq2Matcher, std::equal_to<>> {
class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
public:
static const char* Desc() { return "an equal pair"; }
};
class Ne2Matcher : public PairMatchBase<Ne2Matcher, std::not_equal_to<>> {
class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
public:
static const char* Desc() { return "an unequal pair"; }
};
class Lt2Matcher : public PairMatchBase<Lt2Matcher, std::less<>> {
class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
public:
static const char* Desc() { return "a pair where the first < the second"; }
};
class Gt2Matcher : public PairMatchBase<Gt2Matcher, std::greater<>> {
class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
public:
static const char* Desc() { return "a pair where the first > the second"; }
};
class Le2Matcher : public PairMatchBase<Le2Matcher, std::less_equal<>> {
class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
public:
static const char* Desc() { return "a pair where the first <= the second"; }
};
class Ge2Matcher : public PairMatchBase<Ge2Matcher, std::greater_equal<>> {
class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
public:
static const char* Desc() { return "a pair where the first >= the second"; }
};
@@ -1475,7 +1472,6 @@ class SomeOfArrayMatcher {
operator Matcher<U>() const { // NOLINT
using RawU = typename std::decay<U>::type;
std::vector<Matcher<RawU>> matchers;
matchers.reserve(matchers_.size());
for (const auto& matcher : matchers_) {
matchers.push_back(MatcherCast<RawU>(matcher));
}
@@ -2313,11 +2309,11 @@ class SizeIsMatcher {
: size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
void DescribeTo(::std::ostream* os) const override {
*os << "has a size that ";
*os << "size ";
size_matcher_.DescribeTo(os);
}
void DescribeNegationTo(::std::ostream* os) const override {
*os << "has a size that ";
*os << "size ";
size_matcher_.DescribeNegationTo(os);
}
@@ -2967,7 +2963,7 @@ class KeyMatcherImpl : public MatcherInterface<PairType> {
const bool match = inner_matcher_.MatchAndExplain(
pair_getters::First(key_value, Rank0()), &inner_listener);
const std::string explanation = inner_listener.str();
if (!explanation.empty()) {
if (explanation != "") {
*listener << "whose first field is a value " << explanation;
}
return match;
@@ -3114,12 +3110,12 @@ class PairMatcherImpl : public MatcherInterface<PairType> {
const std::string& second_explanation,
MatchResultListener* listener) const {
*listener << "whose both fields match";
if (!first_explanation.empty()) {
if (first_explanation != "") {
*listener << ", where the first field is a value " << first_explanation;
}
if (!second_explanation.empty()) {
if (second_explanation != "") {
*listener << ", ";
if (!first_explanation.empty()) {
if (first_explanation != "") {
*listener << "and ";
} else {
*listener << "where ";
@@ -3239,21 +3235,6 @@ auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
}
template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<17>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q);
}
template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<18>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r);
}
template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<19>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s);
}
#endif // defined(__cpp_structured_bindings)
template <size_t I, typename T>
@@ -3648,6 +3629,23 @@ class UnorderedElementsAreMatcherImpl
AnalyzeElements(stl_container.begin(), stl_container.end(),
&element_printouts, listener);
if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
return true;
}
if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
if (matrix.LhsSize() != matrix.RhsSize()) {
// The element count doesn't match. If the container is empty,
// there's no need to explain anything as Google Mock already
// prints the empty container. Otherwise we just need to show
// how many elements there actually are.
if (matrix.LhsSize() != 0 && listener->IsInterested()) {
*listener << "which has " << Elements(matrix.LhsSize());
}
return false;
}
}
return VerifyMatchMatrix(element_printouts, matrix, listener) &&
FindPairing(matrix, listener);
}
@@ -4102,12 +4100,7 @@ class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
const char* sep = "";
// Workaround spurious C4189 on MSVC<=15.7 when k is empty.
(void)sep;
// The static_cast to void is needed to silence Clang's -Wcomma warning.
// This pattern looks suspiciously like we may have mismatched parentheses
// and may have been trying to use the first operation of the comma operator
// as a member of the array, so Clang warns that we may have made a mistake.
const char* dummy[] = {
"", (static_cast<void>(*os << sep << "#" << k), sep = ", ")...};
const char* dummy[] = {"", (*os << sep << "#" << k, sep = ", ")...};
(void)dummy;
*os << ") ";
}
@@ -5474,12 +5467,7 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
} \
}; \
}; \
inline name##Matcher GMOCK_INTERNAL_WARNING_PUSH() \
GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-function") \
GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \
name GMOCK_INTERNAL_WARNING_POP()() { \
return {}; \
} \
GTEST_ATTRIBUTE_UNUSED_ inline name##Matcher name() { return {}; } \
template <typename arg_type> \
bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
const arg_type& arg, \
@@ -5545,8 +5533,7 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
\
private: \
::std::string FormatDescription(bool negation) const { \
::std::string gmock_description; \
gmock_description = (description); \
::std::string gmock_description = (description); \
if (!gmock_description.empty()) { \
return gmock_description; \
} \
+17 -13
View File
@@ -526,10 +526,9 @@
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 \
GMOCK_ACTION_CLASS_(name, value_params)(GMOCK_ACTION_CLASS_( \
name, value_params) &&) noexcept GMOCK_INTERNAL_DEFN_COPY_ \
##value_params template <typename F> \
##value_params GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept \
GMOCK_INTERNAL_DEFN_COPY_##value_params template <typename F> \
operator ::testing::Action<F>() const { \
return GMOCK_PP_IF( \
GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
@@ -583,7 +582,10 @@ namespace testing {
// the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
namespace internal {
@@ -600,13 +602,13 @@ 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(
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) {
auto &&callable = args_tuple.template Get<index>();
std::declval<const Params&>()...)) {
internal::FlatTuple<Args&&...> args_tuple(FlatTupleConstructTag{},
std::forward<Args>(args)...);
return params.Apply([&](const Params&... unpacked_params) {
auto&& callable = args_tuple.template Get<index>();
return internal::InvokeArgument(
std::forward<decltype(callable)>(callable), unpacked_params...);
});
@@ -646,12 +648,14 @@ struct InvokeArgumentAction {
// later.
template <std::size_t index, typename... Params>
internal::InvokeArgumentAction<index, typename std::decay<Params>::type...>
InvokeArgument(Params &&...params) {
InvokeArgument(Params&&... params) {
return {internal::FlatTuple<typename std::decay<Params>::type...>(
internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
}
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
} // namespace testing
+15 -44
View File
@@ -40,58 +40,30 @@
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#include <ostream>
#include <string>
#include "gmock/gmock-matchers.h"
namespace testing {
// Silence C4100 (unreferenced formal
// parameter) for MSVC
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#if defined(_MSC_VER) && (_MSC_VER == 1900)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#if (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#pragma warning(disable : 4800)
#endif
#endif
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 IsEmptyMatcher {
public:
// Matches anything that defines empty() and size().
template <typename MatcheeContainerType>
bool MatchAndExplain(const MatcheeContainerType& c,
MatchResultListener* listener) const {
if (c.empty()) {
return true;
}
*listener << "whose size is " << c.size();
return false;
// Defines a matcher that matches an empty container. The container must
// support both size() and empty(), which all STL-like containers provide.
MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
if (arg.empty()) {
return true;
}
// Matches C-style strings.
bool MatchAndExplain(const char* s, MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener);
}
// Describes what this matcher matches.
void DescribeTo(std::ostream* os) const { *os << "is empty"; }
void DescribeNegationTo(std::ostream* os) const { *os << "isn't empty"; }
};
} // namespace internal
// Creates a polymorphic matcher that matches an empty container or C-style
// string. The container must support both size() and empty(), which all
// STL-like containers provide.
inline PolymorphicMatcher<internal::IsEmptyMatcher> IsEmpty() {
return MakePolymorphicMatcher(internal::IsEmptyMatcher());
*result_listener << "whose size is " << arg.size();
return false;
}
// Define a matcher that matches a value that evaluates in boolean
@@ -110,10 +82,9 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
return !static_cast<bool>(arg);
}
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#ifdef _MSC_VER
#pragma warning(pop)
#endif
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
} // namespace testing
+1 -1
View File
@@ -98,7 +98,7 @@ constexpr bool HasStrictnessModifier() {
// deregistration. This guarantees that MockClass's constructor and destructor
// run with the same level of strictness as its instance methods.
#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) && \
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \
(defined(_MSC_VER) || defined(__clang__))
// We need to mark these classes with this declspec to ensure that
// the empty base class optimization is performed.
+23 -88
View File
@@ -65,7 +65,6 @@
#include <functional>
#include <map>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
@@ -204,9 +203,6 @@ class GTEST_API_ UntypedFunctionMockerBase {
using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
struct UninterestingCallCleanupHandler;
struct FailureCleanupHandler;
// Returns an Expectation object that references and co-owns exp,
// which must be an expectation on this mock function.
Expectation GetHandleOf(ExpectationBase* exp);
@@ -566,7 +562,7 @@ class ExpectationSet {
typedef Expectation::Set::value_type value_type;
// Constructs an empty set.
ExpectationSet() = default;
ExpectationSet() {}
// This single-argument ctor must not be explicit, in order to support the
// ExpectationSet es = EXPECT_CALL(...);
@@ -660,7 +656,7 @@ class GTEST_API_ InSequence {
InSequence(const InSequence&) = delete;
InSequence& operator=(const InSequence&) = delete;
};
} GTEST_ATTRIBUTE_UNUSED_;
namespace internal {
@@ -710,12 +706,6 @@ class GTEST_API_ ExpectationBase {
// describes it to the ostream.
virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
// Do not rely on this for correctness.
// This is only for making human-readable test output easier to understand.
void UntypedDescription(std::string description) {
description_ = std::move(description);
}
protected:
friend class ::testing::Expectation;
friend class UntypedFunctionMockerBase;
@@ -782,10 +772,6 @@ class GTEST_API_ ExpectationBase {
retired_ = true;
}
// Returns a human-readable description of this expectation.
// Do not rely on this for correctness. It is only for human readability.
const std::string& GetDescription() const { return description_; }
// Returns true if and only if this expectation is satisfied.
bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
@@ -845,7 +831,6 @@ class GTEST_API_ ExpectationBase {
const char* file_; // The file that contains the expectation.
int line_; // The line number of the expectation.
const std::string source_text_; // The EXPECT_CALL(...) source text.
std::string description_; // User-readable name for the expectation.
// True if and only if the cardinality is specified explicitly.
bool cardinality_specified_;
Cardinality cardinality_; // The cardinality of the expectation.
@@ -924,13 +909,6 @@ class TypedExpectation<R(Args...)> : public ExpectationBase {
return *this;
}
// Do not rely on this for correctness.
// This is only for making human-readable test output easier to understand.
TypedExpectation& Description(std::string name) {
ExpectationBase::UntypedDescription(std::move(name));
return *this;
}
// Implements the .Times() clause.
TypedExpectation& Times(const Cardinality& a_cardinality) {
ExpectationBase::UntypedTimes(a_cardinality);
@@ -1221,15 +1199,10 @@ class TypedExpectation<R(Args...)> : public ExpectationBase {
::std::ostream* why)
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
const ::std::string& expectation_description = GetDescription();
if (IsSaturated()) {
// We have an excessive call.
IncrementCallCount();
*what << "Mock function ";
if (!expectation_description.empty()) {
*what << "\"" << expectation_description << "\" ";
}
*what << "called more times than expected - ";
*what << "Mock function called more times than expected - ";
mocker->DescribeDefaultActionTo(args, what);
DescribeCallCountTo(why);
@@ -1244,11 +1217,7 @@ class TypedExpectation<R(Args...)> : public ExpectationBase {
}
// Must be done after IncrementCount()!
*what << "Mock function ";
if (!expectation_description.empty()) {
*what << "\"" << expectation_description << "\" ";
}
*what << "call matches " << source_text() << "...\n";
*what << "Mock function call matches " << source_text() << "...\n";
return &(GetCurrentAction(mocker, args));
}
@@ -1399,41 +1368,6 @@ class Cleanup final {
std::function<void()> f_;
};
struct UntypedFunctionMockerBase::UninterestingCallCleanupHandler {
CallReaction reaction;
std::stringstream& ss;
~UninterestingCallCleanupHandler() {
ReportUninterestingCall(reaction, ss.str());
}
};
struct UntypedFunctionMockerBase::FailureCleanupHandler {
std::stringstream& ss;
std::stringstream& why;
std::stringstream& loc;
const ExpectationBase* untyped_expectation;
bool found;
bool is_excessive;
~FailureCleanupHandler() {
ss << "\n" << why.str();
if (!found) {
// No expectation matches this call - reports a failure.
Expect(false, nullptr, -1, ss.str());
} else if (is_excessive) {
// We had an upper-bound violation and the failure message is in ss.
Expect(false, untyped_expectation->file(), untyped_expectation->line(),
ss.str());
} else {
// We had an expected call and the matching expectation is
// described in ss.
Log(kInfo, loc.str() + ss.str(), 2);
}
}
};
template <typename F>
class FunctionMocker;
@@ -1446,7 +1380,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
FunctionMocker() = default;
FunctionMocker() {}
// There is no generally useful and implementable semantics of
// copying a mock object, so copying a mock is usually a user error.
@@ -1832,15 +1766,8 @@ R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
//
// We use RAII to do the latter in case R is void or a non-moveable type. In
// either case we can't assign it to a local variable.
//
// Note that std::bind() is essential here.
// We *don't* use any local callback types (like lambdas).
// 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 Cleanup report_uninteresting_call(
[&] { ReportUninterestingCall(reaction, ss.str()); });
return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
}
@@ -1884,14 +1811,22 @@ R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
//
// We use RAII to do the latter in case R is void or a non-moveable type. In
// either case we can't assign it to a local variable.
//
// Note that we *don't* use any local callback types (like lambdas) here.
// Doing so slows down compilation dramatically because the *constructor* of
// std::function<T> is re-instantiated with different template
// parameters each time.
const FailureCleanupHandler handle_failures = {
ss, why, loc, untyped_expectation, found, is_excessive
};
const Cleanup handle_failures([&] {
ss << "\n" << why.str();
if (!found) {
// No expectation matches this call - reports a failure.
Expect(false, nullptr, -1, ss.str());
} else if (is_excessive) {
// We had an upper-bound violation and the failure message is in ss.
Expect(false, untyped_expectation->file(), untyped_expectation->line(),
ss.str());
} else {
// We had an expected call and the matching expectation is
// described in ss.
Log(kInfo, loc.str() + ss.str(), 2);
}
});
return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
ss);
@@ -58,7 +58,11 @@ namespace internal {
// Silence MSVC C4100 (unreferenced formal parameter) and
// C4805('==': unsafe mix of type 'const int' and type 'const bool')
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4805)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4805)
#endif
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
@@ -91,24 +95,6 @@ inline Element* GetRawPointer(Element* p) {
return p;
}
// Default definitions for all compilers.
// NOTE: If you implement support for other compilers, make sure to avoid
// unexpected overlaps.
// (e.g., Clang also processes #pragma GCC, and clang-cl also handles _MSC_VER.)
#define GMOCK_INTERNAL_WARNING_PUSH()
#define GMOCK_INTERNAL_WARNING_CLANG(Level, Name)
#define GMOCK_INTERNAL_WARNING_POP()
#if defined(__clang__)
#undef GMOCK_INTERNAL_WARNING_PUSH
#define GMOCK_INTERNAL_WARNING_PUSH() _Pragma("clang diagnostic push")
#undef GMOCK_INTERNAL_WARNING_CLANG
#define GMOCK_INTERNAL_WARNING_CLANG(Level, Warning) \
_Pragma(GMOCK_PP_INTERNAL_STRINGIZE(clang diagnostic Level Warning))
#undef GMOCK_INTERNAL_WARNING_POP
#define GMOCK_INTERNAL_WARNING_POP() _Pragma("clang diagnostic pop")
#endif
// MSVC treats wchar_t as a native type usually, but treats it as the
// same as unsigned short when the compiler option /Zc:wchar_t- is
// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
@@ -224,7 +210,7 @@ class FailureReporterInterface {
// The type of a failure (either non-fatal or fatal).
enum FailureType { kNonfatal, kFatal };
virtual ~FailureReporterInterface() = default;
virtual ~FailureReporterInterface() {}
// Reports a failure that occurred at the given source file location.
virtual void ReportFailure(FailureType type, const char* file, int line,
@@ -304,6 +290,13 @@ class WithoutMatchers {
// Internal use only: access the singleton instance of WithoutMatchers.
GTEST_API_ WithoutMatchers GetWithoutMatchers();
// Disable MSVC warnings for infinite recursion, since in this case the
// recursion is unreachable.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4717)
#endif
// Invalid<T>() is usable as an expression of type T, but will terminate
// the program with an assertion failure if actually run. This is useful
// when a value of type T is needed for compilation, but the statement
@@ -311,8 +304,7 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers();
// crashes).
template <typename T>
inline T Invalid() {
Assert(/*condition=*/false, /*file=*/"", /*line=*/-1,
"Internal error: attempt to return invalid value");
Assert(false, "", -1, "Internal error: attempt to return invalid value");
#if defined(__GNUC__) || defined(__clang__)
__builtin_unreachable();
#elif defined(_MSC_VER)
@@ -322,6 +314,10 @@ inline T Invalid() {
#endif
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// Given a raw type (i.e. having no top-level reference or const
// modifier) RawContainer that's either an STL-style container or a
// native array, class StlContainerView<RawContainer> has the
@@ -465,21 +461,14 @@ 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
// Can be replaced with std::tuple_element_t in C++14.
template <size_t I, typename T>
using TupleElement = typename std::tuple_element<I, T>::type;
bool Base64Unescape(const std::string& encoded, std::string* decoded);
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4805
#ifdef _MSC_VER
#pragma warning(pop)
#endif
} // namespace internal
} // namespace testing
@@ -56,7 +56,7 @@
#include "gmock/internal/custom/gmock-port.h"
#include "gtest/internal/gtest-port.h"
#ifdef GTEST_HAS_ABSL
#if GTEST_HAS_ABSL
#include "absl/flags/declare.h"
#include "absl/flags/flag.h"
#endif
@@ -73,7 +73,7 @@
#define GMOCK_FLAG(name) FLAGS_gmock_##name
// Pick a command line flags implementation.
#ifdef GTEST_HAS_ABSL
#if GTEST_HAS_ABSL
// Macros for defining flags.
#define GMOCK_DEFINE_bool_(name, default_val, doc) \
+6 -13
View File
@@ -41,7 +41,6 @@
#include <cctype>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <ostream> // NOLINT
#include <string>
#include <vector>
@@ -88,7 +87,7 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
(!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) {
if (starts_new_word && !result.empty()) result += ' ';
if (starts_new_word && result != "") result += ' ';
result += ToLower(*p);
}
}
@@ -182,7 +181,7 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
}
std::cout << "Stack trace:\n"
<< ::testing::internal::GetCurrentOsStackTraceExceptTop(
actual_to_skip);
::testing::UnitTest::GetInstance(), actual_to_skip);
}
std::cout << ::std::flush;
}
@@ -199,22 +198,16 @@ GTEST_API_ void IllegalDoDefault(const char* file, int line) {
"the variable in various places.");
}
constexpr char UndoWebSafeEncoding(char c) {
return c == '-' ? '+' : c == '_' ? '/' : c;
}
constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
return *base64 == 0 ? static_cast<char>(65)
: *base64 == c
? carry
: UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1));
return *base64 == 0 ? static_cast<char>(65)
: *base64 == c ? carry
: UnBase64Impl(c, base64 + 1, carry + 1);
}
template <size_t... I>
constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,
const char* const base64) {
return {
{UnBase64Impl(UndoWebSafeEncoding(static_cast<char>(I)), base64, 0)...}};
return {{UnBase64Impl(static_cast<char>(I), base64, 0)...}};
}
constexpr std::array<char, 256> UnBase64(const char* const base64) {
+1 -18
View File
@@ -53,7 +53,7 @@ GTEST_API_ std::string FormatMatcherDescription(
bool negation, const char* matcher_name,
const std::vector<const char*>& param_names, const Strings& param_values) {
std::string result = ConvertIdentifierNameToWords(matcher_name);
if (!param_values.empty()) {
if (param_values.size() >= 1) {
result += " " + JoinAsKeyValueTuple(param_names, param_values);
}
return negation ? "not (" + result + ")" : result;
@@ -370,23 +370,6 @@ void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
const ::std::vector<std::string>& element_printouts,
const MatchMatrix& matrix, MatchResultListener* listener) const {
if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
return true;
}
if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
if (matrix.LhsSize() != matrix.RhsSize()) {
// The element count doesn't match. If the container is empty,
// there's no need to explain anything as Google Mock already
// prints the empty container. Otherwise we just need to show
// how many elements there actually are.
if (matrix.LhsSize() != 0 && listener->IsInterested()) {
*listener << "which has " << Elements(matrix.LhsSize());
}
return false;
}
}
bool result = true;
::std::vector<char> element_matched(matrix.LhsSize(), 0);
::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
+20 -30
View File
@@ -40,7 +40,6 @@
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
@@ -49,17 +48,17 @@
#include "gtest/gtest.h"
#include "gtest/internal/gtest-port.h"
#if defined(GTEST_OS_CYGWIN) || defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC)
#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
#include <unistd.h> // NOLINT
#endif
#ifdef GTEST_OS_QURT
#include <qurt_event.h>
#endif
// Silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#ifdef _MSC_VER
#if _MSC_VER == 1900
#pragma warning(push)
#pragma warning(disable : 4800)
#endif
#endif
namespace testing {
@@ -96,7 +95,7 @@ ExpectationBase::ExpectationBase(const char* a_file, int a_line,
action_count_checked_(false) {}
// Destructs an ExpectationBase object.
ExpectationBase::~ExpectationBase() = default;
ExpectationBase::~ExpectationBase() {}
// Explicitly specifies the cardinality of this expectation. Used by
// the subclasses to implement the .Times() clause.
@@ -296,9 +295,9 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
"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/"
"https://github.com/google/googletest/blob/master/docs/"
"gmock_cook_book.md#"
"knowing-when-to-expect-useoncall for details.\n",
"knowing-when-to-expect for details.\n",
stack_frames_to_skip);
break;
default: // FAIL
@@ -309,7 +308,7 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
UntypedFunctionMockerBase::UntypedFunctionMockerBase()
: mock_obj_(nullptr), name_("") {}
UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;
UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
// Sets the mock object this mock method belongs to, and registers
// this information in the global mock registry. Will be called
@@ -407,15 +406,8 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
} else if (!untyped_expectation->IsSatisfied()) {
expectations_met = false;
::std::stringstream ss;
const ::std::string& expectation_name =
untyped_expectation->GetDescription();
ss << "Actual function ";
if (!expectation_name.empty()) {
ss << "\"" << expectation_name << "\" ";
}
ss << "call count doesn't match " << untyped_expectation->source_text()
<< "...\n";
ss << "Actual function call count doesn't match "
<< untyped_expectation->source_text() << "...\n";
// No need to show the source file location of the expectation
// in the description, as the Expect() call that follows already
// takes care of it.
@@ -443,7 +435,7 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
return expectations_met;
}
static CallReaction intToCallReaction(int mock_behavior) {
CallReaction intToCallReaction(int mock_behavior) {
if (mock_behavior >= kAllow && mock_behavior <= kFail) {
return static_cast<internal::CallReaction>(mock_behavior);
}
@@ -504,7 +496,7 @@ class MockObjectRegistry {
std::cout << internal::FormatFileLocation(state.first_used_file,
state.first_used_line);
std::cout << " ERROR: this mock object";
if (!state.first_used_test.empty()) {
if (state.first_used_test != "") {
std::cout << " (used in test " << state.first_used_test_suite << "."
<< state.first_used_test << ")";
}
@@ -527,12 +519,8 @@ class MockObjectRegistry {
// RUN_ALL_TESTS() has already returned when this destructor is
// called. Therefore we cannot use the normal Google Test
// failure reporting mechanism.
#ifdef GTEST_OS_QURT
qurt_exception_raise_fatal();
#else
_exit(1); // We cannot call exit() as it is not reentrant and
// may already have been called.
#endif
}
}
@@ -746,13 +734,13 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj)
// needed by VerifyAndClearExpectationsLocked().
}
Expectation::Expectation() = default;
Expectation::Expectation() {}
Expectation::Expectation(
const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
: expectation_base_(an_expectation_base) {}
Expectation::~Expectation() = default;
Expectation::~Expectation() {}
// Adds an expectation to a sequence.
void Sequence::AddExpectation(const Expectation& expectation) const {
@@ -786,6 +774,8 @@ InSequence::~InSequence() {
} // namespace testing
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#ifdef _MSC_VER
#if _MSC_VER == 1900
#pragma warning(pop)
#endif
#endif
-2
View File
@@ -29,8 +29,6 @@
#include "gmock/gmock.h"
#include <string>
#include "gmock/internal/gmock-port.h"
GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
+4 -5
View File
@@ -32,9 +32,8 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) || \
(defined(GTEST_OS_NRF52) && defined(ARDUINO))
#ifdef GTEST_OS_ESP8266
#if GTEST_OS_ESP8266 || GTEST_OS_ESP32
#if GTEST_OS_ESP8266
extern "C" {
#endif
void setup() {
@@ -44,7 +43,7 @@ void setup() {
testing::InitGoogleMock();
}
void loop() { RUN_ALL_TESTS(); }
#ifdef GTEST_OS_ESP8266
#if GTEST_OS_ESP8266
}
#endif
@@ -56,7 +55,7 @@ void loop() { RUN_ALL_TESTS(); }
// Windows. See the following link to track the current status of this bug:
// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library
// // NOLINT
#ifdef GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE
#include <tchar.h> // NOLINT
GTEST_API_ int _tmain(int argc, TCHAR** argv) {
+31 -33
View File
@@ -31,33 +31,33 @@
//
// This file tests the built-in actions.
// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
// length exceeded) for MSVC.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4503)
#if _MSC_VER == 1900
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15
#pragma warning(disable : 4800)
#endif
#endif
#include "gmock/gmock-actions.h"
#include <algorithm>
#include <functional>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#include "gtest/internal/gtest-port.h"
// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
// length exceeded) for MSVC.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
#if defined(_MSC_VER) && (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#endif
namespace testing {
namespace {
@@ -222,8 +222,7 @@ 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.
#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
#if defined(__cplusplus) && __cplusplus >= 201703L
{
struct NonMoveable {
NonMoveable() = default;
@@ -449,7 +448,7 @@ TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
DefaultValue<std::unique_ptr<int>>::SetFactory(
[] { return std::make_unique<int>(42); });
[] { return std::unique_ptr<int>(new int(42)); });
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
EXPECT_EQ(42, *i);
@@ -467,7 +466,7 @@ TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
}
// Tests that DefaultValue<T&>::Exists is false initially.
// Tests that DefaultValue<T&>::Exists is false initiallly.
TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
EXPECT_FALSE(DefaultValue<int&>::Exists());
EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
@@ -685,7 +684,7 @@ TEST(ReturnTest, SupportsReferenceLikeReturnType) {
// A reference wrapper for std::vector<int>, implicitly convertible from it.
struct Result {
const std::vector<int>* v;
Result(const std::vector<int>& vec) : v(&vec) {} // NOLINT
Result(const std::vector<int>& v) : v(&v) {} // NOLINT
};
// Set up an action for a mock function that returns the reference wrapper
@@ -718,7 +717,7 @@ TEST(ReturnTest, PrefersConversionOperator) {
struct Out {
int x;
explicit Out(const int val) : x(val) {}
explicit Out(const int x) : x(x) {}
explicit Out(const In&) : x(0) {}
};
@@ -808,7 +807,7 @@ TEST(ReturnTest, MoveOnlyResultType) {
"");
}
// Tests that Return(v) is covariant.
// Tests that Return(v) is covaraint.
struct Base {
bool operator==(const Base&) { return true; }
@@ -987,7 +986,7 @@ TEST(ReturnRoundRobinTest, WorksForVector) {
class MockClass {
public:
MockClass() = default;
MockClass() {}
MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
MOCK_METHOD0(Foo, MyNonDefaultConstructible());
@@ -1411,7 +1410,7 @@ TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {
void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
};
MockFunction<void(Obj&&)> mock;
MockFunction<void(Obj &&)> mock;
EXPECT_CALL(mock, Call)
.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
.WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
@@ -1439,7 +1438,7 @@ TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {
void operator()(Obj&) && {}
};
MockFunction<void(Obj&&)> mock;
MockFunction<void(Obj &&)> mock;
EXPECT_CALL(mock, Call)
.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
@@ -1597,7 +1596,7 @@ TEST(WithArgsTest, RefQualifiedInnerAction) {
EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
}
#ifndef GTEST_OS_WINDOWS_MOBILE
#if !GTEST_OS_WINDOWS_MOBILE
class SetErrnoAndReturnTest : public testing::Test {
protected:
@@ -1756,7 +1755,9 @@ TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
delete c;
}
std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); }
std::unique_ptr<int> UniquePtrSource() {
return std::unique_ptr<int>(new int(19));
}
std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
std::vector<std::unique_ptr<int>> out;
@@ -1805,7 +1806,7 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
// Check default value
DefaultValue<std::unique_ptr<int>>::SetFactory(
[] { return std::make_unique<int>(42); });
[] { return std::unique_ptr<int>(new int(42)); });
EXPECT_EQ(42, *mock.MakeUnique());
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
@@ -1825,7 +1826,7 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
TEST(MockMethodTest, CanTakeMoveOnlyValue) {
MockClass mock;
auto make = [](int i) { return std::make_unique<int>(i); };
auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
return *i;
@@ -2056,7 +2057,9 @@ struct Double {
}
};
std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); }
std::unique_ptr<int> UniqueInt(int i) {
return std::unique_ptr<int>(new int(i));
}
TEST(FunctorActionTest, ActionFromFunction) {
Action<int(int, int&, int*)> a = &Add;
@@ -2162,8 +2165,3 @@ TEST(ActionMacro, LargeArity) {
} // namespace
} // namespace testing
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#endif
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503
+1 -3
View File
@@ -31,8 +31,6 @@
//
// This file tests the built-in cardinalities.
#include <ostream>
#include "gmock/gmock.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
@@ -52,7 +50,7 @@ using testing::MakeCardinality;
class MockFoo {
public:
MockFoo() = default;
MockFoo() {}
MOCK_METHOD0(Bar, int()); // NOLINT
private:
+31 -40
View File
@@ -27,15 +27,18 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Silence C4503 (decorated name length exceeded) for MSVC.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4503)
#endif
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the function mocker classes.
#include "gmock/gmock-function-mocker.h"
// Silence C4503 (decorated name length exceeded) for MSVC.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4503)
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
// we are getting compiler errors if we use basetyps.h, hence including
// objbase.h for definition of STDMETHOD.
@@ -70,7 +73,7 @@ using testing::TypedEq;
template <typename T>
class TemplatedCopyable {
public:
TemplatedCopyable() = default;
TemplatedCopyable() {}
template <typename U>
TemplatedCopyable(const U& other) {} // NOLINT
@@ -78,7 +81,7 @@ class TemplatedCopyable {
class FooInterface {
public:
virtual ~FooInterface() = default;
virtual ~FooInterface() {}
virtual void VoidReturning(int x) = 0;
@@ -120,7 +123,7 @@ class FooInterface {
virtual int RefQualifiedOverloaded() & = 0;
virtual int RefQualifiedOverloaded() && = 0;
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
STDMETHOD_(int, CTNullary)() = 0;
STDMETHOD_(bool, CTUnary)(int x) = 0;
STDMETHOD_(int, CTDecimal)
@@ -134,10 +137,13 @@ class FooInterface {
// significant in determining whether two virtual functions had the same
// signature. This was fixed in Visual Studio 2008. However, the compiler
// still emits a warning that alerts about this change in behavior.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4373)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4373)
#endif
class MockFoo : public FooInterface {
public:
MockFoo() = default;
MockFoo() {}
// Makes sure that a mock function parameter can be named.
MOCK_METHOD(void, VoidReturning, (int n)); // NOLINT
@@ -178,7 +184,7 @@ class MockFoo : public FooInterface {
MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ());
MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ());
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(int, CTDecimal,
@@ -208,7 +214,7 @@ class MockFoo : public FooInterface {
class LegacyMockFoo : public FooInterface {
public:
LegacyMockFoo() = default;
LegacyMockFoo() {}
// Makes sure that a mock function parameter can be named.
MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
@@ -248,7 +254,7 @@ class LegacyMockFoo : public FooInterface {
MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool));
MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int));
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); // NOLINT
MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
@@ -279,7 +285,9 @@ class LegacyMockFoo : public FooInterface {
LegacyMockFoo& operator=(const LegacyMockFoo&) = delete;
};
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4373
#ifdef _MSC_VER
#pragma warning(pop)
#endif
template <class T>
class FunctionMockerTest : public testing::Test {
@@ -404,7 +412,7 @@ TYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
}
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype.
TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
EXPECT_CALL(this->mock_foo_, CTNullary())
@@ -487,7 +495,7 @@ TEST(FunctionMockerTest, RefQualified) {
class MockB {
public:
MockB() = default;
MockB() {}
MOCK_METHOD(void, DoB, ());
@@ -498,7 +506,7 @@ class MockB {
class LegacyMockB {
public:
LegacyMockB() = default;
LegacyMockB() {}
MOCK_METHOD0(DoB, void());
@@ -534,7 +542,7 @@ TYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
template <typename T>
class StackInterface {
public:
virtual ~StackInterface() = default;
virtual ~StackInterface() {}
// Template parameter appears in function parameter.
virtual void Push(const T& value) = 0;
@@ -547,7 +555,7 @@ class StackInterface {
template <typename T>
class MockStack : public StackInterface<T> {
public:
MockStack() = default;
MockStack() {}
MOCK_METHOD(void, Push, (const T& elem), ());
MOCK_METHOD(void, Pop, (), (final));
@@ -566,7 +574,7 @@ class MockStack : public StackInterface<T> {
template <typename T>
class LegacyMockStack : public StackInterface<T> {
public:
LegacyMockStack() = default;
LegacyMockStack() {}
MOCK_METHOD1_T(Push, void(const T& elem));
MOCK_METHOD0_T(Pop, void());
@@ -620,7 +628,7 @@ TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
}
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// Tests mocking template interfaces with calltype.
template <typename T>
@@ -711,7 +719,7 @@ TYPED_TEST(TemplateMockTestWithCallType, Works) {
class MockOverloadedOnArgNumber {
public:
MockOverloadedOnArgNumber() = default;
MockOverloadedOnArgNumber() {}
MY_MOCK_METHODS1_;
@@ -723,7 +731,7 @@ class MockOverloadedOnArgNumber {
class LegacyMockOverloadedOnArgNumber {
public:
LegacyMockOverloadedOnArgNumber() = default;
LegacyMockOverloadedOnArgNumber() {}
LEGACY_MY_MOCK_METHODS1_;
@@ -758,7 +766,7 @@ TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
class MockOverloadedOnConstness {
public:
MockOverloadedOnConstness() = default;
MockOverloadedOnConstness() {}
MY_MOCK_METHODS2_;
@@ -950,21 +958,6 @@ TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(MockMethodSizes0));
}
TEST(MockMethodMockFunctionTest, EnsureNoUnusedMemberFunction) {
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic error "-Wunused-member-function"
#endif
// https://github.com/google/googletest/issues/4052
struct Foo {
MOCK_METHOD(void, foo, ());
};
EXPECT_CALL(Foo(), foo()).Times(0);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}
void hasTwoParams(int, int);
void MaybeThrows();
void DoesntThrow() noexcept;
@@ -994,5 +987,3 @@ TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) {
} // namespace gmock_function_mocker_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4503
+2 -3
View File
@@ -40,7 +40,6 @@
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
@@ -57,7 +56,7 @@
#include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION_
#ifdef GTEST_OS_CYGWIN
#if GTEST_OS_CYGWIN
#include <sys/types.h> // For ssize_t. NOLINT
#endif
@@ -168,7 +167,7 @@ TEST(KindOfTest, Integer) {
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT
#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || defined(GTEST_OS_CYGWIN)
#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
// ssize_t is not defined on Windows and possibly some other OSes.
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT
#endif
@@ -31,16 +31,15 @@
//
// This file tests some commonly used argument matchers.
#include <cmath>
#include <limits>
#include <memory>
#include <string>
#include "test/gmock-matchers_test.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)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing {
namespace gmock_matchers_test {
@@ -955,7 +954,7 @@ TEST(AllArgsTest, WorksForNonTuple) {
class AllArgsHelper {
public:
AllArgsHelper() = default;
AllArgsHelper() {}
MOCK_METHOD2(Helper, int(char x, int y));
@@ -976,7 +975,7 @@ TEST(AllArgsTest, WorksInWithClause) {
class OptionalMatchersHelper {
public:
OptionalMatchersHelper() = default;
OptionalMatchersHelper() {}
MOCK_METHOD0(NoArgs, int());
@@ -1038,7 +1037,7 @@ class FloatingPointTest : public testing::Test {
Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
further_from_infinity_(
Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
max_(std::numeric_limits<RawType>::max()),
max_(Floating::Max()),
nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {}
@@ -1513,4 +1512,6 @@ TEST(AnyOfTest, WorksOnMoveOnlyType) {
} // namespace gmock_matchers_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
@@ -31,18 +31,15 @@
//
// This file tests some commonly used argument matchers.
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
#include "test/gmock-matchers_test.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)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing {
namespace gmock_matchers_test {
@@ -589,8 +586,8 @@ TEST(MatcherCastTest, ValueIsNotCopied) {
class Base {
public:
virtual ~Base() = default;
Base() = default;
virtual ~Base() {}
Base() {}
private:
Base(const Base&) = delete;
@@ -865,7 +862,7 @@ struct Type {
};
TEST(TypedEqTest, HasSpecifiedType) {
// Verifies that the type of TypedEq<T>(v) is Matcher<T>.
// Verfies that the type of TypedEq<T>(v) is Matcher<T>.
Type<Matcher<int>>::IsTypeOf(TypedEq<int>(5));
Type<Matcher<double>>::IsTypeOf(TypedEq<double>(5));
}
@@ -986,30 +983,6 @@ TEST(ComparisonBaseTest, WorksWithMoveOnly) {
helper.Call(MoveOnly(1));
}
TEST(IsEmptyTest, MatchesContainer) {
const Matcher<std::vector<int>> m = IsEmpty();
std::vector<int> a = {};
std::vector<int> b = {1};
EXPECT_TRUE(m.Matches(a));
EXPECT_FALSE(m.Matches(b));
}
TEST(IsEmptyTest, MatchesStdString) {
const Matcher<std::string> m = IsEmpty();
std::string a = "z";
std::string b = "";
EXPECT_FALSE(m.Matches(a));
EXPECT_TRUE(m.Matches(b));
}
TEST(IsEmptyTest, MatchesCString) {
const Matcher<const char*> m = IsEmpty();
const char a[] = "";
const char b[] = "x";
EXPECT_TRUE(m.Matches(a));
EXPECT_FALSE(m.Matches(b));
}
// Tests that IsNull() matches any NULL pointer of any type.
TEST(IsNullTest, MatchesNullPointer) {
Matcher<int*> m1 = IsNull();
@@ -1531,7 +1504,7 @@ TEST(PairTest, MatchesCorrectly) {
EXPECT_THAT(p, Pair(25, "foo"));
EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
// 'first' doesn't match, but 'second' matches.
// 'first' doesnt' match, but 'second' matches.
EXPECT_THAT(p, Not(Pair(42, "foo")));
EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
@@ -1546,7 +1519,7 @@ TEST(PairTest, MatchesCorrectly) {
TEST(PairTest, WorksWithMoveOnly) {
pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
p.second = std::make_unique<int>(7);
p.second.reset(new int(7));
EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
}
@@ -1711,21 +1684,6 @@ TEST(FieldsAreTest, StructuredBindings) {
};
EXPECT_THAT(MyVarType16{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType17 {
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q;
};
EXPECT_THAT(MyVarType17{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType18 {
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r;
};
EXPECT_THAT(MyVarType18{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType19 {
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s;
};
EXPECT_THAT(MyVarType19{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0));
}
#endif
@@ -1806,13 +1764,11 @@ TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {
EXPECT_FALSE(m1.Matches("invalid base64"));
EXPECT_FALSE(m1.Matches("aGVsbG8gd29ybGQ=")); // hello world
EXPECT_TRUE(m1.Matches("aGVsbG8gd29ybGQh")); // hello world!
EXPECT_TRUE(m1.Matches("+/-_IQ")); // \xfb\xff\xbf!
const Matcher<const std::string&> m2 = WhenBase64Unescaped(EndsWith("!"));
EXPECT_FALSE(m2.Matches("invalid base64"));
EXPECT_FALSE(m2.Matches("aGVsbG8gd29ybGQ=")); // hello world
EXPECT_TRUE(m2.Matches("aGVsbG8gd29ybGQh")); // hello world!
EXPECT_TRUE(m2.Matches("+/-_IQ")); // \xfb\xff\xbf!
#if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<const internal::StringView&> m3 =
@@ -1820,7 +1776,6 @@ TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {
EXPECT_FALSE(m3.Matches("invalid base64"));
EXPECT_FALSE(m3.Matches("aGVsbG8gd29ybGQ=")); // hello world
EXPECT_TRUE(m3.Matches("aGVsbG8gd29ybGQh")); // hello world!
EXPECT_TRUE(m3.Matches("+/-_IQ")); // \xfb\xff\xbf!
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
@@ -2358,4 +2313,6 @@ TEST(PolymorphicMatcherTest, CanAccessImpl) {
} // namespace gmock_matchers_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
@@ -31,23 +31,13 @@
//
// This file tests some commonly used argument matchers.
#include <algorithm>
#include <array>
#include <deque>
#include <forward_list>
#include <iterator>
#include <list>
#include <memory>
#include <ostream>
#include <string>
#include <tuple>
#include <vector>
#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)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
@@ -1192,8 +1182,8 @@ TEST(SizeIsTest, WorksWithMinimalistCustomType) {
TEST(SizeIsTest, CanDescribeSelf) {
Matcher<vector<int>> m = SizeIs(2);
EXPECT_EQ("has a size that is equal to 2", Describe(m));
EXPECT_EQ("has a size that isn't equal to 2", DescribeNegation(m));
EXPECT_EQ("size is equal to 2", Describe(m));
EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
}
TEST(SizeIsTest, ExplainsResult) {
@@ -1836,8 +1826,8 @@ TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
}
TEST(UnorderedElementsAreArrayTest, VectorBool) {
const bool a[] = {false, true, false, true, true};
const bool b[] = {true, false, true, true, false};
const bool a[] = {0, 1, 0, 1, 1};
const bool b[] = {1, 0, 1, 1, 0};
std::vector<bool> expected(std::begin(a), std::end(a));
std::vector<bool> actual(std::begin(b), std::end(b));
StringMatchResultListener listener;
@@ -2788,7 +2778,7 @@ TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
class NativeArrayPassedAsPointerAndSize {
public:
NativeArrayPassedAsPointerAndSize() = default;
NativeArrayPassedAsPointerAndSize() {}
MOCK_METHOD(void, Helper, (int* array, int size));
@@ -3134,4 +3124,6 @@ TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
} // namespace gmock_matchers_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
+16 -34
View File
@@ -31,19 +31,13 @@
//
// This file tests some commonly used argument matchers.
#include <array>
#include <memory>
#include <ostream>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#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)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
@@ -208,7 +202,7 @@ TEST(IsTrueTest, IsTrueIsFalse) {
EXPECT_THAT(nonnull_unique, Not(IsFalse()));
}
#ifdef GTEST_HAS_TYPED_TEST
#if GTEST_HAS_TYPED_TEST
// Tests ContainerEq with different container types, and
// different element types.
@@ -869,7 +863,7 @@ TEST(ArgsTest, AcceptsOneTemplateArg) {
}
TEST(ArgsTest, AcceptsTwoTemplateArgs) {
const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<0, 1>(Lt())));
EXPECT_THAT(t, (Args<1, 2>(Lt())));
@@ -877,13 +871,13 @@ TEST(ArgsTest, AcceptsTwoTemplateArgs) {
}
TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<0, 0>(Eq())));
EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
}
TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<2, 0>(Gt())));
EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
}
@@ -898,7 +892,7 @@ TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
}
TEST(ArgsTest, CanBeNested) {
const std::tuple<short, int, long, int> t(short{4}, 5, 6L, 6); // NOLINT
const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
}
@@ -1567,7 +1561,7 @@ TEST(AnyOfArrayTest, Matchers) {
}
TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {
// AnyOfArray and AllOfArray use the same underlying template-template,
// AnyOfArray and AllOfArry use the same underlying template-template,
// thus it is sufficient to test one here.
const std::vector<int> v0{};
const std::vector<int> v1{1};
@@ -1621,20 +1615,6 @@ TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
EXPECT_THAT(p, Not(UniquePointee(2)));
}
MATCHER(EnsureNoUnusedButMarkedUnusedWarning, "") { return (arg % 2) == 0; }
TEST(MockMethodMockFunctionTest, EnsureNoUnusedButMarkedUnusedWarning) {
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic error "-Wused-but-marked-unused"
#endif
// https://github.com/google/googletest/issues/4055
EXPECT_THAT(0, EnsureNoUnusedButMarkedUnusedWarning());
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}
#if GTEST_HAS_EXCEPTIONS
// std::function<void()> is used below for compatibility with older copies of
@@ -1798,8 +1778,8 @@ TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
{
Matcher<uint64_t> inner = Eq(10);
Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
EXPECT_TRUE(matcher.Matches([]() { throw (uint32_t)10; }));
EXPECT_FALSE(matcher.Matches([]() { throw (uint32_t)11; }));
EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
}
}
@@ -1820,4 +1800,6 @@ TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
} // namespace gmock_matchers_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
+3 -3
View File
@@ -148,9 +148,9 @@ class GreaterThanMatcher : public MatcherInterface<T> {
};
// Names and instantiates a new instance of GTestMatcherTestP.
#define INSTANTIATE_GTEST_MATCHER_TEST_P(TestSuite) \
using TestSuite##P = GTestMatcherTestP; \
INSTANTIATE_TEST_SUITE_P(MatcherInterface, TestSuite##P, Values(false)); \
#define INSTANTIATE_GTEST_MATCHER_TEST_P(TestSuite) \
using TestSuite##P = GTestMatcherTestP; \
INSTANTIATE_TEST_SUITE_P(MatcherInterface, TestSuite##P, Values(false)); \
INSTANTIATE_TEST_SUITE_P(GtestMatcher, TestSuite##P, Values(true))
class GTestMatcherTestP : public testing::TestWithParam<bool> {
+11 -11
View File
@@ -31,23 +31,22 @@
//
// This file tests the built-in actions in gmock-actions.h.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4577)
#endif
#include "gmock/gmock-more-actions.h"
#include <algorithm>
#include <functional>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4577)
namespace testing {
namespace gmock_more_actions_test {
@@ -677,7 +676,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) {
Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end());
std::string s;
a.Perform(std::make_tuple(true, std::back_inserter(s)));
a.Perform(std::make_tuple(true, back_inserter(s)));
EXPECT_EQ(letters, s);
}
@@ -983,7 +982,11 @@ TEST(DoAllTest, ImplicitlyConvertsActionArguments) {
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
// Also suppress C4503 decorated name length exceeded, name was truncated
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4503)
#endif
// Tests the ACTION*() macro family.
// Tests that ACTION() can define an action that doesn't reference the
@@ -1545,6 +1548,3 @@ TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
} // namespace gmock_more_actions_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4577
+4 -4
View File
@@ -40,7 +40,7 @@
// clash with ::testing::Mock.
class Mock {
public:
Mock() = default;
Mock() {}
MOCK_METHOD0(DoThis, void());
@@ -78,7 +78,7 @@ class CallsMockMethodInDestructor {
class Foo {
public:
virtual ~Foo() = default;
virtual ~Foo() {}
virtual void DoThis() = 0;
virtual int DoThat(bool flag) = 0;
@@ -86,7 +86,7 @@ class Foo {
class MockFoo : public Foo {
public:
MockFoo() = default;
MockFoo() {}
void Delete() { delete this; }
MOCK_METHOD0(DoThis, void());
@@ -109,7 +109,7 @@ class MockBar {
(a10 ? 'T' : 'F');
}
virtual ~MockBar() = default;
virtual ~MockBar() {}
const std::string& str() const { return str_; }
+56 -39
View File
@@ -98,7 +98,7 @@ class NonDefaultConstructible {
class MockA {
public:
MockA() = default;
MockA() {}
MOCK_METHOD1(DoA, void(int n));
MOCK_METHOD1(ReturnResult, Result(int n));
@@ -113,7 +113,7 @@ class MockA {
class MockB {
public:
MockB() = default;
MockB() {}
MOCK_CONST_METHOD0(DoB, int()); // NOLINT
MOCK_METHOD1(DoB, int(int n)); // NOLINT
@@ -125,7 +125,7 @@ class MockB {
class ReferenceHoldingMock {
public:
ReferenceHoldingMock() = default;
ReferenceHoldingMock() {}
MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
@@ -143,12 +143,12 @@ class ReferenceHoldingMock {
class CC {
public:
virtual ~CC() = default;
virtual ~CC() {}
virtual int Method() = 0;
};
class MockCC : public CC {
public:
MockCC() = default;
MockCC() {}
MOCK_METHOD0(Method, int());
@@ -739,12 +739,11 @@ TEST(ExpectCallTest, CatchesTooFewCalls) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
MockB b;
EXPECT_CALL(b, DoB(5)).Description("DoB Method").Times(AtLeast(2));
EXPECT_CALL(b, DoB(5)).Times(AtLeast(2));
b.DoB(5);
},
"Actual function \"DoB Method\" call count "
"doesn't match EXPECT_CALL(b, DoB(5))...\n"
"Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
" Expected: to be called at least twice\n"
" Actual: called once - unsatisfied and active");
}
@@ -804,40 +803,39 @@ TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
"to be called at least once");
}
#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
#if defined(__cplusplus) && __cplusplus >= 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.
TEST(ExpectCallTest, NonMoveableType) {
// Define a non-moveable result type.
struct NonMoveableStruct {
explicit NonMoveableStruct(int x_in) : x(x_in) {}
NonMoveableStruct(NonMoveableStruct&&) = delete;
struct Result {
explicit Result(int x_in) : x(x_in) {}
Result(Result&&) = delete;
int x;
};
static_assert(!std::is_move_constructible_v<NonMoveableStruct>);
static_assert(!std::is_copy_constructible_v<NonMoveableStruct>);
static_assert(!std::is_move_constructible_v<Result>);
static_assert(!std::is_copy_constructible_v<Result>);
static_assert(!std::is_move_assignable_v<NonMoveableStruct>);
static_assert(!std::is_copy_assignable_v<NonMoveableStruct>);
static_assert(!std::is_move_assignable_v<Result>);
static_assert(!std::is_copy_assignable_v<Result>);
// We should be able to use a callable that returns that result as both a
// OnceAction and an Action, whether the callable ignores arguments or not.
const auto return_17 = [] { return NonMoveableStruct(17); };
const auto return_17 = [] { return Result(17); };
static_cast<void>(OnceAction<NonMoveableStruct()>{return_17});
static_cast<void>(Action<NonMoveableStruct()>{return_17});
static_cast<void>(OnceAction<Result()>{return_17});
static_cast<void>(Action<Result()>{return_17});
static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17});
static_cast<void>(Action<NonMoveableStruct(int)>{return_17});
static_cast<void>(OnceAction<Result(int)>{return_17});
static_cast<void>(Action<Result(int)>{return_17});
// It should be possible to return the result end to end through an
// EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
MockFunction<NonMoveableStruct()> mock;
MockFunction<Result()> mock;
EXPECT_CALL(mock, Call) //
.WillOnce(return_17) //
.WillRepeatedly(return_17);
@@ -1066,7 +1064,7 @@ TEST(UnexpectedCallTest, UnmatchedArguments) {
// Tests that Google Mock explains that an expectation with
// unsatisfied pre-requisites doesn't match the call.
TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
Sequence s1, s2;
MockB b;
EXPECT_CALL(b, DoB(1)).InSequence(s1);
@@ -1089,7 +1087,16 @@ TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
// Verifies that the failure message contains the two unsatisfied
// pre-requisites but not the satisfied one.
#ifdef GTEST_USES_POSIX_RE
#if GTEST_USES_PCRE
EXPECT_THAT(
r.message(),
ContainsRegex(
// PCRE has trouble using (.|\n) to match any character, but
// supports the (?s) prefix for using . to match any character.
"(?s)the following immediate pre-requisites are not satisfied:\n"
".*: pre-requisite #0\n"
".*: pre-requisite #1"));
#elif GTEST_USES_POSIX_RE
EXPECT_THAT(r.message(),
ContainsRegex(
// POSIX RE doesn't understand the (?s) prefix, but has no
@@ -1104,7 +1111,7 @@ TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
"the following immediate pre-requisites are not satisfied:"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
#endif // GTEST_USES_POSIX_RE
#endif // GTEST_USES_PCRE
b.DoB(1);
b.DoB(3);
@@ -1141,11 +1148,10 @@ TEST(ExcessiveCallTest, DoesDefaultAction) {
// When there is no ON_CALL(), the default value for the return type
// should be returned.
MockB b;
EXPECT_CALL(b, DoB(0)).Description("DoB Method").Times(0);
EXPECT_CALL(b, DoB(0)).Times(0);
int n = -1;
EXPECT_NONFATAL_FAILURE(
n = b.DoB(0),
"Mock function \"DoB Method\" called more times than expected");
EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
"Mock function called more times than expected");
EXPECT_EQ(0, n);
}
@@ -1153,11 +1159,10 @@ TEST(ExcessiveCallTest, DoesDefaultAction) {
// the failure message contains the argument values.
TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
MockA a;
EXPECT_CALL(a, DoA(_)).Description("DoA Method").Times(0);
EXPECT_CALL(a, DoA(_)).Times(0);
EXPECT_NONFATAL_FAILURE(
a.DoA(9),
"Mock function \"DoA Method\" called more times than expected - "
"returning directly.\n"
"Mock function called more times than expected - returning directly.\n"
" Function call: DoA(9)\n"
" Expected: to be never called\n"
" Actual: called once - over-saturated and active");
@@ -1771,11 +1776,16 @@ TEST(DeletingMockEarlyTest, Success2) {
// Suppresses warning on unreferenced formal parameter in MSVC with
// -W4.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
ACTION_P(Delete, ptr) { delete ptr; }
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
MockA* const a = new MockA;
@@ -1882,7 +1892,7 @@ struct Unprintable {
class MockC {
public:
MockC() = default;
MockC() {}
MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
const Printable& x, Unprintable y));
@@ -2049,9 +2059,9 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
"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/"
"https://github.com/google/googletest/blob/master/docs/"
"gmock_cook_book.md#"
"knowing-when-to-expect-useoncall for details.";
"knowing-when-to-expect for details.";
// A void-returning function.
CaptureStdout();
@@ -2122,7 +2132,7 @@ void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
class LogTestHelper {
public:
LogTestHelper() = default;
LogTestHelper() {}
MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
@@ -2589,7 +2599,14 @@ TEST(ParameterlessExpectationsTest,
} // namespace
} // namespace testing
// Allows the user to define their own main and then invoke gmock_main
// from it. This might be necessary on some platforms which require
// specific setup and teardown.
#if GMOCK_RENAME_MAIN
int gmock_main(int argc, char** argv) {
#else
int main(int argc, char** argv) {
#endif // GMOCK_RENAME_MAIN
testing::InitGoogleMock(&argc, argv);
// Ensures that the tests pass no matter what value of
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
-2
View File
@@ -29,8 +29,6 @@
// Tests Google Mock's functionality that depends on exceptions.
#include <exception>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
+25 -34
View File
@@ -54,59 +54,50 @@ class GMockLeakTest(gmock_test_utils.TestCase):
def testCatchesLeakedMockByDefault(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(
TEST_WITH_EXPECT_CALL, env=environ
).exit_code,
)
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL,
env=environ).exit_code)
self.assertNotEqual(
0, gmock_test_utils.Subprocess(TEST_WITH_ON_CALL, env=environ).exit_code
)
0,
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL,
env=environ).exit_code)
def testDoesNotCatchLeakedMockWhenDisabled(self):
self.assertEqual(
self.assertEquals(
0,
gmock_test_utils.Subprocess(
TEST_WITH_EXPECT_CALL + ['--gmock_catch_leaked_mocks=0'],
env=environ,
).exit_code,
)
self.assertEqual(
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
['--gmock_catch_leaked_mocks=0'],
env=environ).exit_code)
self.assertEquals(
0,
gmock_test_utils.Subprocess(
TEST_WITH_ON_CALL + ['--gmock_catch_leaked_mocks=0'], env=environ
).exit_code,
)
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
['--gmock_catch_leaked_mocks=0'],
env=environ).exit_code)
def testCatchesLeakedMockWhenEnabled(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(
TEST_WITH_EXPECT_CALL + ['--gmock_catch_leaked_mocks'], env=environ
).exit_code,
)
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
['--gmock_catch_leaked_mocks'],
env=environ).exit_code)
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(
TEST_WITH_ON_CALL + ['--gmock_catch_leaked_mocks'], env=environ
).exit_code,
)
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
['--gmock_catch_leaked_mocks'],
env=environ).exit_code)
def testCatchesLeakedMockWhenEnabledWithExplictFlagValue(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(
TEST_WITH_EXPECT_CALL + ['--gmock_catch_leaked_mocks=1'],
env=environ,
).exit_code,
)
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
['--gmock_catch_leaked_mocks=1'],
env=environ).exit_code)
def testCatchesMultipleLeakedMocks(self):
self.assertNotEqual(
0,
gmock_test_utils.Subprocess(
TEST_MULTIPLE_LEAKS + ['--gmock_catch_leaked_mocks'], env=environ
).exit_code,
)
gmock_test_utils.Subprocess(TEST_MULTIPLE_LEAKS +
['--gmock_catch_leaked_mocks'],
env=environ).exit_code)
if __name__ == '__main__':
+2 -2
View File
@@ -40,13 +40,13 @@ using ::testing::Return;
class FooInterface {
public:
virtual ~FooInterface() = default;
virtual ~FooInterface() {}
virtual void DoThis() = 0;
};
class MockFoo : public FooInterface {
public:
MockFoo() = default;
MockFoo() {}
MOCK_METHOD0(DoThis, void());
+12 -7
View File
@@ -116,7 +116,7 @@
#include "gmock/gmock.h"
#ifndef GTEST_OS_WINDOWS_MOBILE
#if !GTEST_OS_WINDOWS_MOBILE
#include <errno.h>
#endif
@@ -181,7 +181,7 @@ using testing::WithArg;
using testing::WithArgs;
using testing::WithoutArgs;
#ifndef GTEST_OS_WINDOWS_MOBILE
#if !GTEST_OS_WINDOWS_MOBILE
using testing::SetErrnoAndReturn;
#endif
@@ -194,7 +194,7 @@ using testing::MatchesRegex;
class Interface {
public:
virtual ~Interface() = default;
virtual ~Interface() {}
virtual void VoidFromString(char* str) = 0;
virtual char* StringFromString(char* str) = 0;
virtual int IntFromString(char* str) = 0;
@@ -208,7 +208,7 @@ class Interface {
class Mock : public Interface {
public:
Mock() = default;
Mock() {}
MOCK_METHOD1(VoidFromString, void(char* str));
MOCK_METHOD1(StringFromString, char*(char* str));
@@ -306,7 +306,7 @@ TEST(LinkTest, TestSetArrayArgument) {
mock.VoidFromString(&ch);
}
#ifndef GTEST_OS_WINDOWS_MOBILE
#if !GTEST_OS_WINDOWS_MOBILE
// Tests the linkage of the SetErrnoAndReturn action.
TEST(LinkTest, TestSetErrnoAndReturn) {
@@ -423,7 +423,10 @@ TEST(LinkTest, TestThrow) {
// the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
// Tests the linkage of actions created using ACTION macro.
namespace {
@@ -456,7 +459,9 @@ ACTION_P2(ReturnEqualsEitherOf, first, second) {
}
} // namespace
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
TEST(LinkTest, TestActionP2Macro) {
Mock mock;
+4 -11
View File
@@ -39,7 +39,7 @@ gmock_output_test.py
"""
from io import open # pylint: disable=redefined-builtin, g-importing-member
from io import open # pylint: disable=redefined-builtin, g-importing-member
import os
import re
import sys
@@ -159,22 +159,15 @@ class GMockOutputTest(gmock_test_utils.TestCase):
golden_file = open(GOLDEN_PATH, 'rb')
golden = golden_file.read().decode('utf-8')
golden_file.close()
# On Windows the repository might have been checked out with \r\n line
# endings, so normalize it here.
golden = ToUnixLineEnding(golden)
# The normalized output should match the golden file.
self.assertEqual(golden, output)
# The raw output should contain 2 leaked mock object errors for
# test GMockOutputTest.CatchesLeakedMocks.
self.assertEqual(
[
'GMockOutputTest.CatchesLeakedMocks',
'GMockOutputTest.CatchesLeakedMocks',
],
leaky_tests,
)
self.assertEqual(['GMockOutputTest.CatchesLeakedMocks',
'GMockOutputTest.CatchesLeakedMocks'],
leaky_tests)
if __name__ == '__main__':
+8 -3
View File
@@ -38,7 +38,10 @@
#include "gtest/gtest.h"
// Silence C4100 (unreferenced formal parameter)
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
using testing::_;
using testing::AnyNumber;
@@ -52,7 +55,7 @@ using testing::Value;
class MockFoo {
public:
MockFoo() = default;
MockFoo() {}
MOCK_METHOD3(Bar, char(const std::string& s, int i, double x));
MOCK_METHOD2(Bar2, bool(int x, int y));
@@ -283,4 +286,6 @@ int main(int argc, char** argv) {
return RUN_ALL_TESTS();
}
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
+5 -23
View File
@@ -40,7 +40,6 @@ FILE:#: EXPECT_CALL(foo_, Bar2(0, _))...
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnexpectedCall
[ RUN ] GMockOutputTest.UnexpectedCallToVoidFunction
unknown file: Failure
@@ -54,7 +53,6 @@ FILE:#: EXPECT_CALL(foo_, Bar3(0, _))...
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction
[ RUN ] GMockOutputTest.ExcessiveCall
FILE:#: Failure
@@ -63,7 +61,6 @@ Mock function called more times than expected - returning default value.
Returns: false
Expected: to be called once
Actual: called twice - over-saturated and active
[ FAILED ] GMockOutputTest.ExcessiveCall
[ RUN ] GMockOutputTest.ExcessiveCallToVoidFunction
FILE:#: Failure
@@ -71,7 +68,6 @@ Mock function called more times than expected - returning directly.
Function call: Bar3(0, 1)
Expected: to be called once
Actual: called twice - over-saturated and active
[ FAILED ] GMockOutputTest.ExcessiveCallToVoidFunction
[ RUN ] GMockOutputTest.UninterestingCall
@@ -79,14 +75,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 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.
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/master/docs/gmock_cook_book.md#knowing-when-to-expect 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 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.
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/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure
@@ -108,7 +104,6 @@ FILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(0, 0))...
Actual: 1
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.RetiredExpectation
[ RUN ] GMockOutputTest.UnsatisfiedPrerequisite
unknown file: Failure
@@ -130,7 +125,6 @@ FILE:#: pre-requisite #0
(end of pre-requisites)
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisite
[ RUN ] GMockOutputTest.UnsatisfiedPrerequisites
unknown file: Failure
@@ -153,7 +147,6 @@ FILE:#: pre-requisite #1
(end of pre-requisites)
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisites
[ RUN ] GMockOutputTest.UnsatisfiedWith
FILE:#: Failure
@@ -161,19 +154,16 @@ Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(_, _))...
Expected args: are a pair where the first >= the second
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedWith
[ RUN ] GMockOutputTest.UnsatisfiedExpectation
FILE:#: Failure
Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(0, _))...
Expected: to be called twice
Actual: called once - unsatisfied and active
FILE:#: Failure
Actual function call count doesn't match EXPECT_CALL(foo_, Bar(_, _, _))...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedExpectation
[ RUN ] GMockOutputTest.MismatchArguments
unknown file: Failure
@@ -190,7 +180,6 @@ FILE:#: EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0)))...
Actual: -0.1
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.MismatchArguments
[ RUN ] GMockOutputTest.MismatchWith
unknown file: Failure
@@ -205,7 +194,6 @@ FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
Actual: don't match
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.MismatchWith
[ RUN ] GMockOutputTest.MismatchArgumentsAndWith
unknown file: Failure
@@ -222,7 +210,6 @@ FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
Actual: don't match
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.MismatchArgumentsAndWith
[ RUN ] GMockOutputTest.UnexpectedCallWithDefaultAction
unknown file: Failure
@@ -240,7 +227,6 @@ FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
Actual: 0
Expected: to be called once
Actual: never called - unsatisfied and active
unknown file: Failure
Unexpected mock function call - taking default action specified at:
@@ -256,7 +242,6 @@ FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
Actual: 0
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnexpectedCallWithDefaultAction
[ RUN ] GMockOutputTest.ExcessiveCallWithDefaultAction
FILE:#: Failure
@@ -266,7 +251,6 @@ FILE:#:
Returns: true
Expected: to be called once
Actual: called twice - over-saturated and active
FILE:#: Failure
Mock function called more times than expected - taking default action specified at:
FILE:#:
@@ -274,7 +258,6 @@ FILE:#:
Returns: false
Expected: to be called once
Actual: called twice - over-saturated and active
[ FAILED ] GMockOutputTest.ExcessiveCallWithDefaultAction
[ RUN ] GMockOutputTest.UninterestingCallWithDefaultAction
@@ -283,14 +266,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 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.
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/master/docs/gmock_cook_book.md#knowing-when-to-expect 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 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.
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/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
@@ -309,8 +292,7 @@ Stack trace:
FILE:#: Failure
Value of: (std::pair<int, bool>(42, true))
Expected: is pair (first: is >= 48, second: true)
Actual: (42, true) (of type std::pair<int,bool>)
Actual: (42, true) (of type std::pair<int, bool>)
[ FAILED ] GMockOutputTest.PrintsMatcher
[ FAILED ] GMockOutputTest.UnexpectedCall
[ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction
+1 -1
View File
@@ -174,6 +174,6 @@ TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
// Makes sure Google Mock flags can be accessed in code.
TEST(FlagTest, IsAccessibleInCode) {
bool dummy =
GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose).empty();
GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose) == "";
(void)dummy; // Avoids the "unused local variable" warning.
}
+5
View File
@@ -77,6 +77,9 @@ def GetExitStatus(exit_code):
return -1
# Suppresses the "Invalid const name" lint complaint
# pylint: disable-msg=C6409
# Exposes utilities from gtest_test_utils.
Subprocess = gtest_test_utils.Subprocess
TestCase = gtest_test_utils.TestCase
@@ -84,6 +87,8 @@ environ = gtest_test_utils.environ
SetEnvVar = gtest_test_utils.SetEnvVar
PREMATURE_EXIT_FILE_ENV_VAR = gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR
# pylint: enable-msg=C6409
def Main():
"""Runs the unit test."""
+18 -26
View File
@@ -46,9 +46,14 @@ endif()
# Project version:
cmake_minimum_required(VERSION 3.13)
cmake_minimum_required(VERSION 3.5)
cmake_policy(SET CMP0048 NEW)
project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
if (POLICY CMP0063) # Visibility
cmake_policy(SET CMP0063 NEW)
endif (POLICY CMP0063)
if (COMMAND set_up_hermetic_build)
set_up_hermetic_build()
endif()
@@ -95,14 +100,12 @@ if (INSTALL_GTEST)
set(version_file "${generated_dir}/${cmake_package_name}ConfigVersion.cmake")
write_basic_package_version_file(${version_file} VERSION ${GOOGLETEST_VERSION} COMPATIBILITY AnyNewerVersion)
install(EXPORT ${targets_export_name}
COMPONENT "${PROJECT_NAME}"
NAMESPACE ${cmake_package_name}::
DESTINATION ${cmake_files_install_dir})
set(config_file "${generated_dir}/${cmake_package_name}Config.cmake")
configure_package_config_file("${gtest_SOURCE_DIR}/cmake/Config.cmake.in"
"${config_file}" INSTALL_DESTINATION ${cmake_files_install_dir})
install(FILES ${version_file} ${config_file}
COMPONENT "${PROJECT_NAME}"
DESTINATION ${cmake_files_install_dir})
endif()
@@ -122,31 +125,20 @@ include_directories(${gtest_build_include_dirs})
# aggressive about warnings.
cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
set_target_properties(gtest PROPERTIES VERSION ${GOOGLETEST_VERSION})
if(GTEST_HAS_ABSL)
target_compile_definitions(gtest PUBLIC GTEST_HAS_ABSL=1)
target_link_libraries(gtest PUBLIC
absl::failure_signal_handler
absl::stacktrace
absl::symbolize
absl::flags_parse
absl::flags_reflection
absl::flags_usage
absl::strings
absl::any
absl::optional
absl::variant
re2::re2
)
endif()
cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
string(REPLACE ";" "$<SEMICOLON>" dirs "${gtest_build_include_dirs}")
target_include_directories(gtest SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gtest_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
# If the CMake version supports it, attach header directory information
# to the targets for when we are part of a parent build (ie being pulled
# in via add_subdirectory() rather than being a standalone build).
if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
string(REPLACE ";" "$<SEMICOLON>" dirs "${gtest_build_include_dirs}")
target_include_directories(gtest SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gtest_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
endif()
if(CMAKE_SYSTEM_NAME MATCHES "QNX")
target_link_libraries(gtest PUBLIC regex)
endif()
+20 -34
View File
@@ -9,7 +9,7 @@ depends on which build system you use, and is usually straightforward.
### Build with CMake
GoogleTest comes with a CMake build script
([CMakeLists.txt](https://github.com/google/googletest/blob/main/CMakeLists.txt))
([CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt))
that can be used on a wide range of platforms ("C" stands for cross-platform.).
If you don't have CMake installed already, you can download it for free from
<http://www.cmake.org/>.
@@ -25,7 +25,7 @@ When building GoogleTest as a standalone project, the typical workflow starts
with
```
git clone https://github.com/google/googletest.git -b v1.13.0
git clone https://github.com/google/googletest.git -b release-1.11.0
cd googletest # Main directory of the cloned repository.
mkdir build # Create a directory to hold the build output.
cd build
@@ -94,7 +94,7 @@ include(FetchContent)
FetchContent_Declare(
googletest
# Specify the commit you depend on and update it regularly.
URL https://github.com/google/googletest/archive/5376968f6948923e2411081fd9372e71a59d8e77.zip
URL https://github.com/google/googletest/archive/e2239ee6043f73722e7aa812a459f54a28552929.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
@@ -124,12 +124,12 @@ match the project in which it is included.
#### C++ Standard Version
An environment that supports C++14 is required in order to successfully build
An environment that supports C++11 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 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.
project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command. 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.
### Tweaking GoogleTest
@@ -140,27 +140,23 @@ command line. Generally, these macros are named like `GTEST_XYZ` and you define
them to either 1 or 0 to enable or disable a certain feature.
We list the most frequently used macros below. For a complete list, see file
[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/main/googletest/include/gtest/internal/gtest-port.h).
[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-port.h).
### Multi-threaded Tests
GoogleTest is thread-safe where the pthread library is available. After
`#include <gtest/gtest.h>`, you can check the
`#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
```
-DGTEST_HAS_PTHREAD=1
```
-DGTEST_HAS_PTHREAD=1
or
```
-DGTEST_HAS_PTHREAD=0
```
-DGTEST_HAS_PTHREAD=0
When GoogleTest uses pthread, you may need to add flags to your compiler and/or
linker to select the pthread library, or you'll get link errors. If you use the
@@ -176,27 +172,23 @@ as a DLL on Windows) if you prefer.
To compile *gtest* as a shared library, add
```
-DGTEST_CREATE_SHARED_LIBRARY=1
```
-DGTEST_CREATE_SHARED_LIBRARY=1
to the compiler flags. You'll also need to tell the linker to produce a shared
library instead - consult your linker's manual for how to do it.
To compile your *tests* that use the gtest shared library, add
```
-DGTEST_LINKED_AS_SHARED_LIBRARY=1
```
-DGTEST_LINKED_AS_SHARED_LIBRARY=1
to the compiler flags.
Note: while the above steps aren't technically necessary today when using some
compilers (e.g. GCC), they may become necessary in the future, if we decide to
improve the speed of loading the library (see
<https://gcc.gnu.org/wiki/Visibility> for details). Therefore you are
recommended to always add the above flags when using GoogleTest as a shared
library. Otherwise a future release of GoogleTest may break your build script.
<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended
to always add the above flags when using GoogleTest as a shared library.
Otherwise a future release of GoogleTest may break your build script.
### Avoiding Macro Name Clashes
@@ -208,9 +200,7 @@ rename its macro to avoid the conflict.
Specifically, if both GoogleTest and some other code define macro FOO, you can
add
```
-DGTEST_DONT_DEFINE_FOO=1
```
-DGTEST_DONT_DEFINE_FOO=1
to the compiler flags to tell GoogleTest to change the macro's name from `FOO`
to `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`,
@@ -218,14 +208,10 @@ to `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`,
`EXPECT_FALSE`, `EXPECT_TRUE`, `FAIL`, `SUCCEED`, `TEST`, or `TEST_F`. For
example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
```
GTEST_TEST(SomeTest, DoesThis) { ... }
```
GTEST_TEST(SomeTest, DoesThis) { ... }
instead of
```
TEST(SomeTest, DoesThis) { ... }
```
TEST(SomeTest, DoesThis) { ... }
in order to define a test.
+61 -51
View File
@@ -12,14 +12,17 @@
# Test and Google Mock's option() definitions, and thus must be
# called *after* the options have been defined.
if (POLICY CMP0054)
cmake_policy(SET CMP0054 NEW)
endif (POLICY CMP0054)
# Tweaks CMake's default compiler/linker settings to suit Google Test's needs.
#
# This must be a macro(), as inside a function string() can only
# update variables in the function scope.
macro(fix_default_compiler_settings_)
if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC|Clang")
# For MSVC and Clang, CMake sets certain flags to defaults we want to
# override.
if (MSVC)
# For MSVC, CMake sets certain flags to defaults we want to override.
# This replacement code is taken from sample in the CMake Wiki at
# https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace.
foreach (flag_var
@@ -36,10 +39,6 @@ macro(fix_default_compiler_settings_)
# on CRT DLLs being available. CMake always defaults to using shared
# CRT libraries, so we override that default here.
string(REPLACE "/MD" "-MT" ${flag_var} "${${flag_var}}")
# When using Ninja with Clang, static builds pass -D_DLL on Windows.
# This is incorrect and should not happen, so we fix that here.
string(REPLACE "-D_DLL" "" ${flag_var} "${${flag_var}}")
endif()
# We prefer more strict warning checking for building Google Test.
@@ -83,27 +82,15 @@ macro(config_compiler_and_linker)
# http://stackoverflow.com/questions/3232669 explains the issue.
set(cxx_base_flags "${cxx_base_flags} -wd4702")
# Ensure MSVC treats source files as UTF-8 encoded.
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
set(cxx_base_flags "${cxx_base_flags} -utf-8")
endif()
if (CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
set(cxx_base_flags "${cxx_base_flags} /fp:precise -Wno-inconsistent-missing-override -Wno-microsoft-exception-spec -Wno-unused-function -Wno-unused-but-set-variable")
endif()
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR
CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
set(cxx_base_flags "-Wall -Wshadow -Wconversion -Wundef")
set(cxx_base_flags "${cxx_base_flags} -utf-8")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(cxx_base_flags "-Wall -Wshadow -Wconversion")
set(cxx_exception_flags "-fexceptions")
set(cxx_no_exception_flags "-fno-exceptions")
set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Winline -Wredundant-decls")
set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Wchar-subscripts -Winline -Wredundant-decls")
set(cxx_no_rtti_flags "-fno-rtti")
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(cxx_strict_flags "${cxx_strict_flags} -Wchar-subscripts")
endif()
if (CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
set(cxx_base_flags "${cxx_base_flags} -Wno-implicit-float-size-conversion -ffp-model=precise")
endif()
elseif (CMAKE_COMPILER_IS_GNUCXX)
set(cxx_base_flags "-Wall -Wshadow -Wundef")
set(cxx_base_flags "-Wall -Wshadow")
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0)
set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else")
endif()
@@ -173,8 +160,7 @@ function(cxx_library_with_type name type cxx_flags)
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")
PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
# make PDBs match library name
get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX)
set_target_properties(${name}
@@ -188,14 +174,23 @@ function(cxx_library_with_type name type cxx_flags)
set_target_properties(${name}
PROPERTIES
COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1")
target_compile_definitions(${name} INTERFACE
$<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
if (NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
target_compile_definitions(${name} INTERFACE
$<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
endif()
endif()
if (DEFINED GTEST_HAS_PTHREAD)
target_link_libraries(${name} PUBLIC Threads::Threads)
if ("${CMAKE_VERSION}" VERSION_LESS "3.1.0")
set(threads_spec ${CMAKE_THREAD_LIBS_INIT})
else()
set(threads_spec Threads::Threads)
endif()
target_link_libraries(${name} PUBLIC ${threads_spec})
endif()
target_compile_features(${name} PUBLIC cxx_std_14)
if (NOT "${CMAKE_VERSION}" VERSION_LESS "3.8")
target_compile_features(${name} PUBLIC cxx_std_11)
endif()
endfunction()
########################################################################
@@ -247,7 +242,14 @@ function(cxx_executable name dir libs)
${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN})
endfunction()
find_package(Python3)
# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
if ("${CMAKE_VERSION}" VERSION_LESS "3.12.0")
find_package(PythonInterp)
else()
find_package(Python COMPONENTS Interpreter)
set(PYTHONINTERP_FOUND ${Python_Interpreter_FOUND})
set(PYTHON_EXECUTABLE ${Python_EXECUTABLE})
endif()
# cxx_test_with_flags(name cxx_flags libs srcs...)
#
@@ -273,22 +275,34 @@ endfunction()
# creates a Python test with the given name whose main module is in
# test/name.py. It does nothing if Python is not installed.
function(py_test name)
if (NOT Python3_Interpreter_FOUND)
return()
endif()
get_cmake_property(is_multi "GENERATOR_IS_MULTI_CONFIG")
set(build_dir "${CMAKE_CURRENT_BINARY_DIR}")
if (is_multi)
set(build_dir "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>")
endif()
add_test(NAME ${name}
COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${build_dir} ${ARGN})
# Make the Python import path consistent between Bazel and CMake.
set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})
if (PYTHONINTERP_FOUND)
if ("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" VERSION_GREATER 3.1)
if (CMAKE_CONFIGURATION_TYPES)
# Multi-configuration build generators as for Visual Studio save
# output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug,
# Release etc.), so we have to provide it here.
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
else (CMAKE_CONFIGURATION_TYPES)
# Single-configuration build generators like Makefile generators
# don't have subdirs below CMAKE_CURRENT_BINARY_DIR.
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
endif (CMAKE_CONFIGURATION_TYPES)
else()
# ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can
# directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
# only at ctest runtime (by calling ctest -c <Configuration>), so
# we have to escape $ to delay variable substitution here.
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
endif()
# Make the Python import path consistent between Bazel and CMake.
set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})
endif(PYTHONINTERP_FOUND)
endfunction()
# install_project(targets...)
@@ -297,12 +311,10 @@ endfunction()
function(install_project)
if(INSTALL_GTEST)
install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/"
COMPONENT "${PROJECT_NAME}"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
# Install the project targets.
install(TARGETS ${ARGN}
EXPORT ${targets_export_name}
COMPONENT "${PROJECT_NAME}"
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")
@@ -314,7 +326,6 @@ function(install_project)
get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY)
install(FILES
"${t_pdb_output_directory}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$<CONFIG:Debug>:${t_pdb_name_debug}>$<$<NOT:$<CONFIG:Debug>>:${t_pdb_name}>.pdb"
COMPONENT "${PROJECT_NAME}"
DESTINATION ${CMAKE_INSTALL_LIBDIR}
OPTIONAL)
endforeach()
@@ -325,7 +336,6 @@ function(install_project)
configure_file("${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in"
"${configured_pc}" @ONLY)
install(FILES "${configured_pc}"
COMPONENT "${PROJECT_NAME}"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
endforeach()
endif()
@@ -181,7 +181,7 @@ class GTEST_API_ AssertionResult {
// assertion's expectation). When nothing has been streamed into the
// object, returns an empty string.
const char* message() const {
return message_ != nullptr ? message_->c_str() : "";
return message_.get() != nullptr ? message_->c_str() : "";
}
// Deprecated; please use message() instead.
const char* failure_message() const { return message(); }
@@ -204,7 +204,7 @@ class GTEST_API_ AssertionResult {
private:
// Appends the contents of message to message_.
void AppendMessage(const Message& a_message) {
if (message_ == nullptr) message_ = ::std::make_unique<::std::string>();
if (message_.get() == nullptr) message_.reset(new ::std::string);
message_->append(a_message.GetString().c_str());
}
+3 -3
View File
@@ -51,7 +51,7 @@ GTEST_DECLARE_string_(death_test_style);
namespace testing {
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
namespace internal {
@@ -203,7 +203,7 @@ class GTEST_API_ ExitedWithCode {
const int exit_code_;
};
#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// Tests that an exit code describes an exit due to termination by a
// given signal.
class GTEST_API_ KilledBySignal {
@@ -328,7 +328,7 @@ class GTEST_API_ KilledBySignal {
// death tests are supported; otherwise they just issue a warning. This is
// useful when you are combining death test assertions with normal test
// assertions in one test.
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEATH(statement, regex)
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
+56 -23
View File
@@ -40,7 +40,6 @@
#define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
#include <atomic>
#include <functional>
#include <memory>
#include <ostream>
#include <string>
@@ -107,13 +106,13 @@ class MatchResultListener {
MatchResultListener& operator=(const MatchResultListener&) = delete;
};
inline MatchResultListener::~MatchResultListener() = default;
inline MatchResultListener::~MatchResultListener() {}
// An instance of a subclass of this knows how to describe itself as a
// matcher.
class GTEST_API_ MatcherDescriberInterface {
public:
virtual ~MatcherDescriberInterface() = default;
virtual ~MatcherDescriberInterface() {}
// Describes this matcher to an ostream. The function should print
// a verb phrase that describes the property a value matching this
@@ -179,6 +178,43 @@ class MatcherInterface : public MatcherDescriberInterface {
namespace internal {
struct AnyEq {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a == b;
}
};
struct AnyNe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a != b;
}
};
struct AnyLt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a < b;
}
};
struct AnyGt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a > b;
}
};
struct AnyLe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a <= b;
}
};
struct AnyGe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a >= b;
}
};
// A match result listener that ignores the explanation.
class DummyMatchResultListener : public MatchResultListener {
public:
@@ -494,7 +530,7 @@ template <>
class GTEST_API_ Matcher<const std::string&>
: public internal::MatcherBase<const std::string&> {
public:
Matcher() = default;
Matcher() {}
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<const std::string&>(impl) {}
@@ -516,7 +552,7 @@ template <>
class GTEST_API_ Matcher<std::string>
: public internal::MatcherBase<std::string> {
public:
Matcher() = default;
Matcher() {}
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<std::string>(impl) {}
@@ -544,7 +580,7 @@ template <>
class GTEST_API_ Matcher<const internal::StringView&>
: public internal::MatcherBase<const internal::StringView&> {
public:
Matcher() = default;
Matcher() {}
explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
: internal::MatcherBase<const internal::StringView&>(impl) {}
@@ -570,7 +606,7 @@ template <>
class GTEST_API_ Matcher<internal::StringView>
: public internal::MatcherBase<internal::StringView> {
public:
Matcher() = default;
Matcher() {}
explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
: internal::MatcherBase<internal::StringView>(impl) {}
@@ -722,53 +758,50 @@ class ComparisonBase {
};
template <typename Rhs>
class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>> {
class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
public:
explicit EqMatcher(const Rhs& rhs)
: ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>>(rhs) {}
: ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) {}
static const char* Desc() { return "is equal to"; }
static const char* NegatedDesc() { return "isn't equal to"; }
};
template <typename Rhs>
class NeMatcher
: public ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>> {
class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
public:
explicit NeMatcher(const Rhs& rhs)
: ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>>(rhs) {}
: ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) {}
static const char* Desc() { return "isn't equal to"; }
static const char* NegatedDesc() { return "is equal to"; }
};
template <typename Rhs>
class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>> {
class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
public:
explicit LtMatcher(const Rhs& rhs)
: ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>>(rhs) {}
: ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) {}
static const char* Desc() { return "is <"; }
static const char* NegatedDesc() { return "isn't <"; }
};
template <typename Rhs>
class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>> {
class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
public:
explicit GtMatcher(const Rhs& rhs)
: ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>>(rhs) {}
: ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) {}
static const char* Desc() { return "is >"; }
static const char* NegatedDesc() { return "isn't >"; }
};
template <typename Rhs>
class LeMatcher
: public ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>> {
class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
public:
explicit LeMatcher(const Rhs& rhs)
: ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>>(rhs) {}
: ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) {}
static const char* Desc() { return "is <="; }
static const char* NegatedDesc() { return "isn't <="; }
};
template <typename Rhs>
class GeMatcher
: public ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>> {
class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
public:
explicit GeMatcher(const Rhs& rhs)
: ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>>(rhs) {}
: ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) {}
static const char* Desc() { return "is >="; }
static const char* NegatedDesc() { return "isn't >="; }
};
@@ -809,7 +842,7 @@ class MatchesRegexMatcher {
template <class MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
const std::string s2(s);
const std::string& s2(s);
return full_match_ ? RE::FullMatch(s2, *regex_)
: RE::PartialMatch(s2, *regex_);
}
+2 -36
View File
@@ -50,19 +50,10 @@
#include <limits>
#include <memory>
#include <ostream>
#include <sstream>
#include <string>
#include "gtest/internal/gtest-port.h"
#ifdef GTEST_HAS_ABSL
#include <type_traits>
#include "absl/strings/internal/has_absl_stringify.h"
#include "absl/strings/str_cat.h"
#endif // GTEST_HAS_ABSL
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@@ -118,17 +109,8 @@ class GTEST_API_ Message {
*ss_ << str;
}
// Streams a non-pointer value to this object. If building a version of
// GoogleTest with ABSL, this overload is only enabled if the value does not
// have an AbslStringify definition.
template <typename T
#ifdef GTEST_HAS_ABSL
,
typename std::enable_if<
!absl::strings_internal::HasAbslStringify<T>::value, // NOLINT
int>::type = 0
#endif // GTEST_HAS_ABSL
>
// Streams a non-pointer value to this object.
template <typename T>
inline Message& operator<<(const T& val) {
// Some libraries overload << for STL containers. These
// overloads are defined in the global namespace instead of ::std.
@@ -149,22 +131,6 @@ class GTEST_API_ Message {
return *this;
}
#ifdef GTEST_HAS_ABSL
// Streams a non-pointer value with an AbslStringify definition to this
// object.
template <typename T,
typename std::enable_if<
absl::strings_internal::HasAbslStringify<T>::value, // NOLINT
int>::type = 0>
inline Message& operator<<(const T& val) {
// ::operator<< is needed here for a similar reason as with the non-Abseil
// version above
using ::operator<<;
*ss_ << absl::StrCat(val);
return *this;
}
#endif // GTEST_HAS_ABSL
// Streams a pointer value to this object.
//
// This function is an overload of the previous one. When you
+6 -42
View File
@@ -407,50 +407,9 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
return internal::CartesianProductHolder<Generator...>(g...);
}
// ConvertGenerator() wraps a parameter generator in order to cast each produced
// value through a known type before supplying it to the test suite
//
// Synopsis:
// ConvertGenerator<T>(gen)
// - returns a generator producing the same elements as generated by gen, but
// 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
//
// 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 {
// using TupleT = std::tuple<const char*, Color>;
// std::string animal;
// Color color;
// ParamType(TupleT t) : animal(std::get<0>(t)), color(std::get<1>(t)) {}
// };
// class AnimalTest
// : public testing::TestWithParam<ParamType> {...};
//
// TEST_P(AnimalTest, AnimalLooksNice) {...}
//
// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
// ConvertGenerator<ParamType::TupleT>(
// Combine(Values("cat", "dog"),
// Values(BLACK, WHITE))));
//
template <typename T>
internal::ParamConverterGenerator<T> ConvertGenerator(
internal::ParamGenerator<T> gen) {
return internal::ParamConverterGenerator<T>(gen);
}
#define TEST_P(test_suite_name, test_name) \
class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
: public test_suite_name, \
private ::testing::internal::GTestNonCopyable { \
: public test_suite_name { \
public: \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
void TestBody() override; \
@@ -470,6 +429,11 @@ internal::ParamConverterGenerator<T> ConvertGenerator(
return 0; \
} \
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
(const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete; \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \
const GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name) &) = delete; /* NOLINT */ \
}; \
int GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)::gtest_registering_dummy_ = \
+16 -129
View File
@@ -43,9 +43,6 @@
// 1. foo::PrintTo(const T&, ostream*)
// 2. operator<<(ostream&, const T&) defined in either foo or the
// global namespace.
// * Prefer AbslStringify(..) to operator<<(..), per https://abseil.io/tips/215.
// * Define foo::PrintTo(..) if the type already has AbslStringify(..), but an
// alternative presentation in test results is of interest.
//
// However if T is an STL-style container then it is printed element-wise
// unless foo::PrintTo(const T&, ostream*) is defined. Note that
@@ -111,14 +108,9 @@
#include <string>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>
#ifdef GTEST_HAS_ABSL
#include "absl/strings/internal/has_absl_stringify.h"
#include "absl/strings/str_cat.h"
#endif // GTEST_HAS_ABSL
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
@@ -213,13 +205,12 @@ struct StreamPrinter {
// Don't accept member pointers here. We'd print them via implicit
// conversion to bool, which isn't useful.
typename = typename std::enable_if<
!std::is_member_pointer<T>::value>::type>
// Only accept types for which we can find a streaming operator via
// 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)) {
!std::is_member_pointer<T>::value>::type,
// Only accept types for which we can find a streaming operator via
// ADL (possibly involving implicit conversions).
typename = decltype(std::declval<std::ostream&>()
<< std::declval<const T&>())>
static void PrintValue(const T& value, ::std::ostream* os) {
// Call streaming operator found by ADL, possibly with implicit conversions
// of the arguments.
*os << value;
@@ -267,18 +258,6 @@ struct ConvertibleToStringViewPrinter {
#endif
};
#ifdef GTEST_HAS_ABSL
struct ConvertibleToAbslStringifyPrinter {
template <
typename T,
typename = typename std::enable_if<
absl::strings_internal::HasAbslStringify<T>::value>::type> // NOLINT
static void PrintValue(const T& value, ::std::ostream* os) {
*os << absl::StrCat(value);
}
};
#endif // GTEST_HAS_ABSL
// Prints the given number of bytes in the given object to the given
// ostream.
GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
@@ -317,8 +296,8 @@ struct FindFirstPrinter<
// - Print containers (they have begin/end/etc).
// - Print function pointers.
// - Print object pointers.
// - Print protocol buffers.
// - Use the stream operator, if available.
// - Print protocol buffers.
// - Print types convertible to BiggestInt.
// - Print types convertible to StringView, if available.
// - Fallback to printing the raw bytes of the object.
@@ -326,13 +305,9 @@ template <typename T>
void PrintWithFallback(const T& value, ::std::ostream* os) {
using Printer = typename FindFirstPrinter<
T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
ProtobufPrinter,
#ifdef GTEST_HAS_ABSL
ConvertibleToAbslStringifyPrinter,
#endif // GTEST_HAS_ABSL
internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter,
RawBytesPrinter, FallbackPrinter>::type;
ProtobufPrinter, ConvertibleToIntegerPrinter,
ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
Printer::PrintValue(value, os);
}
@@ -409,7 +384,7 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
#endif
@@ -497,7 +472,7 @@ GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
inline void PrintTo(char16_t c, ::std::ostream* os) {
PrintTo(ImplicitCast_<char32_t>(c), os);
}
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
inline void PrintTo(char8_t c, ::std::ostream* os) {
PrintTo(ImplicitCast_<char32_t>(c), os);
}
@@ -509,87 +484,6 @@ GTEST_API_ void PrintTo(__uint128_t v, ::std::ostream* os);
GTEST_API_ void PrintTo(__int128_t v, ::std::ostream* os);
#endif // __SIZEOF_INT128__
// The default resolution used to print floating-point values uses only
// 6 digits, which can be confusing if a test compares two values whose
// difference lies in the 7th digit. So we'd like to print out numbers
// in full precision.
// However if the value is something simple like 1.1, full will print a
// long string like 1.100000001 due to floating-point numbers not using
// a base of 10. This routiune returns an appropriate resolution for a
// given floating-point number, that is, 6 if it will be accurate, or a
// max_digits10 value (full precision) if it won't, for values between
// 0.0001 and one million.
// It does this by computing what those digits would be (by multiplying
// by an appropriate power of 10), then dividing by that power again to
// see if gets the original value back.
// A similar algorithm applies for values larger than one million; note
// that for those values, we must divide to get a six-digit number, and
// then multiply to possibly get the original value again.
template <typename FloatType>
int AppropriateResolution(FloatType val) {
int full = std::numeric_limits<FloatType>::max_digits10;
if (val < 0) val = -val;
if (val < 1000000) {
FloatType mulfor6 = 1e10;
if (val >= 100000.0) { // 100,000 to 999,999
mulfor6 = 1.0;
} else if (val >= 10000.0) {
mulfor6 = 1e1;
} else if (val >= 1000.0) {
mulfor6 = 1e2;
} else if (val >= 100.0) {
mulfor6 = 1e3;
} else if (val >= 10.0) {
mulfor6 = 1e4;
} else if (val >= 1.0) {
mulfor6 = 1e5;
} else if (val >= 0.1) {
mulfor6 = 1e6;
} else if (val >= 0.01) {
mulfor6 = 1e7;
} else if (val >= 0.001) {
mulfor6 = 1e8;
} else if (val >= 0.0001) {
mulfor6 = 1e9;
}
if (static_cast<FloatType>(static_cast<int32_t>(val * mulfor6 + 0.5)) /
mulfor6 ==
val)
return 6;
} else if (val < 1e10) {
FloatType divfor6 = 1.0;
if (val >= 1e9) { // 1,000,000,000 to 9,999,999,999
divfor6 = 10000;
} else if (val >= 1e8) { // 100,000,000 to 999,999,999
divfor6 = 1000;
} else if (val >= 1e7) { // 10,000,000 to 99,999,999
divfor6 = 100;
} else if (val >= 1e6) { // 1,000,000 to 9,999,999
divfor6 = 10;
}
if (static_cast<FloatType>(static_cast<int32_t>(val / divfor6 + 0.5)) *
divfor6 ==
val)
return 6;
}
return full;
}
inline void PrintTo(float f, ::std::ostream* os) {
auto old_precision = os->precision();
os->precision(AppropriateResolution(f));
*os << f;
os->precision(old_precision);
}
inline void PrintTo(double d, ::std::ostream* os) {
auto old_precision = os->precision();
os->precision(AppropriateResolution(d));
*os << d;
os->precision(old_precision);
}
// Overloads for C strings.
GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
inline void PrintTo(char* s, ::std::ostream* os) {
@@ -610,7 +504,7 @@ inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
inline void PrintTo(unsigned char* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const void*>(s), os);
}
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
// Overloads for u8 strings.
GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
inline void PrintTo(char8_t* s, ::std::ostream* os) {
@@ -662,7 +556,7 @@ inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
}
// Overloads for ::std::u8string
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
PrintU8StringTo(s, os);
@@ -880,7 +774,7 @@ class UniversalPrinter<Variant<T...>> {
public:
static void Print(const Variant<T...>& value, ::std::ostream* os) {
*os << '(';
#ifdef GTEST_HAS_ABSL
#if GTEST_HAS_ABSL
absl::visit(Visitor{os, value.index()}, value);
#else
std::visit(Visitor{os, value.index()}, value);
@@ -930,7 +824,7 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,
::std::ostream* os);
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
// This overload prints a (const) char8_t array compactly.
GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
::std::ostream* os);
@@ -997,13 +891,6 @@ class UniversalTersePrinter<T&> {
UniversalPrint(value, os);
}
};
template <typename 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 UniversalTersePrinter<T[N]> {
public:
@@ -1026,7 +913,7 @@ template <>
class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
};
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
template <>
class UniversalTersePrinter<const char8_t*> {
public:
-2
View File
@@ -33,8 +33,6 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
#define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
#include <string>
#include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
+2 -4
View File
@@ -35,8 +35,6 @@
#define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
#include <iosfwd>
#include <ostream>
#include <string>
#include <vector>
#include "gtest/internal/gtest-internal.h"
@@ -133,7 +131,7 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
// virtual.
class GTEST_API_ TestPartResultArray {
public:
TestPartResultArray() = default;
TestPartResultArray() {}
// Appends the given TestPartResult to the array.
void Append(const TestPartResult& result);
@@ -154,7 +152,7 @@ class GTEST_API_ TestPartResultArray {
// This interface knows how to report a test part result.
class GTEST_API_ TestPartResultReporterInterface {
public:
virtual ~TestPartResultReporterInterface() = default;
virtual ~TestPartResultReporterInterface() {}
virtual void ReportTestPartResult(const TestPartResult& result) = 0;
};
+17 -17
View File
@@ -267,28 +267,28 @@ 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; \
}; \
static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
__FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
GTEST_STRINGIFY_(TestName)); \
} \
template <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; \
}; \
static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
__FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
GTEST_STRINGIFY_(TestName)); \
} \
template <typename gtest_TypeParam_> \
void GTEST_SUITE_NAMESPACE_( \
SuiteName)::TestName<gtest_TypeParam_>::TestBody()
// Note: this won't work correctly if the trailing arguments are macros.
#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
} \
static const char* const GTEST_REGISTERED_TEST_NAMES_( \
SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
+43 -67
View File
@@ -50,14 +50,9 @@
#define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
#include <cstddef>
#include <cstdint>
#include <iomanip>
#include <limits>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <vector>
@@ -166,7 +161,11 @@ namespace testing {
// Silence C4100 (unreferenced formal parameter) and 4805
// unsafe mix of type 'const int' and type 'const bool'
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4805 4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4805)
#pragma warning(disable : 4100)
#endif
// The upper limit for valid stack trace depths.
const int kMaxStackTraceDepth = 100;
@@ -191,17 +190,6 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message);
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 GTestNonCopyable {
public:
GTestNonCopyable() = default;
GTestNonCopyable(const GTestNonCopyable&) = delete;
GTestNonCopyable& operator=(const GTestNonCopyable&) = delete;
~GTestNonCopyable() = default;
};
} // namespace internal
// The friend relationship of some of these classes is cyclic.
@@ -297,13 +285,7 @@ class GTEST_API_ Test {
// SetUp/TearDown method of Environment objects registered with Google
// Test) will be output as attributes of the <testsuites> element.
static void RecordProperty(const std::string& key, const std::string& value);
// We do not define a custom serialization except for values that can be
// converted to int64_t, but other values could be logged in this way.
template <typename T, std::enable_if_t<std::is_convertible<T, int64_t>::value,
bool> = true>
static void RecordProperty(const std::string& key, const T& value) {
RecordProperty(key, (Message() << value).GetString());
}
static void RecordProperty(const std::string& key, int value);
protected:
// Creates a Test object.
@@ -551,14 +533,14 @@ class GTEST_API_ TestInfo {
// Returns the name of the parameter type, or NULL if this is not a typed
// or a type-parameterized test.
const char* type_param() const {
if (type_param_ != nullptr) return type_param_->c_str();
if (type_param_.get() != nullptr) return type_param_->c_str();
return nullptr;
}
// Returns the text representation of the value parameter, or NULL if this
// is not a value-parameterized test.
const char* value_param() const {
if (value_param_ != nullptr) return value_param_->c_str();
if (value_param_.get() != nullptr) return value_param_->c_str();
return nullptr;
}
@@ -600,7 +582,7 @@ class GTEST_API_ TestInfo {
const TestResult* result() const { return &result_; }
private:
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
friend class internal::DefaultDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST
friend class Test;
@@ -697,7 +679,7 @@ class GTEST_API_ TestSuite {
// Returns the name of the parameter type, or NULL if this is not a
// type-parameterized test suite.
const char* type_param() const {
if (type_param_ != nullptr) return type_param_->c_str();
if (type_param_.get() != nullptr) return type_param_->c_str();
return nullptr;
}
@@ -894,7 +876,7 @@ class GTEST_API_ TestSuite {
class Environment {
public:
// The d'tor is virtual as we need to subclass Environment.
virtual ~Environment() = default;
virtual ~Environment() {}
// Override this to define how to set up the environment.
virtual void SetUp() {}
@@ -925,7 +907,7 @@ class GTEST_API_ AssertionException
// the order the corresponding events are fired.
class TestEventListener {
public:
virtual ~TestEventListener() = default;
virtual ~TestEventListener() {}
// Fired before any test activity starts.
virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
@@ -1055,10 +1037,6 @@ class GTEST_API_ TestEventListeners {
return default_xml_generator_;
}
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
void SuppressEventForwarding(bool);
private:
friend class TestSuite;
friend class TestInfo;
@@ -1088,6 +1066,7 @@ class GTEST_API_ TestEventListeners {
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
bool EventForwardingEnabled() const;
void SuppressEventForwarding();
// The actual list of listeners.
internal::TestEventRepeater* repeater_;
@@ -1646,7 +1625,7 @@ class GTEST_API_ AssertHelper {
// the GetParam() method.
//
// Use it with one of the parameter generator defining functions, like Range(),
// Values(), ValuesIn(), Bool(), Combine(), and ConvertGenerator<T>().
// Values(), ValuesIn(), Bool(), and Combine().
//
// class FooTest : public ::testing::TestWithParam<int> {
// protected:
@@ -1674,7 +1653,7 @@ template <typename T>
class WithParamInterface {
public:
typedef T ParamType;
virtual ~WithParamInterface() = default;
virtual ~WithParamInterface() {}
// The current parameter value. Is also available in the test fixture's
// constructor.
@@ -1744,13 +1723,13 @@ class TestWithParam : public Test, public WithParamInterface<T> {};
#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
// Like GTEST_FAIL(), but at the given source file location.
#define GTEST_FAIL_AT(file, line) \
return GTEST_MESSAGE_AT_(file, line, "Failed", \
::testing::TestPartResult::kFatalFailure)
#define GTEST_FAIL_AT(file, line) \
GTEST_MESSAGE_AT_(file, line, "Failed", \
::testing::TestPartResult::kFatalFailure)
// Define this macro to 1 to omit the definition of FAIL(), which is a
// generic name and clashes with some other libraries.
#if !(defined(GTEST_DONT_DEFINE_FAIL) && GTEST_DONT_DEFINE_FAIL)
#if !GTEST_DONT_DEFINE_FAIL
#define FAIL() GTEST_FAIL()
#endif
@@ -1759,7 +1738,7 @@ class TestWithParam : public Test, public WithParamInterface<T> {};
// Define this macro to 1 to omit the definition of SUCCEED(), which
// is a generic name and clashes with some other libraries.
#if !(defined(GTEST_DONT_DEFINE_SUCCEED) && GTEST_DONT_DEFINE_SUCCEED)
#if !GTEST_DONT_DEFINE_SUCCEED
#define SUCCEED() GTEST_SUCCEED()
#endif
@@ -1803,19 +1782,19 @@ class TestWithParam : public Test, public WithParamInterface<T> {};
// Define these macros to 1 to omit the definition of the corresponding
// EXPECT or ASSERT, which clashes with some users' own code.
#if !(defined(GTEST_DONT_DEFINE_EXPECT_TRUE) && GTEST_DONT_DEFINE_EXPECT_TRUE)
#if !GTEST_DONT_DEFINE_EXPECT_TRUE
#define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
#endif
#if !(defined(GTEST_DONT_DEFINE_EXPECT_FALSE) && GTEST_DONT_DEFINE_EXPECT_FALSE)
#if !GTEST_DONT_DEFINE_EXPECT_FALSE
#define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_TRUE) && GTEST_DONT_DEFINE_ASSERT_TRUE)
#if !GTEST_DONT_DEFINE_ASSERT_TRUE
#define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_FALSE) && GTEST_DONT_DEFINE_ASSERT_FALSE)
#if !GTEST_DONT_DEFINE_ASSERT_FALSE
#define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
#endif
@@ -1894,27 +1873,27 @@ class TestWithParam : public Test, public WithParamInterface<T> {};
// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
// ASSERT_XY(), which clashes with some users' own code.
#if !(defined(GTEST_DONT_DEFINE_ASSERT_EQ) && GTEST_DONT_DEFINE_ASSERT_EQ)
#if !GTEST_DONT_DEFINE_ASSERT_EQ
#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_NE) && GTEST_DONT_DEFINE_ASSERT_NE)
#if !GTEST_DONT_DEFINE_ASSERT_NE
#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_LE) && GTEST_DONT_DEFINE_ASSERT_LE)
#if !GTEST_DONT_DEFINE_ASSERT_LE
#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_LT) && GTEST_DONT_DEFINE_ASSERT_LT)
#if !GTEST_DONT_DEFINE_ASSERT_LT
#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_GE) && GTEST_DONT_DEFINE_ASSERT_GE)
#if !GTEST_DONT_DEFINE_ASSERT_GE
#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_GT) && GTEST_DONT_DEFINE_ASSERT_GT)
#if !GTEST_DONT_DEFINE_ASSERT_GT
#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
#endif
@@ -2002,7 +1981,7 @@ GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
double val1, double val2);
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// Macros that test for HRESULT failure and success, these are only useful
// on Windows, and rely on Windows SDK macros and APIs to compile.
@@ -2084,7 +2063,9 @@ class GTEST_API_ ScopedTrace {
ScopedTrace(const ScopedTrace&) = delete;
ScopedTrace& operator=(const ScopedTrace&) = delete;
};
} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
// c'tor and d'tor. Therefore it doesn't
// need to be used otherwise.
// Causes a trace (including the source file path, the current line
// number, and the given message) to be included in every test failure
@@ -2101,8 +2082,8 @@ class GTEST_API_ ScopedTrace {
// Assuming that each thread maintains its own stack of traces.
// Therefore, a SCOPED_TRACE() would (correctly) only affect the
// assertions in its own thread.
#define SCOPED_TRACE(message) \
const ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \
#define SCOPED_TRACE(message) \
::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \
__FILE__, __LINE__, (message))
// Compile-time assertion for type equality.
@@ -2172,7 +2153,7 @@ constexpr bool StaticAssertTypeEq() noexcept {
// Define this macro to 1 to omit the definition of TEST(), which
// is a generic name and clashes with some other libraries.
#if !(defined(GTEST_DONT_DEFINE_TEST) && GTEST_DONT_DEFINE_TEST)
#if !GTEST_DONT_DEFINE_TEST
#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
#endif
@@ -2204,22 +2185,17 @@ constexpr bool StaticAssertTypeEq() noexcept {
#define GTEST_TEST_F(test_fixture, test_name) \
GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>())
#if !(defined(GTEST_DONT_DEFINE_TEST_F) && GTEST_DONT_DEFINE_TEST_F)
#if !GTEST_DONT_DEFINE_TEST_F
#define TEST_F(test_fixture, test_name) GTEST_TEST_F(test_fixture, test_name)
#endif
// Returns a path to a temporary directory, which should be writable. It is
// implementation-dependent whether or not the path is terminated by the
// directory-separator character.
// Returns a path to temporary directory.
// Tries to determine an appropriate directory for the platform.
GTEST_API_ std::string TempDir();
// Returns a path to a directory that contains ancillary data files that might
// be used by tests. It is implementation dependent whether or not the path is
// terminated by the directory-separator character. The directory and the files
// in it should be considered read-only.
GTEST_API_ std::string SrcDir();
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4805 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// Dynamically registers a test with the framework.
//
@@ -42,7 +42,6 @@
#include <stdio.h>
#include <memory>
#include <string>
#include "gtest/gtest-matchers.h"
#include "gtest/internal/gtest-internal.h"
@@ -57,7 +56,7 @@ const char kDeathTestStyleFlag[] = "death_test_style";
const char kDeathTestUseFork[] = "death_test_use_fork";
const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@@ -88,7 +87,7 @@ class GTEST_API_ DeathTest {
static bool Create(const char* statement, Matcher<const std::string&> matcher,
const char* file, int line, DeathTest** test);
DeathTest();
virtual ~DeathTest() = default;
virtual ~DeathTest() {}
// A helper class that aborts a death test when it's deleted.
class ReturnSentinel {
@@ -100,7 +99,7 @@ class GTEST_API_ DeathTest {
DeathTest* const test_;
ReturnSentinel(const ReturnSentinel&) = delete;
ReturnSentinel& operator=(const ReturnSentinel&) = delete;
};
} GTEST_ATTRIBUTE_UNUSED_;
// An enumeration of possible roles that may be taken when a death
// test is encountered. EXECUTE means that the death test logic should
@@ -153,7 +152,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// Factory interface for death tests. May be mocked out for testing.
class DeathTestFactory {
public:
virtual ~DeathTestFactory() = default;
virtual ~DeathTestFactory() {}
virtual bool Create(const char* statement,
Matcher<const std::string&> matcher, const char* file,
int line, DeathTest** test) = 0;
@@ -238,7 +237,7 @@ inline Matcher<const ::std::string&> MakeDeathTestMatcher(
} \
break; \
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
const ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
gtest_dt); \
GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
@@ -42,16 +42,11 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#include <string>
#include "gtest/internal/gtest-port.h"
#include "gtest/internal/gtest-string.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
#if GTEST_HAS_FILE_SYSTEM
namespace testing {
namespace internal {
@@ -204,16 +199,6 @@ class GTEST_API_ FilePath {
// separators. Returns NULL if no path separator was found.
const char* FindLastPathSeparator() const;
// Returns the length of the path root, including the directory separator at
// the end of the prefix. Returns zero by definition if the path is relative.
// Examples:
// - [Windows] "..\Sibling" => 0
// - [Windows] "\Windows" => 1
// - [Windows] "C:/Windows\Notepad.exe" => 3
// - [Windows] "\\Host\Share\C$/Windows" => 13
// - [UNIX] "/bin" => 1
size_t CalculateRootLength() const;
std::string pathname_;
}; // class FilePath
@@ -222,6 +207,4 @@ class GTEST_API_ FilePath {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GTEST_HAS_FILE_SYSTEM
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
@@ -41,7 +41,7 @@
#include "gtest/internal/gtest-port.h"
#ifdef GTEST_OS_LINUX
#if GTEST_OS_LINUX
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
@@ -57,14 +57,12 @@
#include <string.h>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <limits>
#include <map>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "gtest/gtest-message.h"
@@ -307,6 +305,9 @@ class FloatingPoint {
// Returns the floating-point number that represent positive infinity.
static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }
// Returns the maximum representable finite floating-point number.
static RawType Max();
// Non-static methods
// Returns the bits that represents this number.
@@ -387,6 +388,17 @@ class FloatingPoint {
FloatingPointUnion u_;
};
// We cannot use std::numeric_limits<T>::max() as it clashes with the max()
// macro defined by <windows.h>.
template <>
inline float FloatingPoint<float>::Max() {
return FLT_MAX;
}
template <>
inline double FloatingPoint<double>::Max() {
return DBL_MAX;
}
// Typedefs the instances of the FloatingPoint template class that we
// care to use.
typedef FloatingPoint<float> Float;
@@ -435,7 +447,7 @@ GTEST_API_ TypeId GetTestTypeId();
// of a Test object.
class TestFactoryBase {
public:
virtual ~TestFactoryBase() = default;
virtual ~TestFactoryBase() {}
// Creates a test instance to run. The instance is both created and destroyed
// within TestInfoImpl::Run()
@@ -449,7 +461,7 @@ class TestFactoryBase {
TestFactoryBase& operator=(const TestFactoryBase&) = delete;
};
// This class provides implementation of TestFactoryBase interface.
// This class provides implementation of TeastFactoryBase interface.
// It is used in TEST and TEST_F macros.
template <class TestClass>
class TestFactoryImpl : public TestFactoryBase {
@@ -457,7 +469,7 @@ class TestFactoryImpl : public TestFactoryBase {
Test* CreateTest() override { return new TestClass; }
};
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// Predicate-formatters for implementing the HRESULT checking macros
// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
@@ -619,7 +631,7 @@ class GTEST_API_ TypedTestSuitePState {
const char* registered_tests);
private:
typedef ::std::map<std::string, CodeLocation, std::less<>> RegisteredTestsMap;
typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
bool registered_;
RegisteredTestsMap registered_tests_;
@@ -817,7 +829,8 @@ class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
// For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(int skip_count);
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest* unit_test,
int skip_count);
// Helpers for suppressing warnings on unreachable code or constant
// condition.
@@ -900,10 +913,8 @@ class 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
@@ -1497,20 +1508,19 @@ class NeverThrown {
gtest_ar_, text, #actual, #expected) \
.c_str())
#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
const ::testing::internal::HasNewFatalFailureHelper \
gtest_fatal_failure_checker; \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
} \
} else /* NOLINT */ \
GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \
: fail("Expected: " #statement \
" doesn't generate new fatal " \
"failures in the current thread.\n" \
#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
} \
} else \
GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \
: fail("Expected: " #statement \
" doesn't generate new fatal " \
"failures in the current thread.\n" \
" Actual: it does.")
// Expands to the name of the class that implements the given test.
@@ -40,11 +40,8 @@
#include <cassert>
#include <iterator>
#include <map>
#include <memory>
#include <ostream>
#include <set>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
@@ -97,7 +94,7 @@ class ParamGenerator;
template <typename T>
class ParamIteratorInterface {
public:
virtual ~ParamIteratorInterface() = default;
virtual ~ParamIteratorInterface() {}
// A pointer to the base generator instance.
// Used only for the purposes of iterator comparison
// to make sure that two iterators belong to the same generator.
@@ -171,7 +168,7 @@ class ParamGeneratorInterface {
public:
typedef T ParamType;
virtual ~ParamGeneratorInterface() = default;
virtual ~ParamGeneratorInterface() {}
// Generator interface definition
virtual ParamIteratorInterface<T>* Begin() const = 0;
@@ -215,7 +212,7 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
end_(end),
step_(step),
end_index_(CalculateEndIndex(begin, end, step)) {}
~RangeGenerator() override = default;
~RangeGenerator() override {}
ParamIteratorInterface<T>* Begin() const override {
return new Iterator(this, begin_, 0, step_);
@@ -230,7 +227,7 @@ class RangeGenerator : public ParamGeneratorInterface<T> {
Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
IncrementT step)
: base_(base), value_(value), index_(index), step_(step) {}
~Iterator() override = default;
~Iterator() override {}
const ParamGeneratorInterface<T>* BaseGenerator() const override {
return base_;
@@ -299,7 +296,7 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
template <typename ForwardIterator>
ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
: container_(begin, end) {}
~ValuesInIteratorRangeGenerator() override = default;
~ValuesInIteratorRangeGenerator() override {}
ParamIteratorInterface<T>* Begin() const override {
return new Iterator(this, container_.begin());
@@ -316,7 +313,7 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
Iterator(const ParamGeneratorInterface<T>* base,
typename ContainerType::const_iterator iterator)
: base_(base), iterator_(iterator) {}
~Iterator() override = default;
~Iterator() override {}
const ParamGeneratorInterface<T>* BaseGenerator() const override {
return base_;
@@ -420,7 +417,7 @@ class ParameterizedTestFactory : public TestFactoryBase {
template <class ParamType>
class TestMetaFactoryBase {
public:
virtual ~TestMetaFactoryBase() = default;
virtual ~TestMetaFactoryBase() {}
virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
};
@@ -439,7 +436,7 @@ class TestMetaFactory
public:
using ParamType = typename TestSuite::ParamType;
TestMetaFactory() = default;
TestMetaFactory() {}
TestFactoryBase* CreateTestFactory(ParamType parameter) override {
return new ParameterizedTestFactory<TestSuite>(parameter);
@@ -462,7 +459,7 @@ class TestMetaFactory
// and calls RegisterTests() on each of them when asked.
class ParameterizedTestSuiteInfoBase {
public:
virtual ~ParameterizedTestSuiteInfoBase() = default;
virtual ~ParameterizedTestSuiteInfoBase() {}
// Base part of test suite name for display purposes.
virtual const std::string& GetTestSuiteName() const = 0;
@@ -691,7 +688,7 @@ using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
// ParameterizedTestSuiteInfo descriptors.
class ParameterizedTestSuiteRegistry {
public:
ParameterizedTestSuiteRegistry() = default;
ParameterizedTestSuiteRegistry() {}
~ParameterizedTestSuiteRegistry() {
for (auto& test_suite_info : test_suite_infos_) {
delete test_suite_info;
@@ -794,7 +791,10 @@ internal::ParamGenerator<typename Container::value_type> ValuesIn(
namespace internal {
// Used in the Values() function to provide polymorphic capabilities.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
template <typename... Ts>
class ValueArray {
@@ -815,7 +815,9 @@ class ValueArray {
FlatTuple<Ts...> v_;
};
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
template <typename... T>
class CartesianProductGenerator
@@ -825,7 +827,7 @@ class CartesianProductGenerator
CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
: generators_(g) {}
~CartesianProductGenerator() override = default;
~CartesianProductGenerator() override {}
ParamIteratorInterface<ParamType>* Begin() const override {
return new Iterator(this, generators_, false);
@@ -850,7 +852,7 @@ class CartesianProductGenerator
current_(is_end ? end_ : begin_) {
ComputeCurrentValue();
}
~IteratorImpl() override = default;
~IteratorImpl() override {}
const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
return base_;
@@ -948,78 +950,6 @@ class CartesianProductHolder {
std::tuple<Gen...> generators_;
};
template <typename From, typename To>
class ParamGeneratorConverter : public ParamGeneratorInterface<To> {
public:
ParamGeneratorConverter(ParamGenerator<From> gen) // NOLINT
: generator_(std::move(gen)) {}
ParamIteratorInterface<To>* Begin() const override {
return new Iterator(this, generator_.begin(), generator_.end());
}
ParamIteratorInterface<To>* End() const override {
return new Iterator(this, generator_.end(), generator_.end());
}
private:
class Iterator : public ParamIteratorInterface<To> {
public:
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>(*it_));
}
~Iterator() override = default;
const ParamGeneratorInterface<To>* BaseGenerator() const override {
return base_;
}
void Advance() override {
++it_;
if (it_ != end_) value_ = std::make_shared<To>(static_cast<To>(*it_));
}
ParamIteratorInterface<To>* Clone() const override {
return new Iterator(*this);
}
const To* Current() const override { return value_.get(); }
bool Equals(const ParamIteratorInterface<To>& other) const override {
// Having the same base generator guarantees that the other
// iterator is of the same type and we can downcast.
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
<< "The program attempted to compare iterators "
<< "from different generators." << std::endl;
const ParamIterator<From> other_it =
CheckedDowncastToActualType<const Iterator>(&other)->it_;
return it_ == other_it;
}
private:
Iterator(const Iterator& other) = default;
const ParamGeneratorInterface<To>* const base_;
ParamIterator<From> it_;
ParamIterator<From> end_;
std::shared_ptr<To> value_;
}; // class ParamGeneratorConverter::Iterator
ParamGenerator<From> generator_;
}; // class ParamGeneratorConverter
template <class Gen>
class ParamConverterGenerator {
public:
ParamConverterGenerator(ParamGenerator<Gen> g) // NOLINT
: generator_(std::move(g)) {}
template <typename T>
operator ParamGenerator<T>() const { // NOLINT
return ParamGenerator<T>(new ParamGeneratorConverter<Gen, T>(generator_));
}
private:
ParamGenerator<Gen> generator_;
};
} // namespace internal
} // namespace testing
@@ -111,12 +111,6 @@
#define GTEST_OS_ESP32 1
#elif defined(__XTENSA__)
#define GTEST_OS_XTENSA 1
#elif defined(__hexagon__)
#define GTEST_OS_QURT 1
#elif defined(CPU_QN9090) || defined(CPU_QN9090HN)
#define GTEST_OS_NXP_QN9090 1
#elif defined(NRF52)
#define GTEST_OS_NRF52 1
#endif // __CYGWIN__
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
File diff suppressed because it is too large Load Diff
@@ -51,7 +51,6 @@
#include <string.h>
#include <cstdint>
#include <sstream>
#include <string>
#include "gtest/internal/gtest-port.h"
@@ -73,7 +72,7 @@ class GTEST_API_ String {
// memory using malloc().
static const char* CloneCString(const char* c_str);
#ifdef GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE
// Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
// able to pass strings to Win32 APIs on CE we need to convert them
// to 'Unicode', UTF-16.
@@ -37,10 +37,6 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#include <string>
#include <type_traits>
#include <typeinfo>
#include "gtest/internal/gtest-port.h"
// #ifdef __GNUC__ is too general here. It is possible to use gcc without using
@@ -67,22 +63,6 @@ inline std::string CanonicalizeForStdLibVersioning(std::string s) {
s.erase(strlen("std"), end - strlen("std"));
}
}
// Strip redundant spaces in typename to match MSVC
// For example, std::pair<int, bool> -> std::pair<int,bool>
static const char to_search[] = ", ";
static const char replace_str[] = ",";
size_t pos = 0;
while (true) {
// Get the next occurrence from the current position
pos = s.find(to_search, pos);
if (pos == std::string::npos) {
break;
}
// Replace this occurrence of substring
s.replace(pos, strlen(to_search), replace_str);
pos += strlen(replace_str);
}
return s;
}
@@ -101,20 +81,6 @@ inline std::string GetTypeName(const std::type_info& type) {
const std::string name_str(status == 0 ? readable_name : name);
free(readable_name);
return CanonicalizeForStdLibVersioning(name_str);
#elif defined(_MSC_VER)
// Strip struct and class due to differences between
// MSVC and other compilers. std::pair<int,bool> is printed as
// "struct std::pair<int,bool>" when using MSVC vs "std::pair<int, bool>" with
// other compilers.
std::string s = name;
// Only strip the leading "struct " and "class ", so uses rfind == 0 to
// ensure that
if (s.rfind("struct ", 0) == 0) {
s = s.substr(strlen("struct "));
} else if (s.rfind("class ", 0) == 0) {
s = s.substr(strlen("class "));
}
return s;
#else
return name;
#endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
+3 -4
View File
@@ -39,7 +39,7 @@
// The prime table interface.
class PrimeTable {
public:
virtual ~PrimeTable() = default;
virtual ~PrimeTable() {}
// Returns true if and only if n is a prime number.
virtual bool IsPrime(int n) const = 0;
@@ -78,9 +78,8 @@ class PreCalculatedPrimeTable : public PrimeTable {
public:
// 'max' specifies the maximum number the prime table holds.
explicit PreCalculatedPrimeTable(int max)
: is_prime_size_(std::max(1, max + 1)),
is_prime_(new bool[static_cast<size_t>(is_prime_size_)]) {
CalculatePrimesUpTo(is_prime_size_ - 1);
: is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {
CalculatePrimesUpTo(max);
}
~PreCalculatedPrimeTable() override { delete[] is_prime_; }
+1
View File
@@ -38,6 +38,7 @@ using ::testing::InitGoogleTest;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
using ::testing::UnitTest;
namespace {
-2
View File
@@ -32,8 +32,6 @@
// and each test is given one combination as a parameter.
// Use class definitions to test from this header.
#include <tuple>
#include "prime_tables.h"
#include "gtest/gtest.h"
namespace {
+1
View File
@@ -40,6 +40,7 @@ using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
using ::testing::TestSuite;
using ::testing::UnitTest;
namespace {
// Provides alternative output mode which produces minimal amount of
+2 -2
View File
@@ -44,7 +44,7 @@ namespace testing {
// Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult::AssertionResult(const AssertionResult& other)
: success_(other.success_),
message_(other.message_ != nullptr
message_(other.message_.get() != nullptr
? new ::std::string(*other.message_)
: static_cast< ::std::string*>(nullptr)) {}
@@ -58,7 +58,7 @@ void AssertionResult::swap(AssertionResult& other) {
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
AssertionResult AssertionResult::operator!() const {
AssertionResult negation(!success_);
if (message_ != nullptr) negation << *message_;
if (message_.get() != nullptr) negation << *message_;
return negation;
}
+100 -65
View File
@@ -33,18 +33,14 @@
#include "gtest/gtest-death-test.h"
#include <functional>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "gtest/internal/custom/gtest.h"
#include "gtest/internal/gtest-port.h"
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
#ifdef GTEST_OS_MAC
#if GTEST_OS_MAC
#include <crt_externs.h>
#endif // GTEST_OS_MAC
@@ -52,24 +48,24 @@
#include <fcntl.h>
#include <limits.h>
#ifdef GTEST_OS_LINUX
#if GTEST_OS_LINUX
#include <signal.h>
#endif // GTEST_OS_LINUX
#include <stdarg.h>
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
#include <windows.h>
#else
#include <sys/mman.h>
#include <sys/wait.h>
#endif // GTEST_OS_WINDOWS
#ifdef GTEST_OS_QNX
#if GTEST_OS_QNX
#include <spawn.h>
#endif // GTEST_OS_QNX
#ifdef GTEST_OS_FUCHSIA
#if GTEST_OS_FUCHSIA
#include <lib/fdio/fd.h>
#include <lib/fdio/io.h>
#include <lib/fdio/spawn.h>
@@ -135,13 +131,13 @@ GTEST_DEFINE_string_(
namespace testing {
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
namespace internal {
// Valid only for fast death tests. Indicates the code is running in the
// child process of a fast style death test.
#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
static bool g_in_fast_death_test_child = false;
#endif
@@ -151,7 +147,7 @@ static bool g_in_fast_death_test_child = false;
// tests. IMPORTANT: This is an internal utility. Using it may break the
// implementation of death tests. User code MUST NOT use it.
bool InDeathTestChild() {
#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
// On Windows and Fuchsia, death tests are thread-safe regardless of the value
// of the death_test_style flag.
@@ -173,7 +169,7 @@ ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}
// ExitedWithCode function-call operator.
bool ExitedWithCode::operator()(int exit_status) const {
#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
return exit_status == exit_code_;
@@ -184,7 +180,7 @@ bool ExitedWithCode::operator()(int exit_status) const {
#endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
}
#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// KilledBySignal constructor.
KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}
@@ -211,7 +207,7 @@ namespace internal {
static std::string ExitSummary(int exit_code) {
Message m;
#if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
m << "Exited with exit status " << exit_code;
@@ -238,7 +234,7 @@ bool ExitedUnsuccessfully(int exit_status) {
return !ExitedWithCode(0)(exit_status);
}
#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// Generates a textual failure message when a death test finds more than
// one thread running, or cannot determine the number of threads, prior
// to executing the given statement. It is the responsibility of the
@@ -253,7 +249,7 @@ static std::string DeathTestThreadWarning(size_t thread_count) {
msg << "detected " << thread_count << " threads.";
}
msg << " See "
"https://github.com/google/googletest/blob/main/docs/"
"https://github.com/google/googletest/blob/master/docs/"
"advanced.md#death-tests-and-threads"
<< " for more explanation and suggested solutions, especially if"
<< " this is the last message you see before your test times out.";
@@ -267,7 +263,7 @@ static const char kDeathTestReturned = 'R';
static const char kDeathTestThrew = 'T';
static const char kDeathTestInternalError = 'I';
#ifdef GTEST_OS_FUCHSIA
#if GTEST_OS_FUCHSIA
// File descriptor used for the pipe in the child process.
static const int kFuchsiaReadPipeFd = 3;
@@ -288,7 +284,7 @@ enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
// message is propagated back to the parent process. Otherwise, the
// message is simply printed to stderr. In either case, the program
// then exits with status 1.
[[noreturn]] static void DeathTestAbort(const std::string& message) {
static void DeathTestAbort(const std::string& message) {
// On a POSIX system, this function may be called from a threadsafe-style
// death test child process, which operates on a very small stack. Use
// the heap for any additional non-minuscule memory requirements.
@@ -625,21 +621,7 @@ bool DeathTestImpl::Passed(bool status_ok) {
return success;
}
#ifndef GTEST_OS_WINDOWS
// Note: The return value points into args, so the return value's lifetime is
// bound to that of args.
static std::unique_ptr<char*[]> CreateArgvFromArgs(
std::vector<std::string>& args) {
auto result = std::make_unique<char*[]>(args.size() + 1);
for (size_t i = 0; i < args.size(); ++i) {
result[i] = &args[i][0];
}
result[args.size()] = nullptr; // extra null terminator
return result;
}
#endif
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// WindowsDeathTest implements death tests on Windows. Due to the
// specifics of starting new processes on Windows, death tests there are
// always threadsafe, and Google Test considers the
@@ -826,7 +808,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
return OVERSEE_TEST;
}
#elif defined(GTEST_OS_FUCHSIA)
#elif GTEST_OS_FUCHSIA
class FuchsiaDeathTest : public DeathTestImpl {
public:
@@ -854,6 +836,36 @@ class FuchsiaDeathTest : public DeathTestImpl {
zx::socket stderr_socket_;
};
// Utility class for accumulating command-line arguments.
class Arguments {
public:
Arguments() { args_.push_back(nullptr); }
~Arguments() {
for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
++i) {
free(*i);
}
}
void AddArgument(const char* argument) {
args_.insert(args_.end() - 1, posix::StrDup(argument));
}
template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
i != arguments.end(); ++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
}
}
char* const* Argv() { return &args_[0]; }
int size() { return static_cast<int>(args_.size()) - 1; }
private:
std::vector<char*> args_;
};
// Waits for the child in a death test to exit, returning its exit
// status, or 0 if no child process exists. As a side effect, sets the
// outcome data member.
@@ -974,10 +986,10 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
kInternalRunDeathTestFlag + "=" + file_ +
"|" + StreamableToString(line_) + "|" +
StreamableToString(death_test_index);
std::vector<std::string> args = GetInjectableArgvs();
args.push_back(filter_flag);
args.push_back(internal_flag);
Arguments args;
args.AddArguments(GetInjectableArgvs());
args.AddArgument(filter_flag.c_str());
args.AddArgument(internal_flag.c_str());
// Build the pipe for communication with the child.
zx_status_t status;
@@ -1029,14 +1041,8 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
// Spawn the child process.
// Note: The test component must have `fuchsia.process.Launcher` declared
// in its manifest. (Fuchsia integration tests require creating a
// "Fuchsia Test Component" which contains a "Fuchsia Component Manifest")
// Launching processes is a privileged operation in Fuchsia, and the
// declaration indicates that the ability is required for the component.
std::unique_ptr<char*[]> argv = CreateArgvFromArgs(args);
status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, argv[0], argv.get(),
nullptr, 2, spawn_actions,
status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0],
args.Argv(), nullptr, 2, spawn_actions,
child_process_.reset_and_get_address(), nullptr);
GTEST_DEATH_TEST_CHECK_(status == ZX_OK);
@@ -1128,7 +1134,7 @@ DeathTest::TestRole NoExecDeathTest::AssumeRole() {
LogToStderr();
// Event forwarding to the listeners of event listener API mush be shut
// down in death test subprocesses.
GetUnitTestImpl()->listeners()->SuppressEventForwarding(true);
GetUnitTestImpl()->listeners()->SuppressEventForwarding();
g_in_fast_death_test_child = true;
return EXECUTE_TEST;
} else {
@@ -1167,6 +1173,34 @@ class ExecDeathTest : public ForkingDeathTest {
const int line_;
};
// Utility class for accumulating command-line arguments.
class Arguments {
public:
Arguments() { args_.push_back(nullptr); }
~Arguments() {
for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
++i) {
free(*i);
}
}
void AddArgument(const char* argument) {
args_.insert(args_.end() - 1, posix::StrDup(argument));
}
template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
i != arguments.end(); ++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
}
}
char* const* Argv() { return &args_[0]; }
private:
std::vector<char*> args_;
};
// A struct that encompasses the arguments to the child process of a
// threadsafe-style death test process.
struct ExecDeathTestArgs {
@@ -1174,7 +1208,7 @@ struct ExecDeathTestArgs {
int close_fd; // File descriptor to close; the read end of a pipe
};
#ifdef GTEST_OS_QNX
#if GTEST_OS_QNX
extern "C" char** environ;
#else // GTEST_OS_QNX
// The main function for a threadsafe-style death test child process.
@@ -1255,7 +1289,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
ExecDeathTestArgs args = {argv, close_fd};
pid_t child_pid = -1;
#ifdef GTEST_OS_QNX
#if GTEST_OS_QNX
// Obtains the current directory and sets it to be closed in the child
// process.
const int cwd_fd = open(".", O_RDONLY);
@@ -1286,7 +1320,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
#else // GTEST_OS_QNX
#ifdef GTEST_OS_LINUX
#if GTEST_OS_LINUX
// When a SIGPROF signal is received while fork() or clone() are executing,
// the process may hang. To avoid this, we ignore SIGPROF here and re-enable
// it after the call to fork()/clone() is complete.
@@ -1333,10 +1367,11 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
#endif // GTEST_HAS_CLONE
if (use_fork && (child_pid = fork()) == 0) {
_exit(ExecDeathTestChildMain(&args));
ExecDeathTestChildMain(&args);
_exit(0);
}
#endif // GTEST_OS_QNX
#ifdef GTEST_OS_LINUX
#if GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_SYSCALL_(
sigaction(SIGPROF, &saved_sigprof_action, nullptr));
#endif // GTEST_OS_LINUX
@@ -1375,9 +1410,10 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
StreamableToString(line_) + "|" +
StreamableToString(death_test_index) + "|" +
StreamableToString(pipe_fd[1]);
std::vector<std::string> args = GetArgvsForDeathTestChildProcess();
args.push_back(filter_flag);
args.push_back(internal_flag);
Arguments args;
args.AddArguments(GetArgvsForDeathTestChildProcess());
args.AddArgument(filter_flag.c_str());
args.AddArgument(internal_flag.c_str());
DeathTest::set_last_death_test_message("");
@@ -1386,8 +1422,7 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() {
// is necessary.
FlushInfoLog();
std::unique_ptr<char*[]> argv = CreateArgvFromArgs(args);
const pid_t child_pid = ExecDeathTestSpawnChild(argv.get(), pipe_fd[0]);
const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
set_child_pid(child_pid);
set_read_fd(pipe_fd[0]);
@@ -1428,14 +1463,14 @@ bool DefaultDeathTestFactory::Create(const char* statement,
}
}
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
GTEST_FLAG_GET(death_test_style) == "fast") {
*test = new WindowsDeathTest(statement, std::move(matcher), file, line);
}
#elif defined(GTEST_OS_FUCHSIA)
#elif GTEST_OS_FUCHSIA
if (GTEST_FLAG_GET(death_test_style) == "threadsafe" ||
GTEST_FLAG_GET(death_test_style) == "fast") {
@@ -1462,7 +1497,7 @@ bool DefaultDeathTestFactory::Create(const char* statement,
return true;
}
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// Recreates the pipe and event handles from the provided parameters,
// signals the event, and returns a file descriptor wrapped around the pipe
// handle. This function is called in the child process only.
@@ -1529,7 +1564,7 @@ static int GetStatusFileDescriptor(unsigned int parent_process_id,
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
// the flag is specified; otherwise returns NULL.
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
if (GTEST_FLAG_GET(internal_run_death_test).empty()) return nullptr;
if (GTEST_FLAG_GET(internal_run_death_test) == "") return nullptr;
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
// can use it here.
@@ -1539,7 +1574,7 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields);
int write_fd = -1;
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
unsigned int parent_process_id = 0;
size_t write_handle_as_size_t = 0;
@@ -1556,7 +1591,7 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
event_handle_as_size_t);
#elif defined(GTEST_OS_FUCHSIA)
#elif GTEST_OS_FUCHSIA
if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) ||
!ParseNaturalNumber(fields[2], &index)) {
+36 -83
View File
@@ -31,15 +31,12 @@
#include <stdlib.h>
#include <iterator>
#include <string>
#include "gtest/gtest-message.h"
#include "gtest/internal/gtest-port.h"
#ifdef GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE
#include <windows.h>
#elif defined(GTEST_OS_WINDOWS)
#elif GTEST_OS_WINDOWS
#include <direct.h>
#include <io.h>
#else
@@ -50,7 +47,7 @@
#include "gtest/internal/gtest-string.h"
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
#define GTEST_PATH_MAX_ _MAX_PATH
#elif defined(PATH_MAX)
#define GTEST_PATH_MAX_ PATH_MAX
@@ -60,12 +57,10 @@
#define GTEST_PATH_MAX_ _POSIX_PATH_MAX
#endif // GTEST_OS_WINDOWS
#if GTEST_HAS_FILE_SYSTEM
namespace testing {
namespace internal {
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// On Windows, '\\' is the standard path separator, but many tools and the
// Windows API also accept '/' as an alternate path separator. Unless otherwise
// noted, a file path can contain either kind of path separators, or a mixture
@@ -73,7 +68,7 @@ namespace internal {
const char kPathSeparator = '\\';
const char kAlternatePathSeparator = '/';
const char kAlternatePathSeparatorString[] = "/";
#ifdef GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback.
@@ -99,21 +94,19 @@ static bool IsPathSeparator(char c) {
// Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() {
#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \
defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \
defined(GTEST_OS_ESP32) || defined(GTEST_OS_XTENSA) || \
defined(GTEST_OS_QURT) || defined(GTEST_OS_NXP_QN9090) || \
defined(GTEST_OS_NRF52)
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
GTEST_OS_XTENSA
// These platforms do not have a current directory, so we just return
// something reasonable.
return FilePath(kCurrentDirectoryString);
#elif defined(GTEST_OS_WINDOWS)
#elif GTEST_OS_WINDOWS
char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
#else
char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
char* result = getcwd(cwd, sizeof(cwd));
#ifdef GTEST_OS_NACL
#if GTEST_OS_NACL
// getcwd will likely fail in NaCl due to the sandbox, so return something
// reasonable. The user may have provided a shim implementation for getcwd,
// however, so fallback only when failure is detected.
@@ -152,44 +145,6 @@ const char* FilePath::FindLastPathSeparator() const {
return last_sep;
}
size_t FilePath::CalculateRootLength() const {
const auto& path = pathname_;
auto s = path.begin();
auto end = path.end();
#ifdef GTEST_OS_WINDOWS
if (end - s >= 2 && s[1] == ':' && (end - s == 2 || IsPathSeparator(s[2])) &&
(('A' <= s[0] && s[0] <= 'Z') || ('a' <= s[0] && s[0] <= 'z'))) {
// A typical absolute path like "C:\Windows" or "D:"
s += 2;
if (s != end) {
++s;
}
} else if (end - s >= 3 && IsPathSeparator(*s) && IsPathSeparator(*(s + 1)) &&
!IsPathSeparator(*(s + 2))) {
// Move past the "\\" prefix in a UNC path like "\\Server\Share\Folder"
s += 2;
// Skip 2 components and their following separators ("Server\" and "Share\")
for (int i = 0; i < 2; ++i) {
while (s != end) {
bool stop = IsPathSeparator(*s);
++s;
if (stop) {
break;
}
}
}
} else if (s != end && IsPathSeparator(*s)) {
// A drive-rooted path like "\Windows"
++s;
}
#else
if (s != end && IsPathSeparator(*s)) {
++s;
}
#endif
return static_cast<size_t>(s - path.begin());
}
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
@@ -249,7 +204,7 @@ FilePath FilePath::ConcatPaths(const FilePath& directory,
// Returns true if pathname describes something findable in the file-system,
// either a file, directory, or whatever.
bool FilePath::FileOrDirectoryExists() const {
#ifdef GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete[] unicode;
@@ -264,7 +219,7 @@ bool FilePath::FileOrDirectoryExists() const {
// that exists.
bool FilePath::DirectoryExists() const {
bool result = false;
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\").
const FilePath& path(IsRootDirectory() ? *this
@@ -273,7 +228,7 @@ bool FilePath::DirectoryExists() const {
const FilePath& path(*this);
#endif
#ifdef GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete[] unicode;
@@ -291,15 +246,27 @@ bool FilePath::DirectoryExists() const {
}
// Returns true if pathname describes a root directory. (Windows has one
// root directory per disk drive. UNC share roots are also included.)
// root directory per disk drive.)
bool FilePath::IsRootDirectory() const {
size_t root_length = CalculateRootLength();
return root_length > 0 && root_length == pathname_.size() &&
IsPathSeparator(pathname_[root_length - 1]);
#if GTEST_OS_WINDOWS
return pathname_.length() == 3 && IsAbsolutePath();
#else
return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
#endif
}
// Returns true if pathname describes an absolute path.
bool FilePath::IsAbsolutePath() const { return CalculateRootLength() > 0; }
bool FilePath::IsAbsolutePath() const {
const char* const name = pathname_.c_str();
#if GTEST_OS_WINDOWS
return pathname_.length() >= 3 &&
((name[0] >= 'a' && name[0] <= 'z') ||
(name[0] >= 'A' && name[0] <= 'Z')) &&
name[1] == ':' && IsPathSeparator(name[2]);
#else
return IsPathSeparator(name[0]);
#endif
}
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
@@ -349,16 +316,14 @@ bool FilePath::CreateDirectoriesRecursively() const {
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool FilePath::CreateFolder() const {
#ifdef GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE
FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
delete[] unicode;
#elif defined(GTEST_OS_WINDOWS)
#elif GTEST_OS_WINDOWS
int result = _mkdir(pathname_.c_str());
#elif defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \
defined(GTEST_OS_QURT) || defined(GTEST_OS_NXP_QN9090) || \
defined(GTEST_OS_NRF52)
#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
// do nothing
int result = 0;
#else
@@ -382,27 +347,17 @@ FilePath FilePath::RemoveTrailingPathSeparator() const {
// Removes any redundant separators that might be in the pathname.
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
// Note that "\\Host\Share" does not contain a redundancy on Windows!
void FilePath::Normalize() {
auto out = pathname_.begin();
auto i = pathname_.cbegin();
#ifdef GTEST_OS_WINDOWS
// UNC paths are treated specially
if (pathname_.end() - i >= 3 && IsPathSeparator(*i) &&
IsPathSeparator(*(i + 1)) && !IsPathSeparator(*(i + 2))) {
*(out++) = kPathSeparator;
*(out++) = kPathSeparator;
}
#endif
while (i != pathname_.end()) {
const char character = *i;
for (const char character : pathname_) {
if (!IsPathSeparator(character)) {
*(out++) = character;
} else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
*(out++) = kPathSeparator;
} else {
continue;
}
++i;
}
pathname_.erase(out, pathname_.end());
@@ -410,5 +365,3 @@ void FilePath::Normalize() {
} // namespace internal
} // namespace testing
#endif // GTEST_HAS_FILE_SYSTEM
+21 -27
View File
@@ -44,7 +44,6 @@
#include <algorithm>
#include <cstdint>
#include <memory>
#include <set>
#include <string>
#include <vector>
@@ -55,7 +54,7 @@
#include <netdb.h> // NOLINT
#endif
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
#include <windows.h> // NOLINT
#endif // GTEST_OS_WINDOWS
@@ -92,8 +91,7 @@ GTEST_API_ TimeInMillis GetTimeInMillis();
// Returns true if and only if Google Test should use colors in the output.
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
// Formats the given time in milliseconds as seconds. If the input is an exact N
// seconds, the output has a trailing decimal point (e.g., "N." instead of "N").
// Formats the given time in milliseconds as seconds.
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
// Converts the given time in milliseconds to a date string in the ISO 8601
@@ -214,7 +212,7 @@ class GTestFlagSaver {
int32_t stack_trace_depth_;
std::string stream_result_to_;
bool throw_on_failure_;
};
} GTEST_ATTRIBUTE_UNUSED_;
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
// code_point parameter is of type UInt32 because wchar_t may not be
@@ -384,13 +382,13 @@ class GTEST_API_ UnitTestOptions {
static bool FilterMatchesTest(const std::string& test_suite_name,
const std::string& test_name);
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// Function for supporting the gtest_catch_exception flag.
// Returns EXCEPTION_EXECUTE_HANDLER if given SEH exception was handled, or
// EXCEPTION_CONTINUE_SEARCH otherwise.
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
// This function is useful as an __except condition.
static int GTestProcessSEH(DWORD seh_code, const char* location);
static int GTestShouldProcessSEH(DWORD exception_code);
#endif // GTEST_OS_WINDOWS
// Returns true if "name" matches the ':' separated list of glob-style
@@ -398,17 +396,15 @@ class GTEST_API_ UnitTestOptions {
static bool MatchesFilter(const std::string& name, const char* filter);
};
#if GTEST_HAS_FILE_SYSTEM
// Returns the current application's name, removing directory path if that
// is present. Used by UnitTestOptions::GetOutputFile.
GTEST_API_ FilePath GetCurrentExecutableName();
#endif // GTEST_HAS_FILE_SYSTEM
// The role interface for getting the OS stack trace as a string.
class OsStackTraceGetterInterface {
public:
OsStackTraceGetterInterface() = default;
virtual ~OsStackTraceGetterInterface() = default;
OsStackTraceGetterInterface() {}
virtual ~OsStackTraceGetterInterface() {}
// Returns the current OS stack trace as an std::string. Parameters:
//
@@ -436,13 +432,13 @@ class OsStackTraceGetterInterface {
// A working implementation of the OsStackTraceGetterInterface interface.
class OsStackTraceGetter : public OsStackTraceGetterInterface {
public:
OsStackTraceGetter() = default;
OsStackTraceGetter() {}
std::string CurrentStackTrace(int max_depth, int skip_count) override;
void UponLeavingGTest() override;
private:
#ifdef GTEST_HAS_ABSL
#if GTEST_HAS_ABSL
Mutex mutex_; // Protects all internal state.
// We save the stack frame below the frame that calls user code.
@@ -511,9 +507,9 @@ class GTEST_API_ UnitTestImpl {
virtual ~UnitTestImpl();
// There are two different ways to register your own TestPartResultReporter.
// You can register your own reporter to listen either only for test results
// You can register your own repoter to listen either only for test results
// from the current thread or for results from all threads.
// By default, each per-thread test result reporter just passes a new
// By default, each per-thread test result repoter just passes a new
// TestPartResult to the global test result reporter, which registers the
// test part result for the currently running test.
@@ -672,7 +668,7 @@ class GTEST_API_ UnitTestImpl {
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc,
TestInfo* test_info) {
#if GTEST_HAS_FILE_SYSTEM
#if GTEST_HAS_DEATH_TEST
// In order to support thread-safe death tests, we need to
// remember the original working directory when the test program
// was first invoked. We cannot do this in RUN_ALL_TESTS(), as
@@ -685,7 +681,7 @@ class GTEST_API_ UnitTestImpl {
GTEST_CHECK_(!original_working_dir_.IsEmpty())
<< "Failed to get the current working directory.";
}
#endif // GTEST_HAS_FILE_SYSTEM
#endif // GTEST_HAS_DEATH_TEST
GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
set_up_tc, tear_down_tc)
@@ -778,7 +774,7 @@ class GTEST_API_ UnitTestImpl {
return gtest_trace_stack_.get();
}
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
void InitDeathTestSubprocessControlInfo() {
internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
}
@@ -844,11 +840,9 @@ class GTEST_API_ UnitTestImpl {
// The UnitTest object that owns this implementation object.
UnitTest* const parent_;
#if GTEST_HAS_FILE_SYSTEM
// The working directory when the first TEST() or TEST_F() was
// executed.
internal::FilePath original_working_dir_;
#endif // GTEST_HAS_FILE_SYSTEM
// The default test part result reporters.
DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
@@ -856,7 +850,7 @@ class GTEST_API_ UnitTestImpl {
default_per_thread_test_part_result_reporter_;
// Points to (but doesn't own) the global test part result reporter.
TestPartResultReporterInterface* global_test_part_result_reporter_;
TestPartResultReporterInterface* global_test_part_result_repoter_;
// Protects read and write access to global_test_part_result_reporter_.
internal::Mutex global_test_part_result_reporter_mutex_;
@@ -943,7 +937,7 @@ class GTEST_API_ UnitTestImpl {
// How long the test took to run, in milliseconds.
TimeInMillis elapsed_time_;
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
// The decomposed components of the gtest_internal_run_death_test flag,
// parsed when RUN_ALL_TESTS is called.
std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
@@ -967,7 +961,7 @@ inline UnitTestImpl* GetUnitTestImpl() {
return UnitTest::GetInstance()->impl();
}
#ifdef GTEST_USES_SIMPLE_RE
#if GTEST_USES_SIMPLE_RE
// Internal helper functions for implementing the simple regular
// expression matcher.
@@ -993,7 +987,7 @@ GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
// Returns the message describing the last system error, regardless of the
// platform.
@@ -1064,7 +1058,7 @@ class StreamingListener : public EmptyTestEventListener {
// Abstract base class for writing strings to a socket.
class AbstractSocketWriter {
public:
virtual ~AbstractSocketWriter() = default;
virtual ~AbstractSocketWriter() {}
// Sends a string to the socket.
virtual void Send(const std::string& message) = 0;
+56 -54
View File
@@ -37,12 +37,8 @@
#include <cstdint>
#include <fstream>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
#include <io.h>
#include <sys/stat.h>
#include <windows.h>
@@ -55,34 +51,32 @@
#include <unistd.h>
#endif // GTEST_OS_WINDOWS
#ifdef GTEST_OS_MAC
#if GTEST_OS_MAC
#include <mach/mach_init.h>
#include <mach/task.h>
#include <mach/vm_map.h>
#endif // GTEST_OS_MAC
#if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD) || \
defined(GTEST_OS_OPENBSD)
#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
GTEST_OS_NETBSD || GTEST_OS_OPENBSD
#include <sys/sysctl.h>
#if defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
defined(GTEST_OS_GNU_KFREEBSD)
#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
#include <sys/user.h>
#endif
#endif
#ifdef GTEST_OS_QNX
#if GTEST_OS_QNX
#include <devctl.h>
#include <fcntl.h>
#include <sys/procfs.h>
#endif // GTEST_OS_QNX
#ifdef GTEST_OS_AIX
#if GTEST_OS_AIX
#include <procinfo.h>
#include <sys/types.h>
#endif // GTEST_OS_AIX
#ifdef GTEST_OS_FUCHSIA
#if GTEST_OS_FUCHSIA
#include <zircon/process.h>
#include <zircon/syscalls.h>
#endif // GTEST_OS_FUCHSIA
@@ -96,7 +90,7 @@
namespace testing {
namespace internal {
#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_GNU_HURD)
#if GTEST_OS_LINUX || GTEST_OS_GNU_HURD
namespace {
template <typename T>
@@ -119,7 +113,7 @@ size_t GetThreadCount() {
return ReadProcFileField<size_t>(filename, 19);
}
#elif defined(GTEST_OS_MAC)
#elif GTEST_OS_MAC
size_t GetThreadCount() {
const task_t task = mach_task_self();
@@ -137,20 +131,20 @@ size_t GetThreadCount() {
}
}
#elif defined(GTEST_OS_DRAGONFLY) || defined(GTEST_OS_FREEBSD) || \
defined(GTEST_OS_GNU_KFREEBSD) || defined(GTEST_OS_NETBSD)
#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \
GTEST_OS_NETBSD
#ifdef GTEST_OS_NETBSD
#if GTEST_OS_NETBSD
#undef KERN_PROC
#define KERN_PROC KERN_PROC2
#define kinfo_proc kinfo_proc2
#endif
#ifdef GTEST_OS_DRAGONFLY
#if GTEST_OS_DRAGONFLY
#define KP_NLWP(kp) (kp.kp_nthreads)
#elif defined(GTEST_OS_FREEBSD) || defined(GTEST_OS_GNU_KFREEBSD)
#elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD
#define KP_NLWP(kp) (kp.ki_numthreads)
#elif defined(GTEST_OS_NETBSD)
#elif GTEST_OS_NETBSD
#define KP_NLWP(kp) (kp.p_nlwps)
#endif
@@ -162,7 +156,7 @@ size_t GetThreadCount() {
KERN_PROC,
KERN_PROC_PID,
getpid(),
#ifdef GTEST_OS_NETBSD
#if GTEST_OS_NETBSD
sizeof(struct kinfo_proc),
1,
#endif
@@ -175,7 +169,7 @@ size_t GetThreadCount() {
}
return static_cast<size_t>(KP_NLWP(info));
}
#elif defined(GTEST_OS_OPENBSD)
#elif GTEST_OS_OPENBSD
// Returns the number of threads running in the process, or 0 to indicate that
// we cannot detect it.
@@ -199,8 +193,8 @@ size_t GetThreadCount() {
mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
// populate array of structs
std::vector<struct kinfo_proc> info(mib[5]);
if (sysctl(mib, miblen, info.data(), &size, NULL, 0)) {
struct kinfo_proc info[mib[5]];
if (sysctl(mib, miblen, &info, &size, NULL, 0)) {
return 0;
}
@@ -212,7 +206,7 @@ size_t GetThreadCount() {
return nthreads;
}
#elif defined(GTEST_OS_QNX)
#elif GTEST_OS_QNX
// Returns the number of threads running in the process, or 0 to indicate that
// we cannot detect it.
@@ -232,7 +226,7 @@ size_t GetThreadCount() {
}
}
#elif defined(GTEST_OS_AIX)
#elif GTEST_OS_AIX
size_t GetThreadCount() {
struct procentry64 entry;
@@ -245,7 +239,7 @@ size_t GetThreadCount() {
}
}
#elif defined(GTEST_OS_FUCHSIA)
#elif GTEST_OS_FUCHSIA
size_t GetThreadCount() {
int dummy_buffer;
@@ -270,7 +264,7 @@ size_t GetThreadCount() {
#endif // GTEST_OS_LINUX
#if defined(GTEST_IS_THREADSAFE) && defined(GTEST_OS_WINDOWS)
#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
@@ -661,7 +655,7 @@ void ThreadLocalRegistry::OnThreadLocalDestroyed(
#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
#ifdef GTEST_USES_POSIX_RE
#if GTEST_USES_POSIX_RE
// Implements RE. Currently only needed for death tests.
@@ -674,6 +668,7 @@ RE::~RE() {
regfree(&partial_regex_);
regfree(&full_regex_);
}
free(const_cast<char*>(pattern_));
}
// Returns true if and only if regular expression re matches the entire str.
@@ -695,7 +690,7 @@ bool RE::PartialMatch(const char* str, const RE& re) {
// Initializes an RE from its string representation.
void RE::Init(const char* regex) {
pattern_ = regex;
pattern_ = posix::StrDup(regex);
// Reserves enough bytes to hold the regular expression used for a
// full match.
@@ -723,7 +718,7 @@ void RE::Init(const char* regex) {
delete[] full_pattern;
}
#elif defined(GTEST_USES_SIMPLE_RE)
#elif GTEST_USES_SIMPLE_RE
// Returns true if and only if ch appears anywhere in str (excluding the
// terminating '\0' character).
@@ -925,26 +920,27 @@ bool MatchRegexAnywhere(const char* regex, const char* str) {
// Implements the RE class.
RE::~RE() = default;
RE::~RE() {
free(const_cast<char*>(pattern_));
free(const_cast<char*>(full_pattern_));
}
// Returns true if and only if regular expression re matches the entire str.
bool RE::FullMatch(const char* str, const RE& re) {
return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_.c_str(), str);
return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
}
// Returns true if and only if regular expression re matches a substring of
// str (including str itself).
bool RE::PartialMatch(const char* str, const RE& re) {
return re.is_valid_ && MatchRegexAnywhere(re.pattern_.c_str(), str);
return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
}
// Initializes an RE from its string representation.
void RE::Init(const char* regex) {
full_pattern_.clear();
pattern_.clear();
pattern_ = full_pattern_ = nullptr;
if (regex != nullptr) {
pattern_ = regex;
pattern_ = posix::StrDup(regex);
}
is_valid_ = ValidateRegex(regex);
@@ -953,19 +949,25 @@ void RE::Init(const char* regex) {
return;
}
const size_t len = strlen(regex);
// Reserves enough bytes to hold the regular expression used for a
// full match: we need space to prepend a '^' and append a '$'.
full_pattern_.reserve(pattern_.size() + 2);
// full match: we need space to prepend a '^', append a '$', and
// terminate the string with '\0'.
char* buffer = static_cast<char*>(malloc(len + 3));
full_pattern_ = buffer;
if (pattern_.empty() || pattern_.front() != '^') {
full_pattern_.push_back('^'); // Makes sure full_pattern_ starts with '^'.
}
if (*regex != '^')
*buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
full_pattern_.append(pattern_);
// We don't use snprintf or strncpy, as they trigger a warning when
// compiled with VC++ 8.0.
memcpy(buffer, regex, len);
buffer += len;
if (pattern_.empty() || pattern_.back() != '$') {
full_pattern_.push_back('$'); // Makes sure full_pattern_ ends with '$'.
}
if (len == 0 || regex[len - 1] != '$')
*buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
*buffer = '\0';
}
#endif // GTEST_USES_POSIX_RE
@@ -1033,7 +1035,7 @@ class CapturedStream {
public:
// The ctor redirects the stream to a temporary file.
explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT
char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT
@@ -1052,7 +1054,7 @@ class CapturedStream {
// directory, so we create the temporary file in a temporary directory.
std::string name_template;
#ifdef GTEST_OS_LINUX_ANDROID
#if GTEST_OS_LINUX_ANDROID
// Note: Android applications are expected to call the framework's
// Context.getExternalStorageDirectory() method through JNI to get
// the location of the world-writable SD Card directory. However,
@@ -1065,7 +1067,7 @@ class CapturedStream {
// '/sdcard' and other variants cannot be relied on, as they are not
// guaranteed to be mounted, or may have a delay in mounting.
name_template = "/data/local/tmp/";
#elif defined(GTEST_OS_IOS)
#elif GTEST_OS_IOS
char user_temp_dir[PATH_MAX + 1];
// Documented alternative to NSTemporaryDirectory() (for obtaining creating
@@ -1225,7 +1227,7 @@ std::string ReadEntireFile(FILE* file) {
return content;
}
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
static const std::vector<std::string>* g_injected_test_argvs =
nullptr; // Owned.
@@ -1252,7 +1254,7 @@ void ClearInjectableArgvs() {
}
#endif // GTEST_HAS_DEATH_TEST
#ifdef GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE
namespace posix {
void Abort() {
DebugBreak();
+6 -8
View File
@@ -47,8 +47,6 @@
#include <cctype>
#include <cstdint>
#include <cwchar>
#include <iomanip>
#include <ios>
#include <ostream> // NOLINT
#include <string>
#include <type_traits>
@@ -216,7 +214,7 @@ static const char* GetCharWidthPrefix(signed char) { return ""; }
static const char* GetCharWidthPrefix(unsigned char) { return ""; }
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
static const char* GetCharWidthPrefix(char8_t) { return "u8"; }
#endif
@@ -232,7 +230,7 @@ static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
return PrintAsStringLiteralTo(ToChar32(c), os);
}
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
return PrintAsStringLiteralTo(ToChar32(c), os);
}
@@ -317,7 +315,7 @@ void PrintTo(__uint128_t v, ::std::ostream* os) {
low = low / 10 + high_mod * 1844674407370955161 + carry / 10;
char digit = static_cast<char>(carry % 10);
*--p = static_cast<char>('0' + digit);
*--p = '0' + digit;
}
*os << p;
}
@@ -395,7 +393,7 @@ void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os);
}
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
// Prints a (const) char8_t array of 'len' elements, starting at address
// 'begin'.
void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
@@ -438,7 +436,7 @@ void PrintCStringTo(const Char* s, ostream* os) {
void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
#endif
@@ -530,7 +528,7 @@ void PrintStringTo(const ::std::string& s, ostream* os) {
}
}
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
+2 -3
View File
@@ -32,14 +32,13 @@
#include "gtest/gtest-test-part.h"
#include <ostream>
#include <string>
#include "gtest/internal/gtest-port.h"
#include "src/gtest-internal-inl.h"
namespace testing {
using internal::GetUnitTestImpl;
// Gets the summary of the failure message by omitting the stack trace
// in it.
std::string TestPartResult::ExtractSummary(const char* message) {
+1 -5
View File
@@ -29,10 +29,6 @@
#include "gtest/gtest-typed-test.h"
#include <set>
#include <string>
#include <vector>
#include "gtest/gtest.h"
namespace testing {
@@ -94,7 +90,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames(
}
const std::string& errors_str = errors.GetString();
if (!errors_str.empty()) {
if (errors_str != "") {
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
errors_str.c_str());
fflush(stderr);

Some files were not shown because too many files have changed in this diff Show More