Fixes #1081 Signed-off-by: Florian Bruhin <me@the-compiler.org>pull/1083/head
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
|
@ -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
|
@ -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.
|
@ -1,11 +1,10 @@
|
||||
prefix=${pcfiledir}/../..
|
||||
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
|
||||
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
|
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gmock
|
||||
Description: GoogleMock (without main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gtest
|
||||
Requires: gtest = @PROJECT_VERSION@
|
||||
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=${prefix}/@CMAKE_INSTALL_LIBDIR@
|
||||
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
|
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gmock_main
|
||||
Description: GoogleMock (with main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gmock
|
||||
Requires: gmock = @PROJECT_VERSION@
|
||||
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>
|
||||
 `template <typename T>` <br>
|
||||
 `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.
|
File diff suppressed because it is too large
Load Diff
@ -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_
|
File diff suppressed because it is too large
Load Diff
@ -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
@ -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
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
|
||||
#ifndef GOOGLEMOCK_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_
|
@ -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()
|
@ -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()
|
File diff suppressed because it is too large
Load Diff
@ -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
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -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.
|
@ -1,10 +1,9 @@
|
||||
prefix=${pcfiledir}/../..
|
||||
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
|
||||
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
|
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gtest
|
||||
Description: GoogleTest (without main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
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=${prefix}/@CMAKE_INSTALL_LIBDIR@
|
||||
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
|
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gtest_main
|
||||
Description: GoogleTest (with main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gtest
|
||||
Requires: gtest = @PROJECT_VERSION@
|
||||
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@
|
||||
|
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.
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue