Upgrade GoogleTest to 1.16.0

This commit is contained in:
Sam Vervaeck 2025-02-14 20:03:30 +01:00
parent 17c967a475
commit 2a892b3d48
Signed by: samvv
SSH key fingerprint: SHA256:dIg0ywU1OP+ZYifrYxy8c5esO72cIKB+4/9wkZj1VaY
255 changed files with 7975 additions and 5233 deletions

1
deps/googletest vendored Symbolic link
View file

@ -0,0 +1 @@
googletest-1.16.0

View file

@ -0,0 +1,53 @@
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

View file

@ -0,0 +1,33 @@
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

View file

@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Get Help
url: https://github.com/google/googletest/discussions
about: Please ask and answer questions here.

View file

@ -8,6 +8,7 @@ bazel-genfiles
bazel-googletest bazel-googletest
bazel-out bazel-out
bazel-testlogs bazel-testlogs
MODULE.bazel.lock
# python # python
*.pyc *.pyc
@ -24,6 +25,10 @@ Win32-Release/
x64-Debug/ x64-Debug/
x64-Release/ x64-Release/
# VSCode files
.cache/
cmake-variants.yaml
# Ignore autoconf / automake files # Ignore autoconf / automake files
Makefile.in Makefile.in
aclocal.m4 aclocal.m4

View file

@ -56,6 +56,12 @@ config_setting(
constraint_values = ["@platforms//os:openbsd"], constraint_values = ["@platforms//os:openbsd"],
) )
# NOTE: Fuchsia is not an officially supported platform.
config_setting(
name = "fuchsia",
constraint_values = ["@platforms//os:fuchsia"],
)
config_setting( config_setting(
name = "msvc_compiler", name = "msvc_compiler",
flag_values = { flag_values = {
@ -132,18 +138,30 @@ cc_library(
}), }),
deps = select({ deps = select({
":has_absl": [ ":has_absl": [
"@com_google_absl//absl/debugging:failure_signal_handler", "@abseil-cpp//absl/container:flat_hash_set",
"@com_google_absl//absl/debugging:stacktrace", "@abseil-cpp//absl/debugging:failure_signal_handler",
"@com_google_absl//absl/debugging:symbolize", "@abseil-cpp//absl/debugging:stacktrace",
"@com_google_absl//absl/flags:flag", "@abseil-cpp//absl/debugging:symbolize",
"@com_google_absl//absl/flags:parse", "@abseil-cpp//absl/flags:flag",
"@com_google_absl//absl/flags:reflection", "@abseil-cpp//absl/flags:parse",
"@com_google_absl//absl/flags:usage", "@abseil-cpp//absl/flags:reflection",
"@com_google_absl//absl/strings", "@abseil-cpp//absl/flags:usage",
"@com_google_absl//absl/types:any", "@abseil-cpp//absl/strings",
"@com_google_absl//absl/types:optional", "@abseil-cpp//absl/types:any",
"@com_google_absl//absl/types:variant", "@abseil-cpp//absl/types:optional",
"@com_googlesource_code_re2//:re2", "@abseil-cpp//absl/types:variant",
"@re2//:re2",
],
"//conditions:default": [],
}) + select({
# `gtest-death-test.cc` has `EXPECT_DEATH` that spawns a process,
# expects it to crash and inspects its logs with the given matcher,
# so that's why these libraries are needed.
# Otherwise, builds targeting Fuchsia would fail to compile.
":fuchsia": [
"@fuchsia_sdk//pkg/fdio",
"@fuchsia_sdk//pkg/syslog",
"@fuchsia_sdk//pkg/zx",
], ],
"//conditions:default": [], "//conditions:default": [],
}), }),

View file

@ -1,18 +1,10 @@
# Note: CMake support is community-based. The maintainers do not use CMake # Note: CMake support is community-based. The maintainers do not use CMake
# internally. # internally.
cmake_minimum_required(VERSION 3.5) cmake_minimum_required(VERSION 3.13)
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) project(googletest-distribution)
set(GOOGLETEST_VERSION 1.12.1) set(GOOGLETEST_VERSION 1.16.0)
if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_EXTENSIONS OFF)
@ -23,9 +15,19 @@ enable_testing()
include(CMakeDependentOption) include(CMakeDependentOption)
include(GNUInstallDirs) include(GNUInstallDirs)
#Note that googlemock target already builds googletest # Note that googlemock target already builds googletest.
option(BUILD_GMOCK "Builds the googlemock subproject" ON) option(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(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON)
option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF)
if(GTEST_HAS_ABSL)
if(NOT TARGET absl::base)
find_package(absl REQUIRED)
endif()
if(NOT TARGET re2::re2)
find_package(re2 REQUIRED)
endif()
endif()
if(BUILD_GMOCK) if(BUILD_GMOCK)
add_subdirectory( googlemock ) add_subdirectory( googlemock )

View file

@ -47,11 +47,11 @@ PR is acceptable as an alternative.
## The Google Test and Google Mock Communities ## The Google Test and Google Mock Communities
The Google Test community exists primarily through the The Google Test community exists primarily through the
[discussion group](http://groups.google.com/group/googletestframework) and the [discussion group](https://groups.google.com/group/googletestframework) and the
GitHub repository. Likewise, the Google Mock community exists primarily through GitHub repository. Likewise, the Google Mock community exists primarily through
their own [discussion group](http://groups.google.com/group/googlemock). You are their own [discussion group](https://groups.google.com/group/googlemock). You
definitely encouraged to contribute to the discussion and you can also help us are definitely encouraged to contribute to the discussion and you can also help
to keep the effectiveness of the group high by following and promoting the us to keep the effectiveness of the group high by following and promoting the
guidelines listed here. guidelines listed here.
### Please Be Friendly ### Please Be Friendly
@ -80,15 +80,15 @@ fairly rigid coding style, as defined by the
[google-styleguide](https://github.com/google/styleguide) project. All patches [google-styleguide](https://github.com/google/styleguide) project. All patches
will be expected to conform to the style outlined will be expected to conform to the style outlined
[here](https://google.github.io/styleguide/cppguide.html). Use [here](https://google.github.io/styleguide/cppguide.html). Use
[.clang-format](https://github.com/google/googletest/blob/master/.clang-format) [.clang-format](https://github.com/google/googletest/blob/main/.clang-format) to
to check your formatting. check your formatting.
## Requirements for Contributors ## Requirements for Contributors
If you plan to contribute a patch, you need to build Google Test, Google Mock, 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: and their own tests from a git checkout, which has further requirements:
* [Python](https://www.python.org/) v2.3 or newer (for running some of the * [Python](https://www.python.org/) v3.6 or newer (for running some of the
tests and re-generating certain source files from templates) tests and re-generating certain source files from templates)
* [CMake](https://cmake.org/) v2.8.12 or newer * [CMake](https://cmake.org/) v2.8.12 or newer
@ -102,30 +102,40 @@ 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 functionality, you'll want to compile and run Google Test and GoogleMock's own
tests. For that you can use CMake: tests. For that you can use CMake:
```
mkdir mybuild mkdir mybuild
cd mybuild cd mybuild
cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR} 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 To choose between building only Google Test or Google Mock, you may modify your
cmake command to be one of each cmake command to be one of each
```
cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test 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 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 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 in Python. If the cmake command complains about not being able to find Python
(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it (`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it
explicitly where your Python executable can be found: 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 Next, you can build Google Test and / or Google Mock and all desired tests. On
\*nix, this is usually done by \*nix, this is usually done by
```
make make
```
To run the tests, do To run the tests, do
```
make test make test
```
All tests should pass. All tests should pass.

View file

@ -55,6 +55,7 @@ Russ Cox <rsc@google.com>
Russ Rufer <russ@pentad.com> Russ Rufer <russ@pentad.com>
Sean Mcafee <eefacm@gmail.com> Sean Mcafee <eefacm@gmail.com>
Sigurður Ásgeirsson <siggi@google.com> Sigurður Ásgeirsson <siggi@google.com>
Soyeon Kim <sxshx818@naver.com>
Sverre Sundsdal <sundsdal@gmail.com> Sverre Sundsdal <sundsdal@gmail.com>
Szymon Sobik <sobik.szymon@gmail.com> Szymon Sobik <sobik.szymon@gmail.com>
Takeshi Yoshino <tyoshino@google.com> Takeshi Yoshino <tyoshino@google.com>

76
deps/googletest-1.16.0/MODULE.bazel vendored Normal file
View file

@ -0,0 +1,76 @@
# Copyright 2024 Google Inc.
# All Rights Reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# https://bazel.build/external/overview#bzlmod
module(
name = "googletest",
version = "1.16.0",
compatibility_level = 1,
)
# Only direct dependencies need to be listed below.
# Please keep the versions in sync with the versions in the WORKSPACE file.
bazel_dep(
name = "abseil-cpp",
version = "20250127.0",
)
bazel_dep(
name = "platforms",
version = "0.0.10",
)
bazel_dep(
name = "re2",
version = "2024-07-02",
)
bazel_dep(
name = "rules_python",
version = "1.1.0",
dev_dependency = True,
)
# https://rules-python.readthedocs.io/en/stable/toolchains.html#library-modules-with-dev-only-python-usage
python = use_extension(
"@rules_python//python/extensions:python.bzl",
"python",
dev_dependency = True,
)
python.toolchain(
ignore_root_user_error = True,
is_default = True,
python_version = "3.12",
)
# See fake_fuchsia_sdk.bzl for instructions on how to override this with a real SDK, if needed.
fuchsia_sdk = use_extension("//:fake_fuchsia_sdk.bzl", "fuchsia_sdk")
fuchsia_sdk.create_fake()
use_repo(fuchsia_sdk, "fuchsia_sdk")

View file

@ -8,6 +8,8 @@ GoogleTest now follows the
[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support). [Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
We recommend 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). [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.16.0`).
#### Documentation Updates #### Documentation Updates
@ -15,16 +17,21 @@ Our documentation is now live on GitHub Pages at
https://google.github.io/googletest/. We recommend browsing the documentation on https://google.github.io/googletest/. We recommend browsing the documentation on
GitHub Pages rather than directly in the repository. GitHub Pages rather than directly in the repository.
#### Release 1.11.0 #### Release 1.16.0
[Release 1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0) [Release 1.16.0](https://github.com/google/googletest/releases/tag/v1.16.0) is
is now available. now available.
The 1.16.x branch requires at least C++14.
#### Continuous Integration
We use Google's internal systems for continuous integration.
#### Coming Soon #### Coming Soon
* We are planning to take a dependency on * We are planning to take a dependency on
[Abseil](https://github.com/abseil/abseil-cpp). [Abseil](https://github.com/abseil/abseil-cpp).
* More documentation improvements are planned.
## Welcome to **GoogleTest**, Google's C++ test framework! ## Welcome to **GoogleTest**, Google's C++ test framework!
@ -43,64 +50,58 @@ More information about building GoogleTest can be found at
## Features ## Features
* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework. * xUnit test framework: \
* Test discovery. Googletest is based on the [xUnit](https://en.wikipedia.org/wiki/XUnit)
* A rich set of assertions. testing framework, a popular architecture for unit testing
* User-defined assertions. * Test discovery: \
* Death tests. Googletest automatically discovers and runs your tests, eliminating the need
* Fatal and non-fatal failures. to manually register your tests
* Value-parameterized tests. * Rich set of assertions: \
* Type-parameterized tests. Googletest provides a variety of assertions, such as equality, inequality,
* Various options for running the tests. exceptions, and more, making it easy to test your code
* XML test report generation. * 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
## Supported Platforms ## Supported Platforms
GoogleTest requires a codebase and compiler compliant with the C++11 standard or GoogleTest follows Google's
newer. [Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See
The GoogleTest code is officially supported on the following platforms. [this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
Operating systems or tools not listed below are community-supported. For for a list of currently supported versions of compilers, platforms, and build
community-supported platforms, patches that do not complicate the code may be tools.
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? ## Who Is Using GoogleTest?
In addition to many internal projects at Google, GoogleTest is also used by the In addition to many internal projects at Google, GoogleTest is also used by the
following notable projects: following notable projects:
* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser * The [Chromium projects](https://www.chromium.org/) (behind the Chrome
and Chrome OS). browser and Chrome OS).
* The [LLVM](http://llvm.org/) compiler. * The [LLVM](https://llvm.org/) compiler.
* [Protocol Buffers](https://github.com/google/protobuf), Google's data * [Protocol Buffers](https://github.com/google/protobuf), Google's data
interchange format. interchange format.
* The [OpenCV](http://opencv.org/) computer vision library. * The [OpenCV](https://opencv.org/) computer vision library.
## Related Open Source Projects ## Related Open Source Projects
@ -135,7 +136,7 @@ that generates stub code for GoogleTest.
## Contributing Changes ## Contributing Changes
Please read Please read
[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/master/CONTRIBUTING.md) [`CONTRIBUTING.md`](https://github.com/google/googletest/blob/main/CONTRIBUTING.md)
for details on how to contribute to this project. for details on how to contribute to this project.
Happy testing! Happy testing!

61
deps/googletest-1.16.0/WORKSPACE vendored Normal file
View file

@ -0,0 +1,61 @@
# Copyright 2024 Google Inc.
# All Rights Reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
workspace(name = "googletest")
load("//:googletest_deps.bzl", "googletest_deps")
googletest_deps()
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rules_python",
sha256 = "9c6e26911a79fbf510a8f06d8eedb40f412023cf7fa6d1461def27116bff022c",
strip_prefix = "rules_python-1.1.0",
url = "https://github.com/bazelbuild/rules_python/releases/download/1.1.0/rules_python-1.1.0.tar.gz",
)
# https://github.com/bazelbuild/rules_python/releases/tag/1.1.0
load("@rules_python//python:repositories.bzl", "py_repositories")
py_repositories()
http_archive(
name = "bazel_skylib",
sha256 = "cd55a062e763b9349921f0f5db8c3933288dc8ba4f76dd9416aac68acee3cb94",
urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.5.0/bazel-skylib-1.5.0.tar.gz"],
)
http_archive(
name = "platforms",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.10/platforms-0.0.10.tar.gz",
"https://github.com/bazelbuild/platforms/releases/download/0.0.10/platforms-0.0.10.tar.gz",
],
sha256 = "218efe8ee736d26a3572663b374a253c012b716d8af0c07e842e82f238a0a7ee",
)

35
deps/googletest-1.16.0/WORKSPACE.bzlmod vendored Normal file
View file

@ -0,0 +1,35 @@
# Copyright 2024 Google Inc.
# All Rights Reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# https://bazel.build/external/migration#workspace.bzlmod
#
# This file is intentionally empty. When bzlmod is enabled and this
# file exists, the content of WORKSPACE is ignored. This prevents
# bzlmod builds from unintentionally depending on the WORKSPACE file.

View file

@ -31,15 +31,15 @@
set -euox pipefail set -euox pipefail
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20220217" readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20241218"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20220621" readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20250205"
if [[ -z ${GTEST_ROOT:-} ]]; then if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)" GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi fi
if [[ -z ${STD:-} ]]; then if [[ -z ${STD:-} ]]; then
STD="c++11 c++14 c++17 c++20" STD="c++14 c++17 c++20"
fi fi
# Test the CMake build # Test the CMake build
@ -51,11 +51,11 @@ for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
--workdir="/build" \ --workdir="/build" \
--rm \ --rm \
--env="CC=${cc}" \ --env="CC=${cc}" \
--env="CXX_FLAGS=\"-Werror -Wdeprecated\"" \ --env=CXXFLAGS="-Werror -Wdeprecated" \
${LINUX_LATEST_CONTAINER} \ ${LINUX_LATEST_CONTAINER} \
/bin/bash -c " /bin/bash -c "
cmake /src \ cmake /src \
-DCMAKE_CXX_STANDARD=11 \ -DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \ -Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \ -Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \ -Dgmock_build_tests=ON \
@ -67,18 +67,23 @@ for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
done done
# Do one test with an older version of GCC # Do one test with an older version of GCC
# TODO(googletest-team): This currently uses Bazel 5. When upgrading to a
# version of Bazel that supports Bzlmod, add --enable_bzlmod=false to keep test
# coverage for the old WORKSPACE dependency management.
time docker run \ time docker run \
--volume="${GTEST_ROOT}:/src:ro" \ --volume="${GTEST_ROOT}:/src:ro" \
--workdir="/src" \ --workdir="/src" \
--rm \ --rm \
--env="CC=/usr/local/bin/gcc" \ --env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=c++14" \
${LINUX_GCC_FLOOR_CONTAINER} \ ${LINUX_GCC_FLOOR_CONTAINER} \
/usr/local/bin/bazel test ... \ /usr/local/bin/bazel test ... \
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wuninitialized" \ --copt="-Wuninitialized" \
--copt="-Wundef" \
--copt="-Wno-error=pragmas" \ --copt="-Wno-error=pragmas" \
--distdir="/bazel-distdir" \ --features=external_include_paths \
--keep_going \ --keep_going \
--show_timestamps \ --show_timestamps \
--test_output=errors --test_output=errors
@ -97,8 +102,10 @@ for std in ${STD}; do
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wuninitialized" \ --copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \ --define="absl=${absl}" \
--distdir="/bazel-distdir" \ --enable_bzlmod=true \
--features=external_include_paths \
--keep_going \ --keep_going \
--show_timestamps \ --show_timestamps \
--test_output=errors --test_output=errors
@ -120,8 +127,10 @@ for std in ${STD}; do
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wuninitialized" \ --copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \ --define="absl=${absl}" \
--distdir="/bazel-distdir" \ --enable_bzlmod=true \
--features=external_include_paths \
--keep_going \ --keep_going \
--linkopt="--gcc-toolchain=/usr/local" \ --linkopt="--gcc-toolchain=/usr/local" \
--show_timestamps \ --show_timestamps \

View file

@ -40,7 +40,7 @@ for cmake_off_on in OFF ON; do
BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX) BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)
cd ${BUILD_DIR} cd ${BUILD_DIR}
time cmake ${GTEST_ROOT} \ time cmake ${GTEST_ROOT} \
-DCMAKE_CXX_STANDARD=11 \ -DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \ -Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \ -Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \ -Dgmock_build_tests=ON \
@ -53,7 +53,7 @@ done
# Test the Bazel build # Test the Bazel build
# If we are running on Kokoro, check for a versioned Bazel binary. # If we are running on Kokoro, check for a versioned Bazel binary.
KOKORO_GFILE_BAZEL_BIN="bazel-3.7.0-darwin-x86_64" KOKORO_GFILE_BAZEL_BIN="bazel-7.0.0-darwin-x86_64"
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then
BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}" BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}"
chmod +x ${BAZEL_BIN} chmod +x ${BAZEL_BIN}
@ -66,7 +66,11 @@ for absl in 0 1; do
${BAZEL_BIN} test ... \ ${BAZEL_BIN} test ... \
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wundef" \
--cxxopt="-std=c++14" \
--define="absl=${absl}" \ --define="absl=${absl}" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \ --keep_going \
--show_timestamps \ --show_timestamps \
--test_output=errors --test_output=errors

View file

@ -0,0 +1,63 @@
SETLOCAL ENABLEDELAYEDEXPANSION
SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-7.0.0-windows-x86_64.exe
SET PATH=C:\Python34;%PATH%
SET BAZEL_PYTHON=C:\python34\python.exe
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
:: The default home directory on Kokoro is a long path which causes errors
:: because of Windows limitations on path length.
:: --output_user_root=C:\tmp causes Bazel to use a shorter path.
SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community
%BAZEL_EXE% ^
--output_user_root=C:\tmp ^
test ... ^
--compilation_mode=dbg ^
--copt=/std:c++14 ^
--copt=/WX ^
--enable_bzlmod=true ^
--keep_going ^
--test_output=errors ^
--test_tag_filters=-no_test_msvc2017
IF %errorlevel% neq 0 EXIT /B 1

View file

@ -48,7 +48,7 @@
<div class="footer"> <div class="footer">
GoogleTest &middot; GoogleTest &middot;
<a href="https://github.com/google/googletest">GitHub Repository</a> &middot; <a href="https://github.com/google/googletest">GitHub Repository</a> &middot;
<a href="https://github.com/google/googletest/blob/master/LICENSE">License</a> &middot; <a href="https://github.com/google/googletest/blob/main/LICENSE">License</a> &middot;
<a href="https://policies.google.com/privacy">Privacy Policy</a> <a href="https://policies.google.com/privacy">Privacy Policy</a>
</div> </div>
</div> </div>

View file

@ -1,9 +1,9 @@
# Advanced googletest Topics # Advanced GoogleTest Topics
## Introduction ## Introduction
Now that you have read the [googletest Primer](primer.md) and learned how to 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 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 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 messages, propagate fatal failures, reuse and speed up your test fixtures, and
use various flags with your tests. use various flags with your tests.
@ -25,7 +25,7 @@ Reference.
### Predicate Assertions for Better Error Messages ### 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 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 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 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 is awkward especially when the expression has side-effects or is expensive to
evaluate. 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 #### Using an Existing Boolean Function
@ -286,7 +286,7 @@ For example:
```c++ ```c++
TEST(SkipTest, DoesSkip) { TEST(SkipTest, DoesSkip) {
GTEST_SKIP() << "Skipping single test"; GTEST_SKIP() << "Skipping single test";
EXPECT_EQ(0, 1); // Won't fail; it won't be executed FAIL(); // Won't fail; it won't be executed
} }
class SkipFixture : public ::testing::Test { class SkipFixture : public ::testing::Test {
@ -298,15 +298,15 @@ class SkipFixture : public ::testing::Test {
// Tests for SkipFixture won't be executed. // Tests for SkipFixture won't be executed.
TEST_F(SkipFixture, SkipsOneTest) { TEST_F(SkipFixture, SkipsOneTest) {
EXPECT_EQ(5, 7); // Won't fail FAIL(); // Won't fail; it won't be executed
} }
``` ```
As with assertion macros, you can stream a custom message into `GTEST_SKIP()`. 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. 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 This printer knows how to print built-in C++ types, native arrays, STL
@ -315,73 +315,141 @@ 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 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 to do a better job at printing your particular type than to dump the bytes. To
do that, define `<<` for your type: do that, define an `AbslStringify()` overload as a `friend` function template
for your type:
```c++
#include <ostream>
```cpp
namespace foo { namespace foo {
class Bar { // We want googletest to be able to print instances of this. class Point { // We want GoogleTest to be able to print instances of this.
... ...
// Create a free inline friend function. // Provide a friend overload.
friend std::ostream& operator<<(std::ostream& os, const Bar& bar) { template <typename Sink>
return os << bar.DebugString(); // whatever needed to print bar to os 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 // 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 // AbslStringify overload is defined in the SAME namespace that defines Point.
// rules rely on that. // C++'s look-up rules rely on that.
std::ostream& operator<<(std::ostream& os, const Bar& bar) { enum class EnumWithStringify { kMany = 0, kChoices = 1 };
return os << bar.DebugString(); // whatever needed to print bar to os
template <typename Sink>
void AbslStringify(Sink& sink, EnumWithStringify e) {
absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices");
} }
} // namespace foo } // namespace foo
``` ```
Sometimes, this might not be an option: your team may consider it bad style to {: .callout .note}
have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its
doesn't do what you want (and you cannot change it). If so, you can instead string. For more information about supported operations on `AbslStringify()`'s
define a `PrintTo()` function like this: 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:
```c++ ```c++
#include <ostream> #include <ostream>
namespace foo { namespace foo {
class Bar { class Point {
... ...
friend void PrintTo(const Bar& bar, std::ostream* os) { friend void PrintTo(const Point& point, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os *os << "(" << point.x << "," << point.y << ")";
} }
int x;
int y;
}; };
// If you can't declare the function in the class it's important that PrintTo() // 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 // is defined in the SAME namespace that defines Point. C++'s look-up rules
// on that. // rely on that.
void PrintTo(const Bar& bar, std::ostream* os) { void PrintTo(const Point& point, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os *os << "(" << point.x << "," << point.y << ")";
} }
} // namespace foo } // namespace foo
``` ```
If you have defined both `<<` and `PrintTo()`, the latter will be used when If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be
googletest is concerned. This allows you to customize how the value appears in 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 its GoogleTest's output without affecting code that relies on the behavior of
`<<` operator. `AbslStringify()`.
If you want to print a value `x` using googletest's value printer yourself, just If you have an existing `<<` operator and would like to define an
`AbslStringify()`, the latter will be used for GoogleTest printing.
If you want to print a value `x` using GoogleTest's value printer yourself, just
call `::testing::PrintToString(x)`, which returns an `std::string`: call `::testing::PrintToString(x)`, which returns an `std::string`:
```c++ ```c++
vector<pair<Bar, int> > bar_ints = GetBarIntVector(); vector<pair<Point, int> > point_ints = GetPointIntVector();
EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) EXPECT_TRUE(IsCorrectPointIntVector(point_ints))
<< "bar_ints = " << testing::PrintToString(bar_ints); << "point_ints = " << testing::PrintToString(point_ints);
``` ```
For more details regarding `AbslStringify()` and its integration with other
libraries, see go/abslstringify.
## Regular Expression Syntax
When built with Bazel and using Abseil, GoogleTest uses the
[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX
systems (Linux, Cygwin, Mac), GoogleTest uses the
[POSIX extended regular expression](https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
syntax. To learn about POSIX syntax, you may want to read this
[Wikipedia entry](https://en.wikipedia.org/wiki/Regular_expression#POSIX_extended).
On Windows, GoogleTest uses its own simple regular expression implementation. It
lacks many features. For example, we don't support union (`"x|y"`), grouping
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period
(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular
expressions.):
Expression | Meaning
---------- | --------------------------------------------------------------
`c` | matches any literal character `c`
`\\d` | matches any decimal digit
`\\D` | matches any character that's not a decimal digit
`\\f` | matches `\f`
`\\n` | matches `\n`
`\\r` | matches `\r`
`\\s` | matches any ASCII whitespace, including `\n`
`\\S` | matches any character that's not a whitespace
`\\t` | matches `\t`
`\\v` | matches `\v`
`\\w` | matches any letter, `_`, or decimal digit
`\\W` | matches any character that `\\w` doesn't match
`\\c` | matches any literal character `c`, which must be a punctuation
`.` | matches any single character except `\n`
`A?` | matches 0 or 1 occurrences of `A`
`A*` | matches 0 or many occurrences of `A`
`A+` | matches 1 or many occurrences of `A`
`^` | matches the beginning of a string (not that of each line)
`$` | matches the end of a string (not that of each line)
`xy` | matches `x` followed by `y`
To help you determine which capability is available on your system, GoogleTest
defines macros to govern which regular expression it is using. The macros are:
`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
tests to work in all cases, you can either `#if` on these macros or use the more
limited syntax only.
## Death Tests ## Death Tests
In many applications, there are assertions that can cause application failure if In many applications, there are assertions that can cause application failure if
@ -393,7 +461,7 @@ corruption, security holes, or worse. Hence it is vitally important to test that
such assertion statements work as expected. such assertion statements work as expected.
Since these precondition checks cause the processes to die, we call such tests Since these precondition checks cause the processes to die, we call such tests
_death tests_. More generally, any test that checks that a program terminates *death tests*. More generally, any test that checks that a program terminates
(except by throwing an exception) in an expected fashion is also a death test. (except by throwing an exception) in an expected fashion is also a death test.
Note that if a piece of code throws an exception, we don't consider it "death" Note that if a piece of code throws an exception, we don't consider it "death"
@ -439,6 +507,12 @@ verifies that:
exit with exit code 0, and exit with exit code 0, and
* calling `KillProcess()` kills the process with signal `SIGKILL`. * calling `KillProcess()` kills the process with signal `SIGKILL`.
{: .callout .warning}
Warning: If your death test contains mocks and is expecting a specific exit
code, then you must allow the mock objects to be leaked via `Mock::AllowLeak`.
This is because the mock leak detector will exit with its own error code if it
detects a leak.
The test function body may contain other assertions and statements as well, if The test function body may contain other assertions and statements as well, if
necessary. necessary.
@ -451,7 +525,7 @@ Note that a death test only cares about three things:
3. does the stderr output match `matcher`? 3. does the stderr output match `matcher`?
In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it 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. the process.
### Death Test Naming ### Death Test Naming
@ -480,51 +554,6 @@ TEST_F(FooDeathTest, DoesThat) {
} }
``` ```
### Regular Expression Syntax
When built with Bazel and using Abseil, googletest uses the
[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX
systems (Linux, Cygwin, Mac), googletest uses the
[POSIX extended regular expression](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_Regular_Expressions).
On Windows, googletest uses its own simple regular expression implementation. It
lacks many features. For example, we don't support union (`"x|y"`), grouping
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period
(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular
expressions.):
Expression | Meaning
---------- | --------------------------------------------------------------
`c` | matches any literal character `c`
`\\d` | matches any decimal digit
`\\D` | matches any character that's not a decimal digit
`\\f` | matches `\f`
`\\n` | matches `\n`
`\\r` | matches `\r`
`\\s` | matches any ASCII whitespace, including `\n`
`\\S` | matches any character that's not a whitespace
`\\t` | matches `\t`
`\\v` | matches `\v`
`\\w` | matches any letter, `_`, or decimal digit
`\\W` | matches any character that `\\w` doesn't match
`\\c` | matches any literal character `c`, which must be a punctuation
`.` | matches any single character except `\n`
`A?` | matches 0 or 1 occurrences of `A`
`A*` | matches 0 or many occurrences of `A`
`A+` | matches 1 or many occurrences of `A`
`^` | matches the beginning of a string (not that of each line)
`$` | matches the end of a string (not that of each line)
`xy` | matches `x` followed by `y`
To help you determine which capability is available on your system, googletest
defines macros to govern which regular expression it is using. The macros are:
`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
tests to work in all cases, you can either `#if` on these macros or use the more
limited syntax only.
### How It Works ### How It Works
See [Death Assertions](reference/assertions.md#death) in the Assertions See [Death Assertions](reference/assertions.md#death) in the Assertions
@ -539,7 +568,7 @@ arrange that kind of environment. For example, statically-initialized modules
may start threads before main is ever reached. Once threads have been created, may start threads before main is ever reached. Once threads have been created,
it may be difficult or impossible to clean them up. 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 1. A warning is emitted if multiple threads are running when a death test is
encountered. encountered.
@ -562,7 +591,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: particular style of death tests by setting the flag programmatically:
```c++ ```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, You can do this in `main()` to set the style for all death tests in the binary,
@ -592,7 +621,7 @@ TEST(MyDeathTest, TestTwo) {
The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If 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 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 may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid
them in `statement`. them in `statement`.
@ -704,7 +733,7 @@ Some tips on using `SCOPED_TRACE`:
### Propagating Fatal Failures ### Propagating Fatal Failures
A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
when they fail they only abort the _current function_, not the entire test. For when they fail they only abort the *current function*, not the entire test. For
example, the following test will segfault: example, the following test will segfault:
```c++ ```c++
@ -726,7 +755,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 either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
`HasFatalFailure()` function. They are described in the following two `HasFatalFailure()` function. They are described in the following two
subsections. subsections.
@ -760,7 +789,7 @@ in it, the test will continue after the subroutine returns. This may not be what
you want. you want.
Often people want fatal failures to propagate like exceptions. For that 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 Fatal assertion | Nonfatal assertion | Verifies
------------------------------------- | ------------------------------------- | -------- ------------------------------------- | ------------------------------------- | --------
@ -852,7 +881,7 @@ will output XML like this:
> needs to be prefixed with `::testing::Test::` if used outside of the > needs to be prefixed with `::testing::Test::` if used outside of the
> `TEST` body and the test fixture class. > `TEST` body and the test fixture class.
> * *`key`* must be a valid XML attribute name, and cannot conflict with the > * *`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`). > `type_param`, and `value_param`).
> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. > * 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 > If it's called outside of a test but between a test suite's
@ -863,25 +892,25 @@ will output XML like this:
## Sharing Resources Between Tests in the Same Test Suite ## 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 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 that are expensive to set up, making the one-copy-per-test model prohibitively
expensive. expensive.
If the tests don't change the resource, there's no harm in their sharing a 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: 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 1. In your test fixture class (say `FooTest` ), declare as `static` some member
variables to hold the shared resources. variables to hold the shared resources.
2. Outside your test fixture class (typically just below it), define those 2. Outside your test fixture class (typically just below it), define those
member variables, optionally giving them initial values. member variables, optionally giving them initial values.
3. In the same test fixture class, define a `static void SetUpTestSuite()` 3. In the same test fixture class, define a public member function `static void
function (remember not to spell it as **`SetupTestSuite`** with a small SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a
`u`!) to set up the shared resources and a `static void TearDownTestSuite()` small `u`!) to set up the shared resources and a `static void
function to tear them down. 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 *first test* in the `FooTest` test suite (i.e. before creating the first
`FooTest` object), and calls `TearDownTestSuite()` after running the *last test* `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 in it (i.e. after deleting the last `FooTest` object). In between, the tests can
@ -896,7 +925,8 @@ 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 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 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 resources defined as static members, so careful consideration is needed when
managing shared resources to avoid memory leaks. managing shared resources to avoid memory leaks if shared resources are not
properly cleaned up in `TearDownTestSuite()`.
Here's an example of per-test-suite set-up and tear-down: Here's an example of per-test-suite set-up and tear-down:
@ -907,10 +937,15 @@ class FooTest : public testing::Test {
// Called before the first test in this test suite. // Called before the first test in this test suite.
// Can be omitted if not needed. // Can be omitted if not needed.
static void SetUpTestSuite() { static void SetUpTestSuite() {
// Avoid reallocating static objects if called in subclasses of FooTest.
if (shared_resource_ == nullptr) {
shared_resource_ = new ...; 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 ...;
// }
} }
// Per-test-suite tear-down. // Per-test-suite tear-down.
@ -968,24 +1003,34 @@ 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: calling the `::testing::AddGlobalTestEnvironment()` function:
```c++ ```c++
Environment* AddGlobalTestEnvironment(Environment* env); Environment* AddGlobalTestEnvironment(Environment* env);
``` ```
Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of Now, when `RUN_ALL_TESTS()` is invoked, it first calls the `SetUp()` method. The
each environment object, then runs the tests if none of the environments tests are then executed, provided that none of the environments have reported
reported fatal failures and `GTEST_SKIP()` was not called. `RUN_ALL_TESTS()` fatal failures and `GTEST_SKIP()` has not been invoked. Finally, `TearDown()` is
always calls `TearDown()` with each environment object, regardless of whether or called.
not the tests were run.
Note that `SetUp()` and `TearDown()` are only invoked if there is at least one
test to be performed. Importantly, `TearDown()` is executed even if the test is
not run due to a fatal failure or `GTEST_SKIP()`.
Calling `SetUp()` and `TearDown()` for each iteration depends on the flag
`gtest_recreate_environments_when_repeating`. `SetUp()` and `TearDown()` are
called for each environment object when the object is recreated for each
iteration. However, if test environments are not recreated for each iteration,
`SetUp()` is called only on the first iteration, and `TearDown()` is called only
on the last iteration.
It's OK to register multiple environment objects. In this suite, their `SetUp()` 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 will be called in the order they are registered, and their `TearDown()` will be
called in the reverse order. 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. Therefore **do not delete them** by yourself.
You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called,
@ -1037,7 +1082,7 @@ they must be declared **public** rather than **protected** in order to use
```c++ ```c++
class FooTest : class FooTest :
public testing::TestWithParam<const char*> { public testing::TestWithParam<absl::string_view> {
// You can implement all the usual fixture class members here. // You can implement all the usual fixture class members here.
// To access the test parameter, call GetParam() from class // To access the test parameter, call GetParam() from class
// TestWithParam<T>. // TestWithParam<T>.
@ -1048,7 +1093,7 @@ class BaseTest : public testing::Test {
... ...
}; };
class BarTest : public BaseTest, class BarTest : public BaseTest,
public testing::WithParamInterface<const char*> { public testing::WithParamInterface<absl::string_view> {
... ...
}; };
``` ```
@ -1095,6 +1140,11 @@ instantiation of the test suite. The next argument is the name of the test
pattern, and the last is the pattern, and the last is the
[parameter generator](reference/testing.md#param-generators). [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 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 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 actual test suite name. Remember to pick unique prefixes for different
@ -1114,8 +1164,8 @@ with parameter values `"cat"` and `"dog"` using the
[`ValuesIn`](reference/testing.md#param-generators) parameter generator: [`ValuesIn`](reference/testing.md#param-generators) parameter generator:
```c++ ```c++
const char* pets[] = {"cat", "dog"}; constexpr absl::string_view kPets[] = {"cat", "dog"};
INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets)); INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets));
``` ```
The tests from the instantiation above will have these names: The tests from the instantiation above will have these names:
@ -1142,8 +1192,8 @@ GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);
You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples. You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples.
[sample7_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample7_unittest.cc "Parameterized Test example" [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/master/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters" [sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
### Creating Value-Parameterized Abstract Tests ### Creating Value-Parameterized Abstract Tests
@ -1294,7 +1344,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... }
You can see [sample6_unittest.cc] for a complete example. You can see [sample6_unittest.cc] for a complete example.
[sample6_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample6_unittest.cc "Typed Test example" [sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example"
## Type-Parameterized Tests ## Type-Parameterized Tests
@ -1490,12 +1540,12 @@ To test them, we use the following special techniques:
## "Catching" Failures ## "Catching" Failures
If you are building a testing utility on top of googletest, you'll want to test 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. 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. 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 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? we test that a piece of code generates an expected failure?
`"gtest/gtest-spi.h"` contains some constructs to do this. `"gtest/gtest-spi.h"` contains some constructs to do this.
@ -1638,9 +1688,9 @@ particular, you cannot find the test suite name in `SetUpTestSuite()`,
`TearDownTestSuite()` (where you know the test suite name implicitly), or `TearDownTestSuite()` (where you know the test suite name implicitly), or
functions called from them. 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 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 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 method, among others. You may use this API to augment or replace the standard
@ -1701,7 +1751,7 @@ Here's an example:
### Using Event Listeners ### Using Event Listeners
To use the event listener you have defined, add an instance of it to the 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" [`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s"
at the end of the name) in your `main()` function, before calling at the end of the name) in your `main()` function, before calling
`RUN_ALL_TESTS()`: `RUN_ALL_TESTS()`:
@ -1712,7 +1762,7 @@ int main(int argc, char** argv) {
// Gets hold of the event listener list. // Gets hold of the event listener list.
testing::TestEventListeners& listeners = testing::TestEventListeners& listeners =
testing::UnitTest::GetInstance()->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); listeners.Append(new MinimalistPrinter);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
@ -1733,7 +1783,7 @@ You can do so by adding one line:
Now, sit back and enjoy a completely different output from your tests. For more Now, sit back and enjoy a completely different output from your tests. For more
details, see [sample9_unittest.cc]. details, see [sample9_unittest.cc].
[sample9_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample9_unittest.cc "Event listener example" [sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example"
You may append more than one listener to the list. When an `On*Start()` or 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 `OnTestPartResult()` event is fired, the listeners will receive it in the order
@ -1760,17 +1810,17 @@ by the former.
See [sample10_unittest.cc] for an example of a failure-raising listener. See [sample10_unittest.cc] for an example of a failure-raising listener.
[sample10_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample10_unittest.cc "Failure-raising listener example" [sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
## Running Test Programs: Advanced Options ## 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 directly and affect their behavior via the following environment variables
and/or command line flags. For the flags to work, your programs must call and/or command line flags. For the flags to work, your programs must call
`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. `::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
To see a list of supported flags and their usage, please run your test program To see a list of supported flags and their usage, please run your test program
with the `--help` flag. You can also use `-h`, `-?`, or `/?` for short. with the `--help` flag.
If an option is specified both by an environment variable and by a flag, the If an option is specified both by an environment variable and by a flag, the
latter takes precedence. latter takes precedence.
@ -1797,10 +1847,10 @@ corresponding environment variable for this flag.
#### Running a Subset of the Tests #### 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 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 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. 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 The format of a filter is a '`:`'-separated list of wildcard patterns (called
@ -1831,7 +1881,7 @@ For example:
#### Stop test execution upon first failure #### 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 cases (e.g. iterative test development & execution) it may be desirable stop
test execution upon first failure (trading improved latency for completeness). test execution upon first failure (trading improved latency for completeness).
If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set, If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,
@ -1848,7 +1898,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 to the front of the name of each test, or alternatively add it to the front of
the test suite name. 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: will still be compiled:
```c++ ```c++
@ -1863,7 +1913,7 @@ TEST_F(DISABLED_BarTest, DoesXyz) { ... }
{: .callout .note} {: .callout .note}
NOTE: This feature should only be used for temporary pain-relief. You still have 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. a banner warning you if a test program contains any disabled tests.
{: .callout .tip} {: .callout .tip}
@ -1908,8 +1958,12 @@ Repeat the tests whose name matches the filter 1000 times.
If your test program contains If your test program contains
[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be [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. You can also repeated in each iteration as well, as the flakiness may be in it. To avoid
specify the repeat count by setting the `GTEST_REPEAT` environment variable. 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.
### Shuffling the Tests ### Shuffling the Tests
@ -1917,16 +1971,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. environment variable to `1`) to run the tests in a program in a random order.
This helps to reveal bad dependencies between tests. 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 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 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` 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 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 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. 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. random seed and re-shuffle the tests in each iteration.
### Distributing Test Functions to Multiple Machines ### Distributing Test Functions to Multiple Machines
@ -1985,7 +2039,7 @@ shards, but here's one possible scenario:
#### Colored Terminal Output #### 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: important information:
<pre>... <pre>...
@ -2010,25 +2064,25 @@ important information:
You can set the `GTEST_COLOR` environment variable or the `--gtest_color` 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, 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 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`. platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.
#### Suppressing test passes #### 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 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`. `--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.
#### Suppressing the Elapsed Time #### 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 that, run the test program with the `--gtest_print_time=0` command line flag, or
set the GTEST_PRINT_TIME environment variable to `0`. set the GTEST_PRINT_TIME environment variable to `0`.
#### Suppressing UTF-8 Text Output #### 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 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 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 text because, for example, you don't have an UTF-8 compatible output medium, run
@ -2037,7 +2091,7 @@ environment variable to `0`.
#### Generating an XML Report #### 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 textual output. The report contains the duration of each test, and thus can help
you identify slow tests. you identify slow tests.
@ -2048,15 +2102,15 @@ in which case the output can be found in the `test_detail.xml` file in the
current directory. current directory.
If you specify a directory (for example, `"xml:output/directory/"` on Linux or 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 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 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. `foo_test_1.xml`) to avoid overwriting it.
The report is based on the `junitreport` Ant task. Since that format was 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 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 ```xml
<testsuites name="AllTests" ...> <testsuites name="AllTests" ...>
@ -2071,8 +2125,8 @@ apply to googletest tests, as shown here:
``` ```
* The root `<testsuites>` element corresponds to the entire test program. * The root `<testsuites>` element corresponds to the entire test program.
* `<testsuite>` elements correspond to googletest test suites. * `<testsuite>` elements correspond to GoogleTest test suites.
* `<testcase>` elements correspond to googletest test functions. * `<testcase>` elements correspond to GoogleTest test functions.
For instance, the following program For instance, the following program
@ -2105,7 +2159,7 @@ could generate this report:
Things to note: Things to note:
* The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how * 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. `failures` attribute tells how many of them failed.
* The `time` attribute expresses the duration of the test, test suite, or * The `time` attribute expresses the duration of the test, test suite, or
@ -2117,12 +2171,12 @@ Things to note:
* The `file` and `line` attributes record the source file location, where the * The `file` and `line` attributes record the source file location, where the
test was defined. test was defined.
* Each `<failure>` element corresponds to a single failed googletest * Each `<failure>` element corresponds to a single failed GoogleTest
assertion. assertion.
#### Generating a JSON Report #### 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 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 `--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 create the file at the given location. You can also just use the string
@ -2133,7 +2187,7 @@ The report format conforms to the following JSON Schema:
```json ```json
{ {
"$schema": "http://json-schema.org/schema#", "$schema": "https://json-schema.org/schema#",
"type": "object", "type": "object",
"definitions": { "definitions": {
"TestCase": { "TestCase": {
@ -2334,7 +2388,7 @@ IMPORTANT: The exact format of the JSON document is subject to change.
#### Detecting Test Premature Exit #### Detecting Test Premature Exit
Google Test implements the _premature-exit-file_ protocol for test runners to Google Test implements the *premature-exit-file* protocol for test runners to
catch any kind of unexpected exits of test programs. Upon start, Google Test catch any kind of unexpected exits of test programs. Upon start, Google Test
creates the file which will be automatically deleted after all work has been creates the file which will be automatically deleted after all work has been
finished. Then, the test runner can check if this file exists. In case the file finished. Then, the test runner can check if this file exists. In case the file
@ -2347,7 +2401,7 @@ variable has been set.
When running test programs under a debugger, it's very convenient if the When running test programs under a debugger, it's very convenient if the
debugger can catch an assertion failure and automatically drop into interactive 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 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` other than `0`. Alternatively, you can use the `--gtest_break_on_failure`
@ -2355,9 +2409,9 @@ command line flag.
#### Disabling Catching Test-Thrown Exceptions #### 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 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 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 uncaught exception will cause a pop-up window, so catching the exceptions allows
you to run the tests automatically. you to run the tests automatically.
@ -2395,4 +2449,4 @@ void __tsan_on_report() {
``` ```
After compiling your project with one of the sanitizers enabled, if a particular 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.

View file

@ -3,7 +3,7 @@
## Why should test suite names and test names not contain underscore? ## Why should test suite names and test names not contain underscore?
{: .callout .note} {: .callout .note}
Note: GoogleTest reserves underscore (`_`) for special purpose keywords, such as Note: GoogleTest reserves underscore (`_`) for special-purpose keywords, such as
[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition [the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition
to the following rationale. to the following rationale.
@ -33,9 +33,9 @@ contains `_`?
`TestSuiteName_Bar__Test`, which is invalid. `TestSuiteName_Bar__Test`, which is invalid.
So clearly `TestSuiteName` and `TestName` cannot start or end with `_` So clearly `TestSuiteName` and `TestName` cannot start or end with `_`
(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't (Actually, `TestSuiteName` can start with `_`—as long as the `_` isn't followed
followed by an upper-case letter. But that's getting complicated. So for by an upper-case letter. But that's getting complicated. So for simplicity we
simplicity we just say that it cannot start with `_`.). just say that it cannot start with `_`.).
It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the
middle. However, consider this: middle. However, consider this:
@ -128,30 +128,9 @@ both approaches a try. Practice is a much better way to grasp the subtle
differences between the two tools. Once you have some concrete experience, you differences between the two tools. Once you have some concrete experience, you
can much more easily decide which one to use the next time. can much more easily decide which one to use the next time.
## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
{: .callout .note}
**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
now. Please use `EqualsProto`, etc instead.
`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and
are now less tolerant of invalid protocol buffer definitions. In particular, if
you have a `foo.proto` that doesn't fully qualify the type of a protocol message
it references (e.g. `message<Bar>` where it should be `message<blah.Bar>`), you
will now get run-time errors like:
```
... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto":
... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined.
```
If you see this, your `.proto` file is broken and needs to be fixed by making
the types fully qualified. The new definition of `ProtocolMessageEquals` and
`ProtocolMessageEquiv` just happen to reveal your bug.
## My death test modifies some state, but the change seems lost after the death test finishes. Why? ## My death test modifies some state, but the change seems lost after the death test finishes. Why?
Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the Death tests (`EXPECT_DEATH`, etc.) are executed in a sub-process s.t. the
expected crash won't kill the test program (i.e. the parent process). As a expected crash won't kill the test program (i.e. the parent process). As a
result, any in-memory side effects they incur are observable in their respective result, any in-memory side effects they incur are observable in their respective
sub-processes, but not in the parent process. You can think of them as running sub-processes, but not in the parent process. You can think of them as running
@ -192,16 +171,16 @@ class Foo {
}; };
``` ```
You also need to define it *outside* of the class body in `foo.cc`: you also need to define it *outside* of the class body in `foo.cc`:
```c++ ```c++
const int Foo::kBar; // No initializer here. const int Foo::kBar; // No initializer here.
``` ```
Otherwise your code is **invalid C++**, and may break in unexpected ways. In Otherwise your code is **invalid C++**, and may break in unexpected ways. In
particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc.)
generate an "undefined reference" linker error. The fact that "it used to work" will generate an "undefined reference" linker error. The fact that "it used to
doesn't mean it's valid. It just means that you were lucky. :-) work" doesn't mean it's valid. It just means that you were lucky. :-)
If the declaration of the static data member is `constexpr` then it is If the declaration of the static data member is `constexpr` then it is
implicitly an `inline` definition, and a separate definition in `foo.cc` is not implicitly an `inline` definition, and a separate definition in `foo.cc` is not
@ -267,7 +246,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. GoogleTest has no limit on how deep the hierarchy can be.
For a complete example using derived test fixtures, see For a complete example using derived test fixtures, see
[sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc). [sample5_unittest.cc](https://github.com/google/googletest/blob/main/googletest/samples/sample5_unittest.cc).
## My compiler complains "void value not ignored as it ought to be." What does this mean? ## My compiler complains "void value not ignored as it ought to be." What does this mean?
@ -311,7 +290,7 @@ a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
call `TearDown()`, and then delete the test fixture object. call `TearDown()`, and then delete the test fixture object.
When you need to write per-test set-up and tear-down logic, you have the choice When you need to write per-test set-up and tear-down logic, you have the choice
between using the test fixture constructor/destructor or `SetUp()/TearDown()`. between using the test fixture constructor/destructor or `SetUp()`/`TearDown()`.
The former is usually preferred, as it has the following benefits: The former is usually preferred, as it has the following benefits:
* By initializing a member variable in the constructor, we have the option to * By initializing a member variable in the constructor, we have the option to
@ -352,7 +331,7 @@ You may still want to use `SetUp()/TearDown()` in the following cases:
GoogleTest assertions in a destructor if your code could run on such a GoogleTest assertions in a destructor if your code could run on such a
platform. platform.
## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? ## The compiler complains "no matching function to call" when I use `ASSERT_PRED*`. How do I fix it?
See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the
Assertions Reference. Assertions Reference.
@ -410,7 +389,7 @@ C++ is case-sensitive. Did you spell it as `Setup()`?
Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and
wonder why it's never called. wonder why it's never called.
## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ## I have several test suites which share the same test fixture logic; do I have to define a new test fixture class for each of them? This seems pretty tedious.
You don't have to. Instead of You don't have to. Instead of
@ -545,7 +524,7 @@ The new NPTL thread library doesn't suffer from this problem, as it doesn't
create a manager thread. However, if you don't control which machine your test create a manager thread. However, if you don't control which machine your test
runs on, you shouldn't depend on this. runs on, you shouldn't depend on this.
## Why does GoogleTest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? ## Why does GoogleTest require the entire test suite, instead of individual tests, to be named `*DeathTest` when it uses `ASSERT_DEATH`?
GoogleTest does not interleave tests from different test suites. That is, it GoogleTest does not interleave tests from different test suites. That is, it
runs all tests in one test suite first, and then runs all tests in the next test runs all tests in one test suite first, and then runs all tests in the next test
@ -570,7 +549,7 @@ interleave tests from different test suites, we need to run all tests in the
`FooTest` case before running any test in the `BarTest` case. This contradicts `FooTest` case before running any test in the `BarTest` case. This contradicts
with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do? ## But I don't like calling my entire test suite `*DeathTest` when it contains both death tests and non-death tests. What do I do?
You don't have to, but if you like, you may split up the test suite into You don't have to, but if you like, you may split up the test suite into
`FooTest` and `FooDeathTest`, where the names make it clear that they are `FooTest` and `FooDeathTest`, where the names make it clear that they are
@ -607,7 +586,7 @@ defined such that we can print a value of `FooType`.
In addition, if `FooType` is declared in a name space, the `<<` operator also In addition, if `FooType` is declared in a name space, the `<<` operator also
needs to be defined in the *same* name space. See needs to be defined in the *same* name space. See
[Tip of the Week #49](http://abseil.io/tips/49) for details. [Tip of the Week #49](https://abseil.io/tips/49) for details.
## How do I suppress the memory leak messages on Windows? ## How do I suppress the memory leak messages on Windows?
@ -628,10 +607,10 @@ mistake in production. Such cleverness also leads to
advise against the practice, and GoogleTest doesn't provide a way to do it. advise against the practice, and GoogleTest doesn't provide a way to do it.
In general, the recommended way to cause the code to behave differently under In general, the recommended way to cause the code to behave differently under
test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject
different functionality from the test and from the production code. Since your different functionality from the test and from the production code. Since your
production code doesn't link in the for-test logic at all (the production code doesn't link in the for-test logic at all (the
[`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure [`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
that), there is no danger in accidentally running it. that), there is no danger in accidentally running it.
However, if you *really*, *really*, *really* have no choice, and if you follow However, if you *really*, *really*, *really* have no choice, and if you follow
@ -654,7 +633,7 @@ the `--gtest_also_run_disabled_tests` flag.
Yes. Yes.
The rule is **all test methods in the same test suite must use the same fixture The rule is **all test methods in the same test suite must use the same fixture
class.** This means that the following is **allowed** because both tests use the class**. This means that the following is **allowed** because both tests use the
same fixture class (`::testing::Test`). same fixture class (`::testing::Test`).
```c++ ```c++

View file

@ -20,7 +20,7 @@ class Foo {
(note that `~Foo()` **must** be virtual) we can define its mock as (note that `~Foo()` **must** be virtual) we can define its mock as
```cpp ```cpp
#include "gmock/gmock.h" #include <gmock/gmock.h>
class MockFoo : public Foo { class MockFoo : public Foo {
public: 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 // Sets the default action for return type std::unique_ptr<Buzz> to
// creating a new Buzz every time. // creating a new Buzz every time.
DefaultValue<std::unique_ptr<Buzz>>::SetFactory( DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
[] { return MakeUnique<Buzz>(AccessLevel::kInternal); }); [] { return std::make_unique<Buzz>(AccessLevel::kInternal); });
// When this fires, the default action of MakeBuzz() will run, which // When this fires, the default action of MakeBuzz() will run, which
// will return a new Buzz object. // will return a new Buzz object.

View file

@ -177,7 +177,7 @@ class StackInterface {
template <typename Elem> template <typename Elem>
class MockStack : public StackInterface<Elem> { class MockStack : public StackInterface<Elem> {
... ...
MOCK_METHOD(int, GetSize, (), (override)); MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(void, Push, (const Elem& x), (override)); MOCK_METHOD(void, Push, (const Elem& x), (override));
}; };
``` ```
@ -285,6 +285,10 @@ If you are concerned about the performance overhead incurred by virtual
functions, and profiling confirms your concern, you can combine this with the functions, and profiling confirms your concern, you can combine this with the
recipe for [mocking non-virtual methods](#MockingNonVirtualMethods). 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 ### Old-Style `MOCK_METHODn` Macros
Before the generic `MOCK_METHOD` macro Before the generic `MOCK_METHOD` macro
@ -693,9 +697,9 @@ TEST(AbcTest, Xyz) {
EXPECT_CALL(foo, DoThat(_, _)); EXPECT_CALL(foo, DoThat(_, _));
int n = 0; 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. foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked.
EXPECT_EQ(2, n); EXPECT_EQ(n, 2);
} }
``` ```
@ -904,7 +908,7 @@ using ::testing::Contains;
using ::testing::Property; using ::testing::Property;
inline constexpr auto HasFoo = [](const auto& f) { inline constexpr auto HasFoo = [](const auto& f) {
return Property(&MyClass::foo, Contains(f)); return Property("foo", &MyClass::foo, Contains(f));
}; };
... ...
EXPECT_THAT(x, HasFoo("blah")); EXPECT_THAT(x, HasFoo("blah"));
@ -932,8 +936,8 @@ casts a matcher `m` to type `Matcher<T>`. To ensure safety, gMock checks that
floating-point numbers), the conversion from `T` to `U` is not lossy (in floating-point numbers), the conversion from `T` to `U` is not lossy (in
other words, any value representable by `T` can also be represented by `U`); other words, any value representable by `T` can also be represented by `U`);
and and
3. When `U` is a reference, `T` must also be a reference (as the underlying 3. When `U` is a non-const reference, `T` must also be a reference (as the
matcher may be interested in the address of the `U` value). underlying matcher may be interested in the address of the `U` value).
The code won't compile if any of these conditions isn't met. The code won't compile if any of these conditions isn't met.
@ -1125,11 +1129,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: predicate that's satisfied by any number that is >= 0, <= 100, and != 50:
```cpp ```cpp
using testing::AllOf; using ::testing::AllOf;
using testing::Ge; using ::testing::Ge;
using testing::Le; using ::testing::Le;
using testing::Matches; using ::testing::Matches;
using testing::Ne; using ::testing::Ne;
... ...
Matches(AllOf(Ge(0), Le(100), Ne(50))) Matches(AllOf(Ge(0), Le(100), Ne(50)))
``` ```
@ -1158,7 +1162,7 @@ int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
``` ```
Note that the predicate function / functor doesn't have to return `bool`. It 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 in statement works as long as the return value can be used as the condition in the statement
`if (condition) ...`. `if (condition) ...`.
### Matching Arguments that Are Not Copyable ### Matching Arguments that Are Not Copyable
@ -1345,7 +1349,7 @@ class BarPlusBazEqMatcher {
... ...
Foo foo; Foo foo;
EXPECT_CALL(foo, BarPlusBazEq(5))...; EXPECT_THAT(foo, BarPlusBazEq(5))...;
``` ```
### Matching Containers ### Matching Containers
@ -1424,11 +1428,12 @@ Use `Pair` when comparing maps or other associative containers.
{% raw %} {% raw %}
```cpp ```cpp
using testing::ElementsAre; using ::testing::UnorderedElementsAre;
using testing::Pair; using ::testing::Pair;
... ...
std::map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}}; absl::flat_hash_map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
EXPECT_THAT(m, ElementsAre(Pair("a", 1), Pair("b", 2), Pair("c", 3))); EXPECT_THAT(m, UnorderedElementsAre(
Pair("a", 1), Pair("b", 2), Pair("c", 3)));
``` ```
{% endraw %} {% endraw %}
@ -1445,8 +1450,8 @@ using testing::Pair;
* If the container is passed by pointer instead of by reference, just write * If the container is passed by pointer instead of by reference, just write
`Pointee(ElementsAre*(...))`. `Pointee(ElementsAre*(...))`.
* The order of elements *matters* for `ElementsAre*()`. If you are using it * The order of elements *matters* for `ElementsAre*()`. If you are using it
with containers whose element order are undefined (e.g. `hash_map`) you with containers whose element order are undefined (such as a
should use `WhenSorted` around `ElementsAre`. `std::unordered_map`) you should use `UnorderedElementsAre`.
### Sharing Matchers ### Sharing Matchers
@ -1856,7 +1861,7 @@ error. So, what shall you do?
Though you may be tempted, DO NOT use `std::ref()`: Though you may be tempted, DO NOT use `std::ref()`:
```cpp ```cpp
using testing::Return; using ::testing::Return;
class MockFoo : public Foo { class MockFoo : public Foo {
public: public:
@ -1868,7 +1873,7 @@ class MockFoo : public Foo {
EXPECT_CALL(foo, GetValue()) EXPECT_CALL(foo, GetValue())
.WillRepeatedly(Return(std::ref(x))); // Wrong! .WillRepeatedly(Return(std::ref(x))); // Wrong!
x = 42; x = 42;
EXPECT_EQ(42, foo.GetValue()); EXPECT_EQ(foo.GetValue(), 42);
``` ```
Unfortunately, it doesn't work here. The above code will fail with error: Unfortunately, it doesn't work here. The above code will fail with error:
@ -1890,20 +1895,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*: returns the value pointed to by `pointer` at the time the action is *executed*:
```cpp ```cpp
using testing::ReturnPointee; using ::testing::ReturnPointee;
... ...
int x = 0; int x = 0;
MockFoo foo; MockFoo foo;
EXPECT_CALL(foo, GetValue()) EXPECT_CALL(foo, GetValue())
.WillRepeatedly(ReturnPointee(&x)); // Note the & here. .WillRepeatedly(ReturnPointee(&x)); // Note the & here.
x = 42; x = 42;
EXPECT_EQ(42, foo.GetValue()); // This will succeed now. EXPECT_EQ(foo.GetValue(), 42); // This will succeed now.
``` ```
### Combining Actions ### Combining Actions
Want to do more than one thing when a function is called? That's fine. `DoAll()` Want to do more than one thing when a function is called? That's fine. `DoAll()`
allow you to do sequence of actions every time. Only the return value of the allows you to do a sequence of actions every time. Only the return value of the
last action in the sequence will be used. last action in the sequence will be used.
```cpp ```cpp
@ -1922,6 +1927,12 @@ class MockFoo : public Foo {
action_n)); action_n));
``` ```
The return value of the last action **must** match the return type of the mocked
method. In the example above, `action_n` could be `Return(true)`, or a lambda
that returns a `bool`, but not `SaveArg`, which returns `void`. Otherwise the
signature of `DoAll` would not match the signature expected by `WillOnce`, which
is the signature of the mocked method, and it wouldn't compile.
### Verifying Complex Arguments {#SaveArgVerify} ### Verifying Complex Arguments {#SaveArgVerify}
If you want to verify that a method is called with a particular argument but the If you want to verify that a method is called with a particular argument but the
@ -2259,7 +2270,7 @@ TEST_F(FooTest, Test) {
EXPECT_CALL(foo, DoThis(2)) EXPECT_CALL(foo, DoThis(2))
.WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5))); .WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5)));
EXPECT_EQ('+', foo.DoThis(2)); // Invokes SignOfSum(5, 2). EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2).
} }
``` ```
@ -2635,8 +2646,8 @@ action will exhibit different behaviors. Example:
.WillRepeatedly(IncrementCounter(0)); .WillRepeatedly(IncrementCounter(0));
foo.DoThis(); // Returns 1. foo.DoThis(); // Returns 1.
foo.DoThis(); // Returns 2. foo.DoThis(); // Returns 2.
foo.DoThat(); // Returns 1 - Blah() uses a different foo.DoThat(); // Returns 1 - DoThat() uses a different
// counter than Bar()'s. // counter than DoThis()'s.
``` ```
versus versus
@ -2766,36 +2777,33 @@ returns a null `unique_ptr`, thats what youll get if you dont specify a
action: action:
```cpp ```cpp
using ::testing::IsNull;
...
// Use the default action. // Use the default action.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));
// Triggers the previous EXPECT_CALL. // Triggers the previous EXPECT_CALL.
EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello")); EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull());
``` ```
If you are not happy with the default action, you can tweak it as usual; see If you are not happy with the default action, you can tweak it as usual; see
[Setting Default Actions](#OnCall). [Setting Default Actions](#OnCall).
If you just need to return a pre-defined move-only value, you can use the If you just need to return a move-only value, you can use it in combination with
`Return(ByMove(...))` action: `WillOnce`. For example:
```cpp ```cpp
// When this fires, the unique_ptr<> specified by ByMove(...) will EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"))
// be returned. .WillOnce(Return(std::make_unique<Buzz>(AccessLevel::kInternal)));
EXPECT_CALL(mock_buzzer_, MakeBuzz("world")) EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello"));
.WillOnce(Return(ByMove(MakeUnique<Buzz>(AccessLevel::kInternal))));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world"));
``` ```
Note that `ByMove()` is essential here - if you drop it, the code wont compile. 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
Quiz time! What do you think will happen if a `Return(ByMove(...))` action is think of it, after the first time the action runs, the source value will be
performed more than once (e.g. you write `... consumed (since its a move-only value), so the next time around, theres no
.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time value to move from -- youll get a run-time error that `Return(std::move(...))`
the action runs, the source value will be consumed (since its a move-only can only be run once.
value), so the next time around, theres no value to move from -- youll 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, 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 remember that you can always use a lambda or a callable object, which can do
@ -2804,7 +2812,7 @@ pretty much anything you want:
```cpp ```cpp
EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
.WillRepeatedly([](StringPiece text) { .WillRepeatedly([](StringPiece text) {
return MakeUnique<Buzz>(AccessLevel::kInternal); return std::make_unique<Buzz>(AccessLevel::kInternal);
}); });
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
@ -2812,7 +2820,7 @@ pretty much anything you want:
``` ```
Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created
and returned. You cannot do this with `Return(ByMove(...))`. and returned. You cannot do this with `Return(std::make_unique<...>(...))`.
That covers returning move-only values; but how do we work with methods 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 accepting move-only arguments? The answer is that they work normally, although
@ -2823,7 +2831,7 @@ can always use `Return`, or a [lambda or functor](#FunctionsAsActions):
using ::testing::Unused; using ::testing::Unused;
EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true)); EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true));
EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal)), EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal)),
0); 0);
EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce( EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce(
@ -2867,7 +2875,7 @@ method:
// When one calls ShareBuzz() on the MockBuzzer like this, the call is // When one calls ShareBuzz() on the MockBuzzer like this, the call is
// forwarded to DoShareBuzz(), which is mocked. Therefore this statement // forwarded to DoShareBuzz(), which is mocked. Therefore this statement
// will trigger the above EXPECT_CALL. // will trigger the above EXPECT_CALL.
mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0); mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal), 0);
``` ```
### Making the Compilation Faster ### Making the Compilation Faster
@ -3192,11 +3200,11 @@ You can unlock this power by running your test with the `--gmock_verbose=info`
flag. For example, given the test program: flag. For example, given the test program:
```cpp ```cpp
#include "gmock/gmock.h" #include <gmock/gmock.h>
using testing::_; using ::testing::_;
using testing::HasSubstr; using ::testing::HasSubstr;
using testing::Return; using ::testing::Return;
class MockFoo { class MockFoo {
public: public:
@ -3304,7 +3312,7 @@ For convenience, we allow the description string to be empty (`""`), in which
case gMock will use the sequence of words in the matcher name as the case gMock will use the sequence of words in the matcher name as the
description. description.
For example: #### Basic Example
```cpp ```cpp
MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
@ -3342,6 +3350,8 @@ If the above assertions fail, they will print something like:
where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are
automatically calculated from the matcher name `IsDivisibleBy7`. automatically calculated from the matcher name `IsDivisibleBy7`.
#### Adding Custom Failure Messages
As you may have noticed, the auto-generated descriptions (especially those for As you may have noticed, the auto-generated descriptions (especially those for
the negation) may not be so great. You can always override them with a `string` the negation) may not be so great. You can always override them with a `string`
expression of your own: expression of your own:
@ -3375,21 +3385,48 @@ With this definition, the above assertion will give a better message:
Actual: 27 (the remainder is 6) Actual: 27 (the remainder is 6)
``` ```
#### Using EXPECT_ Statements in Matchers
You can also use `EXPECT_...` statements inside custom matcher definitions. In
many cases, this allows you to write your matcher more concisely while still
providing an informative error message. For example:
```cpp
MATCHER(IsDivisibleBy7, "") {
const auto remainder = arg % 7;
EXPECT_EQ(remainder, 0);
return true;
}
```
If you write a test that includes the line `EXPECT_THAT(27, IsDivisibleBy7());`,
you will get an error something like the following:
```shell
Expected equality of these values:
remainder
Which is: 6
0
```
#### `MatchAndExplain`
You should let `MatchAndExplain()` print *any additional information* that can You should let `MatchAndExplain()` print *any additional information* that can
help a user understand the match result. Note that it should explain why the help a user understand the match result. Note that it should explain why the
match succeeds in case of a success (unless it's obvious) - this is useful when match succeeds in case of a success (unless it's obvious) - this is useful when
the matcher is used inside `Not()`. There is no need to print the argument value the matcher is used inside `Not()`. There is no need to print the argument value
itself, as gMock already prints it for you. itself, as gMock already prints it for you.
{: .callout .note} #### Argument Types
NOTE: The type of the value being matched (`arg_type`) is determined by the
context in which you use the matcher and is supplied to you by the compiler, so The type of the value being matched (`arg_type`) is determined by the context in
you don't need to worry about declaring it (nor can you). This allows the which you use the matcher and is supplied to you by the compiler, so you don't
matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match need to worry about declaring it (nor can you). This allows the matcher to be
any type where the value of `(arg % 7) == 0` can be implicitly converted to a polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where
`bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the
`int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`,
be `unsigned long`; and so on. `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be
`unsigned long`; and so on.
### Writing New Parameterized Matchers Quickly ### Writing New Parameterized Matchers Quickly
@ -3817,15 +3854,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 All you need is a call operator with a signature compatible with the mocked
function. So you can use a lambda: function. So you can use a lambda:
``` ```cpp
MockFunction<int(int)> mock; MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; });
EXPECT_EQ(14, mock.AsStdFunction()(2)); EXPECT_EQ(mock.AsStdFunction()(2), 14);
``` ```
Or a struct with a call operator (even a templated one): Or a struct with a call operator (even a templated one):
``` ```cpp
struct MultiplyBy { struct MultiplyBy {
template <typename T> template <typename T>
T operator()(T arg) { return arg * multiplier; } T operator()(T arg) { return arg * multiplier; }
@ -3840,16 +3877,16 @@ struct MultiplyBy {
It's also fine for the callable to take no arguments, ignoring the arguments It's also fine for the callable to take no arguments, ignoring the arguments
supplied to the mock function: supplied to the mock function:
``` ```cpp
MockFunction<int(int)> mock; MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([] { return 17; }); EXPECT_CALL(mock, Call).WillOnce([] { return 17; });
EXPECT_EQ(17, mock.AsStdFunction()(0)); EXPECT_EQ(mock.AsStdFunction()(0), 17);
``` ```
When used with `WillOnce`, the callable can assume it will be called at most When used with `WillOnce`, the callable can assume it will be called at most
once and is allowed to be a move-only type: once and is allowed to be a move-only type:
``` ```cpp
// An action that contains move-only types and has an &&-qualified operator, // 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 // 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 // used with WillOnce, but the compiler will reject it if handed to
@ -4293,7 +4330,7 @@ particular type than to dump the bytes.
### Mock std::function {#MockFunction} ### Mock std::function {#MockFunction}
`std::function` is a general function type introduced in C++11. It is a `std::function` is a general function type introduced in C++11. It is a
preferred way of passing callbacks to new interfaces. Functions are copiable, preferred way of passing callbacks to new interfaces. Functions are copyable,
and are not usually passed around by pointer, which makes them tricky to mock. and are not usually passed around by pointer, which makes them tricky to mock.
But fear not - `MockFunction` can help you with that. But fear not - `MockFunction` can help you with that.

View file

@ -90,14 +90,14 @@ gMock is bundled with googletest.
## A Case for Mock Turtles ## A Case for Mock Turtles
Let's look at an example. Suppose you are developing a graphics program that Let's look at an example. Suppose you are developing a graphics program that
relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like relies on a [LOGO](https://en.wikipedia.org/wiki/Logo_programming_language)-like
API for drawing. How would you test that it does the right thing? Well, you can API for drawing. How would you test that it does the right thing? Well, you can
run it and compare the screen with a golden screen snapshot, but let's admit it: run it and compare the screen with a golden screen snapshot, but let's admit it:
tests like this are expensive to run and fragile (What if you just upgraded to a tests like this are expensive to run and fragile (What if you just upgraded to a
shiny new graphics card that has better anti-aliasing? Suddenly you have to shiny new graphics card that has better anti-aliasing? Suddenly you have to
update all your golden images.). It would be too painful if all your tests are update all your golden images.). It would be too painful if all your tests are
like this. Fortunately, you learned about like this. Fortunately, you learned about
[Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) and know the right thing
to do: instead of having your application talk to the system API directly, wrap to do: instead of having your application talk to the system API directly, wrap
the API in an interface (say, `Turtle`) and code to that interface: the API in an interface (say, `Turtle`) and code to that interface:
@ -164,7 +164,7 @@ follow:
After the process, you should have something like: After the process, you should have something like:
```cpp ```cpp
#include "gmock/gmock.h" // Brings in gMock. #include <gmock/gmock.h> // Brings in gMock.
class MockTurtle : public Turtle { class MockTurtle : public Turtle {
public: public:
@ -224,8 +224,8 @@ Here's an example:
```cpp ```cpp
#include "path/to/mock-turtle.h" #include "path/to/mock-turtle.h"
#include "gmock/gmock.h" #include <gmock/gmock.h>
#include "gtest/gtest.h" #include <gtest/gtest.h>
using ::testing::AtLeast; // #1 using ::testing::AtLeast; // #1
@ -261,6 +261,8 @@ happen. Therefore it's a good idea to turn on the heap checker in your tests
when you allocate mocks on the heap. You get that automatically if you use the when you allocate mocks on the heap. You get that automatically if you use the
`gtest_main` library already. `gtest_main` library already.
###### Expectation Ordering
**Important note:** gMock requires expectations to be set **before** the mock **Important note:** gMock requires expectations to be set **before** the mock
functions are called, otherwise the behavior is **undefined**. Do not alternate functions are called, otherwise the behavior is **undefined**. Do not alternate
between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set

View file

@ -19,19 +19,15 @@ examples here we assume you want to compile the sample
Using `pkg-config` in CMake is fairly easy: Using `pkg-config` in CMake is fairly easy:
```cmake ```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) find_package(PkgConfig)
pkg_search_module(GTEST REQUIRED gtest_main) pkg_search_module(GTEST REQUIRED gtest_main)
add_executable(testapp samples/sample3_unittest.cc) add_executable(testapp)
target_link_libraries(testapp ${GTEST_LDFLAGS}) target_sources(testapp PRIVATE samples/sample3_unittest.cc)
target_compile_options(testapp PUBLIC ${GTEST_CFLAGS}) target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS})
target_compile_options(testapp PRIVATE ${GTEST_CFLAGS})
include(CTest) enable_testing()
add_test(first_and_only_test testapp) add_test(first_and_only_test testapp)
``` ```

View file

@ -0,0 +1,8 @@
# 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.

View file

@ -1,84 +1,84 @@
# 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 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. 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 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, 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 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 and subroutines. This common pattern is easy to recognize and makes tests
easy to maintain. Such consistency is especially helpful when people switch easy to maintain. Such consistency is especially helpful when people switch
projects and start to work on a new code base. 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 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 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 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 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. 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 Thus, you can detect and fix multiple bugs in a single run-edit-compile
cycle. cycle.
5. The testing framework should liberate test writers from housekeeping chores 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 track of all tests defined, and doesn't require the user to enumerate them
in order to run 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 across tests and pay for the set-up/tear-down only once, without making
tests depend on each other. 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 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! minutes to learn the basics and get started. So let's go!
## Beware of the nomenclature ## Beware of the Nomenclature
{: .callout .note} {: .callout .note}
_Note:_ There might be some confusion arising from different definitions of the *Note:* There might be some confusion arising from different definitions of the
terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these. 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 related tests, whereas current publications, including International Software
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and Testing Qualifications Board ([ISTQB](https://www.istqb.org/)) materials and
various textbooks on software quality, use the term 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 The related term *Test*, as it is used in GoogleTest, corresponds to the term
_[Test Case][istqb test case]_ of ISTQB and others. *[Test Case][istqb test case]* of ISTQB and others.
The term _Test_ is commonly of broad enough sense, including ISTQB's definition 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 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. 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 The preferred API is *TestSuite*. The older TestCase API is being slowly
deprecated and refactored away. deprecated and refactored away.
So please be aware of the different definitions of the terms: So please be aware of the different definitions of the terms:
Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term Meaning | GoogleTest Term | [ISTQB](https://www.istqb.org/) Term
:----------------------------------------------------------------------------------- | :---------------------- | :---------------------------------- :----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case] Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
[istqb test case]: http://glossary.istqb.org/en/search/test%20case [istqb test case]: https://glossary.istqb.org/en_US/term/test-case
[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite [istqb test suite]: https://glossary.istqb.org/en_US/term/test-suite
## Basic Concepts ## 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*, 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 *nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
current function; otherwise the program continues normally. current function; otherwise the program continues normally.
@ -98,11 +98,11 @@ assertion level and building up to tests and test suites.
## Assertions ## 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, 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 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 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 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 1. Use the `TEST()` macro to define and name a test function. These are
ordinary C++ functions that don't return a value. ordinary C++ functions that don't return a value.
2. In this function, along with any valid C++ statements you want to include, 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 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 test fails (either fatally or non-fatally), or if the test crashes, the
entire test fails. Otherwise, it succeeds. 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 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, `TEST()` should be the same. In the above example, we have two tests,
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test `HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
@ -210,7 +210,7 @@ objects for several different tests.
To create a fixture: To create a fixture:
1. Derive a class from `::testing::Test` . Start its body with `protected:`, as 1. Derive a class from `testing::Test` . Start its body with `protected:`, as
we'll want to access fixture members from sub-classes. we'll want to access fixture members from sub-classes.
2. Inside the class, declare any objects you plan to use. 2. Inside the class, declare any objects you plan to use.
3. If necessary, write a default constructor or `SetUp()` function to prepare 3. If necessary, write a default constructor or `SetUp()` function to prepare
@ -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: access objects and subroutines in the test fixture:
```c++ ```c++
TEST_F(TestFixtureName, TestName) { TEST_F(TestFixtureClassName, TestName) {
... test body ... ... test body ...
} }
``` ```
Like `TEST()`, the first argument is the test suite name, but for `TEST_F()` Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test
this must be the name of the test fixture class. You've probably guessed: `_F` fixture class. (`_F` stands for "Fixture"). No test suite name is specified for
is for fixture. this macro.
Unfortunately, the C++ macro system does not allow us to create a single macro 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 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 `TEST_F()`, or you'll get the compiler error "`virtual outside class
declaration`". 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 fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean
up by calling `TearDown()`, and then delete the test fixture. Note that 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 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 always deletes a test fixture before it creates the next one.
googletest does **not** reuse the same test fixture for multiple tests. Any GoogleTest does **not** reuse the same test fixture for multiple tests. Any
changes one test makes to the fixture do not affect other tests. 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 As an example, let's write tests for a FIFO queue class named `Queue`, which has
@ -271,15 +271,16 @@ First, define a fixture class. By convention, you should give it the name
`FooTest` where `Foo` is the class being tested. `FooTest` where `Foo` is the class being tested.
```c++ ```c++
class QueueTest : public ::testing::Test { class QueueTest : public testing::Test {
protected: protected:
void SetUp() override { QueueTest() {
// q0_ remains empty
q1_.Enqueue(1); q1_.Enqueue(1);
q2_.Enqueue(2); q2_.Enqueue(2);
q2_.Enqueue(3); q2_.Enqueue(3);
} }
// void TearDown() override {} // ~QueueTest() override = default;
Queue<int> q0_; Queue<int> q0_;
Queue<int> q1_; Queue<int> q1_;
@ -287,8 +288,9 @@ class QueueTest : public ::testing::Test {
}; };
``` ```
In this case, `TearDown()` is not needed since we don't have to clean up after In this case, we don't need to define a destructor or a `TearDown()` method,
each test, other than what's already done by the destructor. because the implicit destructor generated by the compiler will perform all of
the necessary cleanup.
Now we'll write tests using `TEST_F()` and this fixture. Now we'll write tests using `TEST_F()` and this fixture.
@ -324,19 +326,17 @@ would lead to a segfault when `n` is `NULL`.
When these tests run, the following happens: 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`. 2. The first test (`IsEmptyInitially`) runs on `t1`.
3. The first test (`IsEmptyInitially`) runs on `t1`. 3. `t1` is destructed.
4. `t1.TearDown()` cleans up after the test finishes. 4. The above steps are repeated on another `QueueTest` object, this time
5. `t1` is destructed.
6. The above steps are repeated on another `QueueTest` object, this time
running the `DequeueWorks` test. running the `DequeueWorks` test.
**Availability**: Linux, Windows, Mac. **Availability**: Linux, Windows, Mac.
## Invoking the Tests ## 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 unlike with many other C++ testing frameworks, you don't have to re-list all
your defined tests in order to run them. your defined tests in order to run them.
@ -347,7 +347,7 @@ test suites, or even different source files.
When invoked, the `RUN_ALL_TESTS()` macro: 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. * Creates a test fixture object for the first test.
@ -359,7 +359,7 @@ When invoked, the `RUN_ALL_TESTS()` macro:
* Deletes the fixture. * 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. * Repeats the above steps for the next test, until all tests have run.
@ -373,14 +373,14 @@ If a fatal failure happens the subsequent steps will be skipped.
> return the value of `RUN_ALL_TESTS()`. > return the value of `RUN_ALL_TESTS()`.
> >
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than > 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. > [death tests](advanced.md#death-tests)) and thus is not supported.
**Availability**: Linux, Windows, Mac. **Availability**: Linux, Windows, Mac.
## Writing the main() Function ## 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 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 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 should only apply when you need to do something custom before the tests run that
@ -394,14 +394,14 @@ You can start from this boilerplate:
```c++ ```c++
#include "this/package/foo.h" #include "this/package/foo.h"
#include "gtest/gtest.h" #include <gtest/gtest.h>
namespace my { namespace my {
namespace project { namespace project {
namespace { namespace {
// The fixture for testing class Foo. // The fixture for testing class Foo.
class FooTest : public ::testing::Test { class FooTest : public testing::Test {
protected: protected:
// You can remove any or all of the following functions if their bodies would // You can remove any or all of the following functions if their bodies would
// be empty. // be empty.
@ -449,14 +449,14 @@ TEST_F(FooTest, DoesXyz) {
} // namespace my } // namespace my
int main(int argc, char **argv) { int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
``` ```
The `::testing::InitGoogleTest()` function parses the command line for The `testing::InitGoogleTest()` function parses the command line for GoogleTest
googletest flags, and removes all recognized flags. This allows the user to flags, and removes all recognized flags. This allows the user to control a test
control a test program's behavior via various flags, which we'll cover in the program's behavior via various flags, which we'll cover in the
[AdvancedGuide](advanced.md). You **must** call this function before calling [AdvancedGuide](advanced.md). You **must** call this function before calling
`RUN_ALL_TESTS()`, or the flags won't be properly initialized. `RUN_ALL_TESTS()`, or the flags won't be properly initialized.
@ -475,7 +475,7 @@ NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
* Google Test is designed to be thread-safe. The implementation is thread-safe * Google Test is designed to be thread-safe. The implementation is thread-safe
on systems where the `pthreads` library is available. It is currently 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 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 the assertions are done in the main thread. If you want to help, you can
volunteer to implement the necessary synchronization primitives in volunteer to implement the necessary synchronization primitives in

View file

@ -9,19 +9,18 @@ we recommend this tutorial as a starting point.
To complete this tutorial, you'll need: To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows). * A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++11. * A compatible C++ compiler that supports at least C++14.
* [Bazel](https://bazel.build/), the preferred build system used by the * [Bazel](https://bazel.build/) 7.0 or higher, the preferred build system used
GoogleTest team. by the GoogleTest team.
See [Supported Platforms](platforms.md) for more information about platforms See [Supported Platforms](platforms.md) for more information about platforms
compatible with GoogleTest. compatible with GoogleTest.
If you don't already have Bazel installed, see the If you don't already have Bazel installed, see the
[Bazel installation guide](https://docs.bazel.build/versions/main/install.html). [Bazel installation guide](https://bazel.build/install).
{: .callout .note} {: .callout .note} Note: The terminal commands in this tutorial show a Unix
Note: The terminal commands in this tutorial show a Unix shell prompt, but the shell prompt, but the commands work on the Windows command line as well.
commands work on the Windows command line as well.
## Set up a Bazel workspace ## Set up a Bazel workspace
@ -29,7 +28,7 @@ A
[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace) [Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace)
is a directory on your filesystem that you use to manage source files for the is a directory on your filesystem that you use to manage source files for the
software you want to build. Each workspace directory has a text file named software you want to build. Each workspace directory has a text file named
`WORKSPACE` which may be empty, or may contain references to external `MODULE.bazel` which may be empty, or may contain references to external
dependencies required to build the outputs. dependencies required to build the outputs.
First, create a directory for your workspace: First, create a directory for your workspace:
@ -38,30 +37,20 @@ First, create a directory for your workspace:
$ mkdir my_workspace && cd my_workspace $ mkdir my_workspace && cd my_workspace
``` ```
Next, youll create the `WORKSPACE` file to specify dependencies. A common and Next, youll create the `MODULE.bazel` file to specify dependencies. As of Bazel
recommended way to depend on GoogleTest is to use a 7.0, the recommended way to consume GoogleTest is through the
[Bazel external dependency](https://docs.bazel.build/versions/main/external.html) [Bazel Central Registry](https://registry.bazel.build/modules/googletest). To do
via the this, create a `MODULE.bazel` file in the root directory of your Bazel workspace
[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive). with the following content:
To do this, in the root directory of your workspace (`my_workspace/`), create a
file named `WORKSPACE` with the following contents:
``` ```
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # MODULE.bazel
http_archive( # Choose the most recent version available at
name = "com_google_googletest", # https://registry.bazel.build/modules/googletest
urls = ["https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip"], bazel_dep(name = "googletest", version = "1.15.2")
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,
`609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is the Git commit hash of the
GoogleTest version to use; we recommend updating the hash often to point to the
latest version.
Now you're ready to build C++ code that uses GoogleTest. Now you're ready to build C++ code that uses GoogleTest.
## Create and run a binary ## Create and run a binary
@ -96,20 +85,30 @@ cc_test(
name = "hello_test", name = "hello_test",
size = "small", size = "small",
srcs = ["hello_test.cc"], srcs = ["hello_test.cc"],
deps = ["@com_google_googletest//:gtest_main"], deps = [
"@googletest//:gtest",
"@googletest//:gtest_main",
],
) )
``` ```
This `cc_test` rule declares the C++ test binary you want to build, and links to This `cc_test` rule declares the C++ test binary you want to build, and links to
GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE` the GoogleTest library (`@googletest//:gtest"`) and the GoogleTest `main()`
file (`@com_google_googletest`). For more information about Bazel `BUILD` files, function (`@googletest//:gtest_main`). For more information about Bazel `BUILD`
see the files, see the
[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html). [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: Now you can build and run your test:
<pre> <pre>
<strong>my_workspace$ bazel test --test_output=all //:hello_test</strong> <strong>$ bazel test --cxxopt=-std=c++14 --test_output=all //:hello_test</strong>
INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured). INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
INFO: Found 1 test target... INFO: Found 1 test target...
INFO: From Testing //:hello_test: INFO: From Testing //:hello_test:

View file

@ -10,7 +10,7 @@ this tutorial as a starting point. If your project uses Bazel, see the
To complete this tutorial, you'll need: To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows). * A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++11. * A compatible C++ compiler that supports at least C++14.
* [CMake](https://cmake.org/) and a compatible build tool for building the * [CMake](https://cmake.org/) and a compatible build tool for building the
project. project.
* Compatible build tools include * Compatible build tools include
@ -52,13 +52,14 @@ To do this, in your project directory (`my_project`), create a file named
cmake_minimum_required(VERSION 3.14) cmake_minimum_required(VERSION 3.14)
project(my_project) project(my_project)
# GoogleTest requires at least C++11 # GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(FetchContent) include(FetchContent)
FetchContent_Declare( FetchContent_Declare(
googletest googletest
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
) )
# For Windows: Prevent overriding the parent project's compiler/linker settings # For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
@ -66,7 +67,7 @@ FetchContent_MakeAvailable(googletest)
``` ```
The above configuration declares a dependency on GoogleTest which is downloaded The above configuration declares a dependency on GoogleTest which is downloaded
from GitHub. In the above example, `609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is
the Git commit hash of the GoogleTest version to use; we recommend updating the the Git commit hash of the GoogleTest version to use; we recommend updating the
hash often to point to the latest version. hash often to point to the latest version.
@ -108,7 +109,7 @@ add_executable(
) )
target_link_libraries( target_link_libraries(
hello_test hello_test
gtest_main GTest::gtest_main
) )
include(GoogleTest) include(GoogleTest)

View file

@ -1,7 +1,7 @@
# Assertions Reference # Assertions Reference
This page lists the assertion macros provided by GoogleTest for verifying code This page lists the assertion macros provided by GoogleTest for verifying code
behavior. To use them, include the header `gtest/gtest.h`. behavior. To use them, add `#include <gtest/gtest.h>`.
The majority of the macros listed below come as a pair with an `EXPECT_` variant The majority of the macros listed below come as a pair with an `EXPECT_` variant
and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal
@ -88,7 +88,7 @@ For example, the following code verifies that the string `value1` starts with
10: 10:
```cpp ```cpp
#include "gmock/gmock.h" #include <gmock/gmock.h>
using ::testing::AllOf; using ::testing::AllOf;
using ::testing::Gt; using ::testing::Gt;
@ -276,7 +276,8 @@ Units in the Last Place (ULPs). To learn more about ULPs, see the article
`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` `ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)`
Verifies that the two `float` values *`val1`* and *`val2`* are approximately Verifies that the two `float` values *`val1`* and *`val2`* are approximately
equal, to within 4 ULPs from each other. equal, to within 4 ULPs from each other. Infinity and the largest finite float
value are considered to be one ULP apart.
### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ} ### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ}
@ -284,7 +285,8 @@ equal, to within 4 ULPs from each other.
`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` `ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)`
Verifies that the two `double` values *`val1`* and *`val2`* are approximately Verifies that the two `double` values *`val1`* and *`val2`* are approximately
equal, to within 4 ULPs from each other. equal, to within 4 ULPs from each other. Infinity and the largest finite double
value are considered to be one ULP apart.
### EXPECT_NEAR {#EXPECT_NEAR} ### EXPECT_NEAR {#EXPECT_NEAR}
@ -294,6 +296,11 @@ equal, to within 4 ULPs from each other.
Verifies that the difference between *`val1`* and *`val2`* does not exceed the Verifies that the difference between *`val1`* and *`val2`* does not exceed the
absolute error bound *`abs_error`*. absolute error bound *`abs_error`*.
If *`val`* and *`val2`* are both infinity of the same sign, the difference is
considered to be 0. Otherwise, if either value is infinity, the difference is
considered to be infinity. All non-NaN values (including infinity) are
considered to not exceed an *`abs_error`* of infinity.
## Exception Assertions {#exceptions} ## Exception Assertions {#exceptions}
The following assertions verify that a piece of code throws, or does not throw, The following assertions verify that a piece of code throws, or does not throw,
@ -515,7 +522,7 @@ Verifies that *`expression`* is a success `HRESULT`.
### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED} ### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED}
`EXPECT_HRESULT_FAILED(`*`expression`*`)` \ `EXPECT_HRESULT_FAILED(`*`expression`*`)` \
`EXPECT_HRESULT_FAILED(`*`expression`*`)` `ASSERT_HRESULT_FAILED(`*`expression`*`)`
Verifies that *`expression`* is a failure `HRESULT`. Verifies that *`expression`* is a failure `HRESULT`.

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. | | `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. |
| `StrEq(string)` | `argument` is equal to `string`. | | `StrEq(string)` | `argument` is equal to `string`. |
| `StrNe(string)` | `argument` is not 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`. | | `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. |
`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They `ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
use the regular expression syntax defined use the regular expression syntax defined
@ -288,3 +288,15 @@ which must be a permanent callback.
return ExplainMatchResult(matcher, arg.nested().property(), result_listener); 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);
}
```

View file

@ -1,8 +1,7 @@
# Mocking Reference # Mocking Reference
This page lists the facilities provided by GoogleTest for creating and working This page lists the facilities provided by GoogleTest for creating and working
with mock objects. To use them, include the header with mock objects. To use them, add `#include <gmock/gmock.h>`.
`gmock/gmock.h`.
## Macros {#macros} ## Macros {#macros}

View file

@ -3,7 +3,7 @@
<!--* toc_depth: 3 *--> <!--* toc_depth: 3 *-->
This page lists the facilities provided by GoogleTest for writing test programs. This page lists the facilities provided by GoogleTest for writing test programs.
To use them, include the header `gtest/gtest.h`. To use them, add `#include <gtest/gtest.h>`.
## Macros ## Macros
@ -94,7 +94,8 @@ Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with
The argument *`InstantiationName`* is a unique name for the instantiation of the The argument *`InstantiationName`* is a unique name for the instantiation of the
test suite, to distinguish between multiple instantiations. In test output, the test suite, to distinguish between multiple instantiations. In test output, the
instantiation name is added as a prefix to the test suite name instantiation name is added as a prefix to the test suite name
*`TestSuiteName`*. *`TestSuiteName`*. If *`InstantiationName`* is empty
(`INSTANTIATE_TEST_SUITE_P(, ...)`), no prefix is added.
The argument *`param_generator`* is one of the following GoogleTest-provided The argument *`param_generator`* is one of the following GoogleTest-provided
functions that generate the test parameters, all defined in the `::testing` functions that generate the test parameters, all defined in the `::testing`
@ -109,6 +110,7 @@ namespace:
| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. | | `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}`. | | `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`. | | `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 The optional last argument *`name_generator`* is a function or functor that
generates custom test name suffixes based on the test parameters. The function generates custom test name suffixes based on the test parameters. The function
@ -121,8 +123,8 @@ custom function can be used for more control:
```cpp ```cpp
INSTANTIATE_TEST_SUITE_P( INSTANTIATE_TEST_SUITE_P(
MyInstantiation, MyTestSuite, MyInstantiation, MyTestSuite,
::testing::Values(...), testing::Values(...),
[](const ::testing::TestParamInfo<MyTestSuite::ParamType>& info) { [](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
// Can use info.param here to generate the test suffix // Can use info.param here to generate the test suffix
std::string name = ... std::string name = ...
return name; return name;
@ -138,6 +140,7 @@ See also
### TYPED_TEST_SUITE {#TYPED_TEST_SUITE} ### TYPED_TEST_SUITE {#TYPED_TEST_SUITE}
`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)` `TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)`
`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`,`*`NameGenerator`*`)`
Defines a typed test suite based on the test fixture *`TestFixtureName`*. The Defines a typed test suite based on the test fixture *`TestFixtureName`*. The
test suite name is *`TestFixtureName`*. test suite name is *`TestFixtureName`*.
@ -147,7 +150,7 @@ type, for example:
```cpp ```cpp
template <typename T> template <typename T>
class MyFixture : public ::testing::Test { class MyFixture : public testing::Test {
public: public:
... ...
using List = std::list<T>; using List = std::list<T>;
@ -167,6 +170,22 @@ TYPED_TEST_SUITE(MyFixture, MyTypes);
The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE`
macro to parse correctly. macro to parse correctly.
The optional third argument *`NameGenerator`* allows specifying a class that
exposes a templated static function `GetName(int)`. For example:
```cpp
class NameGenerator {
public:
template <typename T>
static std::string GetName(int) {
if constexpr (std::is_same_v<T, char>) return "char";
if constexpr (std::is_same_v<T, int>) return "int";
if constexpr (std::is_same_v<T, unsigned int>) return "unsignedInt";
}
};
TYPED_TEST_SUITE(MyFixture, MyTypes, NameGenerator);
```
See also [`TYPED_TEST`](#TYPED_TEST) and See also [`TYPED_TEST`](#TYPED_TEST) and
[Typed Tests](../advanced.md#typed-tests) for more information. [Typed Tests](../advanced.md#typed-tests) for more information.
@ -276,7 +295,8 @@ must be registered with
The argument *`InstantiationName`* is a unique name for the instantiation of the The argument *`InstantiationName`* is a unique name for the instantiation of the
test suite, to distinguish between multiple instantiations. In test output, the test suite, to distinguish between multiple instantiations. In test output, the
instantiation name is added as a prefix to the test suite name instantiation name is added as a prefix to the test suite name
*`TestSuiteName`*. *`TestSuiteName`*. If *`InstantiationName`* is empty
(`INSTANTIATE_TYPED_TEST_SUITE_P(, ...)`), no prefix is added.
The argument *`Types`* is a [`Types`](#Types) object representing the list of The argument *`Types`* is a [`Types`](#Types) object representing the list of
types to run the tests on, for example: types to run the tests on, for example:
@ -323,7 +343,7 @@ Then the test code should look like:
```cpp ```cpp
namespace my_namespace { namespace my_namespace {
class MyClassTest : public ::testing::Test { class MyClassTest : public testing::Test {
... ...
}; };
@ -386,7 +406,7 @@ GoogleTest defines the following classes and types to help with writing tests.
### AssertionResult {#AssertionResult} ### AssertionResult {#AssertionResult}
`::testing::AssertionResult` `testing::AssertionResult`
A class for indicating whether an assertion was successful. A class for indicating whether an assertion was successful.
@ -400,14 +420,14 @@ To create an instance of this class, use one of the factory functions
### AssertionException {#AssertionException} ### AssertionException {#AssertionException}
`::testing::AssertionException` `testing::AssertionException`
Exception which can be thrown from Exception which can be thrown from
[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult). [`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult).
### EmptyTestEventListener {#EmptyTestEventListener} ### EmptyTestEventListener {#EmptyTestEventListener}
`::testing::EmptyTestEventListener` `testing::EmptyTestEventListener`
Provides an empty implementation of all methods in the Provides an empty implementation of all methods in the
[`TestEventListener`](#TestEventListener) interface, such that a subclass only [`TestEventListener`](#TestEventListener) interface, such that a subclass only
@ -415,7 +435,7 @@ needs to override the methods it cares about.
### Environment {#Environment} ### Environment {#Environment}
`::testing::Environment` `testing::Environment`
Represents a global test environment. See Represents a global test environment. See
[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down). [Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down).
@ -436,7 +456,7 @@ Override this to define how to tear down the environment.
### ScopedTrace {#ScopedTrace} ### ScopedTrace {#ScopedTrace}
`::testing::ScopedTrace` `testing::ScopedTrace`
An instance of this class causes a trace to be included in every test failure 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` message generated by code in the scope of the lifetime of the `ScopedTrace`
@ -452,7 +472,7 @@ ScopedTrace(const char* file, int line, const T& message)
Example usage: Example usage:
```cpp ```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 The resulting trace includes the given source file path and line number, and the
@ -463,7 +483,7 @@ See also [`SCOPED_TRACE`](#SCOPED_TRACE).
### Test {#Test} ### Test {#Test}
`::testing::Test` `testing::Test`
The abstract class that all tests inherit from. `Test` is not copyable. The abstract class that all tests inherit from. `Test` is not copyable.
@ -551,7 +571,7 @@ after running each individual test.
### TestWithParam {#TestWithParam} ### TestWithParam {#TestWithParam}
`::testing::TestWithParam<T>` `testing::TestWithParam<T>`
A convenience class which inherits from both [`Test`](#Test) and A convenience class which inherits from both [`Test`](#Test) and
[`WithParamInterface<T>`](#WithParamInterface). [`WithParamInterface<T>`](#WithParamInterface).
@ -671,7 +691,7 @@ during execution of `SetUpTestSuite` and `TearDownTestSuite`.
### TestInfo {#TestInfo} ### TestInfo {#TestInfo}
`::testing::TestInfo` `testing::TestInfo`
Stores information about a test. Stores information about a test.
@ -750,7 +770,7 @@ Returns the result of the test. See [`TestResult`](#TestResult).
### TestParamInfo {#TestParamInfo} ### TestParamInfo {#TestParamInfo}
`::testing::TestParamInfo<T>` `testing::TestParamInfo<T>`
Describes a parameter to a value-parameterized test. The type `T` is the type of Describes a parameter to a value-parameterized test. The type `T` is the type of
the parameter. the parameter.
@ -760,7 +780,7 @@ and its integer index respectively.
### UnitTest {#UnitTest} ### UnitTest {#UnitTest}
`::testing::UnitTest` `testing::UnitTest`
This class contains information about the test program. This class contains information about the test program.
@ -928,7 +948,7 @@ GoogleTest. See [`TestEventListeners`](#TestEventListeners).
### TestEventListener {#TestEventListener} ### TestEventListener {#TestEventListener}
`::testing::TestEventListener` `testing::TestEventListener`
The interface for tracing execution of tests. The methods below are listed in The interface for tracing execution of tests. The methods below are listed in
the order the corresponding events are fired. the order the corresponding events are fired.
@ -1026,7 +1046,7 @@ Fired after all test activities have ended.
### TestEventListeners {#TestEventListeners} ### TestEventListeners {#TestEventListeners}
`::testing::TestEventListeners` `testing::TestEventListeners`
Lets users add listeners to track events in GoogleTest. Lets users add listeners to track events in GoogleTest.
@ -1071,7 +1091,7 @@ the caller and makes this function return `NULL` the next time.
### TestPartResult {#TestPartResult} ### TestPartResult {#TestPartResult}
`::testing::TestPartResult` `testing::TestPartResult`
A copyable object representing the result of a test part (i.e. an assertion or A copyable object representing the result of a test part (i.e. an assertion or
an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`). an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`).
@ -1153,7 +1173,7 @@ Returns true if and only if the test part failed.
### TestProperty {#TestProperty} ### TestProperty {#TestProperty}
`::testing::TestProperty` `testing::TestProperty`
A copyable object representing a user-specified test property which can be A copyable object representing a user-specified test property which can be
output as a key/value string pair. output as a key/value string pair.
@ -1180,7 +1200,7 @@ Sets a new value, overriding the previous one.
### TestResult {#TestResult} ### TestResult {#TestResult}
`::testing::TestResult` `testing::TestResult`
Contains information about the result of a single test. Contains information about the result of a single test.
@ -1261,20 +1281,20 @@ range, aborts the program.
### TimeInMillis {#TimeInMillis} ### TimeInMillis {#TimeInMillis}
`::testing::TimeInMillis` `testing::TimeInMillis`
An integer type representing time in milliseconds. An integer type representing time in milliseconds.
### Types {#Types} ### Types {#Types}
`::testing::Types<T...>` `testing::Types<T...>`
Represents a list of types for use in typed tests and type-parameterized tests. 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: 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 See [Typed Tests](../advanced.md#typed-tests) and
@ -1283,7 +1303,7 @@ information.
### WithParamInterface {#WithParamInterface} ### WithParamInterface {#WithParamInterface}
`::testing::WithParamInterface<T>` `testing::WithParamInterface<T>`
The pure interface class that all value-parameterized tests inherit from. The pure interface class that all value-parameterized tests inherit from.
@ -1309,14 +1329,16 @@ tests.
### InitGoogleTest {#InitGoogleTest} ### InitGoogleTest {#InitGoogleTest}
`void ::testing::InitGoogleTest(int* argc, char** argv)` \ `void testing::InitGoogleTest(int* argc, char** argv)` \
`void ::testing::InitGoogleTest(int* argc, wchar_t** argv)` \ `void testing::InitGoogleTest(int* argc, wchar_t** argv)` \
`void ::testing::InitGoogleTest()` `void testing::InitGoogleTest()`
Initializes GoogleTest. This must be called before calling Initializes GoogleTest. This must be called before calling
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line
for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it
is removed from `argv`, and `*argc` is decremented. is removed from `argv`, and `*argc` is decremented. Keep in mind that `argv`
must terminate with a `NULL` pointer (i.e. `argv[argc]` is `NULL`), which is
already the case with the default `argv` passed to `main`.
No value is returned. Instead, the GoogleTest flag variables are updated. No value is returned. Instead, the GoogleTest flag variables are updated.
@ -1328,7 +1350,7 @@ platforms where there is no `argc`/`argv`.
### AddGlobalTestEnvironment {#AddGlobalTestEnvironment} ### AddGlobalTestEnvironment {#AddGlobalTestEnvironment}
`Environment* ::testing::AddGlobalTestEnvironment(Environment* env)` `Environment* testing::AddGlobalTestEnvironment(Environment* env)`
Adds a test environment to the test program. Must be called before Adds a test environment to the test program. Must be called before
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See
@ -1341,7 +1363,7 @@ See also [`Environment`](#Environment).
```cpp ```cpp
template <typename Factory> 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* type_param, const char* value_param,
const char* file, int line, Factory factory) const char* file, int line, Factory factory)
``` ```
@ -1380,27 +1402,27 @@ an all-caps name.
### AssertionSuccess {#AssertionSuccess} ### AssertionSuccess {#AssertionSuccess}
`AssertionResult ::testing::AssertionSuccess()` `AssertionResult testing::AssertionSuccess()`
Creates a successful assertion result. See Creates a successful assertion result. See
[`AssertionResult`](#AssertionResult). [`AssertionResult`](#AssertionResult).
### AssertionFailure {#AssertionFailure} ### AssertionFailure {#AssertionFailure}
`AssertionResult ::testing::AssertionFailure()` `AssertionResult testing::AssertionFailure()`
Creates a failed assertion result. Use the `<<` operator to store a failure Creates a failed assertion result. Use the `<<` operator to store a failure
message: message:
```cpp ```cpp
::testing::AssertionFailure() << "My failure message"; testing::AssertionFailure() << "My failure message";
``` ```
See [`AssertionResult`](#AssertionResult). See [`AssertionResult`](#AssertionResult).
### StaticAssertTypeEq {#StaticAssertTypeEq} ### StaticAssertTypeEq {#StaticAssertTypeEq}
`::testing::StaticAssertTypeEq<T1, T2>()` `testing::StaticAssertTypeEq<T1, T2>()`
Compile-time assertion for type equality. Compiles if and only if `T1` and `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. are the same type. The value it returns is irrelevant.
@ -1409,7 +1431,7 @@ See [Type Assertions](../advanced.md#type-assertions) for more information.
### PrintToString {#PrintToString} ### PrintToString {#PrintToString}
`std::string ::testing::PrintToString(x)` `std::string testing::PrintToString(x)`
Prints any value `x` using GoogleTest's value printer. Prints any value `x` using GoogleTest's value printer.
@ -1419,7 +1441,7 @@ for more information.
### PrintToStringParamName {#PrintToStringParamName} ### 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 A built-in parameterized test name generator which returns the result of
[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the [`PrintToString`](#PrintToString) called on `info.param`. Does not work when the

View file

@ -1,7 +1,7 @@
# Googletest Samples # Googletest Samples
If you're like us, you'd like to look at If you're like us, you'd like to look at
[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples) [googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples)
The sample directory has a number of well-commented samples showing how to use a The sample directory has a number of well-commented samples showing how to use a
variety of googletest features. variety of googletest features.

View file

@ -0,0 +1,61 @@
"""Provides a fake @fuchsia_sdk implementation that's used when the real one isn't available.
GoogleTest can be used with the [Fuchsia](https://fuchsia.dev/) SDK. However,
because the Fuchsia SDK does not yet support bzlmod, GoogleTest's `MODULE.bazel`
file by default provides a "fake" Fuchsia SDK.
To override this and use the real Fuchsia SDK, you can add the following to your
project's `MODULE.bazel` file:
fake_fuchsia_sdk_extension =
use_extension("@com_google_googletest//:fake_fuchsia_sdk.bzl", "fuchsia_sdk")
override_repo(fake_fuchsia_sdk_extension, "fuchsia_sdk")
NOTE: The `override_repo` built-in is only available in Bazel 8.0 and higher.
See https://github.com/google/googletest/issues/4472 for more details of why the
fake Fuchsia SDK is needed.
"""
def _fake_fuchsia_sdk_impl(repo_ctx):
for stub_target in repo_ctx.attr._stub_build_targets:
stub_package = stub_target
stub_target_name = stub_target.split("/")[-1]
repo_ctx.file("%s/BUILD.bazel" % stub_package, """
filegroup(
name = "%s",
)
""" % stub_target_name)
fake_fuchsia_sdk = repository_rule(
doc = "Used to create a fake @fuchsia_sdk repository with stub build targets.",
implementation = _fake_fuchsia_sdk_impl,
attrs = {
"_stub_build_targets": attr.string_list(
doc = "The stub build targets to initialize.",
default = [
"pkg/fdio",
"pkg/syslog",
"pkg/zx",
],
),
},
)
_create_fake = tag_class()
def _fuchsia_sdk_impl(module_ctx):
create_fake_sdk = False
for mod in module_ctx.modules:
for _ in mod.tags.create_fake:
create_fake_sdk = True
if create_fake_sdk:
fake_fuchsia_sdk(name = "fuchsia_sdk")
return module_ctx.extension_metadata(reproducible = True)
fuchsia_sdk = module_extension(
implementation = _fuchsia_sdk_impl,
tag_classes = {"create_fake": _create_fake},
)

View file

@ -36,8 +36,7 @@ endif()
# as ${gmock_SOURCE_DIR} and to the root binary directory as # as ${gmock_SOURCE_DIR} and to the root binary directory as
# ${gmock_BINARY_DIR}. # ${gmock_BINARY_DIR}.
# Language "C" is required for find_package(Threads). # Language "C" is required for find_package(Threads).
cmake_minimum_required(VERSION 3.5) cmake_minimum_required(VERSION 3.13)
cmake_policy(SET CMP0048 NEW)
project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
if (COMMAND set_up_hermetic_build) if (COMMAND set_up_hermetic_build)
@ -66,12 +65,13 @@ endif()
config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake
# Adds Google Mock's and Google Test's header directories to the search path. # Adds Google Mock's and Google Test's header directories to the search path.
# Get Google Test's include dirs from the target, gtest_SOURCE_DIR is broken
# when using fetch-content with the name "GTest".
get_target_property(gtest_include_dirs gtest INCLUDE_DIRECTORIES)
set(gmock_build_include_dirs set(gmock_build_include_dirs
"${gmock_SOURCE_DIR}/include" "${gmock_SOURCE_DIR}/include"
"${gmock_SOURCE_DIR}" "${gmock_SOURCE_DIR}"
"${gtest_SOURCE_DIR}/include" "${gtest_include_dirs}")
# This directory is needed to build directly from Google Test sources.
"${gtest_SOURCE_DIR}")
include_directories(${gmock_build_include_dirs}) include_directories(${gmock_build_include_dirs})
######################################################################## ########################################################################
@ -101,10 +101,7 @@ else()
target_link_libraries(gmock_main PUBLIC gmock) target_link_libraries(gmock_main PUBLIC gmock)
set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION}) set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
endif() endif()
# 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}") string(REPLACE ";" "$<SEMICOLON>" dirs "${gmock_build_include_dirs}")
target_include_directories(gmock SYSTEM INTERFACE target_include_directories(gmock SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>" "$<BUILD_INTERFACE:${dirs}>"
@ -112,11 +109,10 @@ if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
target_include_directories(gmock_main SYSTEM INTERFACE target_include_directories(gmock_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>" "$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>") "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
endif()
######################################################################## ########################################################################
# #
# Install rules # Install rules.
install_project(gmock gmock_main) install_project(gmock gmock_main)
######################################################################## ########################################################################
@ -136,11 +132,7 @@ if (gmock_build_tests)
enable_testing() enable_testing()
if (MINGW OR CYGWIN) if (MINGW OR CYGWIN)
if (CMAKE_VERSION VERSION_LESS "2.8.12")
add_compile_options("-Wa,-mbig-obj") add_compile_options("-Wa,-mbig-obj")
else()
add_definitions("-Wa,-mbig-obj")
endif()
endif() endif()
############################################################ ############################################################

View file

@ -8,8 +8,8 @@ derive better designs of your system and write better tests.
It is inspired by: It is inspired by:
* [jMock](http://www.jmock.org/) * [jMock](http://www.jmock.org/)
* [EasyMock](http://www.easymock.org/) * [EasyMock](https://easymock.org/)
* [Hamcrest](http://code.google.com/p/hamcrest/) * [Hamcrest](https://code.google.com/p/hamcrest/)
It is designed with C++'s specifics in mind. It is designed with C++'s specifics in mind.
@ -36,5 +36,5 @@ Details and examples can be found here:
* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html) * [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html)
GoogleMock is a part of GoogleMock is a part of
[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a [GoogleTest C++ testing framework](https://github.com/google/googletest/) and a
subject to the same requirements. subject to the same requirements.

View file

@ -122,7 +122,7 @@
// MORE INFORMATION: // MORE INFORMATION:
// //
// To learn more about using these macros, please search for 'ACTION' on // To learn more about using these macros, please search for 'ACTION' on
// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md // https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md
// IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.* // IWYU pragma: friend gmock/.*
@ -135,6 +135,7 @@
#endif #endif
#include <algorithm> #include <algorithm>
#include <exception>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <string> #include <string>
@ -146,10 +147,7 @@
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gmock/internal/gmock-pp.h" #include "gmock/internal/gmock-pp.h"
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
namespace testing { namespace testing {
@ -178,9 +176,15 @@ struct BuiltInDefaultValueGetter<T, false> {
static T Get() { static T Get() {
Assert(false, __FILE__, __LINE__, Assert(false, __FILE__, __LINE__,
"Default action undefined for the function return type."); "Default action undefined for the function return type.");
return internal::Invalid<T>(); #if defined(__GNUC__) || defined(__clang__)
__builtin_unreachable();
#elif defined(_MSC_VER)
__assume(0);
#else
return Invalid<T>();
// The above statement will never be reached, but is required in // The above statement will never be reached, but is required in
// order for this function to compile. // order for this function to compile.
#endif
} }
}; };
@ -614,7 +618,7 @@ class DefaultValue {
private: private:
class ValueProducer { class ValueProducer {
public: public:
virtual ~ValueProducer() {} virtual ~ValueProducer() = default;
virtual T Produce() = 0; virtual T Produce() = 0;
}; };
@ -702,8 +706,8 @@ class ActionInterface {
typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::Result Result;
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
ActionInterface() {} ActionInterface() = default;
virtual ~ActionInterface() {} virtual ~ActionInterface() = default;
// Performs the action. This method is not const, as in general an // Performs the action. This method is not const, as in general an
// action can have side effects and be stateful. For example, a // action can have side effects and be stateful. For example, a
@ -752,7 +756,7 @@ class Action<R(Args...)> {
// Constructs a null Action. Needed for storing Action objects in // Constructs a null Action. Needed for storing Action objects in
// STL containers. // STL containers.
Action() {} Action() = default;
// Construct an Action from a specified callable. // Construct an Action from a specified callable.
// This cannot take std::function directly, because then Action would not be // This cannot take std::function directly, because then Action would not be
@ -1276,7 +1280,7 @@ class AssignAction {
const T2 value_; const T2 value_;
}; };
#if !GTEST_OS_WINDOWS_MOBILE #ifndef GTEST_OS_WINDOWS_MOBILE
// Implements the SetErrnoAndReturn action to simulate return from // Implements the SetErrnoAndReturn action to simulate return from
// various system calls and libc functions. // various system calls and libc functions.
@ -1420,16 +1424,18 @@ struct WithArgsAction {
// providing a call operator because even with a particular set of arguments // providing a call operator because even with a particular set of arguments
// they don't have a fixed return type. // they don't have a fixed return type.
template <typename R, typename... Args, template <
typename R, typename... Args,
typename std::enable_if< typename std::enable_if<
std::is_convertible< std::is_convertible<InnerAction,
InnerAction, // Unfortunately we can't use the InnerSignature
// Unfortunately we can't use the InnerSignature alias here; // alias here; MSVC complains about the I
// MSVC complains about the I parameter pack not being // parameter pack not being expanded (error C3520)
// expanded (error C3520) despite it being expanded in the // despite it being expanded in the type alias.
// type alias. // TupleElement is also an MSVC workaround.
OnceAction<R(typename std::tuple_element< // See its definition for details.
I, std::tuple<Args...>>::type...)>>::value, OnceAction<R(internal::TupleElement<
I, std::tuple<Args...>>...)>>::value,
int>::type = 0> int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT operator OnceAction<R(Args...)>() && { // NOLINT
struct OA { struct OA {
@ -1445,16 +1451,18 @@ struct WithArgsAction {
return OA{std::move(inner_action)}; return OA{std::move(inner_action)};
} }
template <typename R, typename... Args, template <
typename R, typename... Args,
typename std::enable_if< typename std::enable_if<
std::is_convertible< std::is_convertible<const InnerAction&,
const InnerAction&, // Unfortunately we can't use the InnerSignature
// Unfortunately we can't use the InnerSignature alias here; // alias here; MSVC complains about the I
// MSVC complains about the I parameter pack not being // parameter pack not being expanded (error C3520)
// expanded (error C3520) despite it being expanded in the // despite it being expanded in the type alias.
// type alias. // TupleElement is also an MSVC workaround.
Action<R(typename std::tuple_element< // See its definition for details.
I, std::tuple<Args...>>::type...)>>::value, Action<R(internal::TupleElement<
I, std::tuple<Args...>>...)>>::value,
int>::type = 0> int>::type = 0>
operator Action<R(Args...)>() const { // NOLINT operator Action<R(Args...)>() const { // NOLINT
Action<InnerSignature<R, Args...>> converted(inner_action); Action<InnerSignature<R, Args...>> converted(inner_action);
@ -1485,6 +1493,7 @@ class DoAllAction<FinalAction> {
// providing a call operator because even with a particular set of arguments // providing a call operator because even with a particular set of arguments
// they don't have a fixed return type. // they don't have a fixed return type.
// We support conversion to OnceAction whenever the sub-action does.
template <typename R, typename... Args, template <typename R, typename... Args,
typename std::enable_if< typename std::enable_if<
std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value, std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,
@ -1493,6 +1502,21 @@ class DoAllAction<FinalAction> {
return std::move(final_action_); return std::move(final_action_);
} }
// We also support conversion to OnceAction whenever the sub-action supports
// conversion to Action (since any Action can also be a OnceAction).
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<
negation<
std::is_convertible<FinalAction, OnceAction<R(Args...)>>>,
std::is_convertible<FinalAction, Action<R(Args...)>>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
return Action<R(Args...)>(std::move(final_action_));
}
// We support conversion to Action whenever the sub-action does.
template < template <
typename R, typename... Args, typename R, typename... Args,
typename std::enable_if< typename std::enable_if<
@ -1572,12 +1596,12 @@ class DoAllAction<InitialAction, OtherActions...>
: Base({}, std::forward<U>(other_actions)...), : Base({}, std::forward<U>(other_actions)...),
initial_action_(std::forward<T>(initial_action)) {} initial_action_(std::forward<T>(initial_action)) {}
template <typename R, typename... Args, // We support conversion to OnceAction whenever both the initial action and
// the rest support conversion to OnceAction.
template <
typename R, typename... Args,
typename std::enable_if< typename std::enable_if<
conjunction< conjunction<std::is_convertible<
// Both the initial action and the rest must support
// conversion to OnceAction.
std::is_convertible<
InitialAction, InitialAction,
OnceAction<void(InitialActionArgType<Args>...)>>, OnceAction<void(InitialActionArgType<Args>...)>>,
std::is_convertible<Base, OnceAction<R(Args...)>>>::value, std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
@ -1604,12 +1628,34 @@ class DoAllAction<InitialAction, OtherActions...>
}; };
} }
// We also support conversion to OnceAction whenever the initial action
// supports conversion to Action (since any Action can also be a OnceAction).
//
// The remaining sub-actions must also be compatible, but we don't need to
// special case them because the base class deals with them.
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<
negation<std::is_convertible<
InitialAction,
OnceAction<void(InitialActionArgType<Args>...)>>>,
std::is_convertible<InitialAction,
Action<void(InitialActionArgType<Args>...)>>,
std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
return DoAll(
Action<void(InitialActionArgType<Args>...)>(std::move(initial_action_)),
std::move(static_cast<Base&>(*this)));
}
// We support conversion to Action whenever both the initial action and the
// rest support conversion to Action.
template < template <
typename R, typename... Args, typename R, typename... Args,
typename std::enable_if< typename std::enable_if<
conjunction< conjunction<
// Both the initial action and the rest must support conversion to
// Action.
std::is_convertible<const InitialAction&, std::is_convertible<const InitialAction&,
Action<void(InitialActionArgType<Args>...)>>, Action<void(InitialActionArgType<Args>...)>>,
std::is_convertible<const Base&, Action<R(Args...)>>>::value, std::is_convertible<const Base&, Action<R(Args...)>>>::value,
@ -1657,7 +1703,8 @@ template <size_t k>
struct ReturnArgAction { struct ReturnArgAction {
template <typename... Args, template <typename... Args,
typename = typename std::enable_if<(k < sizeof...(Args))>::type> typename = typename std::enable_if<(k < sizeof...(Args))>::type>
auto operator()(Args&&... args) const -> decltype(std::get<k>( auto operator()(Args&&... args) const
-> decltype(std::get<k>(
std::forward_as_tuple(std::forward<Args>(args)...))) { std::forward_as_tuple(std::forward<Args>(args)...))) {
return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...)); return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...));
} }
@ -1739,6 +1786,13 @@ struct ThrowAction {
return [copy](Args...) -> R { throw copy; }; return [copy](Args...) -> R { throw copy; };
} }
}; };
struct RethrowAction {
std::exception_ptr exception;
template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT
return [ex = exception](Args...) -> R { std::rethrow_exception(ex); };
}
};
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
} // namespace internal } // namespace internal
@ -1925,7 +1979,7 @@ PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {
return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
} }
#if !GTEST_OS_WINDOWS_MOBILE #ifndef GTEST_OS_WINDOWS_MOBILE
// Creates an action that sets errno and returns the appropriate error. // Creates an action that sets errno and returns the appropriate error.
template <typename T> template <typename T>
@ -2055,13 +2109,23 @@ internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
return {pointer}; return {pointer};
} }
// Action Throw(exception) can be used in a mock function of any type
// to throw the given exception. Any copyable value can be thrown.
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
// Action Throw(exception) can be used in a mock function of any type
// to throw the given exception. Any copyable value can be thrown,
// except for std::exception_ptr, which is likely a mistake if
// thrown directly.
template <typename T> template <typename T>
internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) { typename std::enable_if<
!std::is_base_of<std::exception_ptr, typename std::decay<T>::type>::value,
internal::ThrowAction<typename std::decay<T>::type>>::type
Throw(T&& exception) {
return {std::forward<T>(exception)}; return {std::forward<T>(exception)};
} }
// Action Rethrow(exception_ptr) can be used in a mock function of any type
// to rethrow any exception_ptr. Note that the same object is thrown each time.
inline internal::RethrowAction Rethrow(std::exception_ptr exception) {
return {std::move(exception)};
}
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
namespace internal { namespace internal {
@ -2110,13 +2174,13 @@ struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
R operator()(Args&&... arg) const { R operator()(Args&&... arg) const {
static constexpr size_t kMaxArgs = static constexpr size_t kMaxArgs =
sizeof...(Args) <= 10 ? sizeof...(Args) : 10; sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
return Apply(MakeIndexSequence<kMaxArgs>{}, return Apply(std::make_index_sequence<kMaxArgs>{},
MakeIndexSequence<10 - kMaxArgs>{}, std::make_index_sequence<10 - kMaxArgs>{},
args_type{std::forward<Args>(arg)...}); args_type{std::forward<Args>(arg)...});
} }
template <std::size_t... arg_id, std::size_t... excess_id> template <std::size_t... arg_id, std::size_t... excess_id>
R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>, R Apply(std::index_sequence<arg_id...>, std::index_sequence<excess_id...>,
const args_type& args) const { const args_type& args) const {
// Impl need not be specific to the signature of action being implemented; // Impl need not be specific to the signature of action being implemented;
// only the implementing function body needs to have all of the specific // only the implementing function body needs to have all of the specific
@ -2149,9 +2213,9 @@ template <typename F, typename Impl>
} }
#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
, const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ , GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const arg##i##_type& arg##i
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \ GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const args_type& args GMOCK_PP_REPEAT( \
GMOCK_INTERNAL_ARG_UNUSED, , 10) GMOCK_INTERNAL_ARG_UNUSED, , 10)
#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
@ -2291,8 +2355,6 @@ template <typename F, typename Impl>
} // namespace testing } // namespace testing
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#pragma warning(pop)
#endif
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_

View file

@ -65,7 +65,7 @@ namespace testing {
// The implementation of a cardinality. // The implementation of a cardinality.
class CardinalityInterface { class CardinalityInterface {
public: public:
virtual ~CardinalityInterface() {} virtual ~CardinalityInterface() = default;
// Conservative estimate on the lower/upper bound of the number of // Conservative estimate on the lower/upper bound of the number of
// calls allowed. // calls allowed.
@ -92,7 +92,7 @@ class GTEST_API_ Cardinality {
public: public:
// Constructs a null cardinality. Needed for storing Cardinality // Constructs a null cardinality. Needed for storing Cardinality
// objects in STL containers. // objects in STL containers.
Cardinality() {} Cardinality() = default;
// Constructs a Cardinality from its implementation. // Constructs a Cardinality from its implementation.
explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}

View file

@ -34,9 +34,10 @@
// IWYU pragma: private, include "gmock/gmock.h" // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.* // IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
#include <cstddef>
#include <type_traits> // IWYU pragma: keep #include <type_traits> // IWYU pragma: keep
#include <utility> // IWYU pragma: keep #include <utility> // IWYU pragma: keep
@ -69,22 +70,22 @@ constexpr bool PrefixOf(const char* a, const char* b) {
return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1));
} }
template <int N, int M> template <size_t N, size_t M>
constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) {
return N <= M && internal::PrefixOf(prefix, str); return N <= M && internal::PrefixOf(prefix, str);
} }
template <int N, int M> template <size_t N, size_t M>
constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) {
return N <= M && internal::PrefixOf(suffix, str + M - N); return N <= M && internal::PrefixOf(suffix, str + M - N);
} }
template <int N, int M> template <size_t N, size_t M>
constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { constexpr bool Equals(const char (&a)[N], const char (&b)[M]) {
return N == M && internal::PrefixOf(a, b); return N == M && internal::PrefixOf(a, b);
} }
template <int N> template <size_t N>
constexpr bool ValidateSpec(const char (&spec)[N]) { constexpr bool ValidateSpec(const char (&spec)[N]) {
return internal::Equals("const", spec) || return internal::Equals("const", spec) ||
internal::Equals("override", spec) || internal::Equals("override", spec) ||
@ -109,7 +110,10 @@ using internal::FunctionMocker;
} // namespace testing } // namespace testing
#define MOCK_METHOD(...) \ #define MOCK_METHOD(...) \
GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) 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 GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ #define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
@ -177,8 +181,9 @@ using internal::FunctionMocker;
_Signature)>::Result \ _Signature)>::Result \
GMOCK_INTERNAL_EXPAND(_CallType) \ GMOCK_INTERNAL_EXPAND(_CallType) \
_MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \ GMOCK_PP_IF(_Constness, const, ) \
GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \ _RefSpec _NoexceptSpec GMOCK_PP_IF(_Override, override, ) \
GMOCK_PP_IF(_Final, final, ) { \
GMOCK_MOCKER_(_N, _Constness, _MethodName) \ GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.SetOwnerAndName(this, #_MethodName); \ .SetOwnerAndName(this, #_MethodName); \
return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
@ -511,4 +516,4 @@ using internal::FunctionMocker;
#define GMOCK_MOCKER_(arity, constness, Method) \ #define GMOCK_MOCKER_(arity, constness, Method) \
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_

View file

@ -240,7 +240,7 @@
// //
// To learn more about using these macros, please search for 'MATCHER' // To learn more about using these macros, please search for 'MATCHER'
// on // on
// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md // https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md
// //
// This file also implements some commonly used argument matchers. More // This file also implements some commonly used argument matchers. More
// matchers can be defined by the user implementing the // matchers can be defined by the user implementing the
@ -257,7 +257,10 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <exception>
#include <functional>
#include <initializer_list> #include <initializer_list>
#include <ios>
#include <iterator> #include <iterator>
#include <limits> #include <limits>
#include <memory> #include <memory>
@ -405,13 +408,22 @@ class MatcherCastImpl<T, Matcher<U>> {
} }
private: private:
class Impl : public MatcherInterface<T> { // If it's possible to implicitly convert a `const T&` to U, then `Impl` can
// take that as input to avoid a copy. Otherwise, such as when `T` is a
// non-const reference type or a type explicitly constructible only from a
// non-const reference, then `Impl` must use `T` as-is (potentially copying).
using ImplArgT =
typename std::conditional<std::is_convertible<const T&, const U&>::value,
const T&, T>::type;
class Impl : public MatcherInterface<ImplArgT> {
public: public:
explicit Impl(const Matcher<U>& source_matcher) explicit Impl(const Matcher<U>& source_matcher)
: source_matcher_(source_matcher) {} : source_matcher_(source_matcher) {}
// We delegate the matching logic to the source matcher. // We delegate the matching logic to the source matcher.
bool MatchAndExplain(T x, MatchResultListener* listener) const override { bool MatchAndExplain(ImplArgT x,
MatchResultListener* listener) const override {
using FromType = typename std::remove_cv<typename std::remove_pointer< using FromType = typename std::remove_cv<typename std::remove_pointer<
typename std::remove_reference<T>::type>::type>::type; typename std::remove_reference<T>::type>::type>::type;
using ToType = typename std::remove_cv<typename std::remove_pointer< using ToType = typename std::remove_cv<typename std::remove_pointer<
@ -428,9 +440,8 @@ class MatcherCastImpl<T, Matcher<U>> {
// Do the cast to `U` explicitly if necessary. // Do the cast to `U` explicitly if necessary.
// Otherwise, let implicit conversions do the trick. // Otherwise, let implicit conversions do the trick.
using CastType = using CastType = typename std::conditional<
typename std::conditional<std::is_convertible<T&, const U&>::value, std::is_convertible<ImplArgT&, const U&>::value, ImplArgT&, U>::type;
T&, U>::type;
return source_matcher_.MatchAndExplain(static_cast<CastType>(x), return source_matcher_.MatchAndExplain(static_cast<CastType>(x),
listener); listener);
@ -487,12 +498,12 @@ class MatcherBaseImpl<Derived<Ts...>> {
template <typename F> template <typename F>
operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit) operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)
return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{}); return Apply<F>(std::make_index_sequence<sizeof...(Ts)>{});
} }
private: private:
template <typename F, std::size_t... tuple_ids> template <typename F, std::size_t... tuple_ids>
::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const { ::testing::Matcher<F> Apply(std::index_sequence<tuple_ids...>) const {
return ::testing::Matcher<F>( return ::testing::Matcher<F>(
new typename Derived<Ts...>::template gmock_Impl<F>( new typename Derived<Ts...>::template gmock_Impl<F>(
std::get<tuple_ids>(params_)...)); std::get<tuple_ids>(params_)...));
@ -525,18 +536,16 @@ inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {
// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
// contravariant): just keep a copy of the original Matcher<U>, convert the // contravariant): just keep a copy of the original Matcher<U>, convert the
// argument from type T to U, and then pass it to the underlying Matcher<U>. // argument from type T to U, and then pass it to the underlying Matcher<U>.
// The only exception is when U is a reference and T is not, as the // The only exception is when U is a non-const reference and T is not, as the
// underlying Matcher<U> may be interested in the argument's address, which // underlying Matcher<U> may be interested in the argument's address, which
// is not preserved in the conversion from T to U. // cannot be preserved in the conversion from T to U (since a copy of the input
// T argument would be required to provide a non-const reference U).
template <typename T, typename U> template <typename T, typename U>
inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) { inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
// Enforce that T can be implicitly converted to U. // Enforce that T can be implicitly converted to U.
static_assert(std::is_convertible<const T&, const U&>::value, static_assert(std::is_convertible<const T&, const U&>::value,
"T must be implicitly convertible to U"); "T must be implicitly convertible to U (and T must be a "
// Enforce that we are not converting a non-reference type T to a reference "non-const reference if U is a non-const reference)");
// type U.
static_assert(std::is_reference<T>::value || !std::is_reference<U>::value,
"cannot convert non reference arg to reference");
// In case both T and U are arithmetic types, enforce that the // In case both T and U are arithmetic types, enforce that the
// conversion is not lossy. // conversion is not lossy.
typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
@ -558,10 +567,15 @@ Matcher<T> A();
// and MUST NOT BE USED IN USER CODE!!! // and MUST NOT BE USED IN USER CODE!!!
namespace internal { namespace internal {
// Used per go/ranked-overloads for dispatching.
struct Rank0 {};
struct Rank1 : Rank0 {};
using HighestRank = Rank1;
// If the explanation is not empty, prints it to the ostream. // If the explanation is not empty, prints it to the ostream.
inline void PrintIfNotEmpty(const std::string& explanation, inline void PrintIfNotEmpty(const std::string& explanation,
::std::ostream* os) { ::std::ostream* os) {
if (explanation != "" && os != nullptr) { if (!explanation.empty() && os != nullptr) {
*os << ", " << explanation; *os << ", " << explanation;
} }
} }
@ -1045,7 +1059,7 @@ class StartsWithMatcher {
template <typename MatcheeStringType> template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s, bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const { MatchResultListener* /* listener */) const {
const StringType& s2(s); const StringType s2(s);
return s2.length() >= prefix_.length() && return s2.length() >= prefix_.length() &&
s2.substr(0, prefix_.length()) == prefix_; s2.substr(0, prefix_.length()) == prefix_;
} }
@ -1099,7 +1113,7 @@ class EndsWithMatcher {
template <typename MatcheeStringType> template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s, bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const { MatchResultListener* /* listener */) const {
const StringType& s2(s); const StringType s2(s);
return s2.length() >= suffix_.length() && return s2.length() >= suffix_.length() &&
s2.substr(s2.length() - suffix_.length()) == suffix_; s2.substr(s2.length() - suffix_.length()) == suffix_;
} }
@ -1198,27 +1212,27 @@ class PairMatchBase {
}; };
}; };
class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> { class Eq2Matcher : public PairMatchBase<Eq2Matcher, std::equal_to<>> {
public: public:
static const char* Desc() { return "an equal pair"; } static const char* Desc() { return "an equal pair"; }
}; };
class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> { class Ne2Matcher : public PairMatchBase<Ne2Matcher, std::not_equal_to<>> {
public: public:
static const char* Desc() { return "an unequal pair"; } static const char* Desc() { return "an unequal pair"; }
}; };
class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> { class Lt2Matcher : public PairMatchBase<Lt2Matcher, std::less<>> {
public: public:
static const char* Desc() { return "a pair where the first < the second"; } static const char* Desc() { return "a pair where the first < the second"; }
}; };
class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> { class Gt2Matcher : public PairMatchBase<Gt2Matcher, std::greater<>> {
public: public:
static const char* Desc() { return "a pair where the first > the second"; } static const char* Desc() { return "a pair where the first > the second"; }
}; };
class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> { class Le2Matcher : public PairMatchBase<Le2Matcher, std::less_equal<>> {
public: public:
static const char* Desc() { return "a pair where the first <= the second"; } static const char* Desc() { return "a pair where the first <= the second"; }
}; };
class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> { class Ge2Matcher : public PairMatchBase<Ge2Matcher, std::greater_equal<>> {
public: public:
static const char* Desc() { return "a pair where the first >= the second"; } static const char* Desc() { return "a pair where the first >= the second"; }
}; };
@ -1297,34 +1311,48 @@ class AllOfMatcherImpl : public MatcherInterface<const T&> {
bool MatchAndExplain(const T& x, bool MatchAndExplain(const T& x,
MatchResultListener* listener) const override { MatchResultListener* listener) const override {
// If either matcher1_ or matcher2_ doesn't match x, we only need // This method uses matcher's explanation when explaining the result.
// to explain why one of them fails. // However, if matcher doesn't provide one, this method uses matcher's
// description.
std::string all_match_result; std::string all_match_result;
for (const Matcher<T>& matcher : matchers_) {
for (size_t i = 0; i < matchers_.size(); ++i) {
StringMatchResultListener slistener; StringMatchResultListener slistener;
if (matchers_[i].MatchAndExplain(x, &slistener)) { // Return explanation for first failed matcher.
if (all_match_result.empty()) { if (!matcher.MatchAndExplain(x, &slistener)) {
all_match_result = slistener.str(); const std::string explanation = slistener.str();
if (!explanation.empty()) {
*listener << explanation;
} else { } else {
std::string result = slistener.str(); *listener << "which doesn't match (" << Describe(matcher) << ")";
if (!result.empty()) {
all_match_result += ", and ";
all_match_result += result;
} }
}
} else {
*listener << slistener.str();
return false; return false;
} }
// Keep track of explanations in case all matchers succeed.
std::string explanation = slistener.str();
if (explanation.empty()) {
explanation = Describe(matcher);
}
if (all_match_result.empty()) {
all_match_result = explanation;
} else {
if (!explanation.empty()) {
all_match_result += ", and ";
all_match_result += explanation;
}
}
} }
// Otherwise we need to explain why *both* of them match.
*listener << all_match_result; *listener << all_match_result;
return true; return true;
} }
private: private:
// Returns matcher description as a string.
std::string Describe(const Matcher<T>& matcher) const {
StringMatchResultListener listener;
matcher.DescribeTo(listener.stream());
return listener.str();
}
const std::vector<Matcher<T>> matchers_; const std::vector<Matcher<T>> matchers_;
}; };
@ -1402,34 +1430,55 @@ class AnyOfMatcherImpl : public MatcherInterface<const T&> {
bool MatchAndExplain(const T& x, bool MatchAndExplain(const T& x,
MatchResultListener* listener) const override { MatchResultListener* listener) const override {
// This method uses matcher's explanation when explaining the result.
// However, if matcher doesn't provide one, this method uses matcher's
// description.
std::string no_match_result; std::string no_match_result;
for (const Matcher<T>& matcher : matchers_) {
// If either matcher1_ or matcher2_ matches x, we just need to
// explain why *one* of them matches.
for (size_t i = 0; i < matchers_.size(); ++i) {
StringMatchResultListener slistener; StringMatchResultListener slistener;
if (matchers_[i].MatchAndExplain(x, &slistener)) { // Return explanation for first match.
*listener << slistener.str(); if (matcher.MatchAndExplain(x, &slistener)) {
return true; const std::string explanation = slistener.str();
if (!explanation.empty()) {
*listener << explanation;
} else { } else {
if (no_match_result.empty()) { *listener << "which matches (" << Describe(matcher) << ")";
no_match_result = slistener.str();
} else {
std::string result = slistener.str();
if (!result.empty()) {
no_match_result += ", and ";
no_match_result += result;
} }
return true;
}
// Keep track of explanations in case there is no match.
std::string explanation = slistener.str();
if (explanation.empty()) {
explanation = DescribeNegation(matcher);
}
if (no_match_result.empty()) {
no_match_result = explanation;
} else {
if (!explanation.empty()) {
no_match_result += ", and ";
no_match_result += explanation;
} }
} }
} }
// Otherwise we need to explain why *both* of them fail.
*listener << no_match_result; *listener << no_match_result;
return false; return false;
} }
private: private:
// Returns matcher description as a string.
std::string Describe(const Matcher<T>& matcher) const {
StringMatchResultListener listener;
matcher.DescribeTo(listener.stream());
return listener.str();
}
std::string DescribeNegation(const Matcher<T>& matcher) const {
StringMatchResultListener listener;
matcher.DescribeNegationTo(listener.stream());
return listener.str();
}
const std::vector<Matcher<T>> matchers_; const std::vector<Matcher<T>> matchers_;
}; };
@ -1472,6 +1521,7 @@ class SomeOfArrayMatcher {
operator Matcher<U>() const { // NOLINT operator Matcher<U>() const { // NOLINT
using RawU = typename std::decay<U>::type; using RawU = typename std::decay<U>::type;
std::vector<Matcher<RawU>> matchers; std::vector<Matcher<RawU>> matchers;
matchers.reserve(matchers_.size());
for (const auto& matcher : matchers_) { for (const auto& matcher : matchers_) {
matchers.push_back(MatcherCast<RawU>(matcher)); matchers.push_back(MatcherCast<RawU>(matcher));
} }
@ -1479,7 +1529,7 @@ class SomeOfArrayMatcher {
} }
private: private:
const ::std::vector<T> matchers_; const std::vector<std::remove_const_t<T>> matchers_;
}; };
template <typename T> template <typename T>
@ -2231,6 +2281,9 @@ class ResultOfMatcher {
class Impl : public MatcherInterface<T> { class Impl : public MatcherInterface<T> {
using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>( using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(
std::declval<CallableStorageType>(), std::declval<T>())); std::declval<CallableStorageType>(), std::declval<T>()));
using InnerType = std::conditional_t<
std::is_lvalue_reference<ResultType>::value,
const typename std::remove_reference<ResultType>::type&, ResultType>;
public: public:
template <typename M> template <typename M>
@ -2238,7 +2291,7 @@ class ResultOfMatcher {
const CallableStorageType& callable, const M& matcher) const CallableStorageType& callable, const M& matcher)
: result_description_(result_description), : result_description_(result_description),
callable_(callable), callable_(callable),
matcher_(MatcherCast<ResultType>(matcher)) {} matcher_(MatcherCast<InnerType>(matcher)) {}
void DescribeTo(::std::ostream* os) const override { void DescribeTo(::std::ostream* os) const override {
if (result_description_.empty()) { if (result_description_.empty()) {
@ -2268,7 +2321,7 @@ class ResultOfMatcher {
// takes a non-const reference as argument. // takes a non-const reference as argument.
// Also, specifying template argument explicitly is needed because T could // Also, specifying template argument explicitly is needed because T could
// be a non-const reference (e.g. Matcher<Uncopyable&>). // be a non-const reference (e.g. Matcher<Uncopyable&>).
ResultType result = InnerType result =
CallableTraits<Callable>::template Invoke<T>(callable_, obj); CallableTraits<Callable>::template Invoke<T>(callable_, obj);
return MatchPrintAndExplain(result, matcher_, listener); return MatchPrintAndExplain(result, matcher_, listener);
} }
@ -2281,7 +2334,7 @@ class ResultOfMatcher {
// use stateful callables with ResultOf(), which doesn't guarantee // use stateful callables with ResultOf(), which doesn't guarantee
// how many times the callable will be invoked. // how many times the callable will be invoked.
mutable CallableStorageType callable_; mutable CallableStorageType callable_;
const Matcher<ResultType> matcher_; const Matcher<InnerType> matcher_;
}; // class Impl }; // class Impl
const std::string result_description_; const std::string result_description_;
@ -2309,11 +2362,11 @@ class SizeIsMatcher {
: size_matcher_(MatcherCast<SizeType>(size_matcher)) {} : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
void DescribeTo(::std::ostream* os) const override { void DescribeTo(::std::ostream* os) const override {
*os << "size "; *os << "has a size that ";
size_matcher_.DescribeTo(os); size_matcher_.DescribeTo(os);
} }
void DescribeNegationTo(::std::ostream* os) const override { void DescribeNegationTo(::std::ostream* os) const override {
*os << "size "; *os << "has a size that ";
size_matcher_.DescribeNegationTo(os); size_matcher_.DescribeNegationTo(os);
} }
@ -2916,26 +2969,23 @@ class EachMatcher {
const M inner_matcher_; const M inner_matcher_;
}; };
struct Rank1 {};
struct Rank0 : Rank1 {};
namespace pair_getters { namespace pair_getters {
using std::get; using std::get;
template <typename T> template <typename T>
auto First(T& x, Rank1) -> decltype(get<0>(x)) { // NOLINT auto First(T& x, Rank0) -> decltype(get<0>(x)) { // NOLINT
return get<0>(x); return get<0>(x);
} }
template <typename T> template <typename T>
auto First(T& x, Rank0) -> decltype((x.first)) { // NOLINT auto First(T& x, Rank1) -> decltype((x.first)) { // NOLINT
return x.first; return x.first;
} }
template <typename T> template <typename T>
auto Second(T& x, Rank1) -> decltype(get<1>(x)) { // NOLINT auto Second(T& x, Rank0) -> decltype(get<1>(x)) { // NOLINT
return get<1>(x); return get<1>(x);
} }
template <typename T> template <typename T>
auto Second(T& x, Rank0) -> decltype((x.second)) { // NOLINT auto Second(T& x, Rank1) -> decltype((x.second)) { // NOLINT
return x.second; return x.second;
} }
} // namespace pair_getters } // namespace pair_getters
@ -2961,9 +3011,9 @@ class KeyMatcherImpl : public MatcherInterface<PairType> {
MatchResultListener* listener) const override { MatchResultListener* listener) const override {
StringMatchResultListener inner_listener; StringMatchResultListener inner_listener;
const bool match = inner_matcher_.MatchAndExplain( const bool match = inner_matcher_.MatchAndExplain(
pair_getters::First(key_value, Rank0()), &inner_listener); pair_getters::First(key_value, Rank1()), &inner_listener);
const std::string explanation = inner_listener.str(); const std::string explanation = inner_listener.str();
if (explanation != "") { if (!explanation.empty()) {
*listener << "whose first field is a value " << explanation; *listener << "whose first field is a value " << explanation;
} }
return match; return match;
@ -3083,18 +3133,18 @@ class PairMatcherImpl : public MatcherInterface<PairType> {
if (!listener->IsInterested()) { if (!listener->IsInterested()) {
// If the listener is not interested, we don't need to construct the // If the listener is not interested, we don't need to construct the
// explanation. // explanation.
return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) && return first_matcher_.Matches(pair_getters::First(a_pair, Rank1())) &&
second_matcher_.Matches(pair_getters::Second(a_pair, Rank0())); second_matcher_.Matches(pair_getters::Second(a_pair, Rank1()));
} }
StringMatchResultListener first_inner_listener; StringMatchResultListener first_inner_listener;
if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()), if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank1()),
&first_inner_listener)) { &first_inner_listener)) {
*listener << "whose first field does not match"; *listener << "whose first field does not match";
PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
return false; return false;
} }
StringMatchResultListener second_inner_listener; StringMatchResultListener second_inner_listener;
if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()), if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank1()),
&second_inner_listener)) { &second_inner_listener)) {
*listener << "whose second field does not match"; *listener << "whose second field does not match";
PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
@ -3110,12 +3160,12 @@ class PairMatcherImpl : public MatcherInterface<PairType> {
const std::string& second_explanation, const std::string& second_explanation,
MatchResultListener* listener) const { MatchResultListener* listener) const {
*listener << "whose both fields match"; *listener << "whose both fields match";
if (first_explanation != "") { if (!first_explanation.empty()) {
*listener << ", where the first field is a value " << first_explanation; *listener << ", where the first field is a value " << first_explanation;
} }
if (second_explanation != "") { if (!second_explanation.empty()) {
*listener << ", "; *listener << ", ";
if (first_explanation != "") { if (!first_explanation.empty()) {
*listener << "and "; *listener << "and ";
} else { } else {
*listener << "where "; *listener << "where ";
@ -3147,8 +3197,8 @@ class PairMatcher {
}; };
template <typename T, size_t... I> template <typename T, size_t... I>
auto UnpackStructImpl(const T& t, IndexSequence<I...>, int) auto UnpackStructImpl(const T& t, std::index_sequence<I...>,
-> decltype(std::tie(get<I>(t)...)) { int) -> decltype(std::tie(get<I>(t)...)) {
static_assert(std::tuple_size<T>::value == sizeof...(I), static_assert(std::tuple_size<T>::value == sizeof...(I),
"Number of arguments doesn't match the number of fields."); "Number of arguments doesn't match the number of fields.");
return std::tie(get<I>(t)...); return std::tie(get<I>(t)...);
@ -3156,91 +3206,111 @@ auto UnpackStructImpl(const T& t, IndexSequence<I...>, int)
#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606 #if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<1>, char) {
const auto& [a] = t; const auto& [a] = t;
return std::tie(a); return std::tie(a);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<2>, char) {
const auto& [a, b] = t; const auto& [a, b] = t;
return std::tie(a, b); return std::tie(a, b);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<3>, char) {
const auto& [a, b, c] = t; const auto& [a, b, c] = t;
return std::tie(a, b, c); return std::tie(a, b, c);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<4>, char) {
const auto& [a, b, c, d] = t; const auto& [a, b, c, d] = t;
return std::tie(a, b, c, d); return std::tie(a, b, c, d);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<5>, char) {
const auto& [a, b, c, d, e] = t; const auto& [a, b, c, d, e] = t;
return std::tie(a, b, c, d, e); return std::tie(a, b, c, d, e);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<6>, char) {
const auto& [a, b, c, d, e, f] = t; const auto& [a, b, c, d, e, f] = t;
return std::tie(a, b, c, d, e, f); return std::tie(a, b, c, d, e, f);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<7>, char) {
const auto& [a, b, c, d, e, f, g] = t; const auto& [a, b, c, d, e, f, g] = t;
return std::tie(a, b, c, d, e, f, g); return std::tie(a, b, c, d, e, f, g);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<8>, char) {
const auto& [a, b, c, d, e, f, g, h] = t; const auto& [a, b, c, d, e, f, g, h] = t;
return std::tie(a, b, c, d, e, f, g, h); return std::tie(a, b, c, d, e, f, g, h);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<9>, char) {
const auto& [a, b, c, d, e, f, g, h, i] = t; const auto& [a, b, c, d, e, f, g, h, i] = t;
return std::tie(a, b, c, d, e, f, g, h, i); return std::tie(a, b, c, d, e, f, g, h, i);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<10>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j] = t; const auto& [a, b, c, d, e, f, g, h, i, j] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j); return std::tie(a, b, c, d, e, f, g, h, i, j);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<11>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k] = t; const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k); return std::tie(a, b, c, d, e, f, g, h, i, j, k);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<12>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t; const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l); return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<13>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t; const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m); return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<14>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t; const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n); return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<15>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t; const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o); return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
} }
template <typename T> template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) { auto UnpackStructImpl(const T& t, std::make_index_sequence<16>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t; 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); 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, std::make_index_sequence<17>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q);
}
template <typename T>
auto UnpackStructImpl(const T& t, std::make_index_sequence<18>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r);
}
template <typename T>
auto UnpackStructImpl(const T& t, std::make_index_sequence<19>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s);
}
template <typename T>
auto UnpackStructImpl(const T& u, std::make_index_sequence<20>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t] = u;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t);
}
#endif // defined(__cpp_structured_bindings) #endif // defined(__cpp_structured_bindings)
template <size_t I, typename T> template <size_t I, typename T>
auto UnpackStruct(const T& t) auto UnpackStruct(const T& t)
-> decltype((UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0)) { -> decltype((UnpackStructImpl)(t, std::make_index_sequence<I>{}, 0)) {
return (UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0); return (UnpackStructImpl)(t, std::make_index_sequence<I>{}, 0);
} }
// Helper function to do comma folding in C++11. // Helper function to do comma folding in C++11.
@ -3253,7 +3323,7 @@ template <typename Struct, typename StructSize>
class FieldsAreMatcherImpl; class FieldsAreMatcherImpl;
template <typename Struct, size_t... I> template <typename Struct, size_t... I>
class FieldsAreMatcherImpl<Struct, IndexSequence<I...>> class FieldsAreMatcherImpl<Struct, std::index_sequence<I...>>
: public MatcherInterface<Struct> { : public MatcherInterface<Struct> {
using UnpackedType = using UnpackedType =
decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>())); decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));
@ -3335,8 +3405,8 @@ class FieldsAreMatcher {
template <typename Struct> template <typename Struct>
operator Matcher<Struct>() const { // NOLINT operator Matcher<Struct>() const { // NOLINT
return Matcher<Struct>( return Matcher<Struct>(
new FieldsAreMatcherImpl<const Struct&, IndexSequenceFor<Inner...>>( new FieldsAreMatcherImpl<const Struct&,
matchers_)); std::index_sequence_for<Inner...>>(matchers_));
} }
private: private:
@ -3629,23 +3699,6 @@ class UnorderedElementsAreMatcherImpl
AnalyzeElements(stl_container.begin(), stl_container.end(), AnalyzeElements(stl_container.begin(), stl_container.end(),
&element_printouts, listener); &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) && return VerifyMatchMatrix(element_printouts, matrix, listener) &&
FindPairing(matrix, listener); FindPairing(matrix, listener);
} }
@ -3766,7 +3819,7 @@ class UnorderedElementsAreArrayMatcher {
private: private:
UnorderedMatcherRequire::Flags match_flags_; UnorderedMatcherRequire::Flags match_flags_;
::std::vector<T> matchers_; std::vector<std::remove_const_t<T>> matchers_;
}; };
// Implements ElementsAreArray(). // Implements ElementsAreArray().
@ -3787,7 +3840,7 @@ class ElementsAreArrayMatcher {
} }
private: private:
const ::std::vector<T> matchers_; const std::vector<std::remove_const_t<T>> matchers_;
}; };
// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
@ -3874,6 +3927,21 @@ GTEST_API_ std::string FormatMatcherDescription(
bool negation, const char* matcher_name, bool negation, const char* matcher_name,
const std::vector<const char*>& param_names, const Strings& param_values); const std::vector<const char*>& param_names, const Strings& param_values);
// Overloads to support `OptionalMatcher` being used with a type that either
// supports implicit conversion to bool or a `has_value()` method.
template <typename Optional>
auto IsOptionalEngaged(const Optional& optional,
Rank1) -> decltype(!!optional) {
// The use of double-negation here is to preserve historical behavior where
// the matcher used `operator!` rather than directly using `operator bool`.
return !static_cast<bool>(!optional);
}
template <typename Optional>
auto IsOptionalEngaged(const Optional& optional,
Rank0) -> decltype(!optional.has_value()) {
return optional.has_value();
}
// Implements a matcher that checks the value of a optional<> type variable. // Implements a matcher that checks the value of a optional<> type variable.
template <typename ValueMatcher> template <typename ValueMatcher>
class OptionalMatcher { class OptionalMatcher {
@ -3906,7 +3974,7 @@ class OptionalMatcher {
bool MatchAndExplain(Optional optional, bool MatchAndExplain(Optional optional,
MatchResultListener* listener) const override { MatchResultListener* listener) const override {
if (!optional) { if (!IsOptionalEngaged(optional, HighestRank())) {
*listener << "which is not engaged"; *listener << "which is not engaged";
return false; return false;
} }
@ -4100,7 +4168,12 @@ class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {
const char* sep = ""; const char* sep = "";
// Workaround spurious C4189 on MSVC<=15.7 when k is empty. // Workaround spurious C4189 on MSVC<=15.7 when k is empty.
(void)sep; (void)sep;
const char* dummy[] = {"", (*os << sep << "#" << k, 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 = ", ")...};
(void)dummy; (void)dummy;
*os << ") "; *os << ") ";
} }
@ -4734,9 +4807,10 @@ Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
// Supports the Pointwise(m, {a, b, c}) syntax. // Supports the Pointwise(m, {a, b, c}) syntax.
template <typename TupleMatcher, typename T> template <typename TupleMatcher, typename T>
inline internal::PointwiseMatcher<TupleMatcher, std::vector<T>> Pointwise( inline internal::PointwiseMatcher<TupleMatcher,
const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) { std::vector<std::remove_const_t<T>>>
return Pointwise(tuple_matcher, std::vector<T>(rhs)); Pointwise(const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
return Pointwise(tuple_matcher, std::vector<std::remove_const_t<T>>(rhs));
} }
// UnorderedPointwise(pair_matcher, rhs) matches an STL-style // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
@ -4898,7 +4972,7 @@ inline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(
// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0). // - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).
// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1 // - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1
// matches Lt(0). // matches Lt(0).
// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both // - {1, 2} doesn't match IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both
// match Gt(0). The reason is that different matchers must be used for // match Gt(0). The reason is that different matchers must be used for
// elements in different slots of the container. // elements in different slots of the container.
// //
@ -5223,9 +5297,10 @@ inline InnerMatcher AllArgs(const InnerMatcher& matcher) {
} }
// Returns a matcher that matches the value of an optional<> type variable. // Returns a matcher that matches the value of an optional<> type variable.
// The matcher implementation only uses '!arg' and requires that the optional<> // The matcher implementation only uses '!arg' (or 'arg.has_value()' if '!arg`
// type has a 'value_type' member type and that '*arg' is of type 'value_type' // isn't a valid expression) and requires that the optional<> type has a
// and is printable using 'PrintToString'. It is compatible with // 'value_type' member type and that '*arg' is of type 'value_type' and is
// printable using 'PrintToString'. It is compatible with
// std::optional/std::experimental::optional. // std::optional/std::experimental::optional.
// Note that to compare an optional type variable against nullopt you should // Note that to compare an optional type variable against nullopt you should
// use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the // use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the
@ -5467,12 +5542,17 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
} \ } \
}; \ }; \
}; \ }; \
GTEST_ATTRIBUTE_UNUSED_ inline name##Matcher name() { return {}; } \ inline name##Matcher GMOCK_INTERNAL_WARNING_PUSH() \
GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-function") \
GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \
name GMOCK_INTERNAL_WARNING_POP()() { \
return {}; \
} \
template <typename arg_type> \ template <typename arg_type> \
bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \ bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
const arg_type& arg, \ const arg_type& arg, \
::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \ GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED ::testing::MatchResultListener* \
const result_listener) const
#define MATCHER_P(name, p0, description) \ #define MATCHER_P(name, p0, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (#p0), (p0)) GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (#p0), (p0))
@ -5533,7 +5613,8 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
\ \
private: \ private: \
::std::string FormatDescription(bool negation) const { \ ::std::string FormatDescription(bool negation) const { \
::std::string gmock_description = (description); \ ::std::string gmock_description; \
gmock_description = (description); \
if (!gmock_description.empty()) { \ if (!gmock_description.empty()) { \
return gmock_description; \ return gmock_description; \
} \ } \
@ -5553,11 +5634,11 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
} \ } \
template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \ template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
template <typename arg_type> \ template <typename arg_type> \
bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl< \ bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>:: \
arg_type>::MatchAndExplain(const arg_type& arg, \ gmock_Impl<arg_type>::MatchAndExplain( \
::testing::MatchResultListener* \ const arg_type& arg, \
result_listener GTEST_ATTRIBUTE_UNUSED_) \ GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED ::testing:: \
const MatchResultListener* result_listener) const
#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \ #define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \
GMOCK_PP_TAIL( \ GMOCK_PP_TAIL( \
@ -5592,8 +5673,8 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
#define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \ #define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args)) GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))
#define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \ #define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg) \
, gmock_p##i , ::std::forward<arg##_type>(gmock_p##i)
// To prevent ADL on certain functions we put them on a separate namespace. // To prevent ADL on certain functions we put them on a separate namespace.
using namespace no_adl; // NOLINT using namespace no_adl; // NOLINT

View file

@ -526,9 +526,10 @@
GMOCK_INTERNAL_LIST_##value_params)){}) \ GMOCK_INTERNAL_LIST_##value_params)){}) \
GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \ GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \
name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \ name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \
##value_params GMOCK_ACTION_CLASS_(name, value_params)( \ ##value_params \
GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept \ GMOCK_ACTION_CLASS_(name, value_params)(GMOCK_ACTION_CLASS_( \
GMOCK_INTERNAL_DEFN_COPY_##value_params template <typename F> \ name, value_params) &&) noexcept GMOCK_INTERNAL_DEFN_COPY_ \
##value_params template <typename F> \
operator ::testing::Action<F>() const { \ operator ::testing::Action<F>() const { \
return GMOCK_PP_IF( \ return GMOCK_PP_IF( \
GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
@ -582,10 +583,7 @@ namespace testing {
// the macro definition, as the warnings are generated when the macro // the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore // is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here. // we suppress them here.
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
namespace internal { namespace internal {
@ -594,21 +592,23 @@ namespace internal {
// Overloads for other custom-callables are provided in the // Overloads for other custom-callables are provided in the
// internal/custom/gmock-generated-actions.h header. // internal/custom/gmock-generated-actions.h header.
template <typename F, typename... Args> template <typename F, typename... Args>
auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) { auto InvokeArgument(F &&f,
return f(args...); Args... args) -> decltype(std::forward<F>(f)(args...)) {
return std::forward<F>(f)(args...);
} }
template <std::size_t index, typename... Params> template <std::size_t index, typename... Params>
struct InvokeArgumentAction { struct InvokeArgumentAction {
template <typename... Args, template <typename... Args,
typename = typename std::enable_if<(index < sizeof...(Args))>::type> 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::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
std::declval<const Params &>()...)) { std::declval<const Params &>()...)) {
internal::FlatTuple<Args &&...> args_tuple(FlatTupleConstructTag{}, internal::FlatTuple<Args &&...> args_tuple(FlatTupleConstructTag{},
std::forward<Args>(args)...); std::forward<Args>(args)...);
return params.Apply([&](const Params &...unpacked_params) { return params.Apply([&](const Params &...unpacked_params) {
auto&& callable = args_tuple.template Get<index>(); auto &&callable = std::move(args_tuple.template Get<index>());
return internal::InvokeArgument( return internal::InvokeArgument(
std::forward<decltype(callable)>(callable), unpacked_params...); std::forward<decltype(callable)>(callable), unpacked_params...);
}); });
@ -653,9 +653,7 @@ InvokeArgument(Params&&... params) {
internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)}; internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
} }
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#pragma warning(pop)
#endif
} // namespace testing } // namespace testing

View file

@ -40,32 +40,60 @@
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#include <ostream>
#include <string>
#include "gmock/gmock-matchers.h" #include "gmock/gmock-matchers.h"
namespace testing { namespace testing {
// Silence C4100 (unreferenced formal // Silence C4100 (unreferenced formal
// parameter) for MSVC // parameter) for MSVC
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#pragma warning(push) #if defined(_MSC_VER) && (_MSC_VER == 1900)
#pragma warning(disable : 4100)
#if (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value // and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14 // to bool 'true' or 'false') for MSVC 14
#pragma warning(disable : 4800) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#endif
#endif #endif
// Defines a matcher that matches an empty container. The container must namespace internal {
// support both size() and empty(), which all STL-like containers provide.
MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") { // Implements the polymorphic IsEmpty matcher, which
if (arg.empty()) { // 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; return true;
} }
*result_listener << "whose size is " << arg.size(); *listener << "whose size is " << c.size();
return false; return false;
} }
// 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());
}
// Define a matcher that matches a value that evaluates in boolean // Define a matcher that matches a value that evaluates in boolean
// context to true. Useful for types that define "explicit operator // context to true. Useful for types that define "explicit operator
// bool" operators and so can't be compared for equality with true // bool" operators and so can't be compared for equality with true
@ -82,9 +110,10 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
return !static_cast<bool>(arg); return !static_cast<bool>(arg);
} }
#ifdef _MSC_VER #if defined(_MSC_VER) && (_MSC_VER == 1900)
#pragma warning(pop) GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#endif #endif
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
} // namespace testing } // namespace testing

View file

@ -98,7 +98,7 @@ constexpr bool HasStrictnessModifier() {
// deregistration. This guarantees that MockClass's constructor and destructor // deregistration. This guarantees that MockClass's constructor and destructor
// run with the same level of strictness as its instance methods. // run with the same level of strictness as its instance methods.
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \ #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) && \
(defined(_MSC_VER) || defined(__clang__)) (defined(_MSC_VER) || defined(__clang__))
// We need to mark these classes with this declspec to ensure that // We need to mark these classes with this declspec to ensure that
// the empty base class optimization is performed. // the empty base class optimization is performed.

View file

@ -65,6 +65,7 @@
#include <functional> #include <functional>
#include <map> #include <map>
#include <memory> #include <memory>
#include <ostream>
#include <set> #include <set>
#include <sstream> #include <sstream>
#include <string> #include <string>
@ -203,6 +204,9 @@ class GTEST_API_ UntypedFunctionMockerBase {
using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>; using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
struct UninterestingCallCleanupHandler;
struct FailureCleanupHandler;
// Returns an Expectation object that references and co-owns exp, // Returns an Expectation object that references and co-owns exp,
// which must be an expectation on this mock function. // which must be an expectation on this mock function.
Expectation GetHandleOf(ExpectationBase* exp); Expectation GetHandleOf(ExpectationBase* exp);
@ -562,7 +566,7 @@ class ExpectationSet {
typedef Expectation::Set::value_type value_type; typedef Expectation::Set::value_type value_type;
// Constructs an empty set. // Constructs an empty set.
ExpectationSet() {} ExpectationSet() = default;
// This single-argument ctor must not be explicit, in order to support the // This single-argument ctor must not be explicit, in order to support the
// ExpectationSet es = EXPECT_CALL(...); // ExpectationSet es = EXPECT_CALL(...);
@ -656,7 +660,7 @@ class GTEST_API_ InSequence {
InSequence(const InSequence&) = delete; InSequence(const InSequence&) = delete;
InSequence& operator=(const InSequence&) = delete; InSequence& operator=(const InSequence&) = delete;
} GTEST_ATTRIBUTE_UNUSED_; };
namespace internal { namespace internal {
@ -706,6 +710,12 @@ class GTEST_API_ ExpectationBase {
// describes it to the ostream. // describes it to the ostream.
virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0; 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: protected:
friend class ::testing::Expectation; friend class ::testing::Expectation;
friend class UntypedFunctionMockerBase; friend class UntypedFunctionMockerBase;
@ -772,6 +782,10 @@ class GTEST_API_ ExpectationBase {
retired_ = true; 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. // Returns true if and only if this expectation is satisfied.
bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
@ -831,6 +845,7 @@ class GTEST_API_ ExpectationBase {
const char* file_; // The file that contains the expectation. const char* file_; // The file that contains the expectation.
int line_; // The line number of the expectation. int line_; // The line number of the expectation.
const std::string source_text_; // The EXPECT_CALL(...) source text. 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. // True if and only if the cardinality is specified explicitly.
bool cardinality_specified_; bool cardinality_specified_;
Cardinality cardinality_; // The cardinality of the expectation. Cardinality cardinality_; // The cardinality of the expectation.
@ -909,6 +924,13 @@ class TypedExpectation<R(Args...)> : public ExpectationBase {
return *this; 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. // Implements the .Times() clause.
TypedExpectation& Times(const Cardinality& a_cardinality) { TypedExpectation& Times(const Cardinality& a_cardinality) {
ExpectationBase::UntypedTimes(a_cardinality); ExpectationBase::UntypedTimes(a_cardinality);
@ -1199,10 +1221,15 @@ class TypedExpectation<R(Args...)> : public ExpectationBase {
::std::ostream* why) ::std::ostream* why)
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld(); g_gmock_mutex.AssertHeld();
const ::std::string& expectation_description = GetDescription();
if (IsSaturated()) { if (IsSaturated()) {
// We have an excessive call. // We have an excessive call.
IncrementCallCount(); IncrementCallCount();
*what << "Mock function called more times than expected - "; *what << "Mock function ";
if (!expectation_description.empty()) {
*what << "\"" << expectation_description << "\" ";
}
*what << "called more times than expected - ";
mocker->DescribeDefaultActionTo(args, what); mocker->DescribeDefaultActionTo(args, what);
DescribeCallCountTo(why); DescribeCallCountTo(why);
@ -1217,7 +1244,11 @@ class TypedExpectation<R(Args...)> : public ExpectationBase {
} }
// Must be done after IncrementCount()! // Must be done after IncrementCount()!
*what << "Mock function call matches " << source_text() << "...\n"; *what << "Mock function ";
if (!expectation_description.empty()) {
*what << "\"" << expectation_description << "\" ";
}
*what << "call matches " << source_text() << "...\n";
return &(GetCurrentAction(mocker, args)); return &(GetCurrentAction(mocker, args));
} }
@ -1368,6 +1399,41 @@ class Cleanup final {
std::function<void()> f_; 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> template <typename F>
class FunctionMocker; class FunctionMocker;
@ -1380,7 +1446,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
using ArgumentTuple = std::tuple<Args...>; using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>; using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
FunctionMocker() {} FunctionMocker() = default;
// There is no generally useful and implementable semantics of // There is no generally useful and implementable semantics of
// copying a mock object, so copying a mock is usually a user error. // copying a mock object, so copying a mock is usually a user error.
@ -1766,8 +1832,14 @@ 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 // 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. // either case we can't assign it to a local variable.
const Cleanup report_uninteresting_call( //
[&] { ReportUninterestingCall(reaction, ss.str()); }); // 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};
return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss); return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
} }
@ -1811,22 +1883,13 @@ 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 // 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. // either case we can't assign it to a local variable.
const Cleanup handle_failures([&] { //
ss << "\n" << why.str(); // Note that we *don't* use any local callback types (like lambdas) here.
// Doing so slows down compilation dramatically because the *constructor* of
if (!found) { // std::function<T> is re-instantiated with different template
// No expectation matches this call - reports a failure. // parameters each time.
Expect(false, nullptr, -1, ss.str()); const FailureCleanupHandler handle_failures = {
} else if (is_excessive) { ss, why, loc, untyped_expectation, found, 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(), return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
ss); ss);

View file

@ -53,13 +53,14 @@
// //
// where all clauses are optional and WillOnce() can be repeated. // where all clauses are optional and WillOnce() can be repeated.
#include "gmock/gmock-actions.h" #include "gmock/gmock-actions.h" // IWYU pragma: export
#include "gmock/gmock-cardinalities.h" #include "gmock/gmock-cardinalities.h" // IWYU pragma: export
#include "gmock/gmock-function-mocker.h" #include "gmock/gmock-function-mocker.h" // IWYU pragma: export
#include "gmock/gmock-matchers.h" #include "gmock/gmock-matchers.h" // IWYU pragma: export
#include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-actions.h" // IWYU pragma: export
#include "gmock/gmock-more-matchers.h" #include "gmock/gmock-more-matchers.h" // IWYU pragma: export
#include "gmock/gmock-nice-strict.h" #include "gmock/gmock-nice-strict.h" // IWYU pragma: export
#include "gmock/gmock-spec-builders.h" // IWYU pragma: export
#include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"

View file

@ -44,6 +44,7 @@
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include <utility>
#include <vector> #include <vector>
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
@ -58,11 +59,7 @@ namespace internal {
// Silence MSVC C4100 (unreferenced formal parameter) and // Silence MSVC C4100 (unreferenced formal parameter) and
// C4805('==': unsafe mix of type 'const int' and type 'const bool') // C4805('==': unsafe mix of type 'const int' and type 'const bool')
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4805)
#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 // Joins a vector of strings as if they are fields of a tuple; returns
// the joined string. // the joined string.
@ -95,6 +92,24 @@ inline Element* GetRawPointer(Element* p) {
return 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 // 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 // same as unsigned short when the compiler option /Zc:wchar_t- is
// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
@ -210,7 +225,7 @@ class FailureReporterInterface {
// The type of a failure (either non-fatal or fatal). // The type of a failure (either non-fatal or fatal).
enum FailureType { kNonfatal, kFatal }; enum FailureType { kNonfatal, kFatal };
virtual ~FailureReporterInterface() {} virtual ~FailureReporterInterface() = default;
// Reports a failure that occurred at the given source file location. // Reports a failure that occurred at the given source file location.
virtual void ReportFailure(FailureType type, const char* file, int line, virtual void ReportFailure(FailureType type, const char* file, int line,
@ -290,13 +305,6 @@ class WithoutMatchers {
// Internal use only: access the singleton instance of WithoutMatchers. // Internal use only: access the singleton instance of WithoutMatchers.
GTEST_API_ WithoutMatchers GetWithoutMatchers(); 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 // 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 // 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 // when a value of type T is needed for compilation, but the statement
@ -304,7 +312,8 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers();
// crashes). // crashes).
template <typename T> template <typename T>
inline T Invalid() { inline T Invalid() {
Assert(false, "", -1, "Internal error: attempt to return invalid value"); Assert(/*condition=*/false, /*file=*/"", /*line=*/-1,
"Internal error: attempt to return invalid value");
#if defined(__GNUC__) || defined(__clang__) #if defined(__GNUC__) || defined(__clang__)
__builtin_unreachable(); __builtin_unreachable();
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
@ -314,10 +323,6 @@ inline T Invalid() {
#endif #endif
} }
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// Given a raw type (i.e. having no top-level reference or const // Given a raw type (i.e. having no top-level reference or const
// modifier) RawContainer that's either an STL-style container or a // modifier) RawContainer that's either an STL-style container or a
// native array, class StlContainerView<RawContainer> has the // native array, class StlContainerView<RawContainer> has the
@ -416,7 +421,7 @@ struct RemoveConstFromKey<std::pair<const K, V> > {
GTEST_API_ void IllegalDoDefault(const char* file, int line); GTEST_API_ void IllegalDoDefault(const char* file, int line);
template <typename F, typename Tuple, size_t... Idx> template <typename F, typename Tuple, size_t... Idx>
auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) auto ApplyImpl(F&& f, Tuple&& args, std::index_sequence<Idx...>)
-> decltype(std::forward<F>(f)( -> decltype(std::forward<F>(f)(
std::get<Idx>(std::forward<Tuple>(args))...)) { std::get<Idx>(std::forward<Tuple>(args))...)) {
return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...); return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
@ -424,12 +429,13 @@ auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)
// Apply the function to a tuple of arguments. // Apply the function to a tuple of arguments.
template <typename F, typename Tuple> template <typename F, typename Tuple>
auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl( auto Apply(F&& f, Tuple&& args)
-> decltype(ApplyImpl(
std::forward<F>(f), std::forward<Tuple>(args), std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size< std::make_index_sequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>())) { typename std::remove_reference<Tuple>::type>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size< std::make_index_sequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>()); typename std::remove_reference<Tuple>::type>::value>());
} }
@ -461,14 +467,21 @@ struct Function<R(Args...)> {
using MakeResultIgnoredValue = IgnoredValue(Args...); using MakeResultIgnoredValue = IgnoredValue(Args...);
}; };
#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
template <typename R, typename... Args> template <typename R, typename... Args>
constexpr size_t Function<R(Args...)>::ArgumentCount; 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); bool Base64Unescape(const std::string& encoded, std::string* decoded);
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4805
#pragma warning(pop)
#endif
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing

View file

@ -42,6 +42,7 @@
#include <assert.h> #include <assert.h>
#include <stdlib.h> #include <stdlib.h>
#include <cstdint> #include <cstdint>
#include <iostream> #include <iostream>
@ -56,7 +57,7 @@
#include "gmock/internal/custom/gmock-port.h" #include "gmock/internal/custom/gmock-port.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_HAS_ABSL #if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
#include "absl/flags/declare.h" #include "absl/flags/declare.h"
#include "absl/flags/flag.h" #include "absl/flags/flag.h"
#endif #endif
@ -73,7 +74,7 @@
#define GMOCK_FLAG(name) FLAGS_gmock_##name #define GMOCK_FLAG(name) FLAGS_gmock_##name
// Pick a command line flags implementation. // Pick a command line flags implementation.
#if GTEST_HAS_ABSL #if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
// Macros for defining flags. // Macros for defining flags.
#define GMOCK_DEFINE_bool_(name, default_val, doc) \ #define GMOCK_DEFINE_bool_(name, default_val, doc) \
@ -95,7 +96,7 @@
#define GMOCK_FLAG_SET(name, value) \ #define GMOCK_FLAG_SET(name, value) \
(void)(::absl::SetFlag(&GMOCK_FLAG(name), value)) (void)(::absl::SetFlag(&GMOCK_FLAG(name), value))
#else // GTEST_HAS_ABSL #else // defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
// Macros for defining flags. // Macros for defining flags.
#define GMOCK_DEFINE_bool_(name, default_val, doc) \ #define GMOCK_DEFINE_bool_(name, default_val, doc) \
@ -134,6 +135,6 @@
#define GMOCK_FLAG_GET(name) ::testing::GMOCK_FLAG(name) #define GMOCK_FLAG_GET(name) ::testing::GMOCK_FLAG(name)
#define GMOCK_FLAG_SET(name, value) (void)(::testing::GMOCK_FLAG(name) = value) #define GMOCK_FLAG_SET(name, value) (void)(::testing::GMOCK_FLAG(name) = value)
#endif // GTEST_HAS_ABSL #endif // defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS)
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_

View file

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

View file

@ -41,8 +41,10 @@
#include <cctype> #include <cctype>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
#include <iostream>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <string> #include <string>
#include <utility>
#include <vector> #include <vector>
#include "gmock/gmock.h" #include "gmock/gmock.h"
@ -87,7 +89,7 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
(!IsDigit(prev_char) && IsDigit(*p)); (!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) { if (IsAlNum(*p)) {
if (starts_new_word && result != "") result += ' '; if (starts_new_word && !result.empty()) result += ' ';
result += ToLower(*p); result += ToLower(*p);
} }
} }
@ -181,7 +183,7 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
} }
std::cout << "Stack trace:\n" std::cout << "Stack trace:\n"
<< ::testing::internal::GetCurrentOsStackTraceExceptTop( << ::testing::internal::GetCurrentOsStackTraceExceptTop(
::testing::UnitTest::GetInstance(), actual_to_skip); actual_to_skip);
} }
std::cout << ::std::flush; std::cout << ::std::flush;
} }
@ -198,20 +200,26 @@ GTEST_API_ void IllegalDoDefault(const char* file, int line) {
"the variable in various places."); "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) { constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
return *base64 == 0 ? static_cast<char>(65) return *base64 == 0 ? static_cast<char>(65)
: *base64 == c ? carry : *base64 == c
: UnBase64Impl(c, base64 + 1, carry + 1); ? carry
: UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1));
} }
template <size_t... I> template <size_t... I>
constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>, constexpr std::array<char, 256> UnBase64Impl(std::index_sequence<I...>,
const char* const base64) { const char* const base64) {
return {{UnBase64Impl(static_cast<char>(I), base64, 0)...}}; return {
{UnBase64Impl(UndoWebSafeEncoding(static_cast<char>(I)), base64, 0)...}};
} }
constexpr std::array<char, 256> UnBase64(const char* const base64) { constexpr std::array<char, 256> UnBase64(const char* const base64) {
return UnBase64Impl(MakeIndexSequence<256>{}, base64); return UnBase64Impl(std::make_index_sequence<256>{}, base64);
} }
static constexpr char kBase64[] = static constexpr char kBase64[] =

View file

@ -53,7 +53,7 @@ GTEST_API_ std::string FormatMatcherDescription(
bool negation, const char* matcher_name, bool negation, const char* matcher_name,
const std::vector<const char*>& param_names, const Strings& param_values) { const std::vector<const char*>& param_names, const Strings& param_values) {
std::string result = ConvertIdentifierNameToWords(matcher_name); std::string result = ConvertIdentifierNameToWords(matcher_name);
if (param_values.size() >= 1) { if (!param_values.empty()) {
result += " " + JoinAsKeyValueTuple(param_names, param_values); result += " " + JoinAsKeyValueTuple(param_names, param_values);
} }
return negation ? "not (" + result + ")" : result; return negation ? "not (" + result + ")" : result;
@ -120,7 +120,7 @@ GTEST_API_ std::string FormatMatcherDescription(
// [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method". // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
// "Introduction to Algorithms (Second ed.)", pp. 651-664. // "Introduction to Algorithms (Second ed.)", pp. 651-664.
// [2] "Ford-Fulkerson algorithm", Wikipedia, // [2] "Ford-Fulkerson algorithm", Wikipedia,
// 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm' // 'https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
class MaxBipartiteMatchState { class MaxBipartiteMatchState {
public: public:
explicit MaxBipartiteMatchState(const MatchMatrix& graph) explicit MaxBipartiteMatchState(const MatchMatrix& graph)
@ -236,9 +236,8 @@ static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
os << "{"; os << "{";
const char* sep = ""; const char* sep = "";
for (Iter it = pairs.begin(); it != pairs.end(); ++it) { for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
os << sep << "\n (" os << sep << "\n (" << "element #" << it->first << ", " << "matcher #"
<< "element #" << it->first << ", " << it->second << ")";
<< "matcher #" << it->second << ")";
sep = ","; sep = ",";
} }
os << "\n}"; os << "\n}";
@ -370,7 +369,24 @@ void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix( bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
const ::std::vector<std::string>& element_printouts, const ::std::vector<std::string>& element_printouts,
const MatchMatrix& matrix, MatchResultListener* listener) const { const MatchMatrix& matrix, MatchResultListener* listener) const {
bool result = true; if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
return true;
}
const bool is_exact_match_with_size_discrepency =
match_flags() == UnorderedMatcherRequire::ExactMatch &&
matrix.LhsSize() != matrix.RhsSize();
if (is_exact_match_with_size_discrepency) {
// The element count doesn't match. If the container is empty,
// there's no need to explain anything as Google Mock already
// prints the empty container. Otherwise we just need to show
// how many elements there actually are.
if (matrix.LhsSize() != 0 && listener->IsInterested()) {
*listener << "which has " << Elements(matrix.LhsSize()) << "\n";
}
}
bool result = !is_exact_match_with_size_discrepency;
::std::vector<char> element_matched(matrix.LhsSize(), 0); ::std::vector<char> element_matched(matrix.LhsSize(), 0);
::std::vector<char> matcher_matched(matrix.RhsSize(), 0); ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);

View file

@ -40,6 +40,7 @@
#include <map> #include <map>
#include <memory> #include <memory>
#include <set> #include <set>
#include <sstream>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
@ -48,17 +49,17 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC #if defined(GTEST_OS_CYGWIN) || defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC)
#include <unistd.h> // NOLINT #include <unistd.h> // NOLINT
#endif #endif
#ifdef GTEST_OS_QURT
#include <qurt_event.h>
#endif
// Silence C4800 (C4800: 'int *const ': forcing value // Silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15 // to bool 'true' or 'false') for MSVC 15
#ifdef _MSC_VER #if defined(_MSC_VER) && (_MSC_VER == 1900)
#if _MSC_VER == 1900 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#pragma warning(push)
#pragma warning(disable : 4800)
#endif
#endif #endif
namespace testing { namespace testing {
@ -95,7 +96,7 @@ ExpectationBase::ExpectationBase(const char* a_file, int a_line,
action_count_checked_(false) {} action_count_checked_(false) {}
// Destructs an ExpectationBase object. // Destructs an ExpectationBase object.
ExpectationBase::~ExpectationBase() {} ExpectationBase::~ExpectationBase() = default;
// Explicitly specifies the cardinality of this expectation. Used by // Explicitly specifies the cardinality of this expectation. Used by
// the subclasses to implement the .Times() clause. // the subclasses to implement the .Times() clause.
@ -295,9 +296,9 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
"call should not happen. Do not suppress it by blindly adding " "call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. " "an EXPECT_CALL() if you don't mean to enforce the call. "
"See " "See "
"https://github.com/google/googletest/blob/master/docs/" "https://github.com/google/googletest/blob/main/docs/"
"gmock_cook_book.md#" "gmock_cook_book.md#"
"knowing-when-to-expect for details.\n", "knowing-when-to-expect-useoncall for details.\n",
stack_frames_to_skip); stack_frames_to_skip);
break; break;
default: // FAIL default: // FAIL
@ -308,7 +309,7 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
UntypedFunctionMockerBase::UntypedFunctionMockerBase() UntypedFunctionMockerBase::UntypedFunctionMockerBase()
: mock_obj_(nullptr), name_("") {} : mock_obj_(nullptr), name_("") {}
UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;
// Sets the mock object this mock method belongs to, and registers // Sets the mock object this mock method belongs to, and registers
// this information in the global mock registry. Will be called // this information in the global mock registry. Will be called
@ -406,8 +407,15 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
} else if (!untyped_expectation->IsSatisfied()) { } else if (!untyped_expectation->IsSatisfied()) {
expectations_met = false; expectations_met = false;
::std::stringstream ss; ::std::stringstream ss;
ss << "Actual function call count doesn't match "
<< untyped_expectation->source_text() << "...\n"; 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";
// No need to show the source file location of the expectation // No need to show the source file location of the expectation
// in the description, as the Expect() call that follows already // in the description, as the Expect() call that follows already
// takes care of it. // takes care of it.
@ -435,7 +443,7 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
return expectations_met; return expectations_met;
} }
CallReaction intToCallReaction(int mock_behavior) { static CallReaction intToCallReaction(int mock_behavior) {
if (mock_behavior >= kAllow && mock_behavior <= kFail) { if (mock_behavior >= kAllow && mock_behavior <= kFail) {
return static_cast<internal::CallReaction>(mock_behavior); return static_cast<internal::CallReaction>(mock_behavior);
} }
@ -482,6 +490,7 @@ class MockObjectRegistry {
// failure, unless the user explicitly asked us to ignore it. // failure, unless the user explicitly asked us to ignore it.
~MockObjectRegistry() { ~MockObjectRegistry() {
if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return; if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return;
internal::MutexLock l(&internal::g_gmock_mutex);
int leaked_count = 0; int leaked_count = 0;
for (StateMap::const_iterator it = states_.begin(); it != states_.end(); for (StateMap::const_iterator it = states_.begin(); it != states_.end();
@ -496,7 +505,7 @@ class MockObjectRegistry {
std::cout << internal::FormatFileLocation(state.first_used_file, std::cout << internal::FormatFileLocation(state.first_used_file,
state.first_used_line); state.first_used_line);
std::cout << " ERROR: this mock object"; std::cout << " ERROR: this mock object";
if (state.first_used_test != "") { if (!state.first_used_test.empty()) {
std::cout << " (used in test " << state.first_used_test_suite << "." std::cout << " (used in test " << state.first_used_test_suite << "."
<< state.first_used_test << ")"; << state.first_used_test << ")";
} }
@ -519,8 +528,12 @@ class MockObjectRegistry {
// RUN_ALL_TESTS() has already returned when this destructor is // RUN_ALL_TESTS() has already returned when this destructor is
// called. Therefore we cannot use the normal Google Test // called. Therefore we cannot use the normal Google Test
// failure reporting mechanism. // failure reporting mechanism.
_exit(1); // We cannot call exit() as it is not reentrant and #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. // may already have been called.
#endif
} }
} }
@ -734,13 +747,13 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj)
// needed by VerifyAndClearExpectationsLocked(). // needed by VerifyAndClearExpectationsLocked().
} }
Expectation::Expectation() {} Expectation::Expectation() = default;
Expectation::Expectation( Expectation::Expectation(
const std::shared_ptr<internal::ExpectationBase>& an_expectation_base) const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
: expectation_base_(an_expectation_base) {} : expectation_base_(an_expectation_base) {}
Expectation::~Expectation() {} Expectation::~Expectation() = default;
// Adds an expectation to a sequence. // Adds an expectation to a sequence.
void Sequence::AddExpectation(const Expectation& expectation) const { void Sequence::AddExpectation(const Expectation& expectation) const {
@ -774,8 +787,6 @@ InSequence::~InSequence() {
} // namespace testing } // namespace testing
#ifdef _MSC_VER #if defined(_MSC_VER) && (_MSC_VER == 1900)
#if _MSC_VER == 1900 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#pragma warning(pop)
#endif
#endif #endif

View file

@ -29,6 +29,8 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include <string>
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
GMOCK_DEFINE_bool_(catch_leaked_mocks, true, GMOCK_DEFINE_bool_(catch_leaked_mocks, true,

View file

@ -32,8 +32,9 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_ESP8266 || GTEST_OS_ESP32 #if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) || \
#if GTEST_OS_ESP8266 (defined(GTEST_OS_NRF52) && defined(ARDUINO))
#ifdef GTEST_OS_ESP8266
extern "C" { extern "C" {
#endif #endif
void setup() { void setup() {
@ -43,7 +44,7 @@ void setup() {
testing::InitGoogleMock(); testing::InitGoogleMock();
} }
void loop() { RUN_ALL_TESTS(); } void loop() { RUN_ALL_TESTS(); }
#if GTEST_OS_ESP8266 #ifdef GTEST_OS_ESP8266
} }
#endif #endif
@ -55,7 +56,7 @@ void loop() { RUN_ALL_TESTS(); }
// Windows. See the following link to track the current status of this bug: // 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 // https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library
// // NOLINT // // NOLINT
#if GTEST_OS_WINDOWS_MOBILE #ifdef GTEST_OS_WINDOWS_MOBILE
#include <tchar.h> // NOLINT #include <tchar.h> // NOLINT
GTEST_API_ int _tmain(int argc, TCHAR** argv) { GTEST_API_ int _tmain(int argc, TCHAR** argv) {

View file

@ -31,33 +31,33 @@
// //
// This file tests the built-in actions. // 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 "gmock/gmock-actions.h"
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
#include <iterator> #include <iterator>
#include <memory> #include <memory>
#include <sstream>
#include <string> #include <string>
#include <tuple>
#include <type_traits> #include <type_traits>
#include <utility>
#include <vector> #include <vector>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.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 testing {
namespace { namespace {
@ -222,7 +222,8 @@ TEST(TypeTraits, IsInvocableRV) {
// In C++17 and above, where it's guaranteed that functions can return // In C++17 and above, where it's guaranteed that functions can return
// non-moveable objects, everything should work fine for non-moveable rsult // non-moveable objects, everything should work fine for non-moveable rsult
// types too. // types too.
#if defined(__cplusplus) && __cplusplus >= 201703L #if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
{ {
struct NonMoveable { struct NonMoveable {
NonMoveable() = default; NonMoveable() = default;
@ -440,15 +441,15 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_EQ(0, DefaultValue<int>::Get()); EXPECT_EQ(0, DefaultValue<int>::Get());
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, EXPECT_DEATH_IF_SUPPORTED(
""); { DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
} }
TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
DefaultValue<std::unique_ptr<int>>::SetFactory( DefaultValue<std::unique_ptr<int>>::SetFactory(
[] { return std::unique_ptr<int>(new int(42)); }); [] { return std::make_unique<int>(42); });
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get(); std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
EXPECT_EQ(42, *i); EXPECT_EQ(42, *i);
@ -466,7 +467,7 @@ TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
} }
// Tests that DefaultValue<T&>::Exists is false initiallly. // Tests that DefaultValue<T&>::Exists is false initially.
TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) { TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
EXPECT_FALSE(DefaultValue<int&>::Exists()); EXPECT_FALSE(DefaultValue<int&>::Exists());
EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
@ -504,8 +505,8 @@ TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, ""); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, EXPECT_DEATH_IF_SUPPORTED(
""); { DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
} }
// Tests that ActionInterface can be implemented by defining the // Tests that ActionInterface can be implemented by defining the
@ -684,7 +685,7 @@ TEST(ReturnTest, SupportsReferenceLikeReturnType) {
// A reference wrapper for std::vector<int>, implicitly convertible from it. // A reference wrapper for std::vector<int>, implicitly convertible from it.
struct Result { struct Result {
const std::vector<int>* v; const std::vector<int>* v;
Result(const std::vector<int>& v) : v(&v) {} // NOLINT Result(const std::vector<int>& vec) : v(&vec) {} // NOLINT
}; };
// Set up an action for a mock function that returns the reference wrapper // Set up an action for a mock function that returns the reference wrapper
@ -717,7 +718,7 @@ TEST(ReturnTest, PrefersConversionOperator) {
struct Out { struct Out {
int x; int x;
explicit Out(const int x) : x(x) {} explicit Out(const int val) : x(val) {}
explicit Out(const In&) : x(0) {} explicit Out(const In&) : x(0) {}
}; };
@ -807,7 +808,7 @@ TEST(ReturnTest, MoveOnlyResultType) {
""); "");
} }
// Tests that Return(v) is covaraint. // Tests that Return(v) is covariant.
struct Base { struct Base {
bool operator==(const Base&) { return true; } bool operator==(const Base&) { return true; }
@ -986,7 +987,7 @@ TEST(ReturnRoundRobinTest, WorksForVector) {
class MockClass { class MockClass {
public: public:
MockClass() {} MockClass() = default;
MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
MOCK_METHOD0(Foo, MyNonDefaultConstructible()); MOCK_METHOD0(Foo, MyNonDefaultConstructible());
@ -1476,6 +1477,54 @@ TEST(DoAll, SupportsTypeErasedActions) {
} }
} }
// A DoAll action should be convertible to a OnceAction, even when its component
// sub-actions are user-provided types that define only an Action conversion
// operator. If they supposed being called more than once then they also support
// being called at most once.
TEST(DoAll, ConvertibleToOnceActionWithUserProvidedActionConversion) {
// Simplest case: only one sub-action.
struct CustomFinal final {
operator Action<int()>() { // NOLINT
return Return(17);
}
operator Action<int(int, char)>() { // NOLINT
return Return(19);
}
};
{
OnceAction<int()> action = DoAll(CustomFinal{});
EXPECT_EQ(17, std::move(action).Call());
}
{
OnceAction<int(int, char)> action = DoAll(CustomFinal{});
EXPECT_EQ(19, std::move(action).Call(0, 0));
}
// It should also work with multiple sub-actions.
struct CustomInitial final {
operator Action<void()>() { // NOLINT
return [] {};
}
operator Action<void(int, char)>() { // NOLINT
return [] {};
}
};
{
OnceAction<int()> action = DoAll(CustomInitial{}, CustomFinal{});
EXPECT_EQ(17, std::move(action).Call());
}
{
OnceAction<int(int, char)> action = DoAll(CustomInitial{}, CustomFinal{});
EXPECT_EQ(19, std::move(action).Call(0, 0));
}
}
// Tests using WithArgs and with an action that takes 1 argument. // Tests using WithArgs and with an action that takes 1 argument.
TEST(WithArgsTest, OneArg) { TEST(WithArgsTest, OneArg) {
Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT
@ -1596,7 +1645,7 @@ TEST(WithArgsTest, RefQualifiedInnerAction) {
EXPECT_EQ(19, mock.AsStdFunction()(0, 17)); EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
} }
#if !GTEST_OS_WINDOWS_MOBILE #ifndef GTEST_OS_WINDOWS_MOBILE
class SetErrnoAndReturnTest : public testing::Test { class SetErrnoAndReturnTest : public testing::Test {
protected: protected:
@ -1755,9 +1804,7 @@ TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
delete c; delete c;
} }
std::unique_ptr<int> UniquePtrSource() { std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); }
return std::unique_ptr<int>(new int(19));
}
std::vector<std::unique_ptr<int>> VectorUniquePtrSource() { std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
std::vector<std::unique_ptr<int>> out; std::vector<std::unique_ptr<int>> out;
@ -1806,7 +1853,7 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
// Check default value // Check default value
DefaultValue<std::unique_ptr<int>>::SetFactory( DefaultValue<std::unique_ptr<int>>::SetFactory(
[] { return std::unique_ptr<int>(new int(42)); }); [] { return std::make_unique<int>(42); });
EXPECT_EQ(42, *mock.MakeUnique()); EXPECT_EQ(42, *mock.MakeUnique());
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource)); EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
@ -1826,7 +1873,7 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
TEST(MockMethodTest, CanTakeMoveOnlyValue) { TEST(MockMethodTest, CanTakeMoveOnlyValue) {
MockClass mock; MockClass mock;
auto make = [](int i) { return std::unique_ptr<int>(new int(i)); }; auto make = [](int i) { return std::make_unique<int>(i); };
EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) { EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
return *i; return *i;
@ -2057,9 +2104,7 @@ struct Double {
} }
}; };
std::unique_ptr<int> UniqueInt(int i) { std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); }
return std::unique_ptr<int>(new int(i));
}
TEST(FunctorActionTest, ActionFromFunction) { TEST(FunctorActionTest, ActionFromFunction) {
Action<int(int, int&, int*)> a = &Add; Action<int(int, int&, int*)> a = &Add;
@ -2165,3 +2210,8 @@ TEST(ActionMacro, LargeArity) {
} // namespace } // namespace
} // namespace testing } // namespace testing
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#endif
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503

View file

@ -31,6 +31,8 @@
// //
// This file tests the built-in cardinalities. // This file tests the built-in cardinalities.
#include <ostream>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
@ -50,7 +52,7 @@ using testing::MakeCardinality;
class MockFoo { class MockFoo {
public: public:
MockFoo() {} MockFoo() = default;
MOCK_METHOD0(Bar, int()); // NOLINT MOCK_METHOD0(Bar, int()); // NOLINT
private: private:

View file

@ -27,18 +27,15 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // 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. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the function mocker classes. // This file tests the function mocker classes.
#include "gmock/gmock-function-mocker.h" #include "gmock/gmock-function-mocker.h"
#if GTEST_OS_WINDOWS // Silence C4503 (decorated name length exceeded) for MSVC.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4503)
#ifdef GTEST_OS_WINDOWS
// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but // 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 // we are getting compiler errors if we use basetyps.h, hence including
// objbase.h for definition of STDMETHOD. // objbase.h for definition of STDMETHOD.
@ -73,7 +70,7 @@ using testing::TypedEq;
template <typename T> template <typename T>
class TemplatedCopyable { class TemplatedCopyable {
public: public:
TemplatedCopyable() {} TemplatedCopyable() = default;
template <typename U> template <typename U>
TemplatedCopyable(const U& other) {} // NOLINT TemplatedCopyable(const U& other) {} // NOLINT
@ -81,7 +78,7 @@ class TemplatedCopyable {
class FooInterface { class FooInterface {
public: public:
virtual ~FooInterface() {} virtual ~FooInterface() = default;
virtual void VoidReturning(int x) = 0; virtual void VoidReturning(int x) = 0;
@ -123,7 +120,7 @@ class FooInterface {
virtual int RefQualifiedOverloaded() & = 0; virtual int RefQualifiedOverloaded() & = 0;
virtual int RefQualifiedOverloaded() && = 0; virtual int RefQualifiedOverloaded() && = 0;
#if GTEST_OS_WINDOWS #ifdef GTEST_OS_WINDOWS
STDMETHOD_(int, CTNullary)() = 0; STDMETHOD_(int, CTNullary)() = 0;
STDMETHOD_(bool, CTUnary)(int x) = 0; STDMETHOD_(bool, CTUnary)(int x) = 0;
STDMETHOD_(int, CTDecimal) STDMETHOD_(int, CTDecimal)
@ -137,13 +134,10 @@ class FooInterface {
// significant in determining whether two virtual functions had the same // significant in determining whether two virtual functions had the same
// signature. This was fixed in Visual Studio 2008. However, the compiler // signature. This was fixed in Visual Studio 2008. However, the compiler
// still emits a warning that alerts about this change in behavior. // still emits a warning that alerts about this change in behavior.
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4373)
#pragma warning(push)
#pragma warning(disable : 4373)
#endif
class MockFoo : public FooInterface { class MockFoo : public FooInterface {
public: public:
MockFoo() {} MockFoo() = default;
// Makes sure that a mock function parameter can be named. // Makes sure that a mock function parameter can be named.
MOCK_METHOD(void, VoidReturning, (int n)); // NOLINT MOCK_METHOD(void, VoidReturning, (int n)); // NOLINT
@ -184,7 +178,7 @@ class MockFoo : public FooInterface {
MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ()); MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ());
MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ()); MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ());
#if GTEST_OS_WINDOWS #ifdef GTEST_OS_WINDOWS
MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE))); MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE))); MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(int, CTDecimal, MOCK_METHOD(int, CTDecimal,
@ -214,7 +208,7 @@ class MockFoo : public FooInterface {
class LegacyMockFoo : public FooInterface { class LegacyMockFoo : public FooInterface {
public: public:
LegacyMockFoo() {} LegacyMockFoo() = default;
// Makes sure that a mock function parameter can be named. // Makes sure that a mock function parameter can be named.
MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
@ -254,7 +248,7 @@ class LegacyMockFoo : public FooInterface {
MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool)); MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool));
MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int)); MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int));
#if GTEST_OS_WINDOWS #ifdef GTEST_OS_WINDOWS
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int()); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); // NOLINT MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); // NOLINT
MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
@ -285,9 +279,7 @@ class LegacyMockFoo : public FooInterface {
LegacyMockFoo& operator=(const LegacyMockFoo&) = delete; LegacyMockFoo& operator=(const LegacyMockFoo&) = delete;
}; };
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4373
#pragma warning(pop)
#endif
template <class T> template <class T>
class FunctionMockerTest : public testing::Test { class FunctionMockerTest : public testing::Test {
@ -333,8 +325,8 @@ TYPED_TEST(FunctionMockerTest, MocksBinaryFunction) {
// Tests mocking a decimal function. // Tests mocking a decimal function.
TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) { TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(this->mock_foo_, EXPECT_CALL(this->mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100),
Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi")) 5U, nullptr, "hi"))
.WillOnce(Return(5)); .WillOnce(Return(5));
EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
@ -412,7 +404,7 @@ TYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>())); EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
} }
#if GTEST_OS_WINDOWS #ifdef GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype. // Tests mocking a nullary function with calltype.
TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) { TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
EXPECT_CALL(this->mock_foo_, CTNullary()) EXPECT_CALL(this->mock_foo_, CTNullary())
@ -495,7 +487,7 @@ TEST(FunctionMockerTest, RefQualified) {
class MockB { class MockB {
public: public:
MockB() {} MockB() = default;
MOCK_METHOD(void, DoB, ()); MOCK_METHOD(void, DoB, ());
@ -506,7 +498,7 @@ class MockB {
class LegacyMockB { class LegacyMockB {
public: public:
LegacyMockB() {} LegacyMockB() = default;
MOCK_METHOD0(DoB, void()); MOCK_METHOD0(DoB, void());
@ -542,7 +534,7 @@ TYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
template <typename T> template <typename T>
class StackInterface { class StackInterface {
public: public:
virtual ~StackInterface() {} virtual ~StackInterface() = default;
// Template parameter appears in function parameter. // Template parameter appears in function parameter.
virtual void Push(const T& value) = 0; virtual void Push(const T& value) = 0;
@ -555,7 +547,7 @@ class StackInterface {
template <typename T> template <typename T>
class MockStack : public StackInterface<T> { class MockStack : public StackInterface<T> {
public: public:
MockStack() {} MockStack() = default;
MOCK_METHOD(void, Push, (const T& elem), ()); MOCK_METHOD(void, Push, (const T& elem), ());
MOCK_METHOD(void, Pop, (), (final)); MOCK_METHOD(void, Pop, (), (final));
@ -574,7 +566,7 @@ class MockStack : public StackInterface<T> {
template <typename T> template <typename T>
class LegacyMockStack : public StackInterface<T> { class LegacyMockStack : public StackInterface<T> {
public: public:
LegacyMockStack() {} LegacyMockStack() = default;
MOCK_METHOD1_T(Push, void(const T& elem)); MOCK_METHOD1_T(Push, void(const T& elem));
MOCK_METHOD0_T(Pop, void()); MOCK_METHOD0_T(Pop, void());
@ -628,7 +620,7 @@ TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1)); EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
} }
#if GTEST_OS_WINDOWS #ifdef GTEST_OS_WINDOWS
// Tests mocking template interfaces with calltype. // Tests mocking template interfaces with calltype.
template <typename T> template <typename T>
@ -719,7 +711,7 @@ TYPED_TEST(TemplateMockTestWithCallType, Works) {
class MockOverloadedOnArgNumber { class MockOverloadedOnArgNumber {
public: public:
MockOverloadedOnArgNumber() {} MockOverloadedOnArgNumber() = default;
MY_MOCK_METHODS1_; MY_MOCK_METHODS1_;
@ -731,7 +723,7 @@ class MockOverloadedOnArgNumber {
class LegacyMockOverloadedOnArgNumber { class LegacyMockOverloadedOnArgNumber {
public: public:
LegacyMockOverloadedOnArgNumber() {} LegacyMockOverloadedOnArgNumber() = default;
LEGACY_MY_MOCK_METHODS1_; LEGACY_MY_MOCK_METHODS1_;
@ -766,7 +758,7 @@ TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
class MockOverloadedOnConstness { class MockOverloadedOnConstness {
public: public:
MockOverloadedOnConstness() {} MockOverloadedOnConstness() = default;
MY_MOCK_METHODS2_; MY_MOCK_METHODS2_;
@ -958,6 +950,21 @@ TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(MockMethodSizes0)); 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 hasTwoParams(int, int);
void MaybeThrows(); void MaybeThrows();
void DoesntThrow() noexcept; void DoesntThrow() noexcept;
@ -987,3 +994,5 @@ TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) {
} // namespace gmock_function_mocker_test } // namespace gmock_function_mocker_test
} // namespace testing } // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4503

View file

@ -40,6 +40,7 @@
#include <memory> #include <memory>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <tuple>
#include <vector> #include <vector>
#include "gmock/gmock.h" #include "gmock/gmock.h"
@ -56,7 +57,7 @@
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION_ #undef GTEST_IMPLEMENTATION_
#if GTEST_OS_CYGWIN #ifdef GTEST_OS_CYGWIN
#include <sys/types.h> // For ssize_t. NOLINT #include <sys/types.h> // For ssize_t. NOLINT
#endif #endif
@ -167,7 +168,7 @@ TEST(KindOfTest, Integer) {
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); // NOLINT 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_(wchar_t)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT
#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN #if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || defined(GTEST_OS_CYGWIN)
// ssize_t is not defined on Windows and possibly some other OSes. // ssize_t is not defined on Windows and possibly some other OSes.
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT
#endif #endif

View file

@ -31,15 +31,18 @@
// //
// This file tests some commonly used argument matchers. // This file tests some commonly used argument matchers.
#include <cmath>
#include <limits>
#include <memory>
#include <string>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short', // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter // possible loss of data and C4100, unreferenced local parameter
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing { namespace testing {
namespace gmock_matchers_test { namespace gmock_matchers_test {
@ -558,10 +561,9 @@ TEST_P(AllOfTestP, ExplainsResult) {
Matcher<int> m; Matcher<int> m;
// Successful match. Both matchers need to explain. The second // Successful match. Both matchers need to explain. The second
// matcher doesn't give an explanation, so only the first matcher's // matcher doesn't give an explanation, so the matcher description is used.
// explanation is printed.
m = AllOf(GreaterThan(10), Lt(30)); m = AllOf(GreaterThan(10), Lt(30));
EXPECT_EQ("which is 15 more than 10", Explain(m, 25)); EXPECT_EQ("which is 15 more than 10, and is < 30", Explain(m, 25));
// Successful match. Both matchers need to explain. // Successful match. Both matchers need to explain.
m = AllOf(GreaterThan(10), GreaterThan(20)); m = AllOf(GreaterThan(10), GreaterThan(20));
@ -571,7 +573,8 @@ TEST_P(AllOfTestP, ExplainsResult) {
// Successful match. All matchers need to explain. The second // Successful match. All matchers need to explain. The second
// matcher doesn't given an explanation. // matcher doesn't given an explanation.
m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20)); m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20", EXPECT_EQ(
"which is 15 more than 10, and is < 30, and which is 5 more than 20",
Explain(m, 25)); Explain(m, 25));
// Successful match. All matchers need to explain. // Successful match. All matchers need to explain.
@ -587,10 +590,10 @@ TEST_P(AllOfTestP, ExplainsResult) {
EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
// Failed match. The second matcher, which failed, needs to // Failed match. The second matcher, which failed, needs to
// explain. Since it doesn't given an explanation, nothing is // explain. Since it doesn't given an explanation, the matcher text is
// printed. // printed.
m = AllOf(GreaterThan(10), Lt(30)); m = AllOf(GreaterThan(10), Lt(30));
EXPECT_EQ("", Explain(m, 40)); EXPECT_EQ("which doesn't match (is < 30)", Explain(m, 40));
// Failed match. The second matcher, which failed, needs to // Failed match. The second matcher, which failed, needs to
// explain. // explain.
@ -773,45 +776,43 @@ TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
TEST_P(AnyOfTestP, ExplainsResult) { TEST_P(AnyOfTestP, ExplainsResult) {
Matcher<int> m; Matcher<int> m;
// Failed match. Both matchers need to explain. The second // Failed match. The second matcher have no explanation (description is used).
// matcher doesn't give an explanation, so only the first matcher's
// explanation is printed.
m = AnyOf(GreaterThan(10), Lt(0)); m = AnyOf(GreaterThan(10), Lt(0));
EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); EXPECT_EQ("which is 5 less than 10, and isn't < 0", Explain(m, 5));
// Failed match. Both matchers need to explain. // Failed match. Both matchers have explanations.
m = AnyOf(GreaterThan(10), GreaterThan(20)); m = AnyOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20", EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
Explain(m, 5)); Explain(m, 5));
// Failed match. All matchers need to explain. The second // Failed match. The middle matcher have no explanation.
// matcher doesn't given an explanation.
m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30)); m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30", EXPECT_EQ(
"which is 5 less than 10, and isn't > 20, and which is 25 less than 30",
Explain(m, 5)); Explain(m, 5));
// Failed match. All matchers need to explain. // Failed match. All three matchers have explanations.
m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
EXPECT_EQ( EXPECT_EQ(
"which is 5 less than 10, and which is 15 less than 20, " "which is 5 less than 10, and which is 15 less than 20, "
"and which is 25 less than 30", "and which is 25 less than 30",
Explain(m, 5)); Explain(m, 5));
// Successful match. The first matcher, which succeeded, needs to // Successful match. The first macher succeeded and has explanation.
// explain.
m = AnyOf(GreaterThan(10), GreaterThan(20)); m = AnyOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 more than 10", Explain(m, 15)); EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
// Successful match. The second matcher, which succeeded, needs to // Successful match. The second matcher succeeded and has explanation.
// explain. Since it doesn't given an explanation, nothing is
// printed.
m = AnyOf(GreaterThan(10), Lt(30));
EXPECT_EQ("", Explain(m, 0));
// Successful match. The second matcher, which succeeded, needs to
// explain.
m = AnyOf(GreaterThan(30), GreaterThan(20)); m = AnyOf(GreaterThan(30), GreaterThan(20));
EXPECT_EQ("which is 5 more than 20", Explain(m, 25)); EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
// Successful match. The first matcher succeeded and has no explanation.
m = AnyOf(Gt(10), Lt(20));
EXPECT_EQ("which matches (is > 10)", Explain(m, 15));
// Successful match. The second matcher succeeded and has no explanation.
m = AnyOf(Gt(30), Gt(20));
EXPECT_EQ("which matches (is > 20)", Explain(m, 25));
} }
// The following predicate function and predicate functor are for // The following predicate function and predicate functor are for
@ -954,7 +955,7 @@ TEST(AllArgsTest, WorksForNonTuple) {
class AllArgsHelper { class AllArgsHelper {
public: public:
AllArgsHelper() {} AllArgsHelper() = default;
MOCK_METHOD2(Helper, int(char x, int y)); MOCK_METHOD2(Helper, int(char x, int y));
@ -975,7 +976,7 @@ TEST(AllArgsTest, WorksInWithClause) {
class OptionalMatchersHelper { class OptionalMatchersHelper {
public: public:
OptionalMatchersHelper() {} OptionalMatchersHelper() = default;
MOCK_METHOD0(NoArgs, int()); MOCK_METHOD0(NoArgs, int());
@ -1037,7 +1038,7 @@ class FloatingPointTest : public testing::Test {
Floating::ReinterpretBits(infinity_bits_ - max_ulps_)), Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
further_from_infinity_( further_from_infinity_(
Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
max_(Floating::Max()), max_(std::numeric_limits<RawType>::max()),
nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {} nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {}
@ -1512,6 +1513,4 @@ TEST(AnyOfTest, WorksOnMoveOnlyType) {
} // namespace gmock_matchers_test } // namespace gmock_matchers_test
} // namespace testing } // namespace testing
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#pragma warning(pop)
#endif

View file

@ -31,15 +31,19 @@
// //
// This file tests some commonly used argument matchers. // This file tests some commonly used argument matchers.
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short', // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter // possible loss of data and C4100, unreferenced local parameter
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing { namespace testing {
namespace gmock_matchers_test { namespace gmock_matchers_test {
@ -407,9 +411,27 @@ class IntValue {
int value_; int value_;
}; };
// For testing casting matchers between compatible types. This is similar to
// IntValue, but takes a non-const reference to the value, showing MatcherCast
// works with such types (and doesn't, for example, use a const ref internally).
class MutableIntView {
public:
// An int& can be statically (although not implicitly) cast to a
// MutableIntView.
explicit MutableIntView(int& a_value) : value_(a_value) {}
int& value() const { return value_; }
private:
int& value_;
};
// For testing casting matchers between compatible types. // For testing casting matchers between compatible types.
bool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; } bool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; }
// For testing casting matchers between compatible types.
bool IsPositiveMutableIntView(MutableIntView foo) { return foo.value() > 0; }
// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
// can be statically converted to U. // can be statically converted to U.
TEST(MatcherCastTest, FromCompatibleType) { TEST(MatcherCastTest, FromCompatibleType) {
@ -425,14 +447,34 @@ TEST(MatcherCastTest, FromCompatibleType) {
// predicate. // predicate.
EXPECT_TRUE(m4.Matches(1)); EXPECT_TRUE(m4.Matches(1));
EXPECT_FALSE(m4.Matches(0)); EXPECT_FALSE(m4.Matches(0));
Matcher<MutableIntView> m5 = Truly(IsPositiveMutableIntView);
Matcher<int> m6 = MatcherCast<int>(m5);
// In the following, the arguments 1 and 0 are statically converted to
// MutableIntView objects, and then tested by the IsPositiveMutableIntView()
// predicate.
EXPECT_TRUE(m6.Matches(1));
EXPECT_FALSE(m6.Matches(0));
} }
// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>. // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest, FromConstReferenceToNonReference) { TEST(MatcherCastTest, FromConstReferenceToNonReference) {
Matcher<const int&> m1 = Eq(0); int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<int> m2 = MatcherCast<int>(m1); Matcher<int> m2 = MatcherCast<int>(m1);
EXPECT_TRUE(m2.Matches(0)); int n1 = 0;
EXPECT_FALSE(m2.Matches(1)); EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
}
// Tests that MatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest, FromConstReferenceToReference) {
int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<int&> m2 = MatcherCast<int&>(m1);
int n1 = 0;
EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
} }
// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>. // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
@ -441,6 +483,12 @@ TEST(MatcherCastTest, FromReferenceToNonReference) {
Matcher<int> m2 = MatcherCast<int>(m1); Matcher<int> m2 = MatcherCast<int>(m1);
EXPECT_TRUE(m2.Matches(0)); EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1)); EXPECT_FALSE(m2.Matches(1));
// Of course, reference identity isn't preserved since a copy is required.
int n = 0;
Matcher<int&> m3 = Ref(n);
Matcher<int> m4 = MatcherCast<int>(m3);
EXPECT_FALSE(m4.Matches(n));
} }
// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
@ -586,8 +634,8 @@ TEST(MatcherCastTest, ValueIsNotCopied) {
class Base { class Base {
public: public:
virtual ~Base() {} virtual ~Base() = default;
Base() {} Base() = default;
private: private:
Base(const Base&) = delete; Base(const Base&) = delete;
@ -645,6 +693,16 @@ TEST(SafeMatcherCastTest, FromBaseClass) {
EXPECT_FALSE(m4.Matches(d2)); EXPECT_FALSE(m4.Matches(d2));
} }
// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest, FromConstReferenceToNonReference) {
int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<int> m2 = SafeMatcherCast<int>(m1);
int n1 = 0;
EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
}
// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest, FromConstReferenceToReference) { TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
int n = 0; int n = 0;
@ -862,7 +920,7 @@ struct Type {
}; };
TEST(TypedEqTest, HasSpecifiedType) { TEST(TypedEqTest, HasSpecifiedType) {
// Verfies that the type of TypedEq<T>(v) is Matcher<T>. // Verifies that the type of TypedEq<T>(v) is Matcher<T>.
Type<Matcher<int>>::IsTypeOf(TypedEq<int>(5)); Type<Matcher<int>>::IsTypeOf(TypedEq<int>(5));
Type<Matcher<double>>::IsTypeOf(TypedEq<double>(5)); Type<Matcher<double>>::IsTypeOf(TypedEq<double>(5));
} }
@ -983,6 +1041,30 @@ TEST(ComparisonBaseTest, WorksWithMoveOnly) {
helper.Call(MoveOnly(1)); 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. // Tests that IsNull() matches any NULL pointer of any type.
TEST(IsNullTest, MatchesNullPointer) { TEST(IsNullTest, MatchesNullPointer) {
Matcher<int*> m1 = IsNull(); Matcher<int*> m1 = IsNull();
@ -1504,7 +1586,7 @@ TEST(PairTest, MatchesCorrectly) {
EXPECT_THAT(p, Pair(25, "foo")); EXPECT_THAT(p, Pair(25, "foo"));
EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o"))); EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
// 'first' doesnt' match, but 'second' matches. // 'first' doesn't match, but 'second' matches.
EXPECT_THAT(p, Not(Pair(42, "foo"))); EXPECT_THAT(p, Not(Pair(42, "foo")));
EXPECT_THAT(p, Not(Pair(Lt(25), "foo"))); EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
@ -1519,7 +1601,7 @@ TEST(PairTest, MatchesCorrectly) {
TEST(PairTest, WorksWithMoveOnly) { TEST(PairTest, WorksWithMoveOnly) {
pair<std::unique_ptr<int>, std::unique_ptr<int>> p; pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
p.second.reset(new int(7)); p.second = std::make_unique<int>(7);
EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr))); EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
} }
@ -1684,6 +1766,21 @@ TEST(FieldsAreTest, StructuredBindings) {
}; };
EXPECT_THAT(MyVarType16{}, EXPECT_THAT(MyVarType16{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); 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 #endif
@ -1727,6 +1824,15 @@ TEST(StartsWithTest, CanDescribeSelf) {
EXPECT_EQ("starts with \"Hi\"", Describe(m)); EXPECT_EQ("starts with \"Hi\"", Describe(m));
} }
TEST(StartsWithTest, WorksWithStringMatcherOnStringViewMatchee) {
#if GTEST_INTERNAL_HAS_STRING_VIEW
EXPECT_THAT(internal::StringView("talk to me goose"),
StartsWith(std::string("talk")));
#else
GTEST_SKIP() << "Not applicable without internal::StringView.";
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
// Tests EndsWith(s). // Tests EndsWith(s).
TEST(EndsWithTest, MatchesStringWithGivenSuffix) { TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
@ -1764,11 +1870,13 @@ TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {
EXPECT_FALSE(m1.Matches("invalid base64")); EXPECT_FALSE(m1.Matches("invalid base64"));
EXPECT_FALSE(m1.Matches("aGVsbG8gd29ybGQ=")); // hello world EXPECT_FALSE(m1.Matches("aGVsbG8gd29ybGQ=")); // hello world
EXPECT_TRUE(m1.Matches("aGVsbG8gd29ybGQh")); // 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("!")); const Matcher<const std::string&> m2 = WhenBase64Unescaped(EndsWith("!"));
EXPECT_FALSE(m2.Matches("invalid base64")); EXPECT_FALSE(m2.Matches("invalid base64"));
EXPECT_FALSE(m2.Matches("aGVsbG8gd29ybGQ=")); // hello world EXPECT_FALSE(m2.Matches("aGVsbG8gd29ybGQ=")); // hello world
EXPECT_TRUE(m2.Matches("aGVsbG8gd29ybGQh")); // hello world! EXPECT_TRUE(m2.Matches("aGVsbG8gd29ybGQh")); // hello world!
EXPECT_TRUE(m2.Matches("+/-_IQ")); // \xfb\xff\xbf!
#if GTEST_INTERNAL_HAS_STRING_VIEW #if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<const internal::StringView&> m3 = const Matcher<const internal::StringView&> m3 =
@ -1776,6 +1884,7 @@ TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {
EXPECT_FALSE(m3.Matches("invalid base64")); EXPECT_FALSE(m3.Matches("invalid base64"));
EXPECT_FALSE(m3.Matches("aGVsbG8gd29ybGQ=")); // hello world EXPECT_FALSE(m3.Matches("aGVsbG8gd29ybGQ=")); // hello world
EXPECT_TRUE(m3.Matches("aGVsbG8gd29ybGQh")); // hello world! EXPECT_TRUE(m3.Matches("aGVsbG8gd29ybGQh")); // hello world!
EXPECT_TRUE(m3.Matches("+/-_IQ")); // \xfb\xff\xbf!
#endif // GTEST_INTERNAL_HAS_STRING_VIEW #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
@ -2280,9 +2389,11 @@ TEST(ExplainMatchResultTest, AllOf_True_True) {
EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6)); EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
} }
// Tests that when AllOf() succeeds, but matchers have no explanation,
// the matcher description is used.
TEST(ExplainMatchResultTest, AllOf_True_True_2) { TEST(ExplainMatchResultTest, AllOf_True_True_2) {
const Matcher<int> m = AllOf(Ge(2), Le(3)); const Matcher<int> m = AllOf(Ge(2), Le(3));
EXPECT_EQ("", Explain(m, 2)); EXPECT_EQ("is >= 2, and is <= 3", Explain(m, 2));
} }
INSTANTIATE_GTEST_MATCHER_TEST_P(ExplainmatcherResultTest); INSTANTIATE_GTEST_MATCHER_TEST_P(ExplainmatcherResultTest);
@ -2313,6 +2424,4 @@ TEST(PolymorphicMatcherTest, CanAccessImpl) {
} // namespace gmock_matchers_test } // namespace gmock_matchers_test
} // namespace testing } // namespace testing
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#pragma warning(pop)
#endif

View file

@ -31,15 +31,25 @@
// //
// This file tests some commonly used argument matchers. // 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 "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short', // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter // possible loss of data and C4100, unreferenced local parameter
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing { namespace testing {
namespace gmock_matchers_test { namespace gmock_matchers_test {
@ -1182,8 +1192,8 @@ TEST(SizeIsTest, WorksWithMinimalistCustomType) {
TEST(SizeIsTest, CanDescribeSelf) { TEST(SizeIsTest, CanDescribeSelf) {
Matcher<vector<int>> m = SizeIs(2); Matcher<vector<int>> m = SizeIs(2);
EXPECT_EQ("size is equal to 2", Describe(m)); EXPECT_EQ("has a size that is equal to 2", Describe(m));
EXPECT_EQ("size isn't equal to 2", DescribeNegation(m)); EXPECT_EQ("has a size that isn't equal to 2", DescribeNegation(m));
} }
TEST(SizeIsTest, ExplainsResult) { TEST(SizeIsTest, ExplainsResult) {
@ -1194,13 +1204,16 @@ TEST(SizeIsTest, ExplainsResult) {
vector<int> container; vector<int> container;
EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container)); EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
EXPECT_EQ("whose size 0 matches", Explain(m2, container)); EXPECT_EQ("whose size 0 matches", Explain(m2, container));
EXPECT_EQ("whose size 0 matches", Explain(m3, container)); EXPECT_EQ("whose size 0 matches, which matches (is equal to 0)",
Explain(m3, container));
EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container)); EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
container.push_back(0); container.push_back(0);
container.push_back(0); container.push_back(0);
EXPECT_EQ("whose size 2 matches", Explain(m1, container)); EXPECT_EQ("whose size 2 matches", Explain(m1, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container)); EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container)); EXPECT_EQ(
"whose size 2 doesn't match, isn't equal to 0, and isn't equal to 3",
Explain(m3, container));
EXPECT_EQ("whose size 2 matches", Explain(m4, container)); EXPECT_EQ("whose size 2 matches", Explain(m4, container));
} }
@ -1465,7 +1478,9 @@ TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
Explain(m1, container)); Explain(m1, container));
EXPECT_EQ("whose distance between begin() and end() 0 matches", EXPECT_EQ("whose distance between begin() and end() 0 matches",
Explain(m2, container)); Explain(m2, container));
EXPECT_EQ("whose distance between begin() and end() 0 matches", EXPECT_EQ(
"whose distance between begin() and end() 0 matches, which matches (is "
"equal to 0)",
Explain(m3, container)); Explain(m3, container));
EXPECT_EQ( EXPECT_EQ(
"whose distance between begin() and end() 0 doesn't match, which is 1 " "whose distance between begin() and end() 0 doesn't match, which is 1 "
@ -1477,7 +1492,9 @@ TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
Explain(m1, container)); Explain(m1, container));
EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
Explain(m2, container)); Explain(m2, container));
EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", EXPECT_EQ(
"whose distance between begin() and end() 2 doesn't match, isn't equal "
"to 0, and isn't equal to 3",
Explain(m3, container)); Explain(m3, container));
EXPECT_EQ( EXPECT_EQ(
"whose distance between begin() and end() 2 matches, which is 1 more " "whose distance between begin() and end() 2 matches, which is 1 more "
@ -1826,8 +1843,8 @@ TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
} }
TEST(UnorderedElementsAreArrayTest, VectorBool) { TEST(UnorderedElementsAreArrayTest, VectorBool) {
const bool a[] = {0, 1, 0, 1, 1}; const bool a[] = {false, true, false, true, true};
const bool b[] = {1, 0, 1, 1, 0}; const bool b[] = {true, false, true, true, false};
std::vector<bool> expected(std::begin(a), std::end(a)); std::vector<bool> expected(std::begin(a), std::end(a));
std::vector<bool> actual(std::begin(b), std::end(b)); std::vector<bool> actual(std::begin(b), std::end(b));
StringMatchResultListener listener; StringMatchResultListener listener;
@ -2004,7 +2021,14 @@ TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
StringMatchResultListener listener; StringMatchResultListener listener;
EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
<< listener.str(); << listener.str();
EXPECT_THAT(listener.str(), Eq("which has 1 element")); EXPECT_THAT(listener.str(),
Eq("which has 1 element\n"
"where the following matchers don't match any elements:\n"
"matcher #0: is equal to 1,\n"
"matcher #1: is equal to 2,\n"
"matcher #2: is equal to 3\n"
"and where the following elements don't match any matchers:\n"
"element #0: 4"));
} }
TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
@ -2012,7 +2036,11 @@ TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
StringMatchResultListener listener; StringMatchResultListener listener;
EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener)) EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
<< listener.str(); << listener.str();
EXPECT_THAT(listener.str(), Eq("")); EXPECT_THAT(listener.str(),
Eq("where the following matchers don't match any elements:\n"
"matcher #0: is equal to 1,\n"
"matcher #1: is equal to 2,\n"
"matcher #2: is equal to 3"));
} }
TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) { TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
@ -2428,7 +2456,7 @@ TEST(UnorderedPointwiseTest, RejectsWrongSize) {
const double lhs[2] = {1, 2}; const double lhs[2] = {1, 2};
const int rhs[1] = {0}; const int rhs[1] = {0};
EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
EXPECT_EQ("which has 2 elements", EXPECT_EQ("which has 2 elements\n",
Explain(UnorderedPointwise(Gt(), rhs), lhs)); Explain(UnorderedPointwise(Gt(), rhs), lhs));
const int rhs2[3] = {0, 1, 2}; const int rhs2[3] = {0, 1, 2};
@ -2778,7 +2806,7 @@ TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
class NativeArrayPassedAsPointerAndSize { class NativeArrayPassedAsPointerAndSize {
public: public:
NativeArrayPassedAsPointerAndSize() {} NativeArrayPassedAsPointerAndSize() = default;
MOCK_METHOD(void, Helper, (int* array, int size)); MOCK_METHOD(void, Helper, (int* array, int size));
@ -3124,6 +3152,4 @@ TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
} // namespace gmock_matchers_test } // namespace gmock_matchers_test
} // namespace testing } // namespace testing
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#pragma warning(pop)
#endif

View file

@ -31,15 +31,22 @@
// //
// This file tests some commonly used argument matchers. // This file tests some commonly used argument matchers.
#include <array>
#include <cstdint>
#include <memory>
#include <ostream>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short', // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter // possible loss of data and C4100, unreferenced local parameter
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing { namespace testing {
namespace gmock_matchers_test { namespace gmock_matchers_test {
@ -202,7 +209,7 @@ TEST(IsTrueTest, IsTrueIsFalse) {
EXPECT_THAT(nonnull_unique, Not(IsFalse())); EXPECT_THAT(nonnull_unique, Not(IsFalse()));
} }
#if GTEST_HAS_TYPED_TEST #ifdef GTEST_HAS_TYPED_TEST
// Tests ContainerEq with different container types, and // Tests ContainerEq with different container types, and
// different element types. // different element types.
@ -668,6 +675,8 @@ TEST_P(MatcherTupleTestP, ExplainsMatchFailure) {
// explanation. // explanation.
} }
#if GTEST_HAS_TYPED_TEST
// Sample optional type implementation with minimal requirements for use with // Sample optional type implementation with minimal requirements for use with
// Optional matcher. // Optional matcher.
template <typename T> template <typename T>
@ -685,38 +694,94 @@ class SampleOptional {
bool has_value_; bool has_value_;
}; };
TEST(OptionalTest, DescribesSelf) { // Sample optional type implementation with alternative minimal requirements for
const Matcher<SampleOptional<int>> m = Optional(Eq(1)); // use with Optional matcher. In particular, while it doesn't have a bool
// conversion operator, it does have a has_value() method.
template <typename T>
class SampleOptionalWithoutBoolConversion {
public:
using value_type = T;
explicit SampleOptionalWithoutBoolConversion(T value)
: value_(std::move(value)), has_value_(true) {}
SampleOptionalWithoutBoolConversion() : value_(), has_value_(false) {}
bool has_value() const { return has_value_; }
const T& operator*() const { return value_; }
private:
T value_;
bool has_value_;
};
template <typename T>
class OptionalTest : public testing::Test {};
using OptionalTestTypes =
testing::Types<SampleOptional<int>,
SampleOptionalWithoutBoolConversion<int>>;
TYPED_TEST_SUITE(OptionalTest, OptionalTestTypes);
TYPED_TEST(OptionalTest, DescribesSelf) {
const Matcher<TypeParam> m = Optional(Eq(1));
EXPECT_EQ("value is equal to 1", Describe(m)); EXPECT_EQ("value is equal to 1", Describe(m));
} }
TEST(OptionalTest, ExplainsSelf) { TYPED_TEST(OptionalTest, ExplainsSelf) {
const Matcher<SampleOptional<int>> m = Optional(Eq(1)); const Matcher<TypeParam> m = Optional(Eq(1));
EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1))); EXPECT_EQ("whose value 1 matches", Explain(m, TypeParam(1)));
EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2))); EXPECT_EQ("whose value 2 doesn't match", Explain(m, TypeParam(2)));
} }
TEST(OptionalTest, MatchesNonEmptyOptional) { TYPED_TEST(OptionalTest, MatchesNonEmptyOptional) {
const Matcher<SampleOptional<int>> m1 = Optional(1); const Matcher<TypeParam> m1 = Optional(1);
const Matcher<SampleOptional<int>> m2 = Optional(Eq(2)); const Matcher<TypeParam> m2 = Optional(Eq(2));
const Matcher<SampleOptional<int>> m3 = Optional(Lt(3)); const Matcher<TypeParam> m3 = Optional(Lt(3));
SampleOptional<int> opt(1); TypeParam opt(1);
EXPECT_TRUE(m1.Matches(opt)); EXPECT_TRUE(m1.Matches(opt));
EXPECT_FALSE(m2.Matches(opt)); EXPECT_FALSE(m2.Matches(opt));
EXPECT_TRUE(m3.Matches(opt)); EXPECT_TRUE(m3.Matches(opt));
} }
TEST(OptionalTest, DoesNotMatchNullopt) { TYPED_TEST(OptionalTest, DoesNotMatchNullopt) {
const Matcher<SampleOptional<int>> m = Optional(1); const Matcher<TypeParam> m = Optional(1);
SampleOptional<int> empty; TypeParam empty;
EXPECT_FALSE(m.Matches(empty)); EXPECT_FALSE(m.Matches(empty));
} }
TEST(OptionalTest, WorksWithMoveOnly) { TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersTakingReferences) {
Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr)); const Matcher<const int&> eq1 = Eq(1);
EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr))); const Matcher<const int&> eq2 = Eq(2);
TypeParam opt(1);
EXPECT_THAT(opt, Optional(eq1));
EXPECT_THAT(opt, Optional(Not(eq2)));
EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2))));
} }
TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersRequiringConversion) {
const Matcher<int64_t> eq1 = Eq(1);
const Matcher<int64_t> eq2 = Eq(2);
TypeParam opt(1);
EXPECT_THAT(opt, Optional(eq1));
EXPECT_THAT(opt, Optional(Not(eq2)));
EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2))));
}
template <typename T>
class MoveOnlyOptionalTest : public testing::Test {};
using MoveOnlyOptionalTestTypes =
testing::Types<SampleOptional<std::unique_ptr<int>>,
SampleOptionalWithoutBoolConversion<std::unique_ptr<int>>>;
TYPED_TEST_SUITE(MoveOnlyOptionalTest, MoveOnlyOptionalTestTypes);
TYPED_TEST(MoveOnlyOptionalTest, WorksWithMoveOnly) {
Matcher<TypeParam> m = Optional(Eq(nullptr));
EXPECT_TRUE(m.Matches(TypeParam(nullptr)));
}
#endif // GTEST_HAS_TYPED_TEST
class SampleVariantIntString { class SampleVariantIntString {
public: public:
SampleVariantIntString(int i) : i_(i), has_int_(true) {} SampleVariantIntString(int i) : i_(i), has_int_(true) {}
@ -863,7 +928,7 @@ TEST(ArgsTest, AcceptsOneTemplateArg) {
} }
TEST(ArgsTest, AcceptsTwoTemplateArgs) { TEST(ArgsTest, AcceptsTwoTemplateArgs) {
const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<0, 1>(Lt()))); EXPECT_THAT(t, (Args<0, 1>(Lt())));
EXPECT_THAT(t, (Args<1, 2>(Lt()))); EXPECT_THAT(t, (Args<1, 2>(Lt())));
@ -871,13 +936,13 @@ TEST(ArgsTest, AcceptsTwoTemplateArgs) {
} }
TEST(ArgsTest, AcceptsRepeatedTemplateArgs) { TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<0, 0>(Eq()))); EXPECT_THAT(t, (Args<0, 0>(Eq())));
EXPECT_THAT(t, Not(Args<1, 1>(Ne()))); EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
} }
TEST(ArgsTest, AcceptsDecreasingTemplateArgs) { TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<2, 0>(Gt()))); EXPECT_THAT(t, (Args<2, 0>(Gt())));
EXPECT_THAT(t, Not(Args<2, 1>(Lt()))); EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
} }
@ -892,7 +957,7 @@ TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
} }
TEST(ArgsTest, CanBeNested) { TEST(ArgsTest, CanBeNested) {
const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT const std::tuple<short, int, long, int> t(short{4}, 5, 6L, 6); // NOLINT
EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq())))); EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt())))); EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
} }
@ -1561,7 +1626,7 @@ TEST(AnyOfArrayTest, Matchers) {
} }
TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) { TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {
// AnyOfArray and AllOfArry use the same underlying template-template, // AnyOfArray and AllOfArray use the same underlying template-template,
// thus it is sufficient to test one here. // thus it is sufficient to test one here.
const std::vector<int> v0{}; const std::vector<int> v0{};
const std::vector<int> v1{1}; const std::vector<int> v1{1};
@ -1570,10 +1635,10 @@ TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {
const Matcher<int> m1 = AnyOfArray(v1); const Matcher<int> m1 = AnyOfArray(v1);
const Matcher<int> m2 = AnyOfArray(v2); const Matcher<int> m2 = AnyOfArray(v2);
EXPECT_EQ("", Explain(m0, 0)); EXPECT_EQ("", Explain(m0, 0));
EXPECT_EQ("", Explain(m1, 1)); EXPECT_EQ("which matches (is equal to 1)", Explain(m1, 1));
EXPECT_EQ("", Explain(m1, 2)); EXPECT_EQ("isn't equal to 1", Explain(m1, 2));
EXPECT_EQ("", Explain(m2, 3)); EXPECT_EQ("which matches (is equal to 3)", Explain(m2, 3));
EXPECT_EQ("", Explain(m2, 4)); EXPECT_EQ("isn't equal to 2, and isn't equal to 3", Explain(m2, 4));
EXPECT_EQ("()", Describe(m0)); EXPECT_EQ("()", Describe(m0));
EXPECT_EQ("(is equal to 1)", Describe(m1)); EXPECT_EQ("(is equal to 1)", Describe(m1));
EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2)); EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
@ -1615,6 +1680,20 @@ TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
EXPECT_THAT(p, Not(UniquePointee(2))); 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 #if GTEST_HAS_EXCEPTIONS
// std::function<void()> is used below for compatibility with older copies of // std::function<void()> is used below for compatibility with older copies of
@ -1800,6 +1879,4 @@ TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
} // namespace gmock_matchers_test } // namespace gmock_matchers_test
} // namespace testing } // namespace testing
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#pragma warning(pop)
#endif

View file

@ -31,22 +31,23 @@
// //
// This file tests the built-in actions in gmock-actions.h. // 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 "gmock/gmock-more-actions.h"
#include <algorithm>
#include <functional> #include <functional>
#include <iterator>
#include <memory> #include <memory>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4577)
namespace testing { namespace testing {
namespace gmock_more_actions_test { namespace gmock_more_actions_test {
@ -84,6 +85,16 @@ struct UnaryFunctor {
int operator()(bool x) { return x ? 1 : -1; } int operator()(bool x) { return x ? 1 : -1; }
}; };
struct UnaryMoveOnlyFunctor : UnaryFunctor {
UnaryMoveOnlyFunctor() = default;
UnaryMoveOnlyFunctor(const UnaryMoveOnlyFunctor&) = delete;
UnaryMoveOnlyFunctor(UnaryMoveOnlyFunctor&&) = default;
};
struct OneShotUnaryFunctor {
int operator()(bool x) && { return x ? 1 : -1; }
};
const char* Binary(const char* input, short n) { return input + n; } // NOLINT const char* Binary(const char* input, short n) { return input + n; } // NOLINT
int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
@ -676,7 +687,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) {
Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end()); Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end());
std::string s; std::string s;
a.Perform(std::make_tuple(true, back_inserter(s))); a.Perform(std::make_tuple(true, std::back_inserter(s)));
EXPECT_EQ(letters, s); EXPECT_EQ(letters, s);
} }
@ -697,12 +708,24 @@ TEST(InvokeArgumentTest, Function0) {
EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary))); EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary)));
} }
// Tests using InvokeArgument with a unary function. // Tests using InvokeArgument with a unary functor.
TEST(InvokeArgumentTest, Functor1) { TEST(InvokeArgumentTest, Functor1) {
Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor()))); EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor())));
} }
// Tests using InvokeArgument with a unary move-only functor.
TEST(InvokeArgumentTest, Functor1MoveOnly) {
Action<int(UnaryMoveOnlyFunctor)> a = InvokeArgument<0>(true); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryMoveOnlyFunctor())));
}
// Tests using InvokeArgument with a one-shot unary functor.
TEST(InvokeArgumentTest, OneShotFunctor1) {
Action<int(OneShotUnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(OneShotUnaryFunctor())));
}
// Tests using InvokeArgument with a 5-ary function. // Tests using InvokeArgument with a 5-ary function.
TEST(InvokeArgumentTest, Function5) { TEST(InvokeArgumentTest, Function5) {
Action<int(int (*)(int, int, int, int, int))> a = // NOLINT Action<int(int (*)(int, int, int, int, int))> a = // NOLINT
@ -805,6 +828,22 @@ TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {
EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
} }
TEST(InvokeArgumentTest, MoveOnlyType) {
struct Marker {};
struct {
// Method takes a unique_ptr (to a type we don't care about), and an
// invocable type.
MOCK_METHOD(bool, MockMethod,
(std::unique_ptr<Marker>, std::function<int()>), ());
} mock;
ON_CALL(mock, MockMethod(_, _)).WillByDefault(InvokeArgument<1>());
// This compiles, but is a little opaque as a workaround:
ON_CALL(mock, MockMethod(_, _))
.WillByDefault(WithArg<1>(InvokeArgument<0>()));
}
// Tests DoAll(a1, a2). // Tests DoAll(a1, a2).
TEST(DoAllTest, TwoActions) { TEST(DoAllTest, TwoActions) {
int n = 0; int n = 0;
@ -982,11 +1021,7 @@ TEST(DoAllTest, ImplicitlyConvertsActionArguments) {
// is expanded and macro expansion cannot contain #pragma. Therefore // is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here. // we suppress them here.
// Also suppress C4503 decorated name length exceeded, name was truncated // Also suppress C4503 decorated name length exceeded, name was truncated
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4503)
#endif
// Tests the ACTION*() macro family. // Tests the ACTION*() macro family.
// Tests that ACTION() can define an action that doesn't reference the // Tests that ACTION() can define an action that doesn't reference the
@ -1548,3 +1583,6 @@ TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
} // namespace gmock_more_actions_test } // namespace gmock_more_actions_test
} // namespace testing } // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4577

View file

@ -40,7 +40,7 @@
// clash with ::testing::Mock. // clash with ::testing::Mock.
class Mock { class Mock {
public: public:
Mock() {} Mock() = default;
MOCK_METHOD0(DoThis, void()); MOCK_METHOD0(DoThis, void());
@ -78,7 +78,7 @@ class CallsMockMethodInDestructor {
class Foo { class Foo {
public: public:
virtual ~Foo() {} virtual ~Foo() = default;
virtual void DoThis() = 0; virtual void DoThis() = 0;
virtual int DoThat(bool flag) = 0; virtual int DoThat(bool flag) = 0;
@ -86,7 +86,7 @@ class Foo {
class MockFoo : public Foo { class MockFoo : public Foo {
public: public:
MockFoo() {} MockFoo() = default;
void Delete() { delete this; } void Delete() { delete this; }
MOCK_METHOD0(DoThis, void()); MOCK_METHOD0(DoThis, void());
@ -109,7 +109,7 @@ class MockBar {
(a10 ? 'T' : 'F'); (a10 ? 'T' : 'F');
} }
virtual ~MockBar() {} virtual ~MockBar() = default;
const std::string& str() const { return str_; } const std::string& str() const { return str_; }

View file

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

View file

@ -98,7 +98,7 @@ class NonDefaultConstructible {
class MockA { class MockA {
public: public:
MockA() {} MockA() = default;
MOCK_METHOD1(DoA, void(int n)); MOCK_METHOD1(DoA, void(int n));
MOCK_METHOD1(ReturnResult, Result(int n)); MOCK_METHOD1(ReturnResult, Result(int n));
@ -113,7 +113,7 @@ class MockA {
class MockB { class MockB {
public: public:
MockB() {} MockB() = default;
MOCK_CONST_METHOD0(DoB, int()); // NOLINT MOCK_CONST_METHOD0(DoB, int()); // NOLINT
MOCK_METHOD1(DoB, int(int n)); // NOLINT MOCK_METHOD1(DoB, int(int n)); // NOLINT
@ -125,7 +125,7 @@ class MockB {
class ReferenceHoldingMock { class ReferenceHoldingMock {
public: public:
ReferenceHoldingMock() {} ReferenceHoldingMock() = default;
MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*)); MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
@ -143,12 +143,12 @@ class ReferenceHoldingMock {
class CC { class CC {
public: public:
virtual ~CC() {} virtual ~CC() = default;
virtual int Method() = 0; virtual int Method() = 0;
}; };
class MockCC : public CC { class MockCC : public CC {
public: public:
MockCC() {} MockCC() = default;
MOCK_METHOD0(Method, int()); MOCK_METHOD0(Method, int());
@ -739,11 +739,12 @@ TEST(ExpectCallTest, CatchesTooFewCalls) {
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
{ // NOLINT { // NOLINT
MockB b; MockB b;
EXPECT_CALL(b, DoB(5)).Times(AtLeast(2)); EXPECT_CALL(b, DoB(5)).Description("DoB Method").Times(AtLeast(2));
b.DoB(5); b.DoB(5);
}, },
"Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n" "Actual function \"DoB Method\" call count "
"doesn't match EXPECT_CALL(b, DoB(5))...\n"
" Expected: to be called at least twice\n" " Expected: to be called at least twice\n"
" Actual: called once - unsatisfied and active"); " Actual: called once - unsatisfied and active");
} }
@ -803,39 +804,40 @@ TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
"to be called at least once"); "to be called at least once");
} }
#if defined(__cplusplus) && __cplusplus >= 201703L #if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
// It should be possible to return a non-moveable type from a mock action in // 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 // C++17 and above, where it's guaranteed that such a type can be initialized
// from a prvalue returned from a function. // from a prvalue returned from a function.
TEST(ExpectCallTest, NonMoveableType) { TEST(ExpectCallTest, NonMoveableType) {
// Define a non-moveable result type. // Define a non-moveable result type.
struct Result { struct NonMoveableStruct {
explicit Result(int x_in) : x(x_in) {} explicit NonMoveableStruct(int x_in) : x(x_in) {}
Result(Result&&) = delete; NonMoveableStruct(NonMoveableStruct&&) = delete;
int x; int x;
}; };
static_assert(!std::is_move_constructible_v<Result>); static_assert(!std::is_move_constructible_v<NonMoveableStruct>);
static_assert(!std::is_copy_constructible_v<Result>); static_assert(!std::is_copy_constructible_v<NonMoveableStruct>);
static_assert(!std::is_move_assignable_v<Result>); static_assert(!std::is_move_assignable_v<NonMoveableStruct>);
static_assert(!std::is_copy_assignable_v<Result>); static_assert(!std::is_copy_assignable_v<NonMoveableStruct>);
// We should be able to use a callable that returns that result as both a // 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. // OnceAction and an Action, whether the callable ignores arguments or not.
const auto return_17 = [] { return Result(17); }; const auto return_17 = [] { return NonMoveableStruct(17); };
static_cast<void>(OnceAction<Result()>{return_17}); static_cast<void>(OnceAction<NonMoveableStruct()>{return_17});
static_cast<void>(Action<Result()>{return_17}); static_cast<void>(Action<NonMoveableStruct()>{return_17});
static_cast<void>(OnceAction<Result(int)>{return_17}); static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17});
static_cast<void>(Action<Result(int)>{return_17}); static_cast<void>(Action<NonMoveableStruct(int)>{return_17});
// It should be possible to return the result end to end through an // It should be possible to return the result end to end through an
// EXPECT_CALL statement, with both WillOnce and WillRepeatedly. // EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
MockFunction<Result()> mock; MockFunction<NonMoveableStruct()> mock;
EXPECT_CALL(mock, Call) // EXPECT_CALL(mock, Call) //
.WillOnce(return_17) // .WillOnce(return_17) //
.WillRepeatedly(return_17); .WillRepeatedly(return_17);
@ -904,7 +906,7 @@ TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
" - returning default value.")); " - returning default value."));
} }
TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) { TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) {
MockB b; MockB b;
std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1)); EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
@ -1064,7 +1066,7 @@ TEST(UnexpectedCallTest, UnmatchedArguments) {
// Tests that Google Mock explains that an expectation with // Tests that Google Mock explains that an expectation with
// unsatisfied pre-requisites doesn't match the call. // unsatisfied pre-requisites doesn't match the call.
TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
Sequence s1, s2; Sequence s1, s2;
MockB b; MockB b;
EXPECT_CALL(b, DoB(1)).InSequence(s1); EXPECT_CALL(b, DoB(1)).InSequence(s1);
@ -1087,16 +1089,7 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
// Verifies that the failure message contains the two unsatisfied // Verifies that the failure message contains the two unsatisfied
// pre-requisites but not the satisfied one. // pre-requisites but not the satisfied one.
#if GTEST_USES_PCRE #ifdef GTEST_USES_POSIX_RE
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(), EXPECT_THAT(r.message(),
ContainsRegex( ContainsRegex(
// POSIX RE doesn't understand the (?s) prefix, but has no // POSIX RE doesn't understand the (?s) prefix, but has no
@ -1111,7 +1104,7 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
"the following immediate pre-requisites are not satisfied:")); "the following immediate pre-requisites are not satisfied:"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
#endif // GTEST_USES_PCRE #endif // GTEST_USES_POSIX_RE
b.DoB(1); b.DoB(1);
b.DoB(3); b.DoB(3);
@ -1148,10 +1141,11 @@ TEST(ExcessiveCallTest, DoesDefaultAction) {
// When there is no ON_CALL(), the default value for the return type // When there is no ON_CALL(), the default value for the return type
// should be returned. // should be returned.
MockB b; MockB b;
EXPECT_CALL(b, DoB(0)).Times(0); EXPECT_CALL(b, DoB(0)).Description("DoB Method").Times(0);
int n = -1; int n = -1;
EXPECT_NONFATAL_FAILURE(n = b.DoB(0), EXPECT_NONFATAL_FAILURE(
"Mock function called more times than expected"); n = b.DoB(0),
"Mock function \"DoB Method\" called more times than expected");
EXPECT_EQ(0, n); EXPECT_EQ(0, n);
} }
@ -1159,10 +1153,11 @@ TEST(ExcessiveCallTest, DoesDefaultAction) {
// the failure message contains the argument values. // the failure message contains the argument values.
TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) { TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
MockA a; MockA a;
EXPECT_CALL(a, DoA(_)).Times(0); EXPECT_CALL(a, DoA(_)).Description("DoA Method").Times(0);
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
a.DoA(9), a.DoA(9),
"Mock function called more times than expected - returning directly.\n" "Mock function \"DoA Method\" called more times than expected - "
"returning directly.\n"
" Function call: DoA(9)\n" " Function call: DoA(9)\n"
" Expected: to be never called\n" " Expected: to be never called\n"
" Actual: called once - over-saturated and active"); " Actual: called once - over-saturated and active");
@ -1776,16 +1771,11 @@ TEST(DeletingMockEarlyTest, Success2) {
// Suppresses warning on unreferenced formal parameter in MSVC with // Suppresses warning on unreferenced formal parameter in MSVC with
// -W4. // -W4.
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
ACTION_P(Delete, ptr) { delete ptr; } ACTION_P(Delete, ptr) { delete ptr; }
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#pragma warning(pop)
#endif
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) { TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
MockA* const a = new MockA; MockA* const a = new MockA;
@ -1892,7 +1882,7 @@ struct Unprintable {
class MockC { class MockC {
public: public:
MockC() {} MockC() = default;
MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p, MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
const Printable& x, Unprintable y)); const Printable& x, Unprintable y));
@ -2059,9 +2049,9 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
"call should not happen. Do not suppress it by blindly adding " "call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. " "an EXPECT_CALL() if you don't mean to enforce the call. "
"See " "See "
"https://github.com/google/googletest/blob/master/docs/" "https://github.com/google/googletest/blob/main/docs/"
"gmock_cook_book.md#" "gmock_cook_book.md#"
"knowing-when-to-expect for details."; "knowing-when-to-expect-useoncall for details.";
// A void-returning function. // A void-returning function.
CaptureStdout(); CaptureStdout();
@ -2132,7 +2122,7 @@ void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
class LogTestHelper { class LogTestHelper {
public: public:
LogTestHelper() {} LogTestHelper() = default;
MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot)); MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
@ -2599,14 +2589,7 @@ TEST(ParameterlessExpectationsTest,
} // namespace } // namespace
} // namespace testing } // 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) { int main(int argc, char** argv) {
#endif // GMOCK_RENAME_MAIN
testing::InitGoogleMock(&argc, argv); testing::InitGoogleMock(&argc, argv);
// Ensures that the tests pass no matter what value of // Ensures that the tests pass no matter what value of
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.

View file

@ -29,6 +29,8 @@
// Tests Google Mock's functionality that depends on exceptions. // Tests Google Mock's functionality that depends on exceptions.
#include <exception>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"

View file

@ -54,50 +54,59 @@ class GMockLeakTest(gmock_test_utils.TestCase):
def testCatchesLeakedMockByDefault(self): def testCatchesLeakedMockByDefault(self):
self.assertNotEqual( self.assertNotEqual(
0, 0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL, gmock_test_utils.Subprocess(
env=environ).exit_code) TEST_WITH_EXPECT_CALL, env=environ
).exit_code,
)
self.assertNotEqual( self.assertNotEqual(
0, 0, gmock_test_utils.Subprocess(TEST_WITH_ON_CALL, env=environ).exit_code
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL, )
env=environ).exit_code)
def testDoesNotCatchLeakedMockWhenDisabled(self): def testDoesNotCatchLeakedMockWhenDisabled(self):
self.assertEquals( self.assertEqual(
0, 0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL + gmock_test_utils.Subprocess(
['--gmock_catch_leaked_mocks=0'], TEST_WITH_EXPECT_CALL + ['--gmock_catch_leaked_mocks=0'],
env=environ).exit_code) env=environ,
self.assertEquals( ).exit_code,
)
self.assertEqual(
0, 0,
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL + gmock_test_utils.Subprocess(
['--gmock_catch_leaked_mocks=0'], TEST_WITH_ON_CALL + ['--gmock_catch_leaked_mocks=0'], env=environ
env=environ).exit_code) ).exit_code,
)
def testCatchesLeakedMockWhenEnabled(self): def testCatchesLeakedMockWhenEnabled(self):
self.assertNotEqual( self.assertNotEqual(
0, 0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL + gmock_test_utils.Subprocess(
['--gmock_catch_leaked_mocks'], TEST_WITH_EXPECT_CALL + ['--gmock_catch_leaked_mocks'], env=environ
env=environ).exit_code) ).exit_code,
)
self.assertNotEqual( self.assertNotEqual(
0, 0,
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL + gmock_test_utils.Subprocess(
['--gmock_catch_leaked_mocks'], TEST_WITH_ON_CALL + ['--gmock_catch_leaked_mocks'], env=environ
env=environ).exit_code) ).exit_code,
)
def testCatchesLeakedMockWhenEnabledWithExplictFlagValue(self): def testCatchesLeakedMockWhenEnabledWithExplictFlagValue(self):
self.assertNotEqual( self.assertNotEqual(
0, 0,
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL + gmock_test_utils.Subprocess(
['--gmock_catch_leaked_mocks=1'], TEST_WITH_EXPECT_CALL + ['--gmock_catch_leaked_mocks=1'],
env=environ).exit_code) env=environ,
).exit_code,
)
def testCatchesMultipleLeakedMocks(self): def testCatchesMultipleLeakedMocks(self):
self.assertNotEqual( self.assertNotEqual(
0, 0,
gmock_test_utils.Subprocess(TEST_MULTIPLE_LEAKS + gmock_test_utils.Subprocess(
['--gmock_catch_leaked_mocks'], TEST_MULTIPLE_LEAKS + ['--gmock_catch_leaked_mocks'], env=environ
env=environ).exit_code) ).exit_code,
)
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -40,13 +40,13 @@ using ::testing::Return;
class FooInterface { class FooInterface {
public: public:
virtual ~FooInterface() {} virtual ~FooInterface() = default;
virtual void DoThis() = 0; virtual void DoThis() = 0;
}; };
class MockFoo : public FooInterface { class MockFoo : public FooInterface {
public: public:
MockFoo() {} MockFoo() = default;
MOCK_METHOD0(DoThis, void()); MOCK_METHOD0(DoThis, void());

View file

@ -116,7 +116,7 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#if !GTEST_OS_WINDOWS_MOBILE #ifndef GTEST_OS_WINDOWS_MOBILE
#include <errno.h> #include <errno.h>
#endif #endif
@ -181,11 +181,12 @@ using testing::WithArg;
using testing::WithArgs; using testing::WithArgs;
using testing::WithoutArgs; using testing::WithoutArgs;
#if !GTEST_OS_WINDOWS_MOBILE #ifndef GTEST_OS_WINDOWS_MOBILE
using testing::SetErrnoAndReturn; using testing::SetErrnoAndReturn;
#endif #endif
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
using testing::Rethrow;
using testing::Throw; using testing::Throw;
#endif #endif
@ -194,7 +195,7 @@ using testing::MatchesRegex;
class Interface { class Interface {
public: public:
virtual ~Interface() {} virtual ~Interface() = default;
virtual void VoidFromString(char* str) = 0; virtual void VoidFromString(char* str) = 0;
virtual char* StringFromString(char* str) = 0; virtual char* StringFromString(char* str) = 0;
virtual int IntFromString(char* str) = 0; virtual int IntFromString(char* str) = 0;
@ -208,7 +209,7 @@ class Interface {
class Mock : public Interface { class Mock : public Interface {
public: public:
Mock() {} Mock() = default;
MOCK_METHOD1(VoidFromString, void(char* str)); MOCK_METHOD1(VoidFromString, void(char* str));
MOCK_METHOD1(StringFromString, char*(char* str)); MOCK_METHOD1(StringFromString, char*(char* str));
@ -306,7 +307,7 @@ TEST(LinkTest, TestSetArrayArgument) {
mock.VoidFromString(&ch); mock.VoidFromString(&ch);
} }
#if !GTEST_OS_WINDOWS_MOBILE #ifndef GTEST_OS_WINDOWS_MOBILE
// Tests the linkage of the SetErrnoAndReturn action. // Tests the linkage of the SetErrnoAndReturn action.
TEST(LinkTest, TestSetErrnoAndReturn) { TEST(LinkTest, TestSetErrnoAndReturn) {
@ -416,6 +417,14 @@ TEST(LinkTest, TestThrow) {
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42)); EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42));
EXPECT_THROW(mock.VoidFromString(nullptr), int); EXPECT_THROW(mock.VoidFromString(nullptr), int);
} }
// Tests the linkage of the Rethrow action.
TEST(LinkTest, TestRethrow) {
Mock mock;
EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(Rethrow(std::make_exception_ptr(42)));
EXPECT_THROW(mock.VoidFromString(nullptr), int);
}
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS
// The ACTION*() macros trigger warning C4100 (unreferenced formal // The ACTION*() macros trigger warning C4100 (unreferenced formal
@ -423,10 +432,7 @@ TEST(LinkTest, TestThrow) {
// the macro definition, as the warnings are generated when the macro // the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore // is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here. // we suppress them here.
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
// Tests the linkage of actions created using ACTION macro. // Tests the linkage of actions created using ACTION macro.
namespace { namespace {
@ -459,9 +465,7 @@ ACTION_P2(ReturnEqualsEitherOf, first, second) {
} }
} // namespace } // namespace
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#pragma warning(pop)
#endif
TEST(LinkTest, TestActionP2Macro) { TEST(LinkTest, TestActionP2Macro) {
Mock mock; Mock mock;

View file

@ -159,15 +159,22 @@ class GMockOutputTest(gmock_test_utils.TestCase):
golden_file = open(GOLDEN_PATH, 'rb') golden_file = open(GOLDEN_PATH, 'rb')
golden = golden_file.read().decode('utf-8') golden = golden_file.read().decode('utf-8')
golden_file.close() 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. # The normalized output should match the golden file.
self.assertEqual(golden, output) self.assertEqual(golden, output)
# The raw output should contain 2 leaked mock object errors for # The raw output should contain 2 leaked mock object errors for
# test GMockOutputTest.CatchesLeakedMocks. # test GMockOutputTest.CatchesLeakedMocks.
self.assertEqual(['GMockOutputTest.CatchesLeakedMocks', self.assertEqual(
'GMockOutputTest.CatchesLeakedMocks'], [
leaky_tests) 'GMockOutputTest.CatchesLeakedMocks',
'GMockOutputTest.CatchesLeakedMocks',
],
leaky_tests,
)
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -38,10 +38,7 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
// Silence C4100 (unreferenced formal parameter) // Silence C4100 (unreferenced formal parameter)
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
using testing::_; using testing::_;
using testing::AnyNumber; using testing::AnyNumber;
@ -55,7 +52,7 @@ using testing::Value;
class MockFoo { class MockFoo {
public: public:
MockFoo() {} MockFoo() = default;
MOCK_METHOD3(Bar, char(const std::string& s, int i, double x)); MOCK_METHOD3(Bar, char(const std::string& s, int i, double x));
MOCK_METHOD2(Bar2, bool(int x, int y)); MOCK_METHOD2(Bar2, bool(int x, int y));
@ -286,6 +283,4 @@ int main(int argc, char** argv) {
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
#ifdef _MSC_VER GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#pragma warning(pop)
#endif

View file

@ -40,6 +40,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(0, _))...
Actual: 1 Actual: 1
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnexpectedCall [ FAILED ] GMockOutputTest.UnexpectedCall
[ RUN ] GMockOutputTest.UnexpectedCallToVoidFunction [ RUN ] GMockOutputTest.UnexpectedCallToVoidFunction
unknown file: Failure unknown file: Failure
@ -53,6 +54,7 @@ FILE:#: EXPECT_CALL(foo_, Bar3(0, _))...
Actual: 1 Actual: 1
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction [ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction
[ RUN ] GMockOutputTest.ExcessiveCall [ RUN ] GMockOutputTest.ExcessiveCall
FILE:#: Failure FILE:#: Failure
@ -61,6 +63,7 @@ Mock function called more times than expected - returning default value.
Returns: false Returns: false
Expected: to be called once Expected: to be called once
Actual: called twice - over-saturated and active Actual: called twice - over-saturated and active
[ FAILED ] GMockOutputTest.ExcessiveCall [ FAILED ] GMockOutputTest.ExcessiveCall
[ RUN ] GMockOutputTest.ExcessiveCallToVoidFunction [ RUN ] GMockOutputTest.ExcessiveCallToVoidFunction
FILE:#: Failure FILE:#: Failure
@ -68,6 +71,7 @@ Mock function called more times than expected - returning directly.
Function call: Bar3(0, 1) Function call: Bar3(0, 1)
Expected: to be called once Expected: to be called once
Actual: called twice - over-saturated and active Actual: called twice - over-saturated and active
[ FAILED ] GMockOutputTest.ExcessiveCallToVoidFunction [ FAILED ] GMockOutputTest.ExcessiveCallToVoidFunction
[ RUN ] GMockOutputTest.UninterestingCall [ RUN ] GMockOutputTest.UninterestingCall
@ -75,14 +79,14 @@ GMOCK WARNING:
Uninteresting mock function call - returning default value. Uninteresting mock function call - returning default value.
Function call: Bar2(0, 1) Function call: Bar2(0, 1)
Returns: false 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/master/docs/gmock_cook_book.md#knowing-when-to-expect for details. NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
[ OK ] GMockOutputTest.UninterestingCall [ OK ] GMockOutputTest.UninterestingCall
[ RUN ] GMockOutputTest.UninterestingCallToVoidFunction [ RUN ] GMockOutputTest.UninterestingCallToVoidFunction
GMOCK WARNING: GMOCK WARNING:
Uninteresting mock function call - returning directly. Uninteresting mock function call - returning directly.
Function call: Bar3(0, 1) 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/master/docs/gmock_cook_book.md#knowing-when-to-expect for details. NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction [ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation [ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure unknown file: Failure
@ -104,6 +108,7 @@ FILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(0, 0))...
Actual: 1 Actual: 1
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.RetiredExpectation [ FAILED ] GMockOutputTest.RetiredExpectation
[ RUN ] GMockOutputTest.UnsatisfiedPrerequisite [ RUN ] GMockOutputTest.UnsatisfiedPrerequisite
unknown file: Failure unknown file: Failure
@ -125,6 +130,7 @@ FILE:#: pre-requisite #0
(end of pre-requisites) (end of pre-requisites)
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisite [ FAILED ] GMockOutputTest.UnsatisfiedPrerequisite
[ RUN ] GMockOutputTest.UnsatisfiedPrerequisites [ RUN ] GMockOutputTest.UnsatisfiedPrerequisites
unknown file: Failure unknown file: Failure
@ -147,6 +153,7 @@ FILE:#: pre-requisite #1
(end of pre-requisites) (end of pre-requisites)
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedPrerequisites [ FAILED ] GMockOutputTest.UnsatisfiedPrerequisites
[ RUN ] GMockOutputTest.UnsatisfiedWith [ RUN ] GMockOutputTest.UnsatisfiedWith
FILE:#: Failure FILE:#: Failure
@ -154,16 +161,19 @@ Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(_, _))...
Expected args: are a pair where the first >= the second Expected args: are a pair where the first >= the second
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedWith [ FAILED ] GMockOutputTest.UnsatisfiedWith
[ RUN ] GMockOutputTest.UnsatisfiedExpectation [ RUN ] GMockOutputTest.UnsatisfiedExpectation
FILE:#: Failure FILE:#: Failure
Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(0, _))... Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(0, _))...
Expected: to be called twice Expected: to be called twice
Actual: called once - unsatisfied and active Actual: called once - unsatisfied and active
FILE:#: Failure FILE:#: Failure
Actual function call count doesn't match EXPECT_CALL(foo_, Bar(_, _, _))... Actual function call count doesn't match EXPECT_CALL(foo_, Bar(_, _, _))...
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnsatisfiedExpectation [ FAILED ] GMockOutputTest.UnsatisfiedExpectation
[ RUN ] GMockOutputTest.MismatchArguments [ RUN ] GMockOutputTest.MismatchArguments
unknown file: Failure unknown file: Failure
@ -180,6 +190,7 @@ FILE:#: EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0)))...
Actual: -0.1 Actual: -0.1
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.MismatchArguments [ FAILED ] GMockOutputTest.MismatchArguments
[ RUN ] GMockOutputTest.MismatchWith [ RUN ] GMockOutputTest.MismatchWith
unknown file: Failure unknown file: Failure
@ -194,6 +205,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
Actual: don't match Actual: don't match
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.MismatchWith [ FAILED ] GMockOutputTest.MismatchWith
[ RUN ] GMockOutputTest.MismatchArgumentsAndWith [ RUN ] GMockOutputTest.MismatchArgumentsAndWith
unknown file: Failure unknown file: Failure
@ -210,6 +222,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...
Actual: don't match Actual: don't match
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.MismatchArgumentsAndWith [ FAILED ] GMockOutputTest.MismatchArgumentsAndWith
[ RUN ] GMockOutputTest.UnexpectedCallWithDefaultAction [ RUN ] GMockOutputTest.UnexpectedCallWithDefaultAction
unknown file: Failure unknown file: Failure
@ -227,6 +240,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
Actual: 0 Actual: 0
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
unknown file: Failure unknown file: Failure
Unexpected mock function call - taking default action specified at: Unexpected mock function call - taking default action specified at:
@ -242,6 +256,7 @@ FILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...
Actual: 0 Actual: 0
Expected: to be called once Expected: to be called once
Actual: never called - unsatisfied and active Actual: never called - unsatisfied and active
[ FAILED ] GMockOutputTest.UnexpectedCallWithDefaultAction [ FAILED ] GMockOutputTest.UnexpectedCallWithDefaultAction
[ RUN ] GMockOutputTest.ExcessiveCallWithDefaultAction [ RUN ] GMockOutputTest.ExcessiveCallWithDefaultAction
FILE:#: Failure FILE:#: Failure
@ -251,6 +266,7 @@ FILE:#:
Returns: true Returns: true
Expected: to be called once Expected: to be called once
Actual: called twice - over-saturated and active Actual: called twice - over-saturated and active
FILE:#: Failure FILE:#: Failure
Mock function called more times than expected - taking default action specified at: Mock function called more times than expected - taking default action specified at:
FILE:#: FILE:#:
@ -258,6 +274,7 @@ FILE:#:
Returns: false Returns: false
Expected: to be called once Expected: to be called once
Actual: called twice - over-saturated and active Actual: called twice - over-saturated and active
[ FAILED ] GMockOutputTest.ExcessiveCallWithDefaultAction [ FAILED ] GMockOutputTest.ExcessiveCallWithDefaultAction
[ RUN ] GMockOutputTest.UninterestingCallWithDefaultAction [ RUN ] GMockOutputTest.UninterestingCallWithDefaultAction
@ -266,14 +283,14 @@ Uninteresting mock function call - taking default action specified at:
FILE:#: FILE:#:
Function call: Bar2(2, 2) Function call: Bar2(2, 2)
Returns: true 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/master/docs/gmock_cook_book.md#knowing-when-to-expect for details. NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
GMOCK WARNING: GMOCK WARNING:
Uninteresting mock function call - taking default action specified at: Uninteresting mock function call - taking default action specified at:
FILE:#: FILE:#:
Function call: Bar2(1, 1) Function call: Bar2(1, 1)
Returns: false 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/master/docs/gmock_cook_book.md#knowing-when-to-expect for details. NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect-useoncall for details.
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction [ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction [ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
@ -293,6 +310,7 @@ FILE:#: Failure
Value of: (std::pair<int, bool>(42, true)) Value of: (std::pair<int, bool>(42, true))
Expected: is pair (first: is >= 48, second: 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.PrintsMatcher
[ FAILED ] GMockOutputTest.UnexpectedCall [ FAILED ] GMockOutputTest.UnexpectedCall
[ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction [ FAILED ] GMockOutputTest.UnexpectedCallToVoidFunction

View file

@ -174,6 +174,6 @@ TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
// Makes sure Google Mock flags can be accessed in code. // Makes sure Google Mock flags can be accessed in code.
TEST(FlagTest, IsAccessibleInCode) { TEST(FlagTest, IsAccessibleInCode) {
bool dummy = bool dummy =
GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose) == ""; GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose).empty();
(void)dummy; // Avoids the "unused local variable" warning. (void)dummy; // Avoids the "unused local variable" warning.
} }

View file

@ -77,9 +77,6 @@ def GetExitStatus(exit_code):
return -1 return -1
# Suppresses the "Invalid const name" lint complaint
# pylint: disable-msg=C6409
# Exposes utilities from gtest_test_utils. # Exposes utilities from gtest_test_utils.
Subprocess = gtest_test_utils.Subprocess Subprocess = gtest_test_utils.Subprocess
TestCase = gtest_test_utils.TestCase TestCase = gtest_test_utils.TestCase
@ -87,8 +84,6 @@ environ = gtest_test_utils.environ
SetEnvVar = gtest_test_utils.SetEnvVar SetEnvVar = gtest_test_utils.SetEnvVar
PREMATURE_EXIT_FILE_ENV_VAR = gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR PREMATURE_EXIT_FILE_ENV_VAR = gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR
# pylint: enable-msg=C6409
def Main(): def Main():
"""Runs the unit test.""" """Runs the unit test."""

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