Update embedded googletest to 1.11.0

Fixes #1081

Signed-off-by: Florian Bruhin <me@the-compiler.org>
pull/1083/head
Florian Bruhin 3 years ago
parent 5b876f3e0f
commit 231ebad36f

@ -1,73 +0,0 @@
# Build matrix / environment variable are explained on:
# https://docs.travis-ci.com/user/customizing-the-build/
# This file can be validated on:
# http://lint.travis-ci.org/
language: cpp
# Define the matrix explicitly, manually expanding the combinations of (os, compiler, env).
# It is more tedious, but grants us far more flexibility.
matrix:
include:
- os: linux
before_install: chmod -R +x ./ci/*platformio.sh
install: ./ci/install-platformio.sh
script: ./ci/build-platformio.sh
- os: linux
dist: xenial
compiler: gcc
install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh
- os: linux
dist: xenial
compiler: clang
install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh
- os: linux
compiler: gcc
env: BUILD_TYPE=Debug VERBOSE=1 CXX_FLAGS=-std=c++11
- os: linux
compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 -Wgnu-zero-variadic-macro-arguments
- os: linux
compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 NO_EXCEPTION=ON NO_RTTI=ON COMPILER_IS_GNUCXX=ON
- os: osx
compiler: gcc
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
- os: osx
compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
# These are the install and build (script) phases for the most common entries in the matrix. They could be included
# in each entry in the matrix, but that is just repetitive.
install:
- ./ci/install-${TRAVIS_OS_NAME}.sh
- . ./ci/env-${TRAVIS_OS_NAME}.sh
- ./ci/log-config.sh
script: ./ci/travis.sh
# This section installs the necessary dependencies.
addons:
apt:
# List of whitelisted in travis packages for ubuntu-precise can be found here:
# https://github.com/travis-ci/apt-package-whitelist/blob/master/ubuntu-precise
# List of whitelisted in travis apt-sources:
# https://github.com/travis-ci/apt-source-whitelist/blob/master/ubuntu.json
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.9
packages:
- g++-4.9
- clang-3.9
update: true
homebrew:
packages:
- ccache
- gcc@4.9
- llvm@4
update: true
notifications:
email: false

@ -36,9 +36,19 @@ package(default_visibility = ["//visibility:public"])
licenses(["notice"]) licenses(["notice"])
exports_files(["LICENSE"])
config_setting( config_setting(
name = "windows", name = "windows",
constraint_values = ["@bazel_tools//platforms:windows"], constraint_values = ["@platforms//os:windows"],
)
config_setting(
name = "msvc_compiler",
flag_values = {
"@bazel_tools//tools/cpp:compiler": "msvc-cl",
},
visibility = [":__subpackages__"],
) )
config_setting( config_setting(
@ -103,6 +113,7 @@ cc_library(
"@com_google_absl//absl/debugging:stacktrace", "@com_google_absl//absl/debugging:stacktrace",
"@com_google_absl//absl/debugging:symbolize", "@com_google_absl//absl/debugging:symbolize",
"@com_google_absl//absl/strings", "@com_google_absl//absl/strings",
"@com_google_absl//absl/types:any",
"@com_google_absl//absl/types:optional", "@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:variant", "@com_google_absl//absl/types:variant",
], ],

@ -1,21 +1,17 @@
# 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 2.8.8) cmake_minimum_required(VERSION 2.8.12)
if (POLICY CMP0048) if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW) cmake_policy(SET CMP0048 NEW)
endif (POLICY CMP0048) endif (POLICY CMP0048)
project(googletest-distribution) project(googletest-distribution)
set(GOOGLETEST_VERSION 1.10.0) set(GOOGLETEST_VERSION 1.11.0)
if (CMAKE_VERSION VERSION_LESS "3.1") if (CMAKE_VERSION VERSION_GREATER "3.0.2")
add_definitions(-std=c++11) if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
else()
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(NOT CYGWIN)
set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_EXTENSIONS OFF)
endif() endif()
endif() endif()

@ -28,7 +28,7 @@ PR is acceptable as an alternative.
## Contributing A Patch ## Contributing A Patch
1. Submit an issue describing your proposed change to the 1. Submit an issue describing your proposed change to the
[issue tracker](https://github.com/google/googletest). [issue tracker](https://github.com/google/googletest/issues).
2. Please don't mix more than one logical change per submittal, because it 2. Please don't mix more than one logical change per submittal, because it
makes the history hard to follow. If you want to make a change that doesn't makes the history hard to follow. If you want to make a change that doesn't
have a corresponding issue in the issue tracker, please create one. have a corresponding issue in the issue tracker, please create one.
@ -80,7 +80,7 @@ fairly rigid coding style, as defined by the
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/master/.clang-format)
to check your formatting to check your formatting.
## Requirements for Contributors ## Requirements for Contributors
@ -89,7 +89,7 @@ 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/) v2.3 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.6.4 or newer * [CMake](https://cmake.org/) v2.8.12 or newer
## Developing Google Test and Google Mock ## Developing Google Test and Google Mock
@ -128,15 +128,3 @@ To run the tests, do
make test make test
All tests should pass. All tests should pass.
### Regenerating Source Files
Some of Google Test's source files are generated from templates (not in the C++
sense) using a script. For example, the file
include/gtest/internal/gtest-type-util.h.pump is used to generate
gtest-type-util.h in the same directory.
You don't need to worry about regenerating the source files unless you need to
modify them. You would then modify the corresponding `.pump` files and run the
'[pump.py](googletest/scripts/pump.py)' generator script. See the
[Pump Manual](googletest/docs/pump_manual.md).

@ -1,48 +1,44 @@
# Google Test # GoogleTest
#### OSS Builds Status: ### Announcements
[![Build Status](https://api.travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest) #### Live at Head
[![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master)
### Future Plans GoogleTest now follows the
[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
We recommend using the latest commit in the `master` branch in your projects.
#### 1.8.x Release: #### Documentation Updates
[the 1.8.x](https://github.com/google/googletest/releases/tag/release-1.8.1) is Our documentation is now live on GitHub Pages at
the last release that works with pre-C++11 compilers. The 1.8.x will not accept https://google.github.io/googletest/. We recommend browsing the documentation on
any requests for any new features and any bugfix requests will only be accepted GitHub Pages rather than directly in the repository.
if proven "critical"
#### Post 1.8.x: #### Release 1.10.x
On-going work to improve/cleanup/pay technical debt. When this work is completed [Release 1.10.x](https://github.com/google/googletest/releases/tag/release-1.10.0)
there will be a 1.9.x tagged release is now available.
#### Post 1.9.x #### Coming Soon
Post 1.9.x googletest will follow * We are planning to take a dependency on
[Abseil Live at Head philosophy](https://abseil.io/about/philosophy) [Abseil](https://github.com/abseil/abseil-cpp).
* More documentation improvements are planned.
## Welcome to **Google Test**, Google's C++ test framework! ## Welcome to **GoogleTest**, Google's C++ test framework!
This repository is a merger of the formerly separate GoogleTest and GoogleMock This repository is a merger of the formerly separate GoogleTest and GoogleMock
projects. These were so closely related that it makes sense to maintain and projects. These were so closely related that it makes sense to maintain and
release them together. release them together.
Please subscribe to the mailing list at googletestframework@googlegroups.com for ### Getting Started
questions, discussions, and development.
### Getting started: See the [GoogleTest User's Guide](https://google.github.io/googletest/) for
documentation. We recommend starting with the
[GoogleTest Primer](https://google.github.io/googletest/primer.html).
The information for **Google Test** is available in the More information about building GoogleTest can be found at
[Google Test Primer](googletest/docs/primer.md) documentation. [googletest/README.md](googletest/README.md).
**Google Mock** is an extension to Google Test for writing and using C++ mock
classes. See the separate [Google Mock documentation](googlemock/README.md).
More detailed documentation for googletest is in its interior
[googletest/README.md](googletest/README.md) file.
## Features ## Features
@ -57,22 +53,45 @@ More detailed documentation for googletest is in its interior
* Various options for running the tests. * Various options for running the tests.
* XML test report generation. * XML test report generation.
## Platforms ## Supported Platforms
GoogleTest requires a codebase and compiler compliant with the C++11 standard or
newer.
The GoogleTest code is officially supported on the following platforms.
Operating systems or tools not listed below are community-supported. For
community-supported platforms, patches that do not complicate the code may be
considered.
Google test has been used on a variety of platforms: 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 * Linux
* Mac OS X * macOS
* Windows * Windows
* Cygwin
* MinGW
* Windows Mobile
* Symbian
* PlatformIO
## Who Is Using Google Test? ### Compilers
* gcc 5.0+
* clang 5.0+
* MSVC 2015+
**macOS users:** Xcode 9.3+ provides clang 5.0+.
### Build Systems
In addition to many internal projects at Google, Google Test is also used by the * [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?
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](http://www.chromium.org/) (behind the Chrome browser
@ -81,8 +100,6 @@ following notable projects:
* [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](http://opencv.org/) computer vision library.
* [tiny-dnn](https://github.com/tiny-dnn/tiny-dnn): header only,
dependency-free deep learning framework in C++11.
## Related Open Source Projects ## Related Open Source Projects
@ -90,13 +107,13 @@ following notable projects:
automated test-runner and Graphical User Interface with powerful features for automated test-runner and Graphical User Interface with powerful features for
Windows and Linux platforms. Windows and Linux platforms.
[Google Test UI](https://github.com/ospector/gtest-gbar) is test runner that [GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that
runs your test binary, allows you to track its progress via a progress bar, and runs your test binary, allows you to track its progress via a progress bar, and
displays a list of test failures. Clicking on one shows failure text. Google displays a list of test failures. Clicking on one shows failure text. Google
Test UI is written in C#. Test UI is written in C#.
[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event [GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event
listener for Google Test that implements the listener for GoogleTest that implements the
[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test [TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test
result output. If your test runner understands TAP, you may find it useful. result output. If your test runner understands TAP, you may find it useful.
@ -104,31 +121,20 @@ result output. If your test runner understands TAP, you may find it useful.
runs tests from your binary in parallel to provide significant speed-up. runs tests from your binary in parallel to provide significant speed-up.
[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) [GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter)
is a VS Code extension allowing to view Google Tests in a tree view, and is a VS Code extension allowing to view GoogleTest in a tree view, and run/debug
run/debug your tests. your tests.
## Requirements
Google Test is designed to have fairly minimal requirements to build and use
with your projects, but there are some. If you notice any problems on your
platform, please notify
[googletestframework@googlegroups.com](https://groups.google.com/forum/#!forum/googletestframework).
Patches for fixing them are welcome!
### Build Requirements
These are the base requirements to build and use Google Test from a source
package:
* [Bazel](https://bazel.build/) or [CMake](https://cmake.org/). NOTE: Bazel is [C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS
the build system that googletest is using internally and tests against. Code extension allowing to view GoogleTest in a tree view, and run/debug your
CMake is community-supported. tests.
* a C++11-standard-compliant compiler [Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser
that generates stub code for GoogleTest.
## Contributing change ## Contributing Changes
Please read the [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on how to Please read
contribute to this project. [`CONTRIBUTING.md`](https://github.com/google/googletest/blob/master/CONTRIBUTING.md)
for details on how to contribute to this project.
Happy testing! Happy testing!

@ -2,22 +2,23 @@ workspace(name = "com_google_googletest")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# Abseil
http_archive( http_archive(
name = "com_google_absl", name = "com_google_absl",
urls = ["https://github.com/abseil/abseil-cpp/archive/master.zip"], urls = ["https://github.com/abseil/abseil-cpp/archive/7971fb358ae376e016d2d4fc9327aad95659b25e.zip"], # 2021-05-20T02:59:16Z
strip_prefix = "abseil-cpp-master", strip_prefix = "abseil-cpp-7971fb358ae376e016d2d4fc9327aad95659b25e",
sha256 = "aeba534f7307e36fe084b452299e49b97420667a8d28102cf9a0daeed340b859",
) )
http_archive( http_archive(
name = "rules_cc", name = "rules_cc",
strip_prefix = "rules_cc-master", urls = ["https://github.com/bazelbuild/rules_cc/archive/68cb652a71e7e7e2858c50593e5a9e3b94e5b9a9.zip"], # 2021-05-14T14:51:14Z
urls = ["https://github.com/bazelbuild/rules_cc/archive/master.zip"], strip_prefix = "rules_cc-68cb652a71e7e7e2858c50593e5a9e3b94e5b9a9",
sha256 = "1e19e9a3bc3d4ee91d7fcad00653485ee6c798efbbf9588d40b34cbfbded143d",
) )
http_archive( http_archive(
name = "rules_python", name = "rules_python",
strip_prefix = "rules_python-master", urls = ["https://github.com/bazelbuild/rules_python/archive/ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2.zip"], # 2021-05-17T00:24:16Z
urls = ["https://github.com/bazelbuild/rules_python/archive/master.zip"], strip_prefix = "rules_python-ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2",
sha256 = "98b3c592faea9636ac8444bfd9de7f3fb4c60590932d6e6ac5946e3f8dbd5ff6",
) )

@ -1,154 +0,0 @@
version: '{build}'
os: Visual Studio 2015
environment:
matrix:
- compiler: msvc-15-seh
generator: "Visual Studio 15 2017"
build_system: cmake
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
- compiler: msvc-15-seh
generator: "Visual Studio 15 2017 Win64"
build_system: cmake
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
enabled_on_pr: yes
- compiler: msvc-15-seh
build_system: bazel
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
enabled_on_pr: yes
- compiler: msvc-14-seh
build_system: cmake
generator: "Visual Studio 14 2015"
enabled_on_pr: yes
- compiler: msvc-14-seh
build_system: cmake
generator: "Visual Studio 14 2015 Win64"
- compiler: gcc-6.3.0-posix
build_system: cmake
generator: "MinGW Makefiles"
cxx_path: 'C:\mingw-w64\i686-6.3.0-posix-dwarf-rt_v5-rev1\mingw32\bin'
enabled_on_pr: yes
configuration:
- Debug
build:
verbosity: minimal
install:
- ps: |
Write-Output "Compiler: $env:compiler"
Write-Output "Generator: $env:generator"
Write-Output "Env:Configuation: $env:configuration"
Write-Output "Env: $env"
if (-not (Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER)) {
Write-Output "This is *NOT* a pull request build"
} else {
Write-Output "This is a pull request build"
if (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes") {
Write-Output "PR builds are *NOT* explicitly enabled"
}
}
# install Bazel
if ($env:build_system -eq "bazel") {
appveyor DownloadFile https://github.com/bazelbuild/bazel/releases/download/0.28.1/bazel-0.28.1-windows-x86_64.exe -FileName bazel.exe
}
if ($env:build_system -eq "cmake") {
# git bash conflicts with MinGW makefiles
if ($env:generator -eq "MinGW Makefiles") {
$env:path = $env:path.replace("C:\Program Files\Git\usr\bin;", "")
if ($env:cxx_path -ne "") {
$env:path += ";$env:cxx_path"
}
}
}
before_build:
- ps: |
$env:root=$env:APPVEYOR_BUILD_FOLDER
Write-Output "env:root: $env:root"
build_script:
- ps: |
# Only enable some builds for pull requests, the AppVeyor queue is too long.
if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) {
return
} else {
# special case - build with Bazel
if ($env:build_system -eq "bazel") {
& $env:root\bazel.exe build -c opt //:gtest_samples
if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error
$host.SetShouldExit(0)
} else { # a real error
throw "Exec: $ErrorMessage"
}
return
}
}
# by default build with CMake
md _build -Force | Out-Null
cd _build
$conf = if ($env:generator -eq "MinGW Makefiles") {"-DCMAKE_BUILD_TYPE=$env:configuration"} else {"-DCMAKE_CONFIGURATION_TYPES=Debug;Release"}
# Disable test for MinGW (gtest tests fail, gmock tests can not build)
$gtest_build_tests = if ($env:generator -eq "MinGW Makefiles") {"-Dgtest_build_tests=OFF"} else {"-Dgtest_build_tests=ON"}
$gmock_build_tests = if ($env:generator -eq "MinGW Makefiles") {"-Dgmock_build_tests=OFF"} else {"-Dgmock_build_tests=ON"}
& cmake -G "$env:generator" $conf -Dgtest_build_samples=ON $gtest_build_tests $gmock_build_tests ..
if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage"
}
$cmake_parallel = if ($env:generator -eq "MinGW Makefiles") {"-j2"} else {"/m"}
& cmake --build . --config $env:configuration -- $cmake_parallel
if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage"
}
skip_commits:
files:
- '**/*.md'
test_script:
- ps: |
# Only enable some builds for pull requests, the AppVeyor queue is too long.
if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) {
return
}
if ($env:build_system -eq "bazel") {
# special case - testing with Bazel
& $env:root\bazel.exe test //:gtest_samples
if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error
$host.SetShouldExit(0)
} else { # a real error
throw "Exec: $ErrorMessage"
}
}
if ($env:build_system -eq "cmake") {
# built with CMake - test with CTest
if ($env:generator -eq "MinGW Makefiles") {
return # No test available for MinGW
}
& ctest -C $env:configuration --timeout 600 --output-on-failure
if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage"
}
}
artifacts:
- path: '_build/CMakeFiles/*.log'
name: logs
- path: '_build/Testing/**/*.xml'
name: test_results
- path: 'bazel-testlogs/**/test.log'
name: test_logs
- path: 'bazel-testlogs/**/test.xml'
name: test_results

@ -1,37 +0,0 @@
#!/usr/bin/env bash
# Copyright 2017 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.
set -e
bazel version
bazel build --curses=no //...:all
bazel test --curses=no //...:all
bazel test --curses=no //...:all --define absl=1

@ -1,2 +0,0 @@
# run PlatformIO builds
platformio run

@ -1,41 +0,0 @@
#!/usr/bin/env bash
# Copyright 2017 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.
#
# This file should be sourced, and not executed as a standalone script.
#
# TODO() - we can check if this is being sourced using $BASH_VERSION and $BASH_SOURCE[0] != ${0}.
if [ "${TRAVIS_OS_NAME}" = "linux" ]; then
if [ "$CXX" = "g++" ]; then export CXX="g++-4.9" CC="gcc-4.9"; fi
if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.9" CC="clang-3.9"; fi
fi

@ -1,47 +0,0 @@
#!/usr/bin/env bash
# Copyright 2017 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.
#
# This file should be sourced, and not executed as a standalone script.
#
# TODO() - we can check if this is being sourced using $BASH_VERSION and $BASH_SOURCE[0] != ${0}.
#
if [ "${TRAVIS_OS_NAME}" = "osx" ]; then
if [ "$CXX" = "clang++" ]; then
# $PATH needs to be adjusted because the llvm tap doesn't install the
# package to /usr/local/bin, etc, like the gcc tap does.
# See: https://github.com/Homebrew/legacy-homebrew/issues/29733
clang_version=3.9
export PATH="/usr/local/opt/llvm@${clang_version}/bin:$PATH";
fi
fi

@ -1,48 +0,0 @@
#!/usr/bin/env bash
# Copyright 2017 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.
# This file is typically sourced by another script.
# if possible, ask for the precise number of processors,
# otherwise take 2 processors as reasonable default; see
# https://docs.travis-ci.com/user/speeding-up-the-build/#Makefile-optimization
if [ -x /usr/bin/getconf ]; then
NPROCESSORS=$(/usr/bin/getconf _NPROCESSORS_ONLN)
else
NPROCESSORS=2
fi
# as of 2017-09-04 Travis CI reports 32 processors, but GCC build
# crashes if parallelized too much (maybe memory consumption problem),
# so limit to 4 processors for the time being.
if [ $NPROCESSORS -gt 4 ] ; then
echo "$0:Note: Limiting processors to use by make from $NPROCESSORS to 4."
NPROCESSORS=4
fi

@ -1,49 +0,0 @@
#!/usr/bin/env bash
# Copyright 2017 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.
set -eu
if [ "${TRAVIS_OS_NAME}" != linux ]; then
echo "Not a Linux build; skipping installation"
exit 0
fi
if [ "${TRAVIS_SUDO}" = "true" ]; then
echo "deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8" | \
sudo tee /etc/apt/sources.list.d/bazel.list
curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add -
sudo apt-get update && sudo apt-get install -y bazel gcc-4.9 g++-4.9 clang-3.9
elif [ "${CXX}" = "clang++" ]; then
# Use ccache, assuming $HOME/bin is in the path, which is true in the Travis build environment.
ln -sf /usr/bin/ccache $HOME/bin/${CXX};
ln -sf /usr/bin/ccache $HOME/bin/${CC};
fi

@ -1,40 +0,0 @@
#!/usr/bin/env bash
# Copyright 2017 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.
set -eu
if [ "${TRAVIS_OS_NAME}" != "osx" ]; then
echo "Not a macOS build; skipping installation"
exit 0
fi
brew update
brew install ccache gcc@4.9

@ -1,5 +0,0 @@
# install PlatformIO
sudo pip install -U platformio
# update PlatformIO
platformio update

@ -1,51 +0,0 @@
#!/usr/bin/env bash
# Copyright 2017 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.
set -e
# ccache on OS X needs installation first
# reset ccache statistics
ccache --zero-stats
echo PATH=${PATH}
echo "Compiler configuration:"
echo CXX=${CXX}
echo CC=${CC}
echo CXXFLAGS=${CXXFLAGS}
echo "C++ compiler version:"
${CXX} --version || echo "${CXX} does not seem to support the --version flag"
${CXX} -v || echo "${CXX} does not seem to support the -v flag"
echo "C compiler version:"
${CC} --version || echo "${CXX} does not seem to support the --version flag"
${CC} -v || echo "${CXX} does not seem to support the -v flag"

@ -1,44 +0,0 @@
#!/usr/bin/env sh
set -evx
. ci/get-nprocessors.sh
# if possible, ask for the precise number of processors,
# otherwise take 2 processors as reasonable default; see
# https://docs.travis-ci.com/user/speeding-up-the-build/#Makefile-optimization
if [ -x /usr/bin/getconf ]; then
NPROCESSORS=$(/usr/bin/getconf _NPROCESSORS_ONLN)
else
NPROCESSORS=2
fi
# as of 2017-09-04 Travis CI reports 32 processors, but GCC build
# crashes if parallelized too much (maybe memory consumption problem),
# so limit to 4 processors for the time being.
if [ $NPROCESSORS -gt 4 ] ; then
echo "$0:Note: Limiting processors to use by make from $NPROCESSORS to 4."
NPROCESSORS=4
fi
# Tell make to use the processors. No preceding '-' required.
MAKEFLAGS="j${NPROCESSORS}"
export MAKEFLAGS
env | sort
# Set default values to OFF for these variables if not specified.
: "${NO_EXCEPTION:=OFF}"
: "${NO_RTTI:=OFF}"
: "${COMPILER_IS_GNUCXX:=OFF}"
mkdir build || true
cd build
cmake -Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=$NO_EXCEPTION \
-Dcxx_no_rtti=$NO_RTTI \
-DCMAKE_COMPILER_IS_GNUCXX=$COMPILER_IS_GNUCXX \
-DCMAKE_CXX_FLAGS=$CXX_FLAGS \
-DCMAKE_BUILD_TYPE=$BUILD_TYPE \
..
make
CTEST_OUTPUT_ON_FAILURE=1 make test

@ -42,7 +42,7 @@ else()
cmake_policy(SET CMP0048 NEW) cmake_policy(SET CMP0048 NEW)
project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
endif() endif()
cmake_minimum_required(VERSION 2.6.4) cmake_minimum_required(VERSION 2.8.12)
if (COMMAND set_up_hermetic_build) if (COMMAND set_up_hermetic_build)
set_up_hermetic_build() set_up_hermetic_build()
@ -100,8 +100,10 @@ if (MSVC)
else() else()
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc) cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
target_link_libraries(gmock PUBLIC gtest) target_link_libraries(gmock PUBLIC gtest)
set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION})
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc) cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
target_link_libraries(gmock_main PUBLIC gmock) target_link_libraries(gmock_main PUBLIC gmock)
set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
endif() endif()
# If the CMake version supports it, attach header directory information # 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 # to the targets for when we are part of a parent build (ie being pulled
@ -136,20 +138,6 @@ if (gmock_build_tests)
# 'make test' or ctest. # 'make test' or ctest.
enable_testing() enable_testing()
if (WIN32)
file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1"
CONTENT
"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$<CONFIG>\"
$env:Path = \"$project_bin;$env:Path\"
& $args")
elseif (MINGW OR CYGWIN)
file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1"
CONTENT
"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin)
$env:Path = \"$project_bin;$env:Path\"
& $args")
endif()
if (MINGW OR CYGWIN) if (MINGW OR CYGWIN)
if (CMAKE_VERSION VERSION_LESS "2.8.12") if (CMAKE_VERSION VERSION_LESS "2.8.12")
add_compile_options("-Wa,-mbig-obj") add_compile_options("-Wa,-mbig-obj")
@ -165,9 +153,6 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_test(gmock-cardinalities_test gmock_main) cxx_test(gmock-cardinalities_test gmock_main)
cxx_test(gmock_ex_test gmock_main) cxx_test(gmock_ex_test gmock_main)
cxx_test(gmock-function-mocker_test gmock_main) cxx_test(gmock-function-mocker_test gmock_main)
cxx_test(gmock-generated-actions_test gmock_main)
cxx_test(gmock-generated-function-mockers_test gmock_main)
cxx_test(gmock-generated-matchers_test gmock_main)
cxx_test(gmock-internal-utils_test gmock_main) cxx_test(gmock-internal-utils_test gmock_main)
cxx_test(gmock-matchers_test gmock_main) cxx_test(gmock-matchers_test gmock_main)
cxx_test(gmock-more-actions_test gmock_main) cxx_test(gmock-more-actions_test gmock_main)

@ -1,40 +0,0 @@
# This file contains a list of people who've made non-trivial
# contribution to the Google C++ Mocking Framework project. People
# who commit code to the project are encouraged to add their names
# here. Please keep the list sorted by first names.
Benoit Sigoure <tsuna@google.com>
Bogdan Piloca <boo@google.com>
Chandler Carruth <chandlerc@google.com>
Dave MacLachlan <dmaclach@gmail.com>
David Anderson <danderson@google.com>
Dean Sturtevant
Gene Volovich <gv@cite.com>
Hal Burch <gmock@hburch.com>
Jeffrey Yasskin <jyasskin@google.com>
Jim Keller <jimkeller@google.com>
Joe Walnes <joe@truemesh.com>
Jon Wray <jwray@google.com>
Keir Mierle <mierle@gmail.com>
Keith Ray <keith.ray@gmail.com>
Kostya Serebryany <kcc@google.com>
Lev Makhlis
Manuel Klimek <klimek@google.com>
Mario Tanev <radix@google.com>
Mark Paskin
Markus Heule <markus.heule@gmail.com>
Matthew Simmons <simmonmt@acm.org>
Mike Bland <mbland@google.com>
Neal Norwitz <nnorwitz@gmail.com>
Nermin Ozkiranartli <nermin@google.com>
Owen Carlsen <ocarlsen@google.com>
Paneendra Ba <paneendra@google.com>
Paul Menage <menage@google.com>
Piotr Kaminski <piotrk@google.com>
Russ Rufer <russ@pentad.com>
Sverre Sundsdal <sundsdal@gmail.com>
Takeshi Yoshino <tyoshino@google.com>
Vadim Berman <vadimb@google.com>
Vlad Losev <vladl@google.com>
Wolfgang Klier <wklier@google.com>
Zhanyong Wan <wan@google.com>

@ -1,28 +0,0 @@
Copyright 2008, 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.

@ -7,38 +7,38 @@ 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/), and * [EasyMock](http://www.easymock.org/)
* [Hamcrest](http://code.google.com/p/hamcrest/), * [Hamcrest](http://code.google.com/p/hamcrest/)
and designed with C++'s specifics in mind. It is designed with C++'s specifics in mind.
gMock: gMock:
- provides a declarative syntax for defining mocks, - Provides a declarative syntax for defining mocks.
- can define partial (hybrid) mocks, which are a cross of real and mock - Can define partial (hybrid) mocks, which are a cross of real and mock
objects, objects.
- handles functions of arbitrary types and overloaded functions, - Handles functions of arbitrary types and overloaded functions.
- comes with a rich set of matchers for validating function arguments, - Comes with a rich set of matchers for validating function arguments.
- uses an intuitive syntax for controlling the behavior of a mock, - Uses an intuitive syntax for controlling the behavior of a mock.
- does automatic verification of expectations (no record-and-replay needed), - Does automatic verification of expectations (no record-and-replay needed).
- allows arbitrary (partial) ordering constraints on function calls to be - Allows arbitrary (partial) ordering constraints on function calls to be
expressed, expressed.
- lets a user extend it by defining new matchers and actions. - Lets a user extend it by defining new matchers and actions.
- does not use exceptions, and - Does not use exceptions.
- is easy to learn and use. - Is easy to learn and use.
Details and examples can be found here: Details and examples can be found here:
* [gMock for Dummies](docs/for_dummies.md) * [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html)
* [Legacy gMock FAQ](docs/gmock_faq.md) * [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html)
* [gMock Cookbook](docs/cook_book.md) * [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html)
* [gMock Cheat Sheet](docs/cheat_sheet.md) * [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html)
Please note that code under scripts/generator/ is from the [cppclean Please note that code under scripts/generator/ is from the
project](http://code.google.com/p/cppclean/) and under the Apache [cppclean project](http://code.google.com/p/cppclean/) and under the Apache
License, which is different from Google Mock's license. License, which is different from GoogleMock's license.
Google Mock is a part of GoogleMock is a part of
[Google Test C++ testing framework](http://github.com/google/googletest/) and a [GoogleTest C++ testing framework](http://github.com/google/googletest/) and a
subject to the same requirements. subject to the same requirements.

@ -1,11 +1,10 @@
prefix=${pcfiledir}/../.. libdir=@CMAKE_INSTALL_FULL_LIBDIR@
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
Name: gmock Name: gmock
Description: GoogleMock (without main() function) Description: GoogleMock (without main() function)
Version: @PROJECT_VERSION@ Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest URL: https://github.com/google/googletest
Requires: gtest Requires: gtest = @PROJECT_VERSION@
Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@

@ -1,11 +1,10 @@
prefix=${pcfiledir}/../.. libdir=@CMAKE_INSTALL_FULL_LIBDIR@
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
Name: gmock_main Name: gmock_main
Description: GoogleMock (with main() function) Description: GoogleMock (with main() function)
Version: @PROJECT_VERSION@ Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest URL: https://github.com/google/googletest
Requires: gmock Requires: gmock = @PROJECT_VERSION@
Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@

@ -1,781 +0,0 @@
## gMock Cheat Sheet
<!-- GOOGLETEST_CM0019 DO NOT DELETE -->
<!-- GOOGLETEST_CM0033 DO NOT DELETE -->
### Defining a Mock Class
#### Mocking a Normal Class {#MockClass}
Given
```cpp
class Foo {
...
virtual ~Foo();
virtual int GetSize() const = 0;
virtual string Describe(const char* name) = 0;
virtual string Describe(int type) = 0;
virtual bool Process(Bar elem, int count) = 0;
};
```
(note that `~Foo()` **must** be virtual) we can define its mock as
```cpp
#include "gmock/gmock.h"
class MockFoo : public Foo {
...
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(string, Describe, (const char* name), (override));
MOCK_METHOD(string, Describe, (int type), (override));
MOCK_METHOD(bool, Process, (Bar elem, int count), (override));
};
```
To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
which warns on all uninteresting calls, or a "strict" mock, which treats them as
failures:
```cpp
using ::testing::NiceMock;
using ::testing::NaggyMock;
using ::testing::StrictMock;
NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo.
StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
```
**Note:** A mock object is currently naggy by default. We may make it nice by
default in the future.
#### Mocking a Class Template {#MockTemplate}
Class templates can be mocked just like any class.
To mock
```cpp
template <typename Elem>
class StackInterface {
...
virtual ~StackInterface();
virtual int GetSize() const = 0;
virtual void Push(const Elem& x) = 0;
};
```
(note that all member functions that are mocked, including `~StackInterface()`
**must** be virtual).
```cpp
template <typename Elem>
class MockStack : public StackInterface<Elem> {
...
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(void, Push, (const Elem& x), (override));
};
```
#### Specifying Calling Conventions for Mock Functions
If your mock function doesn't use the default calling convention, you can
specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
For example,
```cpp
MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
MOCK_METHOD(int, Bar, (double x, double y),
(const, Calltype(STDMETHODCALLTYPE)));
```
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
### Using Mocks in Tests {#UsingMocks}
The typical work flow is:
1. Import the gMock names you need to use. All gMock symbols are in the
`testing` namespace unless they are macros or otherwise noted.
2. Create the mock objects.
3. Optionally, set the default actions of the mock objects.
4. Set your expectations on the mock objects (How will they be called? What
will they do?).
5. Exercise code that uses the mock objects; if necessary, check the result
using googletest assertions.
6. When a mock object is destructed, gMock automatically verifies that all
expectations on it have been satisfied.
Here's an example:
```cpp
using ::testing::Return; // #1
TEST(BarTest, DoesThis) {
MockFoo foo; // #2
ON_CALL(foo, GetSize()) // #3
.WillByDefault(Return(1));
// ... other default actions ...
EXPECT_CALL(foo, Describe(5)) // #4
.Times(3)
.WillRepeatedly(Return("Category 5"));
// ... other expectations ...
EXPECT_EQ("good", MyProductionFunction(&foo)); // #5
} // #6
```
### Setting Default Actions {#OnCall}
gMock has a **built-in default action** for any function that returns `void`,
`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
the default-constructed value, if one exists for the given type.
To customize the default action for functions with return type *`T`*:
```cpp
using ::testing::DefaultValue;
// Sets the default value to be returned. T must be CopyConstructible.
DefaultValue<T>::Set(value);
// Sets a factory. Will be invoked on demand. T must be MoveConstructible.
// T MakeT();
DefaultValue<T>::SetFactory(&MakeT);
// ... use the mocks ...
// Resets the default value.
DefaultValue<T>::Clear();
```
Example usage:
```cpp
// Sets the default action for return type std::unique_ptr<Buzz> to
// creating a new Buzz every time.
DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
[] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
// When this fires, the default action of MakeBuzz() will run, which
// will return a new Buzz object.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
auto buzz1 = mock_buzzer_.MakeBuzz("hello");
auto buzz2 = mock_buzzer_.MakeBuzz("hello");
EXPECT_NE(nullptr, buzz1);
EXPECT_NE(nullptr, buzz2);
EXPECT_NE(buzz1, buzz2);
// Resets the default action for return type std::unique_ptr<Buzz>,
// to avoid interfere with other tests.
DefaultValue<std::unique_ptr<Buzz>>::Clear();
```
To customize the default action for a particular method of a specific mock
object, use `ON_CALL()`. `ON_CALL()` has a similar syntax to `EXPECT_CALL()`,
but it is used for setting default behaviors (when you do not require that the
mock method is called). See [here](cook_book.md#UseOnCall) for a more detailed
discussion.
```cpp
ON_CALL(mock-object, method(matchers))
.With(multi-argument-matcher) ?
.WillByDefault(action);
```
### Setting Expectations {#ExpectCall}
`EXPECT_CALL()` sets **expectations** on a mock method (How will it be called?
What will it do?):
```cpp
EXPECT_CALL(mock-object, method (matchers)?)
.With(multi-argument-matcher) ?
.Times(cardinality) ?
.InSequence(sequences) *
.After(expectations) *
.WillOnce(action) *
.WillRepeatedly(action) ?
.RetiresOnSaturation(); ?
```
For each item above, `?` means it can be used at most once, while `*` means it
can be used any number of times.
In order to pass, `EXPECT_CALL` must be used before the calls are actually made.
The `(matchers)` is a comma-separated list of matchers that correspond to each
of the arguments of `method`, and sets the expectation only for calls of
`method` that matches all of the matchers.
If `(matchers)` is omitted, the expectation is the same as if the matchers were
set to anything matchers (for example, `(_, _, _, _)` for a four-arg method).
If `Times()` is omitted, the cardinality is assumed to be:
* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
* `Times(n)` when there are `n` `WillOnce()`s but no `WillRepeatedly()`, where
`n` >= 1; or
* `Times(AtLeast(n))` when there are `n` `WillOnce()`s and a
`WillRepeatedly()`, where `n` >= 0.
A method with no `EXPECT_CALL()` is free to be invoked *any number of times*,
and the default action will be taken each time.
### Matchers {#MatcherList}
<!-- GOOGLETEST_CM0020 DO NOT DELETE -->
A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
`EXPECT_CALL()`, or use it to validate a value directly using two macros:
<!-- mdformat off(github rendering does not support multiline tables) -->
| Macro | Description |
| :----------------------------------- | :------------------------------------ |
| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. |
| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. |
<!-- mdformat on -->
Built-in matchers (where `argument` is the function argument, e.g.
`actual_value` in the example above, or when used in the context of
`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are
divided into several categories:
#### Wildcard
Matcher | Description
:-------------------------- | :-----------------------------------------------
`_` | `argument` can be any value of the correct type.
`A<type>()` or `An<type>()` | `argument` can be any value of type `type`.
#### Generic Comparison
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :--------------------- | :-------------------------------------------------- |
| `Eq(value)` or `value` | `argument == value` |
| `Ge(value)` | `argument >= value` |
| `Gt(value)` | `argument > value` |
| `Le(value)` | `argument <= value` |
| `Lt(value)` | `argument < value` |
| `Ne(value)` | `argument != value` |
| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. |
| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. |
| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). |
| `NotNull()` | `argument` is a non-null pointer (raw or smart). |
| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. |
| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |
| `Ref(variable)` | `argument` is a reference to `variable`. |
| `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. |
<!-- mdformat on -->
Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or
destructed later. If the compiler complains that `value` doesn't have a public
copy constructor, try wrap it in `ByRef()`, e.g.
`Eq(ByRef(non_copyable_value))`. If you do that, make sure `non_copyable_value`
is not changed afterwards, or the meaning of your matcher will be changed.
#### Floating-Point Matchers {#FpMatchers}
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :------------------------------- | :--------------------------------- |
| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. |
| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. |
| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. |
| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. |
<!-- mdformat on -->
The above matchers use ULP-based comparison (the same as used in googletest).
They automatically pick a reasonable error bound based on the absolute value of
the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard,
which requires comparing two NaNs for equality to return false. The
`NanSensitive*` version instead treats two NaNs as equal, which is often what a
user wants.
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :------------------------------------------------ | :----------------------- |
| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
<!-- mdformat on -->
#### String Matchers
The `argument` can be either a C string or a C++ string object:
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :---------------------- | :------------------------------------------------- |
| `ContainsRegex(string)` | `argument` matches the given regular expression. |
| `EndsWith(suffix)` | `argument` ends with string `suffix`. |
| `HasSubstr(string)` | `argument` contains `string` as a sub-string. |
| `MatchesRegex(string)` | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. |
| `StartsWith(prefix)` | `argument` starts with string `prefix`. |
| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. |
| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. |
| `StrEq(string)` | `argument` is equal to `string`. |
| `StrNe(string)` | `argument` is not equal to `string`. |
<!-- mdformat on -->
`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
use the regular expression syntax defined
[here](../../googletest/docs/advanced.md#regular-expression-syntax).
`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide strings as
well.
#### Container Matchers
Most STL-style containers support `==`, so you can use `Eq(expected_container)`
or simply `expected_container` to match a container exactly. If you want to
write the elements in-line, match them more flexibly, or get more informative
messages, you can use:
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :---------------------------------------- | :------------------------------- |
| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. |
| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |
| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. |
| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. |
| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. |
| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
| `IsEmpty()` | `argument` is an empty container (`container.empty()`). |
| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. |
| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. |
| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. |
| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. |
| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. |
| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. |
| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. |
| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. |
<!-- mdformat on -->
**Notes:**
* These matchers can also match:
1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`),
and
2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer,
int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)).
* The array being matched may be multi-dimensional (i.e. its elements can be
arrays).
* `m` in `Pointwise(m, ...)` should be a matcher for `::std::tuple<T, U>`
where `T` and `U` are the element type of the actual container and the
expected container, respectively. For example, to compare two `Foo`
containers where `Foo` doesn't support `operator==`, one might write:
```cpp
using ::std::get;
MATCHER(FooEq, "") {
return std::get<0>(arg).Equals(std::get<1>(arg));
}
...
EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
```
#### Member Matchers
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :------------------------------ | :----------------------------------------- |
| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. |
| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. |
| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. |
| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. |
<!-- mdformat on -->
#### Matching the Result of a Function, Functor, or Callback
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :--------------- | :------------------------------------------------ |
| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. |
<!-- mdformat on -->
#### Pointer Matchers
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :------------------------ | :---------------------------------------------- |
| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. |
| `WhenDynamicCastTo<T>(m)` | when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. |
<!-- mdformat on -->
<!-- GOOGLETEST_CM0026 DO NOT DELETE -->
<!-- GOOGLETEST_CM0027 DO NOT DELETE -->
#### Multi-argument Matchers {#MultiArgMatchers}
Technically, all matchers match a *single* value. A "multi-argument" matcher is
just one that matches a *tuple*. The following matchers can be used to match a
tuple `(x, y)`:
Matcher | Description
:------ | :----------
`Eq()` | `x == y`
`Ge()` | `x >= y`
`Gt()` | `x > y`
`Le()` | `x <= y`
`Lt()` | `x < y`
`Ne()` | `x != y`
You can use the following selectors to pick a subset of the arguments (or
reorder them) to participate in the matching:
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :------------------------- | :---------------------------------------------- |
| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. |
| `Args<N1, N2, ..., Nk>(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. |
<!-- mdformat on -->
#### Composite Matchers
You can make a matcher from one or more other matchers:
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :------------------------------- | :-------------------------------------- |
| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. |
| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. |
| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
| `Not(m)` | `argument` doesn't match matcher `m`. |
<!-- mdformat on -->
<!-- GOOGLETEST_CM0028 DO NOT DELETE -->
#### Adapters for Matchers
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :---------------------- | :------------------------------------ |
| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. |
| `SafeMatcherCast<T>(m)` | [safely casts](cook_book.md#casting-matchers) matcher `m` to type `Matcher<T>`. |
| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. |
<!-- mdformat on -->
`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`,
which must be a permanent callback.
#### Using Matchers as Predicates {#MatchersAsPredicatesCheat}
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :---------------------------- | :------------------------------------------ |
| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. |
| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. |
| `Value(value, m)` | evaluates to `true` if `value` matches `m`. |
<!-- mdformat on -->
#### Defining Matchers
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :----------------------------------- | :------------------------------------ |
| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. |
| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
<!-- mdformat on -->
**Notes:**
1. The `MATCHER*` macros cannot be used inside a function or class.
2. The matcher body must be *purely functional* (i.e. it cannot have any side
effect, and the result must not depend on anything other than the value
being matched and the matcher parameters).
3. You can use `PrintToString(x)` to convert a value `x` of any type to a
string.
### Actions {#ActionList}
**Actions** specify what a mock function should do when invoked.
#### Returning a Value
<!-- mdformat off(no multiline tables) -->
| | |
| :-------------------------- | :-------------------------------------------- |
| `Return()` | Return from a `void` mock function. |
| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed. |
| `ReturnArg<N>()` | Return the `N`-th (0-based) argument. |
| `ReturnNew<T>(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. |
| `ReturnNull()` | Return a null pointer. |
| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. |
| `ReturnRef(variable)` | Return a reference to `variable`. |
| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. |
<!-- mdformat on -->
#### Side Effects
<!-- mdformat off(no multiline tables) -->
| | |
| :--------------------------------- | :-------------------------------------- |
| `Assign(&variable, value)` | Assign `value` to variable. |
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. |
| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. |
| `SetArgumentPointee<N>(value)` | Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0. |
| `SetArrayArgument<N>(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. |
| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. |
| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. |
<!-- mdformat on -->
#### Using a Function, Functor, or Lambda as an Action
In the following, by "callable" we mean a free function, `std::function`,
functor, or lambda.
<!-- mdformat off(no multiline tables) -->
| | |
| :---------------------------------- | :------------------------------------- |
| `f` | Invoke f with the arguments passed to the mock function, where f is a callable. |
| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. |
| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. |
| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. |
| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. |
| `InvokeArgument<N>(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. |
<!-- mdformat on -->
The return value of the invoked function is used as the return value of the
action.
When defining a callable to be used with `Invoke*()`, you can declare any unused
parameters as `Unused`:
```cpp
using ::testing::Invoke;
double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
...
EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
```
`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of
`callback`, which must be permanent. The type of `callback` must be a base
callback type instead of a derived one, e.g.
```cpp
BlockingClosure* done = new BlockingClosure;
... Invoke(done) ...; // This won't compile!
Closure* done2 = new BlockingClosure;
... Invoke(done2) ...; // This works.
```
In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference,
wrap it inside `ByRef()`. For example,
```cpp
using ::testing::ByRef;
using ::testing::InvokeArgument;
...
InvokeArgument<2>(5, string("Hi"), ByRef(foo))
```
calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by
value, and `foo` by reference.
#### Default Action
<!-- mdformat off(no multiline tables) -->
| Matcher | Description |
| :------------ | :----------------------------------------------------- |
| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |
<!-- mdformat on -->
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a
composite action - trying to do so will result in a run-time error.
<!-- GOOGLETEST_CM0032 DO NOT DELETE -->
#### Composite Actions
<!-- mdformat off(no multiline tables) -->
| | |
| :----------------------------- | :------------------------------------------ |
| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. |
| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. |
| `WithArg<N>(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. |
| `WithArgs<N1, N2, ..., Nk>(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. |
| `WithoutArgs(a)` | Perform action `a` without any arguments. |
<!-- mdformat on -->
#### Defining Actions
<table border="1" cellspacing="0" cellpadding="1">
<tr>
<td>`struct SumAction {` <br>
&emsp;`template <typename T>` <br>
&emsp;`T operator()(T x, Ty) { return x + y; }` <br>
`};`
</td>
<td> Defines a generic functor that can be used as an action summing its
arguments. </td> </tr>
<tr>
</tr>
</table>
<!-- mdformat off(no multiline tables) -->
| | |
| :--------------------------------- | :-------------------------------------- |
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. |
<!-- mdformat on -->
The `ACTION*` macros cannot be used inside a function or class.
### Cardinalities {#CardinalityList}
These are used in `Times()` to specify how many times a mock function will be
called:
<!-- mdformat off(no multiline tables) -->
| | |
| :---------------- | :----------------------------------------------------- |
| `AnyNumber()` | The function can be called any number of times. |
| `AtLeast(n)` | The call is expected at least `n` times. |
| `AtMost(n)` | The call is expected at most `n` times. |
| `Between(m, n)` | The call is expected between `m` and `n` (inclusive) times. |
| `Exactly(n) or n` | The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0. |
<!-- mdformat on -->
### Expectation Order
By default, the expectations can be matched in *any* order. If some or all
expectations must be matched in a given order, there are two ways to specify it.
They can be used either independently or together.
#### The After Clause {#AfterClause}
```cpp
using ::testing::Expectation;
...
Expectation init_x = EXPECT_CALL(foo, InitX());
Expectation init_y = EXPECT_CALL(foo, InitY());
EXPECT_CALL(foo, Bar())
.After(init_x, init_y);
```
says that `Bar()` can be called only after both `InitX()` and `InitY()` have
been called.
If you don't know how many pre-requisites an expectation has when you write it,
you can use an `ExpectationSet` to collect them:
```cpp
using ::testing::ExpectationSet;
...
ExpectationSet all_inits;
for (int i = 0; i < element_count; i++) {
all_inits += EXPECT_CALL(foo, InitElement(i));
}
EXPECT_CALL(foo, Bar())
.After(all_inits);
```
says that `Bar()` can be called only after all elements have been initialized
(but we don't care about which elements get initialized before the others).
Modifying an `ExpectationSet` after using it in an `.After()` doesn't affect the
meaning of the `.After()`.
#### Sequences {#UsingSequences}
When you have a long chain of sequential expectations, it's easier to specify
the order using **sequences**, which don't require you to given each expectation
in the chain a different name. *All expected calls* in the same sequence must
occur in the order they are specified.
```cpp
using ::testing::Return;
using ::testing::Sequence;
Sequence s1, s2;
...
EXPECT_CALL(foo, Reset())
.InSequence(s1, s2)
.WillOnce(Return(true));
EXPECT_CALL(foo, GetSize())
.InSequence(s1)
.WillOnce(Return(1));
EXPECT_CALL(foo, Describe(A<const char*>()))
.InSequence(s2)
.WillOnce(Return("dummy"));
```
says that `Reset()` must be called before *both* `GetSize()` *and* `Describe()`,
and the latter two can occur in any order.
To put many expectations in a sequence conveniently:
```cpp
using ::testing::InSequence;
{
InSequence seq;
EXPECT_CALL(...)...;
EXPECT_CALL(...)...;
...
EXPECT_CALL(...)...;
}
```
says that all expected calls in the scope of `seq` must occur in strict order.
The name `seq` is irrelevant.
### Verifying and Resetting a Mock
gMock will verify the expectations on a mock object when it is destructed, or
you can do it earlier:
```cpp
using ::testing::Mock;
...
// Verifies and removes the expectations on mock_obj;
// returns true if and only if successful.
Mock::VerifyAndClearExpectations(&mock_obj);
...
// Verifies and removes the expectations on mock_obj;
// also removes the default actions set by ON_CALL();
// returns true if and only if successful.
Mock::VerifyAndClear(&mock_obj);
```
You can also tell gMock that a mock object can be leaked and doesn't need to be
verified:
```cpp
Mock::AllowLeak(&mock_obj);
```
### Mock Classes
gMock defines a convenient mock class template
```cpp
class MockFunction<R(A1, ..., An)> {
public:
MOCK_METHOD(R, Call, (A1, ..., An));
};
```
See this [recipe](cook_book.md#using-check-points) for one application of it.
### Flags
<!-- mdformat off(no multiline tables) -->
| Flag | Description |
| :----------------------------- | :---------------------------------------- |
| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
<!-- mdformat on -->

File diff suppressed because it is too large Load Diff

@ -1,700 +0,0 @@
## gMock for Dummies {#GMockForDummies}
<!-- GOOGLETEST_CM0013 DO NOT DELETE -->
### What Is gMock?
When you write a prototype or test, often it's not feasible or wise to rely on
real objects entirely. A **mock object** implements the same interface as a real
object (so it can be used as one), but lets you specify at run time how it will
be used and what it should do (which methods will be called? in which order? how
many times? with what arguments? what will they return? etc).
**Note:** It is easy to confuse the term *fake objects* with mock objects. Fakes
and mocks actually mean very different things in the Test-Driven Development
(TDD) community:
* **Fake** objects have working implementations, but usually take some
shortcut (perhaps to make the operations less expensive), which makes them
not suitable for production. An in-memory file system would be an example of
a fake.
* **Mocks** are objects pre-programmed with *expectations*, which form a
specification of the calls they are expected to receive.
If all this seems too abstract for you, don't worry - the most important thing
to remember is that a mock allows you to check the *interaction* between itself
and code that uses it. The difference between fakes and mocks shall become much
clearer once you start to use mocks.
**gMock** is a library (sometimes we also call it a "framework" to make it sound
cool) for creating mock classes and using them. It does to C++ what
jMock/EasyMock does to Java (well, more or less).
When using gMock,
1. first, you use some simple macros to describe the interface you want to
mock, and they will expand to the implementation of your mock class;
2. next, you create some mock objects and specify its expectations and behavior
using an intuitive syntax;
3. then you exercise code that uses the mock objects. gMock will catch any
violation to the expectations as soon as it arises.
### Why gMock?
While mock objects help you remove unnecessary dependencies in tests and make
them fast and reliable, using mocks manually in C++ is *hard*:
* Someone has to implement the mocks. The job is usually tedious and
error-prone. No wonder people go great distance to avoid it.
* The quality of those manually written mocks is a bit, uh, unpredictable. You
may see some really polished ones, but you may also see some that were
hacked up in a hurry and have all sorts of ad hoc restrictions.
* The knowledge you gained from using one mock doesn't transfer to the next
one.
In contrast, Java and Python programmers have some fine mock frameworks (jMock,
EasyMock, [Mox](http://wtf/mox), etc), which automate the creation of mocks. As
a result, mocking is a proven effective technique and widely adopted practice in
those communities. Having the right tool absolutely makes the difference.
gMock was built to help C++ programmers. It was inspired by jMock and EasyMock,
but designed with C++'s specifics in mind. It is your friend if any of the
following problems is bothering you:
* You are stuck with a sub-optimal design and wish you had done more
prototyping before it was too late, but prototyping in C++ is by no means
"rapid".
* Your tests are slow as they depend on too many libraries or use expensive
resources (e.g. a database).
* Your tests are brittle as some resources they use are unreliable (e.g. the
network).
* You want to test how your code handles a failure (e.g. a file checksum
error), but it's not easy to cause one.
* You need to make sure that your module interacts with other modules in the
right way, but it's hard to observe the interaction; therefore you resort to
observing the side effects at the end of the action, but it's awkward at
best.
* You want to "mock out" your dependencies, except that they don't have mock
implementations yet; and, frankly, you aren't thrilled by some of those
hand-written mocks.
We encourage you to use gMock as
* a *design* tool, for it lets you experiment with your interface design early
and often. More iterations lead to better designs!
* a *testing* tool to cut your tests' outbound dependencies and probe the
interaction between your module and its collaborators.
### Getting Started
gMock is bundled with googletest.
### A Case for Mock Turtles
Let's look at an example. Suppose you are developing a graphics program that
relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like
API for drawing. How would you test that it does the right thing? Well, you can
run it and compare the screen with a golden screen snapshot, but let's admit it:
tests like this are expensive to run and fragile (What if you just upgraded to a
shiny new graphics card that has better anti-aliasing? Suddenly you have to
update all your golden images.). It would be too painful if all your tests are
like this. Fortunately, you learned about
[Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing
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:
```cpp
class Turtle {
...
virtual ~Turtle() {};
virtual void PenUp() = 0;
virtual void PenDown() = 0;
virtual void Forward(int distance) = 0;
virtual void Turn(int degrees) = 0;
virtual void GoTo(int x, int y) = 0;
virtual int GetX() const = 0;
virtual int GetY() const = 0;
};
```
(Note that the destructor of `Turtle` **must** be virtual, as is the case for
**all** classes you intend to inherit from - otherwise the destructor of the
derived class will not be called when you delete an object through a base
pointer, and you'll get corrupted program states like memory leaks.)
You can control whether the turtle's movement will leave a trace using `PenUp()`
and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and
`GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the
turtle.
Your program will normally use a real implementation of this interface. In
tests, you can use a mock implementation instead. This allows you to easily
check what drawing primitives your program is calling, with what arguments, and
in which order. Tests written this way are much more robust (they won't break
because your new machine does anti-aliasing differently), easier to read and
maintain (the intent of a test is expressed in the code, not in some binary
images), and run *much, much faster*.
### Writing the Mock Class
If you are lucky, the mocks you need to use have already been implemented by
some nice people. If, however, you find yourself in the position to write a mock
class, relax - gMock turns this task into a fun game! (Well, almost.)
#### How to Define It
Using the `Turtle` interface as example, here are the simple steps you need to
follow:
* Derive a class `MockTurtle` from `Turtle`.
* Take a *virtual* function of `Turtle` (while it's possible to
[mock non-virtual methods using templates](cook_book.md#MockingNonVirtualMethods),
it's much more involved).
* In the `public:` section of the child class, write `MOCK_METHOD();`
* Now comes the fun part: you take the function signature, cut-and-paste it
into the macro, and add two commas - one between the return type and the
name, another between the name and the argument list.
* If you're mocking a const method, add a 4th parameter containing `(const)`
(the parentheses are required).
* Since you're overriding a virtual method, we suggest adding the `override`
keyword. For const methods the 4th parameter becomes `(const, override)`,
for non-const methods just `(override)`. This isn't mandatory.
* Repeat until all virtual functions you want to mock are done. (It goes
without saying that *all* pure virtual methods in your abstract class must
be either mocked or overridden.)
After the process, you should have something like:
```cpp
#include "gmock/gmock.h" // Brings in gMock.
class MockTurtle : public Turtle {
public:
...
MOCK_METHOD(void, PenUp, (), (override));
MOCK_METHOD(void, PenDown, (), (override));
MOCK_METHOD(void, Forward, (int distance), (override));
MOCK_METHOD(void, Turn, (int degrees), (override));
MOCK_METHOD(void, GoTo, (int x, int y), (override));
MOCK_METHOD(int, GetX, (), (const, override));
MOCK_METHOD(int, GetY, (), (const, override));
};
```
You don't need to define these mock methods somewhere else - the `MOCK_METHOD`
macro will generate the definitions for you. It's that simple!
#### Where to Put It
When you define a mock class, you need to decide where to put its definition.
Some people put it in a `_test.cc`. This is fine when the interface being mocked
(say, `Foo`) is owned by the same person or team. Otherwise, when the owner of
`Foo` changes it, your test could break. (You can't really expect `Foo`'s
maintainer to fix every test that uses `Foo`, can you?)
So, the rule of thumb is: if you need to mock `Foo` and it's owned by others,
define the mock class in `Foo`'s package (better, in a `testing` sub-package
such that you can clearly separate production code and testing utilities), put
it in a `.h` and a `cc_library`. Then everyone can reference them from their
tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and
only tests that depend on the changed methods need to be fixed.
Another way to do it: you can introduce a thin layer `FooAdaptor` on top of
`Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb
changes in `Foo` much more easily. While this is more work initially, carefully
choosing the adaptor interface can make your code easier to write and more
readable (a net win in the long run), as you can choose `FooAdaptor` to fit your
specific domain much better than `Foo` does.
<!-- GOOGLETEST_CM0029 DO NOT DELETE -->
### Using Mocks in Tests
Once you have a mock class, using it is easy. The typical work flow is:
1. Import the gMock names from the `testing` namespace such that you can use
them unqualified (You only have to do it once per file. Remember that
namespaces are a good idea.
2. Create some mock objects.
3. Specify your expectations on them (How many times will a method be called?
With what arguments? What should it do? etc.).
4. Exercise some code that uses the mocks; optionally, check the result using
googletest assertions. If a mock method is called more than expected or with
wrong arguments, you'll get an error immediately.
5. When a mock is destructed, gMock will automatically check whether all
expectations on it have been satisfied.
Here's an example:
```cpp
#include "path/to/mock-turtle.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::AtLeast; // #1
TEST(PainterTest, CanDrawSomething) {
MockTurtle turtle; // #2
EXPECT_CALL(turtle, PenDown()) // #3
.Times(AtLeast(1));
Painter painter(&turtle); // #4
EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); // #5
}
```
As you might have guessed, this test checks that `PenDown()` is called at least
once. If the `painter` object didn't call this method, your test will fail with
a message like this:
```text
path/to/my_test.cc:119: Failure
Actual function call count doesn't match this expectation:
Actually: never called;
Expected: called at least once.
Stack trace:
...
```
**Tip 1:** If you run the test from an Emacs buffer, you can hit <Enter> on the
line number to jump right to the failed expectation.
**Tip 2:** If your mock objects are never deleted, the final verification won't
happen. Therefore it's a good idea to turn on the heap checker in your tests
when you allocate mocks on the heap. You get that automatically if you use the
`gtest_main` library already.
**Important note:** gMock requires expectations to be set **before** the mock
functions are called, otherwise the behavior is **undefined**. In particular,
you mustn't interleave `EXPECT_CALL()s` and calls to the mock functions.
This means `EXPECT_CALL()` should be read as expecting that a call will occur
*in the future*, not that a call has occurred. Why does gMock work like that?
Well, specifying the expectation beforehand allows gMock to report a violation
as soon as it rises, when the context (stack trace, etc) is still available.
This makes debugging much easier.
Admittedly, this test is contrived and doesn't do much. You can easily achieve
the same effect without using gMock. However, as we shall reveal soon, gMock
allows you to do *so much more* with the mocks.
### Setting Expectations
The key to using a mock object successfully is to set the *right expectations*
on it. If you set the expectations too strict, your test will fail as the result
of unrelated changes. If you set them too loose, bugs can slip through. You want
to do it just right such that your test can catch exactly the kind of bugs you
intend it to catch. gMock provides the necessary means for you to do it "just
right."
#### General Syntax
In gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock
method. The general syntax is:
```cpp
EXPECT_CALL(mock_object, method(matchers))
.Times(cardinality)
.WillOnce(action)
.WillRepeatedly(action);
```
The macro has two arguments: first the mock object, and then the method and its
arguments. Note that the two are separated by a comma (`,`), not a period (`.`).
(Why using a comma? The answer is that it was necessary for technical reasons.)
If the method is not overloaded, the macro can also be called without matchers:
```cpp
EXPECT_CALL(mock_object, non-overloaded-method)
.Times(cardinality)
.WillOnce(action)
.WillRepeatedly(action);
```
This syntax allows the test writer to specify "called with any arguments"
without explicitly specifying the number or types of arguments. To avoid
unintended ambiguity, this syntax may only be used for methods which are not
overloaded
Either form of the macro can be followed by some optional *clauses* that provide
more information about the expectation. We'll discuss how each clause works in
the coming sections.
This syntax is designed to make an expectation read like English. For example,
you can probably guess that
```cpp
using ::testing::Return;
...
EXPECT_CALL(turtle, GetX())
.Times(5)
.WillOnce(Return(100))
.WillOnce(Return(150))
.WillRepeatedly(Return(200));
```
says that the `turtle` object's `GetX()` method will be called five times, it
will return 100 the first time, 150 the second time, and then 200 every time.
Some people like to call this style of syntax a Domain-Specific Language (DSL).
**Note:** Why do we use a macro to do this? Well it serves two purposes: first
it makes expectations easily identifiable (either by `gsearch` or by a human
reader), and second it allows gMock to include the source file location of a
failed expectation in messages, making debugging easier.
#### Matchers: What Arguments Do We Expect?
When a mock function takes arguments, we may specify what arguments we are
expecting, for example:
```cpp
// Expects the turtle to move forward by 100 units.
EXPECT_CALL(turtle, Forward(100));
```
Oftentimes you do not want to be too specific. Remember that talk about tests
being too rigid? Over specification leads to brittle tests and obscures the
intent of tests. Therefore we encourage you to specify only what's necessary—no
more, no less. If you aren't interested in the value of an argument, write `_`
as the argument, which means "anything goes":
```cpp
using ::testing::_;
...
// Expects that the turtle jumps to somewhere on the x=50 line.
EXPECT_CALL(turtle, GoTo(50, _));
```
`_` is an instance of what we call **matchers**. A matcher is like a predicate
and can test whether an argument is what we'd expect. You can use a matcher
inside `EXPECT_CALL()` wherever a function argument is expected. `_` is a
convenient way of saying "any value".
In the above examples, `100` and `50` are also matchers; implicitly, they are
the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be
equal (using `operator==`) to the matcher argument. There are many
[built-in matchers](#MatcherList) for common types (as well as
[custom matchers](cook_book.md#NewMatchers)); for example:
```cpp
using ::testing::Ge;
...
// Expects the turtle moves forward by at least 100.
EXPECT_CALL(turtle, Forward(Ge(100)));
```
If you don't care about *any* arguments, rather than specify `_` for each of
them you may instead omit the parameter list:
```cpp
// Expects the turtle to move forward.
EXPECT_CALL(turtle, Forward);
// Expects the turtle to jump somewhere.
EXPECT_CALL(turtle, GoTo);
```
This works for all non-overloaded methods; if a method is overloaded, you need
to help gMock resolve which overload is expected by specifying the number of
arguments and possibly also the
[types of the arguments](cook_book.md#SelectOverload).
#### Cardinalities: How Many Times Will It Be Called?
The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We
call its argument a **cardinality** as it tells *how many times* the call should
occur. It allows us to repeat an expectation many times without actually writing
it as many times. More importantly, a cardinality can be "fuzzy", just like a
matcher can be. This allows a user to express the intent of a test exactly.
An interesting special case is when we say `Times(0)`. You may have guessed - it
means that the function shouldn't be called with the given arguments at all, and
gMock will report a googletest failure whenever the function is (wrongfully)
called.
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the
list of built-in cardinalities you can use, see
[here](cheat_sheet.md#CardinalityList).
The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer
the cardinality for you.** The rules are easy to remember:
* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the
`EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
* If there are *n* `WillOnce()`'s but **no** `WillRepeatedly()`, where *n* >=
1, the cardinality is `Times(n)`.
* If there are *n* `WillOnce()`'s and **one** `WillRepeatedly()`, where *n* >=
0, the cardinality is `Times(AtLeast(n))`.
**Quick quiz:** what do you think will happen if a function is expected to be
called twice but actually called four times?
#### Actions: What Should It Do?
Remember that a mock object doesn't really have a working implementation? We as
users have to tell it what to do when a method is invoked. This is easy in
gMock.
First, if the return type of a mock function is a built-in type or a pointer,
the function has a **default action** (a `void` function will just return, a
`bool` function will return `false`, and other functions will return 0). In
addition, in C++ 11 and above, a mock function whose return type is
default-constructible (i.e. has a default constructor) has a default action of
returning a default-constructed value. If you don't say anything, this behavior
will be used.
Second, if a mock function doesn't have a default action, or the default action
doesn't suit you, you can specify the action to be taken each time the
expectation matches using a series of `WillOnce()` clauses followed by an
optional `WillRepeatedly()`. For example,
```cpp
using ::testing::Return;
...
EXPECT_CALL(turtle, GetX())
.WillOnce(Return(100))
.WillOnce(Return(200))
.WillOnce(Return(300));
```
says that `turtle.GetX()` will be called *exactly three times* (gMock inferred
this from how many `WillOnce()` clauses we've written, since we didn't
explicitly write `Times()`), and will return 100, 200, and 300 respectively.
```cpp
using ::testing::Return;
...
EXPECT_CALL(turtle, GetY())
.WillOnce(Return(100))
.WillOnce(Return(200))
.WillRepeatedly(Return(300));
```
says that `turtle.GetY()` will be called *at least twice* (gMock knows this as
we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no
explicit `Times()`), will return 100 and 200 respectively the first two times,
and 300 from the third time on.
Of course, if you explicitly write a `Times()`, gMock will not try to infer the
cardinality itself. What if the number you specified is larger than there are
`WillOnce()` clauses? Well, after all `WillOnce()`s are used up, gMock will do
the *default* action for the function every time (unless, of course, you have a
`WillRepeatedly()`.).
What can we do inside `WillOnce()` besides `Return()`? You can return a
reference using `ReturnRef(*variable*)`, or invoke a pre-defined function, among
[others](cook_book.md#using-actions).
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause
only once, even though the action may be performed many times. Therefore you
must be careful about side effects. The following may not do what you want:
```cpp
using ::testing::Return;
...
int n = 100;
EXPECT_CALL(turtle, GetX())
.Times(4)
.WillRepeatedly(Return(n++));
```
Instead of returning 100, 101, 102, ..., consecutively, this mock function will
always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)`
will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will
return the same pointer every time. If you want the side effect to happen every
time, you need to define a custom action, which we'll teach in the
[cook book](http://<!-- GOOGLETEST_CM0012 DO NOT DELETE -->).
Time for another quiz! What do you think the following means?
```cpp
using ::testing::Return;
...
EXPECT_CALL(turtle, GetY())
.Times(4)
.WillOnce(Return(100));
```
Obviously `turtle.GetY()` is expected to be called four times. But if you think
it will return 100 every time, think twice! Remember that one `WillOnce()`
clause will be consumed each time the function is invoked and the default action
will be taken afterwards. So the right answer is that `turtle.GetY()` will
return 100 the first time, but **return 0 from the second time on**, as
returning 0 is the default action for `int` functions.
#### Using Multiple Expectations {#MultiExpectations}
So far we've only shown examples where you have a single expectation. More
realistically, you'll specify expectations on multiple mock methods which may be
from multiple mock objects.
By default, when a mock method is invoked, gMock will search the expectations in
the **reverse order** they are defined, and stop when an active expectation that
matches the arguments is found (you can think of it as "newer rules override
older ones."). If the matching expectation cannot take any more calls, you will
get an upper-bound-violated failure. Here's an example:
```cpp
using ::testing::_;
...
EXPECT_CALL(turtle, Forward(_)); // #1
EXPECT_CALL(turtle, Forward(10)) // #2
.Times(2);
```
If `Forward(10)` is called three times in a row, the third time it will be an
error, as the last matching expectation (#2) has been saturated. If, however,
the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK,
as now #1 will be the matching expectation.
**Note:** Why does gMock search for a match in the *reverse* order of the
expectations? The reason is that this allows a user to set up the default
expectations in a mock object's constructor or the test fixture's set-up phase
and then customize the mock by writing more specific expectations in the test
body. So, if you have two expectations on the same method, you want to put the
one with more specific matchers **after** the other, or the more specific rule
would be shadowed by the more general one that comes after it.
**Tip:** It is very common to start with a catch-all expectation for a method
and `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if
overloaded). This makes any calls to the method expected. This is not necessary
for methods that are not mentioned at all (these are "uninteresting"), but is
useful for methods that have some expectations, but for which other calls are
ok. See
[Understanding Uninteresting vs Unexpected Calls](cook_book.md#uninteresting-vs-unexpected).
#### Ordered vs Unordered Calls {#OrderedCalls}
By default, an expectation can match a call even though an earlier expectation
hasn't been satisfied. In other words, the calls don't have to occur in the
order the expectations are specified.
Sometimes, you may want all the expected calls to occur in a strict order. To
say this in gMock is easy:
```cpp
using ::testing::InSequence;
...
TEST(FooTest, DrawsLineSegment) {
...
{
InSequence seq;
EXPECT_CALL(turtle, PenDown());
EXPECT_CALL(turtle, Forward(100));
EXPECT_CALL(turtle, PenUp());
}
Foo();
}
```
By creating an object of type `InSequence`, all expectations in its scope are
put into a *sequence* and have to occur *sequentially*. Since we are just
relying on the constructor and destructor of this object to do the actual work,
its name is really irrelevant.
In this example, we test that `Foo()` calls the three expected functions in the
order as written. If a call is made out-of-order, it will be an error.
(What if you care about the relative order of some of the calls, but not all of
them? Can you specify an arbitrary partial order? The answer is ... yes! The
details can be found [here](cook_book.md#OrderedCalls).)
#### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}
Now let's do a quick quiz to see how well you can use this mock stuff already.
How would you test that the turtle is asked to go to the origin *exactly twice*
(you want to ignore any other instructions it receives)?
After you've come up with your answer, take a look at ours and compare notes
(solve it yourself first - don't cheat!):
```cpp
using ::testing::_;
using ::testing::AnyNumber;
...
EXPECT_CALL(turtle, GoTo(_, _)) // #1
.Times(AnyNumber());
EXPECT_CALL(turtle, GoTo(0, 0)) // #2
.Times(2);
```
Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, gMock will
see that the arguments match expectation #2 (remember that we always pick the
last matching expectation). Now, since we said that there should be only two
such calls, gMock will report an error immediately. This is basically what we've
told you in the [Using Multiple Expectations](#MultiExpectations) section above.
This example shows that **expectations in gMock are "sticky" by default**, in
the sense that they remain active even after we have reached their invocation
upper bounds. This is an important rule to remember, as it affects the meaning
of the spec, and is **different** to how it's done in many other mocking
frameworks (Why'd we do that? Because we think our rule makes the common cases
easier to express and understand.).
Simple? Let's see if you've really understood it: what does the following code
say?
```cpp
using ::testing::Return;
...
for (int i = n; i > 0; i--) {
EXPECT_CALL(turtle, GetX())
.WillOnce(Return(10*i));
}
```
If you think it says that `turtle.GetX()` will be called `n` times and will
return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we
said, expectations are sticky. So, the second time `turtle.GetX()` is called,
the last (latest) `EXPECT_CALL()` statement will match, and will immediately
lead to an "upper bound violated" error - this piece of code is not very useful!
One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is
to explicitly say that the expectations are *not* sticky. In other words, they
should *retire* as soon as they are saturated:
```cpp
using ::testing::Return;
...
for (int i = n; i > 0; i--) {
EXPECT_CALL(turtle, GetX())
.WillOnce(Return(10*i))
.RetiresOnSaturation();
}
```
And, there's a better way to do it: in this case, we expect the calls to occur
in a specific order, and we line up the actions to match the order. Since the
order is important here, we should make it explicit using a sequence:
```cpp
using ::testing::InSequence;
using ::testing::Return;
...
{
InSequence s;
for (int i = 1; i <= n; i++) {
EXPECT_CALL(turtle, GetX())
.WillOnce(Return(10*i))
.RetiresOnSaturation();
}
}
```
By the way, the other situation where an expectation may *not* be sticky is when
it's in a sequence - as soon as another expectation that comes after it in the
sequence has been used, it automatically retires (and will never be used to
match any call).
#### Uninteresting Calls
A mock object may have many methods, and not all of them are that interesting.
For example, in some tests we may not care about how many times `GetX()` and
`GetY()` get called.
In gMock, if you are not interested in a method, just don't say anything about
it. If a call to this method occurs, you'll see a warning in the test output,
but it won't be a failure. This is called "naggy" behavior; to change, see
[The Nice, the Strict, and the Naggy](cook_book.md#NiceStrictNaggy).

@ -1,396 +0,0 @@
## Legacy gMock FAQ {#GMockFaq}
<!-- GOOGLETEST_CM0021 DO NOT DELETE -->
### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem?
In order for a method to be mocked, it must be *virtual*, unless you use the
[high-perf dependency injection technique](#MockingNonVirtualMethods).
### Can I mock a variadic function?
You cannot mock a variadic function (i.e. a function taking ellipsis (`...`)
arguments) directly in gMock.
The problem is that in general, there is *no way* for a mock object to know how
many arguments are passed to the variadic method, and what the arguments' types
are. Only the *author of the base class* knows the protocol, and we cannot look
into his or her head.
Therefore, to mock such a function, the *user* must teach the mock object how to
figure out the number of arguments and their types. One way to do it is to
provide overloaded versions of the function.
Ellipsis arguments are inherited from C and not really a C++ feature. They are
unsafe to use and don't work with arguments that have constructors or
destructors. Therefore we recommend to avoid them in C++ as much as possible.
### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why?
If you compile this using Microsoft Visual C++ 2005 SP1:
```cpp
class Foo {
...
virtual void Bar(const int i) = 0;
};
class MockFoo : public Foo {
...
MOCK_METHOD(void, Bar, (const int i), (override));
};
```
You may get the following warning:
```shell
warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
```
This is a MSVC bug. The same code compiles fine with gcc, for example. If you
use Visual C++ 2008 SP1, you would get the warning:
```shell
warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
```
In C++, if you *declare* a function with a `const` parameter, the `const`
modifier is ignored. Therefore, the `Foo` base class above is equivalent to:
```cpp
class Foo {
...
virtual void Bar(int i) = 0; // int or const int? Makes no difference.
};
```
In fact, you can *declare* `Bar()` with an `int` parameter, and define it with a
`const int` parameter. The compiler will still match them up.
Since making a parameter `const` is meaningless in the method declaration, we
recommend to remove it in both `Foo` and `MockFoo`. That should workaround the
VC bug.
Note that we are talking about the *top-level* `const` modifier here. If the
function parameter is passed by pointer or reference, declaring the pointee or
referee as `const` is still meaningful. For example, the following two
declarations are *not* equivalent:
```cpp
void Bar(int* p); // Neither p nor *p is const.
void Bar(const int* p); // p is not const, but *p is.
```
<!-- GOOGLETEST_CM0030 DO NOT DELETE -->
### I can't figure out why gMock thinks my expectations are not satisfied. What should I do?
You might want to run your test with `--gmock_verbose=info`. This flag lets
gMock print a trace of every mock function call it receives. By studying the
trace, you'll gain insights on why the expectations you set are not met.
If you see the message "The mock function has no default action set, and its
return type has no default value set.", then try
[adding a default action](for_dummies.md#DefaultValue). Due to a known issue,
unexpected calls on mocks without default actions don't print out a detailed
comparison between the actual arguments and the expected arguments.
### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug?
gMock and `ScopedMockLog` are likely doing the right thing here.
When a test crashes, the failure signal handler will try to log a lot of
information (the stack trace, and the address map, for example). The messages
are compounded if you have many threads with depth stacks. When `ScopedMockLog`
intercepts these messages and finds that they don't match any expectations, it
prints an error for each of them.
You can learn to ignore the errors, or you can rewrite your expectations to make
your test more robust, for example, by adding something like:
```cpp
using ::testing::AnyNumber;
using ::testing::Not;
...
// Ignores any log not done by us.
EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _))
.Times(AnyNumber());
```
### How can I assert that a function is NEVER called?
```cpp
using ::testing::_;
...
EXPECT_CALL(foo, Bar(_))
.Times(0);
```
<!-- GOOGLETEST_CM0031 DO NOT DELETE -->
### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant?
When gMock detects a failure, it prints relevant information (the mock function
arguments, the state of relevant expectations, and etc) to help the user debug.
If another failure is detected, gMock will do the same, including printing the
state of relevant expectations.
Sometimes an expectation's state didn't change between two failures, and you'll
see the same description of the state twice. They are however *not* redundant,
as they refer to *different points in time*. The fact they are the same *is*
interesting information.
### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong?
Does the class (hopefully a pure interface) you are mocking have a virtual
destructor?
Whenever you derive from a base class, make sure its destructor is virtual.
Otherwise Bad Things will happen. Consider the following code:
```cpp
class Base {
public:
// Not virtual, but should be.
~Base() { ... }
...
};
class Derived : public Base {
public:
...
private:
std::string value_;
};
...
Base* p = new Derived;
...
delete p; // Surprise! ~Base() will be called, but ~Derived() will not
// - value_ is leaked.
```
By changing `~Base()` to virtual, `~Derived()` will be correctly called when
`delete p` is executed, and the heap checker will be happy.
### The "newer expectations override older ones" rule makes writing expectations awkward. Why does gMock do that?
When people complain about this, often they are referring to code like:
```cpp
using ::testing::Return;
...
// foo.Bar() should be called twice, return 1 the first time, and return
// 2 the second time. However, I have to write the expectations in the
// reverse order. This sucks big time!!!
EXPECT_CALL(foo, Bar())
.WillOnce(Return(2))
.RetiresOnSaturation();
EXPECT_CALL(foo, Bar())
.WillOnce(Return(1))
.RetiresOnSaturation();
```
The problem, is that they didn't pick the **best** way to express the test's
intent.
By default, expectations don't have to be matched in *any* particular order. If
you want them to match in a certain order, you need to be explicit. This is
gMock's (and jMock's) fundamental philosophy: it's easy to accidentally
over-specify your tests, and we want to make it harder to do so.
There are two better ways to write the test spec. You could either put the
expectations in sequence:
```cpp
using ::testing::Return;
...
// foo.Bar() should be called twice, return 1 the first time, and return
// 2 the second time. Using a sequence, we can write the expectations
// in their natural order.
{
InSequence s;
EXPECT_CALL(foo, Bar())
.WillOnce(Return(1))
.RetiresOnSaturation();
EXPECT_CALL(foo, Bar())
.WillOnce(Return(2))
.RetiresOnSaturation();
}
```
or you can put the sequence of actions in the same expectation:
```cpp
using ::testing::Return;
...
// foo.Bar() should be called twice, return 1 the first time, and return
// 2 the second time.
EXPECT_CALL(foo, Bar())
.WillOnce(Return(1))
.WillOnce(Return(2))
.RetiresOnSaturation();
```
Back to the original questions: why does gMock search the expectations (and
`ON_CALL`s) from back to front? Because this allows a user to set up a mock's
behavior for the common case early (e.g. in the mock's constructor or the test
fixture's set-up phase) and customize it with more specific rules later. If
gMock searches from front to back, this very useful pattern won't be possible.
### gMock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case?
When choosing between being neat and being safe, we lean toward the latter. So
the answer is that we think it's better to show the warning.
Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as
the default behavior rarely changes from test to test. Then in the test body
they set the expectations, which are often different for each test. Having an
`ON_CALL` in the set-up part of a test doesn't mean that the calls are expected.
If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If
we quietly let the call go through without notifying the user, bugs may creep in
unnoticed.
If, however, you are sure that the calls are OK, you can write
```cpp
using ::testing::_;
...
EXPECT_CALL(foo, Bar(_))
.WillRepeatedly(...);
```
instead of
```cpp
using ::testing::_;
...
ON_CALL(foo, Bar(_))
.WillByDefault(...);
```
This tells gMock that you do expect the calls and no warning should be printed.
Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other
values are `info` and `warning`. If you find the output too noisy when
debugging, just choose a less verbose level.
### How can I delete the mock function's argument in an action?
If your mock function takes a pointer argument and you want to delete that
argument, you can use testing::DeleteArg<N>() to delete the N'th (zero-indexed)
argument:
```cpp
using ::testing::_;
...
MOCK_METHOD(void, Bar, (X* x, const Y& y));
...
EXPECT_CALL(mock_foo_, Bar(_, _))
.WillOnce(testing::DeleteArg<0>()));
```
### How can I perform an arbitrary action on a mock function's argument?
If you find yourself needing to perform some action that's not supported by
gMock directly, remember that you can define your own actions using
[`MakeAction()`](#NewMonoActions) or
[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function
and invoke it using [`Invoke()`](#FunctionsAsActions).
```cpp
using ::testing::_;
using ::testing::Invoke;
...
MOCK_METHOD(void, Bar, (X* p));
...
EXPECT_CALL(mock_foo_, Bar(_))
.WillOnce(Invoke(MyAction(...)));
```
### My code calls a static/global function. Can I mock it?
You can, but you need to make some changes.
In general, if you find yourself needing to mock a static function, it's a sign
that your modules are too tightly coupled (and less flexible, less reusable,
less testable, etc). You are probably better off defining a small interface and
call the function through that interface, which then can be easily mocked. It's
a bit of work initially, but usually pays for itself quickly.
This Google Testing Blog
[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it
excellently. Check it out.
### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks!
I know it's not a question, but you get an answer for free any way. :-)
With gMock, you can create mocks in C++ easily. And people might be tempted to
use them everywhere. Sometimes they work great, and sometimes you may find them,
well, a pain to use. So, what's wrong in the latter case?
When you write a test without using mocks, you exercise the code and assert that
it returns the correct value or that the system is in an expected state. This is
sometimes called "state-based testing".
Mocks are great for what some call "interaction-based" testing: instead of
checking the system state at the very end, mock objects verify that they are
invoked the right way and report an error as soon as it arises, giving you a
handle on the precise context in which the error was triggered. This is often
more effective and economical to do than state-based testing.
If you are doing state-based testing and using a test double just to simulate
the real object, you are probably better off using a fake. Using a mock in this
case causes pain, as it's not a strong point for mocks to perform complex
actions. If you experience this and think that mocks suck, you are just not
using the right tool for your problem. Or, you might be trying to solve the
wrong problem. :-)
### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic?
By all means, NO! It's just an FYI. :-)
What it means is that you have a mock function, you haven't set any expectations
on it (by gMock's rule this means that you are not interested in calls to this
function and therefore it can be called any number of times), and it is called.
That's OK - you didn't say it's not OK to call the function!
What if you actually meant to disallow this function to be called, but forgot to
write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the
user's fault, gMock tries to be nice and prints you a note.
So, when you see the message and believe that there shouldn't be any
uninteresting calls, you should investigate what's going on. To make your life
easier, gMock dumps the stack trace when an uninteresting call is encountered.
From that you can figure out which mock function it is, and how it is called.
### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface?
Either way is fine - you want to choose the one that's more convenient for your
circumstance.
Usually, if your action is for a particular function type, defining it using
`Invoke()` should be easier; if your action can be used in functions of
different types (e.g. if you are defining `Return(*value*)`),
`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what
types of functions the action can be used in, and implementing `ActionInterface`
is the way to go here. See the implementation of `Return()` in
`testing/base/public/gmock-actions.h` for an example.
### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean?
You got this error as gMock has no idea what value it should return when the
mock method is called. `SetArgPointee()` says what the side effect is, but
doesn't say what the return value should be. You need `DoAll()` to chain a
`SetArgPointee()` with a `Return()` that provides a value appropriate to the API
being mocked.
See this [recipe](cook_book.md#mocking-side-effects) for more details and an
example.
### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do?
We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6
times as much memory when compiling a mock class. We suggest to avoid `/clr`
when compiling native C++ mocks.

@ -30,12 +30,105 @@
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements some commonly used actions. // The ACTION* family of macros can be used in a namespace scope to
// define custom actions easily. The syntax:
//
// ACTION(name) { statements; }
//
// will define an action with the given name that executes the
// statements. The value returned by the statements will be used as
// the return value of the action. Inside the statements, you can
// refer to the K-th (0-based) argument of the mock function by
// 'argK', and refer to its type by 'argK_type'. For example:
//
// ACTION(IncrementArg1) {
// arg1_type temp = arg1;
// return ++(*temp);
// }
//
// allows you to write
//
// ...WillOnce(IncrementArg1());
//
// You can also refer to the entire argument tuple and its type by
// 'args' and 'args_type', and refer to the mock function type and its
// return type by 'function_type' and 'return_type'.
//
// Note that you don't need to specify the types of the mock function
// arguments. However rest assured that your code is still type-safe:
// you'll get a compiler error if *arg1 doesn't support the ++
// operator, or if the type of ++(*arg1) isn't compatible with the
// mock function's return type, for example.
//
// Sometimes you'll want to parameterize the action. For that you can use
// another macro:
//
// ACTION_P(name, param_name) { statements; }
//
// For example:
//
// ACTION_P(Add, n) { return arg0 + n; }
//
// will allow you to write:
//
// ...WillOnce(Add(5));
//
// Note that you don't need to provide the type of the parameter
// either. If you need to reference the type of a parameter named
// 'foo', you can write 'foo_type'. For example, in the body of
// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
// of 'n'.
//
// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
// multi-parameter actions.
//
// For the purpose of typing, you can view
//
// ACTION_Pk(Foo, p1, ..., pk) { ... }
//
// as shorthand for
//
// template <typename p1_type, ..., typename pk_type>
// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
//
// In particular, you can provide the template type arguments
// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
// although usually you can rely on the compiler to infer the types
// for you automatically. You can assign the result of expression
// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
// pk_type>. This can be useful when composing actions.
//
// You can also overload actions with different numbers of parameters:
//
// ACTION_P(Plus, a) { ... }
// ACTION_P2(Plus, a, b) { ... }
//
// While it's tempting to always use the ACTION* macros when defining
// a new action, you should also consider implementing ActionInterface
// or using MakePolymorphicAction() instead, especially if you need to
// use the action a lot. While these approaches require more work,
// they give you more control on the types of the mock function
// arguments and the action parameters, which in general leads to
// better compiler error messages that pay off in the long run. They
// also allow overloading actions based on parameter types (as opposed
// to just based on the number of parameters).
//
// CAVEAT:
//
// ACTION*() can only be used in a namespace scope as templates cannot be
// declared inside of a local class.
// Users can, however, define any local functors (e.g. a lambda) that
// can be used as actions.
//
// MORE INFORMATION:
//
// To learn more about using these macros, please search for 'ACTION' on
// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
#ifndef _WIN32_WCE #ifndef _WIN32_WCE
# include <errno.h> # include <errno.h>
@ -45,11 +138,13 @@
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <string> #include <string>
#include <tuple>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
#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"
#include "gmock/internal/gmock-pp.h"
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) # pragma warning(push)
@ -162,13 +257,17 @@ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
// Simple two-arg form of std::disjunction.
template <typename P, typename Q>
using disjunction = typename ::std::conditional<P::value, P, Q>::type;
} // namespace internal } // namespace internal
// When an unexpected function call is encountered, Google Mock will // When an unexpected function call is encountered, Google Mock will
@ -350,6 +449,9 @@ class Action {
} }
}; };
template <typename G>
using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
public: public:
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;
@ -361,10 +463,14 @@ class Action {
// 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
// directly constructible from lambda (it would require two conversions). // directly constructible from lambda (it would require two conversions).
template <typename G, template <
typename = typename ::std::enable_if< typename G,
::std::is_constructible<::std::function<F>, G>::value>::type> typename = typename std::enable_if<internal::disjunction<
Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
G>>::value>::type>
Action(G&& fun) { // NOLINT
Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
}
// Constructs an Action from its implementation. // Constructs an Action from its implementation.
explicit Action(ActionInterface<F>* impl) explicit Action(ActionInterface<F>* impl)
@ -396,6 +502,26 @@ class Action {
template <typename G> template <typename G>
friend class Action; friend class Action;
template <typename G>
void Init(G&& g, ::std::true_type) {
fun_ = ::std::forward<G>(g);
}
template <typename G>
void Init(G&& g, ::std::false_type) {
fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
}
template <typename FunctionImpl>
struct IgnoreArgs {
template <typename... Args>
Result operator()(const Args&...) const {
return function_impl();
}
FunctionImpl function_impl;
};
// fun_ is an empty function if and only if this is the DoDefault() action. // fun_ is an empty function if and only if this is the DoDefault() action.
::std::function<F> fun_; ::std::function<F> fun_;
}; };
@ -446,13 +572,9 @@ class PolymorphicAction {
private: private:
Impl impl_; Impl impl_;
GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
}; };
Impl impl_; Impl impl_;
GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
}; };
// Creates an Action from its implementation and returns it. The // Creates an Action from its implementation and returns it. The
@ -593,13 +715,9 @@ class ReturnAction {
private: private:
bool performed_; bool performed_;
const std::shared_ptr<R> wrapper_; const std::shared_ptr<R> wrapper_;
GTEST_DISALLOW_ASSIGN_(Impl);
}; };
const std::shared_ptr<R> value_; const std::shared_ptr<R> value_;
GTEST_DISALLOW_ASSIGN_(ReturnAction);
}; };
// Implements the ReturnNull() action. // Implements the ReturnNull() action.
@ -660,13 +778,9 @@ class ReturnRefAction {
private: private:
T& ref_; T& ref_;
GTEST_DISALLOW_ASSIGN_(Impl);
}; };
T& ref_; T& ref_;
GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
}; };
// Implements the polymorphic ReturnRefOfCopy(x) action, which can be // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
@ -707,13 +821,39 @@ class ReturnRefOfCopyAction {
private: private:
T value_; T value_;
GTEST_DISALLOW_ASSIGN_(Impl);
}; };
const T value_; const T value_;
};
// Implements the polymorphic ReturnRoundRobin(v) action, which can be
// used in any function that returns the element_type of v.
template <typename T>
class ReturnRoundRobinAction {
public:
explicit ReturnRoundRobinAction(std::vector<T> values) {
GTEST_CHECK_(!values.empty())
<< "ReturnRoundRobin requires at least one element.";
state_->values = std::move(values);
}
template <typename... Args>
T operator()(Args&&...) const {
return state_->Next();
}
private:
struct State {
T Next() {
T ret_val = values[i++];
if (i == values.size()) i = 0;
return ret_val;
}
GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction); std::vector<T> values;
size_t i = 0;
};
std::shared_ptr<State> state_ = std::make_shared<State>();
}; };
// Implements the polymorphic DoDefault() action. // Implements the polymorphic DoDefault() action.
@ -740,8 +880,6 @@ class AssignAction {
private: private:
T1* const ptr_; T1* const ptr_;
const T2 value_; const T2 value_;
GTEST_DISALLOW_ASSIGN_(AssignAction);
}; };
#if !GTEST_OS_WINDOWS_MOBILE #if !GTEST_OS_WINDOWS_MOBILE
@ -763,8 +901,6 @@ class SetErrnoAndReturnAction {
private: private:
const int errno_; const int errno_;
const T result_; const T result_;
GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
}; };
#endif // !GTEST_OS_WINDOWS_MOBILE #endif // !GTEST_OS_WINDOWS_MOBILE
@ -816,7 +952,8 @@ struct InvokeMethodWithoutArgsAction {
Class* const obj_ptr; Class* const obj_ptr;
const MethodPtr method_ptr; const MethodPtr method_ptr;
using ReturnType = typename std::result_of<MethodPtr(Class*)>::type; using ReturnType =
decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
template <typename... Args> template <typename... Args>
ReturnType operator()(const Args&...) const { ReturnType operator()(const Args&...) const {
@ -869,13 +1006,9 @@ class IgnoreResultAction {
OriginalFunction; OriginalFunction;
const Action<OriginalFunction> action_; const Action<OriginalFunction> action_;
GTEST_DISALLOW_ASSIGN_(Impl);
}; };
const A action_; const A action_;
GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
}; };
template <typename InnerAction, size_t... I> template <typename InnerAction, size_t... I>
@ -886,7 +1019,8 @@ struct WithArgsAction {
// We use the conversion operator to detect the signature of the inner Action. // We use the conversion operator to detect the signature of the inner Action.
template <typename R, typename... Args> template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT operator Action<R(Args...)>() const { // NOLINT
Action<R(typename std::tuple_element<I, std::tuple<Args...>>::type...)> using TupleType = std::tuple<Args...>;
Action<R(typename std::tuple_element<I, TupleType>::type...)>
converted(action); converted(action);
return [converted](Args... args) -> R { return [converted](Args... args) -> R {
@ -899,9 +1033,13 @@ struct WithArgsAction {
template <typename... Actions> template <typename... Actions>
struct DoAllAction { struct DoAllAction {
private: private:
template <typename... Args, size_t... I> template <typename T>
std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const { using NonFinalType =
return {std::get<I>(actions)...}; typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
template <typename ActionT, size_t... I>
std::vector<ActionT> Convert(IndexSequence<I...>) const {
return {ActionT(std::get<I>(actions))...};
} }
public: public:
@ -910,21 +1048,121 @@ struct DoAllAction {
template <typename R, typename... Args> template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT operator Action<R(Args...)>() const { // NOLINT
struct Op { struct Op {
std::vector<Action<void(Args...)>> converted; std::vector<Action<void(NonFinalType<Args>...)>> converted;
Action<R(Args...)> last; Action<R(Args...)> last;
R operator()(Args... args) const { R operator()(Args... args) const {
auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...); auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
for (auto& a : converted) { for (auto& a : converted) {
a.Perform(tuple_args); a.Perform(tuple_args);
} }
return last.Perform(tuple_args); return last.Perform(std::move(tuple_args));
} }
}; };
return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()), return Op{Convert<Action<void(NonFinalType<Args>...)>>(
MakeIndexSequence<sizeof...(Actions) - 1>()),
std::get<sizeof...(Actions) - 1>(actions)}; std::get<sizeof...(Actions) - 1>(actions)};
} }
}; };
template <typename T, typename... Params>
struct ReturnNewAction {
T* operator()() const {
return internal::Apply(
[](const Params&... unpacked_params) {
return new T(unpacked_params...);
},
params);
}
std::tuple<Params...> params;
};
template <size_t k>
struct ReturnArgAction {
template <typename... Args>
auto operator()(const Args&... args) const ->
typename std::tuple_element<k, std::tuple<Args...>>::type {
return std::get<k>(std::tie(args...));
}
};
template <size_t k, typename Ptr>
struct SaveArgAction {
Ptr pointer;
template <typename... Args>
void operator()(const Args&... args) const {
*pointer = std::get<k>(std::tie(args...));
}
};
template <size_t k, typename Ptr>
struct SaveArgPointeeAction {
Ptr pointer;
template <typename... Args>
void operator()(const Args&... args) const {
*pointer = *std::get<k>(std::tie(args...));
}
};
template <size_t k, typename T>
struct SetArgRefereeAction {
T value;
template <typename... Args>
void operator()(Args&&... args) const {
using argk_type =
typename ::std::tuple_element<k, std::tuple<Args...>>::type;
static_assert(std::is_lvalue_reference<argk_type>::value,
"Argument must be a reference type.");
std::get<k>(std::tie(args...)) = value;
}
};
template <size_t k, typename I1, typename I2>
struct SetArrayArgumentAction {
I1 first;
I2 last;
template <typename... Args>
void operator()(const Args&... args) const {
auto value = std::get<k>(std::tie(args...));
for (auto it = first; it != last; ++it, (void)++value) {
*value = *it;
}
}
};
template <size_t k>
struct DeleteArgAction {
template <typename... Args>
void operator()(const Args&... args) const {
delete std::get<k>(std::tie(args...));
}
};
template <typename Ptr>
struct ReturnPointeeAction {
Ptr pointer;
template <typename... Args>
auto operator()(const Args&...) const -> decltype(*pointer) {
return *pointer;
}
};
#if GTEST_HAS_EXCEPTIONS
template <typename T>
struct ThrowAction {
T exception;
// We use a conversion operator to adapt to any return type.
template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT
T copy = exception;
return [copy](Args...) -> R { throw copy; };
}
};
#endif // GTEST_HAS_EXCEPTIONS
} // namespace internal } // namespace internal
// An Unused object can be implicitly constructed from ANY value. // An Unused object can be implicitly constructed from ANY value.
@ -960,7 +1198,8 @@ struct DoAllAction {
typedef internal::IgnoredValue Unused; typedef internal::IgnoredValue Unused;
// Creates an action that does actions a1, a2, ..., sequentially in // Creates an action that does actions a1, a2, ..., sequentially in
// each invocation. // each invocation. All but the last action will have a readonly view of the
// arguments.
template <typename... Action> template <typename... Action>
internal::DoAllAction<typename std::decay<Action>::type...> DoAll( internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
Action&&... action) { Action&&... action) {
@ -1022,6 +1261,10 @@ inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
return internal::ReturnRefAction<R>(x); return internal::ReturnRefAction<R>(x);
} }
// Prevent using ReturnRef on reference to temporary.
template <typename R, R* = nullptr>
internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
// Creates an action that returns the reference to a copy of the // Creates an action that returns the reference to a copy of the
// argument. The copy is created when the action is constructed and // argument. The copy is created when the action is constructed and
// lives as long as the action. // lives as long as the action.
@ -1039,6 +1282,23 @@ internal::ByMoveWrapper<R> ByMove(R x) {
return internal::ByMoveWrapper<R>(std::move(x)); return internal::ByMoveWrapper<R>(std::move(x));
} }
// Creates an action that returns an element of `vals`. Calling this action will
// repeatedly return the next value from `vals` until it reaches the end and
// will restart from the beginning.
template <typename T>
internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
return internal::ReturnRoundRobinAction<T>(std::move(vals));
}
// Creates an action that returns an element of `vals`. Calling this action will
// repeatedly return the next value from `vals` until it reaches the end and
// will restart from the beginning.
template <typename T>
internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
std::initializer_list<T> vals) {
return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
}
// Creates an action that does the default action for the give mock function. // Creates an action that does the default action for the give mock function.
inline internal::DoDefaultAction DoDefault() { inline internal::DoDefaultAction DoDefault() {
return internal::DoDefaultAction(); return internal::DoDefaultAction();
@ -1047,14 +1307,14 @@ inline internal::DoDefaultAction DoDefault() {
// Creates an action that sets the variable pointed by the N-th // Creates an action that sets the variable pointed by the N-th
// (0-based) function argument to 'value'. // (0-based) function argument to 'value'.
template <size_t N, typename T> template <size_t N, typename T>
internal::SetArgumentPointeeAction<N, T> SetArgPointee(T x) { internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
return {std::move(x)}; return {std::move(value)};
} }
// The following version is DEPRECATED. // The following version is DEPRECATED.
template <size_t N, typename T> template <size_t N, typename T>
internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T x) { internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
return {std::move(x)}; return {std::move(value)};
} }
// Creates an action that sets a pointer referent to a given value. // Creates an action that sets a pointer referent to a given value.
@ -1132,11 +1392,296 @@ inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
return ::std::reference_wrapper<T>(l_value); return ::std::reference_wrapper<T>(l_value);
} }
// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
// instance of type T, constructed on the heap with constructor arguments
// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
template <typename T, typename... Params>
internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
Params&&... params) {
return {std::forward_as_tuple(std::forward<Params>(params)...)};
}
// Action ReturnArg<k>() returns the k-th argument of the mock function.
template <size_t k>
internal::ReturnArgAction<k> ReturnArg() {
return {};
}
// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
// mock function to *pointer.
template <size_t k, typename Ptr>
internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
return {pointer};
}
// Action SaveArgPointee<k>(pointer) saves the value pointed to
// by the k-th (0-based) argument of the mock function to *pointer.
template <size_t k, typename Ptr>
internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
return {pointer};
}
// Action SetArgReferee<k>(value) assigns 'value' to the variable
// referenced by the k-th (0-based) argument of the mock function.
template <size_t k, typename T>
internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
T&& value) {
return {std::forward<T>(value)};
}
// Action SetArrayArgument<k>(first, last) copies the elements in
// source range [first, last) to the array pointed to by the k-th
// (0-based) argument, which can be either a pointer or an
// iterator. The action does not take ownership of the elements in the
// source range.
template <size_t k, typename I1, typename I2>
internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
I2 last) {
return {first, last};
}
// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
// function.
template <size_t k>
internal::DeleteArgAction<k> DeleteArg() {
return {};
}
// This action returns the value pointed to by 'pointer'.
template <typename Ptr>
internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
return {pointer};
}
// Action Throw(exception) can be used in a mock function of any type
// to throw the given exception. Any copyable value can be thrown.
#if GTEST_HAS_EXCEPTIONS
template <typename T>
internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
return {std::forward<T>(exception)};
}
#endif // GTEST_HAS_EXCEPTIONS
namespace internal {
// A macro from the ACTION* family (defined later in gmock-generated-actions.h)
// defines an action that can be used in a mock function. Typically,
// these actions only care about a subset of the arguments of the mock
// function. For example, if such an action only uses the second
// argument, it can be used in any mock function that takes >= 2
// arguments where the type of the second argument is compatible.
//
// Therefore, the action implementation must be prepared to take more
// arguments than it needs. The ExcessiveArg type is used to
// represent those excessive arguments. In order to keep the compiler
// error messages tractable, we define it in the testing namespace
// instead of testing::internal. However, this is an INTERNAL TYPE
// and subject to change without notice, so a user MUST NOT USE THIS
// TYPE DIRECTLY.
struct ExcessiveArg {};
// Builds an implementation of an Action<> for some particular signature, using
// a class defined by an ACTION* macro.
template <typename F, typename Impl> struct ActionImpl;
template <typename Impl>
struct ImplBase {
struct Holder {
// Allows each copy of the Action<> to get to the Impl.
explicit operator const Impl&() const { return *ptr; }
std::shared_ptr<Impl> ptr;
};
using type = typename std::conditional<std::is_constructible<Impl>::value,
Impl, Holder>::type;
};
template <typename R, typename... Args, typename Impl>
struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
using Base = typename ImplBase<Impl>::type;
using function_type = R(Args...);
using args_type = std::tuple<Args...>;
ActionImpl() = default; // Only defined if appropriate for Base.
explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} { }
R operator()(Args&&... arg) const {
static constexpr size_t kMaxArgs =
sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
return Apply(MakeIndexSequence<kMaxArgs>{},
MakeIndexSequence<10 - kMaxArgs>{},
args_type{std::forward<Args>(arg)...});
}
template <std::size_t... arg_id, std::size_t... excess_id>
R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
const args_type& args) const {
// Impl need not be specific to the signature of action being implemented;
// only the implementing function body needs to have all of the specific
// types instantiated. Up to 10 of the args that are provided by the
// args_type get passed, followed by a dummy of unspecified type for the
// remainder up to 10 explicit args.
static constexpr ExcessiveArg kExcessArg{};
return static_cast<const Impl&>(*this).template gmock_PerformImpl<
/*function_type=*/function_type, /*return_type=*/R,
/*args_type=*/args_type,
/*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>(
/*args=*/args, std::get<arg_id>(args)...,
((void)excess_id, kExcessArg)...);
}
};
// Stores a default-constructed Impl as part of the Action<>'s
// std::function<>. The Impl should be trivial to copy.
template <typename F, typename Impl>
::testing::Action<F> MakeAction() {
return ::testing::Action<F>(ActionImpl<F, Impl>());
}
// Stores just the one given instance of Impl.
template <typename F, typename Impl>
::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));
}
#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
, const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
GMOCK_INTERNAL_ARG_UNUSED, , 10)
#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
#define GMOCK_ACTION_TYPE_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
, param##_type gmock_p##i
#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
, std::forward<param##_type>(gmock_p##i)
#define GMOCK_ACTION_GVALUE_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
, param(::std::forward<param##_type>(gmock_p##i))
#define GMOCK_ACTION_INIT_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
#define GMOCK_ACTION_FIELD_PARAMS_(params) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
#define GMOCK_INTERNAL_ACTION(name, full_name, params) \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
class full_name { \
public: \
explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
: impl_(std::make_shared<gmock_Impl>( \
GMOCK_ACTION_GVALUE_PARAMS_(params))) { } \
full_name(const full_name&) = default; \
full_name(full_name&&) noexcept = default; \
template <typename F> \
operator ::testing::Action<F>() const { \
return ::testing::internal::MakeAction<F>(impl_); \
} \
private: \
class gmock_Impl { \
public: \
explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
: GMOCK_ACTION_INIT_PARAMS_(params) {} \
template <typename function_type, typename return_type, \
typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
GMOCK_ACTION_FIELD_PARAMS_(params) \
}; \
std::shared_ptr<const gmock_Impl> impl_; \
}; \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
GMOCK_ACTION_GVALUE_PARAMS_(params)); \
} \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
template <typename function_type, typename return_type, typename args_type, \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl:: \
gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
} // namespace internal
// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
#define ACTION(name) \
class name##Action { \
public: \
explicit name##Action() noexcept {} \
name##Action(const name##Action&) noexcept {} \
template <typename F> \
operator ::testing::Action<F>() const { \
return ::testing::internal::MakeAction<F, gmock_Impl>(); \
} \
private: \
class gmock_Impl { \
public: \
template <typename function_type, typename return_type, \
typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
}; \
}; \
inline name##Action name() GTEST_MUST_USE_RESULT_; \
inline name##Action name() { return name##Action(); } \
template <typename function_type, typename return_type, typename args_type, \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type name##Action::gmock_Impl::gmock_PerformImpl( \
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
#define ACTION_P(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
#define ACTION_P2(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
#define ACTION_P3(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
#define ACTION_P4(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
#define ACTION_P5(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
#define ACTION_P6(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
#define ACTION_P7(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
#define ACTION_P8(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
#define ACTION_P9(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
#define ACTION_P10(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
} // namespace testing } // namespace testing
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) # pragma warning(pop)
#endif #endif
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_

@ -36,8 +36,8 @@
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#include <limits.h> #include <limits.h>
#include <memory> #include <memory>
@ -154,4 +154,4 @@ inline Cardinality MakeCardinality(const CardinalityInterface* c) {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_

@ -33,12 +33,47 @@
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
#include "gmock/gmock-generated-function-mockers.h" // NOLINT #include <type_traits> // IWYU pragma: keep
#include <utility> // IWYU pragma: keep
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-pp.h" #include "gmock/internal/gmock-pp.h"
namespace testing {
namespace internal {
template <typename T>
using identity_t = T;
template <typename Pattern>
struct ThisRefAdjuster {
template <typename T>
using AdjustT = typename std::conditional<
std::is_const<typename std::remove_reference<Pattern>::type>::value,
typename std::conditional<std::is_lvalue_reference<Pattern>::value,
const T&, const T&&>::type,
typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&,
T&&>::type>::type;
template <typename MockType>
static AdjustT<MockType> Adjust(const MockType& mock) {
return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock));
}
};
} // namespace internal
// The style guide prohibits "using" statements in a namespace scope
// inside a header file. However, the FunctionMocker class template
// is meant to be defined in the ::testing namespace. The following
// line is just a trick for working around a bug in MSVC 8.0, which
// cannot handle it if we define FunctionMocker in ::testing.
using internal::FunctionMocker;
} // namespace testing
#define MOCK_METHOD(...) \ #define MOCK_METHOD(...) \
GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)
@ -60,7 +95,8 @@
GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
GMOCK_INTERNAL_HAS_NOEXCEPT(_Spec), GMOCK_INTERNAL_GET_CALLTYPE(_Spec), \ GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \
GMOCK_INTERNAL_GET_CALLTYPE(_Spec), GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \
(GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
@ -94,21 +130,20 @@
::testing::tuple_size<typename ::testing::internal::Function< \ ::testing::tuple_size<typename ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == _N, \ __VA_ARGS__>::ArgumentTuple>::value == _N, \
"This method does not take " GMOCK_PP_STRINGIZE( \ "This method does not take " GMOCK_PP_STRINGIZE( \
_N) " arguments. Parenthesize all types with unproctected commas.") _N) " arguments. Parenthesize all types with unprotected commas.")
#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ #define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)
#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ #define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \
_Override, _Final, _Noexcept, \ _Override, _Final, _NoexceptSpec, \
_CallType, _Signature) \ _CallType, _RefSpec, _Signature) \
typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \ typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \
_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, ) GMOCK_PP_IF(_Noexcept, noexcept, ) \ GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \
GMOCK_PP_IF(_Override, override, ) \ GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \
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) \
@ -116,7 +151,7 @@
} \ } \
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \ ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \
GMOCK_PP_IF(_Constness, const, ) { \ GMOCK_PP_IF(_Constness, const, ) _RefSpec { \
GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \
return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \
@ -124,11 +159,10 @@
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \ ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
const ::testing::internal::WithoutMatchers&, \ const ::testing::internal::WithoutMatchers&, \
GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \
GMOCK_PP_REMOVE_PARENS(_Signature)>*) \ GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \
const GMOCK_PP_IF(_Noexcept, noexcept, ) { \ return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \
return GMOCK_PP_CAT(::testing::internal::AdjustConstness_, \ _Constness, const, ) int _RefSpec>::Adjust(*this) \
GMOCK_PP_IF(_Constness, const, ))(this) \ .gmock_##_MethodName(GMOCK_PP_REPEAT( \
->gmock_##_MethodName(GMOCK_PP_REPEAT( \
GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
} \ } \
mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \ mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
@ -147,9 +181,20 @@
#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ #define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \
GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple))
#define GMOCK_INTERNAL_HAS_NOEXCEPT(_Tuple) \ #define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \
GMOCK_PP_HAS_COMMA( \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple)
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_NOEXCEPT, ~, _Tuple))
#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \
GMOCK_PP_IF( \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \
_elem, )
#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)
#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \
GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
#define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \ #define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple) GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple)
@ -160,6 +205,7 @@
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \
GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \ GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \
GMOCK_PP_STRINGIZE( \ GMOCK_PP_STRINGIZE( \
_elem) " cannot be recognized as a valid specification modifier."); _elem) " cannot be recognized as a valid specification modifier.");
@ -180,12 +226,18 @@
#define GMOCK_INTERNAL_DETECT_FINAL_I_final , #define GMOCK_INTERNAL_DETECT_FINAL_I_final ,
// TODO(iserna): Maybe noexcept should accept an argument here as well.
#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ #define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem)
#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , #define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,
#define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem)
#define GMOCK_INTERNAL_DETECT_REF_I_ref ,
#define GMOCK_INTERNAL_UNPACK_ref(x) x
#define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \ #define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \
GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \ GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \
GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \ GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
@ -203,14 +255,28 @@
GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \ GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \
GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg)) GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \ #define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \
GMOCK_PP_CAT(GMOCK_PP_IDENTITY, _arg) GMOCK_PP_IDENTITY _arg
#define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype #define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ // Note: The use of `identity_t` here allows _Ret to represent return types that
GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), GMOCK_PP_REMOVE_PARENS, \ // would normally need to be specified in a different way. For example, a method
GMOCK_PP_IDENTITY) \ // returning a function pointer must be written as
(_Ret)(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) //
// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...)
//
// But we only support placing the return type at the beginning. To handle this,
// we wrap all calls in identity_t, so that a declaration will be expanded to
//
// identity_t<fn_ptr_return_t (*)(fn_ptr_args_t...)> method(method_args_t...)
//
// This allows us to work around the syntactic oddities of function/method
// types.
#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \
::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \
GMOCK_PP_REMOVE_PARENS, \
GMOCK_PP_IDENTITY)(_Ret)>( \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))
#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ #define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
@ -218,36 +284,196 @@
GMOCK_PP_IDENTITY) \ GMOCK_PP_IDENTITY) \
(_elem) (_elem)
#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ #define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \ GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i gmock_a##_i
#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ #define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
::std::forward<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \ ::std::forward<GMOCK_INTERNAL_ARG_O( \
GMOCK_PP_REMOVE_PARENS(_Signature))>( \ _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)
gmock_a##_i)
#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ #define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
GMOCK_INTERNAL_MATCHER_O(typename, GMOCK_PP_INC(_i), \ GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i gmock_a##_i
#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ #define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
gmock_a##_i gmock_a##_i
#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ #define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
::testing::A<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \ ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()
GMOCK_PP_REMOVE_PARENS(_Signature))>()
#define GMOCK_INTERNAL_ARG_O(_i, ...) \
#define GMOCK_INTERNAL_ARG_O(_tn, _i, ...) GMOCK_ARG_(_tn, _i, __VA_ARGS__) typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type
#define GMOCK_INTERNAL_MATCHER_O(_tn, _i, ...) \ #define GMOCK_INTERNAL_MATCHER_O(_i, ...) \
GMOCK_MATCHER_(_tn, _i, __VA_ARGS__) const ::testing::Matcher<typename ::testing::internal::Function< \
__VA_ARGS__>::template Arg<_i>::type>&
#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)
#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)
#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)
#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)
#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)
#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)
#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)
#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)
#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)
#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)
#define MOCK_METHOD10(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)
#define MOCK_CONST_METHOD0(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)
#define MOCK_CONST_METHOD1(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)
#define MOCK_CONST_METHOD2(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)
#define MOCK_CONST_METHOD3(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)
#define MOCK_CONST_METHOD4(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)
#define MOCK_CONST_METHOD5(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)
#define MOCK_CONST_METHOD6(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)
#define MOCK_CONST_METHOD7(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)
#define MOCK_CONST_METHOD8(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)
#define MOCK_CONST_METHOD9(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)
#define MOCK_CONST_METHOD10(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)
#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)
#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)
#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)
#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)
#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)
#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)
#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)
#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)
#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)
#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)
#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)
#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)
#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)
#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)
#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)
#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)
#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)
#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)
#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)
#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)
#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)
#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)
#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)
#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)
#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)
#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)
#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)
#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)
#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)
#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)
#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)
#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)
#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)
#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \
GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
args_num, ::testing::internal::identity_t<__VA_ARGS__>); \
GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \
(::testing::internal::identity_t<__VA_ARGS__>))
#define GMOCK_MOCKER_(arity, constness, Method) \
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_

@ -1,627 +0,0 @@
$$ -*- mode: c++; -*-
$$ This is a Pump source file. Please use Pump to convert it to
$$ gmock-generated-actions.h.
$$
$var n = 10 $$ The maximum arity we support.
$$}} This meta comment fixes auto-indentation in editors.
// Copyright 2007, 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.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements some commonly used variadic actions.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#include <memory>
#include <utility>
#include "gmock/gmock-actions.h"
#include "gmock/internal/gmock-port.h"
namespace testing {
namespace internal {
// A macro from the ACTION* family (defined later in this file)
// defines an action that can be used in a mock function. Typically,
// these actions only care about a subset of the arguments of the mock
// function. For example, if such an action only uses the second
// argument, it can be used in any mock function that takes >= 2
// arguments where the type of the second argument is compatible.
//
// Therefore, the action implementation must be prepared to take more
// arguments than it needs. The ExcessiveArg type is used to
// represent those excessive arguments. In order to keep the compiler
// error messages tractable, we define it in the testing namespace
// instead of testing::internal. However, this is an INTERNAL TYPE
// and subject to change without notice, so a user MUST NOT USE THIS
// TYPE DIRECTLY.
struct ExcessiveArg {};
// A helper class needed for implementing the ACTION* macros.
template <typename Result, class Impl>
class ActionHelper {
public:
$range i 0..n
$for i
[[
$var template = [[$if i==0 [[]] $else [[
$range j 0..i-1
template <$for j, [[typename A$j]]>
]]]]
$range j 0..i-1
$var As = [[$for j, [[A$j]]]]
$var as = [[$for j, [[std::get<$j>(args)]]]]
$range k 1..n-i
$var eas = [[$for k, [[ExcessiveArg()]]]]
$var arg_list = [[$if (i==0) | (i==n) [[$as$eas]] $else [[$as, $eas]]]]
$template
static Result Perform(Impl* impl, const ::std::tuple<$As>& args) {
return impl->template gmock_PerformImpl<$As>(args, $arg_list);
}
]]
};
} // namespace internal
} // namespace testing
// The ACTION* family of macros can be used in a namespace scope to
// define custom actions easily. The syntax:
//
// ACTION(name) { statements; }
//
// will define an action with the given name that executes the
// statements. The value returned by the statements will be used as
// the return value of the action. Inside the statements, you can
// refer to the K-th (0-based) argument of the mock function by
// 'argK', and refer to its type by 'argK_type'. For example:
//
// ACTION(IncrementArg1) {
// arg1_type temp = arg1;
// return ++(*temp);
// }
//
// allows you to write
//
// ...WillOnce(IncrementArg1());
//
// You can also refer to the entire argument tuple and its type by
// 'args' and 'args_type', and refer to the mock function type and its
// return type by 'function_type' and 'return_type'.
//
// Note that you don't need to specify the types of the mock function
// arguments. However rest assured that your code is still type-safe:
// you'll get a compiler error if *arg1 doesn't support the ++
// operator, or if the type of ++(*arg1) isn't compatible with the
// mock function's return type, for example.
//
// Sometimes you'll want to parameterize the action. For that you can use
// another macro:
//
// ACTION_P(name, param_name) { statements; }
//
// For example:
//
// ACTION_P(Add, n) { return arg0 + n; }
//
// will allow you to write:
//
// ...WillOnce(Add(5));
//
// Note that you don't need to provide the type of the parameter
// either. If you need to reference the type of a parameter named
// 'foo', you can write 'foo_type'. For example, in the body of
// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
// of 'n'.
//
// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P$n to support
// multi-parameter actions.
//
// For the purpose of typing, you can view
//
// ACTION_Pk(Foo, p1, ..., pk) { ... }
//
// as shorthand for
//
// template <typename p1_type, ..., typename pk_type>
// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
//
// In particular, you can provide the template type arguments
// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
// although usually you can rely on the compiler to infer the types
// for you automatically. You can assign the result of expression
// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
// pk_type>. This can be useful when composing actions.
//
// You can also overload actions with different numbers of parameters:
//
// ACTION_P(Plus, a) { ... }
// ACTION_P2(Plus, a, b) { ... }
//
// While it's tempting to always use the ACTION* macros when defining
// a new action, you should also consider implementing ActionInterface
// or using MakePolymorphicAction() instead, especially if you need to
// use the action a lot. While these approaches require more work,
// they give you more control on the types of the mock function
// arguments and the action parameters, which in general leads to
// better compiler error messages that pay off in the long run. They
// also allow overloading actions based on parameter types (as opposed
// to just based on the number of parameters).
//
// CAVEAT:
//
// ACTION*() can only be used in a namespace scope as templates cannot be
// declared inside of a local class.
// Users can, however, define any local functors (e.g. a lambda) that
// can be used as actions.
//
// MORE INFORMATION:
//
// To learn more about using these macros, please search for 'ACTION' on
// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
$range i 0..n
$range k 0..n-1
// An internal macro needed for implementing ACTION*().
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
const args_type& args GTEST_ATTRIBUTE_UNUSED_
$for k [[, \
const arg$k[[]]_type& arg$k GTEST_ATTRIBUTE_UNUSED_]]
// Sometimes you want to give an action explicit template parameters
// that cannot be inferred from its value parameters. ACTION() and
// ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that
// and can be viewed as an extension to ACTION() and ACTION_P*().
//
// The syntax:
//
// ACTION_TEMPLATE(ActionName,
// HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
// AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
//
// defines an action template that takes m explicit template
// parameters and n value parameters. name_i is the name of the i-th
// template parameter, and kind_i specifies whether it's a typename,
// an integral constant, or a template. p_i is the name of the i-th
// value parameter.
//
// Example:
//
// // DuplicateArg<k, T>(output) converts the k-th argument of the mock
// // function to type T and copies it to *output.
// ACTION_TEMPLATE(DuplicateArg,
// HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
// AND_1_VALUE_PARAMS(output)) {
// *output = T(::std::get<k>(args));
// }
// ...
// int n;
// EXPECT_CALL(mock, Foo(_, _))
// .WillOnce(DuplicateArg<1, unsigned char>(&n));
//
// To create an instance of an action template, write:
//
// ActionName<t1, ..., t_m>(v1, ..., v_n)
//
// where the ts are the template arguments and the vs are the value
// arguments. The value argument types are inferred by the compiler.
// If you want to explicitly specify the value argument types, you can
// provide additional template arguments:
//
// ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
//
// where u_i is the desired type of v_i.
//
// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
// number of value parameters, but not on the number of template
// parameters. Without the restriction, the meaning of the following
// is unclear:
//
// OverloadedAction<int, bool>(x);
//
// Are we using a single-template-parameter action where 'bool' refers
// to the type of x, or are we using a two-template-parameter action
// where the compiler is asked to infer the type of x?
//
// Implementation notes:
//
// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
// implementing ACTION_TEMPLATE. The main trick we use is to create
// new macro invocations when expanding a macro. For example, we have
//
// #define ACTION_TEMPLATE(name, template_params, value_params)
// ... GMOCK_INTERNAL_DECL_##template_params ...
//
// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
// to expand to
//
// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
//
// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
// preprocessor will continue to expand it to
//
// ... typename T ...
//
// This technique conforms to the C++ standard and is portable. It
// allows us to implement action templates using O(N) code, where N is
// the maximum number of template/value parameters supported. Without
// using it, we'd have to devote O(N^2) amount of code to implement all
// combinations of m and n.
// Declares the template parameters.
$range j 1..n
$for j [[
$range m 0..j-1
#define GMOCK_INTERNAL_DECL_HAS_$j[[]]
_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[kind$m name$m]]
]]
// Lists the template parameters.
$for j [[
$range m 0..j-1
#define GMOCK_INTERNAL_LIST_HAS_$j[[]]
_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[name$m]]
]]
// Declares the types of value parameters.
$for i [[
$range j 0..i-1
#define GMOCK_INTERNAL_DECL_TYPE_AND_$i[[]]
_VALUE_PARAMS($for j, [[p$j]]) $for j [[, typename p$j##_type]]
]]
// Initializes the value parameters.
$for i [[
$range j 0..i-1
#define GMOCK_INTERNAL_INIT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])\
($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(::std::move(gmock_p$j))]]
]]
// Declares the fields for storing the value parameters.
$for i [[
$range j 0..i-1
#define GMOCK_INTERNAL_DEFN_AND_$i[[]]
_VALUE_PARAMS($for j, [[p$j]]) $for j [[p$j##_type p$j; ]]
]]
// Lists the value parameters.
$for i [[
$range j 0..i-1
#define GMOCK_INTERNAL_LIST_AND_$i[[]]
_VALUE_PARAMS($for j, [[p$j]]) $for j, [[p$j]]
]]
// Lists the value parameter types.
$for i [[
$range j 0..i-1
#define GMOCK_INTERNAL_LIST_TYPE_AND_$i[[]]
_VALUE_PARAMS($for j, [[p$j]]) $for j [[, p$j##_type]]
]]
// Declares the value parameters.
$for i [[
$range j 0..i-1
#define GMOCK_INTERNAL_DECL_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]]
$for j, [[p$j##_type p$j]]
]]
// The suffix of the class template implementing the action template.
$for i [[
$range j 0..i-1
#define GMOCK_INTERNAL_COUNT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]]
$if i==1 [[P]] $elif i>=2 [[P$i]]
]]
// The name of the class template implementing the action template.
#define GMOCK_ACTION_CLASS_(name, value_params)\
GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
$range k 0..n-1
#define ACTION_TEMPLATE(name, template_params, value_params)\
template <GMOCK_INTERNAL_DECL_##template_params\
GMOCK_INTERNAL_DECL_TYPE_##value_params>\
class GMOCK_ACTION_CLASS_(name, value_params) {\
public:\
explicit GMOCK_ACTION_CLASS_(name, value_params)\
GMOCK_INTERNAL_INIT_##value_params {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
typedef F function_type;\
typedef typename ::testing::internal::Function<F>::Result return_type;\
typedef typename ::testing::internal::Function<F>::ArgumentTuple\
args_type;\
explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
}\
template <$for k, [[typename arg$k[[]]_type]]>\
return_type gmock_PerformImpl(const args_type& args[[]]
$for k [[, const arg$k[[]]_type& arg$k]]) const;\
GMOCK_INTERNAL_DEFN_##value_params\
private:\
GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
};\
template <typename F> operator ::testing::Action<F>() const {\
return ::testing::Action<F>(\
new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\
}\
GMOCK_INTERNAL_DEFN_##value_params\
private:\
GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\
};\
template <GMOCK_INTERNAL_DECL_##template_params\
GMOCK_INTERNAL_DECL_TYPE_##value_params>\
inline GMOCK_ACTION_CLASS_(name, value_params)<\
GMOCK_INTERNAL_LIST_##template_params\
GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\
GMOCK_INTERNAL_DECL_##value_params) {\
return GMOCK_ACTION_CLASS_(name, value_params)<\
GMOCK_INTERNAL_LIST_##template_params\
GMOCK_INTERNAL_LIST_TYPE_##value_params>(\
GMOCK_INTERNAL_LIST_##value_params);\
}\
template <GMOCK_INTERNAL_DECL_##template_params\
GMOCK_INTERNAL_DECL_TYPE_##value_params>\
template <typename F>\
template <typename arg0_type, typename arg1_type, typename arg2_type, \
typename arg3_type, typename arg4_type, typename arg5_type, \
typename arg6_type, typename arg7_type, typename arg8_type, \
typename arg9_type>\
typename ::testing::internal::Function<F>::Result\
GMOCK_ACTION_CLASS_(name, value_params)<\
GMOCK_INTERNAL_LIST_##template_params\
GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl<F>::\
gmock_PerformImpl(\
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
$for i
[[
$var template = [[$if i==0 [[]] $else [[
$range j 0..i-1
template <$for j, [[typename p$j##_type]]>\
]]]]
$var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]]
$else [[P$i]]]]]]
$range j 0..i-1
$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::forward<p$j##_type>(gmock_p$j))]]]]]]
$var param_field_decls = [[$for j
[[
p$j##_type p$j;\
]]]]
$var param_field_decls2 = [[$for j
[[
p$j##_type p$j;\
]]]]
$var params = [[$for j, [[p$j]]]]
$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
$var typename_arg_types = [[$for k, [[typename arg$k[[]]_type]]]]
$var arg_types_and_names = [[$for k, [[const arg$k[[]]_type& arg$k]]]]
$var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]]
$else [[ACTION_P$i]]]]
#define $macro_name(name$for j [[, p$j]])\$template
class $class_name {\
public:\
[[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
typedef F function_type;\
typedef typename ::testing::internal::Function<F>::Result return_type;\
typedef typename ::testing::internal::Function<F>::ArgumentTuple\
args_type;\
[[$if i==1 [[explicit ]]]]gmock_Impl($ctor_param_list)$inits {}\
virtual return_type Perform(const args_type& args) {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
}\
template <$typename_arg_types>\
return_type gmock_PerformImpl(const args_type& args, [[]]
$arg_types_and_names) const;\$param_field_decls
private:\
GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
};\
template <typename F> operator ::testing::Action<F>() const {\
return ::testing::Action<F>(new gmock_Impl<F>($params));\
}\$param_field_decls2
private:\
GTEST_DISALLOW_ASSIGN_($class_name);\
};\$template
inline $class_name$param_types name($param_types_and_names) {\
return $class_name$param_types($params);\
}\$template
template <typename F>\
template <$typename_arg_types>\
typename ::testing::internal::Function<F>::Result\
$class_name$param_types::gmock_Impl<F>::gmock_PerformImpl(\
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
]]
$$ } // This meta comment fixes auto-indentation in Emacs. It won't
$$ // show up in the generated code.
namespace testing {
// The ACTION*() macros trigger warning C4100 (unreferenced formal
// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
// the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable:4100)
#endif
// Various overloads for InvokeArgument<N>().
//
// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
// (0-based) argument, which must be a k-ary callable, of the mock
// function, with arguments a1, a2, ..., a_k.
//
// Notes:
//
// 1. The arguments are passed by value by default. If you need to
// pass an argument by reference, wrap it inside ByRef(). For
// example,
//
// InvokeArgument<1>(5, string("Hello"), ByRef(foo))
//
// passes 5 and string("Hello") by value, and passes foo by
// reference.
//
// 2. If the callable takes an argument by reference but ByRef() is
// not used, it will receive the reference to a copy of the value,
// instead of the original value. For example, when the 0-th
// argument of the mock function takes a const string&, the action
//
// InvokeArgument<0>(string("Hello"))
//
// makes a copy of the temporary string("Hello") object and passes a
// reference of the copy, instead of the original temporary object,
// to the callable. This makes it easy for a user to define an
// InvokeArgument action from temporary values and have it performed
// later.
namespace internal {
namespace invoke_argument {
// Appears in InvokeArgumentAdl's argument list to help avoid
// accidental calls to user functions of the same name.
struct AdlTag {};
// InvokeArgumentAdl - a helper for InvokeArgument.
// The basic overloads are provided here for generic functors.
// Overloads for other custom-callables are provided in the
// internal/custom/callback-actions.h header.
$range i 0..n
$for i
[[
$range j 1..i
template <typename R, typename F[[$for j [[, typename A$j]]]]>
R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) {
return f([[$for j, [[a$j]]]]);
}
]]
} // namespace invoke_argument
} // namespace internal
$range i 0..n
$for i [[
$range j 0..i-1
ACTION_TEMPLATE(InvokeArgument,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) {
using internal::invoke_argument::InvokeArgumentAdl;
return InvokeArgumentAdl<return_type>(
internal::invoke_argument::AdlTag(),
::std::get<k>(args)$for j [[, p$j]]);
}
]]
// Various overloads for ReturnNew<T>().
//
// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
// instance of type T, constructed on the heap with constructor arguments
// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
$range i 0..n
$for i [[
$range j 0..i-1
$var ps = [[$for j, [[p$j]]]]
ACTION_TEMPLATE(ReturnNew,
HAS_1_TEMPLATE_PARAMS(typename, T),
AND_$i[[]]_VALUE_PARAMS($ps)) {
return new T($ps);
}
]]
#ifdef _MSC_VER
# pragma warning(pop)
#endif
} // namespace testing
// Include any custom callback actions added by the local installation.
// We must include this header at the end to make sure it can use the
// declarations from this file.
#include "gmock/internal/custom/gmock-generated-actions.h"
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_

@ -1,752 +0,0 @@
// This file was GENERATED by command:
// pump.py gmock-generated-function-mockers.h.pump
// DO NOT EDIT BY HAND!!!
// Copyright 2007, 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.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements function mockers of various arities.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#include <functional>
#include <utility>
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-internal-utils.h"
namespace testing {
namespace internal {
// Removes the given pointer; this is a helper for the expectation setter method
// for parameterless matchers.
//
// We want to make sure that the user cannot set a parameterless expectation on
// overloaded methods, including methods which are overloaded on const. Example:
//
// class MockClass {
// MOCK_METHOD0(GetName, string&());
// MOCK_CONST_METHOD0(GetName, const string&());
// };
//
// TEST() {
// // This should be an error, as it's not clear which overload is expected.
// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value));
// }
//
// Here are the generated expectation-setter methods:
//
// class MockClass {
// // Overload 1
// MockSpec<string&()> gmock_GetName() { ... }
// // Overload 2. Declared const so that the compiler will generate an
// // error when trying to resolve between this and overload 4 in
// // 'gmock_GetName(WithoutMatchers(), nullptr)'.
// MockSpec<string&()> gmock_GetName(
// const WithoutMatchers&, const Function<string&()>*) const {
// // Removes const from this, calls overload 1
// return AdjustConstness_(this)->gmock_GetName();
// }
//
// // Overload 3
// const string& gmock_GetName() const { ... }
// // Overload 4
// MockSpec<const string&()> gmock_GetName(
// const WithoutMatchers&, const Function<const string&()>*) const {
// // Does not remove const, calls overload 3
// return AdjustConstness_const(this)->gmock_GetName();
// }
// }
//
template <typename MockType>
const MockType* AdjustConstness_const(const MockType* mock) {
return mock;
}
// Removes const from and returns the given pointer; this is a helper for the
// expectation setter method for parameterless matchers.
template <typename MockType>
MockType* AdjustConstness_(const MockType* mock) {
return const_cast<MockType*>(mock);
}
} // namespace internal
// The style guide prohibits "using" statements in a namespace scope
// inside a header file. However, the FunctionMocker class template
// is meant to be defined in the ::testing namespace. The following
// line is just a trick for working around a bug in MSVC 8.0, which
// cannot handle it if we define FunctionMocker in ::testing.
using internal::FunctionMocker;
// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
// We define this as a variadic macro in case F contains unprotected
// commas (the same reason that we use variadic macros in other places
// in this file).
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_RESULT_(tn, ...) \
tn ::testing::internal::Function<__VA_ARGS__>::Result
// The type of argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_ARG_(tn, N, ...) \
tn ::testing::internal::Function<__VA_ARGS__>::template Arg<N-1>::type
// The matcher type for argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_MATCHER_(tn, N, ...) \
const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
// The variable for mocking the given method.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_MOCKER_(arity, constness, Method) \
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \
static_assert(0 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
) constness { \
GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(0, constness, Method).Invoke(); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method() constness { \
GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(0, constness, Method).With(); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \
static_assert(1 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(1, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \
static_assert(2 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2) constness { \
GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(2, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \
GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \
static_assert(3 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, \
__VA_ARGS__) gmock_a3) constness { \
GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(3, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \
GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \
static_assert(4 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(4, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \
static_assert(5 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5) constness { \
GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(5, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \
GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \
static_assert(6 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, \
__VA_ARGS__) gmock_a6) constness { \
GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(6, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \
GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \
static_assert(7 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(7, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \
static_assert(8 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
__VA_ARGS__) gmock_a8) constness { \
GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(8, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
::std::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \
GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \
static_assert(9 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
__VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, \
__VA_ARGS__) gmock_a9) constness { \
GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(9, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
::std::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \
::std::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \
GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \
gmock_a9); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \
static_assert(10 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
__VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \
GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \
GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(10, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
::std::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \
::std::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9), \
::std::forward<GMOCK_ARG_(tn, 10, __VA_ARGS__)>(gmock_a10)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \
GMOCK_MATCHER_(tn, 10, \
__VA_ARGS__) gmock_a10) constness { \
GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \
gmock_a10); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 10, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \
Method)
#define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__)
#define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__)
#define MOCK_METHOD2(m, ...) GMOCK_METHOD2_(, , , m, __VA_ARGS__)
#define MOCK_METHOD3(m, ...) GMOCK_METHOD3_(, , , m, __VA_ARGS__)
#define MOCK_METHOD4(m, ...) GMOCK_METHOD4_(, , , m, __VA_ARGS__)
#define MOCK_METHOD5(m, ...) GMOCK_METHOD5_(, , , m, __VA_ARGS__)
#define MOCK_METHOD6(m, ...) GMOCK_METHOD6_(, , , m, __VA_ARGS__)
#define MOCK_METHOD7(m, ...) GMOCK_METHOD7_(, , , m, __VA_ARGS__)
#define MOCK_METHOD8(m, ...) GMOCK_METHOD8_(, , , m, __VA_ARGS__)
#define MOCK_METHOD9(m, ...) GMOCK_METHOD9_(, , , m, __VA_ARGS__)
#define MOCK_METHOD10(m, ...) GMOCK_METHOD10_(, , , m, __VA_ARGS__)
#define MOCK_CONST_METHOD0(m, ...) GMOCK_METHOD0_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD1(m, ...) GMOCK_METHOD1_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD2(m, ...) GMOCK_METHOD2_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD3(m, ...) GMOCK_METHOD3_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD4(m, ...) GMOCK_METHOD4_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD5(m, ...) GMOCK_METHOD5_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD6(m, ...) GMOCK_METHOD6_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD7(m, ...) GMOCK_METHOD7_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD8(m, ...) GMOCK_METHOD8_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD9(m, ...) GMOCK_METHOD9_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD10(m, ...) GMOCK_METHOD10_(, const, , m, __VA_ARGS__)
#define MOCK_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_T(m, ...) \
GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_T(m, ...) \
GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_T(m, ...) \
GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_T(m, ...) \
GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_T(m, ...) \
GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_T(m, ...) \
GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_T(m, ...) \
GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_T(m, ...) \
GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_T(m, ...) \
GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_T(m, ...) \
GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_T(m, ...) \
GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__)
#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD0_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD1_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD2_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD3_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD4_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD5_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD6_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD7_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD8_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD9_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD10_(, , ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__)
#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__)
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_

@ -1,227 +0,0 @@
$$ -*- mode: c++; -*-
$$ This is a Pump source file. Please use Pump to convert
$$ it to gmock-generated-function-mockers.h.
$$
$var n = 10 $$ The maximum arity we support.
// Copyright 2007, 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.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements function mockers of various arities.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#include <functional>
#include <utility>
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-internal-utils.h"
namespace testing {
namespace internal {
$range i 0..n
// Removes the given pointer; this is a helper for the expectation setter method
// for parameterless matchers.
//
// We want to make sure that the user cannot set a parameterless expectation on
// overloaded methods, including methods which are overloaded on const. Example:
//
// class MockClass {
// MOCK_METHOD0(GetName, string&());
// MOCK_CONST_METHOD0(GetName, const string&());
// };
//
// TEST() {
// // This should be an error, as it's not clear which overload is expected.
// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value));
// }
//
// Here are the generated expectation-setter methods:
//
// class MockClass {
// // Overload 1
// MockSpec<string&()> gmock_GetName() { ... }
// // Overload 2. Declared const so that the compiler will generate an
// // error when trying to resolve between this and overload 4 in
// // 'gmock_GetName(WithoutMatchers(), nullptr)'.
// MockSpec<string&()> gmock_GetName(
// const WithoutMatchers&, const Function<string&()>*) const {
// // Removes const from this, calls overload 1
// return AdjustConstness_(this)->gmock_GetName();
// }
//
// // Overload 3
// const string& gmock_GetName() const { ... }
// // Overload 4
// MockSpec<const string&()> gmock_GetName(
// const WithoutMatchers&, const Function<const string&()>*) const {
// // Does not remove const, calls overload 3
// return AdjustConstness_const(this)->gmock_GetName();
// }
// }
//
template <typename MockType>
const MockType* AdjustConstness_const(const MockType* mock) {
return mock;
}
// Removes const from and returns the given pointer; this is a helper for the
// expectation setter method for parameterless matchers.
template <typename MockType>
MockType* AdjustConstness_(const MockType* mock) {
return const_cast<MockType*>(mock);
}
} // namespace internal
// The style guide prohibits "using" statements in a namespace scope
// inside a header file. However, the FunctionMocker class template
// is meant to be defined in the ::testing namespace. The following
// line is just a trick for working around a bug in MSVC 8.0, which
// cannot handle it if we define FunctionMocker in ::testing.
using internal::FunctionMocker;
// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
// We define this as a variadic macro in case F contains unprotected
// commas (the same reason that we use variadic macros in other places
// in this file).
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_RESULT_(tn, ...) \
tn ::testing::internal::Function<__VA_ARGS__>::Result
// The type of argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_ARG_(tn, N, ...) \
tn ::testing::internal::Function<__VA_ARGS__>::template Arg<N-1>::type
// The matcher type for argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_MATCHER_(tn, N, ...) \
const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
// The variable for mocking the given method.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_MOCKER_(arity, constness, Method) \
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
$for i [[
$range j 1..i
$var arg_as = [[$for j, [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
$var as = [[$for j, \
[[::std::forward<GMOCK_ARG_(tn, $j, __VA_ARGS__)>(gmock_a$j)]]]]
$var matcher_arg_as = [[$for j, \
[[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
$var matcher_as = [[$for j, [[gmock_a$j]]]]
$var anything_matchers = [[$for j, \
[[::testing::A<GMOCK_ARG_(tn, $j, __VA_ARGS__)>()]]]]
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \
static_assert($i == ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, "MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
$arg_as) constness { \
GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method($matcher_arg_as) constness { \
GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_($i, constness, Method).With($matcher_as); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method($anything_matchers); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method)
]]
$for i [[
#define MOCK_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, , , m, __VA_ARGS__)
]]
$for i [[
#define MOCK_CONST_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, const, , m, __VA_ARGS__)
]]
$for i [[
#define MOCK_METHOD$i[[]]_T(m, ...) GMOCK_METHOD$i[[]]_(typename, , , m, __VA_ARGS__)
]]
$for i [[
#define MOCK_CONST_METHOD$i[[]]_T(m, ...) \
GMOCK_METHOD$i[[]]_(typename, const, , m, __VA_ARGS__)
]]
$for i [[
#define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD$i[[]]_(, , ct, m, __VA_ARGS__)
]]
$for i [[
#define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD$i[[]]_(, const, ct, m, __VA_ARGS__)
]]
$for i [[
#define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD$i[[]]_(typename, , ct, m, __VA_ARGS__)
]]
$for i [[
#define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD$i[[]]_(typename, const, ct, m, __VA_ARGS__)
]]
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_

@ -1,346 +0,0 @@
$$ -*- mode: c++; -*-
$$ This is a Pump source file. Please use Pump to convert
$$ it to gmock-generated-matchers.h.
$$
$var n = 10 $$ The maximum arity we support.
$$ }} This line fixes auto-indentation of the following code in Emacs.
// Copyright 2008, 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.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements some commonly used variadic matchers.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
#include <iterator>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock-matchers.h"
// The MATCHER* family of macros can be used in a namespace scope to
// define custom matchers easily.
//
// Basic Usage
// ===========
//
// The syntax
//
// MATCHER(name, description_string) { statements; }
//
// defines a matcher with the given name that executes the statements,
// which must return a bool to indicate if the match succeeds. Inside
// the statements, you can refer to the value being matched by 'arg',
// and refer to its type by 'arg_type'.
//
// The description string documents what the matcher does, and is used
// to generate the failure message when the match fails. Since a
// MATCHER() is usually defined in a header file shared by multiple
// C++ source files, we require the description to be a C-string
// literal to avoid possible side effects. It can be empty, in which
// case we'll use the sequence of words in the matcher name as the
// description.
//
// For example:
//
// MATCHER(IsEven, "") { return (arg % 2) == 0; }
//
// allows you to write
//
// // Expects mock_foo.Bar(n) to be called where n is even.
// EXPECT_CALL(mock_foo, Bar(IsEven()));
//
// or,
//
// // Verifies that the value of some_expression is even.
// EXPECT_THAT(some_expression, IsEven());
//
// If the above assertion fails, it will print something like:
//
// Value of: some_expression
// Expected: is even
// Actual: 7
//
// where the description "is even" is automatically calculated from the
// matcher name IsEven.
//
// Argument Type
// =============
//
// Note that the type of the value being matched (arg_type) is
// determined by the context in which you use the matcher and is
// supplied to you by the compiler, so you don't need to worry about
// declaring it (nor can you). This allows the matcher to be
// polymorphic. For example, IsEven() can be used to match any type
// where the value of "(arg % 2) == 0" can be implicitly converted to
// a bool. In the "Bar(IsEven())" example above, if method Bar()
// takes an int, 'arg_type' will be int; if it takes an unsigned long,
// 'arg_type' will be unsigned long; and so on.
//
// Parameterizing Matchers
// =======================
//
// Sometimes you'll want to parameterize the matcher. For that you
// can use another macro:
//
// MATCHER_P(name, param_name, description_string) { statements; }
//
// For example:
//
// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
//
// will allow you to write:
//
// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
//
// which may lead to this message (assuming n is 10):
//
// Value of: Blah("a")
// Expected: has absolute value 10
// Actual: -9
//
// Note that both the matcher description and its parameter are
// printed, making the message human-friendly.
//
// In the matcher definition body, you can write 'foo_type' to
// reference the type of a parameter named 'foo'. For example, in the
// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
// 'value_type' to refer to the type of 'value'.
//
// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
// support multi-parameter matchers.
//
// Describing Parameterized Matchers
// =================================
//
// The last argument to MATCHER*() is a string-typed expression. The
// expression can reference all of the matcher's parameters and a
// special bool-typed variable named 'negation'. When 'negation' is
// false, the expression should evaluate to the matcher's description;
// otherwise it should evaluate to the description of the negation of
// the matcher. For example,
//
// using testing::PrintToString;
//
// MATCHER_P2(InClosedRange, low, hi,
// std::string(negation ? "is not" : "is") + " in range [" +
// PrintToString(low) + ", " + PrintToString(hi) + "]") {
// return low <= arg && arg <= hi;
// }
// ...
// EXPECT_THAT(3, InClosedRange(4, 6));
// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
//
// would generate two failures that contain the text:
//
// Expected: is in range [4, 6]
// ...
// Expected: is not in range [2, 4]
//
// If you specify "" as the description, the failure message will
// contain the sequence of words in the matcher name followed by the
// parameter values printed as a tuple. For example,
//
// MATCHER_P2(InClosedRange, low, hi, "") { ... }
// ...
// EXPECT_THAT(3, InClosedRange(4, 6));
// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
//
// would generate two failures that contain the text:
//
// Expected: in closed range (4, 6)
// ...
// Expected: not (in closed range (2, 4))
//
// Types of Matcher Parameters
// ===========================
//
// For the purpose of typing, you can view
//
// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
//
// as shorthand for
//
// template <typename p1_type, ..., typename pk_type>
// FooMatcherPk<p1_type, ..., pk_type>
// Foo(p1_type p1, ..., pk_type pk) { ... }
//
// When you write Foo(v1, ..., vk), the compiler infers the types of
// the parameters v1, ..., and vk for you. If you are not happy with
// the result of the type inference, you can specify the types by
// explicitly instantiating the template, as in Foo<long, bool>(5,
// false). As said earlier, you don't get to (or need to) specify
// 'arg_type' as that's determined by the context in which the matcher
// is used. You can assign the result of expression Foo(p1, ..., pk)
// to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
// can be useful when composing matchers.
//
// While you can instantiate a matcher template with reference types,
// passing the parameters by pointer usually makes your code more
// readable. If, however, you still want to pass a parameter by
// reference, be aware that in the failure message generated by the
// matcher you will see the value of the referenced object but not its
// address.
//
// Explaining Match Results
// ========================
//
// Sometimes the matcher description alone isn't enough to explain why
// the match has failed or succeeded. For example, when expecting a
// long string, it can be very helpful to also print the diff between
// the expected string and the actual one. To achieve that, you can
// optionally stream additional information to a special variable
// named result_listener, whose type is a pointer to class
// MatchResultListener:
//
// MATCHER_P(EqualsLongString, str, "") {
// if (arg == str) return true;
//
// *result_listener << "the difference: "
/// << DiffStrings(str, arg);
// return false;
// }
//
// Overloading Matchers
// ====================
//
// You can overload matchers with different numbers of parameters:
//
// MATCHER_P(Blah, a, description_string1) { ... }
// MATCHER_P2(Blah, a, b, description_string2) { ... }
//
// Caveats
// =======
//
// When defining a new matcher, you should also consider implementing
// MatcherInterface or using MakePolymorphicMatcher(). These
// approaches require more work than the MATCHER* macros, but also
// give you more control on the types of the value being matched and
// the matcher parameters, which may leads to better compiler error
// messages when the matcher is used wrong. They also allow
// overloading matchers based on parameter types (as opposed to just
// based on the number of parameters).
//
// MATCHER*() can only be used in a namespace scope as templates cannot be
// declared inside of a local class.
//
// More Information
// ================
//
// To learn more about using these macros, please search for 'MATCHER'
// on
// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
$range i 0..n
$for i
[[
$var macro_name = [[$if i==0 [[MATCHER]] $elif i==1 [[MATCHER_P]]
$else [[MATCHER_P$i]]]]
$var class_name = [[name##Matcher[[$if i==0 [[]] $elif i==1 [[P]]
$else [[P$i]]]]]]
$range j 0..i-1
$var template = [[$if i==0 [[]] $else [[
template <$for j, [[typename p$j##_type]]>\
]]]]
$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
$var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]]
$var params = [[$for j, [[p$j]]]]
$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
$var param_field_decls = [[$for j
[[
p$j##_type const p$j;\
]]]]
$var param_field_decls2 = [[$for j
[[
p$j##_type const p$j;\
]]]]
#define $macro_name(name$for j [[, p$j]], description)\$template
class $class_name {\
public:\
template <typename arg_type>\
class gmock_Impl : public ::testing::MatcherInterface<\
GTEST_REFERENCE_TO_CONST_(arg_type)> {\
public:\
[[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\
$impl_inits {}\
virtual bool MatchAndExplain(\
GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
::testing::MatchResultListener* result_listener) const;\
virtual void DescribeTo(::std::ostream* gmock_os) const {\
*gmock_os << FormatDescription(false);\
}\
virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\
*gmock_os << FormatDescription(true);\
}\$param_field_decls
private:\
::std::string FormatDescription(bool negation) const {\
::std::string gmock_description = (description);\
if (!gmock_description.empty()) {\
return gmock_description;\
}\
return ::testing::internal::FormatMatcherDescription(\
negation, #name, \
::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
::std::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\
}\
};\
template <typename arg_type>\
operator ::testing::Matcher<arg_type>() const {\
return ::testing::Matcher<arg_type>(\
new gmock_Impl<arg_type>($params));\
}\
[[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\
}\$param_field_decls2
private:\
};\$template
inline $class_name$param_types name($param_types_and_names) {\
return $class_name$param_types($params);\
}\$template
template <typename arg_type>\
bool $class_name$param_types::gmock_Impl<arg_type>::MatchAndExplain(\
GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
const
]]
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_

File diff suppressed because it is too large Load Diff

@ -30,38 +30,464 @@
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements some actions that depend on gmock-generated-actions.h. // This file implements some commonly used variadic actions.
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
#include <algorithm> #include <memory>
#include <type_traits> #include <utility>
#include "gmock/gmock-generated-actions.h" #include "gmock/gmock-actions.h"
#include "gmock/internal/gmock-port.h"
namespace testing { // Include any custom callback actions added by the local installation.
namespace internal { #include "gmock/internal/custom/gmock-generated-actions.h"
// An internal replacement for std::copy which mimics its behavior. This is // Sometimes you want to give an action explicit template parameters
// necessary because Visual Studio deprecates ::std::copy, issuing warning 4996. // that cannot be inferred from its value parameters. ACTION() and
// However Visual Studio 2010 and later do not honor #pragmas which disable that // ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that
// warning. // and can be viewed as an extension to ACTION() and ACTION_P*().
template<typename InputIterator, typename OutputIterator> //
inline OutputIterator CopyElements(InputIterator first, // The syntax:
InputIterator last, //
OutputIterator output) { // ACTION_TEMPLATE(ActionName,
for (; first != last; ++first, ++output) { // HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
*output = *first; // AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
} //
return output; // defines an action template that takes m explicit template
} // parameters and n value parameters. name_i is the name of the i-th
// template parameter, and kind_i specifies whether it's a typename,
// an integral constant, or a template. p_i is the name of the i-th
// value parameter.
//
// Example:
//
// // DuplicateArg<k, T>(output) converts the k-th argument of the mock
// // function to type T and copies it to *output.
// ACTION_TEMPLATE(DuplicateArg,
// HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
// AND_1_VALUE_PARAMS(output)) {
// *output = T(::std::get<k>(args));
// }
// ...
// int n;
// EXPECT_CALL(mock, Foo(_, _))
// .WillOnce(DuplicateArg<1, unsigned char>(&n));
//
// To create an instance of an action template, write:
//
// ActionName<t1, ..., t_m>(v1, ..., v_n)
//
// where the ts are the template arguments and the vs are the value
// arguments. The value argument types are inferred by the compiler.
// If you want to explicitly specify the value argument types, you can
// provide additional template arguments:
//
// ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
//
// where u_i is the desired type of v_i.
//
// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the
// number of value parameters, but not on the number of template
// parameters. Without the restriction, the meaning of the following
// is unclear:
//
// OverloadedAction<int, bool>(x);
//
// Are we using a single-template-parameter action where 'bool' refers
// to the type of x, or are we using a two-template-parameter action
// where the compiler is asked to infer the type of x?
//
// Implementation notes:
//
// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and
// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for
// implementing ACTION_TEMPLATE. The main trick we use is to create
// new macro invocations when expanding a macro. For example, we have
//
// #define ACTION_TEMPLATE(name, template_params, value_params)
// ... GMOCK_INTERNAL_DECL_##template_params ...
//
// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)
// to expand to
//
// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...
//
// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the
// preprocessor will continue to expand it to
//
// ... typename T ...
//
// This technique conforms to the C++ standard and is portable. It
// allows us to implement action templates using O(N) code, where N is
// the maximum number of template/value parameters supported. Without
// using it, we'd have to devote O(N^2) amount of code to implement all
// combinations of m and n.
} // namespace internal // Declares the template parameters.
#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1) kind0 name0, kind1 name1
#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2) kind0 name0, kind1 name1, kind2 name2
#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
kind3 name3
#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
kind2 name2, kind3 name3, kind4 name4
#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
kind5 name5, kind6 name6
#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
kind4 name4, kind5 name5, kind6 name6, kind7 name7
#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
kind8 name8
#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
kind6 name6, kind7 name7, kind8 name8, kind9 name9
// Lists the template parameters.
#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1) name0, name1
#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2) name0, name1, name2
#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3) name0, name1, name2, name3
#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
name4
#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
name2, name3, name4, name5
#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6) name0, name1, name2, name3, name4, name5, name6
#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
name6, name7, name8
#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
name3, name4, name5, name6, name7, name8, name9
// Declares the types of value parameters.
#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
typename p0##_type, typename p1##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
typename p0##_type, typename p1##_type, typename p2##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
typename p3##_type, typename p4##_type, typename p5##_type, \
typename p6##_type, typename p7##_type, typename p8##_type
#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
typename p2##_type, typename p3##_type, typename p4##_type, \
typename p5##_type, typename p6##_type, typename p7##_type, \
typename p8##_type, typename p9##_type
// Initializes the value parameters.
#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
()
#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
(p0##_type gmock_p0) : p0(::std::move(gmock_p0))
#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
(p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1))
#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
(p0##_type gmock_p0, p1##_type gmock_p1, \
p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3))
#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, \
p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5))
#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7))
#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, \
p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9)\
(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
p9(::std::move(gmock_p9))
// Various overloads for Invoke(). // Defines the copy constructor
#define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \
{} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
#define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default;
#define GMOCK_INTERNAL_DEFN_COPY_AND_10_VALUE_PARAMS(...) = default;
// Declares the fields for storing the value parameters.
#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
p1##_type p1;
#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
p1##_type p1; p2##_type p2;
#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
p1##_type p1; p2##_type p2; p3##_type p3;
#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
p5##_type p5;
#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
p5##_type p5; p6##_type p6;
#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
p5##_type p5; p6##_type p6; p7##_type p7;
#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
p9##_type p9;
// Lists the value parameters.
#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
p2, p3, p4
#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
p1, p2, p3, p4, p5
#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) p0, p1, p2, p3, p4, p5, p6
#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) p0, p1, p2, p3, p4, p5, p6, p7
#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
// Lists the value parameter types.
#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
p1##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
p1##_type, p2##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
p0##_type, p1##_type, p2##_type, p3##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
p6##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
p5##_type, p6##_type, p7##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
p5##_type, p6##_type, p7##_type, p8##_type
#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
// Declares the value parameters.
#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
p1##_type p1
#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
p1##_type p1, p2##_type p2
#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
p1##_type p1, p2##_type p2, p3##_type p3
#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5
#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6
#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
p5##_type p5, p6##_type p6, p7##_type p7
#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
p9##_type p9
// The suffix of the class template implementing the action template.
#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7) P8
#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8) P9
#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
p7, p8, p9) P10
// The name of the class template implementing the action template.
#define GMOCK_ACTION_CLASS_(name, value_params)\
GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
#define ACTION_TEMPLATE(name, template_params, value_params) \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
class GMOCK_ACTION_CLASS_(name, value_params) { \
public: \
explicit GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_INTERNAL_DECL_##value_params) \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
= default; , \
: impl_(std::make_shared<gmock_Impl>( \
GMOCK_INTERNAL_LIST_##value_params)) { }) \
GMOCK_ACTION_CLASS_(name, value_params)( \
const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \
GMOCK_INTERNAL_DEFN_COPY_##value_params \
GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept \
GMOCK_INTERNAL_DEFN_COPY_##value_params \
template <typename F> \
operator ::testing::Action<F>() const { \
return GMOCK_PP_IF( \
GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
(::testing::internal::MakeAction<F, gmock_Impl>()), \
(::testing::internal::MakeAction<F>(impl_))); \
} \
private: \
class gmock_Impl { \
public: \
explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {} \
template <typename function_type, typename return_type, \
typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
GMOCK_INTERNAL_DEFN_##value_params \
}; \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
, std::shared_ptr<const gmock_Impl> impl_;) \
}; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
inline GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
GMOCK_INTERNAL_DECL_##value_params) { \
return GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
GMOCK_INTERNAL_LIST_##value_params); \
} \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
template <typename function_type, typename return_type, typename args_type, \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type GMOCK_ACTION_CLASS_(name, value_params)< \
GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
namespace testing {
// The ACTION*() macros trigger warning C4100 (unreferenced formal // The ACTION*() macros trigger warning C4100 (unreferenced formal
// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
@ -73,90 +499,75 @@ inline OutputIterator CopyElements(InputIterator first,
# pragma warning(disable:4100) # pragma warning(disable:4100)
#endif #endif
// Action ReturnArg<k>() returns the k-th argument of the mock function. namespace internal {
ACTION_TEMPLATE(ReturnArg,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_0_VALUE_PARAMS()) {
return ::std::get<k>(args);
}
// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the // internal::InvokeArgument - a helper for InvokeArgument action.
// mock function to *pointer. // The basic overloads are provided here for generic functors.
ACTION_TEMPLATE(SaveArg, // Overloads for other custom-callables are provided in the
HAS_1_TEMPLATE_PARAMS(int, k), // internal/custom/gmock-generated-actions.h header.
AND_1_VALUE_PARAMS(pointer)) { template <typename F, typename... Args>
*pointer = ::std::get<k>(args); auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {
return f(args...);
} }
// Action SaveArgPointee<k>(pointer) saves the value pointed to template <std::size_t index, typename... Params>
// by the k-th (0-based) argument of the mock function to *pointer. struct InvokeArgumentAction {
ACTION_TEMPLATE(SaveArgPointee, template <typename... Args>
HAS_1_TEMPLATE_PARAMS(int, k), auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument(
AND_1_VALUE_PARAMS(pointer)) { std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
*pointer = *::std::get<k>(args); std::declval<const Params&>()...)) {
} internal::FlatTuple<Args&&...> args_tuple(FlatTupleConstructTag{},
std::forward<Args>(args)...);
return params.Apply([&](const Params&... unpacked_params) {
auto&& callable = args_tuple.template Get<index>();
return internal::InvokeArgument(
std::forward<decltype(callable)>(callable), unpacked_params...);
});
}
// Action SetArgReferee<k>(value) assigns 'value' to the variable internal::FlatTuple<Params...> params;
// referenced by the k-th (0-based) argument of the mock function. };
ACTION_TEMPLATE(SetArgReferee,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(value)) {
typedef typename ::std::tuple_element<k, args_type>::type argk_type;
// Ensures that argument #k is a reference. If you get a compiler
// error on the next line, you are using SetArgReferee<k>(value) in
// a mock function whose k-th (0-based) argument is not a reference.
GTEST_COMPILE_ASSERT_(std::is_reference<argk_type>::value,
SetArgReferee_must_be_used_with_a_reference_argument);
::std::get<k>(args) = value;
}
// Action SetArrayArgument<k>(first, last) copies the elements in } // namespace internal
// source range [first, last) to the array pointed to by the k-th
// (0-based) argument, which can be either a pointer or an
// iterator. The action does not take ownership of the elements in the
// source range.
ACTION_TEMPLATE(SetArrayArgument,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_2_VALUE_PARAMS(first, last)) {
// Visual Studio deprecates ::std::copy, so we use our own copy in that case.
#ifdef _MSC_VER
internal::CopyElements(first, last, ::std::get<k>(args));
#else
::std::copy(first, last, ::std::get<k>(args));
#endif
}
// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock // The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th
// function. // (0-based) argument, which must be a k-ary callable, of the mock
ACTION_TEMPLATE(DeleteArg, // function, with arguments a1, a2, ..., a_k.
HAS_1_TEMPLATE_PARAMS(int, k), //
AND_0_VALUE_PARAMS()) { // Notes:
delete ::std::get<k>(args); //
// 1. The arguments are passed by value by default. If you need to
// pass an argument by reference, wrap it inside std::ref(). For
// example,
//
// InvokeArgument<1>(5, string("Hello"), std::ref(foo))
//
// passes 5 and string("Hello") by value, and passes foo by
// reference.
//
// 2. If the callable takes an argument by reference but std::ref() is
// not used, it will receive the reference to a copy of the value,
// instead of the original value. For example, when the 0-th
// argument of the mock function takes a const string&, the action
//
// InvokeArgument<0>(string("Hello"))
//
// makes a copy of the temporary string("Hello") object and passes a
// reference of the copy, instead of the original temporary object,
// to the callable. This makes it easy for a user to define an
// InvokeArgument action from temporary values and have it performed
// later.
template <std::size_t index, typename... Params>
internal::InvokeArgumentAction<index, typename std::decay<Params>::type...>
InvokeArgument(Params&&... params) {
return {internal::FlatTuple<typename std::decay<Params>::type...>(
internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
} }
// This action returns the value pointed to by 'pointer'.
ACTION_P(ReturnPointee, 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
// Suppresses the 'unreachable code' warning that VC generates in opt modes.
# ifdef _MSC_VER
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4702) // Temporarily disables warning 4702.
# endif
ACTION_P(Throw, exception) { throw exception; }
# ifdef _MSC_VER
# pragma warning(pop) // Restores the warning state.
# endif
#endif // GTEST_HAS_EXCEPTIONS
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) # pragma warning(pop)
#endif #endif
} // namespace testing } // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_

@ -30,17 +30,17 @@
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements some matchers that depend on gmock-generated-matchers.h. // This file implements some matchers that depend on gmock-matchers.h.
// //
// Note that tests are implemented in gmock-matchers_test.cc rather than // Note that tests are implemented in gmock-matchers_test.cc rather than
// gmock-more-matchers-test.cc. // gmock-more-matchers-test.cc.
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#define GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#include "gmock/gmock-generated-matchers.h" #include "gmock/gmock-matchers.h"
namespace testing { namespace testing {
@ -89,4 +89,4 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
} // namespace testing } // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_

@ -60,20 +60,91 @@
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
#include <type_traits>
#include "gmock/gmock-spec-builders.h" #include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
namespace testing { namespace testing {
template <class MockClass>
class NiceMock;
template <class MockClass>
class NaggyMock;
template <class MockClass>
class StrictMock;
namespace internal {
template <typename T>
std::true_type StrictnessModifierProbe(const NiceMock<T>&);
template <typename T>
std::true_type StrictnessModifierProbe(const NaggyMock<T>&);
template <typename T>
std::true_type StrictnessModifierProbe(const StrictMock<T>&);
std::false_type StrictnessModifierProbe(...);
template <typename T>
constexpr bool HasStrictnessModifier() {
return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value;
}
// Base classes that register and deregister with testing::Mock to alter the
// default behavior around uninteresting calls. Inheriting from one of these
// classes first and then MockClass ensures the MockClass constructor is run
// after registration, and that the MockClass destructor runs before
// deregistration. This guarantees that MockClass's constructor and destructor
// run with the same level of strictness as its instance methods.
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \
(defined(_MSC_VER) || defined(__clang__))
// We need to mark these classes with this declspec to ensure that
// the empty base class optimization is performed.
#define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases)
#else
#define GTEST_INTERNAL_EMPTY_BASE_CLASS
#endif
template <typename Base>
class NiceMockImpl {
public:
NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); }
~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
};
template <typename Base>
class NaggyMockImpl {
public:
NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); }
~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
};
template <typename Base>
class StrictMockImpl {
public:
StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); }
~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
};
} // namespace internal
template <class MockClass> template <class MockClass>
class NiceMock : public MockClass { class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
: private internal::NiceMockImpl<MockClass>,
public MockClass {
public: public:
static_assert(!internal::HasStrictnessModifier<MockClass>(),
"Can't apply NiceMock to a class hierarchy that already has a "
"strictness modifier. See "
"https://google.github.io/googletest/"
"gmock_cook_book.html#NiceStrictNaggy");
NiceMock() : MockClass() { NiceMock() : MockClass() {
::testing::Mock::AllowUninterestingCalls( static_assert(sizeof(*this) == sizeof(MockClass),
internal::ImplicitCast_<MockClass*>(this)); "The impl subclass shouldn't introduce any padding");
} }
// Ideally, we would inherit base class's constructors through a using // Ideally, we would inherit base class's constructors through a using
@ -85,21 +156,16 @@ class NiceMock : public MockClass {
// made explicit. // made explicit.
template <typename A> template <typename A>
explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) { explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {
::testing::Mock::AllowUninterestingCalls( static_assert(sizeof(*this) == sizeof(MockClass),
internal::ImplicitCast_<MockClass*>(this)); "The impl subclass shouldn't introduce any padding");
} }
template <typename A1, typename A2, typename... An> template <typename TArg1, typename TArg2, typename... An>
NiceMock(A1&& arg1, A2&& arg2, An&&... args) NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
: MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2), : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
std::forward<An>(args)...) { std::forward<An>(args)...) {
::testing::Mock::AllowUninterestingCalls( static_assert(sizeof(*this) == sizeof(MockClass),
internal::ImplicitCast_<MockClass*>(this)); "The impl subclass shouldn't introduce any padding");
}
~NiceMock() { // NOLINT
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
} }
private: private:
@ -107,11 +173,19 @@ class NiceMock : public MockClass {
}; };
template <class MockClass> template <class MockClass>
class NaggyMock : public MockClass { class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
: private internal::NaggyMockImpl<MockClass>,
public MockClass {
static_assert(!internal::HasStrictnessModifier<MockClass>(),
"Can't apply NaggyMock to a class hierarchy that already has a "
"strictness modifier. See "
"https://google.github.io/googletest/"
"gmock_cook_book.html#NiceStrictNaggy");
public: public:
NaggyMock() : MockClass() { NaggyMock() : MockClass() {
::testing::Mock::WarnUninterestingCalls( static_assert(sizeof(*this) == sizeof(MockClass),
internal::ImplicitCast_<MockClass*>(this)); "The impl subclass shouldn't introduce any padding");
} }
// Ideally, we would inherit base class's constructors through a using // Ideally, we would inherit base class's constructors through a using
@ -123,21 +197,16 @@ class NaggyMock : public MockClass {
// made explicit. // made explicit.
template <typename A> template <typename A>
explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) { explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) {
::testing::Mock::WarnUninterestingCalls( static_assert(sizeof(*this) == sizeof(MockClass),
internal::ImplicitCast_<MockClass*>(this)); "The impl subclass shouldn't introduce any padding");
} }
template <typename A1, typename A2, typename... An> template <typename TArg1, typename TArg2, typename... An>
NaggyMock(A1&& arg1, A2&& arg2, An&&... args) NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
: MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2), : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
std::forward<An>(args)...) { std::forward<An>(args)...) {
::testing::Mock::WarnUninterestingCalls( static_assert(sizeof(*this) == sizeof(MockClass),
internal::ImplicitCast_<MockClass*>(this)); "The impl subclass shouldn't introduce any padding");
}
~NaggyMock() { // NOLINT
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
} }
private: private:
@ -145,11 +214,19 @@ class NaggyMock : public MockClass {
}; };
template <class MockClass> template <class MockClass>
class StrictMock : public MockClass { class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
: private internal::StrictMockImpl<MockClass>,
public MockClass {
public: public:
static_assert(
!internal::HasStrictnessModifier<MockClass>(),
"Can't apply StrictMock to a class hierarchy that already has a "
"strictness modifier. See "
"https://google.github.io/googletest/"
"gmock_cook_book.html#NiceStrictNaggy");
StrictMock() : MockClass() { StrictMock() : MockClass() {
::testing::Mock::FailUninterestingCalls( static_assert(sizeof(*this) == sizeof(MockClass),
internal::ImplicitCast_<MockClass*>(this)); "The impl subclass shouldn't introduce any padding");
} }
// Ideally, we would inherit base class's constructors through a using // Ideally, we would inherit base class's constructors through a using
@ -161,55 +238,24 @@ class StrictMock : public MockClass {
// made explicit. // made explicit.
template <typename A> template <typename A>
explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) { explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) {
::testing::Mock::FailUninterestingCalls( static_assert(sizeof(*this) == sizeof(MockClass),
internal::ImplicitCast_<MockClass*>(this)); "The impl subclass shouldn't introduce any padding");
} }
template <typename A1, typename A2, typename... An> template <typename TArg1, typename TArg2, typename... An>
StrictMock(A1&& arg1, A2&& arg2, An&&... args) StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
: MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2), : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
std::forward<An>(args)...) { std::forward<An>(args)...) {
::testing::Mock::FailUninterestingCalls( static_assert(sizeof(*this) == sizeof(MockClass),
internal::ImplicitCast_<MockClass*>(this)); "The impl subclass shouldn't introduce any padding");
}
~StrictMock() { // NOLINT
::testing::Mock::UnregisterCallReaction(
internal::ImplicitCast_<MockClass*>(this));
} }
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock); GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
}; };
// The following specializations catch some (relatively more common) #undef GTEST_INTERNAL_EMPTY_BASE_CLASS
// user errors of nesting nice and strict mocks. They do NOT catch
// all possible errors.
// These specializations are declared but not defined, as NiceMock,
// NaggyMock, and StrictMock cannot be nested.
template <typename MockClass>
class NiceMock<NiceMock<MockClass> >;
template <typename MockClass>
class NiceMock<NaggyMock<MockClass> >;
template <typename MockClass>
class NiceMock<StrictMock<MockClass> >;
template <typename MockClass>
class NaggyMock<NiceMock<MockClass> >;
template <typename MockClass>
class NaggyMock<NaggyMock<MockClass> >;
template <typename MockClass>
class NaggyMock<StrictMock<MockClass> >;
template <typename MockClass>
class StrictMock<NiceMock<MockClass> >;
template <typename MockClass>
class StrictMock<NaggyMock<MockClass> >;
template <typename MockClass>
class StrictMock<StrictMock<MockClass> >;
} // namespace testing } // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_

@ -58,8 +58,8 @@
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#include <functional> #include <functional>
#include <map> #include <map>
@ -108,6 +108,14 @@ template <typename F> class TypedExpectation;
// Helper class for testing the Expectation class template. // Helper class for testing the Expectation class template.
class ExpectationTester; class ExpectationTester;
// Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
template <typename MockClass>
class NiceMockImpl;
template <typename MockClass>
class StrictMockImpl;
template <typename MockClass>
class NaggyMockImpl;
// Protects the mock object registry (in class Mock), all function // Protects the mock object registry (in class Mock), all function
// mockers, and all expectations. // mockers, and all expectations.
// //
@ -413,14 +421,12 @@ class GTEST_API_ Mock {
template <typename F> template <typename F>
friend class internal::FunctionMocker; friend class internal::FunctionMocker;
template <typename M> template <typename MockClass>
friend class NiceMock; friend class internal::NiceMockImpl;
template <typename MockClass>
template <typename M> friend class internal::NaggyMockImpl;
friend class NaggyMock; template <typename MockClass>
friend class internal::StrictMockImpl;
template <typename M>
friend class StrictMock;
// Tells Google Mock to allow uninteresting calls on the given mock // Tells Google Mock to allow uninteresting calls on the given mock
// object. // object.
@ -499,7 +505,10 @@ class GTEST_API_ Expectation {
public: public:
// Constructs a null object that doesn't reference any expectation. // Constructs a null object that doesn't reference any expectation.
Expectation(); Expectation();
Expectation(Expectation&&) = default;
Expectation(const Expectation&) = default;
Expectation& operator=(Expectation&&) = default;
Expectation& operator=(const Expectation&) = default;
~Expectation(); ~Expectation();
// 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
@ -879,8 +888,6 @@ class GTEST_API_ ExpectationBase {
Clause last_clause_; Clause last_clause_;
mutable bool action_count_checked_; // Under mutex_. mutable bool action_count_checked_; // Under mutex_.
mutable Mutex mutex_; // Protects action_count_checked_. mutable Mutex mutex_; // Protects action_count_checked_.
GTEST_DISALLOW_ASSIGN_(ExpectationBase);
}; // class ExpectationBase }; // class ExpectationBase
// Impements an expectation for the given function type. // Impements an expectation for the given function type.
@ -1295,8 +1302,6 @@ class MockSpec {
internal::FunctionMocker<F>* const function_mocker_; internal::FunctionMocker<F>* const function_mocker_;
// The argument matchers specified in the spec. // The argument matchers specified in the spec.
ArgumentMatcherTuple matchers_; ArgumentMatcherTuple matchers_;
GTEST_DISALLOW_ASSIGN_(MockSpec);
}; // class MockSpec }; // class MockSpec
// Wrapper type for generically holding an ordinary value or lvalue reference. // Wrapper type for generically holding an ordinary value or lvalue reference.
@ -1350,12 +1355,6 @@ class ReferenceOrValueWrapper<T&> {
T* value_ptr_; T* value_ptr_;
}; };
// MSVC warns about using 'this' in base member initializer list, so
// we need to temporarily disable the warning. We have to do it for
// the entire class to suppress the warning, even though it's about
// the constructor only.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
// C++ treats the void type specially. For example, you cannot define // C++ treats the void type specially. For example, you cannot define
// a void-typed variable or pass a void value to a function. // a void-typed variable or pass a void value to a function.
// ActionResultHolder<T> holds a value of type T, where T must be a // ActionResultHolder<T> holds a value of type T, where T must be a
@ -1786,18 +1785,87 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
} }
}; // class FunctionMocker }; // class FunctionMocker
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355
// Reports an uninteresting call (whose description is in msg) in the // Reports an uninteresting call (whose description is in msg) in the
// manner specified by 'reaction'. // manner specified by 'reaction'.
void ReportUninterestingCall(CallReaction reaction, const std::string& msg); void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
} // namespace internal } // namespace internal
// A MockFunction<F> class has one mock method whose type is F. It is namespace internal {
// useful when you just want your test code to emit some messages and
// have Google Mock verify the right messages are sent (and perhaps at template <typename F>
// the right times). For example, if you are exercising code: class MockFunction;
template <typename R, typename... Args>
class MockFunction<R(Args...)> {
public:
MockFunction(const MockFunction&) = delete;
MockFunction& operator=(const MockFunction&) = delete;
std::function<R(Args...)> AsStdFunction() {
return [this](Args... args) -> R {
return this->Call(std::forward<Args>(args)...);
};
}
// Implementation detail: the expansion of the MOCK_METHOD macro.
R Call(Args... args) {
mock_.SetOwnerAndName(this, "Call");
return mock_.Invoke(std::forward<Args>(args)...);
}
MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
mock_.RegisterOwner(this);
return mock_.With(std::move(m)...);
}
MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
return this->gmock_Call(::testing::A<Args>()...);
}
protected:
MockFunction() = default;
~MockFunction() = default;
private:
FunctionMocker<R(Args...)> mock_;
};
/*
The SignatureOf<F> struct is a meta-function returning function signature
corresponding to the provided F argument.
It makes use of MockFunction easier by allowing it to accept more F arguments
than just function signatures.
Specializations provided here cover a signature type itself and any template
that can be parameterized with a signature, including std::function and
boost::function.
*/
template <typename F, typename = void>
struct SignatureOf;
template <typename R, typename... Args>
struct SignatureOf<R(Args...)> {
using type = R(Args...);
};
template <template <typename> class C, typename F>
struct SignatureOf<C<F>,
typename std::enable_if<std::is_function<F>::value>::type>
: SignatureOf<F> {};
template <typename F>
using SignatureOfT = typename SignatureOf<F>::type;
} // namespace internal
// A MockFunction<F> type has one mock method whose type is
// internal::SignatureOfT<F>. It is useful when you just want your
// test code to emit some messages and have Google Mock verify the
// right messages are sent (and perhaps at the right times). For
// example, if you are exercising code:
// //
// Foo(1); // Foo(1);
// Foo(2); // Foo(2);
@ -1831,49 +1899,34 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
// Bar("a") is called by which call to Foo(). // Bar("a") is called by which call to Foo().
// //
// MockFunction<F> can also be used to exercise code that accepts // MockFunction<F> can also be used to exercise code that accepts
// std::function<F> callbacks. To do so, use AsStdFunction() method // std::function<internal::SignatureOfT<F>> callbacks. To do so, use
// to create std::function proxy forwarding to original object's Call. // AsStdFunction() method to create std::function proxy forwarding to
// Example: // original object's Call. Example:
// //
// TEST(FooTest, RunsCallbackWithBarArgument) { // TEST(FooTest, RunsCallbackWithBarArgument) {
// MockFunction<int(string)> callback; // MockFunction<int(string)> callback;
// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1)); // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
// Foo(callback.AsStdFunction()); // Foo(callback.AsStdFunction());
// } // }
//
// The internal::SignatureOfT<F> indirection allows to use other types
// than just function signature type. This is typically useful when
// providing a mock for a predefined std::function type. Example:
//
// using FilterPredicate = std::function<bool(string)>;
// void MyFilterAlgorithm(FilterPredicate predicate);
//
// TEST(FooTest, FilterPredicateAlwaysAccepts) {
// MockFunction<FilterPredicate> predicateMock;
// EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
// MyFilterAlgorithm(predicateMock.AsStdFunction());
// }
template <typename F> template <typename F>
class MockFunction; class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
using Base = internal::MockFunction<internal::SignatureOfT<F>>;
template <typename R, typename... Args>
class MockFunction<R(Args...)> {
public: public:
MockFunction() {} using Base::Base;
MockFunction(const MockFunction&) = delete;
MockFunction& operator=(const MockFunction&) = delete;
std::function<R(Args...)> AsStdFunction() {
return [this](Args... args) -> R {
return this->Call(std::forward<Args>(args)...);
};
}
// Implementation detail: the expansion of the MOCK_METHOD macro.
R Call(Args... args) {
mock_.SetOwnerAndName(this, "Call");
return mock_.Invoke(std::forward<Args>(args)...);
}
internal::MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
mock_.RegisterOwner(this);
return mock_.With(std::move(m)...);
}
internal::MockSpec<R(Args...)> gmock_Call(const internal::WithoutMatchers&,
R (*)(Args...)) {
return this->gmock_Call(::testing::A<Args>()...);
}
private:
internal::FunctionMocker<R(Args...)> mock_;
}; };
// The style guide prohibits "using" statements in a namespace scope // The style guide prohibits "using" statements in a namespace scope
@ -1982,4 +2035,4 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#define EXPECT_CALL(obj, call) \ #define EXPECT_CALL(obj, call) \
GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call) GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_

@ -34,8 +34,8 @@
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
// This file implements the following syntax: // This file implements the following syntax:
// //
@ -59,9 +59,6 @@
#include "gmock/gmock-actions.h" #include "gmock/gmock-actions.h"
#include "gmock/gmock-cardinalities.h" #include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-function-mocker.h" #include "gmock/gmock-function-mocker.h"
#include "gmock/gmock-generated-actions.h"
#include "gmock/gmock-generated-function-mockers.h"
#include "gmock/gmock-generated-matchers.h"
#include "gmock/gmock-matchers.h" #include "gmock/gmock-matchers.h"
#include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-actions.h"
#include "gmock/gmock-more-matchers.h" #include "gmock/gmock-more-matchers.h"
@ -98,4 +95,4 @@ GTEST_API_ void InitGoogleMock();
} // namespace testing } // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_

@ -1,10 +1,6 @@
// This file was GENERATED by command:
// pump.py gmock-generated-actions.h.pump
// DO NOT EDIT BY HAND!!!
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_

@ -1,12 +0,0 @@
$$ -*- mode: c++; -*-
$$ This is a Pump source file. Please use Pump to convert
$$ it to callback-actions.h.
$$
$var max_callback_arity = 5
$$}} This meta comment fixes auto-indentation in editors.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_

@ -31,6 +31,6 @@
// //
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_

@ -33,7 +33,7 @@
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_

@ -36,8 +36,8 @@
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
#include <stdio.h> #include <stdio.h>
#include <ostream> // NOLINT #include <ostream> // NOLINT
@ -71,20 +71,6 @@ GTEST_API_ std::string JoinAsTuple(const Strings& fields);
// "foo_bar_123" are converted to "foo bar 123". // "foo_bar_123" are converted to "foo bar 123".
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name); GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
// PointeeOf<Pointer>::type is the type of a value pointed to by a
// Pointer, which can be either a smart pointer or a raw pointer. The
// following default implementation is for the case where Pointer is a
// smart pointer.
template <typename Pointer>
struct PointeeOf {
// Smart pointer classes define type element_type as the type of
// their pointees.
typedef typename Pointer::element_type type;
};
// This specialization is for the raw pointer case.
template <typename T>
struct PointeeOf<T*> { typedef T type; }; // NOLINT
// GetRawPointer(p) returns the raw pointer underlying p when p is a // GetRawPointer(p) returns the raw pointer underlying p when p is a
// smart pointer, or returns p itself when p is already a raw pointer. // smart pointer, or returns p itself when p is already a raw pointer.
// The following default implementation is for the smart pointer case. // The following default implementation is for the smart pointer case.
@ -136,15 +122,13 @@ GMOCK_DECLARE_KIND_(int, kInteger);
GMOCK_DECLARE_KIND_(unsigned int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger);
GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(long long, kInteger); // NOLINT
GMOCK_DECLARE_KIND_(unsigned long long, kInteger); // NOLINT
#if GMOCK_WCHAR_T_IS_NATIVE_ #if GMOCK_WCHAR_T_IS_NATIVE_
GMOCK_DECLARE_KIND_(wchar_t, kInteger); GMOCK_DECLARE_KIND_(wchar_t, kInteger);
#endif #endif
// Non-standard integer types.
GMOCK_DECLARE_KIND_(Int64, kInteger);
GMOCK_DECLARE_KIND_(UInt64, kInteger);
// All standard floating-point types. // All standard floating-point types.
GMOCK_DECLARE_KIND_(float, kFloatingPoint); GMOCK_DECLARE_KIND_(float, kFloatingPoint);
GMOCK_DECLARE_KIND_(double, kFloatingPoint); GMOCK_DECLARE_KIND_(double, kFloatingPoint);
@ -157,9 +141,6 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
static_cast< ::testing::internal::TypeKind>( \ static_cast< ::testing::internal::TypeKind>( \
::testing::internal::KindOf<type>::value) ::testing::internal::KindOf<type>::value)
// Evaluates to true if and only if integer type T is signed.
#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
// is true if and only if arithmetic type From can be losslessly converted to // is true if and only if arithmetic type From can be losslessly converted to
// arithmetic type To. // arithmetic type To.
@ -170,65 +151,30 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
// From, and kToKind is the kind of To; the value is // From, and kToKind is the kind of To; the value is
// implementation-defined when the above pre-condition is violated. // implementation-defined when the above pre-condition is violated.
template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To> template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
struct LosslessArithmeticConvertibleImpl : public std::false_type {}; using LosslessArithmeticConvertibleImpl = std::integral_constant<
bool,
// Converting bool to bool is lossless. // clang-format off
template <> // Converting from bool is always lossless
struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool> (kFromKind == kBool) ? true
: public std::true_type {}; // Converting between any other type kinds will be lossy if the type
// kinds are not the same.
// Converting bool to any integer type is lossless. : (kFromKind != kToKind) ? false
template <typename To> : (kFromKind == kInteger &&
struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To> // Converting between integers of different widths is allowed so long
: public std::true_type {}; // as the conversion does not go from signed to unsigned.
(((sizeof(From) < sizeof(To)) &&
// Converting bool to any floating-point type is lossless. !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||
template <typename To> // Converting between integers of the same width only requires the
struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To> // two types to have the same signedness.
: public std::true_type {}; ((sizeof(From) == sizeof(To)) &&
(std::is_signed<From>::value == std::is_signed<To>::value)))
// Converting an integer to bool is lossy. ) ? true
template <typename From> // Floating point conversions are lossless if and only if `To` is at least
struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool> // as wide as `From`.
: public std::false_type {}; : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true
: false
// Converting an integer to another non-bool integer is lossless // clang-format on
// if and only if the target type's range encloses the source type's range. >;
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
: public bool_constant<
// When converting from a smaller size to a larger size, we are
// fine as long as we are not converting from signed to unsigned.
((sizeof(From) < sizeof(To)) &&
(!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
// When converting between the same size, the signedness must match.
((sizeof(From) == sizeof(To)) &&
(GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT
#undef GMOCK_IS_SIGNED_
// Converting an integer to a floating-point type may be lossy, since
// the format of a floating-point number is implementation-defined.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
: public std::false_type {};
// Converting a floating-point to bool is lossy.
template <typename From>
struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
: public std::false_type {};
// Converting a floating-point to an integer is lossy.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
: public std::false_type {};
// Converting a floating-point to another floating-point is lossless
// if and only if the target type is at least as big as the source type.
template <typename From, typename To>
struct LosslessArithmeticConvertibleImpl<
kFloatingPoint, From, kFloatingPoint, To>
: public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT
// LosslessArithmeticConvertible<From, To>::value is true if and only if // LosslessArithmeticConvertible<From, To>::value is true if and only if
// arithmetic type From can be losslessly converted to arithmetic type To. // arithmetic type From can be losslessly converted to arithmetic type To.
@ -238,9 +184,9 @@ struct LosslessArithmeticConvertibleImpl<
// reference) built-in arithmetic types; the value is // reference) built-in arithmetic types; the value is
// implementation-defined when the above pre-condition is violated. // implementation-defined when the above pre-condition is violated.
template <typename From, typename To> template <typename From, typename To>
struct LosslessArithmeticConvertible using LosslessArithmeticConvertible =
: public LosslessArithmeticConvertibleImpl< LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,
GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT GMOCK_KIND_OF_(To), To>;
// This interface knows how to report a Google Mock failure (either // This interface knows how to report a Google Mock failure (either
// non-fatal or fatal). // non-fatal or fatal).
@ -334,8 +280,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();
// Type traits.
// Disable MSVC warnings for infinite recursion, since in this case the // Disable MSVC warnings for infinite recursion, since in this case the
// the recursion is unreachable. // the recursion is unreachable.
#ifdef _MSC_VER #ifdef _MSC_VER
@ -420,7 +364,8 @@ template <typename ElementPointer, typename Size>
class StlContainerView< ::std::tuple<ElementPointer, Size> > { class StlContainerView< ::std::tuple<ElementPointer, Size> > {
public: public:
typedef typename std::remove_const< typedef typename std::remove_const<
typename internal::PointeeOf<ElementPointer>::type>::type RawElement; typename std::pointer_traits<ElementPointer>::element_type>::type
RawElement;
typedef internal::NativeArray<RawElement> type; typedef internal::NativeArray<RawElement> type;
typedef const type const_reference; typedef const type const_reference;
@ -464,11 +409,13 @@ auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
// 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) auto Apply(F&& f, Tuple&& args) -> decltype(
-> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args), ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size<Tuple>::value>())) { MakeIndexSequence<std::tuple_size<
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<Tuple>::value>()); MakeIndexSequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>());
} }
// Template struct Function<F>, where F must be a function type, contains // Template struct Function<F>, where F must be a function type, contains
@ -492,8 +439,7 @@ struct Function<R(Args...)> {
using Result = R; using Result = R;
static constexpr size_t ArgumentCount = sizeof...(Args); static constexpr size_t ArgumentCount = sizeof...(Args);
template <size_t I> template <size_t I>
using Arg = ElemFromList<I, typename MakeIndexSequence<sizeof...(Args)>::type, using Arg = ElemFromList<I, Args...>;
Args...>;
using ArgumentTuple = std::tuple<Args...>; using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>; using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
using MakeResultVoid = void(Args...); using MakeResultVoid = void(Args...);
@ -510,4 +456,4 @@ constexpr size_t Function<R(Args...)>::ArgumentCount;
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_

@ -37,11 +37,12 @@
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
#include <assert.h> #include <assert.h>
#include <stdlib.h> #include <stdlib.h>
#include <cstdint>
#include <iostream> #include <iostream>
// Most of the utilities needed for porting Google Mock are also // Most of the utilities needed for porting Google Mock are also
@ -69,8 +70,7 @@
// Macros for declaring flags. // Macros for declaring flags.
# define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) # define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
# define GMOCK_DECLARE_int32_(name) \ # define GMOCK_DECLARE_int32_(name) extern GTEST_API_ int32_t GMOCK_FLAG(name)
extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name)
# define GMOCK_DECLARE_string_(name) \ # define GMOCK_DECLARE_string_(name) \
extern GTEST_API_ ::std::string GMOCK_FLAG(name) extern GTEST_API_ ::std::string GMOCK_FLAG(name)
@ -78,10 +78,10 @@
# define GMOCK_DEFINE_bool_(name, default_val, doc) \ # define GMOCK_DEFINE_bool_(name, default_val, doc) \
GTEST_API_ bool GMOCK_FLAG(name) = (default_val) GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
# define GMOCK_DEFINE_int32_(name, default_val, doc) \ # define GMOCK_DEFINE_int32_(name, default_val, doc) \
GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val) GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val)
# define GMOCK_DEFINE_string_(name, default_val, doc) \ # define GMOCK_DEFINE_string_(name, default_val, doc) \
GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
#endif // !defined(GMOCK_DECLARE_bool_) #endif // !defined(GMOCK_DECLARE_bool_)
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_

@ -1,18 +1,5 @@
#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
#undef GMOCK_PP_INTERNAL_USE_MSVC
#if defined(__clang__)
#define GMOCK_PP_INTERNAL_USE_MSVC 0
#elif defined(_MSC_VER)
// TODO(iserna): Also verify tradional versus comformant preprocessor.
static_assert(
_MSC_VER >= 1900,
"MSVC version not supported. There is support for MSVC 14.0 and above.");
#define GMOCK_PP_INTERNAL_USE_MSVC 1
#else
#define GMOCK_PP_INTERNAL_USE_MSVC 0
#endif
// Expands and concatenates the arguments. Constructed macros reevaluate. // Expands and concatenates the arguments. Constructed macros reevaluate.
#define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2) #define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2)
@ -29,10 +16,6 @@ static_assert(
// Returns the only argument. // Returns the only argument.
#define GMOCK_PP_IDENTITY(_1) _1 #define GMOCK_PP_IDENTITY(_1) _1
// MSVC preprocessor collapses __VA_ARGS__ in a single argument, we use a
// CAT-like directive to force correct evaluation. Each macro has its own.
#if GMOCK_PP_INTERNAL_USE_MSVC
// Evaluates to the number of arguments after expansion. // Evaluates to the number of arguments after expansion.
// //
// #define PAIR x, y // #define PAIR x, y
@ -43,45 +26,27 @@ static_assert(
// GMOCK_PP_NARG(PAIR) => 2 // GMOCK_PP_NARG(PAIR) => 2
// //
// Requires: the number of arguments after expansion is at most 15. // Requires: the number of arguments after expansion is at most 15.
#define GMOCK_PP_NARG(...) \ #define GMOCK_PP_NARG(...) \
GMOCK_PP_INTERNAL_NARG_CAT( \ GMOCK_PP_INTERNAL_16TH( \
GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, \ (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
8, 7, 6, 5, 4, 3, 2, 1), )
// Returns 1 if the expansion of arguments has an unprotected comma. Otherwise // Returns 1 if the expansion of arguments has an unprotected comma. Otherwise
// returns 0. Requires no more than 15 unprotected commas. // returns 0. Requires no more than 15 unprotected commas.
#define GMOCK_PP_HAS_COMMA(...) \ #define GMOCK_PP_HAS_COMMA(...) \
GMOCK_PP_INTERNAL_HAS_COMMA_CAT( \ GMOCK_PP_INTERNAL_16TH( \
GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, \ (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0))
1, 1, 1, 1, 1, 0), )
// Returns the first argument. // Returns the first argument.
#define GMOCK_PP_HEAD(...) \ #define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg))
GMOCK_PP_INTERNAL_HEAD_CAT(GMOCK_PP_INTERNAL_HEAD(__VA_ARGS__), )
// Returns the tail. A variadic list of all arguments minus the first. Requires // Returns the tail. A variadic list of all arguments minus the first. Requires
// at least one argument. // at least one argument.
#define GMOCK_PP_TAIL(...) \ #define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__))
GMOCK_PP_INTERNAL_TAIL_CAT(GMOCK_PP_INTERNAL_TAIL(__VA_ARGS__), )
// Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__) // Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__)
#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ #define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \
GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT( \ GMOCK_PP_IDENTITY( \
GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__), ) GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__))
#else // GMOCK_PP_INTERNAL_USE_MSVC
#define GMOCK_PP_NARG(...) \
GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, \
7, 6, 5, 4, 3, 2, 1)
#define GMOCK_PP_HAS_COMMA(...) \
GMOCK_PP_INTERNAL_INTERNAL_16TH(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 0)
#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD(__VA_ARGS__)
#define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL(__VA_ARGS__)
#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \
GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__)
#endif // GMOCK_PP_INTERNAL_USE_MSVC
// If the arguments after expansion have no tokens, evaluates to `1`. Otherwise // If the arguments after expansion have no tokens, evaluates to `1`. Otherwise
// evaluates to `0`. // evaluates to `0`.
@ -121,6 +86,14 @@ static_assert(
#define GMOCK_PP_IF(_Cond, _Then, _Else) \ #define GMOCK_PP_IF(_Cond, _Then, _Else) \
GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else)
// Similar to GMOCK_PP_IF but takes _Then and _Else in parentheses.
//
// GMOCK_PP_GENERIC_IF(1, (a, b, c), (d, e, f)) => a, b, c
// GMOCK_PP_GENERIC_IF(0, (a, b, c), (d, e, f)) => d, e, f
//
#define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \
GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else))
// Evaluates to the number of arguments after expansion. Identifies 'empty' as // Evaluates to the number of arguments after expansion. Identifies 'empty' as
// 0. // 0.
// //
@ -139,10 +112,9 @@ static_assert(
// Expands to 1 if the first argument starts with something in parentheses, // Expands to 1 if the first argument starts with something in parentheses,
// otherwise to 0. // otherwise to 0.
#define GMOCK_PP_IS_BEGIN_PARENS(...) \ #define GMOCK_PP_IS_BEGIN_PARENS(...) \
GMOCK_PP_INTERNAL_ALTERNATE_HEAD( \ GMOCK_PP_HEAD(GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \
GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \ GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__))
GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__))
// Expands to 1 is there is only one argument and it is enclosed in parentheses. // Expands to 1 is there is only one argument and it is enclosed in parentheses.
#define GMOCK_PP_IS_ENCLOSED_PARENS(...) \ #define GMOCK_PP_IS_ENCLOSED_PARENS(...) \
@ -179,10 +151,6 @@ static_assert(
#define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , ) #define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , )
#define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2 #define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2
#define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__ #define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__
#define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \
_10, _11, _12, _13, _14, _15, _16, \
...) \
_16
#define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5 #define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5
#define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \ #define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \
GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \ GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \
@ -190,30 +158,24 @@ static_assert(
#define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 , #define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 ,
#define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then #define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then
#define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else #define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else
#define GMOCK_PP_INTERNAL_HEAD(_1, ...) _1
#define GMOCK_PP_INTERNAL_TAIL(_1, ...) __VA_ARGS__
#if GMOCK_PP_INTERNAL_USE_MSVC // Because of MSVC treating a token with a comma in it as a single token when
#define GMOCK_PP_INTERNAL_NARG_CAT(_1, _2) GMOCK_PP_INTERNAL_NARG_CAT_I(_1, _2) // passed to another macro, we need to force it to evaluate it as multiple
#define GMOCK_PP_INTERNAL_HEAD_CAT(_1, _2) GMOCK_PP_INTERNAL_HEAD_CAT_I(_1, _2) // tokens. We do that by using a "IDENTITY(MACRO PARENTHESIZED_ARGS)" macro. We
#define GMOCK_PP_INTERNAL_HAS_COMMA_CAT(_1, _2) \ // define one per possible macro that relies on this behavior. Note "_Args" must
GMOCK_PP_INTERNAL_HAS_COMMA_CAT_I(_1, _2) // be parenthesized.
#define GMOCK_PP_INTERNAL_TAIL_CAT(_1, _2) GMOCK_PP_INTERNAL_TAIL_CAT_I(_1, _2) #define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \
#define GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT(_1, _2) \ _10, _11, _12, _13, _14, _15, _16, \
GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT_I(_1, _2) ...) \
#define GMOCK_PP_INTERNAL_NARG_CAT_I(_1, _2) _1##_2 _16
#define GMOCK_PP_INTERNAL_HEAD_CAT_I(_1, _2) _1##_2 #define GMOCK_PP_INTERNAL_16TH(_Args) \
#define GMOCK_PP_INTERNAL_HAS_COMMA_CAT_I(_1, _2) _1##_2 GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args)
#define GMOCK_PP_INTERNAL_TAIL_CAT_I(_1, _2) _1##_2 #define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1
#define GMOCK_PP_INTERNAL_VARIADIC_CALL_CAT_I(_1, _2) _1##_2 #define GMOCK_PP_INTERNAL_HEAD(_Args) \
#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD(...) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args)
GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT(GMOCK_PP_HEAD(__VA_ARGS__), ) #define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__
#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT(_1, _2) \ #define GMOCK_PP_INTERNAL_TAIL(_Args) \
GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT_I(_1, _2) GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args)
#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD_CAT_I(_1, _2) _1##_2
#else // GMOCK_PP_INTERNAL_USE_MSVC
#define GMOCK_PP_INTERNAL_ALTERNATE_HEAD(...) GMOCK_PP_HEAD(__VA_ARGS__)
#endif // GMOCK_PP_INTERNAL_USE_MSVC
#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _ #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _
#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1, #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1,
@ -314,4 +276,4 @@ static_assert(
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple)) (GMOCK_PP_TAIL _Tuple))
#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_

@ -28,8 +28,8 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (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.
"""fuse_gmock_files.py v0.1.0.
"""fuse_gmock_files.py v0.1.0
Fuses Google Mock and Google Test source code into two .h files and a .cc file. Fuses Google Mock and Google Test source code into two .h files and a .cc file.
SYNOPSIS SYNOPSIS
@ -55,27 +55,29 @@ EXAMPLES
This tool is experimental. In particular, it assumes that there is no This tool is experimental. In particular, it assumes that there is no
conditional inclusion of Google Mock or Google Test headers. Please conditional inclusion of Google Mock or Google Test headers. Please
report any problems to googlemock@googlegroups.com. You can read report any problems to googlemock@googlegroups.com. You can read
https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md for more https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
for more
information. information.
""" """
__author__ = 'wan@google.com (Zhanyong Wan)' from __future__ import print_function
import os import os
import re import re
import sets
import sys import sys
__author__ = 'wan@google.com (Zhanyong Wan)'
# We assume that this file is in the scripts/ directory in the Google # We assume that this file is in the scripts/ directory in the Google
# Mock root directory. # Mock root directory.
DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..') DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# We need to call into googletest/scripts/fuse_gtest_files.py. # We need to call into googletest/scripts/fuse_gtest_files.py.
sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, '../googletest/scripts')) sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, '../googletest/scripts'))
import fuse_gtest_files import fuse_gtest_files as gtest # pylint:disable=g-import-not-at-top
gtest = fuse_gtest_files
# Regex for matching '#include "gmock/..."'. # Regex for matching
# '#include "gmock/..."'.
INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gmock/.+)"') INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gmock/.+)"')
# Where to find the source seed files. # Where to find the source seed files.
@ -98,6 +100,9 @@ def ValidateGMockRootDir(gmock_root):
"""Makes sure gmock_root points to a valid gmock root directory. """Makes sure gmock_root points to a valid gmock root directory.
The function aborts the program on failure. The function aborts the program on failure.
Args:
gmock_root: A string with the mock root directory.
""" """
gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root)) gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root))
@ -109,6 +114,9 @@ def ValidateOutputDir(output_dir):
"""Makes sure output_dir points to a valid output directory. """Makes sure output_dir points to a valid output directory.
The function aborts the program on failure. The function aborts the program on failure.
Args:
output_dir: A string representing the output directory.
""" """
gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT) gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT)
@ -119,8 +127,8 @@ def ValidateOutputDir(output_dir):
def FuseGMockH(gmock_root, output_dir): def FuseGMockH(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock/gmock.h in output_dir.""" """Scans folder gmock_root to generate gmock/gmock.h in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w') output_file = open(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
processed_files = sets.Set() # Holds all gmock headers we've processed. processed_files = set() # Holds all gmock headers we've processed.
def ProcessFile(gmock_header_path): def ProcessFile(gmock_header_path):
"""Processes the given gmock header file.""" """Processes the given gmock header file."""
@ -132,25 +140,28 @@ def FuseGMockH(gmock_root, output_dir):
processed_files.add(gmock_header_path) processed_files.add(gmock_header_path)
# Reads each line in the given gmock header. # Reads each line in the given gmock header.
for line in file(os.path.join(gmock_root, gmock_header_path), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line) with open(os.path.join(gmock_root, gmock_header_path), 'r') as fh:
if m: for line in fh:
# It's '#include "gmock/..."' - let's process it recursively. m = INCLUDE_GMOCK_FILE_REGEX.match(line)
ProcessFile('include/' + m.group(1))
else:
m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m: if m:
# It's '#include "gtest/foo.h"'. We translate it to # '#include "gmock/..."'
# "gtest/gtest.h", regardless of what foo is, since all # - let's process it recursively.
# gtest headers are fused into gtest/gtest.h. ProcessFile('include/' + m.group(1))
# There is no need to #include gtest.h twice.
if not gtest.GTEST_H_SEED in processed_files:
processed_files.add(gtest.GTEST_H_SEED)
output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,))
else: else:
# Otherwise we copy the line unchanged to the output file. m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
output_file.write(line) if m:
# '#include "gtest/foo.h"'
# We translate it to "gtest/gtest.h", regardless of what foo is,
# since all gtest headers are fused into gtest/gtest.h.
# There is no need to #include gtest.h twice.
if gtest.GTEST_H_SEED not in processed_files:
processed_files.add(gtest.GTEST_H_SEED)
output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GMOCK_H_SEED) ProcessFile(GMOCK_H_SEED)
output_file.close() output_file.close()
@ -159,7 +170,7 @@ def FuseGMockH(gmock_root, output_dir):
def FuseGMockAllCcToFile(gmock_root, output_file): def FuseGMockAllCcToFile(gmock_root, output_file):
"""Scans folder gmock_root to fuse gmock-all.cc into output_file.""" """Scans folder gmock_root to fuse gmock-all.cc into output_file."""
processed_files = sets.Set() processed_files = set()
def ProcessFile(gmock_source_file): def ProcessFile(gmock_source_file):
"""Processes the given gmock source file.""" """Processes the given gmock source file."""
@ -171,32 +182,37 @@ def FuseGMockAllCcToFile(gmock_root, output_file):
processed_files.add(gmock_source_file) processed_files.add(gmock_source_file)
# Reads each line in the given gmock source file. # Reads each line in the given gmock source file.
for line in file(os.path.join(gmock_root, gmock_source_file), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line) with open(os.path.join(gmock_root, gmock_source_file), 'r') as fh:
if m: for line in fh:
# It's '#include "gmock/foo.h"'. We treat it as '#include m = INCLUDE_GMOCK_FILE_REGEX.match(line)
# "gmock/gmock.h"', as all other gmock headers are being fused
# into gmock.h and cannot be #included directly.
# There is no need to #include "gmock/gmock.h" more than once.
if not GMOCK_H_SEED in processed_files:
processed_files.add(GMOCK_H_SEED)
output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
else:
m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m: if m:
# It's '#include "gtest/..."'. # '#include "gmock/foo.h"'
# There is no need to #include gtest.h as it has been # We treat it as '#include "gmock/gmock.h"', as all other gmock
# #included by gtest-all.cc. # headers are being fused into gmock.h and cannot be
pass # included directly. No need to
# #include "gmock/gmock.h"
# more than once.
if GMOCK_H_SEED not in processed_files:
processed_files.add(GMOCK_H_SEED)
output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
else: else:
m = gtest.INCLUDE_SRC_FILE_REGEX.match(line) m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m: if m:
# It's '#include "src/foo"' - let's process it recursively. # '#include "gtest/..."'
ProcessFile(m.group(1)) # There is no need to #include gtest.h as it has been
# #included by gtest-all.cc.
pass
else: else:
# Otherwise we copy the line unchanged to the output file. m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
output_file.write(line) if m:
# It's '#include "src/foo"' - let's process it recursively.
ProcessFile(m.group(1))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GMOCK_ALL_CC_SEED) ProcessFile(GMOCK_ALL_CC_SEED)
@ -204,12 +220,12 @@ def FuseGMockAllCcToFile(gmock_root, output_file):
def FuseGMockGTestAllCc(gmock_root, output_dir): def FuseGMockGTestAllCc(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir.""" """Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w') with open(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT),
# First, fuse gtest-all.cc into gmock-gtest-all.cc. 'w') as output_file:
gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file) # First, fuse gtest-all.cc into gmock-gtest-all.cc.
# Next, append fused gmock-all.cc to gmock-gtest-all.cc. gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
FuseGMockAllCcToFile(gmock_root, output_file) # Next, append fused gmock-all.cc to gmock-gtest-all.cc.
output_file.close() FuseGMockAllCcToFile(gmock_root, output_file)
def FuseGMock(gmock_root, output_dir): def FuseGMock(gmock_root, output_dir):
@ -232,7 +248,7 @@ def main():
# fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR # fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR
FuseGMock(sys.argv[1], sys.argv[2]) FuseGMock(sys.argv[1], sys.argv[2])
else: else:
print __doc__ print(__doc__)
sys.exit(1) sys.exit(1)

File diff suppressed because it is too large Load Diff

@ -26,9 +26,6 @@ Usage:
Output is sent to stdout. Output is sent to stdout.
""" """
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os import os
import re import re
import sys import sys
@ -41,6 +38,7 @@ try:
_dummy = set _dummy = set
except NameError: except NameError:
import sets import sets
set = sets.Set set = sets.Set
_VERSION = (1, 0, 1) # The version of this script. _VERSION = (1, 0, 1) # The version of this script.
@ -48,79 +46,100 @@ _VERSION = (1, 0, 1) # The version of this script.
_INDENT = 2 _INDENT = 2
def _RenderType(ast_type):
"""Renders the potentially recursively templated type into a string.
Args:
ast_type: The AST of the type.
Returns:
Rendered string of the type.
"""
# Add modifiers like 'const'.
modifiers = ''
if ast_type.modifiers:
modifiers = ' '.join(ast_type.modifiers) + ' '
return_type = modifiers + ast_type.name
if ast_type.templated_types:
# Collect template args.
template_args = []
for arg in ast_type.templated_types:
rendered_arg = _RenderType(arg)
template_args.append(rendered_arg)
return_type += '<' + ', '.join(template_args) + '>'
if ast_type.pointer:
return_type += '*'
if ast_type.reference:
return_type += '&'
return return_type
def _GenerateArg(source):
"""Strips out comments, default arguments, and redundant spaces from a single argument.
Args:
source: A string for a single argument.
Returns:
Rendered string of the argument.
"""
# Remove end of line comments before eliminating newlines.
arg = re.sub(r'//.*', '', source)
# Remove c-style comments.
arg = re.sub(r'/\*.*\*/', '', arg)
# Remove default arguments.
arg = re.sub(r'=.*', '', arg)
# Collapse spaces and newlines into a single space.
arg = re.sub(r'\s+', ' ', arg)
return arg.strip()
def _EscapeForMacro(s):
"""Escapes a string for use as an argument to a C++ macro."""
paren_count = 0
for c in s:
if c == '(':
paren_count += 1
elif c == ')':
paren_count -= 1
elif c == ',' and paren_count == 0:
return '(' + s + ')'
return s
def _GenerateMethods(output_lines, source, class_node): def _GenerateMethods(output_lines, source, class_node):
function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | function_type = (
ast.FUNCTION_OVERRIDE) ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | ast.FUNCTION_OVERRIDE)
ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
indent = ' ' * _INDENT indent = ' ' * _INDENT
for node in class_node.body: for node in class_node.body:
# We only care about virtual functions. # We only care about virtual functions.
if (isinstance(node, ast.Function) and if (isinstance(node, ast.Function) and node.modifiers & function_type and
node.modifiers & function_type and
not node.modifiers & ctor_or_dtor): not node.modifiers & ctor_or_dtor):
# Pick out all the elements we need from the original function. # Pick out all the elements we need from the original function.
const = '' modifiers = 'override'
if node.modifiers & ast.FUNCTION_CONST: if node.modifiers & ast.FUNCTION_CONST:
const = 'CONST_' modifiers = 'const, ' + modifiers
return_type = 'void' return_type = 'void'
if node.return_type: if node.return_type:
# Add modifiers like 'const'. return_type = _EscapeForMacro(_RenderType(node.return_type))
modifiers = ''
if node.return_type.modifiers: args = []
modifiers = ' '.join(node.return_type.modifiers) + ' ' for p in node.parameters:
return_type = modifiers + node.return_type.name arg = _GenerateArg(source[p.start:p.end])
template_args = [arg.name for arg in node.return_type.templated_types] if arg != 'void':
if template_args: args.append(_EscapeForMacro(arg))
return_type += '<' + ', '.join(template_args) + '>'
if len(template_args) > 1:
for line in [
'// The following line won\'t really compile, as the return',
'// type has multiple template arguments. To fix it, use a',
'// typedef for the return type.']:
output_lines.append(indent + line)
if node.return_type.pointer:
return_type += '*'
if node.return_type.reference:
return_type += '&'
num_parameters = len(node.parameters)
if len(node.parameters) == 1:
first_param = node.parameters[0]
if source[first_param.start:first_param.end].strip() == 'void':
# We must treat T(void) as a function with no parameters.
num_parameters = 0
tmpl = ''
if class_node.templated_types:
tmpl = '_T'
mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl)
args = ''
if node.parameters:
# Due to the parser limitations, it is impossible to keep comments
# while stripping the default parameters. When defaults are
# present, we choose to strip them and comments (and produce
# compilable code).
# TODO(nnorwitz@google.com): Investigate whether it is possible to
# preserve parameter name when reconstructing parameter text from
# the AST.
if len([param for param in node.parameters if param.default]) > 0:
args = ', '.join(param.type.name for param in node.parameters)
else:
# Get the full text of the parameters from the start
# of the first parameter to the end of the last parameter.
start = node.parameters[0].start
end = node.parameters[-1].end
# Remove // comments.
args_strings = re.sub(r'//.*', '', source[start:end])
# Condense multiple spaces and eliminate newlines putting the
# parameters together on a single line. Ensure there is a
# space in an argument which is split by a newline without
# intervening whitespace, e.g.: int\nBar
args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
# Create the mock method definition. # Create the mock method definition.
output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name), output_lines.extend([
'%s%s(%s));' % (indent*3, return_type, args)]) '%sMOCK_METHOD(%s, %s, (%s), (%s));' %
(indent, return_type, node.name, ', '.join(args), modifiers)
])
def _GenerateMocks(filename, source, ast_list, desired_class_names): def _GenerateMocks(filename, source, ast_list, desired_class_names):
@ -141,12 +160,13 @@ def _GenerateMocks(filename, source, ast_list, desired_class_names):
# Add template args for templated classes. # Add template args for templated classes.
if class_node.templated_types: if class_node.templated_types:
# TODO(paulchang): The AST doesn't preserve template argument order,
# so we have to make up names here.
# TODO(paulchang): Handle non-type template arguments (e.g. # TODO(paulchang): Handle non-type template arguments (e.g.
# template<typename T, int N>). # template<typename T, int N>).
template_arg_count = len(class_node.templated_types.keys())
template_args = ['T%d' % n for n in range(template_arg_count)] # class_node.templated_types is an OrderedDict from strings to a tuples.
# The key is the name of the template, and the value is
# (type_name, default). Both type_name and default could be None.
template_args = class_node.templated_types.keys()
template_decls = ['typename ' + arg for arg in template_args] template_decls = ['typename ' + arg for arg in template_args]
lines.append('template <' + ', '.join(template_decls) + '>') lines.append('template <' + ', '.join(template_decls) + '>')
parent_name += '<' + ', '.join(template_args) + '>' parent_name += '<' + ', '.join(template_args) + '>'
@ -171,7 +191,7 @@ def _GenerateMocks(filename, source, ast_list, desired_class_names):
# Close the namespace. # Close the namespace.
if class_node.namespace: if class_node.namespace:
for i in range(len(class_node.namespace)-1, -1, -1): for i in range(len(class_node.namespace) - 1, -1, -1):
lines.append('} // namespace %s' % class_node.namespace[i]) lines.append('} // namespace %s' % class_node.namespace[i])
lines.append('') # Add an extra newline. lines.append('') # Add an extra newline.

@ -17,9 +17,6 @@
"""Tests for gmock.scripts.generator.cpp.gmock_class.""" """Tests for gmock.scripts.generator.cpp.gmock_class."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os import os
import sys import sys
import unittest import unittest
@ -34,7 +31,8 @@ from cpp import gmock_class
class TestCase(unittest.TestCase): class TestCase(unittest.TestCase):
"""Helper class that adds assert methods.""" """Helper class that adds assert methods."""
def StripLeadingWhitespace(self, lines): @staticmethod
def StripLeadingWhitespace(lines):
"""Strip leading whitespace in each line in 'lines'.""" """Strip leading whitespace in each line in 'lines'."""
return '\n'.join([s.lstrip() for s in lines.split('\n')]) return '\n'.join([s.lstrip() for s in lines.split('\n')])
@ -45,7 +43,8 @@ class TestCase(unittest.TestCase):
class GenerateMethodsTest(TestCase): class GenerateMethodsTest(TestCase):
def GenerateMethodSource(self, cpp_source): @staticmethod
def GenerateMethodSource(cpp_source):
"""Convert C++ source to Google Mock output source lines.""" """Convert C++ source to Google Mock output source lines."""
method_source_lines = [] method_source_lines = []
# <test> is a pseudo-filename, it is not read or written. # <test> is a pseudo-filename, it is not read or written.
@ -62,7 +61,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testSimpleConstructorsAndDestructor(self): def testSimpleConstructorsAndDestructor(self):
@ -79,7 +78,7 @@ class Foo {
""" """
# The constructors and destructor should be ignored. # The constructors and destructor should be ignored.
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testVirtualDestructor(self): def testVirtualDestructor(self):
@ -92,7 +91,7 @@ class Foo {
""" """
# The destructor should be ignored. # The destructor should be ignored.
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testExplicitlyDefaultedConstructorsAndDestructor(self): def testExplicitlyDefaultedConstructorsAndDestructor(self):
@ -108,7 +107,7 @@ class Foo {
""" """
# The constructors and destructor should be ignored. # The constructors and destructor should be ignored.
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testExplicitlyDeletedConstructorsAndDestructor(self): def testExplicitlyDeletedConstructorsAndDestructor(self):
@ -124,7 +123,7 @@ class Foo {
""" """
# The constructors and destructor should be ignored. # The constructors and destructor should be ignored.
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testSimpleOverrideMethod(self): def testSimpleOverrideMethod(self):
@ -135,7 +134,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testSimpleConstMethod(self): def testSimpleConstMethod(self):
@ -146,7 +145,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));', 'MOCK_METHOD(void, Bar, (bool flag), (const, override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testExplicitVoid(self): def testExplicitVoid(self):
@ -157,7 +156,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint(void));', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testStrangeNewlineInParameter(self): def testStrangeNewlineInParameter(self):
@ -169,7 +168,7 @@ a) = 0;
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nvoid(int a));', 'MOCK_METHOD(void, Bar, (int a), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testDefaultParameters(self): def testDefaultParameters(self):
@ -180,18 +179,58 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\nvoid(int, char));', 'MOCK_METHOD(void, Bar, (int a, char c), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testMultipleDefaultParameters(self): def testMultipleDefaultParameters(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual void Bar(int a = 42, char c = 'x') = 0; virtual void Bar(
int a = 42,
char c = 'x',
const int* const p = nullptr,
const std::string& s = "42",
char tab[] = {'4','2'},
int const *& rp = aDefaultPointer) = 0;
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\nvoid(int, char));', 'MOCK_METHOD(void, Bar, '
'(int a, char c, const int* const p, const std::string& s, char tab[], int const *& rp), '
'(override));', self.GenerateMethodSource(source))
def testMultipleSingleLineDefaultParameters(self):
source = """
class Foo {
public:
virtual void Bar(int a = 42, int b = 43, int c = 44) = 0;
};
"""
self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD(void, Bar, (int a, int b, int c), (override));',
self.GenerateMethodSource(source))
def testConstDefaultParameter(self):
source = """
class Test {
public:
virtual bool Bar(const int test_arg = 42) = 0;
};
"""
self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD(bool, Bar, (const int test_arg), (override));',
self.GenerateMethodSource(source))
def testConstRefDefaultParameter(self):
source = """
class Test {
public:
virtual bool Bar(const std::string& test_arg = "42" ) = 0;
};
"""
self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD(bool, Bar, (const std::string& test_arg), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testRemovesCommentsWhenDefaultsArePresent(self): def testRemovesCommentsWhenDefaultsArePresent(self):
@ -203,7 +242,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\nvoid(int, char));', 'MOCK_METHOD(void, Bar, (int a, char c), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testDoubleSlashCommentsInParameterListAreRemoved(self): def testDoubleSlashCommentsInParameterListAreRemoved(self):
@ -216,7 +255,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));', 'MOCK_METHOD(void, Bar, (int a, int b), (const, override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testCStyleCommentsInParameterListAreNotRemoved(self): def testCStyleCommentsInParameterListAreNotRemoved(self):
@ -230,7 +269,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\nconst string&(int /* keeper */, int b));', 'MOCK_METHOD(const string&, Bar, (int, int b), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testArgsOfTemplateTypes(self): def testArgsOfTemplateTypes(self):
@ -240,8 +279,7 @@ class Foo {
virtual int Bar(const vector<int>& v, map<int, string>* output); virtual int Bar(const vector<int>& v, map<int, string>* output);
};""" };"""
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\n' 'MOCK_METHOD(int, Bar, (const vector<int>& v, (map<int, string>* output)), (override));',
'int(const vector<int>& v, map<int, string>* output));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testReturnTypeWithOneTemplateArg(self): def testReturnTypeWithOneTemplateArg(self):
@ -251,7 +289,7 @@ class Foo {
virtual vector<int>* Bar(int n); virtual vector<int>* Bar(int n);
};""" };"""
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nvector<int>*(int n));', 'MOCK_METHOD(vector<int>*, Bar, (int n), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testReturnTypeWithManyTemplateArgs(self): def testReturnTypeWithManyTemplateArgs(self):
@ -260,13 +298,8 @@ class Foo {
public: public:
virtual map<int, string> Bar(); virtual map<int, string> Bar();
};""" };"""
# Comparing the comment text is brittle - we'll think of something
# better in case this gets annoying, but for now let's keep it simple.
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'// The following line won\'t really compile, as the return\n' 'MOCK_METHOD((map<int, string>), Bar, (), (override));',
'// type has multiple template arguments. To fix it, use a\n'
'// typedef for the return type.\n'
'MOCK_METHOD0(Bar,\nmap<int, string>());',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testSimpleMethodInTemplatedClass(self): def testSimpleMethodInTemplatedClass(self):
@ -278,7 +311,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0_T(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testPointerArgWithoutNames(self): def testPointerArgWithoutNames(self):
@ -288,7 +321,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nint(C*));', 'MOCK_METHOD(int, Bar, (C*), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testReferenceArgWithoutNames(self): def testReferenceArgWithoutNames(self):
@ -298,7 +331,7 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nint(C&));', 'MOCK_METHOD(int, Bar, (C&), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testArrayArgWithoutNames(self): def testArrayArgWithoutNames(self):
@ -308,13 +341,14 @@ class Foo {
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nint(C[]));', 'MOCK_METHOD(int, Bar, (C[]), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
class GenerateMocksTest(TestCase): class GenerateMocksTest(TestCase):
def GenerateMocks(self, cpp_source): @staticmethod
def GenerateMocks(cpp_source):
"""Convert C++ source to complete Google Mock output source.""" """Convert C++ source to complete Google Mock output source."""
# <test> is a pseudo-filename, it is not read or written. # <test> is a pseudo-filename, it is not read or written.
filename = '<test>' filename = '<test>'
@ -327,31 +361,30 @@ class GenerateMocksTest(TestCase):
source = """ source = """
namespace Foo { namespace Foo {
namespace Bar { class Forward; } namespace Bar { class Forward; }
namespace Baz { namespace Baz::Qux {
class Test { class Test {
public: public:
virtual void Foo(); virtual void Foo();
}; };
} // namespace Baz } // namespace Baz::Qux
} // namespace Foo } // namespace Foo
""" """
expected = """\ expected = """\
namespace Foo { namespace Foo {
namespace Baz { namespace Baz::Qux {
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD0(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
} // namespace Baz } // namespace Baz::Qux
} // namespace Foo } // namespace Foo
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testClassWithStorageSpecifierMacro(self): def testClassWithStorageSpecifierMacro(self):
source = """ source = """
@ -363,12 +396,11 @@ class STORAGE_SPECIFIER Test {
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD0(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testTemplatedForwardDeclaration(self): def testTemplatedForwardDeclaration(self):
source = """ source = """
@ -381,12 +413,11 @@ class Test {
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD0(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testTemplatedClass(self): def testTemplatedClass(self):
source = """ source = """
@ -397,15 +428,14 @@ class Test {
}; };
""" """
expected = """\ expected = """\
template <typename T0, typename T1> template <typename S, typename T>
class MockTest : public Test<T0, T1> { class MockTest : public Test<S, T> {
public: public:
MOCK_METHOD0_T(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testTemplateInATemplateTypedef(self): def testTemplateInATemplateTypedef(self):
source = """ source = """
@ -418,12 +448,29 @@ class Test {
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD1(Bar, MOCK_METHOD(void, Bar, (const FooType& test_arg), (override));
void(const FooType& test_arg));
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testTemplatedClassWithTemplatedArguments(self):
source = """
template <typename S, typename T, typename U, typename V, typename W>
class Test {
public:
virtual U Foo(T some_arg);
};
"""
expected = """\
template <typename S, typename T, typename U, typename V, typename W>
class MockTest : public Test<S, T, U, V, W> {
public:
MOCK_METHOD(U, Foo, (T some_arg), (override));
};
"""
self.assertEqualIgnoreLeadingWhitespace(expected,
self.GenerateMocks(source))
def testTemplateInATemplateTypedefWithComma(self): def testTemplateInATemplateTypedefWithComma(self):
source = """ source = """
@ -437,30 +484,87 @@ class Test {
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD1(Bar, MOCK_METHOD(void, Bar, (const FooType& test_arg), (override));
void(const FooType& test_arg));
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testEnumClass(self): def testParenthesizedCommaInArg(self):
source = """ source = """
class Test { class Test {
public: public:
enum class Baz { BAZINGA }; virtual void Bar(std::function<void(int, int)> f);
virtual void Bar(const FooType& test_arg);
}; };
""" """
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD1(Bar, MOCK_METHOD(void, Bar, (std::function<void(int, int)> f), (override));
void(const FooType& test_arg));
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testEnumType(self):
source = """
class Test {
public:
enum Bar {
BAZ, QUX, QUUX, QUUUX
};
virtual void Foo();
};
"""
expected = """\
class MockTest : public Test {
public:
MOCK_METHOD(void, Foo, (), (override));
};
"""
self.assertEqualIgnoreLeadingWhitespace(expected,
self.GenerateMocks(source))
def testEnumClassType(self):
source = """
class Test {
public:
enum class Bar {
BAZ, QUX, QUUX, QUUUX
};
virtual void Foo();
};
"""
expected = """\
class MockTest : public Test {
public:
MOCK_METHOD(void, Foo, (), (override));
};
"""
self.assertEqualIgnoreLeadingWhitespace(expected,
self.GenerateMocks(source))
def testStdFunction(self):
source = """
class Test {
public:
Test(std::function<int(std::string)> foo) : foo_(foo) {}
virtual std::function<int(std::string)> foo();
private:
std::function<int(std::string)> foo_;
};
"""
expected = """\
class MockTest : public Test {
public:
MOCK_METHOD(std::function<int (std::string)>, foo, (), (override));
};
"""
self.assertEqualIgnoreLeadingWhitespace(expected,
self.GenerateMocks(source))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

@ -17,9 +17,6 @@
"""C++ keywords and helper utilities for determining keywords.""" """C++ keywords and helper utilities for determining keywords."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
try: try:
# Python 3.x # Python 3.x
import builtins import builtins

@ -17,9 +17,6 @@
"""Tokenize C++ source code.""" """Tokenize C++ source code."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
try: try:
# Python 3.x # Python 3.x
import builtins import builtins

@ -17,12 +17,8 @@
"""Generic utilities for C++ parsing.""" """Generic utilities for C++ parsing."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import sys import sys
# Set to True to see the start/end token indices. # Set to True to see the start/end token indices.
DEBUG = True DEBUG = True

@ -16,7 +16,6 @@
"""Driver for starting up Google Mock class generator.""" """Driver for starting up Google Mock class generator."""
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
import os import os
import sys import sys

@ -1,303 +0,0 @@
#!/bin/sh
# These variables are automatically filled in by the configure script.
name="@PACKAGE_TARNAME@"
version="@PACKAGE_VERSION@"
show_usage()
{
echo "Usage: gmock-config [OPTIONS...]"
}
show_help()
{
show_usage
cat <<\EOF
The `gmock-config' script provides access to the necessary compile and linking
flags to connect with Google C++ Mocking Framework, both in a build prior to
installation, and on the system proper after installation. The installation
overrides may be issued in combination with any other queries, but will only
affect installation queries if called on a built but not installed gmock. The
installation queries may not be issued with any other types of queries, and
only one installation query may be made at a time. The version queries and
compiler flag queries may be combined as desired but not mixed. Different
version queries are always combined with logical "and" semantics, and only the
last of any particular query is used while all previous ones ignored. All
versions must be specified as a sequence of numbers separated by periods.
Compiler flag queries output the union of the sets of flags when combined.
Examples:
gmock-config --min-version=1.0 || echo "Insufficient Google Mock version."
g++ $(gmock-config --cppflags --cxxflags) -o foo.o -c foo.cpp
g++ $(gmock-config --ldflags --libs) -o foo foo.o
# When using a built but not installed Google Mock:
g++ $(../../my_gmock_build/scripts/gmock-config ...) ...
# When using an installed Google Mock, but with installation overrides:
export GMOCK_PREFIX="/opt"
g++ $(gmock-config --libdir="/opt/lib64" ...) ...
Help:
--usage brief usage information
--help display this help message
Installation Overrides:
--prefix=<dir> overrides the installation prefix
--exec-prefix=<dir> overrides the executable installation prefix
--libdir=<dir> overrides the library installation prefix
--includedir=<dir> overrides the header file installation prefix
Installation Queries:
--prefix installation prefix
--exec-prefix executable installation prefix
--libdir library installation directory
--includedir header file installation directory
--version the version of the Google Mock installation
Version Queries:
--min-version=VERSION return 0 if the version is at least VERSION
--exact-version=VERSION return 0 if the version is exactly VERSION
--max-version=VERSION return 0 if the version is at most VERSION
Compilation Flag Queries:
--cppflags compile flags specific to the C-like preprocessors
--cxxflags compile flags appropriate for C++ programs
--ldflags linker flags
--libs libraries for linking
EOF
}
# This function bounds our version with a min and a max. It uses some clever
# POSIX-compliant variable expansion to portably do all the work in the shell
# and avoid any dependency on a particular "sed" or "awk" implementation.
# Notable is that it will only ever compare the first 3 components of versions.
# Further components will be cleanly stripped off. All versions must be
# unadorned, so "v1.0" will *not* work. The minimum version must be in $1, and
# the max in $2. TODO(chandlerc@google.com): If this ever breaks, we should
# investigate expanding this via autom4te from AS_VERSION_COMPARE rather than
# continuing to maintain our own shell version.
check_versions()
{
major_version=${version%%.*}
minor_version="0"
point_version="0"
if test "${version#*.}" != "${version}"; then
minor_version=${version#*.}
minor_version=${minor_version%%.*}
fi
if test "${version#*.*.}" != "${version}"; then
point_version=${version#*.*.}
point_version=${point_version%%.*}
fi
min_version="$1"
min_major_version=${min_version%%.*}
min_minor_version="0"
min_point_version="0"
if test "${min_version#*.}" != "${min_version}"; then
min_minor_version=${min_version#*.}
min_minor_version=${min_minor_version%%.*}
fi
if test "${min_version#*.*.}" != "${min_version}"; then
min_point_version=${min_version#*.*.}
min_point_version=${min_point_version%%.*}
fi
max_version="$2"
max_major_version=${max_version%%.*}
max_minor_version="0"
max_point_version="0"
if test "${max_version#*.}" != "${max_version}"; then
max_minor_version=${max_version#*.}
max_minor_version=${max_minor_version%%.*}
fi
if test "${max_version#*.*.}" != "${max_version}"; then
max_point_version=${max_version#*.*.}
max_point_version=${max_point_version%%.*}
fi
test $(($major_version)) -lt $(($min_major_version)) && exit 1
if test $(($major_version)) -eq $(($min_major_version)); then
test $(($minor_version)) -lt $(($min_minor_version)) && exit 1
if test $(($minor_version)) -eq $(($min_minor_version)); then
test $(($point_version)) -lt $(($min_point_version)) && exit 1
fi
fi
test $(($major_version)) -gt $(($max_major_version)) && exit 1
if test $(($major_version)) -eq $(($max_major_version)); then
test $(($minor_version)) -gt $(($max_minor_version)) && exit 1
if test $(($minor_version)) -eq $(($max_minor_version)); then
test $(($point_version)) -gt $(($max_point_version)) && exit 1
fi
fi
exit 0
}
# Show the usage line when no arguments are specified.
if test $# -eq 0; then
show_usage
exit 1
fi
while test $# -gt 0; do
case $1 in
--usage) show_usage; exit 0;;
--help) show_help; exit 0;;
# Installation overrides
--prefix=*) GMOCK_PREFIX=${1#--prefix=};;
--exec-prefix=*) GMOCK_EXEC_PREFIX=${1#--exec-prefix=};;
--libdir=*) GMOCK_LIBDIR=${1#--libdir=};;
--includedir=*) GMOCK_INCLUDEDIR=${1#--includedir=};;
# Installation queries
--prefix|--exec-prefix|--libdir|--includedir|--version)
if test -n "${do_query}"; then
show_usage
exit 1
fi
do_query=${1#--}
;;
# Version checking
--min-version=*)
do_check_versions=yes
min_version=${1#--min-version=}
;;
--max-version=*)
do_check_versions=yes
max_version=${1#--max-version=}
;;
--exact-version=*)
do_check_versions=yes
exact_version=${1#--exact-version=}
;;
# Compiler flag output
--cppflags) echo_cppflags=yes;;
--cxxflags) echo_cxxflags=yes;;
--ldflags) echo_ldflags=yes;;
--libs) echo_libs=yes;;
# Everything else is an error
*) show_usage; exit 1;;
esac
shift
done
# These have defaults filled in by the configure script but can also be
# overridden by environment variables or command line parameters.
prefix="${GMOCK_PREFIX:-@prefix@}"
exec_prefix="${GMOCK_EXEC_PREFIX:-@exec_prefix@}"
libdir="${GMOCK_LIBDIR:-@libdir@}"
includedir="${GMOCK_INCLUDEDIR:-@includedir@}"
# We try and detect if our binary is not located at its installed location. If
# it's not, we provide variables pointing to the source and build tree rather
# than to the install tree. We also locate Google Test using the configured
# gtest-config script rather than searching the PATH and our bindir for one.
# This allows building against a just-built gmock rather than an installed
# gmock.
bindir="@bindir@"
this_relative_bindir=`dirname $0`
this_bindir=`cd ${this_relative_bindir}; pwd -P`
if test "${this_bindir}" = "${this_bindir%${bindir}}"; then
# The path to the script doesn't end in the bindir sequence from Autoconf,
# assume that we are in a build tree.
build_dir=`dirname ${this_bindir}`
src_dir=`cd ${this_bindir}/@top_srcdir@; pwd -P`
# TODO(chandlerc@google.com): This is a dangerous dependency on libtool, we
# should work to remove it, and/or remove libtool altogether, replacing it
# with direct references to the library and a link path.
gmock_libs="${build_dir}/lib/libgmock.la"
gmock_ldflags=""
# We provide hooks to include from either the source or build dir, where the
# build dir is always preferred. This will potentially allow us to write
# build rules for generated headers and have them automatically be preferred
# over provided versions.
gmock_cppflags="-I${build_dir}/include -I${src_dir}/include"
gmock_cxxflags=""
# Directly invoke the gtest-config script used during the build process.
gtest_config="@GTEST_CONFIG@"
else
# We're using an installed gmock, although it may be staged under some
# prefix. Assume (as our own libraries do) that we can resolve the prefix,
# and are present in the dynamic link paths.
gmock_ldflags="-L${libdir}"
gmock_libs="-l${name}"
gmock_cppflags="-I${includedir}"
gmock_cxxflags=""
# We also prefer any gtest-config script installed in our prefix. Lacking
# one, we look in the PATH for one.
gtest_config="${bindir}/gtest-config"
if test ! -x "${gtest_config}"; then
gtest_config=`which gtest-config`
fi
fi
# Ensure that we have located a Google Test to link against.
if ! test -x "${gtest_config}"; then
echo "Unable to locate Google Test, check your Google Mock configuration" \
"and installation" >&2
exit 1
elif ! "${gtest_config}" "--exact-version=@GTEST_VERSION@"; then
echo "The Google Test found is not the same version as Google Mock was " \
"built against" >&2
exit 1
fi
# Add the necessary Google Test bits into the various flag variables
gmock_cppflags="${gmock_cppflags} `${gtest_config} --cppflags`"
gmock_cxxflags="${gmock_cxxflags} `${gtest_config} --cxxflags`"
gmock_ldflags="${gmock_ldflags} `${gtest_config} --ldflags`"
gmock_libs="${gmock_libs} `${gtest_config} --libs`"
# Do an installation query if requested.
if test -n "$do_query"; then
case $do_query in
prefix) echo $prefix; exit 0;;
exec-prefix) echo $exec_prefix; exit 0;;
libdir) echo $libdir; exit 0;;
includedir) echo $includedir; exit 0;;
version) echo $version; exit 0;;
*) show_usage; exit 1;;
esac
fi
# Do a version check if requested.
if test "$do_check_versions" = "yes"; then
# Make sure we didn't receive a bad combination of parameters.
test "$echo_cppflags" = "yes" && show_usage && exit 1
test "$echo_cxxflags" = "yes" && show_usage && exit 1
test "$echo_ldflags" = "yes" && show_usage && exit 1
test "$echo_libs" = "yes" && show_usage && exit 1
if test "$exact_version" != ""; then
check_versions $exact_version $exact_version
# unreachable
else
check_versions ${min_version:-0.0.0} ${max_version:-9999.9999.9999}
# unreachable
fi
fi
# Do the output in the correct order so that these can be used in-line of
# a compiler invocation.
output=""
test "$echo_cppflags" = "yes" && output="$output $gmock_cppflags"
test "$echo_cxxflags" = "yes" && output="$output $gmock_cxxflags"
test "$echo_ldflags" = "yes" && output="$output $gmock_ldflags"
test "$echo_libs" = "yes" && output="$output $gmock_libs"
echo $output
exit 0

@ -1,640 +0,0 @@
#!/usr/bin/env python
#
# Copyright 2008, 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.
"""Converts compiler's errors in code using Google Mock to plain English."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import re
import sys
_VERSION = '1.0.3'
_EMAIL = 'googlemock@googlegroups.com'
_COMMON_GMOCK_SYMBOLS = [
# Matchers
'_',
'A',
'AddressSatisfies',
'AllOf',
'An',
'AnyOf',
'ContainerEq',
'Contains',
'ContainsRegex',
'DoubleEq',
'ElementsAre',
'ElementsAreArray',
'EndsWith',
'Eq',
'Field',
'FloatEq',
'Ge',
'Gt',
'HasSubstr',
'IsInitializedProto',
'Le',
'Lt',
'MatcherCast',
'Matches',
'MatchesRegex',
'NanSensitiveDoubleEq',
'NanSensitiveFloatEq',
'Ne',
'Not',
'NotNull',
'Pointee',
'Property',
'Ref',
'ResultOf',
'SafeMatcherCast',
'StartsWith',
'StrCaseEq',
'StrCaseNe',
'StrEq',
'StrNe',
'Truly',
'TypedEq',
'Value',
# Actions
'Assign',
'ByRef',
'DeleteArg',
'DoAll',
'DoDefault',
'IgnoreResult',
'Invoke',
'InvokeArgument',
'InvokeWithoutArgs',
'Return',
'ReturnNew',
'ReturnNull',
'ReturnRef',
'SaveArg',
'SetArgReferee',
'SetArgPointee',
'SetArgumentPointee',
'SetArrayArgument',
'SetErrnoAndReturn',
'Throw',
'WithArg',
'WithArgs',
'WithoutArgs',
# Cardinalities
'AnyNumber',
'AtLeast',
'AtMost',
'Between',
'Exactly',
# Sequences
'InSequence',
'Sequence',
# Misc
'DefaultValue',
'Mock',
]
# Regex for matching source file path and line number in the compiler's errors.
_GCC_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(\d+:)?\s+'
_CLANG_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(?P<column>\d+):\s+'
_CLANG_NON_GMOCK_FILE_LINE_RE = (
r'(?P<file>.*[/\\^](?!gmock-)[^/\\]+):(?P<line>\d+):(?P<column>\d+):\s+')
def _FindAllMatches(regex, s):
"""Generates all matches of regex in string s."""
r = re.compile(regex)
return r.finditer(s)
def _GenericDiagnoser(short_name, long_name, diagnoses, msg):
"""Diagnoses the given disease by pattern matching.
Can provide different diagnoses for different patterns.
Args:
short_name: Short name of the disease.
long_name: Long name of the disease.
diagnoses: A list of pairs (regex, pattern for formatting the diagnosis
for matching regex).
msg: Compiler's error messages.
Yields:
Tuples of the form
(short name of disease, long name of disease, diagnosis).
"""
for regex, diagnosis in diagnoses:
if re.search(regex, msg):
diagnosis = '%(file)s:%(line)s:' + diagnosis
for m in _FindAllMatches(regex, msg):
yield (short_name, long_name, diagnosis % m.groupdict())
def _NeedToReturnReferenceDiagnoser(msg):
"""Diagnoses the NRR disease, given the error messages by the compiler."""
gcc_regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n'
+ _GCC_FILE_LINE_RE + r'instantiated from here\n'
r'.*gmock-actions\.h.*error: creating array with negative size')
clang_regex = (r'error:.*array.*negative.*\r?\n'
r'(.*\n)*?' +
_CLANG_NON_GMOCK_FILE_LINE_RE +
r'note: in instantiation of function template specialization '
r'\'testing::internal::ReturnAction<(?P<type>.*)>'
r'::operator Action<.*>\' requested here')
clang11_re = (r'use_ReturnRef_instead_of_Return_to_return_a_reference.*'
r'(.*\n)*?' + _CLANG_NON_GMOCK_FILE_LINE_RE)
diagnosis = """
You are using a Return() action in a function that returns a reference to
%(type)s. Please use ReturnRef() instead."""
return _GenericDiagnoser('NRR', 'Need to Return Reference',
[(clang_regex, diagnosis),
(clang11_re, diagnosis % {'type': 'a type'}),
(gcc_regex, diagnosis % {'type': 'a type'})],
msg)
def _NeedToReturnSomethingDiagnoser(msg):
"""Diagnoses the NRS disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'(instantiated from here\n.'
r'*gmock.*actions\.h.*error: void value not ignored)'
r'|(error: control reaches end of non-void function)')
clang_regex1 = (_CLANG_FILE_LINE_RE +
r'error: cannot initialize return object '
r'of type \'Result\' \(aka \'(?P<return_type>.*)\'\) '
r'with an rvalue of type \'void\'')
clang_regex2 = (_CLANG_FILE_LINE_RE +
r'error: cannot initialize return object '
r'of type \'(?P<return_type>.*)\' '
r'with an rvalue of type \'void\'')
diagnosis = """
You are using an action that returns void, but it needs to return
%(return_type)s. Please tell it *what* to return. Perhaps you can use
the pattern DoAll(some_action, Return(some_value))?"""
return _GenericDiagnoser(
'NRS',
'Need to Return Something',
[(gcc_regex, diagnosis % {'return_type': '*something*'}),
(clang_regex1, diagnosis),
(clang_regex2, diagnosis)],
msg)
def _NeedToReturnNothingDiagnoser(msg):
"""Diagnoses the NRN disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
r'.*gmock-actions\.h.*error: instantiation of '
r'\'testing::internal::ReturnAction<R>::Impl<F>::value_\' '
r'as type \'void\'')
clang_regex1 = (r'error: field has incomplete type '
r'\'Result\' \(aka \'void\'\)(\r)?\n'
r'(.*\n)*?' +
_CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
r'of function template specialization '
r'\'testing::internal::ReturnAction<(?P<return_type>.*)>'
r'::operator Action<void \(.*\)>\' requested here')
clang_regex2 = (r'error: field has incomplete type '
r'\'Result\' \(aka \'void\'\)(\r)?\n'
r'(.*\n)*?' +
_CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
r'of function template specialization '
r'\'testing::internal::DoBothAction<.*>'
r'::operator Action<(?P<return_type>.*) \(.*\)>\' '
r'requested here')
diagnosis = """
You are using an action that returns %(return_type)s, but it needs to return
void. Please use a void-returning action instead.
All actions but the last in DoAll(...) must return void. Perhaps you need
to re-arrange the order of actions in a DoAll(), if you are using one?"""
return _GenericDiagnoser(
'NRN',
'Need to Return Nothing',
[(gcc_regex, diagnosis % {'return_type': '*something*'}),
(clang_regex1, diagnosis),
(clang_regex2, diagnosis)],
msg)
def _IncompleteByReferenceArgumentDiagnoser(msg):
"""Diagnoses the IBRA disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
r'.*gtest-printers\.h.*error: invalid application of '
r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
clang_regex = (r'.*gtest-printers\.h.*error: invalid application of '
r'\'sizeof\' to an incomplete type '
r'\'(?P<type>.*)( const)?\'\r?\n'
r'(.*\n)*?' +
_CLANG_NON_GMOCK_FILE_LINE_RE +
r'note: in instantiation of member function '
r'\'testing::internal2::TypeWithoutFormatter<.*>::'
r'PrintValue\' requested here')
diagnosis = """
In order to mock this function, Google Mock needs to see the definition
of type "%(type)s" - declaration alone is not enough. Either #include
the header that defines it, or change the argument to be passed
by pointer."""
return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type',
[(gcc_regex, diagnosis),
(clang_regex, diagnosis)],
msg)
def _OverloadedFunctionMatcherDiagnoser(msg):
"""Diagnoses the OFM disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
r'call to \'Truly\(<unresolved overloaded function type>\)')
clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function for '
r'call to \'Truly')
diagnosis = """
The argument you gave to Truly() is an overloaded function. Please tell
your compiler which overloaded version you want to use.
For example, if you want to use the version whose signature is
bool Foo(int n);
you should write
Truly(static_cast<bool (*)(int n)>(Foo))"""
return _GenericDiagnoser('OFM', 'Overloaded Function Matcher',
[(gcc_regex, diagnosis),
(clang_regex, diagnosis)],
msg)
def _OverloadedFunctionActionDiagnoser(msg):
"""Diagnoses the OFA disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for call to '
r'\'Invoke\(<unresolved overloaded function type>')
clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching '
r'function for call to \'Invoke\'\r?\n'
r'(.*\n)*?'
r'.*\bgmock-generated-actions\.h:\d+:\d+:\s+'
r'note: candidate template ignored:\s+'
r'couldn\'t infer template argument \'FunctionImpl\'')
diagnosis = """
Function you are passing to Invoke is overloaded. Please tell your compiler
which overloaded version you want to use.
For example, if you want to use the version whose signature is
bool MyFunction(int n, double x);
you should write something like
Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))"""
return _GenericDiagnoser('OFA', 'Overloaded Function Action',
[(gcc_regex, diagnosis),
(clang_regex, diagnosis)],
msg)
def _OverloadedMethodActionDiagnoser(msg):
"""Diagnoses the OMA disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
r'call to \'Invoke\(.+, <unresolved overloaded function '
r'type>\)')
clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function '
r'for call to \'Invoke\'\r?\n'
r'(.*\n)*?'
r'.*\bgmock-generated-actions\.h:\d+:\d+: '
r'note: candidate function template not viable: '
r'requires .*, but 2 (arguments )?were provided')
diagnosis = """
The second argument you gave to Invoke() is an overloaded method. Please
tell your compiler which overloaded version you want to use.
For example, if you want to use the version whose signature is
class Foo {
...
bool Bar(int n, double x);
};
you should write something like
Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
return _GenericDiagnoser('OMA', 'Overloaded Method Action',
[(gcc_regex, diagnosis),
(clang_regex, diagnosis)],
msg)
def _MockObjectPointerDiagnoser(msg):
"""Diagnoses the MOP disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'error: request for member '
r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
clang_regex = (_CLANG_FILE_LINE_RE + r'error: member reference type '
r'\'(?P<class_name>.*?) *\' is a pointer; '
r'(did you mean|maybe you meant) to use \'->\'\?')
diagnosis = """
The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*,
not a *pointer* to it. Please write '*(%(mock_object)s)' instead of
'%(mock_object)s' as your first argument.
For example, given the mock class:
class %(class_name)s : public ... {
...
MOCK_METHOD0(%(method)s, ...);
};
and the following mock instance:
%(class_name)s* mock_ptr = ...
you should use the EXPECT_CALL like this:
EXPECT_CALL(*mock_ptr, %(method)s(...));"""
return _GenericDiagnoser(
'MOP',
'Mock Object Pointer',
[(gcc_regex, diagnosis),
(clang_regex, diagnosis % {'mock_object': 'mock_object',
'method': 'method',
'class_name': '%(class_name)s'})],
msg)
def _NeedToUseSymbolDiagnoser(msg):
"""Diagnoses the NUS disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
r'(was not declared in this scope|has not been declared)')
clang_regex = (_CLANG_FILE_LINE_RE +
r'error: (use of undeclared identifier|unknown type name|'
r'no template named) \'(?P<symbol>[^\']+)\'')
diagnosis = """
'%(symbol)s' is defined by Google Mock in the testing namespace.
Did you forget to write
using testing::%(symbol)s;
?"""
for m in (list(_FindAllMatches(gcc_regex, msg)) +
list(_FindAllMatches(clang_regex, msg))):
symbol = m.groupdict()['symbol']
if symbol in _COMMON_GMOCK_SYMBOLS:
yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict())
def _NeedToUseReturnNullDiagnoser(msg):
"""Diagnoses the NRNULL disease, given the error messages by the compiler."""
gcc_regex = ('instantiated from \'testing::internal::ReturnAction<R>'
'::operator testing::Action<Func>\(\) const.*\n' +
_GCC_FILE_LINE_RE + r'instantiated from here\n'
r'.*error: no matching function for call to \'ImplicitCast_\('
r'(:?long )?int&\)')
clang_regex = (r'\bgmock-actions.h:.* error: no matching function for '
r'call to \'ImplicitCast_\'\r?\n'
r'(.*\n)*?' +
_CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
r'of function template specialization '
r'\'testing::internal::ReturnAction<(int|long)>::operator '
r'Action<(?P<type>.*)\(\)>\' requested here')
diagnosis = """
You are probably calling Return(NULL) and the compiler isn't sure how to turn
NULL into %(type)s. Use ReturnNull() instead.
Note: the line number may be off; please fix all instances of Return(NULL)."""
return _GenericDiagnoser(
'NRNULL', 'Need to use ReturnNull',
[(clang_regex, diagnosis),
(gcc_regex, diagnosis % {'type': 'the right type'})],
msg)
def _TypeInTemplatedBaseDiagnoser(msg):
"""Diagnoses the TTB disease, given the error messages by the compiler."""
# This version works when the type is used as the mock function's return
# type.
gcc_4_3_1_regex_type_in_retval = (
r'In member function \'int .*\n' + _GCC_FILE_LINE_RE +
r'error: a function call cannot appear in a constant-expression')
gcc_4_4_0_regex_type_in_retval = (
r'error: a function call cannot appear in a constant-expression'
+ _GCC_FILE_LINE_RE + r'error: template argument 1 is invalid\n')
# This version works when the type is used as the mock function's sole
# parameter type.
gcc_regex_type_of_sole_param = (
_GCC_FILE_LINE_RE +
r'error: \'(?P<type>.+)\' was not declared in this scope\n'
r'.*error: template argument 1 is invalid\n')
# This version works when the type is used as a parameter of a mock
# function that has multiple parameters.
gcc_regex_type_of_a_param = (
r'error: expected `;\' before \'::\' token\n'
+ _GCC_FILE_LINE_RE +
r'error: \'(?P<type>.+)\' was not declared in this scope\n'
r'.*error: template argument 1 is invalid\n'
r'.*error: \'.+\' was not declared in this scope')
clang_regex_type_of_retval_or_sole_param = (
_CLANG_FILE_LINE_RE +
r'error: use of undeclared identifier \'(?P<type>.*)\'\n'
r'(.*\n)*?'
r'(?P=file):(?P=line):\d+: error: '
r'non-friend class member \'Result\' cannot have a qualified name'
)
clang_regex_type_of_a_param = (
_CLANG_FILE_LINE_RE +
r'error: C\+\+ requires a type specifier for all declarations\n'
r'(.*\n)*?'
r'(?P=file):(?P=line):(?P=column): error: '
r'C\+\+ requires a type specifier for all declarations'
)
clang_regex_unknown_type = (
_CLANG_FILE_LINE_RE +
r'error: unknown type name \'(?P<type>[^\']+)\''
)
diagnosis = """
In a mock class template, types or typedefs defined in the base class
template are *not* automatically visible. This is how C++ works. Before
you can use a type or typedef named %(type)s defined in base class Base<T>, you
need to make it visible. One way to do it is:
typedef typename Base<T>::%(type)s %(type)s;"""
for diag in _GenericDiagnoser(
'TTB', 'Type in Template Base',
[(gcc_4_3_1_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
(gcc_4_4_0_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
(gcc_regex_type_of_sole_param, diagnosis),
(gcc_regex_type_of_a_param, diagnosis),
(clang_regex_type_of_retval_or_sole_param, diagnosis),
(clang_regex_type_of_a_param, diagnosis % {'type': 'Foo'})],
msg):
yield diag
# Avoid overlap with the NUS pattern.
for m in _FindAllMatches(clang_regex_unknown_type, msg):
type_ = m.groupdict()['type']
if type_ not in _COMMON_GMOCK_SYMBOLS:
yield ('TTB', 'Type in Template Base', diagnosis % m.groupdict())
def _WrongMockMethodMacroDiagnoser(msg):
"""Diagnoses the WMM disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE +
r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
r'.*\n'
r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
r'error:.*array.*negative.*r?\n'
r'(.*\n)*?'
r'(?P=file):(?P=line):(?P=column): error: too few arguments '
r'to function call, expected (?P<args>\d+), '
r'have (?P<wrong_args>\d+)')
clang11_re = (_CLANG_NON_GMOCK_FILE_LINE_RE +
r'.*this_method_does_not_take_'
r'(?P<wrong_args>\d+)_argument.*')
diagnosis = """
You are using MOCK_METHOD%(wrong_args)s to define a mock method that has
%(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s,
MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead."""
return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
[(gcc_regex, diagnosis),
(clang11_re, diagnosis % {'wrong_args': 'm',
'args': 'n'}),
(clang_regex, diagnosis)],
msg)
def _WrongParenPositionDiagnoser(msg):
"""Diagnoses the WPP disease, given the error messages by the compiler."""
gcc_regex = (_GCC_FILE_LINE_RE +
r'error:.*testing::internal::MockSpec<.* has no member named \''
r'(?P<method>\w+)\'')
clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
r'error: no member named \'(?P<method>\w+)\' in '
r'\'testing::internal::MockSpec<.*>\'')
diagnosis = """
The closing parenthesis of ON_CALL or EXPECT_CALL should be *before*
".%(method)s". For example, you should write:
EXPECT_CALL(my_mock, Foo(_)).%(method)s(...);
instead of:
EXPECT_CALL(my_mock, Foo(_).%(method)s(...));"""
return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
[(gcc_regex, diagnosis),
(clang_regex, diagnosis)],
msg)
_DIAGNOSERS = [
_IncompleteByReferenceArgumentDiagnoser,
_MockObjectPointerDiagnoser,
_NeedToReturnNothingDiagnoser,
_NeedToReturnReferenceDiagnoser,
_NeedToReturnSomethingDiagnoser,
_NeedToUseReturnNullDiagnoser,
_NeedToUseSymbolDiagnoser,
_OverloadedFunctionActionDiagnoser,
_OverloadedFunctionMatcherDiagnoser,
_OverloadedMethodActionDiagnoser,
_TypeInTemplatedBaseDiagnoser,
_WrongMockMethodMacroDiagnoser,
_WrongParenPositionDiagnoser,
]
def Diagnose(msg):
"""Generates all possible diagnoses given the compiler error message."""
msg = re.sub(r'\x1b\[[^m]*m', '', msg) # Strips all color formatting.
# Assuming the string is using the UTF-8 encoding, replaces the left and
# the right single quote characters with apostrophes.
msg = re.sub(r'(\xe2\x80\x98|\xe2\x80\x99)', "'", msg)
diagnoses = []
for diagnoser in _DIAGNOSERS:
for diag in diagnoser(msg):
diagnosis = '[%s - %s]\n%s' % diag
if not diagnosis in diagnoses:
diagnoses.append(diagnosis)
return diagnoses
def main():
print ('Google Mock Doctor v%s - '
'diagnoses problems in code using Google Mock.' % _VERSION)
if sys.stdin.isatty():
print ('Please copy and paste the compiler errors here. Press c-D when '
'you are done:')
else:
print ('Waiting for compiler errors on stdin . . .')
msg = sys.stdin.read().strip()
diagnoses = Diagnose(msg)
count = len(diagnoses)
if not count:
print ("""
Your compiler complained:
8<------------------------------------------------------------
%s
------------------------------------------------------------>8
Uh-oh, I'm not smart enough to figure out what the problem is. :-(
However...
If you send your source code and the compiler's error messages to
%s, you can be helped and I can get smarter --
win-win for us!""" % (msg, _EMAIL))
else:
print ('------------------------------------------------------------')
print ('Your code appears to have the following',)
if count > 1:
print ('%s diseases:' % (count,))
else:
print ('disease:')
i = 0
for d in diagnoses:
i += 1
if count > 1:
print ('\n#%s:' % (i,))
print (d)
print ("""
How did I do? If you think I'm wrong or unhelpful, please send your
source code and the compiler's error messages to %s.
Then you can be helped and I can get smarter -- I promise I won't be upset!""" %
_EMAIL)
if __name__ == '__main__':
main()

File diff suppressed because it is too large Load Diff

@ -1,78 +0,0 @@
#!/usr/bin/env python
#
# Copyright 2009, 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.
"""upload_gmock.py v0.1.0 -- uploads a Google Mock patch for review.
This simple wrapper passes all command line flags and
--cc=googlemock@googlegroups.com to upload.py.
USAGE: upload_gmock.py [options for upload.py]
"""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
CC_FLAG = '--cc='
GMOCK_GROUP = 'googlemock@googlegroups.com'
def main():
# Finds the path to upload.py, assuming it is in the same directory
# as this file.
my_dir = os.path.dirname(os.path.abspath(__file__))
upload_py_path = os.path.join(my_dir, 'upload.py')
# Adds Google Mock discussion group to the cc line if it's not there
# already.
upload_py_argv = [upload_py_path]
found_cc_flag = False
for arg in sys.argv[1:]:
if arg.startswith(CC_FLAG):
found_cc_flag = True
cc_line = arg[len(CC_FLAG):]
cc_list = [addr for addr in cc_line.split(',') if addr]
if GMOCK_GROUP not in cc_list:
cc_list.append(GMOCK_GROUP)
upload_py_argv.append(CC_FLAG + ','.join(cc_list))
else:
upload_py_argv.append(arg)
if not found_cc_flag:
upload_py_argv.append(CC_FLAG + GMOCK_GROUP)
# Invokes upload.py with the modified command line flags.
os.execv(upload_py_path, upload_py_argv)
if __name__ == '__main__':
main()

@ -34,7 +34,6 @@
// utilities for defining matchers. // utilities for defining matchers.
#include "gmock/gmock-matchers.h" #include "gmock/gmock-matchers.h"
#include "gmock/gmock-generated-matchers.h"
#include <string.h> #include <string.h>
#include <iostream> #include <iostream>
@ -219,8 +218,6 @@ class MaxBipartiteMatchState {
// right_[left_[i]] = i. // right_[left_[i]] = i.
::std::vector<size_t> left_; ::std::vector<size_t> left_;
::std::vector<size_t> right_; ::std::vector<size_t> right_;
GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
}; };
const size_t MaxBipartiteMatchState::kUnused; const size_t MaxBipartiteMatchState::kUnused;

@ -36,14 +36,17 @@
#include "gmock/gmock-spec-builders.h" #include "gmock/gmock-spec-builders.h"
#include <stdlib.h> #include <stdlib.h>
#include <iostream> // NOLINT #include <iostream> // NOLINT
#include <map> #include <map>
#include <memory> #include <memory>
#include <set> #include <set>
#include <string> #include <string>
#include <vector> #include <vector>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
# include <unistd.h> // NOLINT # include <unistd.h> // NOLINT
@ -70,7 +73,8 @@ GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
const char* file, int line, const char* file, int line,
const std::string& message) { const std::string& message) {
::std::ostringstream s; ::std::ostringstream s;
s << file << ":" << line << ": " << message << ::std::endl; s << internal::FormatFileLocation(file, line) << " " << message
<< ::std::endl;
Log(severity, s.str(), 0); Log(severity, s.str(), 0);
} }
@ -291,8 +295,8 @@ 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/googlemock/" "https://github.com/google/googletest/blob/master/docs/"
"docs/cook_book.md#" "gmock_cook_book.md#"
"knowing-when-to-expect for details.\n", "knowing-when-to-expect for details.\n",
stack_frames_to_skip); stack_frames_to_skip);
break; break;
@ -429,10 +433,10 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
// The UntypedFindMatchingExpectation() function acquires and // The UntypedFindMatchingExpectation() function acquires and
// releases g_gmock_mutex. // releases g_gmock_mutex.
const ExpectationBase* const untyped_expectation = const ExpectationBase* const untyped_expectation =
this->UntypedFindMatchingExpectation( this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
untyped_args, &untyped_action, &is_excessive, &is_excessive, &ss, &why);
&ss, &why);
const bool found = untyped_expectation != nullptr; const bool found = untyped_expectation != nullptr;
// True if and only if we need to print the call's arguments // True if and only if we need to print the call's arguments
@ -457,26 +461,42 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
untyped_expectation->DescribeLocationTo(&loc); untyped_expectation->DescribeLocationTo(&loc);
} }
UntypedActionResultHolderBase* const result = UntypedActionResultHolderBase* result = nullptr;
untyped_action == nullptr
? this->UntypedPerformDefaultAction(untyped_args, ss.str()) auto perform_action = [&] {
: this->UntypedPerformAction(untyped_action, untyped_args); return untyped_action == nullptr
if (result != nullptr) result->PrintAsActionResult(&ss); ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
ss << "\n" << why.str(); : this->UntypedPerformAction(untyped_action, untyped_args);
};
if (!found) { auto handle_failures = [&] {
// No expectation matches this call - reports a failure. ss << "\n" << why.str();
Expect(false, nullptr, -1, ss.str());
} else if (is_excessive) { if (!found) {
// We had an upper-bound violation and the failure message is in ss. // No expectation matches this call - reports a failure.
Expect(false, untyped_expectation->file(), Expect(false, nullptr, -1, ss.str());
untyped_expectation->line(), ss.str()); } else if (is_excessive) {
} else { // We had an upper-bound violation and the failure message is in ss.
// We had an expected call and the matching expectation is Expect(false, untyped_expectation->file(), untyped_expectation->line(),
// described in ss. ss.str());
Log(kInfo, loc.str() + ss.str(), 2); } else {
// We had an expected call and the matching expectation is
// described in ss.
Log(kInfo, loc.str() + ss.str(), 2);
}
};
#if GTEST_HAS_EXCEPTIONS
try {
result = perform_action();
} catch (...) {
handle_failures();
throw;
} }
#else
result = perform_action();
#endif
if (result != nullptr) result->PrintAsActionResult(&ss);
handle_failures();
return result; return result;
} }
@ -620,7 +640,7 @@ class MockObjectRegistry {
if (leaked_count > 0) { if (leaked_count > 0) {
std::cout << "\nERROR: " << leaked_count << " leaked mock " std::cout << "\nERROR: " << leaked_count << " leaked mock "
<< (leaked_count == 1 ? "object" : "objects") << (leaked_count == 1 ? "object" : "objects")
<< " found at program exit. Expectations on a mock object is " << " found at program exit. Expectations on a mock object are "
"verified when the object is destructed. Leaking a mock " "verified when the object is destructed. Leaking a mock "
"means that its expectations aren't verified, which is " "means that its expectations aren't verified, which is "
"usually a test bug. If you really intend to leak a mock, " "usually a test bug. If you really intend to leak a mock, "

@ -124,7 +124,7 @@ static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
} }
static bool ParseGoogleMockIntFlag(const char* str, const char* flag, static bool ParseGoogleMockIntFlag(const char* str, const char* flag,
int* value) { int32_t* value) {
// Gets the value of the flag as a string. // Gets the value of the flag as a string.
const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);

@ -32,7 +32,10 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#ifdef ARDUINO #if GTEST_OS_ESP8266 || GTEST_OS_ESP32
#if GTEST_OS_ESP8266
extern "C" {
#endif
void setup() { void setup() {
// Since Google Mock depends on Google Test, InitGoogleMock() is // Since Google Mock depends on Google Test, InitGoogleMock() is
// also responsible for initializing Google Test. Therefore there's // also responsible for initializing Google Test. Therefore there's
@ -40,6 +43,10 @@ void setup() {
testing::InitGoogleMock(); testing::InitGoogleMock();
} }
void loop() { RUN_ALL_TESTS(); } void loop() { RUN_ALL_TESTS(); }
#if GTEST_OS_ESP8266
}
#endif
#else #else
// MS C++ compiler/linker has a bug on Windows (not on Windows CE), which // MS C++ compiler/linker has a bug on Windows (not on Windows CE), which

@ -28,8 +28,6 @@
# (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.
# #
# Author: misterg@google.com (Gennadiy Civil)
#
# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock # Bazel Build for Google C++ Testing Framework(Google Test)-googlemock
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test") load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
@ -54,6 +52,9 @@ py_library(
name = "gmock_test_utils", name = "gmock_test_utils",
testonly = 1, testonly = 1,
srcs = ["gmock_test_utils.py"], srcs = ["gmock_test_utils.py"],
deps = [
"//googletest/test:gtest_test_utils",
],
) )
cc_binary( cc_binary(
@ -71,6 +72,10 @@ py_test(
":gmock_leak_test_", ":gmock_leak_test_",
":gmock_test_utils", ":gmock_test_utils",
], ],
tags = [
"no_test_msvc2015",
"no_test_msvc2017",
],
) )
cc_test( cc_test(
@ -98,7 +103,10 @@ py_test(
":gmock_output_test_", ":gmock_output_test_",
":gmock_output_test_golden.txt", ":gmock_output_test_golden.txt",
], ],
python_version = "PY2", tags = [
"no_test_msvc2015",
"no_test_msvc2017",
],
deps = [":gmock_test_utils"], deps = [":gmock_test_utils"],
) )

@ -32,11 +32,13 @@
// //
// This file tests the built-in actions. // This file tests the built-in actions.
// Silence C4800 (C4800: 'int *const ': forcing value // Silence C4100 (unreferenced formal parameter) for MSVC
// to bool 'true' or 'false') for MSVC 15
#ifdef _MSC_VER #ifdef _MSC_VER
#if _MSC_VER == 1900
# pragma warning(push) # pragma warning(push)
# pragma warning(disable:4100)
#if _MSC_VER == 1900
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15
# pragma warning(disable:4800) # pragma warning(disable:4800)
#endif #endif
#endif #endif
@ -46,6 +48,7 @@
#include <iterator> #include <iterator>
#include <memory> #include <memory>
#include <string> #include <string>
#include <type_traits>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
@ -53,36 +56,34 @@
namespace { namespace {
// This list should be kept sorted. using ::testing::_;
using testing::_; using ::testing::Action;
using testing::Action; using ::testing::ActionInterface;
using testing::ActionInterface; using ::testing::Assign;
using testing::Assign; using ::testing::ByMove;
using testing::ByMove; using ::testing::ByRef;
using testing::ByRef; using ::testing::DefaultValue;
using testing::DefaultValue; using ::testing::DoAll;
using testing::DoAll; using ::testing::DoDefault;
using testing::DoDefault; using ::testing::IgnoreResult;
using testing::IgnoreResult; using ::testing::Invoke;
using testing::Invoke; using ::testing::InvokeWithoutArgs;
using testing::InvokeWithoutArgs; using ::testing::MakePolymorphicAction;
using testing::MakePolymorphicAction; using ::testing::PolymorphicAction;
using testing::Ne; using ::testing::Return;
using testing::PolymorphicAction; using ::testing::ReturnNew;
using testing::Return; using ::testing::ReturnNull;
using testing::ReturnNull; using ::testing::ReturnRef;
using testing::ReturnRef; using ::testing::ReturnRefOfCopy;
using testing::ReturnRefOfCopy; using ::testing::ReturnRoundRobin;
using testing::SetArgPointee; using ::testing::SetArgPointee;
using testing::SetArgumentPointee; using ::testing::SetArgumentPointee;
using testing::Unused; using ::testing::Unused;
using testing::WithArgs; using ::testing::WithArgs;
using testing::internal::BuiltInDefaultValue; using ::testing::internal::BuiltInDefaultValue;
using testing::internal::Int64;
using testing::internal::UInt64;
#if !GTEST_OS_WINDOWS_MOBILE #if !GTEST_OS_WINDOWS_MOBILE
using testing::SetErrnoAndReturn; using ::testing::SetErrnoAndReturn;
#endif #endif
// Tests that BuiltInDefaultValue<T*>::Get() returns NULL. // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
@ -121,8 +122,9 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); // NOLINT
EXPECT_EQ(0, BuiltInDefaultValue<float>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
EXPECT_EQ(0, BuiltInDefaultValue<double>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
} }
@ -145,8 +147,9 @@ TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); // NOLINT
EXPECT_TRUE(BuiltInDefaultValue<float>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
EXPECT_TRUE(BuiltInDefaultValue<double>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
} }
@ -573,8 +576,6 @@ class FromType {
private: private:
bool* const converted_; bool* const converted_;
GTEST_DISALLOW_ASSIGN_(FromType);
}; };
class ToType { class ToType {
@ -646,6 +647,41 @@ TEST(ReturnRefTest, IsCovariant) {
EXPECT_EQ(&derived, &a.Perform(std::make_tuple())); EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));
} }
template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
bool CanCallReturnRef(T&&) { return true; }
bool CanCallReturnRef(Unused) { return false; }
// Tests that ReturnRef(v) is working with non-temporaries (T&)
TEST(ReturnRefTest, WorksForNonTemporary) {
int scalar_value = 123;
EXPECT_TRUE(CanCallReturnRef(scalar_value));
std::string non_scalar_value("ABC");
EXPECT_TRUE(CanCallReturnRef(non_scalar_value));
const int const_scalar_value{321};
EXPECT_TRUE(CanCallReturnRef(const_scalar_value));
const std::string const_non_scalar_value("CBA");
EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value));
}
// Tests that ReturnRef(v) is not working with temporaries (T&&)
TEST(ReturnRefTest, DoesNotWorkForTemporary) {
auto scalar_value = []() -> int { return 123; };
EXPECT_FALSE(CanCallReturnRef(scalar_value()));
auto non_scalar_value = []() -> std::string { return "ABC"; };
EXPECT_FALSE(CanCallReturnRef(non_scalar_value()));
// cannot use here callable returning "const scalar type",
// because such const for scalar return type is ignored
EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321)));
auto const_non_scalar_value = []() -> const std::string { return "CBA"; };
EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value()));
}
// Tests that ReturnRefOfCopy(v) works for reference types. // Tests that ReturnRefOfCopy(v) works for reference types.
TEST(ReturnRefOfCopyTest, WorksForReference) { TEST(ReturnRefOfCopyTest, WorksForReference) {
int n = 42; int n = 42;
@ -670,6 +706,31 @@ TEST(ReturnRefOfCopyTest, IsCovariant) {
EXPECT_NE(&derived, &a.Perform(std::make_tuple())); EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
} }
// Tests that ReturnRoundRobin(v) works with initializer lists
TEST(ReturnRoundRobinTest, WorksForInitList) {
Action<int()> ret = ReturnRoundRobin({1, 2, 3});
EXPECT_EQ(1, ret.Perform(std::make_tuple()));
EXPECT_EQ(2, ret.Perform(std::make_tuple()));
EXPECT_EQ(3, ret.Perform(std::make_tuple()));
EXPECT_EQ(1, ret.Perform(std::make_tuple()));
EXPECT_EQ(2, ret.Perform(std::make_tuple()));
EXPECT_EQ(3, ret.Perform(std::make_tuple()));
}
// Tests that ReturnRoundRobin(v) works with vectors
TEST(ReturnRoundRobinTest, WorksForVector) {
std::vector<double> v = {4.4, 5.5, 6.6};
Action<double()> ret = ReturnRoundRobin(v);
EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
}
// Tests that DoDefault() does the default action for the mock method. // Tests that DoDefault() does the default action for the mock method.
class MockClass { class MockClass {
@ -734,7 +795,7 @@ TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
} }
// Tests that DoDefault() returns the default value set by // Tests that DoDefault() returns the default value set by
// DefaultValue<T>::Set() when it's not overriden by an ON_CALL(). // DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
DefaultValue<int>::Set(1); DefaultValue<int>::Set(1);
MockClass mock; MockClass mock;
@ -1230,6 +1291,52 @@ TEST(ByRefTest, PrintsCorrectly) {
EXPECT_EQ(expected.str(), actual.str()); EXPECT_EQ(expected.str(), actual.str());
} }
struct UnaryConstructorClass {
explicit UnaryConstructorClass(int v) : value(v) {}
int value;
};
// Tests using ReturnNew() with a unary constructor.
TEST(ReturnNewTest, Unary) {
Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
UnaryConstructorClass* c = a.Perform(std::make_tuple());
EXPECT_EQ(4000, c->value);
delete c;
}
TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
Action<UnaryConstructorClass*(bool, int)> a =
ReturnNew<UnaryConstructorClass>(4000);
UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
EXPECT_EQ(4000, c->value);
delete c;
}
TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
Action<const UnaryConstructorClass*()> a =
ReturnNew<UnaryConstructorClass>(4000);
const UnaryConstructorClass* c = a.Perform(std::make_tuple());
EXPECT_EQ(4000, c->value);
delete c;
}
class TenArgConstructorClass {
public:
TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
int a8, int a9, int a10)
: value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
int value_;
};
// Tests using ReturnNew() with a 10-argument constructor.
TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(
1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,
0);
TenArgConstructorClass* c = a.Perform(std::make_tuple());
EXPECT_EQ(1234567890, c->value_);
delete c;
}
std::unique_ptr<int> UniquePtrSource() { std::unique_ptr<int> UniquePtrSource() {
return std::unique_ptr<int>(new int(19)); return std::unique_ptr<int>(new int(19));
@ -1408,8 +1515,19 @@ TEST(FunctorActionTest, TypeConversion) {
EXPECT_EQ(1, s2.Perform(std::make_tuple("hello"))); EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
// Also between the lambda and the action itself. // Also between the lambda and the action itself.
const Action<bool(std::string)> x = [](Unused) { return 42; }; const Action<bool(std::string)> x1 = [](Unused) { return 42; };
EXPECT_TRUE(x.Perform(std::make_tuple("hello"))); const Action<bool(std::string)> x2 = [] { return 42; };
EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));
EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));
// Ensure decay occurs where required.
std::function<int()> f = [] { return 7; };
Action<int(int)> d = f;
f = nullptr;
EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
// Ensure creation of an empty action succeeds.
Action<void(int)>(nullptr);
} }
TEST(FunctorActionTest, UnusedArguments) { TEST(FunctorActionTest, UnusedArguments) {
@ -1434,6 +1552,26 @@ TEST(MoveOnlyArgumentsTest, ReturningActions) {
EXPECT_EQ(x, 3); EXPECT_EQ(x, 3);
} }
ACTION(ReturnArity) {
return std::tuple_size<args_type>::value;
}
TEST(ActionMacro, LargeArity) {
EXPECT_EQ(
1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));
EXPECT_EQ(
10,
testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(
ReturnArity())
.Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));
EXPECT_EQ(
20,
testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,
int, int, int, int, int, int, int, int, int)>(
ReturnArity())
.Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19)));
}
} // Unnamed namespace } // Unnamed namespace

@ -1,16 +0,0 @@
#include "gmock/gmock.h"
#include <memory>
#include <string>
#if defined(TEST_MOCK_METHOD_INVALID_CONST_SPEC)
struct Base {
MOCK_METHOD(int, F, (), (onst));
};
#else
// Sanity check - this should compile.
#endif

@ -1,43 +0,0 @@
"""Negative compilation tests for Google Mock macro MOCK_METHOD."""
import os
import sys
IS_LINUX = os.name == "posix" and os.uname()[0] == "Linux"
if not IS_LINUX:
sys.stderr.write(
"WARNING: Negative compilation tests are not supported on this platform")
sys.exit(0)
# Suppresses the 'Import not at the top of the file' lint complaint.
# pylint: disable-msg=C6204
from google3.testing.pybase import fake_target_util
from google3.testing.pybase import googletest
# pylint: enable-msg=C6204
class GMockMethodNCTest(googletest.TestCase):
"""Negative compilation tests for MOCK_METHOD."""
# The class body is intentionally empty. The actual test*() methods
# will be defined at run time by a call to
# DefineNegativeCompilationTests() later.
pass
# Defines a list of test specs, where each element is a tuple
# (test name, list of regexes for matching the compiler errors).
TEST_SPECS = [
("MOCK_METHOD_INVALID_CONST_SPEC",
[r"onst cannot be recognized as a valid specification modifier"]),
]
# Define a test method in GMockNCTest for each element in TEST_SPECS.
fake_target_util.DefineNegativeCompilationTests(
GMockMethodNCTest,
"google3/third_party/googletest/googlemock/test/gmock-function-mocker_nc",
"gmock-function-mocker_nc.o", TEST_SPECS)
if __name__ == "__main__":
googletest.main()

@ -31,7 +31,7 @@
// 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-generated-function-mockers.h" #include "gmock/gmock-function-mocker.h"
#if GTEST_OS_WINDOWS #if 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
@ -40,8 +40,11 @@
# include <objbase.h> # include <objbase.h>
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
#include <functional>
#include <map> #include <map>
#include <string> #include <string>
#include <type_traits>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
@ -101,6 +104,20 @@ class FooInterface {
virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0; virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;
virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable<int>&) = 0; virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable<int>&) = 0;
virtual int (*ReturnsFunctionPointer1(int))(bool) = 0;
using fn_ptr = int (*)(bool);
virtual fn_ptr ReturnsFunctionPointer2(int) = 0;
virtual int RefQualifiedConstRef() const& = 0;
virtual int RefQualifiedConstRefRef() const&& = 0;
virtual int RefQualifiedRef() & = 0;
virtual int RefQualifiedRefRef() && = 0;
virtual int RefQualifiedOverloaded() const& = 0;
virtual int RefQualifiedOverloaded() const&& = 0;
virtual int RefQualifiedOverloaded() & = 0;
virtual int RefQualifiedOverloaded() && = 0;
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
STDMETHOD_(int, CTNullary)() = 0; STDMETHOD_(int, CTNullary)() = 0;
STDMETHOD_(bool, CTUnary)(int x) = 0; STDMETHOD_(bool, CTUnary)(int x) = 0;
@ -159,6 +176,9 @@ class MockFoo : public FooInterface {
MOCK_METHOD(int, TypeWithTemplatedCopyCtor, MOCK_METHOD(int, TypeWithTemplatedCopyCtor,
(const TemplatedCopyable<int>&)); // NOLINT (const TemplatedCopyable<int>&)); // NOLINT
MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ());
MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ());
#if GTEST_OS_WINDOWS #if 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)));
@ -171,189 +191,301 @@ class MockFoo : public FooInterface {
(Calltype(STDMETHODCALLTYPE))); (Calltype(STDMETHODCALLTYPE)));
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Test reference qualified functions.
MOCK_METHOD(int, RefQualifiedConstRef, (), (const, ref(&), override));
MOCK_METHOD(int, RefQualifiedConstRefRef, (), (const, ref(&&), override));
MOCK_METHOD(int, RefQualifiedRef, (), (ref(&), override));
MOCK_METHOD(int, RefQualifiedRefRef, (), (ref(&&), override));
MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&), override));
MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&&), override));
MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&), override));
MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&&), override));
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
}; };
class LegacyMockFoo : public FooInterface {
public:
LegacyMockFoo() {}
// Makes sure that a mock function parameter can be named.
MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
MOCK_METHOD0(Nullary, int()); // NOLINT
// Makes sure that a mock function parameter can be unnamed.
MOCK_METHOD1(Unary, bool(int)); // NOLINT
MOCK_METHOD2(Binary, long(short, int)); // NOLINT
MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT
double, unsigned, char*, const std::string& str));
MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
MOCK_METHOD1(TakesConstReference, std::string(const int&));
MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());
MOCK_CONST_METHOD1(ReturnTypeWithComma,
std::map<int, std::string>(int)); // NOLINT
MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, char(char)); // NOLINT
MOCK_METHOD0(OverloadedOnConstness, int()); // NOLINT
MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT
MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
MOCK_METHOD1(TypeWithComma,
int(const std::map<int, std::string>&)); // NOLINT
MOCK_METHOD1(TypeWithTemplatedCopyCtor,
int(const TemplatedCopyable<int>&)); // NOLINT
MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool));
MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int));
#if GTEST_OS_WINDOWS
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); // NOLINT
MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
int(bool b, char c, short d, int e, // NOLINT
long f, float g, double h, // NOLINT
unsigned i, char* j, const std::string& k));
MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst,
char(int)); // NOLINT
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
std::map<int, std::string>());
#endif // GTEST_OS_WINDOWS
// We can't mock these with the old macros, but we need to define them to make
// it concrete.
int RefQualifiedConstRef() const& override { return 0; }
int RefQualifiedConstRefRef() const&& override { return 0; }
int RefQualifiedRef() & override { return 0; }
int RefQualifiedRefRef() && override { return 0; }
int RefQualifiedOverloaded() const& override { return 0; }
int RefQualifiedOverloaded() const&& override { return 0; }
int RefQualifiedOverloaded() & override { return 0; }
int RefQualifiedOverloaded() && override { return 0; }
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockFoo);
};
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) # pragma warning(pop)
#endif #endif
class MockMethodFunctionMockerTest : public testing::Test { template <class T>
class FunctionMockerTest : public testing::Test {
protected: protected:
MockMethodFunctionMockerTest() : foo_(&mock_foo_) {} FunctionMockerTest() : foo_(&mock_foo_) {}
FooInterface* const foo_; FooInterface* const foo_;
MockFoo mock_foo_; T mock_foo_;
}; };
using FunctionMockerTestTypes = ::testing::Types<MockFoo, LegacyMockFoo>;
TYPED_TEST_SUITE(FunctionMockerTest, FunctionMockerTestTypes);
// Tests mocking a void-returning function. // Tests mocking a void-returning function.
TEST_F(MockMethodFunctionMockerTest, MocksVoidFunction) { TYPED_TEST(FunctionMockerTest, MocksVoidFunction) {
EXPECT_CALL(mock_foo_, VoidReturning(Lt(100))); EXPECT_CALL(this->mock_foo_, VoidReturning(Lt(100)));
foo_->VoidReturning(0); this->foo_->VoidReturning(0);
} }
// Tests mocking a nullary function. // Tests mocking a nullary function.
TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunction) { TYPED_TEST(FunctionMockerTest, MocksNullaryFunction) {
EXPECT_CALL(mock_foo_, Nullary()) EXPECT_CALL(this->mock_foo_, Nullary())
.WillOnce(DoDefault()) .WillOnce(DoDefault())
.WillOnce(Return(1)); .WillOnce(Return(1));
EXPECT_EQ(0, foo_->Nullary()); EXPECT_EQ(0, this->foo_->Nullary());
EXPECT_EQ(1, foo_->Nullary()); EXPECT_EQ(1, this->foo_->Nullary());
} }
// Tests mocking a unary function. // Tests mocking a unary function.
TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunction) { TYPED_TEST(FunctionMockerTest, MocksUnaryFunction) {
EXPECT_CALL(mock_foo_, Unary(Eq(2))) EXPECT_CALL(this->mock_foo_, Unary(Eq(2))).Times(2).WillOnce(Return(true));
.Times(2)
.WillOnce(Return(true));
EXPECT_TRUE(foo_->Unary(2)); EXPECT_TRUE(this->foo_->Unary(2));
EXPECT_FALSE(foo_->Unary(2)); EXPECT_FALSE(this->foo_->Unary(2));
} }
// Tests mocking a binary function. // Tests mocking a binary function.
TEST_F(MockMethodFunctionMockerTest, MocksBinaryFunction) { TYPED_TEST(FunctionMockerTest, MocksBinaryFunction) {
EXPECT_CALL(mock_foo_, Binary(2, _)) EXPECT_CALL(this->mock_foo_, Binary(2, _)).WillOnce(Return(3));
.WillOnce(Return(3));
EXPECT_EQ(3, foo_->Binary(2, 1)); EXPECT_EQ(3, this->foo_->Binary(2, 1));
} }
// Tests mocking a decimal function. // Tests mocking a decimal function.
TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunction) { TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), EXPECT_CALL(this->mock_foo_,
Lt(100), 5U, NULL, "hi")) Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(5)); .WillOnce(Return(5));
EXPECT_EQ(5, 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"));
} }
// Tests mocking a function that takes a non-const reference. // Tests mocking a function that takes a non-const reference.
TEST_F(MockMethodFunctionMockerTest, TYPED_TEST(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
MocksFunctionWithNonConstReferenceArgument) {
int a = 0; int a = 0;
EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a))) EXPECT_CALL(this->mock_foo_, TakesNonConstReference(Ref(a)))
.WillOnce(Return(true)); .WillOnce(Return(true));
EXPECT_TRUE(foo_->TakesNonConstReference(a)); EXPECT_TRUE(this->foo_->TakesNonConstReference(a));
} }
// Tests mocking a function that takes a const reference. // Tests mocking a function that takes a const reference.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstReferenceArgument) { TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
int a = 0; int a = 0;
EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a))) EXPECT_CALL(this->mock_foo_, TakesConstReference(Ref(a)))
.WillOnce(Return("Hello")); .WillOnce(Return("Hello"));
EXPECT_EQ("Hello", foo_->TakesConstReference(a)); EXPECT_EQ("Hello", this->foo_->TakesConstReference(a));
} }
// Tests mocking a function that takes a const variable. // Tests mocking a function that takes a const variable.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstArgument) { TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstArgument) {
EXPECT_CALL(mock_foo_, TakesConst(Lt(10))) EXPECT_CALL(this->mock_foo_, TakesConst(Lt(10))).WillOnce(DoDefault());
.WillOnce(DoDefault());
EXPECT_FALSE(foo_->TakesConst(5)); EXPECT_FALSE(this->foo_->TakesConst(5));
} }
// Tests mocking functions overloaded on the number of arguments. // Tests mocking functions overloaded on the number of arguments.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) { TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber()) EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber())
.WillOnce(Return(1)); .WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_)) EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber(_))
.WillOnce(Return(2)); .WillOnce(Return(2));
EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1)); EXPECT_EQ(2, this->foo_->OverloadedOnArgumentNumber(1));
EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber()); EXPECT_EQ(1, this->foo_->OverloadedOnArgumentNumber());
} }
// Tests mocking functions overloaded on the types of argument. // Tests mocking functions overloaded on the types of argument.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) { TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>())) EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(An<int>()))
.WillOnce(Return(1)); .WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a'))) EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
.WillOnce(Return('b')); .WillOnce(Return('b'));
EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0)); EXPECT_EQ(1, this->foo_->OverloadedOnArgumentType(0));
EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a')); EXPECT_EQ('b', this->foo_->OverloadedOnArgumentType('a'));
} }
// Tests mocking functions overloaded on the const-ness of this object. // Tests mocking functions overloaded on the const-ness of this object.
TEST_F(MockMethodFunctionMockerTest, TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
MocksFunctionsOverloadedOnConstnessOfThis) { EXPECT_CALL(this->mock_foo_, OverloadedOnConstness());
EXPECT_CALL(mock_foo_, OverloadedOnConstness()); EXPECT_CALL(Const(this->mock_foo_), OverloadedOnConstness())
EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
.WillOnce(Return('a')); .WillOnce(Return('a'));
EXPECT_EQ(0, foo_->OverloadedOnConstness()); EXPECT_EQ(0, this->foo_->OverloadedOnConstness());
EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness()); EXPECT_EQ('a', Const(*this->foo_).OverloadedOnConstness());
} }
TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithComma) { TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithComma) {
const std::map<int, std::string> a_map; const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, ReturnTypeWithComma()) EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma()).WillOnce(Return(a_map));
.WillOnce(Return(a_map)); EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma(42)).WillOnce(Return(a_map));
EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma()); EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42)); EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma(42));
} }
TEST_F(MockMethodFunctionMockerTest, MocksTypeWithTemplatedCopyCtor) { TYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true)); EXPECT_CALL(this->mock_foo_, TypeWithTemplatedCopyCtor(_))
EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>())); .WillOnce(Return(true));
EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
} }
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype. // Tests mocking a nullary function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunctionWithCallType) { TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTNullary()) EXPECT_CALL(this->mock_foo_, CTNullary())
.WillOnce(Return(-1)) .WillOnce(Return(-1))
.WillOnce(Return(0)); .WillOnce(Return(0));
EXPECT_EQ(-1, foo_->CTNullary()); EXPECT_EQ(-1, this->foo_->CTNullary());
EXPECT_EQ(0, foo_->CTNullary()); EXPECT_EQ(0, this->foo_->CTNullary());
} }
// Tests mocking a unary function with calltype. // Tests mocking a unary function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunctionWithCallType) { TYPED_TEST(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTUnary(Eq(2))) EXPECT_CALL(this->mock_foo_, CTUnary(Eq(2)))
.Times(2) .Times(2)
.WillOnce(Return(true)) .WillOnce(Return(true))
.WillOnce(Return(false)); .WillOnce(Return(false));
EXPECT_TRUE(foo_->CTUnary(2)); EXPECT_TRUE(this->foo_->CTUnary(2));
EXPECT_FALSE(foo_->CTUnary(2)); EXPECT_FALSE(this->foo_->CTUnary(2));
} }
// Tests mocking a decimal function with calltype. // Tests mocking a decimal function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunctionWithCallType) { TYPED_TEST(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), EXPECT_CALL(this->mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
Lt(100), 5U, NULL, "hi")) Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(10)); .WillOnce(Return(10));
EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi")); EXPECT_EQ(10, this->foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
} }
// Tests mocking functions overloaded on the const-ness of this object. // Tests mocking functions overloaded on the const-ness of this object.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsConstFunctionWithCallType) { TYPED_TEST(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
EXPECT_CALL(Const(mock_foo_), CTConst(_)) EXPECT_CALL(Const(this->mock_foo_), CTConst(_)).WillOnce(Return('a'));
.WillOnce(Return('a'));
EXPECT_EQ('a', Const(*foo_).CTConst(0)); EXPECT_EQ('a', Const(*this->foo_).CTConst(0));
} }
TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithCommaAndCallType) { TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
const std::map<int, std::string> a_map; const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, CTReturnTypeWithComma()) EXPECT_CALL(this->mock_foo_, CTReturnTypeWithComma()).WillOnce(Return(a_map));
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma()); EXPECT_EQ(a_map, this->mock_foo_.CTReturnTypeWithComma());
} }
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
TEST(FunctionMockerTest, RefQualified) {
MockFoo mock_foo;
EXPECT_CALL(mock_foo, RefQualifiedConstRef).WillOnce(Return(1));
EXPECT_CALL(std::move(mock_foo), // NOLINT
RefQualifiedConstRefRef)
.WillOnce(Return(2));
EXPECT_CALL(mock_foo, RefQualifiedRef).WillOnce(Return(3));
EXPECT_CALL(std::move(mock_foo), // NOLINT
RefQualifiedRefRef)
.WillOnce(Return(4));
EXPECT_CALL(static_cast<const MockFoo&>(mock_foo), RefQualifiedOverloaded())
.WillOnce(Return(5));
EXPECT_CALL(static_cast<const MockFoo&&>(mock_foo), RefQualifiedOverloaded())
.WillOnce(Return(6));
EXPECT_CALL(static_cast<MockFoo&>(mock_foo), RefQualifiedOverloaded())
.WillOnce(Return(7));
EXPECT_CALL(static_cast<MockFoo&&>(mock_foo), RefQualifiedOverloaded())
.WillOnce(Return(8));
EXPECT_EQ(mock_foo.RefQualifiedConstRef(), 1);
EXPECT_EQ(std::move(mock_foo).RefQualifiedConstRefRef(), 2); // NOLINT
EXPECT_EQ(mock_foo.RefQualifiedRef(), 3);
EXPECT_EQ(std::move(mock_foo).RefQualifiedRefRef(), 4); // NOLINT
EXPECT_EQ(std::cref(mock_foo).get().RefQualifiedOverloaded(), 5);
EXPECT_EQ(std::move(std::cref(mock_foo).get()) // NOLINT
.RefQualifiedOverloaded(),
6);
EXPECT_EQ(mock_foo.RefQualifiedOverloaded(), 7);
EXPECT_EQ(std::move(mock_foo).RefQualifiedOverloaded(), 8); // NOLINT
}
class MockB { class MockB {
public: public:
MockB() {} MockB() {}
@ -364,20 +496,33 @@ class MockB {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
}; };
class LegacyMockB {
public:
LegacyMockB() {}
MOCK_METHOD0(DoB, void());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockB);
};
template <typename T>
class ExpectCallTest : public ::testing::Test {};
using ExpectCallTestTypes = ::testing::Types<MockB, LegacyMockB>;
TYPED_TEST_SUITE(ExpectCallTest, ExpectCallTestTypes);
// Tests that functions with no EXPECT_CALL() rules can be called any // Tests that functions with no EXPECT_CALL() rules can be called any
// number of times. // number of times.
TEST(MockMethodExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) { TYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
{ { TypeParam b; }
MockB b;
}
{ {
MockB b; TypeParam b;
b.DoB(); b.DoB();
} }
{ {
MockB b; TypeParam b;
b.DoB(); b.DoB();
b.DoB(); b.DoB();
} }
@ -416,9 +561,33 @@ class MockStack : public StackInterface<T> {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
}; };
template <typename T>
class LegacyMockStack : public StackInterface<T> {
public:
LegacyMockStack() {}
MOCK_METHOD1_T(Push, void(const T& elem));
MOCK_METHOD0_T(Pop, void());
MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT
MOCK_CONST_METHOD0_T(GetTop, const T&());
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); // NOLINT
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStack);
};
template <typename T>
class TemplateMockTest : public ::testing::Test {};
using TemplateMockTestTypes =
::testing::Types<MockStack<int>, LegacyMockStack<int>>;
TYPED_TEST_SUITE(TemplateMockTest, TemplateMockTestTypes);
// Tests that template mock works. // Tests that template mock works.
TEST(MockMethodTemplateMockTest, Works) { TYPED_TEST(TemplateMockTest, Works) {
MockStack<int> mock; TypeParam mock;
EXPECT_CALL(mock, GetSize()) EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0)) .WillOnce(Return(0))
@ -439,8 +608,8 @@ TEST(MockMethodTemplateMockTest, Works) {
EXPECT_EQ(0, mock.GetSize()); EXPECT_EQ(0, mock.GetSize());
} }
TEST(MockMethodTemplateMockTest, MethodWithCommaInReturnTypeWorks) { TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
MockStack<int> mock; TypeParam mock;
const std::map<int, int> a_map; const std::map<int, int> a_map;
EXPECT_CALL(mock, ReturnTypeWithComma()) EXPECT_CALL(mock, ReturnTypeWithComma())
@ -484,9 +653,31 @@ class MockStackWithCallType : public StackInterfaceWithCallType<T> {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
}; };
template <typename T>
class LegacyMockStackWithCallType : public StackInterfaceWithCallType<T> {
public:
LegacyMockStackWithCallType() {}
MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStackWithCallType);
};
template <typename T>
class TemplateMockTestWithCallType : public ::testing::Test {};
using TemplateMockTestWithCallTypeTypes =
::testing::Types<MockStackWithCallType<int>,
LegacyMockStackWithCallType<int>>;
TYPED_TEST_SUITE(TemplateMockTestWithCallType,
TemplateMockTestWithCallTypeTypes);
// Tests that template mock with calltype works. // Tests that template mock with calltype works.
TEST(MockMethodTemplateMockTestWithCallType, Works) { TYPED_TEST(TemplateMockTestWithCallType, Works) {
MockStackWithCallType<int> mock; TypeParam mock;
EXPECT_CALL(mock, GetSize()) EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0)) .WillOnce(Return(0))
@ -513,6 +704,11 @@ TEST(MockMethodTemplateMockTestWithCallType, Works) {
MOCK_METHOD(int, Overloaded, (int), (const)); \ MOCK_METHOD(int, Overloaded, (int), (const)); \
MOCK_METHOD(bool, Overloaded, (bool f, int n)) MOCK_METHOD(bool, Overloaded, (bool f, int n))
#define LEGACY_MY_MOCK_METHODS1_ \
MOCK_METHOD0(Overloaded, void()); \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD2(Overloaded, bool(bool f, int n))
class MockOverloadedOnArgNumber { class MockOverloadedOnArgNumber {
public: public:
MockOverloadedOnArgNumber() {} MockOverloadedOnArgNumber() {}
@ -523,8 +719,25 @@ class MockOverloadedOnArgNumber {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
}; };
TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) { class LegacyMockOverloadedOnArgNumber {
MockOverloadedOnArgNumber mock; public:
LegacyMockOverloadedOnArgNumber() {}
LEGACY_MY_MOCK_METHODS1_;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockOverloadedOnArgNumber);
};
template <typename T>
class OverloadedMockMethodTest : public ::testing::Test {};
using OverloadedMockMethodTestTypes =
::testing::Types<MockOverloadedOnArgNumber,
LegacyMockOverloadedOnArgNumber>;
TYPED_TEST_SUITE(OverloadedMockMethodTest, OverloadedMockMethodTestTypes);
TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
TypeParam mock;
EXPECT_CALL(mock, Overloaded()); EXPECT_CALL(mock, Overloaded());
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true)); EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
@ -632,6 +845,68 @@ TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) {
EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); EXPECT_EQ(-1, call(foo.AsStdFunction(), i));
} }
namespace {
template <typename Expected, typename F>
static constexpr bool IsMockFunctionTemplateArgumentDeducedTo(
const internal::MockFunction<F>&) {
return std::is_same<F, Expected>::value;
}
} // namespace
template <typename F>
class MockMethodMockFunctionSignatureTest : public Test {};
using MockMethodMockFunctionSignatureTypes =
Types<void(), int(), void(int), int(int), int(bool, int),
int(bool, char, int, int, int, int, int, char, int, bool)>;
TYPED_TEST_SUITE(MockMethodMockFunctionSignatureTest,
MockMethodMockFunctionSignatureTypes);
TYPED_TEST(MockMethodMockFunctionSignatureTest,
IsMockFunctionTemplateArgumentDeducedForRawSignature) {
using Argument = TypeParam;
MockFunction<Argument> foo;
EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
}
TYPED_TEST(MockMethodMockFunctionSignatureTest,
IsMockFunctionTemplateArgumentDeducedForStdFunction) {
using Argument = std::function<TypeParam>;
MockFunction<Argument> foo;
EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
}
TYPED_TEST(
MockMethodMockFunctionSignatureTest,
IsMockFunctionCallMethodSignatureTheSameForRawSignatureAndStdFunction) {
using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
using ForStdFunction =
decltype(&MockFunction<std::function<TypeParam>>::Call);
EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
}
template <typename F>
struct AlternateCallable {
};
TYPED_TEST(MockMethodMockFunctionSignatureTest,
IsMockFunctionTemplateArgumentDeducedForAlternateCallable) {
using Argument = AlternateCallable<TypeParam>;
MockFunction<Argument> foo;
EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));
}
TYPED_TEST(
MockMethodMockFunctionSignatureTest,
IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) {
using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
using ForStdFunction =
decltype(&MockFunction<std::function<TypeParam>>::Call);
EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
}
struct MockMethodSizes0 { struct MockMethodSizes0 {
MOCK_METHOD(void, func, ()); MOCK_METHOD(void, func, ());
@ -649,11 +924,62 @@ struct MockMethodSizes4 {
MOCK_METHOD(void, func, (int, int, int, int)); MOCK_METHOD(void, func, (int, int, int, int));
}; };
struct LegacyMockMethodSizes0 {
MOCK_METHOD0(func, void());
};
struct LegacyMockMethodSizes1 {
MOCK_METHOD1(func, void(int));
};
struct LegacyMockMethodSizes2 {
MOCK_METHOD2(func, void(int, int));
};
struct LegacyMockMethodSizes3 {
MOCK_METHOD3(func, void(int, int, int));
};
struct LegacyMockMethodSizes4 {
MOCK_METHOD4(func, void(int, int, int, int));
};
TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes1));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes2));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes3));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes4));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(MockMethodSizes0));
}
void hasTwoParams(int, int);
void MaybeThrows();
void DoesntThrow() noexcept;
struct MockMethodNoexceptSpecifier {
MOCK_METHOD(void, func1, (), (noexcept));
MOCK_METHOD(void, func2, (), (noexcept(true)));
MOCK_METHOD(void, func3, (), (noexcept(false)));
MOCK_METHOD(void, func4, (), (noexcept(noexcept(MaybeThrows()))));
MOCK_METHOD(void, func5, (), (noexcept(noexcept(DoesntThrow()))));
MOCK_METHOD(void, func6, (), (noexcept(noexcept(DoesntThrow())), const));
MOCK_METHOD(void, func7, (), (const, noexcept(noexcept(DoesntThrow()))));
// Put commas in the noexcept expression
MOCK_METHOD(void, func8, (), (noexcept(noexcept(hasTwoParams(1, 2))), const));
};
TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) {
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func1()));
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func2()));
EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func3()));
EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func4()));
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func5()));
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func6()));
EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func7()));
EXPECT_EQ(noexcept(std::declval<MockMethodNoexceptSpecifier>().func8()),
noexcept(hasTwoParams(1, 2)));
} }
} // namespace gmock_function_mocker_test } // namespace gmock_function_mocker_test

@ -1,659 +0,0 @@
// Copyright 2007, 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.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the function mocker classes.
#include "gmock/gmock-generated-function-mockers.h"
#if GTEST_OS_WINDOWS
// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
// we are getting compiler errors if we use basetyps.h, hence including
// objbase.h for definition of STDMETHOD.
# include <objbase.h>
#endif // GTEST_OS_WINDOWS
#include <map>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace testing {
namespace gmock_generated_function_mockers_test {
using testing::_;
using testing::A;
using testing::An;
using testing::AnyNumber;
using testing::Const;
using testing::DoDefault;
using testing::Eq;
using testing::Lt;
using testing::MockFunction;
using testing::Ref;
using testing::Return;
using testing::ReturnRef;
using testing::TypedEq;
template<typename T>
class TemplatedCopyable {
public:
TemplatedCopyable() {}
template <typename U>
TemplatedCopyable(const U& other) {} // NOLINT
};
class FooInterface {
public:
virtual ~FooInterface() {}
virtual void VoidReturning(int x) = 0;
virtual int Nullary() = 0;
virtual bool Unary(int x) = 0;
virtual long Binary(short x, int y) = 0; // NOLINT
virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT
float g, double h, unsigned i, char* j,
const std::string& k) = 0;
virtual bool TakesNonConstReference(int& n) = 0; // NOLINT
virtual std::string TakesConstReference(const int& n) = 0;
virtual bool TakesConst(const int x) = 0;
virtual int OverloadedOnArgumentNumber() = 0;
virtual int OverloadedOnArgumentNumber(int n) = 0;
virtual int OverloadedOnArgumentType(int n) = 0;
virtual char OverloadedOnArgumentType(char c) = 0;
virtual int OverloadedOnConstness() = 0;
virtual char OverloadedOnConstness() const = 0;
virtual int TypeWithHole(int (*func)()) = 0;
virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;
virtual int TypeWithTemplatedCopyCtor(
const TemplatedCopyable<int>& a_vector) = 0;
#if GTEST_OS_WINDOWS
STDMETHOD_(int, CTNullary)() = 0;
STDMETHOD_(bool, CTUnary)(int x) = 0;
STDMETHOD_(int, CTDecimal)
(bool b, char c, short d, int e, long f, // NOLINT
float g, double h, unsigned i, char* j, const std::string& k) = 0;
STDMETHOD_(char, CTConst)(int x) const = 0;
#endif // GTEST_OS_WINDOWS
};
// Const qualifiers on arguments were once (incorrectly) considered
// significant in determining whether two virtual functions had the same
// signature. This was fixed in Visual Studio 2008. However, the compiler
// still emits a warning that alerts about this change in behavior.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4373)
#endif
class MockFoo : public FooInterface {
public:
MockFoo() {}
// Makes sure that a mock function parameter can be named.
MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
MOCK_METHOD0(Nullary, int()); // NOLINT
// Makes sure that a mock function parameter can be unnamed.
MOCK_METHOD1(Unary, bool(int)); // NOLINT
MOCK_METHOD2(Binary, long(short, int)); // NOLINT
MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT
double, unsigned, char*, const std::string& str));
MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
MOCK_METHOD1(TakesConstReference, std::string(const int&));
MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());
MOCK_CONST_METHOD1(ReturnTypeWithComma,
std::map<int, std::string>(int)); // NOLINT
MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, char(char)); // NOLINT
MOCK_METHOD0(OverloadedOnConstness, int()); // NOLINT
MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT
MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
MOCK_METHOD1(TypeWithComma,
int(const std::map<int, std::string>&)); // NOLINT
MOCK_METHOD1(TypeWithTemplatedCopyCtor,
int(const TemplatedCopyable<int>&)); // NOLINT
#if GTEST_OS_WINDOWS
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int));
MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
int(bool b, char c, short d, int e, long f,
float g, double h, unsigned i, char* j,
const std::string& k));
MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int));
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
std::map<int, std::string>());
#endif // GTEST_OS_WINDOWS
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
};
#ifdef _MSC_VER
# pragma warning(pop)
#endif
class FunctionMockerTest : public testing::Test {
protected:
FunctionMockerTest() : foo_(&mock_foo_) {}
FooInterface* const foo_;
MockFoo mock_foo_;
};
// Tests mocking a void-returning function.
TEST_F(FunctionMockerTest, MocksVoidFunction) {
EXPECT_CALL(mock_foo_, VoidReturning(Lt(100)));
foo_->VoidReturning(0);
}
// Tests mocking a nullary function.
TEST_F(FunctionMockerTest, MocksNullaryFunction) {
EXPECT_CALL(mock_foo_, Nullary())
.WillOnce(DoDefault())
.WillOnce(Return(1));
EXPECT_EQ(0, foo_->Nullary());
EXPECT_EQ(1, foo_->Nullary());
}
// Tests mocking a unary function.
TEST_F(FunctionMockerTest, MocksUnaryFunction) {
EXPECT_CALL(mock_foo_, Unary(Eq(2)))
.Times(2)
.WillOnce(Return(true));
EXPECT_TRUE(foo_->Unary(2));
EXPECT_FALSE(foo_->Unary(2));
}
// Tests mocking a binary function.
TEST_F(FunctionMockerTest, MocksBinaryFunction) {
EXPECT_CALL(mock_foo_, Binary(2, _))
.WillOnce(Return(3));
EXPECT_EQ(3, foo_->Binary(2, 1));
}
// Tests mocking a decimal function.
TEST_F(FunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
nullptr, "hi"))
.WillOnce(Return(5));
EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
}
// Tests mocking a function that takes a non-const reference.
TEST_F(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
int a = 0;
EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a)))
.WillOnce(Return(true));
EXPECT_TRUE(foo_->TakesNonConstReference(a));
}
// Tests mocking a function that takes a const reference.
TEST_F(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
int a = 0;
EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a)))
.WillOnce(Return("Hello"));
EXPECT_EQ("Hello", foo_->TakesConstReference(a));
}
// Tests mocking a function that takes a const variable.
TEST_F(FunctionMockerTest, MocksFunctionWithConstArgument) {
EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
.WillOnce(DoDefault());
EXPECT_FALSE(foo_->TakesConst(5));
}
// Tests mocking functions overloaded on the number of arguments.
TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber())
.WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_))
.WillOnce(Return(2));
EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1));
EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber());
}
// Tests mocking functions overloaded on the types of argument.
TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>()))
.WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
.WillOnce(Return('b'));
EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0));
EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a'));
}
// Tests mocking functions overloaded on the const-ness of this object.
TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
EXPECT_CALL(mock_foo_, OverloadedOnConstness());
EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
.WillOnce(Return('a'));
EXPECT_EQ(0, foo_->OverloadedOnConstness());
EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
}
TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) {
const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
}
TEST_F(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true));
EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
}
#if GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype.
TEST_F(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTNullary())
.WillOnce(Return(-1))
.WillOnce(Return(0));
EXPECT_EQ(-1, foo_->CTNullary());
EXPECT_EQ(0, foo_->CTNullary());
}
// Tests mocking a unary function with calltype.
TEST_F(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTUnary(Eq(2)))
.Times(2)
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_TRUE(foo_->CTUnary(2));
EXPECT_FALSE(foo_->CTUnary(2));
}
// Tests mocking a decimal function with calltype.
TEST_F(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
nullptr, "hi"))
.WillOnce(Return(10));
EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
}
// Tests mocking functions overloaded on the const-ness of this object.
TEST_F(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
EXPECT_CALL(Const(mock_foo_), CTConst(_))
.WillOnce(Return('a'));
EXPECT_EQ('a', Const(*foo_).CTConst(0));
}
TEST_F(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
}
#endif // GTEST_OS_WINDOWS
class MockB {
public:
MockB() {}
MOCK_METHOD0(DoB, void());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
};
// Tests that functions with no EXPECT_CALL() ruls can be called any
// number of times.
TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
{
MockB b;
}
{
MockB b;
b.DoB();
}
{
MockB b;
b.DoB();
b.DoB();
}
}
// Tests mocking template interfaces.
template <typename T>
class StackInterface {
public:
virtual ~StackInterface() {}
// Template parameter appears in function parameter.
virtual void Push(const T& value) = 0;
virtual void Pop() = 0;
virtual int GetSize() const = 0;
// Template parameter appears in function return type.
virtual const T& GetTop() const = 0;
};
template <typename T>
class MockStack : public StackInterface<T> {
public:
MockStack() {}
MOCK_METHOD1_T(Push, void(const T& elem));
MOCK_METHOD0_T(Pop, void());
MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT
MOCK_CONST_METHOD0_T(GetTop, const T&());
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); // NOLINT
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
};
// Tests that template mock works.
TEST(TemplateMockTest, Works) {
MockStack<int> mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
.WillOnce(Return(1))
.WillOnce(Return(0));
EXPECT_CALL(mock, Push(_));
int n = 5;
EXPECT_CALL(mock, GetTop())
.WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize());
mock.Push(5);
EXPECT_EQ(1, mock.GetSize());
EXPECT_EQ(5, mock.GetTop());
mock.Pop();
EXPECT_EQ(0, mock.GetSize());
}
TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
MockStack<int> mock;
const std::map<int, int> a_map;
EXPECT_CALL(mock, ReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_CALL(mock, ReturnTypeWithComma(1))
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
}
#if GTEST_OS_WINDOWS
// Tests mocking template interfaces with calltype.
template <typename T>
class StackInterfaceWithCallType {
public:
virtual ~StackInterfaceWithCallType() {}
// Template parameter appears in function parameter.
STDMETHOD_(void, Push)(const T& value) = 0;
STDMETHOD_(void, Pop)() = 0;
STDMETHOD_(int, GetSize)() const = 0;
// Template parameter appears in function return type.
STDMETHOD_(const T&, GetTop)() const = 0;
};
template <typename T>
class MockStackWithCallType : public StackInterfaceWithCallType<T> {
public:
MockStackWithCallType() {}
MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
};
// Tests that template mock with calltype works.
TEST(TemplateMockTestWithCallType, Works) {
MockStackWithCallType<int> mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
.WillOnce(Return(1))
.WillOnce(Return(0));
EXPECT_CALL(mock, Push(_));
int n = 5;
EXPECT_CALL(mock, GetTop())
.WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize());
mock.Push(5);
EXPECT_EQ(1, mock.GetSize());
EXPECT_EQ(5, mock.GetTop());
mock.Pop();
EXPECT_EQ(0, mock.GetSize());
}
#endif // GTEST_OS_WINDOWS
#define MY_MOCK_METHODS1_ \
MOCK_METHOD0(Overloaded, void()); \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD2(Overloaded, bool(bool f, int n))
class MockOverloadedOnArgNumber {
public:
MockOverloadedOnArgNumber() {}
MY_MOCK_METHODS1_;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
};
TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
MockOverloadedOnArgNumber mock;
EXPECT_CALL(mock, Overloaded());
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
mock.Overloaded();
EXPECT_EQ(2, mock.Overloaded(1));
EXPECT_TRUE(mock.Overloaded(true, 1));
}
#define MY_MOCK_METHODS2_ \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD1(Overloaded, int(int n))
class MockOverloadedOnConstness {
public:
MockOverloadedOnConstness() {}
MY_MOCK_METHODS2_;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness);
};
TEST(OverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) {
MockOverloadedOnConstness mock;
const MockOverloadedOnConstness* const_mock = &mock;
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3));
EXPECT_EQ(2, mock.Overloaded(1));
EXPECT_EQ(3, const_mock->Overloaded(1));
}
TEST(MockFunctionTest, WorksForVoidNullary) {
MockFunction<void()> foo;
EXPECT_CALL(foo, Call());
foo.Call();
}
TEST(MockFunctionTest, WorksForNonVoidNullary) {
MockFunction<int()> foo;
EXPECT_CALL(foo, Call())
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, foo.Call());
EXPECT_EQ(2, foo.Call());
}
TEST(MockFunctionTest, WorksForVoidUnary) {
MockFunction<void(int)> foo;
EXPECT_CALL(foo, Call(1));
foo.Call(1);
}
TEST(MockFunctionTest, WorksForNonVoidBinary) {
MockFunction<int(bool, int)> foo;
EXPECT_CALL(foo, Call(false, 42))
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_CALL(foo, Call(true, Ge(100)))
.WillOnce(Return(3));
EXPECT_EQ(1, foo.Call(false, 42));
EXPECT_EQ(2, foo.Call(false, 42));
EXPECT_EQ(3, foo.Call(true, 120));
}
TEST(MockFunctionTest, WorksFor10Arguments) {
MockFunction<int(bool a0, char a1, int a2, int a3, int a4,
int a5, int a6, char a7, int a8, bool a9)> foo;
EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _))
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true));
EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false));
}
TEST(MockFunctionTest, AsStdFunction) {
MockFunction<int(int)> foo;
auto call = [](const std::function<int(int)> &f, int i) {
return f(i);
};
EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));
EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));
EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));
EXPECT_EQ(-2, call(foo.AsStdFunction(), 2));
}
TEST(MockFunctionTest, AsStdFunctionReturnsReference) {
MockFunction<int&()> foo;
int value = 1;
EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value));
int& ref = foo.AsStdFunction()();
EXPECT_EQ(1, ref);
value = 2;
EXPECT_EQ(2, ref);
}
TEST(MockFunctionTest, AsStdFunctionWithReferenceParameter) {
MockFunction<int(int &)> foo;
auto call = [](const std::function<int(int& )> &f, int &i) {
return f(i);
};
int i = 42;
EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1));
EXPECT_EQ(-1, call(foo.AsStdFunction(), i));
}
struct MockMethodSizes0 {
MOCK_METHOD0(func, void());
};
struct MockMethodSizes1 {
MOCK_METHOD1(func, void(int));
};
struct MockMethodSizes2 {
MOCK_METHOD2(func, void(int, int));
};
struct MockMethodSizes3 {
MOCK_METHOD3(func, void(int, int, int));
};
struct MockMethodSizes4 {
MOCK_METHOD4(func, void(int, int, int, int));
};
TEST(MockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
}
} // namespace gmock_generated_function_mockers_test
} // namespace testing

@ -36,11 +36,11 @@
#include <stdlib.h> #include <stdlib.h>
#include <cstdint>
#include <map> #include <map>
#include <memory> #include <memory>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <type_traits>
#include <vector> #include <vector>
#include "gmock/gmock.h" #include "gmock/gmock.h"
@ -124,20 +124,6 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
ConvertIdentifierNameToWords("_Chapter11Section_1_")); ConvertIdentifierNameToWords("_Chapter11Section_1_"));
} }
TEST(PointeeOfTest, WorksForSmartPointers) {
EXPECT_TRUE(
(std::is_same<int, PointeeOf<std::unique_ptr<int>>::type>::value));
EXPECT_TRUE(
(std::is_same<std::string,
PointeeOf<std::shared_ptr<std::string>>::type>::value));
}
TEST(PointeeOfTest, WorksForRawPointers) {
EXPECT_TRUE((std::is_same<int, PointeeOf<int*>::type>::value));
EXPECT_TRUE((std::is_same<const char, PointeeOf<const char*>::type>::value));
EXPECT_TRUE((std::is_void<PointeeOf<void*>::type>::value));
}
TEST(GetRawPointerTest, WorksForSmartPointers) { TEST(GetRawPointerTest, WorksForSmartPointers) {
const char* const raw_p1 = new const char('a'); // NOLINT const char* const raw_p1 = new const char('a'); // NOLINT
const std::unique_ptr<const char> p1(raw_p1); const std::unique_ptr<const char> p1(raw_p1);
@ -173,9 +159,9 @@ TEST(KindOfTest, Integer) {
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(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_(Int64)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(UInt64)); // 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 GTEST_OS_LINUX || GTEST_OS_MAC || 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.
@ -223,11 +209,12 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));
// Unsigned => larger unsigned is fine. // Unsigned => larger unsigned is fine.
EXPECT_TRUE( EXPECT_TRUE((LosslessArithmeticConvertible<
(LosslessArithmeticConvertible<unsigned short, UInt64>::value)); // NOLINT unsigned short, uint64_t>::value)); // NOLINT
// Signed => unsigned is not fine. // Signed => unsigned is not fine.
EXPECT_FALSE((LosslessArithmeticConvertible<short, UInt64>::value)); // NOLINT EXPECT_FALSE((LosslessArithmeticConvertible<
short, uint64_t>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible< EXPECT_FALSE((LosslessArithmeticConvertible<
signed char, unsigned int>::value)); // NOLINT signed char, unsigned int>::value)); // NOLINT
@ -243,12 +230,12 @@ TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {
EXPECT_FALSE((LosslessArithmeticConvertible< EXPECT_FALSE((LosslessArithmeticConvertible<
unsigned char, signed char>::value)); unsigned char, signed char>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<UInt64, Int64>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value));
// Larger size => smaller size is not fine. // Larger size => smaller size is not fine.
EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value)); // NOLINT EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<Int64, unsigned int>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int64_t, unsigned int>::value));
} }
TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) { TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {
@ -267,7 +254,7 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {
TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) { TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {
EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value)); // NOLINT EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value)); // NOLINT
EXPECT_FALSE((LosslessArithmeticConvertible<double, Int64>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, int64_t>::value));
EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));
} }

File diff suppressed because it is too large Load Diff

@ -67,6 +67,12 @@ class NotDefaultConstructible {
explicit NotDefaultConstructible(int) {} explicit NotDefaultConstructible(int) {}
}; };
class CallsMockMethodInDestructor {
public:
~CallsMockMethodInDestructor() { OnDestroy(); }
MOCK_METHOD(void, OnDestroy, ());
};
// Defines some mock classes needed by the tests. // Defines some mock classes needed by the tests.
class Foo { class Foo {
@ -302,6 +308,13 @@ TEST(NiceMockTest, AcceptsClassNamedMock) {
nice.DoThis(); nice.DoThis();
} }
TEST(NiceMockTest, IsNiceInDestructor) {
{
NiceMock<CallsMockMethodInDestructor> nice_on_destroy;
// Don't add an expectation for the call before the mock goes out of scope.
}
}
TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) { TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) {
NiceMock<MockFoo> nice_foo; NiceMock<MockFoo> nice_foo;
EXPECT_FALSE(Mock::IsNaggy(&nice_foo)); EXPECT_FALSE(Mock::IsNaggy(&nice_foo));
@ -405,6 +418,22 @@ TEST(NaggyMockTest, AcceptsClassNamedMock) {
naggy.DoThis(); naggy.DoThis();
} }
TEST(NaggyMockTest, IsNaggyInDestructor) {
const std::string saved_flag = GMOCK_FLAG(verbose);
GMOCK_FLAG(verbose) = "warning";
CaptureStdout();
{
NaggyMock<CallsMockMethodInDestructor> naggy_on_destroy;
// Don't add an expectation for the call before the mock goes out of scope.
}
EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag;
}
TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) { TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) {
NaggyMock<MockFoo> naggy_foo; NaggyMock<MockFoo> naggy_foo;
EXPECT_TRUE(Mock::IsNaggy(&naggy_foo)); EXPECT_TRUE(Mock::IsNaggy(&naggy_foo));
@ -489,6 +518,16 @@ TEST(StrictMockTest, AcceptsClassNamedMock) {
strict.DoThis(); strict.DoThis();
} }
TEST(StrictMockTest, IsStrictInDestructor) {
EXPECT_NONFATAL_FAILURE(
{
StrictMock<CallsMockMethodInDestructor> strict_on_destroy;
// Don't add an expectation for the call before the mock goes out of
// scope.
},
"Uninteresting mock function call");
}
TEST(StrictMockTest, IsNaggy_IsNice_IsStrict) { TEST(StrictMockTest, IsNaggy_IsNice_IsStrict) {
StrictMock<MockFoo> strict_foo; StrictMock<MockFoo> strict_foo;
EXPECT_FALSE(Mock::IsNaggy(&strict_foo)); EXPECT_FALSE(Mock::IsNaggy(&strict_foo));

@ -1,5 +1,10 @@
#include "gmock/internal/gmock-pp.h" #include "gmock/internal/gmock-pp.h"
// Used to test MSVC treating __VA_ARGS__ with a comma in it as one value
#define GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_comma ,
#define GMOCK_TEST_REPLACE_comma_WITH_COMMA(x) \
GMOCK_PP_CAT(GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_, x)
// Static assertions. // Static assertions.
namespace testing { namespace testing {
namespace internal { namespace internal {
@ -17,6 +22,11 @@ static_assert(GMOCK_PP_NARG(x, y, z, w) == 4, "");
static_assert(!GMOCK_PP_HAS_COMMA(), ""); static_assert(!GMOCK_PP_HAS_COMMA(), "");
static_assert(GMOCK_PP_HAS_COMMA(b, ), ""); static_assert(GMOCK_PP_HAS_COMMA(b, ), "");
static_assert(!GMOCK_PP_HAS_COMMA((, )), ""); static_assert(!GMOCK_PP_HAS_COMMA((, )), "");
static_assert(GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma)),
"");
static_assert(
GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma(unrelated))),
"");
static_assert(!GMOCK_PP_IS_EMPTY(, ), ""); static_assert(!GMOCK_PP_IS_EMPTY(, ), "");
static_assert(!GMOCK_PP_IS_EMPTY(a), ""); static_assert(!GMOCK_PP_IS_EMPTY(a), "");
static_assert(!GMOCK_PP_IS_EMPTY(()), ""); static_assert(!GMOCK_PP_IS_EMPTY(()), "");

@ -69,8 +69,8 @@ using testing::AtMost;
using testing::Between; using testing::Between;
using testing::Cardinality; using testing::Cardinality;
using testing::CardinalityInterface; using testing::CardinalityInterface;
using testing::ContainsRegex;
using testing::Const; using testing::Const;
using testing::ContainsRegex;
using testing::DoAll; using testing::DoAll;
using testing::DoDefault; using testing::DoDefault;
using testing::Eq; using testing::Eq;
@ -2179,8 +2179,8 @@ 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/googlemock/docs/" "https://github.com/google/googletest/blob/master/docs/"
"cook_book.md#" "gmock_cook_book.md#"
"knowing-when-to-expect for details."; "knowing-when-to-expect for details.";
// A void-returning function. // A void-returning function.

@ -37,9 +37,6 @@
// below list of actual *_test.cc files might change). // below list of actual *_test.cc files might change).
#include "test/gmock-actions_test.cc" #include "test/gmock-actions_test.cc"
#include "test/gmock-cardinalities_test.cc" #include "test/gmock-cardinalities_test.cc"
#include "test/gmock-generated-actions_test.cc"
#include "test/gmock-generated-function-mockers_test.cc"
#include "test/gmock-generated-matchers_test.cc"
#include "test/gmock-internal-utils_test.cc" #include "test/gmock-internal-utils_test.cc"
#include "test/gmock-matchers_test.cc" #include "test/gmock-matchers_test.cc"
#include "test/gmock-more-actions_test.cc" #include "test/gmock-more-actions_test.cc"

@ -112,8 +112,8 @@
// is defined as LinkTest1 in gmock_link_test.cc and as LinkTest2 in // is defined as LinkTest1 in gmock_link_test.cc and as LinkTest2 in
// gmock_link2_test.cc to avoid producing linker errors. // gmock_link2_test.cc to avoid producing linker errors.
#ifndef GMOCK_TEST_GMOCK_LINK_TEST_H_ #ifndef GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
#define GMOCK_TEST_GMOCK_LINK_TEST_H_ #define GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
#include "gmock/gmock.h" #include "gmock/gmock.h"
@ -687,4 +687,4 @@ TEST(LinkTest, TestMatcherCast) {
EXPECT_TRUE(m.Matches(nullptr)); EXPECT_TRUE(m.Matches(nullptr));
} }
#endif // GMOCK_TEST_GMOCK_LINK_TEST_H_ #endif // GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_

@ -75,14 +75,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/googlemock/docs/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/master/docs/gmock_cook_book.md#knowing-when-to-expect 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/googlemock/docs/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/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction [ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation [ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure unknown file: Failure
@ -266,14 +266,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/googlemock/docs/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/master/docs/gmock_cook_book.md#knowing-when-to-expect 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/googlemock/docs/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/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction [ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction [ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
@ -314,4 +314,4 @@ Expected: is pair (is >= 48, true)
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#. FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#. FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#. FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object is verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock. ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object are verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.

@ -53,7 +53,7 @@ else()
cmake_policy(SET CMP0048 NEW) cmake_policy(SET CMP0048 NEW)
project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
endif() endif()
cmake_minimum_required(VERSION 2.6.4) cmake_minimum_required(VERSION 2.8.12)
if (POLICY CMP0063) # Visibility if (POLICY CMP0063) # Visibility
cmake_policy(SET CMP0063 NEW) cmake_policy(SET CMP0063 NEW)
@ -92,10 +92,13 @@ include(cmake/internal_utils.cmake)
config_compiler_and_linker() # Defined in internal_utils.cmake. config_compiler_and_linker() # Defined in internal_utils.cmake.
# Needed to set the namespace for both the export targets and the
# alias libraries
set(cmake_package_name GTest CACHE INTERNAL "")
# Create the CMake package file descriptors. # Create the CMake package file descriptors.
if (INSTALL_GTEST) if (INSTALL_GTEST)
include(CMakePackageConfigHelpers) include(CMakePackageConfigHelpers)
set(cmake_package_name GTest)
set(targets_export_name ${cmake_package_name}Targets CACHE INTERNAL "") set(targets_export_name ${cmake_package_name}Targets CACHE INTERNAL "")
set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated" CACHE INTERNAL "") set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated" CACHE INTERNAL "")
set(cmake_files_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${cmake_package_name}") set(cmake_files_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${cmake_package_name}")
@ -126,7 +129,9 @@ include_directories(${gtest_build_include_dirs})
# are used for other targets, to ensure that gtest can be compiled by a user # are used for other targets, to ensure that gtest can be compiled by a user
# aggressive about warnings. # aggressive about warnings.
cxx_library(gtest "${cxx_strict}" src/gtest-all.cc) cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
set_target_properties(gtest PROPERTIES VERSION ${GOOGLETEST_VERSION})
cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc) cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
# If the CMake version supports it, attach header directory information # 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 # 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). # in via add_subdirectory() rather than being a standalone build).
@ -182,20 +187,6 @@ if (gtest_build_tests)
# 'make test' or ctest. # 'make test' or ctest.
enable_testing() enable_testing()
if (WIN32)
file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1"
CONTENT
"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$<CONFIG>\"
$env:Path = \"$project_bin;$env:Path\"
& $args")
elseif (MINGW OR CYGWIN)
file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1"
CONTENT
"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin)
$env:Path = \"$project_bin;$env:Path\"
& $args")
endif()
############################################################ ############################################################
# C++ tests built with standard compiler flags. # C++ tests built with standard compiler flags.
@ -266,6 +257,7 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_executable(googletest-break-on-failure-unittest_ test gtest) cxx_executable(googletest-break-on-failure-unittest_ test gtest)
py_test(googletest-break-on-failure-unittest) py_test(googletest-break-on-failure-unittest)
py_test(gtest_skip_check_output_test)
py_test(gtest_skip_environment_check_output_test) py_test(gtest_skip_environment_check_output_test)
# Visual Studio .NET 2003 does not support STL with exceptions disabled. # Visual Studio .NET 2003 does not support STL with exceptions disabled.
@ -317,6 +309,9 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_executable(googletest-uninitialized-test_ test gtest) cxx_executable(googletest-uninitialized-test_ test gtest)
py_test(googletest-uninitialized-test) py_test(googletest-uninitialized-test)
cxx_executable(gtest_list_output_unittest_ test gtest)
py_test(gtest_list_output_unittest)
cxx_executable(gtest_xml_outfile1_test_ test gtest_main) cxx_executable(gtest_xml_outfile1_test_ test gtest_main)
cxx_executable(gtest_xml_outfile2_test_ test gtest_main) cxx_executable(gtest_xml_outfile2_test_ test gtest_main)
py_test(gtest_xml_outfiles_test) py_test(gtest_xml_outfiles_test)

@ -1,37 +0,0 @@
# This file contains a list of people who've made non-trivial
# contribution to the Google C++ Testing Framework project. People
# who commit code to the project are encouraged to add their names
# here. Please keep the list sorted by first names.
Ajay Joshi <jaj@google.com>
Balázs Dán <balazs.dan@gmail.com>
Bharat Mediratta <bharat@menalto.com>
Chandler Carruth <chandlerc@google.com>
Chris Prince <cprince@google.com>
Chris Taylor <taylorc@google.com>
Dan Egnor <egnor@google.com>
Eric Roman <eroman@chromium.org>
Hady Zalek <hady.zalek@gmail.com>
Jeffrey Yasskin <jyasskin@google.com>
Jói Sigurðsson <joi@google.com>
Keir Mierle <mierle@gmail.com>
Keith Ray <keith.ray@gmail.com>
Kenton Varda <kenton@google.com>
Manuel Klimek <klimek@google.com>
Markus Heule <markus.heule@gmail.com>
Mika Raento <mikie@iki.fi>
Miklós Fazekas <mfazekas@szemafor.com>
Pasi Valminen <pasi.valminen@gmail.com>
Patrick Hanna <phanna@google.com>
Patrick Riley <pfr@google.com>
Peter Kaminski <piotrk@google.com>
Preston Jackson <preston.a.jackson@gmail.com>
Rainer Klaffenboeck <rainer.klaffenboeck@dynatrace.com>
Russ Cox <rsc@google.com>
Russ Rufer <russ@pentad.com>
Sean Mcafee <eefacm@gmail.com>
Sigurður Ásgeirsson <siggi@google.com>
Tracy Bialik <tracy@pentad.com>
Vadim Berman <vadimb@google.com>
Vlad Losev <vladl@google.com>
Zhanyong Wan <wan@google.com>

@ -1,28 +0,0 @@
Copyright 2008, 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.

@ -2,39 +2,51 @@
#### Setup #### Setup
To build Google Test and your tests that use it, you need to tell your build To build GoogleTest and your tests that use it, you need to tell your build
system where to find its headers and source files. The exact way to do it system where to find its headers and source files. The exact way to do it
depends on which build system you use, and is usually straightforward. depends on which build system you use, and is usually straightforward.
### Build with CMake ### Build with CMake
Google Test comes with a CMake build script ( GoogleTest comes with a CMake build script
[CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt)) ([CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt))
that can be used on a wide range of platforms ("C" stands for cross-platform.). that can be used on a wide range of platforms ("C" stands for cross-platform.).
If you don't have CMake installed already, you can download it for free from If you don't have CMake installed already, you can download it for free from
<http://www.cmake.org/>. <http://www.cmake.org/>.
CMake works by generating native makefiles or build projects that can be used in CMake works by generating native makefiles or build projects that can be used in
the compiler environment of your choice. You can either build Google Test as a the compiler environment of your choice. You can either build GoogleTest as a
standalone project or it can be incorporated into an existing CMake build for standalone project or it can be incorporated into an existing CMake build for
another project. another project.
#### Standalone CMake Project #### Standalone CMake Project
When building Google Test as a standalone project, the typical workflow starts When building GoogleTest as a standalone project, the typical workflow starts
with: with
mkdir mybuild # Create a directory to hold the build output. ```
cd mybuild git clone https://github.com/google/googletest.git -b release-1.10.0
cmake ${GTEST_DIR} # Generate native build scripts. cd googletest # Main directory of the cloned repository.
mkdir build # Create a directory to hold the build output.
cd build
cmake .. # Generate native build scripts for GoogleTest.
```
If you want to build Google Test's samples, you should replace the last command The above command also includes GoogleMock by default. And so, if you want to
with build only GoogleTest, you should replace the last command with
cmake -Dgtest_build_samples=ON ${GTEST_DIR} ```
cmake .. -DBUILD_GMOCK=OFF
```
If you are on a \*nix system, you should now see a Makefile in the current If you are on a \*nix system, you should now see a Makefile in the current
directory. Just type 'make' to build gtest. directory. Just type `make` to build GoogleTest. And then you can simply install
GoogleTest if you are a system administrator.
```
make
sudo make install # Install in /usr/local/ by default
```
If you use Windows and have Visual Studio installed, a `gtest.sln` file and If you use Windows and have Visual Studio installed, a `gtest.sln` file and
several `.vcproj` files will be created. You can then build them using Visual several `.vcproj` files will be created. You can then build them using Visual
@ -44,13 +56,19 @@ On Mac OS X with Xcode installed, a `.xcodeproj` file will be generated.
#### Incorporating Into An Existing CMake Project #### Incorporating Into An Existing CMake Project
If you want to use gtest in a project which already uses CMake, then a more If you want to use GoogleTest in a project which already uses CMake, the easiest
robust and flexible approach is to build gtest as part of that project directly. way is to get installed libraries and headers.
This is done by making the GoogleTest source code available to the main build
and adding it using CMake's `add_subdirectory()` command. This has the * Import GoogleTest by using `find_package` (or `pkg_check_modules`). For
significant advantage that the same compiler and linker settings are used example, if `find_package(GTest CONFIG REQUIRED)` succeeds, you can use the
between gtest and the rest of your project, so issues associated with using libraries as `GTest::gtest`, `GTest::gmock`.
incompatible libraries (eg debug/release), etc. are avoided. This is
And a more robust and flexible approach is to build GoogleTest as part of that
project directly. This is done by making the GoogleTest source code available to
the main build and adding it using CMake's `add_subdirectory()` command. This
has the significant advantage that the same compiler and linker settings are
used between GoogleTest and the rest of your project, so issues associated with
using incompatible libraries (eg debug/release), etc. are avoided. This is
particularly useful on Windows. Making GoogleTest's source code available to the particularly useful on Windows. Making GoogleTest's source code available to the
main build can be done a few different ways: main build can be done a few different ways:
@ -64,68 +82,23 @@ main build can be done a few different ways:
possible or appropriate. Git submodules, for example, have their own set of possible or appropriate. Git submodules, for example, have their own set of
advantages and drawbacks. advantages and drawbacks.
* Use CMake to download GoogleTest as part of the build's configure step. This * Use CMake to download GoogleTest as part of the build's configure step. This
is just a little more complex, but doesn't have the limitations of the other approach doesn't have the limitations of the other methods.
methods.
The last of the above methods is implemented with a small piece of CMake code in The last of the above methods is implemented with a small piece of CMake code
a separate file (e.g. `CMakeLists.txt.in`) which is copied to the build area and that downloads and pulls the GoogleTest code into the main build.
then invoked as a sub-build _during the CMake stage_. That directory is then
pulled into the main build with `add_subdirectory()`. For example:
New file `CMakeLists.txt.in`: Just add to your `CMakeLists.txt`:
```cmake ```cmake
cmake_minimum_required(VERSION 2.8.2) include(FetchContent)
FetchContent_Declare(
project(googletest-download NONE) googletest
# Specify the commit you depend on and update it regularly.
include(ExternalProject) URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
ExternalProject_Add(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG master
SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-src"
BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-build"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
) )
``` # For Windows: Prevent overriding the parent project's compiler/linker settings
Existing build's `CMakeLists.txt`:
```cmake
# Download and unpack googletest at configure time
configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
RESULT_VARIABLE result
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if(result)
message(FATAL_ERROR "CMake step for googletest failed: ${result}")
endif()
execute_process(COMMAND ${CMAKE_COMMAND} --build .
RESULT_VARIABLE result
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if(result)
message(FATAL_ERROR "Build step for googletest failed: ${result}")
endif()
# Prevent overriding the parent project's compiler/linker
# settings on Windows
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
# Add googletest directly to our build. This defines
# the gtest and gtest_main targets.
add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/googletest-src
${CMAKE_CURRENT_BINARY_DIR}/googletest-build
EXCLUDE_FROM_ALL)
# The gtest/gtest_main targets carry header search path
# dependencies automatically when using CMake 2.8.11 or
# later. Otherwise we have to add them here ourselves.
if (CMAKE_VERSION VERSION_LESS 2.8.11)
include_directories("${gtest_SOURCE_DIR}/include")
endif()
# Now simply link against gtest or gtest_main as needed. Eg # Now simply link against gtest or gtest_main as needed. Eg
add_executable(example example.cpp) add_executable(example example.cpp)
@ -133,20 +106,18 @@ target_link_libraries(example gtest_main)
add_test(NAME example_test COMMAND example) add_test(NAME example_test COMMAND example)
``` ```
Note that this approach requires CMake 2.8.2 or later due to its use of the Note that this approach requires CMake 3.14 or later due to its use of the
`ExternalProject_Add()` command. The above technique is discussed in more detail `FetchContent_MakeAvailable()` command.
in [this separate article](http://crascit.com/2015/07/25/cmake-gtest/) which
also contains a link to a fully generalized implementation of the technique.
##### Visual Studio Dynamic vs Static Runtimes ##### Visual Studio Dynamic vs Static Runtimes
By default, new Visual Studio projects link the C runtimes dynamically but By default, new Visual Studio projects link the C runtimes dynamically but
Google Test links them statically. This will generate an error that looks GoogleTest links them statically. This will generate an error that looks
something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch
detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value
'MDd_DynamicDebug' in main.obj 'MDd_DynamicDebug' in main.obj
Google Test already has a CMake option for this: `gtest_force_shared_crt` GoogleTest already has a CMake option for this: `gtest_force_shared_crt`
Enabling this option will make gtest link the runtimes dynamically too, and Enabling this option will make gtest link the runtimes dynamically too, and
match the project in which it is included. match the project in which it is included.
@ -154,17 +125,17 @@ match the project in which it is included.
#### C++ Standard Version #### C++ Standard Version
An environment that supports C++11 is required in order to successfully build An environment that supports C++11 is required in order to successfully build
Google Test. One way to ensure this is to specify the standard in the top-level GoogleTest. One way to ensure this is to specify the standard in the top-level
project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command. If this project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command. If this
is not feasible, for example in a C project using Google Test for validation, is not feasible, for example in a C project using GoogleTest for validation,
then it can be specified by adding it to the options for cmake via the then it can be specified by adding it to the options for cmake via the
`DCMAKE_CXX_FLAGS` option. `DCMAKE_CXX_FLAGS` option.
### Tweaking Google Test ### Tweaking GoogleTest
Google Test can be used in diverse environments. The default configuration may GoogleTest can be used in diverse environments. The default configuration may
not work (or may not work well) out of the box in some environments. However, not work (or may not work well) out of the box in some environments. However,
you can easily tweak Google Test by defining control macros on the compiler you can easily tweak GoogleTest by defining control macros on the compiler
command line. Generally, these macros are named like `GTEST_XYZ` and you define command line. Generally, these macros are named like `GTEST_XYZ` and you define
them to either 1 or 0 to enable or disable a certain feature. them to either 1 or 0 to enable or disable a certain feature.
@ -173,12 +144,12 @@ We list the most frequently used macros below. For a complete list, see file
### Multi-threaded Tests ### Multi-threaded Tests
Google Test is thread-safe where the pthread library is available. After GoogleTest is thread-safe where the pthread library is available. After
`#include "gtest/gtest.h"`, you can check the `#include "gtest/gtest.h"`, you can check the
`GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is `GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is
`#defined` to 1, no if it's undefined.). `#defined` to 1, no if it's undefined.).
If Google Test doesn't correctly detect whether pthread is available in your If GoogleTest doesn't correctly detect whether pthread is available in your
environment, you can force it with environment, you can force it with
-DGTEST_HAS_PTHREAD=1 -DGTEST_HAS_PTHREAD=1
@ -187,16 +158,16 @@ or
-DGTEST_HAS_PTHREAD=0 -DGTEST_HAS_PTHREAD=0
When Google Test uses pthread, you may need to add flags to your compiler and/or When GoogleTest uses pthread, you may need to add flags to your compiler and/or
linker to select the pthread library, or you'll get link errors. If you use the linker to select the pthread library, or you'll get link errors. If you use the
CMake script or the deprecated Autotools script, this is taken care of for you. CMake script, this is taken care of for you. If you use your own build script,
If you use your own build script, you'll need to read your compiler and linker's you'll need to read your compiler and linker's manual to figure out what flags
manual to figure out what flags to add. to add.
### As a Shared Library (DLL) ### As a Shared Library (DLL)
Google Test is compact, so most users can build and link it as a static library GoogleTest is compact, so most users can build and link it as a static library
for the simplicity. You can choose to use Google Test as a shared library (known for the simplicity. You can choose to use GoogleTest as a shared library (known
as a DLL on Windows) if you prefer. as a DLL on Windows) if you prefer.
To compile *gtest* as a shared library, add To compile *gtest* as a shared library, add
@ -216,22 +187,22 @@ Note: while the above steps aren't technically necessary today when using some
compilers (e.g. GCC), they may become necessary in the future, if we decide to compilers (e.g. GCC), they may become necessary in the future, if we decide to
improve the speed of loading the library (see improve the speed of loading the library (see
<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended <http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended
to always add the above flags when using Google Test as a shared library. to always add the above flags when using GoogleTest as a shared library.
Otherwise a future release of Google Test may break your build script. Otherwise a future release of GoogleTest may break your build script.
### Avoiding Macro Name Clashes ### Avoiding Macro Name Clashes
In C++, macros don't obey namespaces. Therefore two libraries that both define a In C++, macros don't obey namespaces. Therefore two libraries that both define a
macro of the same name will clash if you `#include` both definitions. In case a macro of the same name will clash if you `#include` both definitions. In case a
Google Test macro clashes with another library, you can force Google Test to GoogleTest macro clashes with another library, you can force GoogleTest to
rename its macro to avoid the conflict. rename its macro to avoid the conflict.
Specifically, if both Google Test and some other code define macro FOO, you can Specifically, if both GoogleTest and some other code define macro FOO, you can
add add
-DGTEST_DONT_DEFINE_FOO=1 -DGTEST_DONT_DEFINE_FOO=1
to the compiler flags to tell Google Test to change the macro's name from `FOO` to the compiler flags to tell GoogleTest to change the macro's name from `FOO`
to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For
example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write

@ -1,10 +1,9 @@
prefix=${pcfiledir}/../.. libdir=@CMAKE_INSTALL_FULL_LIBDIR@
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
Name: gtest Name: gtest
Description: GoogleTest (without main() function) Description: GoogleTest (without main() function)
Version: @PROJECT_VERSION@ Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest URL: https://github.com/google/googletest
Libs: -L${libdir} -lgtest @CMAKE_THREAD_LIBS_INIT@ Libs: -L${libdir} -lgtest @CMAKE_THREAD_LIBS_INIT@
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@

@ -1,11 +1,10 @@
prefix=${pcfiledir}/../.. libdir=@CMAKE_INSTALL_FULL_LIBDIR@
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
Name: gtest_main Name: gtest_main
Description: GoogleTest (with main() function) Description: GoogleTest (with main() function)
Version: @PROJECT_VERSION@ Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest URL: https://github.com/google/googletest
Requires: gtest Requires: gtest = @PROJECT_VERSION@
Libs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@ Libs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@

@ -72,7 +72,7 @@ macro(config_compiler_and_linker)
if (MSVC) if (MSVC)
# Newlines inside flags variables break CMake's NMake generator. # Newlines inside flags variables break CMake's NMake generator.
# TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds. # TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds.
set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J -Zi") set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J")
set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32") set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32")
set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN") set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN")
set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1") set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1")
@ -81,6 +81,8 @@ macro(config_compiler_and_linker)
# Suppress "unreachable code" warning # Suppress "unreachable code" warning
# http://stackoverflow.com/questions/3232669 explains the issue. # http://stackoverflow.com/questions/3232669 explains the issue.
set(cxx_base_flags "${cxx_base_flags} -wd4702") set(cxx_base_flags "${cxx_base_flags} -wd4702")
# Ensure MSVC treats source files as UTF-8 encoded.
set(cxx_base_flags "${cxx_base_flags} -utf-8")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(cxx_base_flags "-Wall -Wshadow -Werror -Wconversion") set(cxx_base_flags "-Wall -Wshadow -Werror -Wconversion")
set(cxx_exception_flags "-fexceptions") set(cxx_exception_flags "-fexceptions")
@ -148,6 +150,7 @@ function(cxx_library_with_type name type cxx_flags)
# type can be either STATIC or SHARED to denote a static or shared library. # type can be either STATIC or SHARED to denote a static or shared library.
# ARGN refers to additional arguments after 'cxx_flags'. # ARGN refers to additional arguments after 'cxx_flags'.
add_library(${name} ${type} ${ARGN}) add_library(${name} ${type} ${ARGN})
add_library(${cmake_package_name}::${name} ALIAS ${name})
set_target_properties(${name} set_target_properties(${name}
PROPERTIES PROPERTIES
COMPILE_FLAGS "${cxx_flags}") COMPILE_FLAGS "${cxx_flags}")
@ -188,6 +191,10 @@ function(cxx_library_with_type name type cxx_flags)
endif() endif()
target_link_libraries(${name} PUBLIC ${threads_spec}) target_link_libraries(${name} PUBLIC ${threads_spec})
endif() endif()
if (NOT "${CMAKE_VERSION}" VERSION_LESS "3.8")
target_compile_features(${name} PUBLIC cxx_std_11)
endif()
endfunction() endfunction()
######################################################################## ########################################################################
@ -240,7 +247,13 @@ function(cxx_executable name dir libs)
endfunction() endfunction()
# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE. # Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
find_package(PythonInterp) if ("${CMAKE_VERSION}" VERSION_LESS "3.12.0")
find_package(PythonInterp)
else()
find_package(Python COMPONENTS Interpreter)
set(PYTHONINTERP_FOUND ${Python_Interpreter_FOUND})
set(PYTHON_EXECUTABLE ${Python_EXECUTABLE})
endif()
# cxx_test_with_flags(name cxx_flags libs srcs...) # cxx_test_with_flags(name cxx_flags libs srcs...)
# #
@ -248,13 +261,7 @@ find_package(PythonInterp)
# from the given source files with the given compiler flags. # from the given source files with the given compiler flags.
function(cxx_test_with_flags name cxx_flags libs) function(cxx_test_with_flags name cxx_flags libs)
cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN}) cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN})
if (WIN32 OR MINGW) add_test(NAME ${name} COMMAND "$<TARGET_FILE:${name}>")
add_test(NAME ${name}
COMMAND "powershell" "-Command" "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1" "$<TARGET_FILE:${name}>")
else()
add_test(NAME ${name}
COMMAND "$<TARGET_FILE:${name}>")
endif()
endfunction() endfunction()
# cxx_test(name libs srcs...) # cxx_test(name libs srcs...)
@ -278,45 +285,24 @@ function(py_test name)
# Multi-configuration build generators as for Visual Studio save # Multi-configuration build generators as for Visual Studio save
# output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug, # output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug,
# Release etc.), so we have to provide it here. # Release etc.), so we have to provide it here.
if (WIN32 OR MINGW) add_test(NAME ${name}
add_test(NAME ${name} COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1
${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
else()
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN}) --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
endif()
else (CMAKE_CONFIGURATION_TYPES) else (CMAKE_CONFIGURATION_TYPES)
# Single-configuration build generators like Makefile generators # Single-configuration build generators like Makefile generators
# don't have subdirs below CMAKE_CURRENT_BINARY_DIR. # don't have subdirs below CMAKE_CURRENT_BINARY_DIR.
if (WIN32 OR MINGW) add_test(NAME ${name}
add_test(NAME ${name} COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1 --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
else()
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
endif()
endif (CMAKE_CONFIGURATION_TYPES) endif (CMAKE_CONFIGURATION_TYPES)
else() else()
# ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can # ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can
# directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known # directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
# only at ctest runtime (by calling ctest -c <Configuration>), so # only at ctest runtime (by calling ctest -c <Configuration>), so
# we have to escape $ to delay variable substitution here. # we have to escape $ to delay variable substitution here.
if (WIN32 OR MINGW) add_test(NAME ${name}
add_test(NAME ${name} COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1 --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
else()
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
endif()
endif() endif()
endif(PYTHONINTERP_FOUND) endif(PYTHONINTERP_FOUND)
endfunction() endfunction()

File diff suppressed because it is too large Load Diff

@ -1,753 +0,0 @@
# Googletest FAQ
<!-- GOOGLETEST_CM0014 DO NOT DELETE -->
## Why should test suite names and test names not contain underscore?
Underscore (`_`) is special, as C++ reserves the following to be used by the
compiler and the standard library:
1. any identifier that starts with an `_` followed by an upper-case letter, and
2. any identifier that contains two consecutive underscores (i.e. `__`)
*anywhere* in its name.
User code is *prohibited* from using such identifiers.
Now let's look at what this means for `TEST` and `TEST_F`.
Currently `TEST(TestSuiteName, TestName)` generates a class named
`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName`
contains `_`?
1. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say,
`_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus
invalid.
2. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get
`Foo__TestName_Test`, which is invalid.
3. If `TestName` starts with an `_` (say, `_Bar`), we get
`TestSuiteName__Bar_Test`, which is invalid.
4. If `TestName` ends with an `_` (say, `Bar_`), we get
`TestSuiteName_Bar__Test`, which is invalid.
So clearly `TestSuiteName` and `TestName` cannot start or end with `_`
(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't
followed by an upper-case letter. But that's getting complicated. So for
simplicity we just say that it cannot start with `_`.).
It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the
middle. However, consider this:
```c++
TEST(Time, Flies_Like_An_Arrow) { ... }
TEST(Time_Flies, Like_An_Arrow) { ... }
```
Now, the two `TEST`s will both generate the same class
(`Time_Flies_Like_An_Arrow_Test`). That's not good.
So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and
`TestName`. The rule is more constraining than necessary, but it's simple and
easy to remember. It also gives googletest some wiggle room in case its
implementation needs to change in the future.
If you violate the rule, there may not be immediate consequences, but your test
may (just may) break with a new compiler (or a new version of the compiler you
are using) or with a new version of googletest. Therefore it's best to follow
the rule.
## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
First of all you can use `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr,
ptr)`. This is the preferred syntax in the style guide because nullptr does not
have the type problems that NULL does. Which is why NULL does not work.
Due to some peculiarity of C++, it requires some non-trivial template meta
programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
and `ASSERT_XX()` macros. Therefore we only do it where it's most needed
(otherwise we make the implementation of googletest harder to maintain and more
error-prone than necessary).
The `EXPECT_EQ()` macro takes the *expected* value as its first argument and the
*actual* value as the second. It's reasonable that someone wants to write
`EXPECT_EQ(NULL, some_expression)`, and this indeed was requested several times.
Therefore we implemented it.
The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion
fails, you already know that `ptr` must be `NULL`, so it doesn't add any
information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)`
works just as well.
If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to
support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a
convention on the order of the two arguments for `EXPECT_NE`. This means using
the template meta programming tricks twice in the implementation, making it even
harder to understand and maintain. We believe the benefit doesn't justify the
cost.
Finally, with the growth of the gMock matcher library, we are encouraging people
to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One
significant advantage of the matcher approach is that matchers can be easily
combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be
easily combined. Therefore we want to invest more in the matchers than in the
`EXPECT_XX()` macros.
## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests?
For testing various implementations of the same interface, either typed tests or
value-parameterized tests can get it done. It's really up to you the user to
decide which is more convenient for you, depending on your particular case. Some
rough guidelines:
* Typed tests can be easier to write if instances of the different
implementations can be created the same way, modulo the type. For example,
if all these implementations have a public default constructor (such that
you can write `new TypeParam`), or if their factory functions have the same
form (e.g. `CreateInstance<TypeParam>()`).
* Value-parameterized tests can be easier to write if you need different code
patterns to create different implementations' instances, e.g. `new Foo` vs
`new Bar(5)`. To accommodate for the differences, you can write factory
function wrappers and pass these function pointers to the tests as their
parameters.
* When a typed test fails, the default output includes the name of the type,
which can help you quickly identify which implementation is wrong.
Value-parameterized tests only show the number of the failed iteration by
default. You will need to define a function that returns the iteration name
and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more
useful output.
* When using typed tests, you need to make sure you are testing against the
interface type, not the concrete types (in other words, you want to make
sure `implicit_cast<MyInterface*>(my_concrete_impl)` works, not just that
`my_concrete_impl` works). It's less likely to make mistakes in this area
when using value-parameterized tests.
I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give
both approaches a try. Practice is a much better way to grasp the subtle
differences between the two tools. Once you have some concrete experience, you
can much more easily decide which one to use the next time.
## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
**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?
Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
expected crash won't kill the test program (i.e. the parent process). As a
result, any in-memory side effects they incur are observable in their respective
sub-processes, but not in the parent process. You can think of them as running
in a parallel universe, more or less.
In particular, if you use mocking and the death test statement invokes some mock
methods, the parent process will think the calls have never occurred. Therefore,
you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH`
macro.
## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
Actually, the bug is in `htonl()`.
According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to
use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as
a *macro*, which breaks this usage.
Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not*
standard C++. That hacky implementation has some ad hoc limitations. In
particular, it prevents you from writing `Foo<sizeof(htonl(x))>()`, where `Foo`
is a template that has an integral argument.
The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a
template argument, and thus doesn't compile in opt mode when `a` contains a call
to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as
the solution must work with different compilers on various platforms.
`htonl()` has some other problems as described in `//util/endian/endian.h`,
which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()`
does, only without its problems. We suggest you to use `ghtonl()` instead of
`htonl()`, both in your tests and production code.
`//util/endian/endian.h` also defines `ghtons()`, which solves similar problems
in `htons()`.
Don't forget to add `//util/endian` to the list of dependencies in the `BUILD`
file wherever `ghtonl()` and `ghtons()` are used. The library consists of a
single header file and will not bloat your binary.
## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong?
If your class has a static data member:
```c++
// foo.h
class Foo {
...
static const int kBar = 100;
};
```
You also need to define it *outside* of the class body in `foo.cc`:
```c++
const int Foo::kBar; // No initializer here.
```
Otherwise your code is **invalid C++**, and may break in unexpected ways. In
particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
generate an "undefined reference" linker error. The fact that "it used to work"
doesn't mean it's valid. It just means that you were lucky. :-)
## Can I derive a test fixture from another?
Yes.
Each test fixture has a corresponding and same named test suite. This means only
one test suite can use a particular fixture. Sometimes, however, multiple test
cases may want to use the same or slightly different fixtures. For example, you
may want to make sure that all of a GUI library's test suites don't leak
important system resources like fonts and brushes.
In googletest, you share a fixture among test suites by putting the shared logic
in a base test fixture, then deriving from that base a separate fixture for each
test suite that wants to use this common logic. You then use `TEST_F()` to write
tests using each derived fixture.
Typically, your code looks like this:
```c++
// Defines a base test fixture.
class BaseTest : public ::testing::Test {
protected:
...
};
// Derives a fixture FooTest from BaseTest.
class FooTest : public BaseTest {
protected:
void SetUp() override {
BaseTest::SetUp(); // Sets up the base fixture first.
... additional set-up work ...
}
void TearDown() override {
... clean-up work for FooTest ...
BaseTest::TearDown(); // Remember to tear down the base fixture
// after cleaning up FooTest!
}
... functions and variables for FooTest ...
};
// Tests that use the fixture FooTest.
TEST_F(FooTest, Bar) { ... }
TEST_F(FooTest, Baz) { ... }
... additional fixtures derived from BaseTest ...
```
If necessary, you can continue to derive test fixtures from a derived fixture.
googletest has no limit on how deep the hierarchy can be.
For a complete example using derived test fixtures, see
[sample5_unittest.cc](../samples/sample5_unittest.cc).
## My compiler complains "void value not ignored as it ought to be." What does this mean?
You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
`ASSERT_*()` can only be used in `void` functions, due to exceptions being
disabled by our build system. Please see more details
[here](advanced.md#assertion-placement).
## My death test hangs (or seg-faults). How do I fix it?
In googletest, death tests are run in a child process and the way they work is
delicate. To write death tests you really need to understand how they work.
Please make sure you have read [this](advanced.md#how-it-works).
In particular, death tests don't like having multiple threads in the parent
process. So the first thing you can try is to eliminate creating threads outside
of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects
instead of real ones in your tests.
Sometimes this is impossible as some library you must use may be creating
threads before `main()` is even reached. In this case, you can try to minimize
the chance of conflicts by either moving as many activities as possible inside
`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
leaving as few things as possible in it. Also, you can try to set the death test
style to `"threadsafe"`, which is safer but slower, and see if it helps.
If you go with thread-safe death tests, remember that they rerun the test
program from the beginning in the child process. Therefore make sure your
program can run side-by-side with itself and is deterministic.
In the end, this boils down to good concurrent programming. You have to make
sure that there is no race conditions or dead locks in your program. No silver
bullet - sorry!
## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
The first thing to remember is that googletest does **not** reuse the same test
fixture object across multiple tests. For each `TEST_F`, googletest will create
a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
call `TearDown()`, and then delete the test fixture object.
When you need to write per-test set-up and tear-down logic, you have the choice
between using the test fixture constructor/destructor or `SetUp()/TearDown()`.
The former is usually preferred, as it has the following benefits:
* By initializing a member variable in the constructor, we have the option to
make it `const`, which helps prevent accidental changes to its value and
makes the tests more obviously correct.
* In case we need to subclass the test fixture class, the subclass'
constructor is guaranteed to call the base class' constructor *first*, and
the subclass' destructor is guaranteed to call the base class' destructor
*afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of
forgetting to call the base class' `SetUp()/TearDown()` or call them at the
wrong time.
You may still want to use `SetUp()/TearDown()` in the following cases:
* C++ does not allow virtual function calls in constructors and destructors.
You can call a method declared as virtual, but it will not use dynamic
dispatch, it will use the definition from the class the constructor of which
is currently executing. This is because calling a virtual method before the
derived class constructor has a chance to run is very dangerous - the
virtual method might operate on uninitialized data. Therefore, if you need
to call a method that will be overridden in a derived class, you have to use
`SetUp()/TearDown()`.
* In the body of a constructor (or destructor), it's not possible to use the
`ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal
test failure that should prevent the test from running, it's necessary to
use `abort` <!-- GOOGLETEST_CM0015 DO NOT DELETE --> and abort the whole test executable,
or to use `SetUp()` instead of a constructor.
* If the tear-down operation could throw an exception, you must use
`TearDown()` as opposed to the destructor, as throwing in a destructor leads
to undefined behavior and usually will kill your program right away. Note
that many standard libraries (like STL) may throw when exceptions are
enabled in the compiler. Therefore you should prefer `TearDown()` if you
want to write portable tests that work with or without exceptions.
* The googletest team is considering making the assertion macros throw on
platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
client-side), which will eliminate the need for the user to propagate
failures from a subroutine to its caller. Therefore, you shouldn't use
googletest assertions in a destructor if your code could run on such a
platform.
## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is
overloaded or a template, the compiler will have trouble figuring out which
overloaded version it should use. `ASSERT_PRED_FORMAT*` and
`EXPECT_PRED_FORMAT*` don't have this problem.
If you see this error, you might want to switch to
`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure
message. If, however, that is not an option, you can resolve the problem by
explicitly telling the compiler which version to pick.
For example, suppose you have
```c++
bool IsPositive(int n) {
return n > 0;
}
bool IsPositive(double x) {
return x > 0;
}
```
you will get a compiler error if you write
```c++
EXPECT_PRED1(IsPositive, 5);
```
However, this will work:
```c++
EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
```
(The stuff inside the angled brackets for the `static_cast` operator is the type
of the function pointer for the `int`-version of `IsPositive()`.)
As another example, when you have a template function
```c++
template <typename T>
bool IsNegative(T x) {
return x < 0;
}
```
you can use it in a predicate assertion like this:
```c++
ASSERT_PRED1(IsNegative<int>, -5);
```
Things are more interesting if your template has more than one parameters. The
following won't compile:
```c++
ASSERT_PRED2(GreaterThan<int, int>, 5, 0);
```
as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which
is one more than expected. The workaround is to wrap the predicate function in
parentheses:
```c++
ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
```
## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why?
Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
instead of
```c++
return RUN_ALL_TESTS();
```
they write
```c++
RUN_ALL_TESTS();
```
This is **wrong and dangerous**. The testing services needs to see the return
value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
`main()` function ignores it, your test will be considered successful even if it
has a googletest assertion failure. Very bad.
We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
`gcc`. If you do so, you'll get a compiler error.
If you see the compiler complaining about you ignoring the return value of
`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the
return value of `main()`.
But how could we introduce a change that breaks existing tests? Well, in this
case, the code was already broken in the first place, so we didn't break it. :-)
## My compiler complains that a constructor (or destructor) cannot return a value. What's going on?
Due to a peculiarity of C++, in order to support the syntax for streaming
messages to an `ASSERT_*`, e.g.
```c++
ASSERT_EQ(1, Foo()) << "blah blah" << foo;
```
we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
content of your constructor/destructor to a private void member function, or
switch to `EXPECT_*()` if that works. This
[section](advanced.md#assertion-placement) in the user's guide explains it.
## My SetUp() function is not called. Why?
C++ is case-sensitive. Did you spell it as `Setup()`?
Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and
wonder why it's never called.
## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious.
You don't have to. Instead of
```c++
class FooTest : public BaseTest {};
TEST_F(FooTest, Abc) { ... }
TEST_F(FooTest, Def) { ... }
class BarTest : public BaseTest {};
TEST_F(BarTest, Abc) { ... }
TEST_F(BarTest, Def) { ... }
```
you can simply `typedef` the test fixtures:
```c++
typedef BaseTest FooTest;
TEST_F(FooTest, Abc) { ... }
TEST_F(FooTest, Def) { ... }
typedef BaseTest BarTest;
TEST_F(BarTest, Abc) { ... }
TEST_F(BarTest, Def) { ... }
```
## googletest output is buried in a whole bunch of LOG messages. What do I do?
The googletest output is meant to be a concise and human-friendly report. If
your test generates textual output itself, it will mix with the googletest
output, making it hard to read. However, there is an easy solution to this
problem.
Since `LOG` messages go to stderr, we decided to let googletest output go to
stdout. This way, you can easily separate the two using redirection. For
example:
```shell
$ ./my_test > gtest_output.txt
```
## Why should I prefer test fixtures over global variables?
There are several good reasons:
1. It's likely your test needs to change the states of its global variables.
This makes it difficult to keep side effects from escaping one test and
contaminating others, making debugging difficult. By using fixtures, each
test has a fresh set of variables that's different (but with the same
names). Thus, tests are kept independent of each other.
2. Global variables pollute the global namespace.
3. Test fixtures can be reused via subclassing, which cannot be done easily
with global variables. This is useful if many test suites have something in
common.
## What can the statement argument in ASSERT_DEATH() be?
`ASSERT_DEATH(*statement*, *regex*)` (or any death assertion macro) can be used
wherever `*statement*` is valid. So basically `*statement*` can be any C++
statement that makes sense in the current context. In particular, it can
reference global and/or local variables, and can be:
* a simple function call (often the case),
* a complex expression, or
* a compound statement.
Some examples are shown here:
```c++
// A death test can be a simple function call.
TEST(MyDeathTest, FunctionCall) {
ASSERT_DEATH(Xyz(5), "Xyz failed");
}
// Or a complex expression that references variables and functions.
TEST(MyDeathTest, ComplexExpression) {
const bool c = Condition();
ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
"(Func1|Method) failed");
}
// Death assertions can be used any where in a function. In
// particular, they can be inside a loop.
TEST(MyDeathTest, InsideLoop) {
// Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
for (int i = 0; i < 5; i++) {
EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
::testing::Message() << "where i is " << i);
}
}
// A death assertion can contain a compound statement.
TEST(MyDeathTest, CompoundStatement) {
// Verifies that at lease one of Bar(0), Bar(1), ..., and
// Bar(4) dies.
ASSERT_DEATH({
for (int i = 0; i < 5; i++) {
Bar(i);
}
},
"Bar has \\d+ errors");
}
```
gtest-death-test_test.cc contains more examples if you are interested.
## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
Googletest needs to be able to create objects of your test fixture class, so it
must have a default constructor. Normally the compiler will define one for you.
However, there are cases where you have to define your own:
* If you explicitly declare a non-default constructor for class `FooTest`
(`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a
default constructor, even if it would be empty.
* If `FooTest` has a const non-static data member, then you have to define the
default constructor *and* initialize the const member in the initializer
list of the constructor. (Early versions of `gcc` doesn't force you to
initialize the const member. It's a bug that has been fixed in `gcc 4`.)
## Why does ASSERT_DEATH complain about previous threads that were already joined?
With the Linux pthread library, there is no turning back once you cross the line
from single thread to multiple threads. The first time you create a thread, a
manager thread is created in addition, so you get 3, not 2, threads. Later when
the thread you create joins the main thread, the thread count decrements by 1,
but the manager thread will never be killed, so you still have 2 threads, which
means you cannot safely run a death test.
The new NPTL thread library doesn't suffer from this problem, as it doesn't
create a manager thread. However, if you don't control which machine your test
runs on, you shouldn't depend on this.
## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
googletest does not interleave tests from different test suites. That is, it
runs all tests in one test suite first, and then runs all tests in the next test
suite, and so on. googletest does this because it needs to set up a test suite
before the first test in it is run, and tear it down afterwords. Splitting up
the test case would require multiple set-up and tear-down processes, which is
inefficient and makes the semantics unclean.
If we were to determine the order of tests based on test name instead of test
case name, then we would have a problem with the following situation:
```c++
TEST_F(FooTest, AbcDeathTest) { ... }
TEST_F(FooTest, Uvw) { ... }
TEST_F(BarTest, DefDeathTest) { ... }
TEST_F(BarTest, Xyz) { ... }
```
Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
interleave tests from different test suites, we need to run all tests in the
`FooTest` case before running any test in the `BarTest` case. This contradicts
with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do?
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
related:
```c++
class FooTest : public ::testing::Test { ... };
TEST_F(FooTest, Abc) { ... }
TEST_F(FooTest, Def) { ... }
using FooDeathTest = FooTest;
TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
```
## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
makes it harder to search for real problems in the parent's log. Therefore,
googletest only prints them when the death test has failed.
If you really need to see such LOG messages, a workaround is to temporarily
break the death test (e.g. by changing the regex pattern it is expected to
match). Admittedly, this is a hack. We'll consider a more permanent solution
after the fork-and-exec-style death tests are implemented.
## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives?
If you use a user-defined type `FooType` in an assertion, you must make sure
there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
defined such that we can print a value of `FooType`.
In addition, if `FooType` is declared in a name space, the `<<` operator also
needs to be defined in the *same* name space. See https://abseil.io/tips/49 for details.
## How do I suppress the memory leak messages on Windows?
Since the statically initialized googletest singleton requires allocations on
the heap, the Visual C++ memory leak detector will report memory leaks at the
end of the program run. The easiest way to avoid this is to use the
`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
statically initialized heap objects. See MSDN for more details and additional
heap check/debug routines.
## How can my code detect if it is running in a test?
If you write code that sniffs whether it's running in a test and does different
things accordingly, you are leaking test-only logic into production code and
there is no easy way to ensure that the test-only code paths aren't run by
mistake in production. Such cleverness also leads to
[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
advise against the practice, and googletest doesn't provide a way to do it.
In general, the recommended way to cause the code to behave differently under
test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject
different functionality from the test and from the production code. Since your
production code doesn't link in the for-test logic at all (the
[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
that), there is no danger in accidentally running it.
However, if you *really*, *really*, *really* have no choice, and if you follow
the rule of ending your test program names with `_test`, you can use the
*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know
whether the code is under test.
## How do I temporarily disable a test?
If you have a broken test that you cannot fix right away, you can add the
DISABLED_ prefix to its name. This will exclude it from execution. This is
better than commenting out the code or using #if 0, as disabled tests are still
compiled (and thus won't rot).
To include disabled tests in test execution, just invoke the test program with
the --gtest_also_run_disabled_tests flag.
## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?
Yes.
The rule is **all test methods in the same test suite must use the same fixture
class.** This means that the following is **allowed** because both tests use the
same fixture class (`::testing::Test`).
```c++
namespace foo {
TEST(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace foo
namespace bar {
TEST(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace bar
```
However, the following code is **not allowed** and will produce a runtime error
from googletest because the test methods are using different test fixture
classes with the same test suite name.
```c++
namespace foo {
class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest
TEST_F(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace foo
namespace bar {
class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest
TEST_F(CoolTest, DoSomething) {
SUCCEED();
}
} // namespace bar
```

@ -1,141 +0,0 @@
## Using GoogleTest from various build systems
GoogleTest comes with pkg-config files that can be used to determine all
necessary flags for compiling and linking to GoogleTest (and GoogleMock).
Pkg-config is a standardised plain-text format containing
* the includedir (-I) path
* necessary macro (-D) definitions
* further required flags (-pthread)
* the library (-L) path
* the library (-l) to link to
All current build systems support pkg-config in one way or another. For all
examples here we assume you want to compile the sample
`samples/sample3_unittest.cc`.
### CMake
Using `pkg-config` in CMake is fairly easy:
```cmake
cmake_minimum_required(VERSION 3.0)
cmake_policy(SET CMP0048 NEW)
project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX)
find_package(PkgConfig)
pkg_search_module(GTEST REQUIRED gtest_main)
add_executable(testapp samples/sample3_unittest.cc)
target_link_libraries(testapp ${GTEST_LDFLAGS})
target_compile_options(testapp PUBLIC ${GTEST_CFLAGS})
include(CTest)
add_test(first_and_only_test testapp)
```
It is generally recommended that you use `target_compile_options` + `_CFLAGS`
over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not
just -I flags (GoogleTest might require a macro indicating to internal headers
that all libraries have been compiled with threading enabled. In addition,
GoogleTest might also require `-pthread` in the compiling step, and as such
splitting the pkg-config `Cflags` variable into include dirs and macros for
`target_compile_definitions()` might still miss this). The same recommendation
goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens
to discard `-L` flags and `-pthread`.
### Autotools
Finding GoogleTest in Autoconf and using it from Automake is also fairly easy:
In your `configure.ac`:
```
AC_PREREQ([2.69])
AC_INIT([my_gtest_pkgconfig], [0.0.1])
AC_CONFIG_SRCDIR([samples/sample3_unittest.cc])
AC_PROG_CXX
PKG_CHECK_MODULES([GTEST], [gtest_main])
AM_INIT_AUTOMAKE([foreign subdir-objects])
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
```
and in your `Makefile.am`:
```
check_PROGRAMS = testapp
TESTS = $(check_PROGRAMS)
testapp_SOURCES = samples/sample3_unittest.cc
testapp_CXXFLAGS = $(GTEST_CFLAGS)
testapp_LDADD = $(GTEST_LIBS)
```
### Meson
Meson natively uses pkgconfig to query dependencies:
```
project('my_gtest_pkgconfig', 'cpp', version : '0.0.1')
gtest_dep = dependency('gtest_main')
testapp = executable(
'testapp',
files(['samples/sample3_unittest.cc']),
dependencies : gtest_dep,
install : false)
test('first_and_only_test', testapp)
```
### Plain Makefiles
Since `pkg-config` is a small Unix command-line utility, it can be used in
handwritten `Makefile`s too:
```makefile
GTEST_CFLAGS = `pkg-config --cflags gtest_main`
GTEST_LIBS = `pkg-config --libs gtest_main`
.PHONY: tests all
tests: all
./testapp
all: testapp
testapp: testapp.o
$(CXX) $(CXXFLAGS) $(LDFLAGS) $< -o $@ $(GTEST_LIBS)
testapp.o: samples/sample3_unittest.cc
$(CXX) $(CPPFLAGS) $(CXXFLAGS) $< -c -o $@ $(GTEST_CFLAGS)
```
### Help! pkg-config can't find GoogleTest!
Let's say you have a `CMakeLists.txt` along the lines of the one in this
tutorial and you try to run `cmake`. It is very possible that you get a failure
along the lines of:
```
-- Checking for one of the modules 'gtest_main'
CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message):
None of the required 'gtest_main' found
```
These failures are common if you installed GoogleTest yourself and have not
sourced it from a distro or other package manager. If so, you need to tell
pkg-config where it can find the `.pc` files containing the information. Say you
installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are
installed under `/usr/local/lib64/pkgconfig`. If you set
```
export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig
```
pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`.

@ -1,567 +0,0 @@
# Googletest Primer
## Introduction: Why googletest?
*googletest* helps you write better C++ tests.
googletest is a testing framework developed by the Testing Technology team with
Google's specific requirements and constraints in mind. Whether you work on
Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it
supports *any* kind of tests, not just unit tests.
So what makes a good test, and how does googletest fit in? We believe:
1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
that succeeds or fails as a result of other tests. googletest isolates the
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.
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
and subroutines. This common pattern is easy to recognize and makes tests
easy to maintain. Such consistency is especially helpful when people switch
projects and start to work on a new code base.
3. Tests should be *portable* and *reusable*. Google has a lot of code that is
platform-neutral; its tests should also be platform-neutral. googletest
works on different OSes, with different compilers, with or without
exceptions, so googletest tests can work with a variety of configurations.
4. When tests fail, they should provide as much *information* about the problem
as possible. googletest doesn't stop at the first test failure. Instead, it
only stops the current test and continues with the next. You can also set up
tests that report non-fatal failures after which the current test continues.
Thus, you can detect and fix multiple bugs in a single run-edit-compile
cycle.
5. The testing framework should liberate test writers from housekeeping chores
and let them focus on the test *content*. googletest automatically keeps
track of all tests defined, and doesn't require the user to enumerate them
in order to run them.
6. Tests should be *fast*. With googletest, you can reuse shared resources
across tests and pay for the set-up/tear-down only once, without making
tests depend on each other.
Since googletest is based on the popular xUnit architecture, you'll feel right
at home if you've used JUnit or PyUnit before. If not, it will take you about 10
minutes to learn the basics and get started. So let's go!
## Beware of the nomenclature
_Note:_ There might be some confusion arising from different definitions of the
terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
Historically, googletest started to use the term _Test Case_ for grouping
related tests, whereas current publications, including International Software
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
various textbooks on software quality, use the term
_[Test Suite][istqb test suite]_ for this.
The related term _Test_, as it is used in googletest, corresponds to the term
_[Test Case][istqb test case]_ of ISTQB and others.
The term _Test_ is commonly of broad enough sense, including ISTQB's definition
of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as
was used in Google Test is of contradictory sense and thus confusing.
googletest recently started replacing the term _Test Case_ with _Test Suite_.
The preferred API is *TestSuite*. The older TestCase API is being slowly
deprecated and refactored away.
So please be aware of the different definitions of the terms:
<!-- mdformat off(github rendering does not support multiline tables) -->
Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
:----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
<!-- mdformat on -->
[istqb test case]: http://glossary.istqb.org/en/search/test%20case
[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite
## Basic Concepts
When using googletest, you start by writing *assertions*, which are statements
that check whether a condition is true. An assertion's result can be *success*,
*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
current function; otherwise the program continues normally.
*Tests* use assertions to verify the tested code's behavior. If a test crashes
or has a failed assertion, then it *fails*; otherwise it *succeeds*.
A *test suite* contains one or many tests. You should group your tests into test
suites that reflect the structure of the tested code. When multiple tests in a
test suite need to share common objects and subroutines, you can put them into a
*test fixture* class.
A *test program* can contain multiple test suites.
We'll now explain how to write a test program, starting at the individual
assertion level and building up to tests and test suites.
## Assertions
googletest assertions are macros that resemble function calls. You test a class
or function by making assertions about its behavior. When an assertion fails,
googletest prints the assertion's source file and line number location, along
with a failure message. You may also supply a custom failure message which will
be appended to googletest's message.
The assertions come in pairs that test the same thing but have different effects
on the current function. `ASSERT_*` versions generate fatal failures when they
fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal
failures, which don't abort the current function. Usually `EXPECT_*` are
preferred, as they allow more than one failure to be reported in a test.
However, you should use `ASSERT_*` if it doesn't make sense to continue when the
assertion in question fails.
Since a failed `ASSERT_*` returns from the current function immediately,
possibly skipping clean-up code that comes after it, it may cause a space leak.
Depending on the nature of the leak, it may or may not be worth fixing - so keep
this in mind if you get a heap checker error in addition to assertion errors.
To provide a custom failure message, simply stream it into the macro using the
`<<` operator or a sequence of such operators. An example:
```c++
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
for (int i = 0; i < x.size(); ++i) {
EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
}
```
Anything that can be streamed to an `ostream` can be streamed to an assertion
macro--in particular, C strings and `string` objects. If a wide string
(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
streamed to an assertion, it will be translated to UTF-8 when printed.
### Basic Assertions
These assertions do basic true/false condition testing.
Fatal assertion | Nonfatal assertion | Verifies
-------------------------- | -------------------------- | --------------------
`ASSERT_TRUE(condition);` | `EXPECT_TRUE(condition);` | `condition` is true
`ASSERT_FALSE(condition);` | `EXPECT_FALSE(condition);` | `condition` is false
Remember, when they fail, `ASSERT_*` yields a fatal failure and returns from the
current function, while `EXPECT_*` yields a nonfatal failure, allowing the
function to continue running. In either case, an assertion failure means its
containing test fails.
**Availability**: Linux, Windows, Mac.
### Binary Comparison
This section describes assertions that compare two values.
Fatal assertion | Nonfatal assertion | Verifies
------------------------ | ------------------------ | --------------
`ASSERT_EQ(val1, val2);` | `EXPECT_EQ(val1, val2);` | `val1 == val2`
`ASSERT_NE(val1, val2);` | `EXPECT_NE(val1, val2);` | `val1 != val2`
`ASSERT_LT(val1, val2);` | `EXPECT_LT(val1, val2);` | `val1 < val2`
`ASSERT_LE(val1, val2);` | `EXPECT_LE(val1, val2);` | `val1 <= val2`
`ASSERT_GT(val1, val2);` | `EXPECT_GT(val1, val2);` | `val1 > val2`
`ASSERT_GE(val1, val2);` | `EXPECT_GE(val1, val2);` | `val1 >= val2`
Value arguments must be comparable by the assertion's comparison operator or
you'll get a compiler error. We used to require the arguments to support the
`<<` operator for streaming to an `ostream`, but this is no longer necessary. If
`<<` is supported, it will be called to print the arguments when the assertion
fails; otherwise googletest will attempt to print them in the best way it can.
For more details and how to customize the printing of the arguments, see the
[documentation](../../googlemock/docs/cook_book.md#teaching-gmock-how-to-print-your-values).
These assertions can work with a user-defined type, but only if you define the
corresponding comparison operator (e.g., `==` or `<`). Since this is discouraged
by the Google
[C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading),
you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of
two objects of a user-defined type.
However, when possible, `ASSERT_EQ(actual, expected)` is preferred to
`ASSERT_TRUE(actual == expected)`, since it tells you `actual` and `expected`'s
values on failure.
Arguments are always evaluated exactly once. Therefore, it's OK for the
arguments to have side effects. However, as with any ordinary C/C++ function,
the arguments' evaluation order is undefined (i.e., the compiler is free to
choose any order), and your code should not depend on any particular argument
evaluation order.
`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it
tests if they are in the same memory location, not if they have the same value.
Therefore, if you want to compare C strings (e.g. `const char*`) by value, use
`ASSERT_STREQ()`, which will be described later on. In particular, to assert
that a C string is `NULL`, use `ASSERT_STREQ(c_string, NULL)`. Consider using
`ASSERT_EQ(c_string, nullptr)` if c++11 is supported. To compare two `string`
objects, you should use `ASSERT_EQ`.
When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)`
instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is
typed, while `NULL` is not. See the [FAQ](faq.md) for more details.
If you're working with floating point numbers, you may want to use the floating
point variations of some of these macros in order to avoid problems caused by
rounding. See [Advanced googletest Topics](advanced.md) for details.
Macros in this section work with both narrow and wide string objects (`string`
and `wstring`).
**Availability**: Linux, Windows, Mac.
**Historical note**: Before February 2016 `*_EQ` had a convention of calling it
as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now
`*_EQ` treats both parameters in the same way.
### String Comparison
The assertions in this group compare two **C strings**. If you want to compare
two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
<!-- mdformat off(github rendering does not support multiline tables) -->
| Fatal assertion | Nonfatal assertion | Verifies |
| -------------------------- | ------------------------------ | -------------------------------------------------------- |
| `ASSERT_STREQ(str1,str2);` | `EXPECT_STREQ(str1,str2);` | the two C strings have the same content |
| `ASSERT_STRNE(str1,str2);` | `EXPECT_STRNE(str1,str2);` | the two C strings have different contents |
| `ASSERT_STRCASEEQ(str1,str2);` | `EXPECT_STRCASEEQ(str1,str2);` | the two C strings have the same content, ignoring case |
| `ASSERT_STRCASENE(str1,str2);` | `EXPECT_STRCASENE(str1,str2);` | the two C strings have different contents, ignoring case |
<!-- mdformat on-->
Note that "CASE" in an assertion name means that case is ignored. A `NULL`
pointer and an empty string are considered *different*.
`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a comparison
of two wide strings fails, their values will be printed as UTF-8 narrow strings.
**Availability**: Linux, Windows, Mac.
**See also**: For more string comparison tricks (substring, prefix, suffix, and
regular expression matching, for example), see [this](advanced.md) in the
Advanced googletest Guide.
## Simple Tests
To create a test:
1. Use the `TEST()` macro to define and name a test function. These are
ordinary C++ functions that don't return a value.
2. In this function, along with any valid C++ statements you want to include,
use the various googletest assertions to check values.
3. The test's result is determined by the assertions; if any assertion in the
test fails (either fatally or non-fatally), or if the test crashes, the
entire test fails. Otherwise, it succeeds.
```c++
TEST(TestSuiteName, TestName) {
... test body ...
}
```
`TEST()` arguments go from general to specific. The *first* argument is the name
of the test suite, and the *second* argument is the test's name within the test
case. Both names must be valid C++ identifiers, and they should not contain
any underscores (`_`). A test's *full name* consists of its containing test suite and
its individual name. Tests from different test suites can have the same
individual name.
For example, let's take a simple integer function:
```c++
int Factorial(int n); // Returns the factorial of n
```
A test suite for this function might look like:
```c++
// Tests factorial of 0.
TEST(FactorialTest, HandlesZeroInput) {
EXPECT_EQ(Factorial(0), 1);
}
// Tests factorial of positive numbers.
TEST(FactorialTest, HandlesPositiveInput) {
EXPECT_EQ(Factorial(1), 1);
EXPECT_EQ(Factorial(2), 2);
EXPECT_EQ(Factorial(3), 6);
EXPECT_EQ(Factorial(8), 40320);
}
```
googletest groups the test results by test suites, so logically related tests
should be in the same test suite; in other words, the first argument to their
`TEST()` should be the same. In the above example, we have two tests,
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
suite `FactorialTest`.
When naming your test suites and tests, you should follow the same convention as
for
[naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names).
**Availability**: Linux, Windows, Mac.
## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests}
If you find yourself writing two or more tests that operate on similar data, you
can use a *test fixture*. This allows you to reuse the same configuration of
objects for several different tests.
To create a fixture:
1. Derive a class from `::testing::Test` . Start its body with `protected:`, as
we'll want to access fixture members from sub-classes.
2. Inside the class, declare any objects you plan to use.
3. If necessary, write a default constructor or `SetUp()` function to prepare
the objects for each test. A common mistake is to spell `SetUp()` as
**`Setup()`** with a small `u` - Use `override` in C++11 to make sure you
spelled it correctly.
4. If necessary, write a destructor or `TearDown()` function to release any
resources you allocated in `SetUp()` . To learn when you should use the
constructor/destructor and when you should use `SetUp()/TearDown()`, read
the [FAQ](faq.md#CtorVsSetUp).
5. If needed, define subroutines for your tests to share.
When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
access objects and subroutines in the test fixture:
```c++
TEST_F(TestFixtureName, TestName) {
... test body ...
}
```
Like `TEST()`, the first argument is the test suite name, but for `TEST_F()`
this must be the name of the test fixture class. You've probably guessed: `_F`
is for fixture.
Unfortunately, the C++ macro system does not allow us to create a single macro
that can handle both types of tests. Using the wrong macro causes a compiler
error.
Also, you must first define a test fixture class before using it in a
`TEST_F()`, or you'll get the compiler error "`virtual outside class
declaration`".
For each test defined with `TEST_F()`, googletest will create a *fresh* test
fixture at runtime, immediately initialize it via `SetUp()`, run the test,
clean up by calling `TearDown()`, and then delete the test fixture. Note that
different tests in the same test suite have different test fixture objects, and
googletest always deletes a test fixture before it creates the next one.
googletest does **not** reuse the same test fixture for multiple tests. Any
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
the following interface:
```c++
template <typename E> // E is the element type.
class Queue {
public:
Queue();
void Enqueue(const E& element);
E* Dequeue(); // Returns NULL if the queue is empty.
size_t size() const;
...
};
```
First, define a fixture class. By convention, you should give it the name
`FooTest` where `Foo` is the class being tested.
```c++
class QueueTest : public ::testing::Test {
protected:
void SetUp() override {
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
}
// void TearDown() override {}
Queue<int> q0_;
Queue<int> q1_;
Queue<int> q2_;
};
```
In this case, `TearDown()` is not needed since we don't have to clean up after
each test, other than what's already done by the destructor.
Now we'll write tests using `TEST_F()` and this fixture.
```c++
TEST_F(QueueTest, IsEmptyInitially) {
EXPECT_EQ(q0_.size(), 0);
}
TEST_F(QueueTest, DequeueWorks) {
int* n = q0_.Dequeue();
EXPECT_EQ(n, nullptr);
n = q1_.Dequeue();
ASSERT_NE(n, nullptr);
EXPECT_EQ(*n, 1);
EXPECT_EQ(q1_.size(), 0);
delete n;
n = q2_.Dequeue();
ASSERT_NE(n, nullptr);
EXPECT_EQ(*n, 2);
EXPECT_EQ(q2_.size(), 1);
delete n;
}
```
The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
to use `EXPECT_*` when you want the test to continue to reveal more errors after
the assertion failure, and use `ASSERT_*` when continuing after failure doesn't
make sense. For example, the second assertion in the `Dequeue` test is
`ASSERT_NE(nullptr, n)`, as we need to dereference the pointer `n` later, which
would lead to a segfault when `n` is `NULL`.
When these tests run, the following happens:
1. googletest constructs a `QueueTest` object (let's call it `t1`).
2. `t1.SetUp()` initializes `t1`.
3. The first test (`IsEmptyInitially`) runs on `t1`.
4. `t1.TearDown()` cleans up after the test finishes.
5. `t1` is destructed.
6. The above steps are repeated on another `QueueTest` object, this time
running the `DequeueWorks` test.
**Availability**: Linux, Windows, Mac.
## Invoking the Tests
`TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
unlike with many other C++ testing frameworks, you don't have to re-list all
your defined tests in order to run them.
After defining your tests, you can run them with `RUN_ALL_TESTS()`, which
returns `0` if all the tests are successful, or `1` otherwise. Note that
`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from
different test suites, or even different source files.
When invoked, the `RUN_ALL_TESTS()` macro:
* Saves the state of all googletest flags.
* Creates a test fixture object for the first test.
* Initializes it via `SetUp()`.
* Runs the test on the fixture object.
* Cleans up the fixture via `TearDown()`.
* Deletes the fixture.
* Restores the state of all googletest flags.
* Repeats the above steps for the next test, until all tests have run.
If a fatal failure happens the subsequent steps will be skipped.
> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or
> you will get a compiler error. The rationale for this design is that the
> automated testing service determines whether a test has passed based on its
> exit code, not on its stdout/stderr output; thus your `main()` function must
> return the value of `RUN_ALL_TESTS()`.
>
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
> once conflicts with some advanced googletest features (e.g., thread-safe
> [death tests](advanced.md#death-tests)) and thus is not supported.
**Availability**: Linux, Windows, Mac.
## Writing the main() Function
Write your own main() function, which should return the value of
`RUN_ALL_TESTS()`.
You can start from this boilerplate:
```c++
#include "this/package/foo.h"
#include "gtest/gtest.h"
namespace {
// The fixture for testing class Foo.
class FooTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
FooTest() {
// You can do set-up work for each test here.
}
~FooTest() override {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
void SetUp() override {
// Code here will be called immediately after the constructor (right
// before each test).
}
void TearDown() override {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test suite for Foo.
};
// Tests that the Foo::Bar() method does Abc.
TEST_F(FooTest, MethodBarDoesAbc) {
const std::string input_filepath = "this/package/testdata/myinputfile.dat";
const std::string output_filepath = "this/package/testdata/myoutputfile.dat";
Foo f;
EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0);
}
// Tests that Foo does Xyz.
TEST_F(FooTest, DoesXyz) {
// Exercises the Xyz feature of Foo.
}
} // namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
```
The `::testing::InitGoogleTest()` function parses the command line for
googletest flags, and removes all recognized flags. This allows the user to
control a test program's behavior via various flags, which we'll cover in
the [AdvancedGuide](advanced.md). You **must** call this function before calling
`RUN_ALL_TESTS()`, or the flags won't be properly initialized.
On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
in programs compiled in `UNICODE` mode as well.
But maybe you think that writing all those main() functions is too much work? We
agree with you completely, and that's why Google Test provides a basic
implementation of main(). If it fits your needs, then just link your test with
gtest\_main library and you are good to go.
NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
## Known Limitations
* Google Test is designed to be thread-safe. The implementation is thread-safe
on systems where the `pthreads` library is available. It is currently
_unsafe_ to use Google Test assertions from two threads concurrently on
other systems (e.g. Windows). In most tests this is not an issue as usually
the assertions are done in the main thread. If you want to help, you can
volunteer to implement the necessary synchronization primitives in
`gtest-port.h` for your platform.

@ -1,190 +0,0 @@
<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming.
# The Problem
Template and macro libraries often need to define many classes, functions, or
macros that vary only (or almost only) in the number of arguments they take.
It's a lot of repetitive, mechanical, and error-prone work.
Variadic templates and variadic macros can alleviate the problem. However, while
both are being considered by the C++ committee, neither is in the standard yet
or widely supported by compilers. Thus they are often not a good choice,
especially when your code needs to be portable. And their capabilities are still
limited.
As a result, authors of such libraries often have to write scripts to generate
their implementation. However, our experience is that it's tedious to write such
scripts, which tend to reflect the structure of the generated code poorly and
are often hard to read and edit. For example, a small change needed in the
generated code may require some non-intuitive, non-trivial changes in the
script. This is especially painful when experimenting with the code.
# Our Solution
Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta
Programming, or Practical Utility for Meta Programming, whichever you prefer) is
a simple meta-programming tool for C++. The idea is that a programmer writes a
`foo.pump` file which contains C++ code plus meta code that manipulates the C++
code. The meta code can handle iterations over a range, nested iterations, local
meta variable definitions, simple arithmetic, and conditional expressions. You
can view it as a small Domain-Specific Language. The meta language is designed
to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, for example) and
concise, making Pump code intuitive and easy to maintain.
## Highlights
* The implementation is in a single Python script and thus ultra portable: no
build or installation is needed and it works cross platforms.
* Pump tries to be smart with respect to
[Google's style guide](https://github.com/google/styleguide): it breaks long
lines (easy to have when they are generated) at acceptable places to fit
within 80 columns and indent the continuation lines correctly.
* The format is human-readable and more concise than XML.
* The format works relatively well with Emacs' C++ mode.
## Examples
The following Pump code (where meta keywords start with `$`, `[[` and `]]` are
meta brackets, and `$$` starts a meta comment that ends with the line):
```
$var n = 3 $$ Defines a meta variable n.
$range i 0..n $$ Declares the range of meta iterator i (inclusive).
$for i [[
$$ Meta loop.
// Foo$i does blah for $i-ary predicates.
$range j 1..i
template <size_t N $for j [[, typename A$j]]>
class Foo$i {
$if i == 0 [[
blah a;
]] $elif i <= 2 [[
blah b;
]] $else [[
blah c;
]]
};
]]
```
will be translated by the Pump compiler to:
```cpp
// Foo0 does blah for 0-ary predicates.
template <size_t N>
class Foo0 {
blah a;
};
// Foo1 does blah for 1-ary predicates.
template <size_t N, typename A1>
class Foo1 {
blah b;
};
// Foo2 does blah for 2-ary predicates.
template <size_t N, typename A1, typename A2>
class Foo2 {
blah b;
};
// Foo3 does blah for 3-ary predicates.
template <size_t N, typename A1, typename A2, typename A3>
class Foo3 {
blah c;
};
```
In another example,
```
$range i 1..n
Func($for i + [[a$i]]);
$$ The text between i and [[ is the separator between iterations.
```
will generate one of the following lines (without the comments), depending on
the value of `n`:
```cpp
Func(); // If n is 0.
Func(a1); // If n is 1.
Func(a1 + a2); // If n is 2.
Func(a1 + a2 + a3); // If n is 3.
// And so on...
```
## Constructs
We support the following meta programming constructs:
| `$var id = exp` | Defines a named constant value. `$id` is |
: : valid util the end of the current meta :
: : lexical block. :
| :------------------------------- | :--------------------------------------- |
| `$range id exp..exp` | Sets the range of an iteration variable, |
: : which can be reused in multiple loops :
: : later. :
| `$for id sep [[ code ]]` | Iteration. The range of `id` must have |
: : been defined earlier. `$id` is valid in :
: : `code`. :
| `$($)` | Generates a single `$` character. |
| `$id` | Value of the named constant or iteration |
: : variable. :
| `$(exp)` | Value of the expression. |
| `$if exp [[ code ]] else_branch` | Conditional. |
| `[[ code ]]` | Meta lexical block. |
| `cpp_code` | Raw C++ code. |
| `$$ comment` | Meta comment. |
**Note:** To give the user some freedom in formatting the Pump source code, Pump
ignores a new-line character if it's right after `$for foo` or next to `[[` or
`]]`. Without this rule you'll often be forced to write very long lines to get
the desired output. Therefore sometimes you may need to insert an extra new-line
in such places for a new-line to show up in your output.
## Grammar
```ebnf
code ::= atomic_code*
atomic_code ::= $var id = exp
| $var id = [[ code ]]
| $range id exp..exp
| $for id sep [[ code ]]
| $($)
| $id
| $(exp)
| $if exp [[ code ]] else_branch
| [[ code ]]
| cpp_code
sep ::= cpp_code | empty_string
else_branch ::= $else [[ code ]]
| $elif exp [[ code ]] else_branch
| empty_string
exp ::= simple_expression_in_Python_syntax
```
## Code
You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py).
It is still very unpolished and lacks automated tests, although it has been
successfully used many times. If you find a chance to use it in your project,
please let us know what you think! We also welcome help on improving Pump.
## Real Examples
You can find real-world applications of Pump in
[Google Test](https://github.com/google/googletest/tree/master/googletest) and
[Google Mock](https://github.com/google/googletest/tree/master/googlemock). The
source file `foo.h.pump` generates `foo.h`.
## Tips
* If a meta variable is followed by a letter or digit, you can separate them
using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper`
generate `Foo1Helper` when `j` is 1.
* To avoid extra-long Pump source lines, you can break a line anywhere you
want by inserting `[[]]` followed by a new line. Since any new-line
character next to `[[` or `]]` is ignored, the generated code won't contain
this new line.

@ -1,22 +0,0 @@
# Googletest Samples {#samples}
If you're like us, you'd like to look at
[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples)
The sample directory has a number of well-commented samples showing how to use a
variety of googletest features.
* Sample #1 shows the basic steps of using googletest to test C++ functions.
* Sample #2 shows a more complex unit test for a class with multiple member
functions.
* Sample #3 uses a test fixture.
* Sample #4 teaches you how to use googletest and `googletest.h` together to
get the best of both libraries.
* Sample #5 puts shared testing logic in a base test fixture, and reuses it in
derived fixtures.
* Sample #6 demonstrates type-parameterized tests.
* Sample #7 teaches the basics of value-parameterized tests.
* Sample #8 shows using `Combine()` in value-parameterized tests.
* Sample #9 shows use of the listener API to modify Google Test's console
output and the use of its reflection API to inspect test results.
* Sample #10 shows use of the listener API to implement a primitive memory
leak checker.

@ -35,8 +35,8 @@
// directly. // directly.
// GOOGLETEST_CM0001 DO NOT DELETE // GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
#include "gtest/internal/gtest-death-test-internal.h" #include "gtest/internal/gtest-death-test-internal.h"
@ -97,6 +97,10 @@ GTEST_API_ bool InDeathTestChild();
// //
// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
// //
// The final parameter to each of these macros is a matcher applied to any data
// the sub-process wrote to stderr. For compatibility with existing tests, a
// bare string is interpreted as a regular expression matcher.
//
// On the regular expressions used in death tests: // On the regular expressions used in death tests:
// //
// GOOGLETEST_CM0005 DO NOT DELETE // GOOGLETEST_CM0005 DO NOT DELETE
@ -162,27 +166,27 @@ GTEST_API_ bool InDeathTestChild();
// directory in PATH. // directory in PATH.
// //
// Asserts that a given statement causes the program to exit, with an // Asserts that a given `statement` causes the program to exit, with an
// integer exit status that satisfies predicate, and emitting error output // integer exit status that satisfies `predicate`, and emitting error output
// that matches regex. // that matches `matcher`.
# define ASSERT_EXIT(statement, predicate, regex) \ # define ASSERT_EXIT(statement, predicate, matcher) \
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)
// Like ASSERT_EXIT, but continues on to successive tests in the // Like `ASSERT_EXIT`, but continues on to successive tests in the
// test suite, if any: // test suite, if any:
# define EXPECT_EXIT(statement, predicate, regex) \ # define EXPECT_EXIT(statement, predicate, matcher) \
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)
// Asserts that a given statement causes the program to exit, either by // Asserts that a given `statement` causes the program to exit, either by
// explicitly exiting with a nonzero exit code or being killed by a // explicitly exiting with a nonzero exit code or being killed by a
// signal, and emitting error output that matches regex. // signal, and emitting error output that matches `matcher`.
# define ASSERT_DEATH(statement, regex) \ # define ASSERT_DEATH(statement, matcher) \
ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
// Like ASSERT_DEATH, but continues on to successive tests in the // Like `ASSERT_DEATH`, but continues on to successive tests in the
// test suite, if any: // test suite, if any:
# define EXPECT_DEATH(statement, regex) \ # define EXPECT_DEATH(statement, matcher) \
EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
@ -190,11 +194,10 @@ GTEST_API_ bool InDeathTestChild();
class GTEST_API_ ExitedWithCode { class GTEST_API_ ExitedWithCode {
public: public:
explicit ExitedWithCode(int exit_code); explicit ExitedWithCode(int exit_code);
ExitedWithCode(const ExitedWithCode&) = default;
void operator=(const ExitedWithCode& other) = delete;
bool operator()(int exit_status) const; bool operator()(int exit_status) const;
private: private:
// No implementation - assignment is unsupported.
void operator=(const ExitedWithCode& other);
const int exit_code_; const int exit_code_;
}; };
@ -340,4 +343,4 @@ class GTEST_API_ KilledBySignal {
} // namespace testing } // namespace testing
#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_

@ -32,13 +32,10 @@
// This file implements just enough of the matcher interface to allow // This file implements just enough of the matcher interface to allow
// EXPECT_DEATH and friends to accept a matcher argument. // EXPECT_DEATH and friends to accept a matcher argument.
// IWYU pragma: private, include "testing/base/public/gunit.h" #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
// IWYU pragma: friend third_party/googletest/googlemock/.* #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
// IWYU pragma: friend third_party/googletest/googletest/.*
#ifndef GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
#define GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
#include <atomic>
#include <memory> #include <memory>
#include <ostream> #include <ostream>
#include <string> #include <string>
@ -63,20 +60,16 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(
namespace testing { namespace testing {
// To implement a matcher Foo for type T, define: // To implement a matcher Foo for type T, define:
// 1. a class FooMatcherImpl that implements the // 1. a class FooMatcherMatcher that implements the matcher interface:
// MatcherInterface<T> interface, and // using is_gtest_matcher = void;
// 2. a factory function that creates a Matcher<T> object from a // bool MatchAndExplain(const T&, std::ostream*);
// FooMatcherImpl*. // (MatchResultListener* can also be used instead of std::ostream*)
// // void DescribeTo(std::ostream*);
// The two-level delegation design makes it possible to allow a user // void DescribeNegationTo(std::ostream*);
// to write "v" instead of "Eq(v)" where a Matcher is expected, which
// is impossible if we pass matchers by pointers. It also eases
// ownership management as Matcher objects can now be copied like
// plain values.
// MatchResultListener is an abstract class. Its << operator can be
// used by a matcher to explain why a value matches or doesn't match.
// //
// 2. a factory function that creates a Matcher<T> object from a
// FooMatcherMatcher.
class MatchResultListener { class MatchResultListener {
public: public:
// Creates a listener object with the given underlying ostream. The // Creates a listener object with the given underlying ostream. The
@ -113,7 +106,7 @@ inline MatchResultListener::~MatchResultListener() {
// An instance of a subclass of this knows how to describe itself as a // An instance of a subclass of this knows how to describe itself as a
// matcher. // matcher.
class MatcherDescriberInterface { class GTEST_API_ MatcherDescriberInterface {
public: public:
virtual ~MatcherDescriberInterface() {} virtual ~MatcherDescriberInterface() {}
@ -181,31 +174,6 @@ class MatcherInterface : public MatcherDescriberInterface {
namespace internal { namespace internal {
// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
template <typename T>
class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
public:
explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
: impl_(impl) {}
~MatcherInterfaceAdapter() override { delete impl_; }
void DescribeTo(::std::ostream* os) const override { impl_->DescribeTo(os); }
void DescribeNegationTo(::std::ostream* os) const override {
impl_->DescribeNegationTo(os);
}
bool MatchAndExplain(const T& x,
MatchResultListener* listener) const override {
return impl_->MatchAndExplain(x, listener);
}
private:
const MatcherInterface<T>* const impl_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
};
struct AnyEq { struct AnyEq {
template <typename A, typename B> template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a == b; } bool operator()(const A& a, const B& b) const { return a == b; }
@ -252,16 +220,35 @@ class StreamMatchResultListener : public MatchResultListener {
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener); GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
}; };
struct SharedPayloadBase {
std::atomic<int> ref{1};
void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
};
template <typename T>
struct SharedPayload : SharedPayloadBase {
explicit SharedPayload(const T& v) : value(v) {}
explicit SharedPayload(T&& v) : value(std::move(v)) {}
static void Destroy(SharedPayloadBase* shared) {
delete static_cast<SharedPayload*>(shared);
}
T value;
};
// An internal class for implementing Matcher<T>, which will derive // An internal class for implementing Matcher<T>, which will derive
// from it. We put functionalities common to all Matcher<T> // from it. We put functionalities common to all Matcher<T>
// specializations here to avoid code duplication. // specializations here to avoid code duplication.
template <typename T> template <typename T>
class MatcherBase { class MatcherBase : private MatcherDescriberInterface {
public: public:
// Returns true if and only if the matcher matches x; also explains the // Returns true if and only if the matcher matches x; also explains the
// match result to 'listener'. // match result to 'listener'.
bool MatchAndExplain(const T& x, MatchResultListener* listener) const { bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
return impl_->MatchAndExplain(x, listener); GTEST_CHECK_(vtable_ != nullptr);
return vtable_->match_and_explain(*this, x, listener);
} }
// Returns true if and only if this matcher matches x. // Returns true if and only if this matcher matches x.
@ -271,11 +258,15 @@ class MatcherBase {
} }
// Describes this matcher to an ostream. // Describes this matcher to an ostream.
void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } void DescribeTo(::std::ostream* os) const final {
GTEST_CHECK_(vtable_ != nullptr);
vtable_->describe(*this, os, false);
}
// Describes the negation of this matcher to an ostream. // Describes the negation of this matcher to an ostream.
void DescribeNegationTo(::std::ostream* os) const { void DescribeNegationTo(::std::ostream* os) const final {
impl_->DescribeNegationTo(os); GTEST_CHECK_(vtable_ != nullptr);
vtable_->describe(*this, os, true);
} }
// Explains why x matches, or doesn't match, the matcher. // Explains why x matches, or doesn't match, the matcher.
@ -288,31 +279,194 @@ class MatcherBase {
// of the describer, which is only guaranteed to be alive when // of the describer, which is only guaranteed to be alive when
// this matcher object is alive. // this matcher object is alive.
const MatcherDescriberInterface* GetDescriber() const { const MatcherDescriberInterface* GetDescriber() const {
return impl_.get(); if (vtable_ == nullptr) return nullptr;
return vtable_->get_describer(*this);
} }
protected: protected:
MatcherBase() {} MatcherBase() : vtable_(nullptr) {}
// Constructs a matcher from its implementation. // Constructs a matcher from its implementation.
explicit MatcherBase(const MatcherInterface<const T&>* impl) : impl_(impl) {}
template <typename U> template <typename U>
explicit MatcherBase( explicit MatcherBase(const MatcherInterface<U>* impl) {
const MatcherInterface<U>* impl, Init(impl);
typename std::enable_if<!std::is_same<U, const U&>::value>::type* = }
nullptr)
: impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {} template <typename M, typename = typename std::remove_reference<
M>::type::is_gtest_matcher>
MatcherBase(M&& m) { // NOLINT
Init(std::forward<M>(m));
}
MatcherBase(const MatcherBase& other)
: vtable_(other.vtable_), buffer_(other.buffer_) {
if (IsShared()) buffer_.shared->Ref();
}
MatcherBase& operator=(const MatcherBase& other) {
if (this == &other) return *this;
Destroy();
vtable_ = other.vtable_;
buffer_ = other.buffer_;
if (IsShared()) buffer_.shared->Ref();
return *this;
}
MatcherBase(const MatcherBase&) = default; MatcherBase(MatcherBase&& other)
MatcherBase& operator=(const MatcherBase&) = default; : vtable_(other.vtable_), buffer_(other.buffer_) {
MatcherBase(MatcherBase&&) = default; other.vtable_ = nullptr;
MatcherBase& operator=(MatcherBase&&) = default; }
MatcherBase& operator=(MatcherBase&& other) {
if (this == &other) return *this;
Destroy();
vtable_ = other.vtable_;
buffer_ = other.buffer_;
other.vtable_ = nullptr;
return *this;
}
virtual ~MatcherBase() {} ~MatcherBase() override { Destroy(); }
private: private:
std::shared_ptr<const MatcherInterface<const T&>> impl_; struct VTable {
bool (*match_and_explain)(const MatcherBase&, const T&,
MatchResultListener*);
void (*describe)(const MatcherBase&, std::ostream*, bool negation);
// Returns the captured object if it implements the interface, otherwise
// returns the MatcherBase itself.
const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
// Called on shared instances when the reference count reaches 0.
void (*shared_destroy)(SharedPayloadBase*);
};
bool IsShared() const {
return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
}
// If the implementation uses a listener, call that.
template <typename P>
static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
MatchResultListener* listener)
-> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
return P::Get(m).MatchAndExplain(value, listener->stream());
}
template <typename P>
static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
MatchResultListener* listener)
-> decltype(P::Get(m).MatchAndExplain(value, listener)) {
return P::Get(m).MatchAndExplain(value, listener);
}
template <typename P>
static void DescribeImpl(const MatcherBase& m, std::ostream* os,
bool negation) {
if (negation) {
P::Get(m).DescribeNegationTo(os);
} else {
P::Get(m).DescribeTo(os);
}
}
template <typename P>
static const MatcherDescriberInterface* GetDescriberImpl(
const MatcherBase& m) {
// If the impl is a MatcherDescriberInterface, then return it.
// Otherwise use MatcherBase itself.
// This allows us to implement the GetDescriber() function without support
// from the impl, but some users really want to get their impl back when
// they call GetDescriber().
// We use std::get on a tuple as a workaround of not having `if constexpr`.
return std::get<(
std::is_convertible<decltype(&P::Get(m)),
const MatcherDescriberInterface*>::value
? 1
: 0)>(std::make_tuple(&m, &P::Get(m)));
}
template <typename P>
const VTable* GetVTable() {
static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
&DescribeImpl<P>, &GetDescriberImpl<P>,
P::shared_destroy};
return &kVTable;
}
union Buffer {
// Add some types to give Buffer some common alignment/size use cases.
void* ptr;
double d;
int64_t i;
// And add one for the out-of-line cases.
SharedPayloadBase* shared;
};
void Destroy() {
if (IsShared() && buffer_.shared->Unref()) {
vtable_->shared_destroy(buffer_.shared);
}
}
template <typename M>
static constexpr bool IsInlined() {
return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
std::is_trivially_copy_constructible<M>::value &&
std::is_trivially_destructible<M>::value;
}
template <typename M, bool = MatcherBase::IsInlined<M>()>
struct ValuePolicy {
static const M& Get(const MatcherBase& m) {
// When inlined along with Init, need to be explicit to avoid violating
// strict aliasing rules.
const M *ptr = static_cast<const M*>(
static_cast<const void*>(&m.buffer_));
return *ptr;
}
static void Init(MatcherBase& m, M impl) {
::new (static_cast<void*>(&m.buffer_)) M(impl);
}
static constexpr auto shared_destroy = nullptr;
};
template <typename M>
struct ValuePolicy<M, false> {
using Shared = SharedPayload<M>;
static const M& Get(const MatcherBase& m) {
return static_cast<Shared*>(m.buffer_.shared)->value;
}
template <typename Arg>
static void Init(MatcherBase& m, Arg&& arg) {
m.buffer_.shared = new Shared(std::forward<Arg>(arg));
}
static constexpr auto shared_destroy = &Shared::Destroy;
};
template <typename U, bool B>
struct ValuePolicy<const MatcherInterface<U>*, B> {
using M = const MatcherInterface<U>;
using Shared = SharedPayload<std::unique_ptr<M>>;
static const M& Get(const MatcherBase& m) {
return *static_cast<Shared*>(m.buffer_.shared)->value;
}
static void Init(MatcherBase& m, M* impl) {
m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
}
static constexpr auto shared_destroy = &Shared::Destroy;
};
template <typename M>
void Init(M&& m) {
using MM = typename std::decay<M>::type;
using Policy = ValuePolicy<MM>;
vtable_ = GetVTable<Policy>();
Policy::Init(*this, std::forward<M>(m));
}
const VTable* vtable_;
Buffer buffer_;
}; };
} // namespace internal } // namespace internal
@ -340,6 +494,10 @@ class Matcher : public internal::MatcherBase<T> {
nullptr) nullptr)
: internal::MatcherBase<T>(impl) {} : internal::MatcherBase<T>(impl) {}
template <typename M, typename = typename std::remove_reference<
M>::type::is_gtest_matcher>
Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
// Implicit constructor here allows people to write // Implicit constructor here allows people to write
// EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
Matcher(T value); // NOLINT Matcher(T value); // NOLINT
@ -357,6 +515,11 @@ class GTEST_API_ Matcher<const std::string&>
explicit Matcher(const MatcherInterface<const std::string&>* impl) explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<const std::string&>(impl) {} : internal::MatcherBase<const std::string&>(impl) {}
template <typename M, typename = typename std::remove_reference<
M>::type::is_gtest_matcher>
Matcher(M&& m) // NOLINT
: internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
// Allows the user to write str instead of Eq(str) sometimes, where // Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object. // str is a std::string object.
Matcher(const std::string& s); // NOLINT Matcher(const std::string& s); // NOLINT
@ -376,6 +539,11 @@ class GTEST_API_ Matcher<std::string>
explicit Matcher(const MatcherInterface<std::string>* impl) explicit Matcher(const MatcherInterface<std::string>* impl)
: internal::MatcherBase<std::string>(impl) {} : internal::MatcherBase<std::string>(impl) {}
template <typename M, typename = typename std::remove_reference<
M>::type::is_gtest_matcher>
Matcher(M&& m) // NOLINT
: internal::MatcherBase<std::string>(std::forward<M>(m)) {}
// Allows the user to write str instead of Eq(str) sometimes, where // Allows the user to write str instead of Eq(str) sometimes, where
// str is a string object. // str is a string object.
Matcher(const std::string& s); // NOLINT Matcher(const std::string& s); // NOLINT
@ -384,18 +552,24 @@ class GTEST_API_ Matcher<std::string>
Matcher(const char* s); // NOLINT Matcher(const char* s); // NOLINT
}; };
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
// The following two specializations allow the user to write str // The following two specializations allow the user to write str
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
// matcher is expected. // matcher is expected.
template <> template <>
class GTEST_API_ Matcher<const absl::string_view&> class GTEST_API_ Matcher<const internal::StringView&>
: public internal::MatcherBase<const absl::string_view&> { : public internal::MatcherBase<const internal::StringView&> {
public: public:
Matcher() {} Matcher() {}
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl) explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
: internal::MatcherBase<const absl::string_view&>(impl) {} : internal::MatcherBase<const internal::StringView&>(impl) {}
template <typename M, typename = typename std::remove_reference<
M>::type::is_gtest_matcher>
Matcher(M&& m) // NOLINT
: internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
}
// Allows the user to write str instead of Eq(str) sometimes, where // Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object. // str is a std::string object.
@ -404,20 +578,25 @@ class GTEST_API_ Matcher<const absl::string_view&>
// Allows the user to write "foo" instead of Eq("foo") sometimes. // Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT Matcher(const char* s); // NOLINT
// Allows the user to pass absl::string_views directly. // Allows the user to pass absl::string_views or std::string_views directly.
Matcher(absl::string_view s); // NOLINT Matcher(internal::StringView s); // NOLINT
}; };
template <> template <>
class GTEST_API_ Matcher<absl::string_view> class GTEST_API_ Matcher<internal::StringView>
: public internal::MatcherBase<absl::string_view> { : public internal::MatcherBase<internal::StringView> {
public: public:
Matcher() {} Matcher() {}
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl) explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
: internal::MatcherBase<absl::string_view>(impl) {} : internal::MatcherBase<internal::StringView>(impl) {}
explicit Matcher(const MatcherInterface<absl::string_view>* impl) explicit Matcher(const MatcherInterface<internal::StringView>* impl)
: internal::MatcherBase<absl::string_view>(impl) {} : internal::MatcherBase<internal::StringView>(impl) {}
template <typename M, typename = typename std::remove_reference<
M>::type::is_gtest_matcher>
Matcher(M&& m) // NOLINT
: internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
// Allows the user to write str instead of Eq(str) sometimes, where // Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object. // str is a std::string object.
@ -426,10 +605,10 @@ class GTEST_API_ Matcher<absl::string_view>
// Allows the user to write "foo" instead of Eq("foo") sometimes. // Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT Matcher(const char* s); // NOLINT
// Allows the user to pass absl::string_views directly. // Allows the user to pass absl::string_views or std::string_views directly.
Matcher(absl::string_view s); // NOLINT Matcher(internal::StringView s); // NOLINT
}; };
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Prints a matcher in a human-readable format. // Prints a matcher in a human-readable format.
template <typename T> template <typename T>
@ -474,13 +653,13 @@ class PolymorphicMatcher {
public: public:
explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); } void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
virtual void DescribeNegationTo(::std::ostream* os) const { void DescribeNegationTo(::std::ostream* os) const override {
impl_.DescribeNegationTo(os); impl_.DescribeNegationTo(os);
} }
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { bool MatchAndExplain(T x, MatchResultListener* listener) const override {
return impl_.MatchAndExplain(x, listener); return impl_.MatchAndExplain(x, listener);
} }
@ -529,37 +708,32 @@ template <typename D, typename Rhs, typename Op>
class ComparisonBase { class ComparisonBase {
public: public:
explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {} explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
using is_gtest_matcher = void;
template <typename Lhs> template <typename Lhs>
operator Matcher<Lhs>() const { bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
return Matcher<Lhs>(new Impl<const Lhs&>(rhs_)); return Op()(lhs, Unwrap(rhs_));
}
void DescribeTo(std::ostream* os) const {
*os << D::Desc() << " ";
UniversalPrint(Unwrap(rhs_), os);
}
void DescribeNegationTo(std::ostream* os) const {
*os << D::NegatedDesc() << " ";
UniversalPrint(Unwrap(rhs_), os);
} }
private: private:
template <typename T> template <typename T>
static const T& Unwrap(const T& v) { return v; } static const T& Unwrap(const T& v) {
return v;
}
template <typename T> template <typename T>
static const T& Unwrap(std::reference_wrapper<T> v) { return v; } static const T& Unwrap(std::reference_wrapper<T> v) {
return v;
template <typename Lhs, typename = Rhs> }
class Impl : public MatcherInterface<Lhs> {
public:
explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
bool MatchAndExplain(Lhs lhs,
MatchResultListener* /* listener */) const override {
return Op()(lhs, Unwrap(rhs_));
}
void DescribeTo(::std::ostream* os) const override {
*os << D::Desc() << " ";
UniversalPrint(Unwrap(rhs_), os);
}
void DescribeNegationTo(::std::ostream* os) const override {
*os << D::NegatedDesc() << " ";
UniversalPrint(Unwrap(rhs_), os);
}
private:
Rhs rhs_;
};
Rhs rhs_; Rhs rhs_;
}; };
@ -612,6 +786,10 @@ class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
static const char* NegatedDesc() { return "isn't >="; } static const char* NegatedDesc() { return "isn't >="; }
}; };
template <typename T, typename = typename std::enable_if<
std::is_constructible<std::string, T>::value>::type>
using StringLike = T;
// Implements polymorphic matchers MatchesRegex(regex) and // Implements polymorphic matchers MatchesRegex(regex) and
// ContainsRegex(regex), which can be used as a Matcher<T> as long as // ContainsRegex(regex), which can be used as a Matcher<T> as long as
// T can be converted to a string. // T can be converted to a string.
@ -620,12 +798,12 @@ class MatchesRegexMatcher {
MatchesRegexMatcher(const RE* regex, bool full_match) MatchesRegexMatcher(const RE* regex, bool full_match)
: regex_(regex), full_match_(full_match) {} : regex_(regex), full_match_(full_match) {}
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
bool MatchAndExplain(const absl::string_view& s, bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const { MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener); return MatchAndExplain(std::string(s), listener);
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly: // Accepts pointer types, particularly:
// const char* // const char*
@ -672,9 +850,10 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const internal::RE* regex) { const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true)); return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
} }
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( template <typename T = std::string>
const std::string& regex) { PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
return MatchesRegex(new internal::RE(regex)); const internal::StringLike<T>& regex) {
return MatchesRegex(new internal::RE(std::string(regex)));
} }
// Matches a string that contains regular expression 'regex'. // Matches a string that contains regular expression 'regex'.
@ -683,9 +862,10 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const internal::RE* regex) { const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false)); return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
} }
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( template <typename T = std::string>
const std::string& regex) { PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
return ContainsRegex(new internal::RE(regex)); const internal::StringLike<T>& regex) {
return ContainsRegex(new internal::RE(std::string(regex)));
} }
// Creates a polymorphic matcher that matches anything equal to x. // Creates a polymorphic matcher that matches anything equal to x.
@ -747,4 +927,4 @@ inline internal::NeMatcher<Rhs> Ne(Rhs x) {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
#endif // GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_ #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_

@ -44,11 +44,12 @@
// GOOGLETEST_CM0001 DO NOT DELETE // GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
#include <limits> #include <limits>
#include <memory> #include <memory>
#include <sstream>
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
@ -215,4 +216,4 @@ std::string StreamableToString(const T& streamable) {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_

@ -30,12 +30,9 @@
// Macros and functions for implementing parameterized tests // Macros and functions for implementing parameterized tests
// in Google C++ Testing and Mocking Framework (Google Test) // in Google C++ Testing and Mocking Framework (Google Test)
// //
// This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
//
// GOOGLETEST_CM0001 DO NOT DELETE // GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
// Value-parameterized tests allow you to test your code with different // Value-parameterized tests allow you to test your code with different
// parameters without writing multiple copies of the same test. // parameters without writing multiple copies of the same test.
@ -371,8 +368,6 @@ inline internal::ParamGenerator<bool> Bool() {
// std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types // std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
// of elements from sequences produces by gen1, gen2, ..., genN. // of elements from sequences produces by gen1, gen2, ..., genN.
// //
// Combine can have up to 10 arguments.
//
// Example: // Example:
// //
// This will instantiate tests in test suite AnimalTest each one with // This will instantiate tests in test suite AnimalTest each one with
@ -416,19 +411,20 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
: public test_suite_name { \ : public test_suite_name { \
public: \ public: \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
virtual void TestBody(); \ void TestBody() override; \
\ \
private: \ private: \
static int AddToRegistry() { \ static int AddToRegistry() { \
::testing::UnitTest::GetInstance() \ ::testing::UnitTest::GetInstance() \
->parameterized_test_registry() \ ->parameterized_test_registry() \
.GetTestSuitePatternHolder<test_suite_name>( \ .GetTestSuitePatternHolder<test_suite_name>( \
#test_suite_name, \ GTEST_STRINGIFY_(test_suite_name), \
::testing::internal::CodeLocation(__FILE__, __LINE__)) \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
->AddTestPattern( \ ->AddTestPattern( \
GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \ GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \ new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
test_suite_name, test_name)>()); \ test_suite_name, test_name)>(), \
::testing::internal::CodeLocation(__FILE__, __LINE__)); \
return 0; \ return 0; \
} \ } \
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
@ -483,13 +479,21 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
::testing::UnitTest::GetInstance() \ ::testing::UnitTest::GetInstance() \
->parameterized_test_registry() \ ->parameterized_test_registry() \
.GetTestSuitePatternHolder<test_suite_name>( \ .GetTestSuitePatternHolder<test_suite_name>( \
#test_suite_name, \ GTEST_STRINGIFY_(test_suite_name), \
::testing::internal::CodeLocation(__FILE__, __LINE__)) \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \
->AddTestSuiteInstantiation( \ ->AddTestSuiteInstantiation( \
#prefix, &gtest_##prefix##test_suite_name##_EvalGenerator_, \ GTEST_STRINGIFY_(prefix), \
&gtest_##prefix##test_suite_name##_EvalGenerator_, \
&gtest_##prefix##test_suite_name##_EvalGenerateName_, \ &gtest_##prefix##test_suite_name##_EvalGenerateName_, \
__FILE__, __LINE__) __FILE__, __LINE__)
// Allow Marking a Parameterized test class as not needing to be instantiated.
#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
namespace gtest_do_not_use_outside_namespace_scope {} \
static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
GTEST_STRINGIFY_(T))
// Legacy API is deprecated but still available // Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#define INSTANTIATE_TEST_CASE_P \ #define INSTANTIATE_TEST_CASE_P \
@ -500,4 +504,4 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
} // namespace testing } // namespace testing
#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_

@ -97,10 +97,11 @@
// GOOGLETEST_CM0001 DO NOT DELETE // GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#include <functional> #include <functional>
#include <memory>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <sstream> #include <sstream>
#include <string> #include <string>
@ -108,64 +109,124 @@
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_HAS_ABSL
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#endif // GTEST_HAS_ABSL
namespace testing { namespace testing {
// Definitions in the 'internal' and 'internal2' name spaces are // Definitions in the internal* namespaces are subject to change without notice.
// subject to change without notice. DO NOT USE THEM IN USER CODE! // DO NOT USE THEM IN USER CODE!
namespace internal2 { namespace internal {
// Prints the given number of bytes in the given object to the given template <typename T>
// ostream. void UniversalPrint(const T& value, ::std::ostream* os);
GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
size_t count,
::std::ostream* os);
// For selecting which printer to use when a given type has neither << // Used to print an STL-style container when the user doesn't define
// nor PrintTo(). // a PrintTo() for it.
enum TypeKind { struct ContainerPrinter {
kProtobuf, // a protobuf type template <typename T,
kConvertibleToInteger, // a type implicitly convertible to BiggestInt typename = typename std::enable_if<
// (e.g. a named or unnamed enum type) (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
#if GTEST_HAS_ABSL !IsRecursiveContainer<T>::value>::type>
kConvertibleToStringView, // a type implicitly convertible to static void PrintValue(const T& container, std::ostream* os) {
// absl::string_view const size_t kMaxCount = 32; // The maximum number of elements to print.
#endif *os << '{';
kOtherType // anything else size_t count = 0;
for (auto&& elem : container) {
if (count > 0) {
*os << ',';
if (count == kMaxCount) { // Enough has been printed.
*os << " ...";
break;
}
}
*os << ' ';
// We cannot call PrintTo(elem, os) here as PrintTo() doesn't
// handle `elem` being a native array.
internal::UniversalPrint(elem, os);
++count;
}
if (count > 0) {
*os << ' ';
}
*os << '}';
}
}; };
// TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called // Used to print a pointer that is neither a char pointer nor a member
// by the universal printer to print a value of type T when neither // pointer, when the user doesn't define PrintTo() for it. (A member
// operator<< nor PrintTo() is defined for T, where kTypeKind is the // variable pointer or member function pointer doesn't really point to
// "kind" of T as defined by enum TypeKind. // a location in the address space. Their representation is
template <typename T, TypeKind kTypeKind> // implementation-defined. Therefore they will be printed as raw
class TypeWithoutFormatter { // bytes.)
public: struct FunctionPointerPrinter {
// This default version is called when kTypeKind is kOtherType. template <typename T, typename = typename std::enable_if<
std::is_function<T>::value>::type>
static void PrintValue(T* p, ::std::ostream* os) {
if (p == nullptr) {
*os << "NULL";
} else {
// T is a function type, so '*os << p' doesn't do what we want
// (it just prints p as bool). We want to print p as a const
// void*.
*os << reinterpret_cast<const void*>(p);
}
}
};
struct PointerPrinter {
template <typename T>
static void PrintValue(T* p, ::std::ostream* os) {
if (p == nullptr) {
*os << "NULL";
} else {
// T is not a function type. We just call << to print p,
// relying on ADL to pick up user-defined << for their pointer
// types, if any.
*os << p;
}
}
};
namespace internal_stream_operator_without_lexical_name_lookup {
// The presence of an operator<< here will terminate lexical scope lookup
// straight away (even though it cannot be a match because of its argument
// types). Thus, the two operator<< calls in StreamPrinter will find only ADL
// candidates.
struct LookupBlocker {};
void operator<<(LookupBlocker, LookupBlocker);
struct StreamPrinter {
template <typename T,
// Don't accept member pointers here. We'd print them via implicit
// conversion to bool, which isn't useful.
typename = typename std::enable_if<
!std::is_member_pointer<T>::value>::type,
// Only accept types for which we can find a streaming operator via
// ADL (possibly involving implicit conversions).
typename = decltype(std::declval<std::ostream&>()
<< std::declval<const T&>())>
static void PrintValue(const T& value, ::std::ostream* os) { static void PrintValue(const T& value, ::std::ostream* os) {
PrintBytesInObjectTo( // Call streaming operator found by ADL, possibly with implicit conversions
static_cast<const unsigned char*>( // of the arguments.
reinterpret_cast<const void*>(std::addressof(value))), *os << value;
sizeof(value), os);
} }
}; };
// We print a protobuf using its ShortDebugString() when the string } // namespace internal_stream_operator_without_lexical_name_lookup
// doesn't exceed this many characters; otherwise we print it using
// DebugString() for better readability.
const size_t kProtobufOneLinerMaxLength = 50;
template <typename T> struct ProtobufPrinter {
class TypeWithoutFormatter<T, kProtobuf> { // We print a protobuf using its ShortDebugString() when the string
public: // doesn't exceed this many characters; otherwise we print it using
// DebugString() for better readability.
static const size_t kProtobufOneLinerMaxLength = 50;
template <typename T,
typename = typename std::enable_if<
internal::HasDebugStringAndShortDebugString<T>::value>::type>
static void PrintValue(const T& value, ::std::ostream* os) { static void PrintValue(const T& value, ::std::ostream* os) {
std::string pretty_str = value.ShortDebugString(); std::string pretty_str = value.ShortDebugString();
if (pretty_str.length() > kProtobufOneLinerMaxLength) { if (pretty_str.length() > kProtobufOneLinerMaxLength) {
@ -175,9 +236,7 @@ class TypeWithoutFormatter<T, kProtobuf> {
} }
}; };
template <typename T> struct ConvertibleToIntegerPrinter {
class TypeWithoutFormatter<T, kConvertibleToInteger> {
public:
// Since T has no << operator or PrintTo() but can be implicitly // Since T has no << operator or PrintTo() but can be implicitly
// converted to BiggestInt, we print it as a BiggestInt. // converted to BiggestInt, we print it as a BiggestInt.
// //
@ -185,112 +244,73 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> {
// case printing it as an integer is the desired behavior. In case // case printing it as an integer is the desired behavior. In case
// T is not an enum, printing it as an integer is the best we can do // T is not an enum, printing it as an integer is the best we can do
// given that it has no user-defined printer. // given that it has no user-defined printer.
static void PrintValue(const T& value, ::std::ostream* os) { static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
const internal::BiggestInt kBigInt = value; *os << value;
*os << kBigInt;
} }
}; };
#if GTEST_HAS_ABSL struct ConvertibleToStringViewPrinter {
template <typename T> #if GTEST_INTERNAL_HAS_STRING_VIEW
class TypeWithoutFormatter<T, kConvertibleToStringView> { static void PrintValue(internal::StringView value, ::std::ostream* os) {
public: internal::UniversalPrint(value, os);
// Since T has neither operator<< nor PrintTo() but can be implicitly }
// converted to absl::string_view, we print it as a absl::string_view.
//
// Note: the implementation is further below, as it depends on
// internal::PrintTo symbol which is defined later in the file.
static void PrintValue(const T& value, ::std::ostream* os);
};
#endif
// Prints the given value to the given ostream. If the value is a
// protocol message, its debug string is printed; if it's an enum or
// of a type implicitly convertible to BiggestInt, it's printed as an
// integer; otherwise the bytes in the value are printed. This is
// what UniversalPrinter<T>::Print() does when it knows nothing about
// type T and T has neither << operator nor PrintTo().
//
// A user can override this behavior for a class type Foo by defining
// a << operator in the namespace where Foo is defined.
//
// We put this operator in namespace 'internal2' instead of 'internal'
// to simplify the implementation, as much code in 'internal' needs to
// use << in STL, which would conflict with our own << were it defined
// in 'internal'.
//
// Note that this operator<< takes a generic std::basic_ostream<Char,
// CharTraits> type instead of the more restricted std::ostream. If
// we define it to take an std::ostream instead, we'll get an
// "ambiguous overloads" compiler error when trying to print a type
// Foo that supports streaming to std::basic_ostream<Char,
// CharTraits>, as the compiler cannot tell whether
// operator<<(std::ostream&, const T&) or
// operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
// specific.
template <typename Char, typename CharTraits, typename T>
::std::basic_ostream<Char, CharTraits>& operator<<(
::std::basic_ostream<Char, CharTraits>& os, const T& x) {
TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
? kProtobuf
: std::is_convertible<
const T&, internal::BiggestInt>::value
? kConvertibleToInteger
:
#if GTEST_HAS_ABSL
std::is_convertible<
const T&, absl::string_view>::value
? kConvertibleToStringView
:
#endif #endif
kOtherType)>::PrintValue(x, &os); };
return os;
}
} // namespace internal2
} // namespace testing
// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up // Prints the given number of bytes in the given object to the given
// magic needed for implementing UniversalPrinter won't work. // ostream.
namespace testing_internal { GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
size_t count,
::std::ostream* os);
struct RawBytesPrinter {
// SFINAE on `sizeof` to make sure we have a complete type.
template <typename T, size_t = sizeof(T)>
static void PrintValue(const T& value, ::std::ostream* os) {
PrintBytesInObjectTo(
static_cast<const unsigned char*>(
// Load bearing cast to void* to support iOS
reinterpret_cast<const void*>(std::addressof(value))),
sizeof(value), os);
}
};
// Used to print a value that is not an STL-style container when the struct FallbackPrinter {
// user doesn't define PrintTo() for it. template <typename T>
template <typename T> static void PrintValue(const T&, ::std::ostream* os) {
void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { *os << "(incomplete type)";
// With the following statement, during unqualified name lookup, }
// testing::internal2::operator<< appears as if it was declared in };
// the nearest enclosing namespace that contains both
// ::testing_internal and ::testing::internal2, i.e. the global
// namespace. For more details, refer to the C++ Standard section
// 7.3.4-1 [namespace.udir]. This allows us to fall back onto
// testing::internal2::operator<< in case T doesn't come with a <<
// operator.
//
// We cannot write 'using ::testing::internal2::operator<<;', which
// gcc 3.3 fails to compile due to a compiler bug.
using namespace ::testing::internal2; // NOLINT
// Assuming T is defined in namespace foo, in the next statement, // Try every printer in order and return the first one that works.
// the compiler will consider all of: template <typename T, typename E, typename Printer, typename... Printers>
// struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
// 1. foo::operator<< (thanks to Koenig look-up),
// 2. ::operator<< (as the current namespace is enclosed in ::),
// 3. testing::internal2::operator<< (thanks to the using statement above).
//
// The operator<< whose type matches T best will be picked.
//
// We deliberately allow #2 to be a candidate, as sometimes it's
// impossible to define #1 (e.g. when foo is ::std, defining
// anything in it is undefined behavior unless you are a compiler
// vendor.).
*os << value;
}
} // namespace testing_internal template <typename T, typename Printer, typename... Printers>
struct FindFirstPrinter<
T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
Printer, Printers...> {
using type = Printer;
};
namespace testing { // Select the best printer in the following order:
namespace internal { // - Print containers (they have begin/end/etc).
// - Print function pointers.
// - Print object pointers.
// - Use the stream operator, if available.
// - Print protocol buffers.
// - Print types convertible to BiggestInt.
// - Print types convertible to StringView, if available.
// - Fallback to printing the raw bytes of the object.
template <typename T>
void PrintWithFallback(const T& value, ::std::ostream* os) {
using Printer = typename FindFirstPrinter<
T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
ProtobufPrinter, ConvertibleToIntegerPrinter,
ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
Printer::PrintValue(value, os);
}
// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
// value of type ToPrint that is an operand of a comparison assertion // value of type ToPrint that is an operand of a comparison assertion
@ -340,6 +360,14 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
#ifdef __cpp_char8_t
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
#endif
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_ #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
@ -357,6 +385,14 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
#ifdef __cpp_char8_t
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
#endif
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
@ -389,85 +425,6 @@ std::string FormatForComparisonFailureMessage(
template <typename T> template <typename T>
class UniversalPrinter; class UniversalPrinter;
template <typename T>
void UniversalPrint(const T& value, ::std::ostream* os);
enum DefaultPrinterType {
kPrintContainer,
kPrintPointer,
kPrintFunctionPointer,
kPrintOther,
};
template <DefaultPrinterType type> struct WrapPrinterType {};
// Used to print an STL-style container when the user doesn't define
// a PrintTo() for it.
template <typename C>
void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
const C& container, ::std::ostream* os) {
const size_t kMaxCount = 32; // The maximum number of elements to print.
*os << '{';
size_t count = 0;
for (typename C::const_iterator it = container.begin();
it != container.end(); ++it, ++count) {
if (count > 0) {
*os << ',';
if (count == kMaxCount) { // Enough has been printed.
*os << " ...";
break;
}
}
*os << ' ';
// We cannot call PrintTo(*it, os) here as PrintTo() doesn't
// handle *it being a native array.
internal::UniversalPrint(*it, os);
}
if (count > 0) {
*os << ' ';
}
*os << '}';
}
// Used to print a pointer that is neither a char pointer nor a member
// pointer, when the user doesn't define PrintTo() for it. (A member
// variable pointer or member function pointer doesn't really point to
// a location in the address space. Their representation is
// implementation-defined. Therefore they will be printed as raw
// bytes.)
template <typename T>
void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
T* p, ::std::ostream* os) {
if (p == nullptr) {
*os << "NULL";
} else {
// T is not a function type. We just call << to print p,
// relying on ADL to pick up user-defined << for their pointer
// types, if any.
*os << p;
}
}
template <typename T>
void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
T* p, ::std::ostream* os) {
if (p == nullptr) {
*os << "NULL";
} else {
// T is a function type, so '*os << p' doesn't do what we want
// (it just prints p as bool). We want to print p as a const
// void*.
*os << reinterpret_cast<const void*>(p);
}
}
// Used to print a non-container, non-pointer value when the user
// doesn't define PrintTo() for it.
template <typename T>
void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
const T& value, ::std::ostream* os) {
::testing_internal::DefaultPrintNonContainerTo(value, os);
}
// Prints the given value using the << operator if it has one; // Prints the given value using the << operator if it has one;
// otherwise prints the bytes in it. This is what // otherwise prints the bytes in it. This is what
// UniversalPrinter<T>::Print() does when PrintTo() is not specialized // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
@ -481,36 +438,7 @@ void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
// wants). // wants).
template <typename T> template <typename T>
void PrintTo(const T& value, ::std::ostream* os) { void PrintTo(const T& value, ::std::ostream* os) {
// DefaultPrintTo() is overloaded. The type of its first argument internal::PrintWithFallback(value, os);
// determines which version will be picked.
//
// Note that we check for container types here, prior to we check
// for protocol message types in our operator<<. The rationale is:
//
// For protocol messages, we want to give people a chance to
// override Google Mock's format by defining a PrintTo() or
// operator<<. For STL containers, other formats can be
// incompatible with Google Mock's format for the container
// elements; therefore we check for container types here to ensure
// that our format is used.
//
// Note that MSVC and clang-cl do allow an implicit conversion from
// pointer-to-function to pointer-to-object, but clang-cl warns on it.
// So don't use ImplicitlyConvertible if it can be helped since it will
// cause this warning, and use a separate overload of DefaultPrintTo for
// function pointers so that the `*os << p` in the object pointer overload
// doesn't cause that warning either.
DefaultPrintTo(
WrapPrinterType <
(sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
!IsRecursiveContainer<T>::value
? kPrintContainer
: !std::is_pointer<T>::value
? kPrintOther
: std::is_function<typename std::remove_pointer<T>::type>::value
? kPrintFunctionPointer
: kPrintPointer > (),
value, os);
} }
// The following list of PrintTo() overloads tells // The following list of PrintTo() overloads tells
@ -541,6 +469,16 @@ inline void PrintTo(bool x, ::std::ostream* os) {
// is implemented as an unsigned type. // is implemented as an unsigned type.
GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
inline void PrintTo(char16_t c, ::std::ostream* os) {
PrintTo(ImplicitCast_<char32_t>(c), os);
}
#ifdef __cpp_char8_t
inline void PrintTo(char8_t c, ::std::ostream* os) {
PrintTo(ImplicitCast_<char32_t>(c), os);
}
#endif
// Overloads for C strings. // Overloads for C strings.
GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
inline void PrintTo(char* s, ::std::ostream* os) { inline void PrintTo(char* s, ::std::ostream* os) {
@ -561,6 +499,23 @@ inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
inline void PrintTo(unsigned char* s, ::std::ostream* os) { inline void PrintTo(unsigned char* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const void*>(s), os); PrintTo(ImplicitCast_<const void*>(s), os);
} }
#ifdef __cpp_char8_t
// Overloads for u8 strings.
GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
inline void PrintTo(char8_t* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const char8_t*>(s), os);
}
#endif
// Overloads for u16 strings.
GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);
inline void PrintTo(char16_t* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const char16_t*>(s), os);
}
// Overloads for u32 strings.
GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);
inline void PrintTo(char32_t* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const char32_t*>(s), os);
}
// MSVC can be configured to define wchar_t as a typedef of unsigned // MSVC can be configured to define wchar_t as a typedef of unsigned
// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
@ -595,6 +550,26 @@ inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
PrintStringTo(s, os); PrintStringTo(s, os);
} }
// Overloads for ::std::u8string
#ifdef __cpp_char8_t
GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
PrintU8StringTo(s, os);
}
#endif
// Overloads for ::std::u16string
GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
PrintU16StringTo(s, os);
}
// Overloads for ::std::u32string
GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
PrintU32StringTo(s, os);
}
// Overloads for ::std::wstring. // Overloads for ::std::wstring.
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
@ -603,12 +578,12 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
// Overload for absl::string_view. // Overload for internal::StringView.
inline void PrintTo(absl::string_view sp, ::std::ostream* os) { inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
PrintTo(::std::string(sp), os); PrintTo(::std::string(sp), os);
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; } inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
@ -617,6 +592,43 @@ void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
UniversalPrinter<T&>::Print(ref.get(), os); UniversalPrinter<T&>::Print(ref.get(), os);
} }
inline const void* VoidifyPointer(const void* p) { return p; }
inline const void* VoidifyPointer(volatile const void* p) {
return const_cast<const void*>(p);
}
template <typename T, typename Ptr>
void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
if (ptr == nullptr) {
*os << "(nullptr)";
} else {
// We can't print the value. Just print the pointer..
*os << "(" << (VoidifyPointer)(ptr.get()) << ")";
}
}
template <typename T, typename Ptr,
typename = typename std::enable_if<!std::is_void<T>::value &&
!std::is_array<T>::value>::type>
void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
if (ptr == nullptr) {
*os << "(nullptr)";
} else {
*os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
UniversalPrinter<T>::Print(*ptr, os);
*os << ")";
}
}
template <typename T, typename D>
void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
(PrintSmartPointer<T>)(ptr, os, 0);
}
template <typename T>
void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
(PrintSmartPointer<T>)(ptr, os, 0);
}
// Helper function for printing a tuple. T must be instantiated with // Helper function for printing a tuple. T must be instantiated with
// a tuple type. // a tuple type.
template <typename T> template <typename T>
@ -682,14 +694,46 @@ class UniversalPrinter {
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
}; };
#if GTEST_HAS_ABSL // Remove any const-qualifiers before passing a type to UniversalPrinter.
template <typename T>
class UniversalPrinter<const T> : public UniversalPrinter<T> {};
#if GTEST_INTERNAL_HAS_ANY
// Printer for std::any / absl::any
// Printer for absl::optional template <>
class UniversalPrinter<Any> {
public:
static void Print(const Any& value, ::std::ostream* os) {
if (value.has_value()) {
*os << "value of type " << GetTypeName(value);
} else {
*os << "no value";
}
}
private:
static std::string GetTypeName(const Any& value) {
#if GTEST_HAS_RTTI
return internal::GetTypeName(value.type());
#else
static_cast<void>(value); // possibly unused
return "<unknown_type>";
#endif // GTEST_HAS_RTTI
}
};
#endif // GTEST_INTERNAL_HAS_ANY
#if GTEST_INTERNAL_HAS_OPTIONAL
// Printer for std::optional / absl::optional
template <typename T> template <typename T>
class UniversalPrinter<::absl::optional<T>> { class UniversalPrinter<Optional<T>> {
public: public:
static void Print(const ::absl::optional<T>& value, ::std::ostream* os) { static void Print(const Optional<T>& value, ::std::ostream* os) {
*os << '('; *os << '(';
if (!value) { if (!value) {
*os << "nullopt"; *os << "nullopt";
@ -700,14 +744,22 @@ class UniversalPrinter<::absl::optional<T>> {
} }
}; };
// Printer for absl::variant #endif // GTEST_INTERNAL_HAS_OPTIONAL
#if GTEST_INTERNAL_HAS_VARIANT
// Printer for std::variant / absl::variant
template <typename... T> template <typename... T>
class UniversalPrinter<::absl::variant<T...>> { class UniversalPrinter<Variant<T...>> {
public: public:
static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) { static void Print(const Variant<T...>& value, ::std::ostream* os) {
*os << '('; *os << '(';
absl::visit(Visitor{os}, value); #if GTEST_HAS_ABSL
absl::visit(Visitor{os, value.index()}, value);
#else
std::visit(Visitor{os, value.index()}, value);
#endif // GTEST_HAS_ABSL
*os << ')'; *os << ')';
} }
@ -715,14 +767,16 @@ class UniversalPrinter<::absl::variant<T...>> {
struct Visitor { struct Visitor {
template <typename U> template <typename U>
void operator()(const U& u) const { void operator()(const U& u) const {
*os << "'" << GetTypeName<U>() << "' with value "; *os << "'" << GetTypeName<U>() << "(index = " << index
<< ")' with value ";
UniversalPrint(u, os); UniversalPrint(u, os);
} }
::std::ostream* os; ::std::ostream* os;
std::size_t index;
}; };
}; };
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_VARIANT
// UniversalPrintArray(begin, len, os) prints an array of 'len' // UniversalPrintArray(begin, len, os) prints an array of 'len'
// elements, starting at address 'begin'. // elements, starting at address 'begin'.
@ -751,6 +805,20 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
GTEST_API_ void UniversalPrintArray( GTEST_API_ void UniversalPrintArray(
const char* begin, size_t len, ::std::ostream* os); const char* begin, size_t len, ::std::ostream* os);
#ifdef __cpp_char8_t
// This overload prints a (const) char8_t array compactly.
GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
::std::ostream* os);
#endif
// This overload prints a (const) char16_t array compactly.
GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
::std::ostream* os);
// This overload prints a (const) char32_t array compactly.
GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
::std::ostream* os);
// This overload prints a (const) wchar_t array compactly. // This overload prints a (const) wchar_t array compactly.
GTEST_API_ void UniversalPrintArray( GTEST_API_ void UniversalPrintArray(
const wchar_t* begin, size_t len, ::std::ostream* os); const wchar_t* begin, size_t len, ::std::ostream* os);
@ -823,12 +891,55 @@ class UniversalTersePrinter<const char*> {
} }
}; };
template <> template <>
class UniversalTersePrinter<char*> { class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
};
#ifdef __cpp_char8_t
template <>
class UniversalTersePrinter<const char8_t*> {
public: public:
static void Print(char* str, ::std::ostream* os) { static void Print(const char8_t* str, ::std::ostream* os) {
UniversalTersePrinter<const char*>::Print(str, os); if (str == nullptr) {
*os << "NULL";
} else {
UniversalPrint(::std::u8string(str), os);
}
} }
}; };
template <>
class UniversalTersePrinter<char8_t*>
: public UniversalTersePrinter<const char8_t*> {};
#endif
template <>
class UniversalTersePrinter<const char16_t*> {
public:
static void Print(const char16_t* str, ::std::ostream* os) {
if (str == nullptr) {
*os << "NULL";
} else {
UniversalPrint(::std::u16string(str), os);
}
}
};
template <>
class UniversalTersePrinter<char16_t*>
: public UniversalTersePrinter<const char16_t*> {};
template <>
class UniversalTersePrinter<const char32_t*> {
public:
static void Print(const char32_t* str, ::std::ostream* os) {
if (str == nullptr) {
*os << "NULL";
} else {
UniversalPrint(::std::u32string(str), os);
}
}
};
template <>
class UniversalTersePrinter<char32_t*>
: public UniversalTersePrinter<const char32_t*> {};
#if GTEST_HAS_STD_WSTRING #if GTEST_HAS_STD_WSTRING
template <> template <>
@ -901,16 +1012,6 @@ Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
} // namespace internal } // namespace internal
#if GTEST_HAS_ABSL
namespace internal2 {
template <typename T>
void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
const T& value, ::std::ostream* os) {
internal::PrintTo(absl::string_view(value), os);
}
} // namespace internal2
#endif
template <typename T> template <typename T>
::std::string PrintToString(const T& value) { ::std::string PrintToString(const T& value) {
::std::stringstream ss; ::std::stringstream ss;
@ -925,4 +1026,4 @@ template <typename T>
// declarations from this file. // declarations from this file.
#include "gtest/internal/custom/gtest-printers.h" #include "gtest/internal/custom/gtest-printers.h"
#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_

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

Loading…
Cancel
Save