aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndroid Build Coastguard Worker <android-build-coastguard-worker@google.com>2021-07-15 01:34:53 +0000
committerAndroid Build Coastguard Worker <android-build-coastguard-worker@google.com>2021-07-15 01:34:53 +0000
commitf45b58cc66694c9ba3b7b8c95fbd1bb11d058b92 (patch)
tree54fb90f190c69a329c719650bad4fe22bf879033
parent58559ab54de872ea8208cb244c41545424b5382b (diff)
parent6d793b72ffe4cf5deb99227bd70ee74a8bc34d72 (diff)
downloadgoogletest-android12-mainline-tethering-release.tar.gz
Change-Id: I4580df897d3d339973cb4ad83cc2285acc7e32d3
-rw-r--r--.github/ISSUE_TEMPLATE/00-bug_report.md43
-rw-r--r--.github/ISSUE_TEMPLATE/config.yml1
-rw-r--r--.travis.yml38
-rw-r--r--Android.bp44
-rw-r--r--BUILD.bazel23
-rw-r--r--CMakeLists.txt10
-rw-r--r--CONTRIBUTING.md16
-rw-r--r--CONTRIBUTORS (renamed from googletest/CONTRIBUTORS)25
-rw-r--r--METADATA9
-rw-r--r--README.md128
-rw-r--r--TEST_MAPPING8
-rw-r--r--WORKSPACE29
-rw-r--r--appveyor.yml156
-rwxr-xr-xci/build-linux-bazel.sh37
-rw-r--r--ci/build-platformio.sh2
-rwxr-xr-xci/env-linux.sh41
-rwxr-xr-xci/env-osx.sh47
-rwxr-xr-xci/install-linux.sh49
-rwxr-xr-xci/install-osx.sh40
-rw-r--r--ci/install-platformio.sh5
-rw-r--r--ci/linux-presubmit.sh124
-rw-r--r--[-rwxr-xr-x]ci/macos-presubmit.sh (renamed from ci/get-nprocessors.sh)59
-rwxr-xr-xci/travis.sh44
-rw-r--r--docs/_config.yml1
-rw-r--r--docs/_data/navigation.yml35
-rw-r--r--docs/_layouts/default.html53
-rw-r--r--docs/_sass/main.scss193
-rw-r--r--docs/advanced.md (renamed from googletest/docs/advanced.md)430
-rw-r--r--docs/assets/css/style.scss5
-rw-r--r--docs/community_created_documentation.md7
-rw-r--r--docs/faq.md (renamed from googletest/docs/faq.md)95
-rw-r--r--docs/gmock_cheat_sheet.md483
-rw-r--r--docs/gmock_cook_book.md (renamed from googlemock/docs/cook_book.md)571
-rw-r--r--docs/gmock_faq.md (renamed from googlemock/docs/gmock_faq.md)20
-rw-r--r--docs/gmock_for_dummies.md (renamed from googlemock/docs/for_dummies.md)87
-rw-r--r--docs/index.md22
-rw-r--r--docs/pkgconfig.md (renamed from googletest/docs/pkgconfig.md)73
-rw-r--r--docs/platforms.md35
-rw-r--r--docs/primer.md (renamed from googletest/docs/primer.md)9
-rw-r--r--docs/quickstart-bazel.md161
-rw-r--r--docs/quickstart-cmake.md156
-rw-r--r--docs/reference/matchers.md282
-rw-r--r--docs/samples.md (renamed from googletest/docs/samples.md)2
-rw-r--r--googlemock/Android.bp10
-rw-r--r--googlemock/CMakeLists.txt21
-rw-r--r--googlemock/CONTRIBUTORS40
l---------[-rw-r--r--]googlemock/LICENSE29
l---------googlemock/NOTICE2
-rw-r--r--googlemock/README.md50
-rw-r--r--googlemock/cmake/gmock.pc.in2
-rw-r--r--googlemock/cmake/gmock_main.pc.in2
-rw-r--r--googlemock/docs/README.md4
-rw-r--r--googlemock/docs/cheat_sheet.md776
-rw-r--r--googlemock/docs/pump_manual.md187
-rw-r--r--googlemock/include/gmock/gmock-actions.h565
-rw-r--r--googlemock/include/gmock/gmock-cardinalities.h6
-rw-r--r--googlemock/include/gmock/gmock-function-mocker.h297
-rw-r--r--googlemock/include/gmock/gmock-generated-actions.h1757
-rw-r--r--googlemock/include/gmock/gmock-generated-actions.h.pump579
-rw-r--r--googlemock/include/gmock/gmock-generated-function-mockers.h752
-rw-r--r--googlemock/include/gmock/gmock-generated-function-mockers.h.pump227
-rw-r--r--googlemock/include/gmock/gmock-generated-matchers.h1097
-rw-r--r--googlemock/include/gmock/gmock-generated-matchers.h.pump346
-rw-r--r--googlemock/include/gmock/gmock-matchers.h1179
-rw-r--r--googlemock/include/gmock/gmock-more-actions.h603
-rw-r--r--googlemock/include/gmock/gmock-more-matchers.h10
-rw-r--r--googlemock/include/gmock/gmock-nice-strict.h196
-rw-r--r--googlemock/include/gmock/gmock-spec-builders.h167
-rw-r--r--googlemock/include/gmock/gmock.h11
-rw-r--r--googlemock/include/gmock/internal/custom/gmock-generated-actions.h10
-rw-r--r--googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump12
-rw-r--r--googlemock/include/gmock/internal/custom/gmock-matchers.h6
-rw-r--r--googlemock/include/gmock/internal/custom/gmock-port.h6
-rw-r--r--googlemock/include/gmock/internal/gmock-internal-utils.h33
-rw-r--r--googlemock/include/gmock/internal/gmock-port.h6
-rw-r--r--googlemock/include/gmock/internal/gmock-pp.h20
-rwxr-xr-xgooglemock/scripts/fuse_gmock_files.py128
-rwxr-xr-xgooglemock/scripts/generator/cpp/ast.py2942
-rwxr-xr-xgooglemock/scripts/generator/cpp/gmock_class.py367
-rwxr-xr-xgooglemock/scripts/generator/cpp/gmock_class_test.py486
-rwxr-xr-xgooglemock/scripts/pump.py856
-rw-r--r--googlemock/src/gmock-matchers.cc3
-rw-r--r--googlemock/src/gmock-spec-builders.cc64
-rw-r--r--googlemock/src/gmock.cc2
-rw-r--r--googlemock/test/Android.bp12
-rw-r--r--googlemock/test/BUILD.bazel13
-rw-r--r--googlemock/test/gmock-actions_test.cc146
-rw-r--r--googlemock/test/gmock-function-mocker_nc.cc16
-rw-r--r--googlemock/test/gmock-function-mocker_nc_test.py43
-rw-r--r--googlemock/test/gmock-function-mocker_test.cc470
-rw-r--r--googlemock/test/gmock-generated-actions_test.cc1064
-rw-r--r--googlemock/test/gmock-generated-function-mockers_test.cc659
-rw-r--r--googlemock/test/gmock-generated-matchers_test.cc1314
-rw-r--r--googlemock/test/gmock-internal-utils_test.cc14
-rw-r--r--googlemock/test/gmock-matchers_test.cc1879
-rw-r--r--googlemock/test/gmock-more-actions_test.cc945
-rw-r--r--googlemock/test/gmock-nice-strict_test.cc39
-rw-r--r--googlemock/test/gmock-spec-builders_test.cc4
-rw-r--r--googlemock/test/gmock_all_test.cc3
-rw-r--r--googlemock/test/gmock_link_test.h6
-rw-r--r--googlemock/test/gmock_output_test_golden.txt10
-rwxr-xr-xgooglemock/test/pump_test.py182
-rw-r--r--googletest/Android.bp28
-rw-r--r--googletest/Android.mk18
-rw-r--r--googletest/CMakeLists.txt26
l---------[-rw-r--r--]googletest/LICENSE29
l---------googletest/NOTICE2
-rw-r--r--googletest/README.md169
-rw-r--r--googletest/cmake/gtest_main.pc.in2
-rw-r--r--googletest/cmake/internal_utils.cmake62
-rw-r--r--googletest/docs/README.md4
-rw-r--r--googletest/include/gtest/gtest-death-test.h11
-rw-r--r--googletest/include/gtest/gtest-matchers.h408
-rw-r--r--googletest/include/gtest/gtest-message.h6
-rw-r--r--googletest/include/gtest/gtest-param-test.h21
-rw-r--r--googletest/include/gtest/gtest-printers.h663
-rw-r--r--googletest/include/gtest/gtest-spi.h6
-rw-r--r--googletest/include/gtest/gtest-test-part.h6
-rw-r--r--googletest/include/gtest/gtest-typed-test.h14
-rw-r--r--googletest/include/gtest/gtest.h102
-rw-r--r--googletest/include/gtest/gtest_pred_impl.h6
-rw-r--r--googletest/include/gtest/gtest_prod.h6
-rw-r--r--googletest/include/gtest/internal/custom/gtest-port.h6
-rw-r--r--googletest/include/gtest/internal/custom/gtest-printers.h6
-rw-r--r--googletest/include/gtest/internal/custom/gtest.h10
-rw-r--r--googletest/include/gtest/internal/gtest-death-test-internal.h6
-rw-r--r--googletest/include/gtest/internal/gtest-filepath.h8
-rw-r--r--googletest/include/gtest/internal/gtest-internal.h270
-rw-r--r--googletest/include/gtest/internal/gtest-param-util.h52
-rw-r--r--googletest/include/gtest/internal/gtest-port-arch.h9
-rw-r--r--googletest/include/gtest/internal/gtest-port.h206
-rw-r--r--googletest/include/gtest/internal/gtest-string.h9
-rw-r--r--googletest/include/gtest/internal/gtest-type-util.h48
-rw-r--r--googletest/samples/prime_tables.h12
-rw-r--r--googletest/samples/sample1.h6
-rw-r--r--googletest/samples/sample2.h7
-rw-r--r--googletest/samples/sample3-inl.h6
-rw-r--r--googletest/samples/sample4.h6
-rw-r--r--googletest/samples/sample6_unittest.cc7
-rwxr-xr-xgoogletest/scripts/release_docs.py2
-rw-r--r--googletest/src/gtest-death-test.cc63
-rw-r--r--googletest/src/gtest-filepath.cc41
-rw-r--r--googletest/src/gtest-internal-inl.h43
-rw-r--r--googletest/src/gtest-matchers.cc28
-rw-r--r--googletest/src/gtest-port.cc19
-rw-r--r--googletest/src/gtest-printers.cc197
-rw-r--r--googletest/src/gtest-typed-test.cc16
-rw-r--r--googletest/src/gtest.cc1037
-rw-r--r--googletest/test/Android.bp9
-rw-r--r--googletest/test/BUILD.bazel51
-rw-r--r--googletest/test/googletest-death-test-test.cc36
-rw-r--r--googletest/test/googletest-death-test_ex_test.cc2
-rwxr-xr-xgoogletest/test/googletest-env-var-test.py3
-rw-r--r--googletest/test/googletest-env-var-test_.cc10
-rwxr-xr-xgoogletest/test/googletest-failfast-unittest.py410
-rw-r--r--googletest/test/googletest-failfast-unittest_.cc167
-rw-r--r--[-rwxr-xr-x]googletest/test/googletest-global-environment-unittest.py (renamed from ci/log-config.sh)59
-rw-r--r--googletest/test/googletest-global-environment-unittest_.cc (renamed from googletest/test/googletest-test2_test.cc)55
-rw-r--r--googletest/test/googletest-json-output-unittest.py104
-rw-r--r--googletest/test/googletest-options-test.cc3
-rw-r--r--googletest/test/googletest-output-test-golden-lin.txt53
-rw-r--r--googletest/test/googletest-output-test_.cc81
-rw-r--r--googletest/test/googletest-param-test-test.cc36
-rw-r--r--googletest/test/googletest-param-test-test.h6
-rw-r--r--googletest/test/googletest-port-test.cc20
-rw-r--r--googletest/test/googletest-printers-test.cc387
-rw-r--r--googletest/test/googletest-shuffle-test_.cc2
-rw-r--r--googletest/test/gtest-typed-test2_test.cc4
-rw-r--r--googletest/test/gtest-typed-test_test.cc33
-rw-r--r--googletest/test/gtest-typed-test_test.h11
-rw-r--r--googletest/test/gtest-unittest-api_test.cc21
-rwxr-xr-xgoogletest/test/gtest_help_test.py4
-rw-r--r--googletest/test/gtest_list_output_unittest.py155
-rw-r--r--googletest/test/gtest_list_output_unittest_.cc26
-rwxr-xr-xgoogletest/test/gtest_test_utils.py4
-rw-r--r--googletest/test/gtest_unittest.cc494
-rwxr-xr-xgoogletest/test/gtest_xml_outfiles_test.py4
-rwxr-xr-xgoogletest/test/gtest_xml_output_unittest.py84
-rw-r--r--googletest/test/gtest_xml_output_unittest_.cc13
-rwxr-xr-xgoogletest/test/gtest_xml_test_utils.py9
-rw-r--r--googletest/test/production.h6
-rw-r--r--library.json4
-rw-r--r--platformio.ini47
183 files changed, 14740 insertions, 15755 deletions
diff --git a/.github/ISSUE_TEMPLATE/00-bug_report.md b/.github/ISSUE_TEMPLATE/00-bug_report.md
new file mode 100644
index 00000000..0f7e8b53
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/00-bug_report.md
@@ -0,0 +1,43 @@
+---
+name: Bug report
+about: Create a report to help us improve
+title: ''
+labels: 'bug'
+assignees: ''
+---
+
+**Describe the bug**
+
+Include a clear and concise description of what the problem is, including what
+you expected to happen, and what actually happened.
+
+**Steps to reproduce the bug**
+
+It's important that we are able to reproduce the problem that you are
+experiencing. Please provide all code and relevant steps to reproduce the
+problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links
+to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the
+problem are also helpful.
+
+**Does the bug persist in the most recent commit?**
+
+We recommend using the latest commit in the master branch in your projects.
+
+**What operating system and version are you using?**
+
+If you are using a Linux distribution please include the name and version of the
+distribution as well.
+
+**What compiler and version are you using?**
+
+Please include the output of `gcc -v` or `clang -v`, or the equivalent for your
+compiler.
+
+**What build system are you using?**
+
+Please include the output of `bazel --version` or `cmake --version`, or the
+equivalent for your build system.
+
+**Additional context**
+
+Add any other context about the problem here.
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 00000000..3ba13e0c
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1 @@
+blank_issues_enabled: false
diff --git a/.travis.yml b/.travis.yml
index 04b51dde..982e99c4 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -10,34 +10,31 @@ language: cpp
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
+ dist: bionic
compiler: gcc
install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh
- os: linux
- dist: xenial
+ dist: bionic
compiler: clang
install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh
- os: linux
+ dist: bionic
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
+ env: BUILD_TYPE=Debug CXX_FLAGS="-std=c++11 -Wdeprecated"
- os: linux
+ dist: bionic
compiler: clang
- env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 NO_EXCEPTION=ON NO_RTTI=ON COMPILER_IS_GNUCXX=ON
+ env: BUILD_TYPE=Release CXX_FLAGS="-std=c++11 -Wdeprecated" NO_EXCEPTION=ON NO_RTTI=ON COMPILER_IS_GNUCXX=ON
- os: osx
+ osx_image: xcode12.2
compiler: gcc
- env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
+ env: BUILD_TYPE=Release CC=gcc-10 CXX=g++-10 CXX_FLAGS="-std=c++11 -Wdeprecated" HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
- os: osx
+ osx_image: xcode12.2
compiler: clang
- env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
+ env: BUILD_TYPE=Release CXX_FLAGS="-std=c++11 -Wdeprecated" 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.
@@ -51,22 +48,13 @@ 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
+ - g++
+ - clang
update: true
homebrew:
packages:
- - ccache
- - gcc@4.9
- - llvm@4
+ - gcc@10
update: true
notifications:
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 00000000..8ecadf4c
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,44 @@
+//
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package {
+ default_applicable_licenses: ["external_googletest_license"],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+ name: "external_googletest_license",
+ visibility: [":__subpackages__"],
+ license_kinds: [
+ "SPDX-license-identifier-Apache-2.0",
+ "SPDX-license-identifier-BSD",
+ ],
+ license_text: [
+ "LICENSE",
+ ],
+}
diff --git a/BUILD.bazel b/BUILD.bazel
index 9b48aee5..14661b6a 100644
--- a/BUILD.bazel
+++ b/BUILD.bazel
@@ -36,9 +36,19 @@ package(default_visibility = ["//visibility:public"])
licenses(["notice"])
+exports_files(["LICENSE"])
+
config_setting(
name = "windows",
- constraint_values = ["@bazel_tools//platforms:windows"],
+ constraint_values = ["@platforms//os:windows"],
+)
+
+config_setting(
+ name = "msvc_compiler",
+ flag_values = {
+ "@bazel_tools//tools/cpp:compiler": "msvc-cl",
+ },
+ visibility = [":__subpackages__"],
)
config_setting(
@@ -46,6 +56,12 @@ config_setting(
values = {"define": "absl=1"},
)
+config_setting(
+ name = "ios",
+ values = {"apple_platform_type": "ios"},
+ visibility = [":__subpackages__"],
+)
+
# Library that defines the FRIEND_TEST macro.
cc_library(
name = "gtest_prod",
@@ -76,6 +92,10 @@ cc_library(
"googlemock/include/gmock/*.h",
]),
copts = select({
+ ":ios": [
+ "-xobjective-c++",
+ "-pthread",
+ ],
":windows": [],
"//conditions:default": ["-pthread"],
}),
@@ -103,6 +123,7 @@ cc_library(
"@com_google_absl//absl/debugging:stacktrace",
"@com_google_absl//absl/debugging:symbolize",
"@com_google_absl//absl/strings",
+ "@com_google_absl//absl/types:any",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:variant",
],
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 755b8b72..12fd7450 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,7 +1,7 @@
# Note: CMake support is community-based. The maintainers do not use CMake
# internally.
-cmake_minimum_required(VERSION 2.8.8)
+cmake_minimum_required(VERSION 2.8.12)
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
@@ -10,12 +10,8 @@ endif (POLICY CMP0048)
project(googletest-distribution)
set(GOOGLETEST_VERSION 1.10.0)
-if (CMAKE_VERSION VERSION_LESS "3.1")
- add_definitions(-std=c++11)
-else()
- set(CMAKE_CXX_STANDARD 11)
- set(CMAKE_CXX_STANDARD_REQUIRED ON)
- if(NOT CYGWIN AND NOT MSYS)
+if (CMAKE_VERSION VERSION_GREATER "3.0.2")
+ if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
set(CMAKE_CXX_EXTENSIONS OFF)
endif()
endif()
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index bd1843eb..da45e445 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -28,7 +28,7 @@ PR is acceptable as an alternative.
## Contributing A Patch
1. Submit an issue describing your proposed change to the
- [issue tracker](https://github.com/google/googletest).
+ [issue tracker](https://github.com/google/googletest/issues).
2. Please don't mix more than one logical change per submittal, because it
makes the history hard to follow. If you want to make a change that doesn't
have a corresponding issue in the issue tracker, please create one.
@@ -89,7 +89,7 @@ and their own tests from a git checkout, which has further requirements:
* [Python](https://www.python.org/) v2.3 or newer (for running some of the
tests and re-generating certain source files from templates)
-* [CMake](https://cmake.org/) v2.6.4 or newer
+* [CMake](https://cmake.org/) v2.8.12 or newer
## Developing Google Test and Google Mock
@@ -128,15 +128,3 @@ To run the tests, do
make test
All tests should pass.
-
-### Regenerating Source Files
-
-Some of Google Test's source files are generated from templates (not in the C++
-sense) using a script. For example, the file
-*googlemock/include/gmock/gmock-generated-actions.h.pump* is used to generate
-*gmock-generated-actions.h* in the same directory.
-
-You don't need to worry about regenerating the source files unless you need to
-modify them. You would then modify the corresponding `.pump` files and run the
-'[pump.py](googlemock/scripts/pump.py)' generator script. See the
-[Pump Manual](googlemock/docs/pump_manual.md).
diff --git a/googletest/CONTRIBUTORS b/CONTRIBUTORS
index 1e4afe21..76db0b40 100644
--- a/googletest/CONTRIBUTORS
+++ b/CONTRIBUTORS
@@ -5,34 +5,59 @@
Ajay Joshi <jaj@google.com>
Balázs Dán <balazs.dan@gmail.com>
+Benoit Sigoure <tsuna@google.com>
Bharat Mediratta <bharat@menalto.com>
+Bogdan Piloca <boo@google.com>
Chandler Carruth <chandlerc@google.com>
Chris Prince <cprince@google.com>
Chris Taylor <taylorc@google.com>
Dan Egnor <egnor@google.com>
+Dave MacLachlan <dmaclach@gmail.com>
+David Anderson <danderson@google.com>
+Dean Sturtevant
Eric Roman <eroman@chromium.org>
+Gene Volovich <gv@cite.com>
Hady Zalek <hady.zalek@gmail.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>
Jói Sigurðsson <joi@google.com>
Keir Mierle <mierle@gmail.com>
Keith Ray <keith.ray@gmail.com>
Kenton Varda <kenton@google.com>
+Kostya Serebryany <kcc@google.com>
Krystian Kuzniarek <krystian.kuzniarek@gmail.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>
Mika Raento <mikie@iki.fi>
+Mike Bland <mbland@google.com>
Miklós Fazekas <mfazekas@szemafor.com>
+Neal Norwitz <nnorwitz@gmail.com>
+Nermin Ozkiranartli <nermin@google.com>
+Owen Carlsen <ocarlsen@google.com>
+Paneendra Ba <paneendra@google.com>
Pasi Valminen <pasi.valminen@gmail.com>
Patrick Hanna <phanna@google.com>
Patrick Riley <pfr@google.com>
+Paul Menage <menage@google.com>
Peter Kaminski <piotrk@google.com>
+Piotr 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>
+Sverre Sundsdal <sundsdal@gmail.com>
+Takeshi Yoshino <tyoshino@google.com>
Tracy Bialik <tracy@pentad.com>
Vadim Berman <vadimb@google.com>
Vlad Losev <vladl@google.com>
+Wolfgang Klier <wklier@google.com>
Zhanyong Wan <wan@google.com>
diff --git a/METADATA b/METADATA
index 46c04b18..43071481 100644
--- a/METADATA
+++ b/METADATA
@@ -9,10 +9,11 @@ third_party {
type: GIT
value: "https://github.com/google/googletest.git"
}
- version: "306f3754a71d6d1ac644681d3544d06744914228"
+ version: "609281088cfefc76f9d0ce82e1ff6c30cc3591e5"
+ license_type: NOTICE
last_upgrade_date {
- year: 2020
- month: 1
- day: 8
+ year: 2021
+ month: 2
+ day: 16
}
}
diff --git a/README.md b/README.md
index e332e9a2..7d872a57 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,18 @@
-# Google Test
+# GoogleTest
-#### OSS Builds Status:
+### Announcements
-[![Build Status](https://api.travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest)
-[![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master)
+#### Live at Head
-### Announcements:
+GoogleTest now follows the
+[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
+We recommend using the latest commit in the `master` branch in your projects.
+
+#### Documentation Updates
+
+Our documentation is now live on GitHub Pages at
+https://google.github.io/googletest/. We recommend browsing the documentation on
+GitHub Pages rather than directly in the repository.
#### Release 1.10.x
@@ -14,30 +21,24 @@ is now available.
#### Coming Soon
-* Post 1.10.x googletest will follow
- [Abseil Live at Head philosophy](https://abseil.io/about/philosophy)
-* We are also planning to take a dependency on
+* We are planning to take a dependency on
[Abseil](https://github.com/abseil/abseil-cpp).
+* More documentation improvements are planned.
-## Welcome to **Google Test**, Google's C++ test framework!
+## Welcome to **GoogleTest**, Google's C++ test framework!
This repository is a merger of the formerly separate GoogleTest and GoogleMock
projects. These were so closely related that it makes sense to maintain and
release them together.
-Please subscribe to the mailing list at googletestframework@googlegroups.com for
-questions, discussions, and development.
-
-### Getting started:
+### Getting Started
-The information for **Google Test** is available in the
-[Google Test Primer](googletest/docs/primer.md) documentation.
+See the [GoogleTest User's Guide](https://google.github.io/googletest/) for
+documentation. We recommend starting with the
+[GoogleTest Primer](https://google.github.io/googletest/primer.html).
-**Google Mock** is an extension to Google Test for writing and using C++ mock
-classes. See the separate [Google Mock documentation](googlemock/README.md).
-
-More detailed documentation for googletest is in its interior
-[googletest/README.md](googletest/README.md) file.
+More information about building GoogleTest can be found at
+[googletest/README.md](googletest/README.md).
## Features
@@ -52,22 +53,45 @@ More detailed documentation for googletest is in its interior
* Various options for running the tests.
* XML test report generation.
-## Platforms
+## Supported Platforms
+
+GoogleTest requires a codebase and compiler compliant with the C++11 standard or
+newer.
-Google test has been used on a variety of platforms:
+The GoogleTest code is officially supported on the following platforms.
+Operating systems or tools not listed below are community-supported. For
+community-supported platforms, patches that do not complicate the code may be
+considered.
+
+If you notice any problems on your platform, please file an issue on the
+[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
+Pull requests containing fixes are welcome!
+
+### Operating Systems
* Linux
-* Mac OS X
+* macOS
* Windows
-* Cygwin
-* MinGW
-* Windows Mobile
-* Symbian
-* PlatformIO
-## Who Is Using Google Test?
+### Compilers
+
+* gcc 5.0+
+* clang 5.0+
+* MSVC 2015+
+
+**macOS users:** Xcode 9.3+ provides clang 5.0+.
+
+### Build Systems
-In addition to many internal projects at Google, Google Test is also used by the
+* [Bazel](https://bazel.build/)
+* [CMake](https://cmake.org/)
+
+**Note:** Bazel is the build system used by the team internally and in tests.
+CMake is supported on a best-effort basis and by the community.
+
+## Who Is Using GoogleTest?
+
+In addition to many internal projects at Google, GoogleTest is also used by the
following notable projects:
* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser
@@ -76,8 +100,6 @@ following notable projects:
* [Protocol Buffers](https://github.com/google/protobuf), Google's data
interchange format.
* The [OpenCV](http://opencv.org/) computer vision library.
-* [tiny-dnn](https://github.com/tiny-dnn/tiny-dnn): header only,
- dependency-free deep learning framework in C++11.
## Related Open Source Projects
@@ -85,13 +107,13 @@ following notable projects:
automated test-runner and Graphical User Interface with powerful features for
Windows and Linux platforms.
-[Google Test UI](https://github.com/ospector/gtest-gbar) is test runner that
+[GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that
runs your test binary, allows you to track its progress via a progress bar, and
displays a list of test failures. Clicking on one shows failure text. Google
Test UI is written in C#.
[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event
-listener for Google Test that implements the
+listener for GoogleTest that implements the
[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test
result output. If your test runner understands TAP, you may find it useful.
@@ -99,38 +121,20 @@ result output. If your test runner understands TAP, you may find it useful.
runs tests from your binary in parallel to provide significant speed-up.
[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter)
-is a VS Code extension allowing to view Google Tests in a tree view, and
-run/debug your tests.
+is a VS Code extension allowing to view GoogleTest in a tree view, and run/debug
+your tests.
-[Catch2 and Google Test Explorer](https://github.com/matepek/vscode-catch2-test-adapter)
-is a VS Code extension allowing to view Google Tests in a tree view, and
-run/debug your tests.
+[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS
+Code extension allowing to view GoogleTest in a tree view, and run/debug your
+tests.
[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser
-that generates stub code for Google Test.
-
-## Requirements
-
-Google Test is designed to have fairly minimal requirements to build and use
-with your projects, but there are some. If you notice any problems on your
-platform, please notify
-[googletestframework@googlegroups.com](https://groups.google.com/forum/#!forum/googletestframework).
-Patches for fixing them are welcome!
-
-### Build Requirements
-
-These are the base requirements to build and use Google Test from a source
-package:
-
-* [Bazel](https://bazel.build/) or [CMake](https://cmake.org/). NOTE: Bazel is
- the build system that googletest is using internally and tests against.
- CMake is community-supported.
-
-* a C++11-standard-compliant compiler
+that generates stub code for GoogleTest.
-## Contributing change
+## Contributing Changes
-Please read the [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on how to
-contribute to this project.
+Please read
+[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/master/CONTRIBUTING.md)
+for details on how to contribute to this project.
Happy testing!
diff --git a/TEST_MAPPING b/TEST_MAPPING
index c4002f27..8e6577df 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -2,6 +2,14 @@
"presubmit": [
{
"name": "gtest_isolated_tests"
+ },
+ {
+ // Confirm GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST behavior
+ "name": "VtsHalBluetoothA2dpV1_0TargetTest"
+ },
+ {
+ // Confirm VTS test can pass
+ "name": "VtsHalPowerStatsV1_0TargetTest"
}
]
}
diff --git a/WORKSPACE b/WORKSPACE
index 2289bdb7..3b445173 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -2,22 +2,29 @@ workspace(name = "com_google_googletest")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
-# Abseil
http_archive(
- name = "com_google_absl",
- urls = ["https://github.com/abseil/abseil-cpp/archive/master.zip"],
- strip_prefix = "abseil-cpp-master",
+ name = "com_google_absl", # 2020-10-13T16:49:13Z
+ sha256 = "00c3707bf9cd5eabd1ec6932cc65b97378c043f22573be3adf7d11bb7af17d06",
+ strip_prefix = "abseil-cpp-f3f785ab59478dd0312bf1b5df65d380650bf0dc",
+ urls = [
+ "https://github.com/abseil/abseil-cpp/archive/f3f785ab59478dd0312bf1b5df65d380650bf0dc.zip",
+ ],
)
http_archive(
- name = "rules_cc",
- strip_prefix = "rules_cc-master",
- urls = ["https://github.com/bazelbuild/rules_cc/archive/master.zip"],
+ name = "rules_cc", # 2020-10-05T06:01:24Z
+ sha256 = "35ea62c63cd71d4000efe85f9f4f17e8afb23896c37ee9510952db2e9d8fbb70",
+ strip_prefix = "rules_cc-f055da4ff0cb2b3c73de1fe2f094ebdfb8b3acb9",
+ urls = [
+ "https://github.com/bazelbuild/rules_cc/archive/f055da4ff0cb2b3c73de1fe2f094ebdfb8b3acb9.zip",
+ ],
)
http_archive(
- name = "rules_python",
- strip_prefix = "rules_python-master",
- urls = ["https://github.com/bazelbuild/rules_python/archive/master.zip"],
+ name = "rules_python", # 2020-09-30T13:50:21Z
+ sha256 = "6e49996ad3cf45b2232b8f94ca1e3ead369c28394c51632be8d85fe826383012",
+ strip_prefix = "rules_python-c064f7008a30f307ea7516cf52358a653011f82b",
+ urls = [
+ "https://github.com/bazelbuild/rules_python/archive/c064f7008a30f307ea7516cf52358a653011f82b.zip",
+ ],
)
-
diff --git a/appveyor.yml b/appveyor.yml
deleted file mode 100644
index ec155a76..00000000
--- a/appveyor.yml
+++ /dev/null
@@ -1,156 +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
- enabled_on_pr: yes
-
- - 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"
- enabled_on_pr: yes
-
- - 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
diff --git a/ci/build-linux-bazel.sh b/ci/build-linux-bazel.sh
deleted file mode 100755
index ae8fb758..00000000
--- a/ci/build-linux-bazel.sh
+++ /dev/null
@@ -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
diff --git a/ci/build-platformio.sh b/ci/build-platformio.sh
deleted file mode 100644
index 1d7658d8..00000000
--- a/ci/build-platformio.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-# run PlatformIO builds
-platformio run
diff --git a/ci/env-linux.sh b/ci/env-linux.sh
deleted file mode 100755
index 37800d6a..00000000
--- a/ci/env-linux.sh
+++ /dev/null
@@ -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
diff --git a/ci/env-osx.sh b/ci/env-osx.sh
deleted file mode 100755
index 9c421e14..00000000
--- a/ci/env-osx.sh
+++ /dev/null
@@ -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
diff --git a/ci/install-linux.sh b/ci/install-linux.sh
deleted file mode 100755
index 05e2cb28..00000000
--- a/ci/install-linux.sh
+++ /dev/null
@@ -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
diff --git a/ci/install-osx.sh b/ci/install-osx.sh
deleted file mode 100755
index cc475082..00000000
--- a/ci/install-osx.sh
+++ /dev/null
@@ -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
diff --git a/ci/install-platformio.sh b/ci/install-platformio.sh
deleted file mode 100644
index 4d7860a5..00000000
--- a/ci/install-platformio.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-# install PlatformIO
-sudo pip install -U platformio
-
-# update PlatformIO
-platformio update
diff --git a/ci/linux-presubmit.sh b/ci/linux-presubmit.sh
new file mode 100644
index 00000000..d02130c3
--- /dev/null
+++ b/ci/linux-presubmit.sh
@@ -0,0 +1,124 @@
+#!/bin/bash
+#
+# Copyright 2020, 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 -euox pipefail
+
+readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20201008"
+readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20201015"
+
+if [[ -z ${GTEST_ROOT:-} ]]; then
+ GTEST_ROOT="$(realpath $(dirname ${0})/..)"
+fi
+
+if [[ -z ${STD:-} ]]; then
+ STD="c++11 c++14 c++17 c++20"
+fi
+
+# Test the CMake build
+for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
+ for cmake_off_on in OFF ON; do
+ time docker run \
+ --volume="${GTEST_ROOT}:/src:ro" \
+ --tmpfs="/build:exec" \
+ --workdir="/build" \
+ --rm \
+ --env="CC=${cc}" \
+ --env="CXX_FLAGS=\"-Werror -Wdeprecated\"" \
+ ${LINUX_LATEST_CONTAINER} \
+ /bin/bash -c "
+ cmake /src \
+ -DCMAKE_CXX_STANDARD=11 \
+ -Dgtest_build_samples=ON \
+ -Dgtest_build_tests=ON \
+ -Dgmock_build_tests=ON \
+ -Dcxx_no_exception=${cmake_off_on} \
+ -Dcxx_no_rtti=${cmake_off_on} && \
+ make -j$(nproc) && \
+ ctest -j$(nproc) --output-on-failure"
+ done
+done
+
+# Do one test with an older version of GCC
+time docker run \
+ --volume="${GTEST_ROOT}:/src:ro" \
+ --workdir="/src" \
+ --rm \
+ --env="CC=/usr/local/bin/gcc" \
+ ${LINUX_GCC_FLOOR_CONTAINER} \
+ /usr/local/bin/bazel test ... \
+ --copt="-Wall" \
+ --copt="-Werror" \
+ --copt="-Wno-error=pragmas" \
+ --keep_going \
+ --show_timestamps \
+ --test_output=errors
+
+# Test GCC
+for std in ${STD}; do
+ for absl in 0 1; do
+ time docker run \
+ --volume="${GTEST_ROOT}:/src:ro" \
+ --workdir="/src" \
+ --rm \
+ --env="CC=/usr/local/bin/gcc" \
+ --env="BAZEL_CXXOPTS=-std=${std}" \
+ ${LINUX_LATEST_CONTAINER} \
+ /usr/local/bin/bazel test ... \
+ --copt="-Wall" \
+ --copt="-Werror" \
+ --define="absl=${absl}" \
+ --keep_going \
+ --show_timestamps \
+ --test_output=errors
+ done
+done
+
+# Test Clang
+for std in ${STD}; do
+ for absl in 0 1; do
+ time docker run \
+ --volume="${GTEST_ROOT}:/src:ro" \
+ --workdir="/src" \
+ --rm \
+ --env="CC=/opt/llvm/clang/bin/clang" \
+ --env="BAZEL_CXXOPTS=-std=${std}" \
+ ${LINUX_LATEST_CONTAINER} \
+ /usr/local/bin/bazel test ... \
+ --copt="--gcc-toolchain=/usr/local" \
+ --copt="-Wall" \
+ --copt="-Werror" \
+ --define="absl=${absl}" \
+ --keep_going \
+ --linkopt="--gcc-toolchain=/usr/local" \
+ --show_timestamps \
+ --test_output=errors
+ done
+done
diff --git a/ci/get-nprocessors.sh b/ci/macos-presubmit.sh
index 43635e76..d6423faa 100755..100644
--- a/ci/get-nprocessors.sh
+++ b/ci/macos-presubmit.sh
@@ -1,7 +1,7 @@
-#!/usr/bin/env bash
-# Copyright 2017 Google Inc.
-# All Rights Reserved.
+#!/bin/bash
#
+# Copyright 2020, 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
@@ -29,20 +29,45 @@
# (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
+set -euox pipefail
+
+if [[ -z ${GTEST_ROOT:-} ]]; then
+ GTEST_ROOT="$(realpath $(dirname ${0})/..)"
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
+# Test the CMake build
+for cmake_off_on in OFF ON; do
+ BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)
+ cd ${BUILD_DIR}
+ time cmake ${GTEST_ROOT} \
+ -DCMAKE_CXX_STANDARD=11 \
+ -Dgtest_build_samples=ON \
+ -Dgtest_build_tests=ON \
+ -Dgmock_build_tests=ON \
+ -Dcxx_no_exception=${cmake_off_on} \
+ -Dcxx_no_rtti=${cmake_off_on}
+ time make
+ time ctest -j$(nproc) --output-on-failure
+done
+
+# Test the Bazel build
+
+# If we are running on Kokoro, check for a versioned Bazel binary.
+KOKORO_GFILE_BAZEL_BIN="bazel-3.7.0-darwin-x86_64"
+if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then
+ BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}"
+ chmod +x ${BAZEL_BIN}
+else
+ BAZEL_BIN="bazel"
fi
+
+cd ${GTEST_ROOT}
+for absl in 0 1; do
+ ${BAZEL_BIN} test ... \
+ --copt="-Wall" \
+ --copt="-Werror" \
+ --define="absl=${absl}" \
+ --keep_going \
+ --show_timestamps \
+ --test_output=errors
+done
diff --git a/ci/travis.sh b/ci/travis.sh
deleted file mode 100755
index 9ff3bad3..00000000
--- a/ci/travis.sh
+++ /dev/null
@@ -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
diff --git a/docs/_config.yml b/docs/_config.yml
new file mode 100644
index 00000000..d12867ea
--- /dev/null
+++ b/docs/_config.yml
@@ -0,0 +1 @@
+title: GoogleTest
diff --git a/docs/_data/navigation.yml b/docs/_data/navigation.yml
new file mode 100644
index 00000000..fdde2834
--- /dev/null
+++ b/docs/_data/navigation.yml
@@ -0,0 +1,35 @@
+nav:
+- section: "Get Started"
+ items:
+ - title: "Supported Platforms"
+ url: "/platforms.html"
+ - title: "Quickstart: Bazel"
+ url: "/quickstart-bazel.html"
+ - title: "Quickstart: CMake"
+ url: "/quickstart-cmake.html"
+- section: "Guides"
+ items:
+ - title: "GoogleTest Primer"
+ url: "/primer.html"
+ - title: "Advanced Topics"
+ url: "/advanced.html"
+ - title: "Mocking for Dummies"
+ url: "/gmock_for_dummies.html"
+ - title: "Mocking Cookbook"
+ url: "/gmock_cook_book.html"
+ - title: "Mocking Cheat Sheet"
+ url: "/gmock_cheat_sheet.html"
+- section: "References"
+ items:
+ - title: "Matchers"
+ url: "/reference/matchers.html"
+ - title: "Testing FAQ"
+ url: "/faq.html"
+ - title: "Mocking FAQ"
+ url: "/gmock_faq.html"
+ - title: "Code Samples"
+ url: "/samples.html"
+ - title: "Using pkg-config"
+ url: "/pkgconfig.html"
+ - title: "Community Documentation"
+ url: "/community_created_documentation.html"
diff --git a/docs/_layouts/default.html b/docs/_layouts/default.html
new file mode 100644
index 00000000..731042f1
--- /dev/null
+++ b/docs/_layouts/default.html
@@ -0,0 +1,53 @@
+<!DOCTYPE html>
+<html lang="{{ site.lang | default: "en-US" }}">
+ <head>
+ <meta charset="UTF-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+
+{% seo %}
+ <link rel="stylesheet" href="{{ "/assets/css/style.css?v=" | append: site.github.build_revision | relative_url }}">
+ </head>
+ <body>
+ <div class="sidebar">
+ <div class="header">
+ <h1><a href="{{ "/" | relative_url }}">{{ site.title | default: "Documentation" }}</a></h1>
+ </div>
+ <input type="checkbox" id="nav-toggle" class="nav-toggle">
+ <label for="nav-toggle" class="expander">
+ <span class="arrow"></span>
+ </label>
+ <nav>
+ {% for item in site.data.navigation.nav %}
+ <h2>{{ item.section }}</h2>
+ <ul>
+ {% for subitem in item.items %}
+ <a href="{{subitem.url | relative_url }}">
+ <li class="{% if subitem.url == page.url %}active{% endif %}">
+ {{ subitem.title }}
+ </li>
+ </a>
+ {% endfor %}
+ </ul>
+ {% endfor %}
+ </nav>
+ </div>
+ <div class="main markdown-body">
+ <div class="main-inner">
+ {{ content }}
+ </div>
+ </div>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/4.1.0/anchor.min.js" integrity="sha256-lZaRhKri35AyJSypXXs4o6OPFTbTmUoltBbDCbdzegg=" crossorigin="anonymous"></script>
+ <script>anchors.add('.main h2, .main h3, .main h4, .main h5, .main h6');</script>
+ {% if site.google_analytics %}
+ <script>
+ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
+ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
+ m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
+ })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
+ ga('create', '{{ site.google_analytics }}', 'auto');
+ ga('send', 'pageview');
+ </script>
+ {% endif %}
+ </body>
+</html>
diff --git a/docs/_sass/main.scss b/docs/_sass/main.scss
new file mode 100644
index 00000000..91e633bb
--- /dev/null
+++ b/docs/_sass/main.scss
@@ -0,0 +1,193 @@
+// Styles for GoogleTest docs website on GitHub Pages.
+// Color variables are defined in
+// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables
+
+$sidebar-width: 260px;
+
+body {
+ display: flex;
+ margin: 0;
+}
+
+.sidebar {
+ background: $black;
+ color: $text-white;
+ flex-shrink: 0;
+ height: 100vh;
+ overflow: auto;
+ position: sticky;
+ top: 0;
+ width: $sidebar-width;
+}
+
+.sidebar h1 {
+ font-size: 1.5em;
+}
+
+.sidebar h2 {
+ color: $gray-light;
+ font-size: 0.8em;
+ font-weight: normal;
+ margin-bottom: 0.8em;
+ padding-left: 2.5em;
+ text-transform: uppercase;
+}
+
+.sidebar .header {
+ background: $black;
+ padding: 2em;
+ position: sticky;
+ top: 0;
+ width: 100%;
+}
+
+.sidebar .header a {
+ color: $text-white;
+ text-decoration: none;
+}
+
+.sidebar .nav-toggle {
+ display: none;
+}
+
+.sidebar .expander {
+ cursor: pointer;
+ display: none;
+ height: 3em;
+ position: absolute;
+ right: 1em;
+ top: 1.5em;
+ width: 3em;
+}
+
+.sidebar .expander .arrow {
+ border: solid white;
+ border-width: 0 3px 3px 0;
+ display: block;
+ height: 0.7em;
+ margin: 1em auto;
+ transform: rotate(45deg);
+ transition: transform 0.5s;
+ width: 0.7em;
+}
+
+.sidebar nav {
+ width: 100%;
+}
+
+.sidebar nav ul {
+ list-style-type: none;
+ margin-bottom: 1em;
+ padding: 0;
+
+ &:last-child {
+ margin-bottom: 2em;
+ }
+
+ a {
+ text-decoration: none;
+ }
+
+ li {
+ color: $text-white;
+ padding-left: 2em;
+ text-decoration: none;
+ }
+
+ li.active {
+ background: $border-gray-darker;
+ font-weight: bold;
+ }
+
+ li:hover {
+ background: $border-gray-darker;
+ }
+}
+
+.main {
+ width: calc(100% - #{$sidebar-width});
+}
+
+.main .main-inner {
+ margin: 2em;
+}
+
+.main table th {
+ text-align: left;
+}
+
+.main .callout {
+ border-left: 0.25em solid white;
+ padding: 1em;
+
+ a {
+ text-decoration: underline;
+ }
+
+ &.important {
+ background-color: $bg-yellow-light;
+ border-color: $bg-yellow;
+ color: $black;
+ }
+
+ &.note {
+ background-color: $bg-blue-light;
+ border-color: $text-blue;
+ color: $text-blue;
+ }
+
+ &.tip {
+ background-color: $green-000;
+ border-color: $green-700;
+ color: $green-700;
+ }
+
+ &.warning {
+ background-color: $red-000;
+ border-color: $text-red;
+ color: $text-red;
+ }
+}
+
+.main .good pre {
+ background-color: $bg-green-light;
+}
+
+.main .bad pre {
+ background-color: $red-000;
+}
+
+@media all and (max-width: 768px) {
+ body {
+ flex-direction: column;
+ }
+
+ .sidebar {
+ height: auto;
+ position: relative;
+ width: 100%;
+ }
+
+ .sidebar .expander {
+ display: block;
+ }
+
+ .sidebar nav {
+ height: 0;
+ overflow: hidden;
+ }
+
+ .sidebar .nav-toggle:checked {
+ & ~ nav {
+ height: auto;
+ }
+
+ & + .expander .arrow {
+ transform: rotate(-135deg);
+ }
+ }
+
+ .main {
+ width: 100%;
+ }
+}
diff --git a/googletest/docs/advanced.md b/docs/advanced.md
index 10af769e..0fe7b8e1 100644
--- a/googletest/docs/advanced.md
+++ b/docs/advanced.md
@@ -1,7 +1,5 @@
# Advanced googletest Topics
-<!-- GOOGLETEST_CM0016 DO NOT DELETE -->
-
## Introduction
Now that you have read the [googletest Primer](primer.md) and learned how to
@@ -28,6 +26,7 @@ SUCCEED();
Generates a success. This does **NOT** make the overall test succeed. A test is
considered successful only if none of its assertions fail during its execution.
+{: .callout .note}
NOTE: `SUCCEED()` is purely documentary and currently doesn't generate any
user-visible output. However, we may add `SUCCEED()` messages to googletest's
output in the future.
@@ -54,6 +53,7 @@ switch(expression) {
}
```
+{: .callout .note}
NOTE: you can only use `FAIL()` in functions that return `void`. See the
[Assertion Placement section](#assertion-placement) for more information.
@@ -101,7 +101,6 @@ If you already have a function or functor that returns `bool` (or a type that
can be implicitly converted to `bool`), you can use it in a *predicate
assertion* to get the function arguments printed for free:
-<!-- mdformat off(github rendering does not support multiline tables) -->
| Fatal assertion | Nonfatal assertion | Verifies |
| --------------------------------- | --------------------------------- | --------------------------- |
@@ -109,7 +108,6 @@ assertion* to get the function arguments printed for free:
| `ASSERT_PRED2(pred2, val1, val2)` | `EXPECT_PRED2(pred2, val1, val2)` | `pred2(val1, val2)` is true |
| `...` | `...` | `...` |
-<!-- mdformat on-->
In the above, `predn` is an `n`-ary predicate function or functor, where `val1`,
`val2`, ..., and `valn` are its arguments. The assertion succeeds if the
predicate returns `true` when applied to the given arguments, and fails
@@ -147,11 +145,12 @@ b is 4
c is 10
```
+{: .callout .note}
> NOTE:
>
> 1. If you see a compiler error "no matching function to call" when using
> `ASSERT_PRED*` or `EXPECT_PRED*`, please see
-> [this](faq.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert-pred-how-do-i-fix-it)
+> [this](faq.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_pred-how-do-i-fix-it)
> for how to resolve it.
#### Using a Function That Returns an AssertionResult
@@ -187,11 +186,11 @@ write a predicate function that returns `AssertionResult` instead of `bool`. For
example, if you define `IsEven()` as:
```c++
-::testing::AssertionResult IsEven(int n) {
+testing::AssertionResult IsEven(int n) {
if ((n % 2) == 0)
- return ::testing::AssertionSuccess();
+ return testing::AssertionSuccess();
else
- return ::testing::AssertionFailure() << n << " is odd";
+ return testing::AssertionFailure() << n << " is odd";
}
```
@@ -225,11 +224,11 @@ are fine with making the predicate slower in the success case, you can supply a
success message:
```c++
-::testing::AssertionResult IsEven(int n) {
+testing::AssertionResult IsEven(int n) {
if ((n % 2) == 0)
- return ::testing::AssertionSuccess() << n << " is even";
+ return testing::AssertionSuccess() << n << " is even";
else
- return ::testing::AssertionFailure() << n << " is odd";
+ return testing::AssertionFailure() << n << " is odd";
}
```
@@ -260,14 +259,14 @@ a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a *predicate-formatter*
(`pred_formatn`), which is a function or functor with the signature:
```c++
-::testing::AssertionResult PredicateFormattern(const char* expr1,
- const char* expr2,
- ...
- const char* exprn,
- T1 val1,
- T2 val2,
- ...
- Tn valn);
+testing::AssertionResult PredicateFormattern(const char* expr1,
+ const char* expr2,
+ ...
+ const char* exprn,
+ T1 val1,
+ T2 val2,
+ ...
+ Tn valn);
```
where `val1`, `val2`, ..., and `valn` are the values of the predicate arguments,
@@ -285,13 +284,13 @@ used with `EXPECT_PRED2()`:
int SmallestPrimeCommonDivisor(int m, int n) { ... }
// A predicate-formatter for asserting that two integers are mutually prime.
-::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
- const char* n_expr,
- int m,
- int n) {
- if (MutuallyPrime(m, n)) return ::testing::AssertionSuccess();
+testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
+ const char* n_expr,
+ int m,
+ int n) {
+ if (MutuallyPrime(m, n)) return testing::AssertionSuccess();
- return ::testing::AssertionFailure() << m_expr << " and " << n_expr
+ return testing::AssertionFailure() << m_expr << " and " << n_expr
<< " (" << m << " and " << n << ") are not mutually prime, "
<< "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n);
}
@@ -331,26 +330,22 @@ want to learn more, see
#### Floating-Point Macros
-<!-- mdformat off(github rendering does not support multiline tables) -->
| Fatal assertion | Nonfatal assertion | Verifies |
| ------------------------------- | ------------------------------- | ---------------------------------------- |
| `ASSERT_FLOAT_EQ(val1, val2);` | `EXPECT_FLOAT_EQ(val1, val2);` | the two `float` values are almost equal |
| `ASSERT_DOUBLE_EQ(val1, val2);` | `EXPECT_DOUBLE_EQ(val1, val2);` | the two `double` values are almost equal |
-<!-- mdformat on-->
By "almost equal" we mean the values are within 4 ULP's from each other.
The following assertions allow you to choose the acceptable error bound:
-<!-- mdformat off(github rendering does not support multiline tables) -->
| Fatal assertion | Nonfatal assertion | Verifies |
| ------------------------------------- | ------------------------------------- | -------------------------------------------------------------------------------- |
| `ASSERT_NEAR(val1, val2, abs_error);` | `EXPECT_NEAR(val1, val2, abs_error);` | the difference between `val1` and `val2` doesn't exceed the given absolute error |
-<!-- mdformat on-->
#### Floating-Point Predicate-Format Functions
@@ -360,8 +355,8 @@ that can be used in predicate assertion macros (e.g. `EXPECT_PRED_FORMAT2`,
etc).
```c++
-EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2);
-EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
+EXPECT_PRED_FORMAT2(testing::FloatLE, val1, val2);
+EXPECT_PRED_FORMAT2(testing::DoubleLE, val1, val2);
```
Verifies that `val1` is less than, or almost equal to, `val2`. You can replace
@@ -369,17 +364,15 @@ Verifies that `val1` is less than, or almost equal to, `val2`. You can replace
### Asserting Using gMock Matchers
-[gMock](../../googlemock) comes with a library of matchers for validating
-arguments passed to mock objects. A gMock *matcher* is basically a predicate
-that knows how to describe itself. It can be used in these assertion macros:
+gMock comes with a library of *matchers* for validating arguments passed to mock
+objects. A gMock matcher is basically a predicate that knows how to describe
+itself. It can be used in these assertion macros:
-<!-- mdformat off(github rendering does not support multiline tables) -->
| Fatal assertion | Nonfatal assertion | Verifies |
| ------------------------------ | ------------------------------ | --------------------- |
| `ASSERT_THAT(value, matcher);` | `EXPECT_THAT(value, matcher);` | value matches matcher |
-<!-- mdformat on-->
For example, `StartsWith(prefix)` is a matcher that matches a string starting
with `prefix`, and you can write:
@@ -391,17 +384,14 @@ using ::testing::StartsWith;
EXPECT_THAT(Foo(), StartsWith("Hello"));
```
-Read this
-[recipe](../../googlemock/docs/cook_book.md#using-matchers-in-googletest-assertions)
-in the gMock Cookbook for more details.
-
-gMock has a rich set of matchers. You can do many things googletest cannot do
-alone with them. For a list of matchers gMock provides, read
-[this](../../googlemock/docs/cook_book.md##using-matchers). It's easy to write
-your [own matchers](../../googlemock/docs/cook_book.md#NewMatchers) too.
+See
+[Using Matchers in googletest Assertions](gmock_cook_book.md#using-matchers-in-googletest-assertions)
+in the gMock Cookbook for more details. For a list of built-in matchers, see the
+[Matchers Reference](reference/matchers.md). You can also write your own
+matchers—see [Writing New Matchers Quickly](gmock_cook_book.md#NewMatchers).
gMock is bundled with googletest, so you don't need to add any build dependency
-in order to take advantage of this. Just include `"testing/base/public/gmock.h"`
+in order to take advantage of this. Just include `"gmock/gmock.h"`
and you're ready to go.
### More String Assertions
@@ -409,9 +399,8 @@ and you're ready to go.
(Please read the [previous](#asserting-using-gmock-matchers) section first if
you haven't.)
-You can use the gMock
-[string matchers](../../googlemock/docs/cheat_sheet.md#string-matchers) with
-`EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks
+You can use the gMock [string matchers](reference/matchers.md#string-matchers)
+with `EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks
(sub-string, prefix, suffix, regular expression, and etc). For example,
```c++
@@ -429,7 +418,7 @@ its DOM tree matches an
```c++
// Currently still in //template/prototemplate/testing:xpath_matcher
#include "template/prototemplate/testing/xpath_matcher.h"
-using prototemplate::testing::MatchesXPath;
+using ::prototemplate::testing::MatchesXPath;
EXPECT_THAT(html_string, MatchesXPath("//a[text()='click here']"));
```
@@ -476,7 +465,7 @@ instantiated. For example, given:
```c++
template <typename T> class Foo {
public:
- void Bar() { ::testing::StaticAssertTypeEq<int, T>(); }
+ void Bar() { testing::StaticAssertTypeEq<int, T>(); }
};
```
@@ -516,6 +505,7 @@ any assertion inside of it.
If changing the function's type is not an option, you should just use assertions
that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`.
+{: .callout .note}
NOTE: Constructors and destructors are not considered void-returning functions,
according to the C++ language specification, and so you may not use fatal
assertions in them; you'll get a compilation error if you try. Instead, either
@@ -523,13 +513,46 @@ call `abort` and crash the entire test executable, or put the fatal assertion in
a `SetUp`/`TearDown` function; see
[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp)
+{: .callout .warning}
WARNING: A fatal assertion in a helper function (private void-returning method)
-called from a constructor or destructor does not does not terminate the current
-test, as your intuition might suggest: it merely returns from the constructor or
+called from a constructor or destructor does not terminate the current test, as
+your intuition might suggest: it merely returns from the constructor or
destructor early, possibly leaving your object in a partially-constructed or
partially-destructed state! You almost certainly want to `abort` or use
`SetUp`/`TearDown` instead.
+## Skipping test execution
+
+Related to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test
+execution at runtime with the `GTEST_SKIP()` macro. This is useful when you need
+to check for preconditions of the system under test during runtime and skip
+tests in a meaningful way.
+
+`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods
+of classes derived from either `::testing::Environment` or `::testing::Test`.
+For example:
+
+```c++
+TEST(SkipTest, DoesSkip) {
+ GTEST_SKIP() << "Skipping single test";
+ EXPECT_EQ(0, 1); // Won't fail; it won't be executed
+}
+
+class SkipFixture : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ GTEST_SKIP() << "Skipping all tests for this fixture";
+ }
+};
+
+// Tests for SkipFixture won't be executed.
+TEST_F(SkipFixture, SkipsOneTest) {
+ EXPECT_EQ(5, 7); // Won't fail
+}
+```
+
+As with assertion macros, you can stream a custom message into `GTEST_SKIP()`.
+
## Teaching googletest How to Print Your Values
When a test assertion such as `EXPECT_EQ` fails, googletest prints the argument
@@ -605,7 +628,7 @@ call `::testing::PrintToString(x)`, which returns an `std::string`:
vector<pair<Bar, int> > bar_ints = GetBarIntVector();
EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
- << "bar_ints = " << ::testing::PrintToString(bar_ints);
+ << "bar_ints = " << testing::PrintToString(bar_ints);
```
## Death Tests
@@ -638,6 +661,7 @@ Fatal assertion | Nonfatal assertion
------------------------------------------------ | ------------------------------------------------ | --------
`ASSERT_DEATH(statement, matcher);` | `EXPECT_DEATH(statement, matcher);` | `statement` crashes with the given error
`ASSERT_DEATH_IF_SUPPORTED(statement, matcher);` | `EXPECT_DEATH_IF_SUPPORTED(statement, matcher);` | if death tests are supported, verifies that `statement` crashes with the given error; otherwise verifies nothing
+`ASSERT_DEBUG_DEATH(statement, matcher);` | `EXPECT_DEBUG_DEATH(statement, matcher);` | `statement` crashes with the given error **in debug mode**. When not in debug (i.e. `NDEBUG` is defined), this just executes `statement`
`ASSERT_EXIT(statement, predicate, matcher);` | `EXPECT_EXIT(statement, predicate, matcher);` | `statement` exits with the given error, and its exit code matches `predicate`
where `statement` is a statement that is expected to cause the process to die,
@@ -652,6 +676,7 @@ to be an expression.
As usual, the `ASSERT` variants abort the current test function, while the
`EXPECT` variants do not.
+{: .callout .note}
> NOTE: We use the word "crash" here to mean that the process terminates with a
> *non-zero* exit status code. There are two possibilities: either the process
> has called `exit()` or `_exit()` with a non-zero value, or it may be killed by
@@ -673,7 +698,7 @@ This expression is `true` if the program exited normally with the given exit
code.
```c++
-::testing::KilledBySignal(signal_number) // Not available on Windows.
+testing::KilledBySignal(signal_number) // Not available on Windows.
```
This expression is `true` if the program was killed by the given signal.
@@ -706,11 +731,11 @@ TEST(MyDeathTest, Foo) {
}
TEST(MyDeathTest, NormalExit) {
- EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success");
+ EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success");
}
TEST(MyDeathTest, KillMyself) {
- EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL),
+ EXPECT_EXIT(KillMyself(), testing::KilledBySignal(SIGKILL),
"Sending myself unblockable signal");
}
```
@@ -727,6 +752,7 @@ necessary.
### Death Test Naming
+{: .callout .important}
IMPORTANT: We strongly recommend you to follow the convention of naming your
**test suite** (not test) `*DeathTest` when it contains a death test, as
demonstrated in the above example. The
@@ -737,7 +763,7 @@ If a test fixture class is shared by normal tests and death tests, you can use
duplicating its code:
```c++
-class FooTest : public ::testing::Test { ... };
+class FooTest : public testing::Test { ... };
using FooDeathTest = FooTest;
@@ -797,7 +823,7 @@ limited syntax only.
Under the hood, `ASSERT_EXIT()` spawns a new process and executes the death test
statement in that process. The details of how precisely that happens depend on
-the platform and the variable ::testing::GTEST_FLAG(death_test_style) (which is
+the platform and the variable `::testing::GTEST_FLAG(death_test_style)` (which is
initialized from the command-line flag `--gtest_death_test_style`).
* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the
@@ -813,7 +839,8 @@ initialized from the command-line flag `--gtest_death_test_style`).
consideration to be run - much like the `threadsafe` mode on POSIX.
Other values for the variable are illegal and will cause the death test to fail.
-Currently, the flag's default value is **"fast"**
+Currently, the flag's default value is
+**`"fast"`**.
1. the child's exit status satisfies the predicate, and
2. the child's stderr matches the regular expression.
@@ -862,13 +889,13 @@ restored afterwards, so you need not do that yourself. For example:
```c++
int main(int argc, char** argv) {
- InitGoogle(argv[0], &argc, &argv, true);
- ::testing::FLAGS_gtest_death_test_style = "fast";
+ testing::InitGoogleTest(&argc, argv);
+ testing::FLAGS_gtest_death_test_style = "fast";
return RUN_ALL_TESTS();
}
TEST(MyDeathTest, TestOne) {
- ::testing::FLAGS_gtest_death_test_style = "threadsafe";
+ testing::FLAGS_gtest_death_test_style = "threadsafe";
// This test is run in the "threadsafe" style:
ASSERT_DEATH(ThisShouldDie(), "");
}
@@ -908,6 +935,13 @@ handlers registered with `pthread_atfork(3)`.
## Using Assertions in Sub-routines
+{: .callout .note}
+Note: If you want to put a series of test assertions in a subroutine to check
+for a complex condition, consider using
+[a custom GMock matcher](gmock_cook_book.md#NewMatchers)
+instead. This lets you provide a more readable error message in case of failure
+and avoid all of the issues described below.
+
### Adding Traces to Assertions
If a test sub-routine is called from several places, when an assertion inside it
@@ -955,7 +989,7 @@ path/to/foo_test.cc:11: Failure
Value of: Bar(n)
Expected: 1
Actual: 2
- Trace:
+Google Test trace:
path/to/foo_test.cc:17: A
path/to/foo_test.cc:12: Failure
@@ -1005,7 +1039,7 @@ TEST(FooTest, Bar) {
// in Subroutine() to abort the entire test.
// The actual behavior: the function goes on after Subroutine() returns.
- int* p = NULL;
+ int* p = nullptr;
*p = 3; // Segfault!
}
```
@@ -1099,7 +1133,7 @@ If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test
fixture, you must add the `::testing::Test::` prefix, as in:
```c++
-if (::testing::Test::HasFatalFailure()) return;
+if (testing::Test::HasFatalFailure()) return;
```
Similarly, `HasNonfatalFailure()` returns `true` if the current test has at
@@ -1129,6 +1163,7 @@ will output XML like this:
...
```
+{: .callout .note}
> NOTE:
>
> * `RecordProperty()` is a static member of the `Test` class. Therefore it
@@ -1178,7 +1213,7 @@ state to its original value before passing control to the next test.
Here's an example of per-test-suite set-up and tear-down:
```c++
-class FooTest : public ::testing::Test {
+class FooTest : public testing::Test {
protected:
// Per-test-suite set-up.
// Called before the first test in this test suite.
@@ -1192,20 +1227,20 @@ class FooTest : public ::testing::Test {
// Can be omitted if not needed.
static void TearDownTestSuite() {
delete shared_resource_;
- shared_resource_ = NULL;
+ shared_resource_ = nullptr;
}
// You can define per-test set-up logic as usual.
- virtual void SetUp() { ... }
+ void SetUp() override { ... }
// You can define per-test tear-down logic as usual.
- virtual void TearDown() { ... }
+ void TearDown() override { ... }
// Some expensive resource shared by all tests.
static T* shared_resource_;
};
-T* FooTest::shared_resource_ = NULL;
+T* FooTest::shared_resource_ = nullptr;
TEST_F(FooTest, Test1) {
... you can refer to shared_resource_ here ...
@@ -1216,6 +1251,7 @@ TEST_F(FooTest, Test2) {
}
```
+{: .callout .note}
NOTE: Though the above code declares `SetUpTestSuite()` protected, it may
sometimes be necessary to declare it public, such as when using it with
`TEST_P`.
@@ -1267,8 +1303,8 @@ probably in `main()`. If you use `gtest_main`, you need to call this before
variable like this:
```c++
-::testing::Environment* const foo_env =
- ::testing::AddGlobalTestEnvironment(new FooEnvironment);
+testing::Environment* const foo_env =
+ testing::AddGlobalTestEnvironment(new FooEnvironment);
```
However, we strongly recommend you to write your own `main()` and call
@@ -1303,6 +1339,7 @@ and `testing::WithParamInterface<T>`. `T` can be any copyable type. If it's a
raw pointer, you are responsible for managing the lifespan of the pointed
values.
+{: .callout .note}
NOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()`
they must be declared **public** rather than **protected** in order to use
`TEST_P`.
@@ -1348,7 +1385,6 @@ for generating test parameters. They return what we call (surprise!) *parameter
generators*. Here is a summary of them, which are all in the `testing`
namespace:
-<!-- mdformat off(github rendering does not support multiline tables) -->
| Parameter Generator | Behavior |
| ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
@@ -1358,7 +1394,6 @@ namespace:
| `Bool()` | Yields sequence `{false, true}`. |
| `Combine(g1, g2, ..., gN)` | Yields all combinations (Cartesian product) as std\:\:tuples of the values generated by the `N` generators. |
-<!-- mdformat on-->
For more details, see the comments at the definitions of these functions.
@@ -1366,56 +1401,67 @@ The following statement will instantiate tests from the `FooTest` test suite
each with parameter values `"meeny"`, `"miny"`, and `"moe"`.
```c++
-INSTANTIATE_TEST_SUITE_P(InstantiationName,
+INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe,
FooTest,
testing::Values("meeny", "miny", "moe"));
```
+{: .callout .note}
NOTE: The code above must be placed at global or namespace scope, not at
function scope.
-NOTE: Don't forget this step! If you do your test will silently pass, but none
-of its suites will ever run!
+The first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the
+instantiation of the test suite. The next argument is the name of the test
+pattern, and the last is the parameter generator.
-To distinguish different instances of the pattern (yes, you can instantiate it
-more than once), the first argument to `INSTANTIATE_TEST_SUITE_P` is a prefix
-that will be added to the actual test suite name. Remember to pick unique
-prefixes for different instantiations. The tests from the instantiation above
-will have these names:
+You can instantiate a test pattern more than once, so to distinguish different
+instances of the pattern, the instantiation name is added as a prefix to the
+actual test suite name. Remember to pick unique prefixes for different
+instantiations. The tests from the instantiation above will have these names:
-* `InstantiationName/FooTest.DoesBlah/0` for `"meeny"`
-* `InstantiationName/FooTest.DoesBlah/1` for `"miny"`
-* `InstantiationName/FooTest.DoesBlah/2` for `"moe"`
-* `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"`
-* `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"`
-* `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"`
+* `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"`
+* `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"`
+* `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"`
+* `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"`
+* `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"`
+* `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"`
You can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests).
-This statement will instantiate all tests from `FooTest` again, each with
-parameter values `"cat"` and `"dog"`:
+The following statement will instantiate all tests from `FooTest` again, each
+with parameter values `"cat"` and `"dog"`:
```c++
const char* pets[] = {"cat", "dog"};
-INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest,
- testing::ValuesIn(pets));
+INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets));
```
The tests from the instantiation above will have these names:
-* `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"`
-* `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"`
-* `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"`
-* `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"`
+* `Pets/FooTest.DoesBlah/0` for `"cat"`
+* `Pets/FooTest.DoesBlah/1` for `"dog"`
+* `Pets/FooTest.HasBlahBlah/0` for `"cat"`
+* `Pets/FooTest.HasBlahBlah/1` for `"dog"`
Please note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the
given test suite, whether their definitions come before or *after* the
`INSTANTIATE_TEST_SUITE_P` statement.
+Additionally, by default, every `TEST_P` without a corresponding
+`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite
+`GoogleTestVerification`. If you have a test suite where that omission is not an
+error, for example it is in a library that may be linked in for other reasons or
+where the list of test cases is dynamic and may be empty, then this check can be
+suppressed by tagging the test suite:
+
+```c++
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);
+```
+
You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples.
-[sample7_unittest.cc]: ../samples/sample7_unittest.cc "Parameterized Test example"
-[sample8_unittest.cc]: ../samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
+[sample7_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample7_unittest.cc "Parameterized Test example"
+[sample8_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
### Creating Value-Parameterized Abstract Tests
@@ -1452,6 +1498,7 @@ the test parameters. The function should accept one argument of type
returns the value of `testing::PrintToString(GetParam())`. It does not work for
`std::string` or C strings.
+{: .callout .note}
NOTE: test names must be non-empty, unique, and may only contain ASCII
alphanumeric characters. In particular, they
[should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore)
@@ -1478,19 +1525,19 @@ for conciseness:
```c++
enum class MyType { MY_FOO = 0, MY_BAR = 1 };
-class MyTestSuite : public testing::TestWithParam<std::tuple<MyType, string>> {
+class MyTestSuite : public testing::TestWithParam<std::tuple<MyType, std::string>> {
};
INSTANTIATE_TEST_SUITE_P(
MyGroup, MyTestSuite,
testing::Combine(
- testing::Values(MyType::VALUE_0, MyType::VALUE_1),
- testing::ValuesIn("", "")),
+ testing::Values(MyType::MY_FOO, MyType::MY_BAR),
+ testing::Values("A", "B")),
[](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
- string name = absl::StrCat(
- std::get<0>(info.param) == MY_FOO ? "Foo" : "Bar", "_",
+ std::string name = absl::StrCat(
+ std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar",
std::get<1>(info.param));
- absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_');
+ absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '');
return name;
});
```
@@ -1517,10 +1564,10 @@ Remember to derive it from `::testing::Test`:
```c++
template <typename T>
-class FooTest : public ::testing::Test {
+class FooTest : public testing::Test {
public:
...
- typedef std::list<T> List;
+ using List = std::list<T>;
static T shared_;
T value_;
};
@@ -1565,7 +1612,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... }
You can see [sample6_unittest.cc] for a complete example.
-[sample6_unittest.cc]: ../samples/sample6_unittest.cc "Typed Test example"
+[sample6_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample6_unittest.cc "Typed Test example"
## Type-Parameterized Tests
@@ -1585,7 +1632,7 @@ First, define a fixture class template, as we did with typed tests:
```c++
template <typename T>
-class FooTest : public ::testing::Test {
+class FooTest : public testing::Test {
...
};
```
@@ -1624,7 +1671,7 @@ put the above code in a header file, you can `#include` it in multiple C++
source files and instantiate it multiple times.
```c++
-typedef ::testing::Types<char, int, unsigned int> MyTypes;
+using MyTypes = ::testing::Types<char, int, unsigned int>;
INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
```
@@ -1720,10 +1767,11 @@ To test them, we use the following special techniques:
}
```
- Pay special attention when your class is defined in a namespace, as you
- should define your test fixtures and tests in the same namespace if you want
- them to be friends of your class. For example, if the code to be tested
- looks like:
+ Pay special attention when your class is defined in a namespace. If you want
+ your test fixtures and tests to be friends of your class, then they must be
+ defined in the exact same namespace (no anonymous or inline namespaces).
+
+ For example, if the code to be tested looks like:
```c++
namespace my_namespace {
@@ -1743,7 +1791,7 @@ To test them, we use the following special techniques:
```c++
namespace my_namespace {
- class FooTest : public ::testing::Test {
+ class FooTest : public testing::Test {
protected:
...
};
@@ -1764,7 +1812,7 @@ In frameworks that report a failure by throwing an exception, you could catch
the exception and assert on it. But googletest doesn't use exceptions, so how do
we test that a piece of code generates an expected failure?
-gunit-spi.h contains some constructs to do this. After #including this header,
+`"gtest/gtest-spi.h"` contains some constructs to do this. After #including this header,
you can use
```c++
@@ -1790,6 +1838,7 @@ well, use one of the following macros instead:
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring);
```
+{: .callout .note}
NOTE: Assertions from multiple threads are currently not supported on Windows.
For technical reasons, there are some caveats:
@@ -1838,7 +1887,7 @@ undefined.
Use case example:
```c++
-class MyFixture : public ::testing::Test {
+class MyFixture : public testing::Test {
public:
// All of these optional, just like in regular macro usage.
static void SetUpTestSuite() { ... }
@@ -1858,7 +1907,7 @@ class MyTest : public MyFixture {
void RegisterMyTests(const std::vector<int>& values) {
for (int v : values) {
- ::testing::RegisterTest(
+ testing::RegisterTest(
"MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
std::to_string(v).c_str(),
__FILE__, __LINE__,
@@ -1903,8 +1952,8 @@ To obtain a `TestInfo` object for the currently running test, call
```c++
// Gets information about the currently running test.
// Do NOT delete the returned object - it's managed by the UnitTest class.
- const ::testing::TestInfo* const test_info =
- ::testing::UnitTest::GetInstance()->current_test_info();
+ const testing::TestInfo* const test_info =
+ testing::UnitTest::GetInstance()->current_test_info();
printf("We are in test %s of test suite %s.\n",
test_info->name(),
@@ -1912,8 +1961,8 @@ To obtain a `TestInfo` object for the currently running test, call
```
`current_test_info()` returns a null pointer if no test is running. In
-particular, you cannot find the test suite name in `TestSuiteSetUp()`,
-`TestSuiteTearDown()` (where you know the test suite name implicitly), or
+particular, you cannot find the test suite name in `SetUpTestSuite()`,
+`TearDownTestSuite()` (where you know the test suite name implicitly), or
functions called from them.
## Extending googletest by Handling Test Events
@@ -1950,15 +1999,15 @@ interesting information about the event and the test program's state.
Here's an example:
```c++
- class MinimalistPrinter : public ::testing::EmptyTestEventListener {
+ class MinimalistPrinter : public testing::EmptyTestEventListener {
// Called before a test starts.
- virtual void OnTestStart(const ::testing::TestInfo& test_info) {
+ void OnTestStart(const testing::TestInfo& test_info) override {
printf("*** Test %s.%s starting.\n",
test_info.test_suite_name(), test_info.name());
}
// Called after a failed assertion or a SUCCESS().
- virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) {
+ void OnTestPartResult(const testing::TestPartResult& test_part_result) override {
printf("%s in %s:%d\n%s\n",
test_part_result.failed() ? "*** Failure" : "Success",
test_part_result.file_name(),
@@ -1967,7 +2016,7 @@ Here's an example:
}
// Called after a test ends.
- virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
+ void OnTestEnd(const testing::TestInfo& test_info) override {
printf("*** Test %s.%s ending.\n",
test_info.test_suite_name(), test_info.name());
}
@@ -1983,10 +2032,10 @@ the "s" at the end of the name) in your `main()` function, before calling
```c++
int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
+ testing::InitGoogleTest(&argc, argv);
// Gets hold of the event listener list.
- ::testing::TestEventListeners& listeners =
- ::testing::UnitTest::GetInstance()->listeners();
+ testing::TestEventListeners& listeners =
+ testing::UnitTest::GetInstance()->listeners();
// Adds a listener to the end. googletest takes the ownership.
listeners.Append(new MinimalistPrinter);
return RUN_ALL_TESTS();
@@ -2008,7 +2057,7 @@ You can do so by adding one line:
Now, sit back and enjoy a completely different output from your tests. For more
details, see [sample9_unittest.cc].
-[sample9_unittest.cc]: ../samples/sample9_unittest.cc "Event listener example"
+[sample9_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample9_unittest.cc "Event listener example"
You may append more than one listener to the list. When an `On*Start()` or
`OnTestPartResult()` event is fired, the listeners will receive it in the order
@@ -2035,7 +2084,7 @@ by the former.
See [sample10_unittest.cc] for an example of a failure-raising listener.
-[sample10_unittest.cc]: ../samples/sample10_unittest.cc "Failure-raising listener example"
+[sample10_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
## Running Test Programs: Advanced Options
@@ -2104,6 +2153,15 @@ For example:
everything in test suite `FooTest` except `FooTest.Bar` and everything in
test suite `BarTest` except `BarTest.Foo`.
+#### Stop test execution upon first failure
+
+By default, a googletest program runs all tests the user has defined. In some
+cases (e.g. iterative test development & execution) it may be desirable stop
+test execution upon first failure (trading improved latency for completeness).
+If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,
+the test runner will stop execution as soon as the first test failure is
+found.
+
#### Temporarily Disabling Tests
If you have a broken test that you cannot fix right away, you can add the
@@ -2122,19 +2180,21 @@ will still be compiled:
// Tests that Foo does Abc.
TEST(FooTest, DISABLED_DoesAbc) { ... }
-class DISABLED_BarTest : public ::testing::Test { ... };
+class DISABLED_BarTest : public testing::Test { ... };
// Tests that Bar does Xyz.
TEST_F(DISABLED_BarTest, DoesXyz) { ... }
```
+{: .callout .note}
NOTE: This feature should only be used for temporary pain-relief. You still have
to fix the disabled tests at a later date. As a reminder, googletest will print
a banner warning you if a test program contains any disabled tests.
-TIP: You can easily count the number of disabled tests you have using `gsearch`
-and/or `grep`. This number can be used as a metric for improving your test
-quality.
+{: .callout .tip}
+TIP: You can easily count the number of disabled tests you have using
+`grep`. This number can be used as a metric for
+improving your test quality.
#### Temporarily Enabling Disabled Tests
@@ -2201,38 +2261,25 @@ random seed and re-shuffle the tests in each iteration.
googletest can use colors in its terminal output to make it easier to spot the
important information:
-<code>
-...<br/>
- <font color="green">[----------]</font><font color="black"> 1 test from
- FooTest</font><br/>
- <font color="green">[ RUN &nbsp; &nbsp; &nbsp;]</font><font color="black">
- FooTest.DoesAbc</font><br/>
- <font color="green">[ &nbsp; &nbsp; &nbsp; OK ]</font><font color="black">
- FooTest.DoesAbc </font><br/>
- <font color="green">[----------]</font><font color="black">
- 2 tests from BarTest</font><br/>
- <font color="green">[ RUN &nbsp; &nbsp; &nbsp;]</font><font color="black">
- BarTest.HasXyzProperty </font><br/>
- <font color="green">[ &nbsp; &nbsp; &nbsp; OK ]</font><font color="black">
- BarTest.HasXyzProperty</font><br/>
- <font color="green">[ RUN &nbsp; &nbsp; &nbsp;]</font><font color="black">
- BarTest.ReturnsTrueOnSuccess ... some error messages ...</font><br/>
- <font color="red">[ &nbsp; FAILED ]</font><font color="black">
- BarTest.ReturnsTrueOnSuccess ...</font><br/>
- <font color="green">[==========]</font><font color="black">
- 30 tests from 14 test suites ran.</font><br/>
- <font color="green">[ &nbsp; PASSED ]</font><font color="black">
- 28 tests.</font><br/>
- <font color="red">[ &nbsp; FAILED ]</font><font color="black">
- 2 tests, listed below:</font><br/>
- <font color="red">[ &nbsp; FAILED ]</font><font color="black">
- BarTest.ReturnsTrueOnSuccess</font><br/>
- <font color="red">[ &nbsp; FAILED ]</font><font color="black">
- AnotherTest.DoesXyz<br/>
-<br/>
- 2 FAILED TESTS
- </font>
-</code>
+<pre>...
+<font color="green">[----------]</font> 1 test from FooTest
+<font color="green">[ RUN ]</font> FooTest.DoesAbc
+<font color="green">[ OK ]</font> FooTest.DoesAbc
+<font color="green">[----------]</font> 2 tests from BarTest
+<font color="green">[ RUN ]</font> BarTest.HasXyzProperty
+<font color="green">[ OK ]</font> BarTest.HasXyzProperty
+<font color="green">[ RUN ]</font> BarTest.ReturnsTrueOnSuccess
+... some error messages ...
+<font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess
+...
+<font color="green">[==========]</font> 30 tests from 14 test suites ran.
+<font color="green">[ PASSED ]</font> 28 tests.
+<font color="red">[ FAILED ]</font> 2 tests, listed below:
+<font color="red">[ FAILED ]</font> BarTest.ReturnsTrueOnSuccess
+<font color="red">[ FAILED ]</font> AnotherTest.DoesXyz
+
+ 2 FAILED TESTS
+</pre>
You can set the `GTEST_COLOR` environment variable or the `--gtest_color`
command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
@@ -2240,6 +2287,12 @@ disable colors, or let googletest decide. When the value is `auto`, googletest
will use colors if and only if the output goes to a terminal and (on non-Windows
platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.
+#### Suppressing test passes
+
+By default, googletest prints 1 line of output for each test, indicating if it
+passed or failed. To show only test failures, run the test program with
+`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.
+
#### Suppressing the Elapsed Time
By default, googletest prints the time it takes to run each test. To disable
@@ -2261,8 +2314,7 @@ environment variable to `0`.
googletest can emit a detailed XML report to a file in addition to its normal
textual output. The report contains the duration of each test, and thus can help
-you identify slow tests. The report is also used by the http://unittest
-dashboard to show per-test-method error messages.
+you identify slow tests.
To generate the XML report, set the `GTEST_OUTPUT` environment variable or the
`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will
@@ -2537,10 +2589,23 @@ could generate this report:
}
```
+{: .callout .important}
IMPORTANT: The exact format of the JSON document is subject to change.
### Controlling How Failures Are Reported
+#### Detecting Test Premature Exit
+
+Google Test implements the _premature-exit-file_ protocol for test runners
+to catch any kind of unexpected exits of test programs. Upon start,
+Google Test creates the file which will be automatically deleted after
+all work has been finished. Then, the test runner can check if this file
+exists. In case the file remains undeleted, the inspected test has exited
+prematurely.
+
+This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment
+variable has been set.
+
#### Turning Assertion Failures into Break-Points
When running test programs under a debugger, it's very convenient if the
@@ -2565,3 +2630,32 @@ to be handled by the debugger, such that you can examine the call stack when an
exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS`
environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when
running the tests.
+
+### Sanitizer Integration
+
+The
+[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html),
+[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer),
+and
+[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual)
+all provide weak functions that you can override to trigger explicit failures
+when they detect sanitizer errors, such as creating a reference from `nullptr`.
+To override these functions, place definitions for them in a source file that
+you compile as part of your main binary:
+
+```
+extern "C" {
+void __ubsan_on_report() {
+ FAIL() << "Encountered an undefined behavior sanitizer error";
+}
+void __asan_on_error() {
+ FAIL() << "Encountered an address sanitizer error";
+}
+void __tsan_on_report() {
+ FAIL() << "Encountered a thread sanitizer error";
+}
+} // extern "C"
+```
+
+After compiling your project with one of the sanitizers enabled, if a particular
+test triggers a sanitizer error, googletest will report that it failed.
diff --git a/docs/assets/css/style.scss b/docs/assets/css/style.scss
new file mode 100644
index 00000000..bb30f418
--- /dev/null
+++ b/docs/assets/css/style.scss
@@ -0,0 +1,5 @@
+---
+---
+
+@import "jekyll-theme-primer";
+@import "main";
diff --git a/docs/community_created_documentation.md b/docs/community_created_documentation.md
new file mode 100644
index 00000000..4569075f
--- /dev/null
+++ b/docs/community_created_documentation.md
@@ -0,0 +1,7 @@
+# Community-Created Documentation
+
+The following is a list, in no particular order, of links to documentation
+created by the Googletest community.
+
+* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md),
+ by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy)
diff --git a/googletest/docs/faq.md b/docs/faq.md
index 05ecdd7d..40712321 100644
--- a/googletest/docs/faq.md
+++ b/docs/faq.md
@@ -1,9 +1,12 @@
# Googletest FAQ
-<!-- GOOGLETEST_CM0014 DO NOT DELETE -->
-
## Why should test suite names and test names not contain underscore?
+{: .callout .note}
+Note: Googletest reserves underscore (`_`) for special purpose keywords, such as
+[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition
+to the following rationale.
+
Underscore (`_`) is special, as C++ reserves the following to be used by the
compiler and the standard library:
@@ -57,9 +60,10 @@ 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.
+First of all, you can use `nullptr` with each of these macros, e.g.
+`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`,
+`ASSERT_NE(ptr, nullptr)`. This is the preferred syntax in the style guide
+because `nullptr` does not have the type problems that `NULL` does.
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()`
@@ -67,22 +71,21 @@ 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.
+Historically, the `EXPECT_EQ()` macro took the *expected* value as its first
+argument and the *actual* value as the second, though this argument order is now
+discouraged. It was reasonable that someone wanted
+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
+The need for `EXPECT_NE(NULL, ptr)` wasn'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.
+If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'd have to
+support `EXPECT_NE(ptr, NULL)` as well. 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
@@ -127,6 +130,7 @@ can much more easily decide which one to use the next time.
## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
+{: .callout .note}
**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
now. Please use `EqualsProto`, etc instead.
@@ -176,18 +180,6 @@ 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:
@@ -211,6 +203,18 @@ 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. :-)
+If the declaration of the static data member is `constexpr` then it is
+implicitly an `inline` definition, and a separate definition in `foo.cc` is not
+needed:
+
+```c++
+// foo.h
+class Foo {
+ ...
+ static constexpr int kBar = 100; // Defines kBar, no need to do it in foo.cc.
+};
+```
+
## Can I derive a test fixture from another?
Yes.
@@ -263,7 +267,7 @@ If necessary, you can continue to derive test fixtures from a derived fixture.
googletest has no limit on how deep the hierarchy can be.
For a complete example using derived test fixtures, see
-[sample5_unittest.cc](../samples/sample5_unittest.cc).
+[sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc).
## My compiler complains "void value not ignored as it ought to be." What does this mean?
@@ -295,7 +299,7 @@ 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
+sure that there are no race conditions or deadlocks in your program. No silver
bullet - sorry!
## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
@@ -332,8 +336,8 @@ You may still want to use `SetUp()/TearDown()` in the following cases:
* 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.
+ use `abort` 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
@@ -401,7 +405,7 @@ you can use it in a predicate assertion like this:
ASSERT_PRED1(IsNegative<int>, -5);
```
-Things are more interesting if your template has more than one parameters. The
+Things are more interesting if your template has more than one parameter. The
following won't compile:
```c++
@@ -555,7 +559,7 @@ TEST(MyDeathTest, ComplexExpression) {
"(Func1|Method) failed");
}
-// Death assertions can be used any where in a function. In
+// Death assertions can be used anywhere 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.
@@ -578,8 +582,6 @@ TEST(MyDeathTest, CompoundStatement) {
}
```
-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
@@ -597,7 +599,7 @@ However, there are cases where you have to define your own:
## 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
+from a single thread to multiple threads. The first time you create a thread, a
manager thread is created in addition, so you get 3, not 2, threads. Later when
the thread you create joins the main thread, the thread count decrements by 1,
but the manager thread will never be killed, so you still have 2 threads, which
@@ -612,7 +614,7 @@ runs on, you shouldn't depend on this.
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
+before the first test in it is run, and tear it down afterwards. Splitting up
the test case would require multiple set-up and tear-down processes, which is
inefficient and makes the semantics unclean.
@@ -661,14 +663,15 @@ 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?
+## 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.
+needs to be defined in the *same* name space. See
+[Tip of the Week #49](http://abseil.io/tips/49) for details.
## How do I suppress the memory leak messages on Windows?
@@ -689,10 +692,10 @@ mistake in production. Such cleverness also leads to
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
+test is [Dependency Injection](http://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
+[`testonly`](http://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
@@ -703,12 +706,12 @@ 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).
+`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.
+the `--gtest_also_run_disabled_tests` flag.
## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?
diff --git a/docs/gmock_cheat_sheet.md b/docs/gmock_cheat_sheet.md
new file mode 100644
index 00000000..cda9ddd5
--- /dev/null
+++ b/docs/gmock_cheat_sheet.md
@@ -0,0 +1,483 @@
+# gMock Cheat Sheet
+
+## 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.
+```
+
+{: .callout .note}
+**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(MyProductionFunction(&foo), "good"); // #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(buzz1, nullptr);
+ EXPECT_NE(buzz2, nullptr);
+ 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](gmock_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}
+
+See the [Matchers Reference](reference/matchers.md).
+
+## Actions {#ActionList}
+
+**Actions** specify what a mock function should do when invoked.
+
+### Returning a Value
+
+| | |
+| :-------------------------------- | :-------------------------------------------- |
+| `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. |
+| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. |
+
+### Side Effects
+
+| | |
+| :--------------------------------- | :-------------------------------------- |
+| `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. |
+
+### Using a Function, Functor, or Lambda as an Action
+
+In the following, by "callable" we mean a free function, `std::function`,
+functor, or lambda.
+
+| | |
+| :---------------------------------- | :------------------------------------- |
+| `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. |
+
+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 `std::ref()`. For example,
+
+```cpp
+using ::testing::InvokeArgument;
+...
+InvokeArgument<2>(5, string("Hi"), std::ref(foo))
+```
+
+calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by
+value, and `foo` by reference.
+
+### Default Action
+
+| Matcher | Description |
+| :------------ | :----------------------------------------------------- |
+| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |
+
+{: .callout .note}
+**Note:** due to technical reasons, `DoDefault()` cannot be used inside a
+composite action - trying to do so will result in a run-time error.
+
+### Composite Actions
+
+| | |
+| :----------------------------- | :------------------------------------------ |
+| `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 and will receive a readonly view of the arguments. |
+| `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. |
+
+### Defining Actions
+
+| | |
+| :--------------------------------- | :-------------------------------------- |
+| `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`. |
+
+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:
+
+| | |
+| :---------------- | :----------------------------------------------------- |
+| `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. |
+
+## 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 give 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](gmock_cook_book.md#using-check-points) for one application of
+it.
+
+## Flags
+
+| 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. |
diff --git a/googlemock/docs/cook_book.md b/docs/gmock_cook_book.md
index a4935214..891c35cf 100644
--- a/googlemock/docs/cook_book.md
+++ b/docs/gmock_cook_book.md
@@ -1,10 +1,10 @@
# gMock Cookbook
-<!-- GOOGLETEST_CM0012 DO NOT DELETE -->
-
You can find recipes for using gMock here. If you haven't yet, please read
-[this](for_dummies.md) first to make sure you understand the basics.
+[the dummy guide](gmock_for_dummies.md) first to make sure you understand the
+basics.
+{: .callout .note}
**Note:** gMock lives in the `testing` name space. For readability, it is
recommended to write `using ::testing::Foo;` once in your file before using the
name `Foo` defined by gMock. We omit such `using` statements in this section for
@@ -35,13 +35,17 @@ generated method:
`noexcept` method.
* **`Calltype(...)`** - Sets the call type for the method (e.g. to
`STDMETHODCALLTYPE`), useful in Windows.
+* **`ref(...)`** - Marks the method with the reference qualification
+ specified. Required if overriding a method that has reference
+ qualifications. Eg `ref(&)` or `ref(&&)`.
### Dealing with unprotected commas
Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent
`MOCK_METHOD` from parsing its arguments correctly:
-```cpp {.bad}
+{: .bad}
+```cpp
class MockFoo {
public:
MOCK_METHOD(std::pair<bool, int>, GetPair, ()); // Won't compile!
@@ -51,7 +55,8 @@ class MockFoo {
Solution 1 - wrap with parentheses:
-```cpp {.good}
+{: .good}
+```cpp
class MockFoo {
public:
MOCK_METHOD((std::pair<bool, int>), GetPair, ());
@@ -64,7 +69,8 @@ invalid C++. `MOCK_METHOD` removes the parentheses.
Solution 2 - define an alias:
-```cpp {.good}
+{: .good}
+```cpp
class MockFoo {
public:
using BoolAndInt = std::pair<bool, int>;
@@ -138,6 +144,7 @@ class MockFoo : public Foo {
};
```
+{: .callout .note}
**Note:** if you don't mock all versions of the overloaded method, the compiler
will give you a warning about some methods in the base class being hidden. To
fix that, use `using` to bring them in scope:
@@ -177,8 +184,7 @@ class MockStack : public StackInterface<Elem> {
### Mocking Non-virtual Methods {#MockingNonVirtualMethods}
-gMock can mock non-virtual functions to be used in Hi-perf dependency
-injection.<!-- GOOGLETEST_CM0017 DO NOT DELETE -->
+gMock can mock non-virtual functions to be used in Hi-perf dependency injection.
In this case, instead of sharing a common base class with the real class, your
mock class will be *unrelated* to the real class, but contain methods with the
@@ -245,9 +251,9 @@ tests.
### Mocking Free Functions
-It's possible to use gMock to mock a free function (i.e. a C-style function or a
-static method). You just need to rewrite your code to use an interface (abstract
-class).
+It is not possible to directly mock a free function (i.e. a C-style function or
+a static method). If you need to, you can rewrite your code to use an interface
+(abstract class).
Instead of calling a free function (say, `OpenFile`) directly, introduce an
interface for it and have a concrete subclass that calls the free function:
@@ -262,7 +268,7 @@ class FileInterface {
class File : public FileInterface {
public:
...
- virtual bool Open(const char* path, const char* mode) {
+ bool Open(const char* path, const char* mode) override {
return OpenFile(path, mode);
}
};
@@ -281,9 +287,11 @@ recipe for [mocking non-virtual methods](#MockingNonVirtualMethods).
### Old-Style `MOCK_METHODn` Macros
-Before the generic `MOCK_METHOD` macro was introduced, mocks where created using
-a family of macros collectively called `MOCK_METHODn`. These macros are still
-supported, though migration to the new `MOCK_METHOD` is recommended.
+Before the generic `MOCK_METHOD` macro
+[was introduced in 2018](https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2),
+mocks where created using a family of macros collectively called `MOCK_METHODn`.
+These macros are still supported, though migration to the new `MOCK_METHOD` is
+recommended.
The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`:
@@ -297,44 +305,86 @@ The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`:
Old macros and their new equivalents:
-<a name="table99"></a>
-<table border="1" cellspacing="0" cellpadding="1">
-<tr> <th colspan=2> Simple </th></tr>
-<tr> <td> Old </td> <td> `MOCK_METHOD1(Foo, bool(int))` </td> </tr>
-<tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int))` </td> </tr>
-
-<tr> <th colspan=2> Const Method </th></tr> <tr> <td> Old </td> <td>
-`MOCK_CONST_METHOD1(Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td>
-`MOCK_METHOD(bool, Foo, (int), (const))` </td> </tr>
-
-<tr> <th colspan=2> Method in a Class Template </th></tr> <tr> <td> Old </td>
-<td> `MOCK_METHOD1_T(Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td>
-`MOCK_METHOD(bool, Foo, (int))` </td> </tr>
-
-<tr> <th colspan=2> Const Method in a Class Template </th></tr> <tr> <td> Old
-</td> <td> `MOCK_CONST_METHOD1_T(Foo, bool(int))` </td> </tr> <tr> <td> New
-</td> <td> `MOCK_METHOD(bool, Foo, (int), (const))` </td> </tr>
-
-<tr> <th colspan=2> Method with Call Type </th></tr> <tr> <td> Old </td> <td>
-`MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))` </td> </tr> <tr>
-<td> New </td> <td> `MOCK_METHOD(bool, Foo, (int),
-(Calltype(STDMETHODCALLTYPE)))` </td> </tr>
-
-<tr> <th colspan=2> Const Method with Call Type </th></tr> <tr> <td> Old</td>
-<td> `MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))` </td>
-</tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int), (const,
-Calltype(STDMETHODCALLTYPE)))` </td> </tr>
-
-<tr> <th colspan=2> Method with Call Type in a Class Template </th></tr> <tr>
-<td> Old </td> <td> `MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo,
-bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int),
-(Calltype(STDMETHODCALLTYPE)))` </td> </tr>
-
-<tr> <th colspan=2> Const Method with Call Type in a Class Template </th></tr>
-<tr> <td> Old </td> <td> `MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE,
-Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo,
-(int), (const, Calltype(STDMETHODCALLTYPE)))` </td> </tr>
-
+<table>
+ <tr><th colspan=2>Simple</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_METHOD1(Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Const Method</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_CONST_METHOD1(Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (const))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Method in a Class Template</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_METHOD1_T(Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Const Method in a Class Template</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_CONST_METHOD1_T(Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (const))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Method with Call Type</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Const Method with Call Type</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Method with Call Type in a Class Template</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code></td>
+ </tr>
+
+ <tr><th colspan=2>Const Method with Call Type in a Class Template</th></tr>
+ <tr>
+ <td>Old</td>
+ <td><code>MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>
+ </tr>
+ <tr>
+ <td>New</td>
+ <td><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code></td>
+ </tr>
</table>
### The Nice, the Strict, and the Naggy {#NiceStrictNaggy}
@@ -405,13 +455,14 @@ TEST(...) {
}
```
+{: .callout .note}
NOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of
*methods* with no expectations); they do not affect *unexpected* calls (calls of
methods with expectations, but they don't match). See
[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected).
-There are some caveats though (I dislike them just as much as the next guy, but
-sadly they are side effects of C++'s limitations):
+There are some caveats though (sadly they are side effects of C++'s
+limitations):
1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods
defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class.
@@ -421,17 +472,7 @@ sadly they are side effects of C++'s limitations):
`NiceMock<StrictMock<MockFoo> >`) is **not** supported.
2. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` may not work correctly if the
destructor of `MockFoo` is not virtual. We would like to fix this, but it
- requires cleaning up existing tests. http://b/28934720 tracks the issue.
-3. During the constructor or destructor of `MockFoo`, the mock object is *not*
- nice or strict. This may cause surprises if the constructor or destructor
- calls a mock method on `this` object. (This behavior, however, is consistent
- with C++'s general rule: if a constructor or destructor calls a virtual
- method of `this` object, that method is treated as non-virtual. In other
- words, to the base class's constructor or destructor, `this` object behaves
- like an instance of the base class, not the derived class. This rule is
- required for safety. Otherwise a base constructor may use members of a
- derived class before they are initialized, or a base destructor may use
- members of a derived class after they have been destroyed.)
+ requires cleaning up existing tests.
Finally, you should be **very cautious** about when to use naggy or strict
mocks, as they tend to make tests more brittle and harder to maintain. When you
@@ -471,9 +512,9 @@ The trick is to redispatch the method in the mock class:
class ScopedMockLog : public LogSink {
public:
...
- virtual void send(LogSeverity severity, const char* full_filename,
+ void send(LogSeverity severity, const char* full_filename,
const char* base_filename, int line, const tm* tm_time,
- const char* message, size_t message_len) {
+ const char* message, size_t message_len) override {
// We are only interested in the log severity, full file name, and
// log message.
Log(severity, full_filename, std::string(message, message_len));
@@ -513,7 +554,7 @@ argument matchers:
```cpp
ON_CALL(factory, DoMakeTurtle)
- .WillByDefault(MakeMockTurtle());
+ .WillByDefault(Return(MakeMockTurtle()));
```
### Alternative to Mocking Concrete Classes
@@ -777,28 +818,12 @@ perhaps your test doesn't need to mock `Concrete()` at all (but it would be
oh-so painful to have to define a new mock class whenever you don't need to mock
one of its methods).
-The trick is to leave a back door in your mock class for accessing the real
-methods in the base class:
-
-```cpp
-class MockFoo : public Foo {
- public:
- // Mocking a pure method.
- MOCK_METHOD(void, Pure, (int n), (override));
- // Mocking a concrete method. Foo::Concrete() is shadowed.
- MOCK_METHOD(int, Concrete, (const char* str), (override));
-
- // Use this to call Concrete() defined in Foo.
- int FooConcrete(const char* str) { return Foo::Concrete(str); }
-};
-```
-
-Now, you can call `Foo::Concrete()` inside an action by:
+You can call `Foo::Concrete()` inside an action by:
```cpp
...
EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) {
- return foo.FooConcrete(str);
+ return foo.Foo::Concrete(str);
});
```
@@ -807,7 +832,7 @@ or tell the mock object that you don't want to mock `Concrete()`:
```cpp
...
ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) {
- return foo.FooConcrete(str);
+ return foo.Foo::Concrete(str);
});
```
@@ -848,7 +873,6 @@ A frequently used matcher is `_`, which matches anything:
```cpp
EXPECT_CALL(foo, DoThat(_, NotNull()));
```
-<!-- GOOGLETEST_CM0022 DO NOT DELETE -->
### Combining Matchers {#CombiningMatchers}
@@ -871,6 +895,22 @@ using ::testing::Not;
NULL));
```
+Matchers are function objects, and parametrized matchers can be composed just
+like any other function. However because their types can be long and rarely
+provide meaningful information, it can be easier to express them with C++14
+generic lambdas to avoid specifying types. For example,
+
+```cpp
+using ::testing::Contains;
+using ::testing::Property;
+
+inline constexpr auto HasFoo = [](const auto& f) {
+ return Property(&MyClass::foo, Contains(f));
+};
+...
+ EXPECT_THAT(x, HasFoo("blah"));
+```
+
### Casting Matchers {#SafeMatcherCast}
gMock matchers are statically typed, meaning that the compiler can catch your
@@ -1048,7 +1088,8 @@ z`. Note that in this example, it wasn't necessary specify the positional
matchers.
As a convenience and example, gMock provides some matchers for 2-tuples,
-including the `Lt()` matcher above. See [here](#MultiArgMatchers) for the
+including the `Lt()` matcher above. See
+[Multi-argument Matchers](reference/matchers.md#MultiArgMatchers) for the
complete list.
Note that if you want to pass the arguments to a predicate of your own (e.g.
@@ -1144,10 +1185,12 @@ Hamcrest project, which adds `assertThat()` to JUnit.
### Using Predicates as Matchers
-gMock provides a [built-in set](#MatcherList) of matchers. In case you find them
-lacking, you can use an arbitrary unary predicate function or functor as a
-matcher - as long as the predicate accepts a value of the type you want. You do
-this by wrapping the predicate inside the `Truly()` function, for example:
+gMock provides a set of built-in matchers for matching arguments with expected
+values—see the [Matchers Reference](reference/matchers.md) for more information.
+In case you find the built-in set lacking, you can use an arbitrary unary
+predicate function or functor as a matcher - as long as the predicate accepts a
+value of the type you want. You do this by wrapping the predicate inside the
+`Truly()` function, for example:
```cpp
using ::testing::Truly;
@@ -1162,8 +1205,6 @@ Note that the predicate function / functor doesn't have to return `bool`. It
works as long as the return value can be used as the condition in in statement
`if (condition) ...`.
-<!-- GOOGLETEST_CM0023 DO NOT DELETE -->
-
### Matching Arguments that Are Not Copyable
When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of
@@ -1180,15 +1221,14 @@ executed. Just tell gMock that it should save a reference to `bar`, instead of a
copy of it. Here's how:
```cpp
-using ::testing::ByRef;
using ::testing::Eq;
using ::testing::Lt;
...
// Expects that Foo()'s argument == bar.
- EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));
+ EXPECT_CALL(mock_obj, Foo(Eq(std::ref(bar))));
// Expects that Foo()'s argument < bar.
- EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
+ EXPECT_CALL(mock_obj, Foo(Lt(std::ref(bar))));
```
Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the
@@ -1218,17 +1258,17 @@ that satisfies matcher `m`.
For example:
-<!-- mdformat off(github rendering does not support multiline tables) -->
| Expression | Description |
| :--------------------------- | :--------------------------------------- |
| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. |
| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. |
-<!-- mdformat on -->
Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument
-and be declared as `const`.
+and be declared as `const`. Don't use `Property()` against member functions that
+you do not own, because taking addresses of functions is fragile and generally
+not part of the contract of the function.
-BTW, `Field()` and `Property()` can also match plain pointers to objects. For
+`Field()` and `Property()` can also match plain pointers to objects. For
instance,
```cpp
@@ -1317,32 +1357,30 @@ how you can define a matcher to do it:
```cpp
using ::testing::Matcher;
-using ::testing::MatcherInterface;
-using ::testing::MatchResultListener;
-class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
+class BarPlusBazEqMatcher {
public:
explicit BarPlusBazEqMatcher(int expected_sum)
: expected_sum_(expected_sum) {}
bool MatchAndExplain(const Foo& foo,
- MatchResultListener* /* listener */) const override {
+ std::ostream* /* listener */) const {
return (foo.bar() + foo.baz()) == expected_sum_;
}
- void DescribeTo(std::ostream* os) const override {
- *os << "bar() + baz() equals " << expected_sum_;
+ void DescribeTo(std::ostream& os) const {
+ os << "bar() + baz() equals " << expected_sum_;
}
- void DescribeNegationTo(std::ostream* os) const override {
- *os << "bar() + baz() does not equal " << expected_sum_;
+ void DescribeNegationTo(std::ostream& os) const {
+ os << "bar() + baz() does not equal " << expected_sum_;
}
private:
const int expected_sum_;
};
Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
- return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
+ return BarPlusBazEqMatcher(expected_sum);
}
...
@@ -1422,6 +1460,8 @@ using ::testing::ElementsAreArray;
Use `Pair` when comparing maps or other associative containers.
+{% raw %}
+
```cpp
using testing::ElementsAre;
using testing::Pair;
@@ -1430,6 +1470,8 @@ using testing::Pair;
EXPECT_THAT(m, ElementsAre(Pair("a", 1), Pair("b", 2), Pair("c", 3)));
```
+{% endraw %}
+
**Tips:**
* `ElementsAre*()` can be used to match *any* container that implements the
@@ -1468,6 +1510,7 @@ using ::testing::Matcher;
### Matchers must have no side-effects {#PureMatchers}
+{: .callout .warning}
WARNING: gMock does not guarantee when or how many times a matcher will be
invoked. Therefore, all matchers must be *purely functional*: they cannot have
any side effects, and the match result must not depend on anything other than
@@ -1482,8 +1525,6 @@ mock object and gMock.
### Knowing When to Expect {#UseOnCall}
-<!-- GOOGLETEST_CM0018 DO NOT DELETE -->
-
**`ON_CALL`** is likely the *single most under-utilized construct* in gMock.
There are basically two constructs for defining the behavior of a mock object:
@@ -1675,11 +1716,11 @@ times from calling it with the wrong arguments.
### Expecting Ordered Calls {#OrderedCalls}
-Although an `EXPECT_CALL()` statement defined earlier takes precedence when
-gMock tries to match a function call with an expectation, by default calls don't
-have to happen in the order `EXPECT_CALL()` statements are written. For example,
-if the arguments match the matchers in the third `EXPECT_CALL()`, but not those
-in the first two, then the third expectation will be used.
+Although an `EXPECT_CALL()` statement defined later takes precedence when gMock
+tries to match a function call with an expectation, by default calls don't have
+to happen in the order `EXPECT_CALL()` statements are written. For example, if
+the arguments match the matchers in the second `EXPECT_CALL()`, but not those in
+the first and third, then the second expectation will be used.
If you would rather have all calls occur in the order of the expectations, put
the `EXPECT_CALL()` statements in a block where you define a variable of type
@@ -1712,8 +1753,8 @@ brittle tests. For example, we may care about `A` occurring before both `B` and
the test should reflect our real intent, instead of being overly constraining.
gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the
-calls. One way to express the DAG is to use the [After](#AfterClause) clause of
-`EXPECT_CALL`.
+calls. One way to express the DAG is to use the
+[After](gmock_cheat_sheet.md#AfterClause) clause of `EXPECT_CALL`.
Another way is via the `InSequence()` clause (not the same as the `InSequence`
class), which we borrowed from jMock 2. It's less flexible than `After()`, but
@@ -1851,10 +1892,9 @@ Methods"). However, gMock doesn't let you use `ReturnRef()` in a mock function
whose return type is not a reference, as doing that usually indicates a user
error. So, what shall you do?
-Though you may be tempted, DO NOT use `ByRef()`:
+Though you may be tempted, DO NOT use `std::ref()`:
```cpp
-using testing::ByRef;
using testing::Return;
class MockFoo : public Foo {
@@ -1865,7 +1905,7 @@ class MockFoo : public Foo {
int x = 0;
MockFoo foo;
EXPECT_CALL(foo, GetValue())
- .WillRepeatedly(Return(ByRef(x))); // Wrong!
+ .WillRepeatedly(Return(std::ref(x))); // Wrong!
x = 42;
EXPECT_EQ(42, foo.GetValue());
```
@@ -1881,9 +1921,9 @@ Expected: 42
The reason is that `Return(*value*)` converts `value` to the actual return type
of the mock function at the time when the action is *created*, not when it is
*executed*. (This behavior was chosen for the action to be safe when `value` is
-a proxy object that references some temporary objects.) As a result, `ByRef(x)`
-is converted to an `int` value (instead of a `const int&`) when the expectation
-is set, and `Return(ByRef(x))` will always return 0.
+a proxy object that references some temporary objects.) As a result,
+`std::ref(x)` is converted to an `int` value (instead of a `const int&`) when
+the expectation is set, and `Return(std::ref(x))` will always return 0.
`ReturnPointee(pointer)` was provided to solve this problem specifically. It
returns the value pointed to by `pointer` at the time the action is *executed*:
@@ -2128,7 +2168,7 @@ class MockFoo : public Foo {
DefaultValue<Bar>::Clear();
```
-Please note that changing the default value for a type can make you tests hard
+Please note that changing the default value for a type can make your tests hard
to understand. We recommend you to use this feature judiciously. For example,
you may want to make sure the `Set()` and `Clear()` calls are right next to the
code that uses your mock.
@@ -2174,9 +2214,7 @@ own precedence order distinct from the `ON_CALL` precedence order.
### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions}
If the built-in actions don't suit you, you can use an existing callable
-(function, `std::function`, method, functor, lambda as an action.
-
-<!-- GOOGLETEST_CM0024 DO NOT DELETE -->
+(function, `std::function`, method, functor, lambda) as an action.
```cpp
using ::testing::_; using ::testing::Invoke;
@@ -2203,6 +2241,7 @@ class Helper {
.WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1)));
EXPECT_CALL(foo, ComplexJob(_))
.WillOnce(Invoke(&helper, &Helper::ComplexJob))
+ .WillOnce([] { return true; })
.WillRepeatedly([](int x) { return x > 0; });
foo.Sum(5, 6); // Invokes CalculateSum(5, 6).
@@ -2212,13 +2251,13 @@ class Helper {
```
The only requirement is that the type of the function, etc must be *compatible*
-with the signature of the mock function, meaning that the latter's arguments can
-be implicitly converted to the corresponding arguments of the former, and the
-former's return type can be implicitly converted to that of the latter. So, you
-can invoke something whose type is *not* exactly the same as the mock function,
-as long as it's safe to do so - nice, huh?
+with the signature of the mock function, meaning that the latter's arguments (if
+it takes any) can be implicitly converted to the corresponding arguments of the
+former, and the former's return type can be implicitly converted to that of the
+latter. So, you can invoke something whose type is *not* exactly the same as the
+mock function, as long as it's safe to do so - nice, huh?
-**`Note:`{.escaped}**
+Note that:
* The action takes ownership of the callback and will delete it when the
action itself is destructed.
@@ -2267,19 +2306,20 @@ TEST_F(FooTest, Test) {
### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments
-`Invoke()` is very useful for doing actions that are more complex. It passes the
-mock function's arguments to the function, etc being invoked such that the
-callee has the full context of the call to work with. If the invoked function is
-not interested in some or all of the arguments, it can simply ignore them.
+`Invoke()` passes the mock function's arguments to the function, etc being
+invoked such that the callee has the full context of the call to work with. If
+the invoked function is not interested in some or all of the arguments, it can
+simply ignore them.
Yet, a common pattern is that a test author wants to invoke a function without
-the arguments of the mock function. `Invoke()` allows her to do that using a
-wrapper function that throws away the arguments before invoking an underlining
-nullary function. Needless to say, this can be tedious and obscures the intent
-of the test.
+the arguments of the mock function. She could do that using a wrapper function
+that throws away the arguments before invoking an underlining nullary function.
+Needless to say, this can be tedious and obscures the intent of the test.
-`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except that it
-doesn't pass the mock function's arguments to the callee. Here's an example:
+There are two solutions to this problem. First, you can pass any callable of
+zero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like
+`Invoke()` except that it doesn't pass the mock function's arguments to the
+callee. Here's an example of each:
```cpp
using ::testing::_;
@@ -2296,14 +2336,14 @@ bool Job2(int n, char c) { ... }
...
MockFoo foo;
EXPECT_CALL(foo, ComplexJob(_))
- .WillOnce(InvokeWithoutArgs(Job1))
+ .WillOnce([] { Job1(); });
.WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a')));
foo.ComplexJob(10); // Invokes Job1().
foo.ComplexJob(20); // Invokes Job2(5, 'a').
```
-**`Note:`{.escaped}**
+Note that:
* The action takes ownership of the callback and will delete it when the
action itself is destructed.
@@ -2346,6 +2386,7 @@ using ::testing::_;
// second argument DoThis() receives.
```
+{: .callout .note}
NOTE: The section below is legacy documentation from before C++ had lambdas:
Arghh, you need to refer to a mock function argument but C++ has no lambda
@@ -2374,7 +2415,7 @@ using ::testing::InvokeArgument;
```
What if the callable takes an argument by reference? No problem - just wrap it
-inside `ByRef()`:
+inside `std::ref()`:
```cpp
...
@@ -2383,20 +2424,19 @@ inside `ByRef()`:
(override));
...
using ::testing::_;
- using ::testing::ByRef;
using ::testing::InvokeArgument;
...
MockFoo foo;
Helper helper;
...
EXPECT_CALL(foo, Bar(_))
- .WillOnce(InvokeArgument<0>(5, ByRef(helper)));
- // ByRef(helper) guarantees that a reference to helper, not a copy of it,
- // will be passed to the callback.
+ .WillOnce(InvokeArgument<0>(5, std::ref(helper)));
+ // std::ref(helper) guarantees that a reference to helper, not a copy of
+ // it, will be passed to the callback.
```
What if the callable takes an argument by reference and we do **not** wrap the
-argument in `ByRef()`? Then `InvokeArgument()` will *make a copy* of the
+argument in `std::ref()`? Then `InvokeArgument()` will *make a copy* of the
argument, and pass a *reference to the copy*, instead of a reference to the
original value, to the callable. This is especially handy when the argument is a
temporary value:
@@ -2667,26 +2707,18 @@ behavior nondeterministic. A better way is to use gMock actions and
`Notification` objects to force your asynchronous test to behave synchronously.
```cpp
-using ::testing::DoAll;
-using ::testing::InvokeWithoutArgs;
-using ::testing::Return;
-
class MockEventDispatcher : public EventDispatcher {
MOCK_METHOD(bool, DispatchEvent, (int32), (override));
};
-ACTION_P(Notify, notification) {
- notification->Notify();
-}
-
TEST(EventQueueTest, EnqueueEventTest) {
MockEventDispatcher mock_event_dispatcher;
EventQueue event_queue(&mock_event_dispatcher);
const int32 kEventId = 321;
- Notification done;
+ absl::Notification done;
EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId))
- .WillOnce(Notify(&done));
+ .WillOnce([&done] { done.Notify(); });
event_queue.EnqueueEvent(kEventId);
done.WaitForNotification();
@@ -2699,6 +2731,7 @@ additional action to notify the `Notification` object. Now we can just call
asynchronous call to finish. After that, our test suite is complete and we can
safely exit.
+{: .callout .note}
Note: this example has a downside: namely, if the expectation is not satisfied,
our test will run forever. It will eventually time-out and fail, but it will
take longer and be slightly harder to debug. To alleviate this problem, you can
@@ -2849,8 +2882,8 @@ work with non-copyable objects; you'll have to use functors instead.
#### Legacy workarounds for move-only types {#LegacyMoveOnly}
Support for move-only function arguments was only introduced to gMock in April
-2017. In older code, you may encounter the following workaround for the lack of
-this feature (it is no longer necessary - we're including it just for
+of 2017. In older code, you may encounter the following workaround for the lack
+of this feature (it is no longer necessary - we're including it just for
reference):
```cpp
@@ -2978,6 +3011,7 @@ TEST(MyServerTest, ProcessesRequest) {
} // server is destroyed when it goes out of scope here.
```
+{: .callout .tip}
**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to
indicate whether the verification was successful (`true` for yes), so you can
wrap that function call inside a `ASSERT_TRUE()` if there is no point going
@@ -3071,7 +3105,7 @@ class MockFoo : public Foo {
...
// Add the following two lines to the mock class.
MOCK_METHOD(void, Die, ());
- virtual ~MockFoo() { Die(); }
+ ~MockFoo() override { Die(); }
};
```
@@ -3270,8 +3304,6 @@ If you are interested in the mock call trace but not the stack traces, you can
combine `--gmock_verbose=info` with `--gtest_stack_trace_depth=0` on the test
command line.
-<!-- GOOGLETEST_CM0025 DO NOT DELETE -->
-
### Running Tests in Emacs
If you build and run your tests in Emacs using the `M-x google-compile` command
@@ -3296,6 +3328,7 @@ after typing `M-m`), or `M-up`/`M-down` to move back and forth between errors.
### Writing New Matchers Quickly {#NewMatchers}
+{: .callout .warning}
WARNING: gMock does not guarantee when or how many times a matcher will be
invoked. Therefore, all matchers must be functionally pure. See
[this section](#PureMatchers) for more details.
@@ -3399,6 +3432,7 @@ match succeeds in case of a success (unless it's obvious) - this is useful when
the matcher is used inside `Not()`. There is no need to print the argument value
itself, as gMock already prints it for you.
+{: .callout .note}
NOTE: The type of the value being matched (`arg_type`) is determined by the
context in which you use the matcher and is supplied to you by the compiler, so
you don't need to worry about declaring it (nor can you). This allows the
@@ -3537,51 +3571,39 @@ MATCHER_P2(Blah, a, b, description_string_2) { ... }
```
While it's tempting to always use the `MATCHER*` macros when defining a new
-matcher, you should also consider implementing `MatcherInterface` or using
-`MakePolymorphicMatcher()` instead (see the recipes that follow), especially if
-you need to use the matcher a lot. While these approaches require more work,
-they give you more control on the types of the value being matched and the
-matcher parameters, which in general leads to better compiler error messages
-that pay off in the long run. They also allow overloading matchers based on
-parameter types (as opposed to just based on the number of parameters).
+matcher, you should also consider implementing the matcher interface directly
+instead (see the recipes that follow), especially if you need to use the matcher
+a lot. While these approaches require more work, they give you more control on
+the types of the value being matched and the matcher parameters, which in
+general leads to better compiler error messages that pay off in the long run.
+They also allow overloading matchers based on parameter types (as opposed to
+just based on the number of parameters).
### Writing New Monomorphic Matchers
-A matcher of argument type `T` implements `::testing::MatcherInterface<T>` and
-does two things: it tests whether a value of type `T` matches the matcher, and
-can describe what kind of values it matches. The latter ability is used for
+A matcher of argument type `T` implements the matcher interface for `T` and does
+two things: it tests whether a value of type `T` matches the matcher, and can
+describe what kind of values it matches. The latter ability is used for
generating readable error messages when expectations are violated.
-The interface looks like this:
+A matcher of `T` must declare a typedef like:
```cpp
-class MatchResultListener {
- public:
- ...
- // Streams x to the underlying ostream; does nothing if the ostream
- // is NULL.
- template <typename T>
- MatchResultListener& operator<<(const T& x);
-
- // Returns the underlying ostream.
- std::ostream* stream();
-};
-
-template <typename T>
-class MatcherInterface {
- public:
- virtual ~MatcherInterface();
+using is_gtest_matcher = void;
+```
- // Returns true if and only if the matcher matches x; also explains the match
- // result to 'listener'.
- virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
+and supports the following operations:
- // Describes this matcher to an ostream.
- virtual void DescribeTo(std::ostream* os) const = 0;
+```cpp
+// Match a value and optionally explain into an ostream.
+bool matched = matcher.MatchAndExplain(value, maybe_os);
+// where `value` is of type `T` and
+// `maybe_os` is of type `std::ostream*`, where it can be null if the caller
+// is not interested in there textual explanation.
- // Describes the negation of this matcher to an ostream.
- virtual void DescribeNegationTo(std::ostream* os) const;
-};
+matcher.DescribeTo(os);
+matcher.DescribeNegationTo(os);
+// where `os` is of type `std::ostream*`.
```
If you need a custom matcher but `Truly()` is not a good option (for example,
@@ -3596,29 +3618,27 @@ For example, you can define a matcher to test whether an `int` is divisible by 7
and then use it like this:
```cpp
-using ::testing::MakeMatcher;
using ::testing::Matcher;
-using ::testing::MatcherInterface;
-using ::testing::MatchResultListener;
-class DivisibleBy7Matcher : public MatcherInterface<int> {
+class DivisibleBy7Matcher {
public:
- bool MatchAndExplain(int n,
- MatchResultListener* /* listener */) const override {
+ using is_gtest_matcher = void;
+
+ bool MatchAndExplain(int n, std::ostream*) const {
return (n % 7) == 0;
}
- void DescribeTo(std::ostream* os) const override {
+ void DescribeTo(std::ostream* os) const {
*os << "is divisible by 7";
}
- void DescribeNegationTo(std::ostream* os) const override {
+ void DescribeNegationTo(std::ostream* os) const {
*os << "is not divisible by 7";
}
};
Matcher<int> DivisibleBy7() {
- return MakeMatcher(new DivisibleBy7Matcher);
+ return DivisibleBy7Matcher();
}
...
@@ -3626,16 +3646,15 @@ Matcher<int> DivisibleBy7() {
```
You may improve the matcher message by streaming additional information to the
-`listener` argument in `MatchAndExplain()`:
+`os` argument in `MatchAndExplain()`:
```cpp
-class DivisibleBy7Matcher : public MatcherInterface<int> {
+class DivisibleBy7Matcher {
public:
- bool MatchAndExplain(int n,
- MatchResultListener* listener) const override {
+ bool MatchAndExplain(int n, std::ostream* os) const {
const int remainder = n % 7;
- if (remainder != 0) {
- *listener << "the remainder is " << remainder;
+ if (remainder != 0 && os != nullptr) {
+ *os << "the remainder is " << remainder;
}
return remainder == 0;
}
@@ -3651,15 +3670,87 @@ Expected: is divisible by 7
Actual: 23 (the remainder is 2)
```
+{: .callout .tip}
+Tip: for convenience, `MatchAndExplain()` can take a `MatchResultListener*`
+instead of `std::ostream*`.
+
### Writing New Polymorphic Matchers
-You've learned how to write your own matchers in the previous recipe. Just one
-problem: a matcher created using `MakeMatcher()` only works for one particular
-type of arguments. If you want a *polymorphic* matcher that works with arguments
-of several types (for instance, `Eq(x)` can be used to match a *`value`* as long
-as `value == x` compiles -- *`value`* and `x` don't have to share the same
-type), you can learn the trick from `testing/base/public/gmock-matchers.h` but
-it's a bit involved.
+Expanding what we learned above to *polymorphic* matchers is now just as simple
+as adding templates in the right place.
+
+```cpp
+
+class NotNullMatcher {
+ public:
+ using is_gtest_matcher = void;
+
+ // To implement a polymorphic matcher, we just need to make MatchAndExplain a
+ // template on its first argument.
+
+ // In this example, we want to use NotNull() with any pointer, so
+ // MatchAndExplain() accepts a pointer of any type as its first argument.
+ // In general, you can define MatchAndExplain() as an ordinary method or
+ // a method template, or even overload it.
+ template <typename T>
+ bool MatchAndExplain(T* p, std::ostream*) const {
+ return p != nullptr;
+ }
+
+ // Describes the property of a value matching this matcher.
+ void DescribeTo(std::ostream* os) const { *os << "is not NULL"; }
+
+ // Describes the property of a value NOT matching this matcher.
+ void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; }
+};
+
+NotNullMatcher NotNull() {
+ return NotNullMatcher();
+}
+
+...
+
+ EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer.
+```
+
+### Legacy Matcher Implementation
+
+Defining matchers used to be somewhat more complicated, in which it required
+several supporting classes and virtual functions. To implement a matcher for
+type `T` using the legacy API you have to derive from `MatcherInterface<T>` and
+call `MakeMatcher` to construct the object.
+
+The interface looks like this:
+
+```cpp
+class MatchResultListener {
+ public:
+ ...
+ // Streams x to the underlying ostream; does nothing if the ostream
+ // is NULL.
+ template <typename T>
+ MatchResultListener& operator<<(const T& x);
+
+ // Returns the underlying ostream.
+ std::ostream* stream();
+};
+
+template <typename T>
+class MatcherInterface {
+ public:
+ virtual ~MatcherInterface();
+
+ // Returns true if and only if the matcher matches x; also explains the match
+ // result to 'listener'.
+ virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
+
+ // Describes this matcher to an ostream.
+ virtual void DescribeTo(std::ostream* os) const = 0;
+
+ // Describes the negation of this matcher to an ostream.
+ virtual void DescribeNegationTo(std::ostream* os) const;
+};
+```
Fortunately, most of the time you can define a polymorphic matcher easily with
the help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as
@@ -3704,6 +3795,7 @@ PolymorphicMatcher<NotNullMatcher> NotNull() {
EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer.
```
+{: .callout .note}
**Note:** Your polymorphic matcher class does **not** need to inherit from
`MatcherInterface` or any other class, and its methods do **not** need to be
virtual.
@@ -3717,8 +3809,8 @@ A cardinality is used in `Times()` to tell gMock how many times you expect a
call to occur. It doesn't have to be exact. For example, you can say
`AtLeast(5)` or `Between(2, 4)`.
-If the [built-in set](cheat_sheet.md#CardinalityList) of cardinalities doesn't
-suit you, you are free to define your own by implementing the following
+If the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities
+doesn't suit you, you are free to define your own by implementing the following
interface (in namespace `testing`):
```cpp
@@ -4041,23 +4133,18 @@ If you are writing a function that returns an `ACTION` object, you'll need to
know its type. The type depends on the macro used to define the action and the
parameter types. The rule is relatively simple:
+
| Given Definition | Expression | Has Type |
| ----------------------------- | ------------------- | --------------------- |
| `ACTION(Foo)` | `Foo()` | `FooAction` |
-| `ACTION_TEMPLATE(Foo,` | `Foo<t1, ..., | `FooAction<t1, ..., |
-: `HAS_m_TEMPLATE_PARAMS(...),` : t_m>()` : t_m>` :
-: `AND_0_VALUE_PARAMS())` : : :
+| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |
| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
-| `ACTION_TEMPLATE(Bar,` | `Bar<t1, ..., t_m>` | `FooActionP<t1, ..., |
-: `HAS_m_TEMPLATE_PARAMS(...),` : `(int_value)` : t_m, int>` :
-: `AND_1_VALUE_PARAMS(p1))` : : :
-| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value,` | `BazActionP2<bool, |
-: : `int_value)` : int>` :
-| `ACTION_TEMPLATE(Baz,` | `Baz<t1, ..., t_m>` | `FooActionP2<t1, ..., |
-: `HAS_m_TEMPLATE_PARAMS(...),` : `(bool_value,` : t_m,` `bool, int>` :
-: `AND_2_VALUE_PARAMS(p1, p2))` : `int_value)` : :
+| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `BarActionP<t1, ..., t_m, int>` |
+| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
+| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `BazActionP2<t1, ..., t_m, bool, int>` |
| ... | ... | ... |
+
Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`,
and etc) for actions with different numbers of value parameters, or the action
definitions cannot be overloaded on the number of them.
@@ -4206,7 +4293,7 @@ value printer.
This printer knows how to print built-in C++ types, native arrays, STL
containers, and any type that supports the `<<` operator. For other types, it
prints the raw bytes in the value and hopes that you the user can figure it out.
-[googletest's advanced guide](../../googletest/docs/advanced.md#teaching-googletest-how-to-print-your-values)
+[The GoogleTest advanced guide](advanced.md#teaching-googletest-how-to-print-your-values)
explains how to extend the printer to do a better job at printing your
particular type than to dump the bytes.
@@ -4265,5 +4352,3 @@ expectations.
Although `std::function` supports unlimited number of arguments, `MockFunction`
implementation is limited to ten. If you ever hit that limit... well, your
callback has bigger problems than being mockable. :-)
-
-<!-- GOOGLETEST_CM0034 DO NOT DELETE -->
diff --git a/googlemock/docs/gmock_faq.md b/docs/gmock_faq.md
index 214aabf1..09623b4e 100644
--- a/googlemock/docs/gmock_faq.md
+++ b/docs/gmock_faq.md
@@ -1,11 +1,9 @@
-## Legacy gMock FAQ {#GMockFaq}
-
-<!-- GOOGLETEST_CM0021 DO NOT DELETE -->
+# Legacy gMock FAQ
### 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).
+[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods).
### Can I mock a variadic function?
@@ -81,8 +79,6 @@ 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
@@ -91,9 +87,9 @@ 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.
+[adding a default action](gmock_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?
@@ -126,8 +122,6 @@ using ::testing::_;
.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
@@ -386,8 +380,8 @@ 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.
+See this [recipe](gmock_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?
diff --git a/googlemock/docs/for_dummies.md b/docs/gmock_for_dummies.md
index 93cf06f3..370f17e1 100644
--- a/googlemock/docs/for_dummies.md
+++ b/docs/gmock_for_dummies.md
@@ -1,8 +1,6 @@
-## gMock for Dummies {#GMockForDummies}
+# gMock for Dummies
-<!-- GOOGLETEST_CM0013 DO NOT DELETE -->
-
-### What Is gMock?
+## 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
@@ -10,9 +8,9 @@ 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:
+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
@@ -39,7 +37,7 @@ When using gMock,
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?
+## 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*:
@@ -53,9 +51,9 @@ them fast and reliable, using mocks manually in C++ is *hard*:
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.
+EasyMock, 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
@@ -85,11 +83,11 @@ We encourage you to use gMock as
* a *testing* tool to cut your tests' outbound dependencies and probe the
interaction between your module and its collaborators.
-### Getting Started
+## Getting Started
gMock is bundled with googletest.
-### A Case for Mock Turtles
+## A Case for Mock Turtles
Let's look at an example. Suppose you are developing a graphics program that
relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like
@@ -106,7 +104,7 @@ the API in an interface (say, `Turtle`) and code to that interface:
```cpp
class Turtle {
...
- virtual ~Turtle() {};
+ virtual ~Turtle() {}
virtual void PenUp() = 0;
virtual void PenDown() = 0;
virtual void Forward(int distance) = 0;
@@ -135,20 +133,20 @@ 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
+## 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
+### 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),
+ [mock non-virtual methods using templates](gmock_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
@@ -184,7 +182,7 @@ class MockTurtle : public Turtle {
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
+### 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
@@ -206,9 +204,7 @@ 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
+## Using Mocks in Tests
Once you have a mock class, using it is easy. The typical work flow is:
@@ -257,8 +253,8 @@ 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 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
@@ -279,7 +275,7 @@ 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
+## 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
@@ -288,7 +284,7 @@ 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
+### General Syntax
In gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock
method. The general syntax is:
@@ -314,8 +310,8 @@ EXPECT_CALL(mock_object, non-overloaded-method)
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
+unintended ambiguity, this syntax may only be used for methods that 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
@@ -338,12 +334,13 @@ 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).
+{: .callout .note}
**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
+it makes expectations easily identifiable (either by `grep` 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?
+### Matchers: What Arguments Do We Expect?
When a mock function takes arguments, we may specify what arguments we are
expecting, for example:
@@ -374,8 +371,8 @@ 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:
+[built-in matchers](reference/matchers.md) for common types (as well as
+[custom matchers](gmock_cook_book.md#NewMatchers)); for example:
```cpp
using ::testing::Ge;
@@ -397,9 +394,9 @@ 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).
+[types of the arguments](gmock_cook_book.md#SelectOverload).
-#### Cardinalities: How Many Times Will It Be Called?
+### 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
@@ -414,7 +411,7 @@ 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).
+[here](gmock_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:
@@ -429,7 +426,7 @@ the cardinality for you.** The rules are easy to remember:
**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?
+### 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
@@ -483,7 +480,7 @@ the *default* action for the function every time (unless, of course, you have a
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).
+[others](gmock_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
@@ -503,7 +500,7 @@ 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 -->).
+[cook book](gmock_cook_book.md).
Time for another quiz! What do you think the following means?
@@ -522,7 +519,7 @@ 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}
+### 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
@@ -547,6 +544,7 @@ 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.
+{: .callout .note}
**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
@@ -555,15 +553,16 @@ 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.
+{: .callout .tip}
**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).
+[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected).
-#### Ordered vs Unordered Calls {#OrderedCalls}
+### 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
@@ -598,9 +597,9 @@ 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).)
+details can be found [here](gmock_cook_book.md#OrderedCalls).)
-#### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}
+### 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*
@@ -688,7 +687,7 @@ 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
+### 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
@@ -697,4 +696,4 @@ For example, in some tests we may not care about how many times `GetX()` and
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).
+[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy).
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 00000000..b162c740
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,22 @@
+# GoogleTest User's Guide
+
+## Welcome to GoogleTest!
+
+GoogleTest is Google's C++ testing and mocking framework. This user's guide has
+the following contents:
+
+* [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using
+ GoogleTest. Read this first if you are new to GoogleTest.
+* [GoogleTest Advanced](advanced.md) - Read this when you've finished the
+ Primer and want to utilize GoogleTest to its full potential.
+* [GoogleTest Samples](samples.md) - Describes some GoogleTest samples.
+* [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here
+ first.
+* [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock
+ objects and use them in tests.
+* [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to
+ common mocking use cases.
+* [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for
+ matchers, actions, invariants, and more.
+* [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific
+ questions.
diff --git a/googletest/docs/pkgconfig.md b/docs/pkgconfig.md
index 117166cf..768e9b4c 100644
--- a/googletest/docs/pkgconfig.md
+++ b/docs/pkgconfig.md
@@ -45,77 +45,6 @@ splitting the pkg-config `Cflags` variable into include dirs and macros for
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
@@ -216,4 +145,4 @@ $ pkg-config --libs gtest
which contains the correct sysroot now. For a more comprehensive guide to also
including `${CHOST}` in build system calls, see the excellent tutorial by Diego
-Elio Pettenò: https://autotools.io/pkgconfig/cross-compiling.html
+Elio Pettenò: <https://autotools.io/pkgconfig/cross-compiling.html>
diff --git a/docs/platforms.md b/docs/platforms.md
new file mode 100644
index 00000000..eba6ef80
--- /dev/null
+++ b/docs/platforms.md
@@ -0,0 +1,35 @@
+# Supported Platforms
+
+GoogleTest requires a codebase and compiler compliant with the C++11 standard or
+newer.
+
+The GoogleTest code is officially supported on the following platforms.
+Operating systems or tools not listed below are community-supported. For
+community-supported platforms, patches that do not complicate the code may be
+considered.
+
+If you notice any problems on your platform, please file an issue on the
+[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
+Pull requests containing fixes are welcome!
+
+### Operating systems
+
+* Linux
+* macOS
+* Windows
+
+### Compilers
+
+* gcc 5.0+
+* clang 5.0+
+* MSVC 2015+
+
+**macOS users:** Xcode 9.3+ provides clang 5.0+.
+
+### Build systems
+
+* [Bazel](https://bazel.build/)
+* [CMake](https://cmake.org/)
+
+Bazel is the build system used by the team internally and in tests. CMake is
+supported on a best-effort basis and by the community.
diff --git a/googletest/docs/primer.md b/docs/primer.md
index f581d77a..44a1cb55 100644
--- a/googletest/docs/primer.md
+++ b/docs/primer.md
@@ -44,6 +44,7 @@ minutes to learn the basics and get started. So let's go!
## Beware of the nomenclature
+{: .callout .note}
_Note:_ There might be some confusion arising from different definitions of the
terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
@@ -66,13 +67,11 @@ 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
@@ -169,7 +168,7 @@ you'll get a compiler error. We used to require the arguments to support the
`<<` 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).
+[documentation](./advanced.md#teaching-googletest-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
@@ -218,7 +217,6 @@ as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now
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 |
| -------------------------- | ------------------------------ | -------------------------------------------------------- |
@@ -227,7 +225,6 @@ two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead.
| `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*.
@@ -464,6 +461,7 @@ When invoked, the `RUN_ALL_TESTS()` macro:
If a fatal failure happens the subsequent steps will be skipped.
+{: .callout .important}
> 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
@@ -566,6 +564,7 @@ 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
the `gtest_main` library and you are good to go.
+{: .callout .note}
NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
## Known Limitations
diff --git a/docs/quickstart-bazel.md b/docs/quickstart-bazel.md
new file mode 100644
index 00000000..362ee6d0
--- /dev/null
+++ b/docs/quickstart-bazel.md
@@ -0,0 +1,161 @@
+# Quickstart: Building with Bazel
+
+This tutorial aims to get you up and running with GoogleTest using the Bazel
+build system. If you're using GoogleTest for the first time or need a refresher,
+we recommend this tutorial as a starting point.
+
+## Prerequisites
+
+To complete this tutorial, you'll need:
+
+* A compatible operating system (e.g. Linux, macOS, Windows).
+* A compatible C++ compiler that supports at least C++11.
+* [Bazel](https://bazel.build/), the preferred build system used by the
+ GoogleTest team.
+
+See [Supported Platforms](platforms.md) for more information about platforms
+compatible with GoogleTest.
+
+If you don't already have Bazel installed, see the
+[Bazel installation guide](https://docs.bazel.build/versions/master/install.html).
+
+{: .callout .note}
+Note: The terminal commands in this tutorial show a Unix shell prompt, but the
+commands work on the Windows command line as well.
+
+## Set up a Bazel workspace
+
+A
+[Bazel workspace](https://docs.bazel.build/versions/master/build-ref.html#workspace)
+is a directory on your filesystem that you use to manage source files for the
+software you want to build. Each workspace directory has a text file named
+`WORKSPACE` which may be empty, or may contain references to external
+dependencies required to build the outputs.
+
+First, create a directory for your workspace:
+
+```
+$ mkdir my_workspace && cd my_workspace
+```
+
+Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and
+recommended way to depend on GoogleTest is to use a
+[Bazel external dependency](https://docs.bazel.build/versions/master/external.html)
+via the
+[`http_archive` rule](https://docs.bazel.build/versions/master/repo/http.html#http_archive).
+To do this, in the root directory of your workspace (`my_workspace/`), create a
+file named `WORKSPACE` with the following contents:
+
+```
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
+
+http_archive(
+ name = "com_google_googletest",
+ urls = ["https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip"],
+ strip_prefix = "googletest-609281088cfefc76f9d0ce82e1ff6c30cc3591e5",
+)
+```
+
+The above configuration declares a dependency on GoogleTest which is downloaded
+as a ZIP archive from GitHub. In the above example,
+`609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is the Git commit hash of the
+GoogleTest version to use; we recommend updating the hash often to point to the
+latest version.
+
+Bazel also needs a dependency on the
+[`rules_cc` repository](https://github.com/bazelbuild/rules_cc) to build C++
+code, so add the following to the `WORKSPACE` file:
+
+```
+http_archive(
+ name = "rules_cc",
+ urls = ["https://github.com/bazelbuild/rules_cc/archive/40548a2974f1aea06215272d9c2b47a14a24e556.zip"],
+ strip_prefix = "rules_cc-40548a2974f1aea06215272d9c2b47a14a24e556",
+)
+```
+
+Now you're ready to build C++ code that uses GoogleTest.
+
+## Create and run a binary
+
+With your Bazel workspace set up, you can now use GoogleTest code within your
+own project.
+
+As an example, create a file named `hello_test.cc` in your `my_workspace`
+directory with the following contents:
+
+```cpp
+#include <gtest/gtest.h>
+
+// Demonstrate some basic assertions.
+TEST(HelloTest, BasicAssertions) {
+ // Expect two strings not to be equal.
+ EXPECT_STRNE("hello", "world");
+ // Expect equality.
+ EXPECT_EQ(7 * 6, 42);
+}
+```
+
+GoogleTest provides [assertions](primer.md#assertions) that you use to test the
+behavior of your code. The above sample includes the main GoogleTest header file
+and demonstrates some basic assertions.
+
+To build the code, create a file named `BUILD` in the same directory with the
+following contents:
+
+```
+load("@rules_cc//cc:defs.bzl", "cc_test")
+
+cc_test(
+ name = "hello_test",
+ size = "small",
+ srcs = ["hello_test.cc"],
+ deps = ["@com_google_googletest//:gtest_main"],
+)
+```
+
+This `cc_test` rule declares the C++ test binary you want to build, and links to
+GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE`
+file (`@com_google_googletest`). For more information about Bazel `BUILD` files,
+see the
+[Bazel C++ Tutorial](https://docs.bazel.build/versions/master/tutorial/cpp.html).
+
+Now you can build and run your test:
+
+<pre>
+<strong>my_workspace$ bazel test --test_output=all //:hello_test</strong>
+INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
+INFO: Found 1 test target...
+INFO: From Testing //:hello_test:
+==================== Test output for //:hello_test:
+Running main() from gmock_main.cc
+[==========] Running 1 test from 1 test suite.
+[----------] Global test environment set-up.
+[----------] 1 test from HelloTest
+[ RUN ] HelloTest.BasicAssertions
+[ OK ] HelloTest.BasicAssertions (0 ms)
+[----------] 1 test from HelloTest (0 ms total)
+
+[----------] Global test environment tear-down
+[==========] 1 test from 1 test suite ran. (0 ms total)
+[ PASSED ] 1 test.
+================================================================================
+Target //:hello_test up-to-date:
+ bazel-bin/hello_test
+INFO: Elapsed time: 4.190s, Critical Path: 3.05s
+INFO: 27 processes: 8 internal, 19 linux-sandbox.
+INFO: Build completed successfully, 27 total actions
+//:hello_test PASSED in 0.1s
+
+INFO: Build completed successfully, 27 total actions
+</pre>
+
+Congratulations! You've successfully built and run a test binary using
+GoogleTest.
+
+## Next steps
+
+* [Check out the Primer](primer.md) to start learning how to write simple
+ tests.
+* [See the code samples](samples.md) for more examples showing how to use a
+ variety of GoogleTest features.
diff --git a/docs/quickstart-cmake.md b/docs/quickstart-cmake.md
new file mode 100644
index 00000000..420f1d3a
--- /dev/null
+++ b/docs/quickstart-cmake.md
@@ -0,0 +1,156 @@
+# Quickstart: Building with CMake
+
+This tutorial aims to get you up and running with GoogleTest using CMake. If
+you're using GoogleTest for the first time or need a refresher, we recommend
+this tutorial as a starting point. If your project uses Bazel, see the
+[Quickstart for Bazel](quickstart-bazel.md) instead.
+
+## Prerequisites
+
+To complete this tutorial, you'll need:
+
+* A compatible operating system (e.g. Linux, macOS, Windows).
+* A compatible C++ compiler that supports at least C++11.
+* [CMake](https://cmake.org/) and a compatible build tool for building the
+ project.
+ * Compatible build tools include
+ [Make](https://www.gnu.org/software/make/),
+ [Ninja](https://ninja-build.org/), and others - see
+ [CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html)
+ for more information.
+
+See [Supported Platforms](platforms.md) for more information about platforms
+compatible with GoogleTest.
+
+If you don't already have CMake installed, see the
+[CMake installation guide](https://cmake.org/install).
+
+{: .callout .note}
+Note: The terminal commands in this tutorial show a Unix shell prompt, but the
+commands work on the Windows command line as well.
+
+## Set up a project
+
+CMake uses a file named `CMakeLists.txt` to configure the build system for a
+project. You'll use this file to set up your project and declare a dependency on
+GoogleTest.
+
+First, create a directory for your project:
+
+```
+$ mkdir my_project && cd my_project
+```
+
+Next, you'll create the `CMakeLists.txt` file and declare a dependency on
+GoogleTest. There are many ways to express dependencies in the CMake ecosystem;
+in this quickstart, you'll use the
+[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html).
+To do this, in your project directory (`my_project`), create a file named
+`CMakeLists.txt` with the following contents:
+
+```cmake
+cmake_minimum_required(VERSION 3.14)
+project(my_project)
+
+# GoogleTest requires at least C++11
+set(CMAKE_CXX_STANDARD 11)
+
+include(FetchContent)
+FetchContent_Declare(
+ googletest
+ URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
+)
+# For Windows: Prevent overriding the parent project's compiler/linker settings
+set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
+FetchContent_MakeAvailable(googletest)
+```
+
+The above configuration declares a dependency on GoogleTest which is downloaded
+from GitHub. In the above example, `609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is
+the Git commit hash of the GoogleTest version to use; we recommend updating the
+hash often to point to the latest version.
+
+For more information about how to create `CMakeLists.txt` files, see the
+[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html).
+
+## Create and run a binary
+
+With GoogleTest declared as a dependency, you can use GoogleTest code within
+your own project.
+
+As an example, create a file named `hello_test.cc` in your `my_project`
+directory with the following contents:
+
+```cpp
+#include <gtest/gtest.h>
+
+// Demonstrate some basic assertions.
+TEST(HelloTest, BasicAssertions) {
+ // Expect two strings not to be equal.
+ EXPECT_STRNE("hello", "world");
+ // Expect equality.
+ EXPECT_EQ(7 * 6, 42);
+}
+```
+
+GoogleTest provides [assertions](primer.md#assertions) that you use to test the
+behavior of your code. The above sample includes the main GoogleTest header file
+and demonstrates some basic assertions.
+
+To build the code, add the following to the end of your `CMakeLists.txt` file:
+
+```cmake
+enable_testing()
+
+add_executable(
+ hello_test
+ hello_test.cc
+)
+target_link_libraries(
+ hello_test
+ gtest_main
+)
+
+include(GoogleTest)
+gtest_discover_tests(hello_test)
+```
+
+The above configuration enables testing in CMake, declares the C++ test binary
+you want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The
+last two lines enable CMake's test runner to discover the tests included in the
+binary, using the
+[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html).
+
+Now you can build and run your test:
+
+<pre>
+<strong>my_project$ cmake -S . -B build</strong>
+-- The C compiler identification is GNU 10.2.1
+-- The CXX compiler identification is GNU 10.2.1
+...
+-- Build files have been written to: .../my_project/build
+
+<strong>my_project$ cmake --build build</strong>
+Scanning dependencies of target gtest
+...
+[100%] Built target gmock_main
+
+<strong>my_project$ cd build && ctest</strong>
+Test project .../my_project/build
+ Start 1: HelloTest.BasicAssertions
+1/1 Test #1: HelloTest.BasicAssertions ........ Passed 0.00 sec
+
+100% tests passed, 0 tests failed out of 1
+
+Total Test time (real) = 0.01 sec
+</pre>
+
+Congratulations! You've successfully built and run a test binary using
+GoogleTest.
+
+## Next steps
+
+* [Check out the Primer](primer.md) to start learning how to write simple
+ tests.
+* [See the code samples](samples.md) for more examples showing how to use a
+ variety of GoogleTest features.
diff --git a/docs/reference/matchers.md b/docs/reference/matchers.md
new file mode 100644
index 00000000..a2ded435
--- /dev/null
+++ b/docs/reference/matchers.md
@@ -0,0 +1,282 @@
+# Matchers Reference
+
+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:
+
+| 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. |
+
+{: .callout .note}
+**Note:** Although equality matching via `EXPECT_THAT(actual_value,
+expected_value)` is supported, prefer to make the comparison explicit via
+`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value,
+expected_value)`.
+
+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
+
+| 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`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)|
+| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |
+| `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. |
+
+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 `std::ref()`, e.g.
+`Eq(std::ref(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.
+
+`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types
+that can be explicitly converted to Boolean, but are not implicitly converted to
+Boolean. In other cases, you can use the basic
+[`EXPECT_TRUE` and `EXPECT_FALSE`](primer.md#basic-assertions) assertions.
+
+### Floating-Point Matchers {#FpMatchers}
+
+| 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. |
+| `IsNan()` | `argument` is any floating-point type with a NaN value. |
+
+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.
+
+| 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. |
+
+### String Matchers
+
+The `argument` can be either a C string or a C++ string object:
+
+| 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. |
+| `IsEmpty()` | `argument` is an empty 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`. |
+
+`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
+use the regular expression syntax defined
+[here](advanced.md#regular-expression-syntax). All of these matchers, except
+`ContainsRegex()` and `MatchesRegex()` work for wide strings as well.
+
+### 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:
+
+| 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))`. |
+
+**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, ...)` and `UnorderedPointwise(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
+
+| 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_. |
+| `Field(field_name, &class::field, m)` | The same as the two-parameter version, but provides a better error message. |
+| `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`. |
+| `FieldsAre(m...)` | `argument` is a compatible object where each field matches piecewise with the matchers `m...`. A compatible object is any that supports the `std::tuple_size<Obj>`+`get<I>(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. |
+| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. |
+| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message.
+
+**Notes:**
+
+* You can use `FieldsAre()` to match any type that supports structured
+ bindings, such as `std::tuple`, `std::pair`, `std::array`, and aggregate
+ types. For example:
+
+ ```cpp
+ std::tuple<int, std::string> my_tuple{7, "hello world"};
+ EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr("hello")));
+
+ struct MyStruct {
+ int value = 42;
+ std::string greeting = "aloha";
+ };
+ MyStruct s;
+ EXPECT_THAT(s, FieldsAre(42, "aloha"));
+ ```
+
+* Don't use `Property()` against member functions that you do not own, because
+ taking addresses of functions is fragile and generally not part of the
+ contract of the function.
+
+### Matching the Result of a Function, Functor, or Callback
+
+| Matcher | Description |
+| :--------------- | :------------------------------------------------ |
+| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. |
+
+### Pointer Matchers
+
+| Matcher | Description |
+| :------------------------ | :---------------------------------------------- |
+| `Address(m)` | the result of `std::addressof(argument)` matches `m`. |
+| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. |
+| `Pointer(m)` | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. |
+| `WhenDynamicCastTo<T>(m)` | when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. |
+
+### 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:
+
+| 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())`. |
+
+### Composite Matchers
+
+You can make a matcher from one or more other matchers:
+
+| 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`. |
+
+### Adapters for Matchers
+
+| Matcher | Description |
+| :---------------------- | :------------------------------------ |
+| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. |
+| `SafeMatcherCast<T>(m)` | [safely casts](gmock_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. |
+
+`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`,
+which must be a permanent callback.
+
+### Using Matchers as Predicates {#MatchersAsPredicatesCheat}
+
+| 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`. |
+
+### Defining Matchers
+
+| 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 matcher `IsDivisibleBy(n)` to match a number divisible by `n`. |
+| `MATCHER_P2(IsBetween, a, b, absl::StrCat(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`]. |
+
+**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.
+4. You can use `ExplainMatchResult()` in a custom matcher to wrap another
+ matcher, for example:
+
+ ```cpp
+ MATCHER_P(NestedPropertyMatches, matcher, "") {
+ return ExplainMatchResult(matcher, arg.nested().property(), result_listener);
+ }
+ ```
diff --git a/googletest/docs/samples.md b/docs/samples.md
index aaa58838..2d97ca55 100644
--- a/googletest/docs/samples.md
+++ b/docs/samples.md
@@ -1,4 +1,4 @@
-# Googletest Samples {#samples}
+# Googletest Samples
If you're like us, you'd like to look at
[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples)
diff --git a/googlemock/Android.bp b/googlemock/Android.bp
index d86410d5..5e90057f 100644
--- a/googlemock/Android.bp
+++ b/googlemock/Android.bp
@@ -12,6 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "external_googletest_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ // SPDX-license-identifier-BSD
+ default_applicable_licenses: ["external_googletest_license"],
+}
+
cc_defaults {
name: "gmock_flags",
diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt
index d32b70b5..e7df8ec5 100644
--- a/googlemock/CMakeLists.txt
+++ b/googlemock/CMakeLists.txt
@@ -42,7 +42,7 @@ else()
cmake_policy(SET CMP0048 NEW)
project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
endif()
-cmake_minimum_required(VERSION 2.6.4)
+cmake_minimum_required(VERSION 2.8.12)
if (COMMAND set_up_hermetic_build)
set_up_hermetic_build()
@@ -100,8 +100,10 @@ if (MSVC)
else()
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
target_link_libraries(gmock PUBLIC gtest)
+ set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION})
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
target_link_libraries(gmock_main PUBLIC gmock)
+ set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
endif()
# If the CMake version supports it, attach header directory information
# to the targets for when we are part of a parent build (ie being pulled
@@ -136,20 +138,6 @@ if (gmock_build_tests)
# 'make test' or ctest.
enable_testing()
- if (WIN32)
- file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1"
- CONTENT
-"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$<CONFIG>\"
-$env:Path = \"$project_bin;$env:Path\"
-& $args")
- elseif (MINGW OR CYGWIN)
- file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1"
- CONTENT
-"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin)
-$env:Path = \"$project_bin;$env:Path\"
-& $args")
- endif()
-
if (MINGW OR CYGWIN)
if (CMAKE_VERSION VERSION_LESS "2.8.12")
add_compile_options("-Wa,-mbig-obj")
@@ -165,9 +153,6 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_test(gmock-cardinalities_test gmock_main)
cxx_test(gmock_ex_test gmock_main)
cxx_test(gmock-function-mocker_test gmock_main)
- cxx_test(gmock-generated-actions_test gmock_main)
- cxx_test(gmock-generated-function-mockers_test gmock_main)
- cxx_test(gmock-generated-matchers_test gmock_main)
cxx_test(gmock-internal-utils_test gmock_main)
cxx_test(gmock-matchers_test gmock_main)
cxx_test(gmock-more-actions_test gmock_main)
diff --git a/googlemock/CONTRIBUTORS b/googlemock/CONTRIBUTORS
deleted file mode 100644
index 6e9ae362..00000000
--- a/googlemock/CONTRIBUTORS
+++ /dev/null
@@ -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>
diff --git a/googlemock/LICENSE b/googlemock/LICENSE
index 1941a11f..ea5b6064 100644..120000
--- a/googlemock/LICENSE
+++ b/googlemock/LICENSE
@@ -1,28 +1 @@
-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.
+../LICENSE \ No newline at end of file
diff --git a/googlemock/NOTICE b/googlemock/NOTICE
index 7a694c96..ea5b6064 120000
--- a/googlemock/NOTICE
+++ b/googlemock/NOTICE
@@ -1 +1 @@
-LICENSE \ No newline at end of file
+../LICENSE \ No newline at end of file
diff --git a/googlemock/README.md b/googlemock/README.md
index 183fdb81..ead68832 100644
--- a/googlemock/README.md
+++ b/googlemock/README.md
@@ -7,38 +7,38 @@ derive better designs of your system and write better tests.
It is inspired by:
-* [jMock](http://www.jmock.org/),
-* [EasyMock](http://www.easymock.org/), and
-* [Hamcrest](http://code.google.com/p/hamcrest/),
+* [jMock](http://www.jmock.org/)
+* [EasyMock](http://www.easymock.org/)
+* [Hamcrest](http://code.google.com/p/hamcrest/)
-and designed with C++'s specifics in mind.
+It is designed with C++'s specifics in mind.
gMock:
-- provides a declarative syntax for defining mocks,
-- can define partial (hybrid) mocks, which are a cross of real and mock
- objects,
-- handles functions of arbitrary types and overloaded functions,
-- comes with a rich set of matchers for validating function arguments,
-- uses an intuitive syntax for controlling the behavior of a mock,
-- does automatic verification of expectations (no record-and-replay needed),
-- allows arbitrary (partial) ordering constraints on function calls to be
- expressed,
-- lets a user extend it by defining new matchers and actions.
-- does not use exceptions, and
-- is easy to learn and use.
+- Provides a declarative syntax for defining mocks.
+- Can define partial (hybrid) mocks, which are a cross of real and mock
+ objects.
+- Handles functions of arbitrary types and overloaded functions.
+- Comes with a rich set of matchers for validating function arguments.
+- Uses an intuitive syntax for controlling the behavior of a mock.
+- Does automatic verification of expectations (no record-and-replay needed).
+- Allows arbitrary (partial) ordering constraints on function calls to be
+ expressed.
+- Lets a user extend it by defining new matchers and actions.
+- Does not use exceptions.
+- Is easy to learn and use.
Details and examples can be found here:
-* [gMock for Dummies](docs/for_dummies.md)
-* [Legacy gMock FAQ](docs/gmock_faq.md)
-* [gMock Cookbook](docs/cook_book.md)
-* [gMock Cheat Sheet](docs/cheat_sheet.md)
+* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html)
+* [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html)
+* [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html)
+* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html)
-Please note that code under scripts/generator/ is from the [cppclean
-project](http://code.google.com/p/cppclean/) and under the Apache
-License, which is different from Google Mock's license.
+Please note that code under scripts/generator/ is from the
+[cppclean project](http://code.google.com/p/cppclean/) and under the Apache
+License, which is different from GoogleMock's license.
-Google Mock is a part of
-[Google Test C++ testing framework](http://github.com/google/googletest/) and a
+GoogleMock is a part of
+[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a
subject to the same requirements.
diff --git a/googlemock/cmake/gmock.pc.in b/googlemock/cmake/gmock.pc.in
index 5780fcaa..23c67b5c 100644
--- a/googlemock/cmake/gmock.pc.in
+++ b/googlemock/cmake/gmock.pc.in
@@ -5,6 +5,6 @@ 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@
diff --git a/googlemock/cmake/gmock_main.pc.in b/googlemock/cmake/gmock_main.pc.in
index f2dfe69e..66ffea7f 100644
--- a/googlemock/cmake/gmock_main.pc.in
+++ b/googlemock/cmake/gmock_main.pc.in
@@ -5,6 +5,6 @@ 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@
diff --git a/googlemock/docs/README.md b/googlemock/docs/README.md
new file mode 100644
index 00000000..1bc57b79
--- /dev/null
+++ b/googlemock/docs/README.md
@@ -0,0 +1,4 @@
+# Content Moved
+
+We are working on updates to the GoogleTest documentation, which has moved to
+the top-level [docs](../../docs) directory.
diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md
deleted file mode 100644
index b425e0a0..00000000
--- a/googlemock/docs/cheat_sheet.md
+++ /dev/null
@@ -1,776 +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`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)|
-| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |
-| `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.
-
-`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types
-that can be explicitly converted to Boolean, but are not implicitly converted to
-Boolean. In other cases, you can use the basic
-[`EXPECT_TRUE` and `EXPECT_FALSE`](../../googletest/docs/primer#basic-assertions)
-assertions.
-
-#### 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. |
-| `IsNan()` | `argument` is any floating-point type with a NaN value. |
-<!-- 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). All of
-these matchers, except `ContainsRegex()` and `MatchesRegex()` 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. |
-| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. |
-<!-- 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
-
-<!-- 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 -->
diff --git a/googlemock/docs/pump_manual.md b/googlemock/docs/pump_manual.md
deleted file mode 100644
index cdf7c57d..00000000
--- a/googlemock/docs/pump_manual.md
+++ /dev/null
@@ -1,187 +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.
-
-Our experience is that it's tedious to write custom 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.
-
-This script may be useful for generating meta code, for example a series of
-macros of FOO1, FOO2, etc. Nevertheless, please make it your last resort
-technique by favouring C++ template metaprogramming or variadic macros.
-
-# 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.
diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h
index 4b8dcebb..f2393bd3 100644
--- a/googlemock/include/gmock/gmock-actions.h
+++ b/googlemock/include/gmock/gmock-actions.h
@@ -30,12 +30,105 @@
// Google Mock - a framework for writing C++ mock classes.
//
-// This file implements some commonly used actions.
+// The ACTION* family of macros can be used in a namespace scope to
+// define custom actions easily. The syntax:
+//
+// ACTION(name) { statements; }
+//
+// will define an action with the given name that executes the
+// statements. The value returned by the statements will be used as
+// the return value of the action. Inside the statements, you can
+// refer to the K-th (0-based) argument of the mock function by
+// 'argK', and refer to its type by 'argK_type'. For example:
+//
+// ACTION(IncrementArg1) {
+// arg1_type temp = arg1;
+// return ++(*temp);
+// }
+//
+// allows you to write
+//
+// ...WillOnce(IncrementArg1());
+//
+// You can also refer to the entire argument tuple and its type by
+// 'args' and 'args_type', and refer to the mock function type and its
+// return type by 'function_type' and 'return_type'.
+//
+// Note that you don't need to specify the types of the mock function
+// arguments. However rest assured that your code is still type-safe:
+// you'll get a compiler error if *arg1 doesn't support the ++
+// operator, or if the type of ++(*arg1) isn't compatible with the
+// mock function's return type, for example.
+//
+// Sometimes you'll want to parameterize the action. For that you can use
+// another macro:
+//
+// ACTION_P(name, param_name) { statements; }
+//
+// For example:
+//
+// ACTION_P(Add, n) { return arg0 + n; }
+//
+// will allow you to write:
+//
+// ...WillOnce(Add(5));
+//
+// Note that you don't need to provide the type of the parameter
+// either. If you need to reference the type of a parameter named
+// 'foo', you can write 'foo_type'. For example, in the body of
+// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
+// of 'n'.
+//
+// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
+// multi-parameter actions.
+//
+// For the purpose of typing, you can view
+//
+// ACTION_Pk(Foo, p1, ..., pk) { ... }
+//
+// as shorthand for
+//
+// template <typename p1_type, ..., typename pk_type>
+// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
+//
+// In particular, you can provide the template type arguments
+// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
+// although usually you can rely on the compiler to infer the types
+// for you automatically. You can assign the result of expression
+// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
+// pk_type>. This can be useful when composing actions.
+//
+// You can also overload actions with different numbers of parameters:
+//
+// ACTION_P(Plus, a) { ... }
+// ACTION_P2(Plus, a, b) { ... }
+//
+// While it's tempting to always use the ACTION* macros when defining
+// a new action, you should also consider implementing ActionInterface
+// or using MakePolymorphicAction() instead, especially if you need to
+// use the action a lot. While these approaches require more work,
+// they give you more control on the types of the mock function
+// arguments and the action parameters, which in general leads to
+// better compiler error messages that pay off in the long run. They
+// also allow overloading actions based on parameter types (as opposed
+// to just based on the number of parameters).
+//
+// CAVEAT:
+//
+// ACTION*() can only be used in a namespace scope as templates cannot be
+// declared inside of a local class.
+// Users can, however, define any local functors (e.g. a lambda) that
+// can be used as actions.
+//
+// MORE INFORMATION:
+//
+// To learn more about using these macros, please search for 'ACTION' on
+// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
#ifndef _WIN32_WCE
# include <errno.h>
@@ -45,11 +138,13 @@
#include <functional>
#include <memory>
#include <string>
+#include <tuple>
#include <type_traits>
#include <utility>
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h"
+#include "gmock/internal/gmock-pp.h"
#ifdef _MSC_VER
# pragma warning(push)
@@ -169,6 +264,10 @@ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
+// Simple two-arg form of std::disjunction.
+template <typename P, typename Q>
+using disjunction = typename ::std::conditional<P::value, P, Q>::type;
+
} // namespace internal
// When an unexpected function call is encountered, Google Mock will
@@ -350,6 +449,9 @@ class Action {
}
};
+ template <typename G>
+ using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
+
public:
typedef typename internal::Function<F>::Result Result;
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
@@ -361,10 +463,14 @@ class Action {
// Construct an Action from a specified callable.
// This cannot take std::function directly, because then Action would not be
// directly constructible from lambda (it would require two conversions).
- template <typename G,
- typename = typename ::std::enable_if<
- ::std::is_constructible<::std::function<F>, G>::value>::type>
- Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
+ template <
+ typename G,
+ typename = typename std::enable_if<internal::disjunction<
+ IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
+ G>>::value>::type>
+ Action(G&& fun) { // NOLINT
+ Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
+ }
// Constructs an Action from its implementation.
explicit Action(ActionInterface<F>* impl)
@@ -396,6 +502,26 @@ class Action {
template <typename G>
friend class Action;
+ template <typename G>
+ void Init(G&& g, ::std::true_type) {
+ fun_ = ::std::forward<G>(g);
+ }
+
+ template <typename G>
+ void Init(G&& g, ::std::false_type) {
+ fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
+ }
+
+ template <typename FunctionImpl>
+ struct IgnoreArgs {
+ template <typename... Args>
+ Result operator()(const Args&...) const {
+ return function_impl();
+ }
+
+ FunctionImpl function_impl;
+ };
+
// fun_ is an empty function if and only if this is the DoDefault() action.
::std::function<F> fun_;
};
@@ -446,13 +572,9 @@ class PolymorphicAction {
private:
Impl impl_;
-
- GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
};
Impl impl_;
-
- GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
};
// Creates an Action from its implementation and returns it. The
@@ -593,13 +715,9 @@ class ReturnAction {
private:
bool performed_;
const std::shared_ptr<R> wrapper_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const std::shared_ptr<R> value_;
-
- GTEST_DISALLOW_ASSIGN_(ReturnAction);
};
// Implements the ReturnNull() action.
@@ -660,13 +778,9 @@ class ReturnRefAction {
private:
T& ref_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
T& ref_;
-
- GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
};
// Implements the polymorphic ReturnRefOfCopy(x) action, which can be
@@ -707,13 +821,9 @@ class ReturnRefOfCopyAction {
private:
T value_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const T value_;
-
- GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
};
// Implements the polymorphic ReturnRoundRobin(v) action, which can be
@@ -770,8 +880,6 @@ class AssignAction {
private:
T1* const ptr_;
const T2 value_;
-
- GTEST_DISALLOW_ASSIGN_(AssignAction);
};
#if !GTEST_OS_WINDOWS_MOBILE
@@ -793,8 +901,6 @@ class SetErrnoAndReturnAction {
private:
const int errno_;
const T result_;
-
- GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
};
#endif // !GTEST_OS_WINDOWS_MOBILE
@@ -846,7 +952,8 @@ struct InvokeMethodWithoutArgsAction {
Class* const obj_ptr;
const MethodPtr method_ptr;
- using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
+ using ReturnType =
+ decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
template <typename... Args>
ReturnType operator()(const Args&...) const {
@@ -899,13 +1006,9 @@ class IgnoreResultAction {
OriginalFunction;
const Action<OriginalFunction> action_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const A action_;
-
- GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
};
template <typename InnerAction, size_t... I>
@@ -930,9 +1033,13 @@ struct WithArgsAction {
template <typename... Actions>
struct DoAllAction {
private:
- template <typename... Args, size_t... I>
- std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
- return {std::get<I>(actions)...};
+ template <typename T>
+ using NonFinalType =
+ typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
+
+ template <typename ActionT, size_t... I>
+ std::vector<ActionT> Convert(IndexSequence<I...>) const {
+ return {ActionT(std::get<I>(actions))...};
}
public:
@@ -941,21 +1048,121 @@ struct DoAllAction {
template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT
struct Op {
- std::vector<Action<void(Args...)>> converted;
+ std::vector<Action<void(NonFinalType<Args>...)>> converted;
Action<R(Args...)> last;
R operator()(Args... args) const {
auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
for (auto& a : converted) {
a.Perform(tuple_args);
}
- return last.Perform(tuple_args);
+ return last.Perform(std::move(tuple_args));
}
};
- return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()),
+ return Op{Convert<Action<void(NonFinalType<Args>...)>>(
+ MakeIndexSequence<sizeof...(Actions) - 1>()),
std::get<sizeof...(Actions) - 1>(actions)};
}
};
+template <typename T, typename... Params>
+struct ReturnNewAction {
+ T* operator()() const {
+ return internal::Apply(
+ [](const Params&... unpacked_params) {
+ return new T(unpacked_params...);
+ },
+ params);
+ }
+ std::tuple<Params...> params;
+};
+
+template <size_t k>
+struct ReturnArgAction {
+ template <typename... Args>
+ auto operator()(const Args&... args) const ->
+ typename std::tuple_element<k, std::tuple<Args...>>::type {
+ return std::get<k>(std::tie(args...));
+ }
+};
+
+template <size_t k, typename Ptr>
+struct SaveArgAction {
+ Ptr pointer;
+
+ template <typename... Args>
+ void operator()(const Args&... args) const {
+ *pointer = std::get<k>(std::tie(args...));
+ }
+};
+
+template <size_t k, typename Ptr>
+struct SaveArgPointeeAction {
+ Ptr pointer;
+
+ template <typename... Args>
+ void operator()(const Args&... args) const {
+ *pointer = *std::get<k>(std::tie(args...));
+ }
+};
+
+template <size_t k, typename T>
+struct SetArgRefereeAction {
+ T value;
+
+ template <typename... Args>
+ void operator()(Args&&... args) const {
+ using argk_type =
+ typename ::std::tuple_element<k, std::tuple<Args...>>::type;
+ static_assert(std::is_lvalue_reference<argk_type>::value,
+ "Argument must be a reference type.");
+ std::get<k>(std::tie(args...)) = value;
+ }
+};
+
+template <size_t k, typename I1, typename I2>
+struct SetArrayArgumentAction {
+ I1 first;
+ I2 last;
+
+ template <typename... Args>
+ void operator()(const Args&... args) const {
+ auto value = std::get<k>(std::tie(args...));
+ for (auto it = first; it != last; ++it, (void)++value) {
+ *value = *it;
+ }
+ }
+};
+
+template <size_t k>
+struct DeleteArgAction {
+ template <typename... Args>
+ void operator()(const Args&... args) const {
+ delete std::get<k>(std::tie(args...));
+ }
+};
+
+template <typename Ptr>
+struct ReturnPointeeAction {
+ Ptr pointer;
+ template <typename... Args>
+ auto operator()(const Args&...) const -> decltype(*pointer) {
+ return *pointer;
+ }
+};
+
+#if GTEST_HAS_EXCEPTIONS
+template <typename T>
+struct ThrowAction {
+ T exception;
+ // We use a conversion operator to adapt to any return type.
+ template <typename R, typename... Args>
+ operator Action<R(Args...)>() const { // NOLINT
+ T copy = exception;
+ return [copy](Args...) -> R { throw copy; };
+ }
+};
+#endif // GTEST_HAS_EXCEPTIONS
+
} // namespace internal
// An Unused object can be implicitly constructed from ANY value.
@@ -991,7 +1198,8 @@ struct DoAllAction {
typedef internal::IgnoredValue Unused;
// Creates an action that does actions a1, a2, ..., sequentially in
-// each invocation.
+// each invocation. All but the last action will have a readonly view of the
+// arguments.
template <typename... Action>
internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
Action&&... action) {
@@ -1184,6 +1392,76 @@ inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
return ::std::reference_wrapper<T>(l_value);
}
+// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
+// instance of type T, constructed on the heap with constructor arguments
+// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
+template <typename T, typename... Params>
+internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
+ Params&&... params) {
+ return {std::forward_as_tuple(std::forward<Params>(params)...)};
+}
+
+// Action ReturnArg<k>() returns the k-th argument of the mock function.
+template <size_t k>
+internal::ReturnArgAction<k> ReturnArg() {
+ return {};
+}
+
+// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
+// mock function to *pointer.
+template <size_t k, typename Ptr>
+internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
+ return {pointer};
+}
+
+// Action SaveArgPointee<k>(pointer) saves the value pointed to
+// by the k-th (0-based) argument of the mock function to *pointer.
+template <size_t k, typename Ptr>
+internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
+ return {pointer};
+}
+
+// Action SetArgReferee<k>(value) assigns 'value' to the variable
+// referenced by the k-th (0-based) argument of the mock function.
+template <size_t k, typename T>
+internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
+ T&& value) {
+ return {std::forward<T>(value)};
+}
+
+// Action SetArrayArgument<k>(first, last) copies the elements in
+// source range [first, last) to the array pointed to by the k-th
+// (0-based) argument, which can be either a pointer or an
+// iterator. The action does not take ownership of the elements in the
+// source range.
+template <size_t k, typename I1, typename I2>
+internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
+ I2 last) {
+ return {first, last};
+}
+
+// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
+// function.
+template <size_t k>
+internal::DeleteArgAction<k> DeleteArg() {
+ return {};
+}
+
+// This action returns the value pointed to by 'pointer'.
+template <typename Ptr>
+internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
+ return {pointer};
+}
+
+// Action Throw(exception) can be used in a mock function of any type
+// to throw the given exception. Any copyable value can be thrown.
+#if GTEST_HAS_EXCEPTIONS
+template <typename T>
+internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
+ return {std::forward<T>(exception)};
+}
+#endif // GTEST_HAS_EXCEPTIONS
+
namespace internal {
// A macro from the ACTION* family (defined later in gmock-generated-actions.h)
@@ -1202,33 +1480,208 @@ namespace internal {
// TYPE DIRECTLY.
struct ExcessiveArg {};
-// A helper class needed for implementing the ACTION* macros.
-template <typename Result, class Impl>
-class ActionHelper {
- public:
- template <typename... Ts>
- static Result Perform(Impl* impl, const std::tuple<Ts...>& args) {
- return Apply(impl, args, MakeIndexSequence<sizeof...(Ts)>{},
- MakeIndexSequence<10 - sizeof...(Ts)>{});
+// Builds an implementation of an Action<> for some particular signature, using
+// a class defined by an ACTION* macro.
+template <typename F, typename Impl> struct ActionImpl;
+
+template <typename Impl>
+struct ImplBase {
+ struct Holder {
+ // Allows each copy of the Action<> to get to the Impl.
+ explicit operator const Impl&() const { return *ptr; }
+ std::shared_ptr<Impl> ptr;
+ };
+ using type = typename std::conditional<std::is_constructible<Impl>::value,
+ Impl, Holder>::type;
+};
+
+template <typename R, typename... Args, typename Impl>
+struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
+ using Base = typename ImplBase<Impl>::type;
+ using function_type = R(Args...);
+ using args_type = std::tuple<Args...>;
+
+ ActionImpl() = default; // Only defined if appropriate for Base.
+ explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} { }
+
+ R operator()(Args&&... arg) const {
+ static constexpr size_t kMaxArgs =
+ sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
+ return Apply(MakeIndexSequence<kMaxArgs>{},
+ MakeIndexSequence<10 - kMaxArgs>{},
+ args_type{std::forward<Args>(arg)...});
}
- private:
- template <typename... Ts, std::size_t... tuple_ids, std::size_t... rest_ids>
- static Result Apply(Impl* impl, const std::tuple<Ts...>& args,
- IndexSequence<tuple_ids...>, IndexSequence<rest_ids...>) {
- return impl->template gmock_PerformImpl<Ts...>(
- args, std::get<tuple_ids>(args)...,
- ((void)rest_ids, ExcessiveArg())...);
+ template <std::size_t... arg_id, std::size_t... excess_id>
+ R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
+ const args_type& args) const {
+ // Impl need not be specific to the signature of action being implemented;
+ // only the implementing function body needs to have all of the specific
+ // types instantiated. Up to 10 of the args that are provided by the
+ // args_type get passed, followed by a dummy of unspecified type for the
+ // remainder up to 10 explicit args.
+ static constexpr ExcessiveArg kExcessArg{};
+ return static_cast<const Impl&>(*this).template gmock_PerformImpl<
+ /*function_type=*/function_type, /*return_type=*/R,
+ /*args_type=*/args_type,
+ /*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>(
+ /*args=*/args, std::get<arg_id>(args)...,
+ ((void)excess_id, kExcessArg)...);
}
};
+// Stores a default-constructed Impl as part of the Action<>'s
+// std::function<>. The Impl should be trivial to copy.
+template <typename F, typename Impl>
+::testing::Action<F> MakeAction() {
+ return ::testing::Action<F>(ActionImpl<F, Impl>());
+}
+
+// Stores just the one given instance of Impl.
+template <typename F, typename Impl>
+::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
+ return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));
+}
+
+#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
+ , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
+#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
+ const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
+ GMOCK_INTERNAL_ARG_UNUSED, , 10)
+
+#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
+#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
+ const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
+
+#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
+#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
+ GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
+
+#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
+#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
+
+#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
+#define GMOCK_ACTION_TYPE_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
+
+#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
+ , param##_type gmock_p##i
+#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
+
+#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
+ , std::forward<param##_type>(gmock_p##i)
+#define GMOCK_ACTION_GVALUE_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
+
+#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
+ , param(::std::forward<param##_type>(gmock_p##i))
+#define GMOCK_ACTION_INIT_PARAMS_(params) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
+
+#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
+#define GMOCK_ACTION_FIELD_PARAMS_(params) \
+ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
+
+#define GMOCK_INTERNAL_ACTION(name, full_name, params) \
+ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
+ class full_name { \
+ public: \
+ explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
+ : impl_(std::make_shared<gmock_Impl>( \
+ GMOCK_ACTION_GVALUE_PARAMS_(params))) { } \
+ full_name(const full_name&) = default; \
+ full_name(full_name&&) noexcept = default; \
+ template <typename F> \
+ operator ::testing::Action<F>() const { \
+ return ::testing::internal::MakeAction<F>(impl_); \
+ } \
+ private: \
+ class gmock_Impl { \
+ public: \
+ explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
+ : GMOCK_ACTION_INIT_PARAMS_(params) {} \
+ template <typename function_type, typename return_type, \
+ typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
+ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
+ GMOCK_ACTION_FIELD_PARAMS_(params) \
+ }; \
+ std::shared_ptr<const gmock_Impl> impl_; \
+ }; \
+ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
+ inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
+ GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
+ return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
+ GMOCK_ACTION_GVALUE_PARAMS_(params)); \
+ } \
+ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
+ template <typename function_type, typename return_type, typename args_type, \
+ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
+ return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl:: \
+ gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
+
} // namespace internal
+// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
+#define ACTION(name) \
+ class name##Action { \
+ public: \
+ explicit name##Action() noexcept {} \
+ name##Action(const name##Action&) noexcept {} \
+ template <typename F> \
+ operator ::testing::Action<F>() const { \
+ return ::testing::internal::MakeAction<F, gmock_Impl>(); \
+ } \
+ private: \
+ class gmock_Impl { \
+ public: \
+ template <typename function_type, typename return_type, \
+ typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
+ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
+ }; \
+ }; \
+ inline name##Action name() GTEST_MUST_USE_RESULT_; \
+ inline name##Action name() { return name##Action(); } \
+ template <typename function_type, typename return_type, typename args_type, \
+ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
+ return_type name##Action::gmock_Impl::gmock_PerformImpl( \
+ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
+
+#define ACTION_P(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
+
+#define ACTION_P2(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
+
+#define ACTION_P3(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
+
+#define ACTION_P4(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
+
+#define ACTION_P5(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
+
+#define ACTION_P6(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
+
+#define ACTION_P7(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
+
+#define ACTION_P8(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
+
+#define ACTION_P9(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
+
+#define ACTION_P10(name, ...) \
+ GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
+
} // namespace testing
#ifdef _MSC_VER
# pragma warning(pop)
#endif
-
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
diff --git a/googlemock/include/gmock/gmock-cardinalities.h b/googlemock/include/gmock/gmock-cardinalities.h
index 46e01e10..fc7f803a 100644
--- a/googlemock/include/gmock/gmock-cardinalities.h
+++ b/googlemock/include/gmock/gmock-cardinalities.h
@@ -36,8 +36,8 @@
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#include <limits.h>
#include <memory>
@@ -154,4 +154,4 @@ inline Cardinality MakeCardinality(const CardinalityInterface* c) {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h
index c5291412..0fc6f6f3 100644
--- a/googlemock/include/gmock/gmock-function-mocker.h
+++ b/googlemock/include/gmock/gmock-function-mocker.h
@@ -33,17 +33,45 @@
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
-#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
-#include "gmock/gmock-generated-function-mockers.h" // NOLINT
+#include <type_traits> // IWYU pragma: keep
+#include <utility> // IWYU pragma: keep
+
+#include "gmock/gmock-spec-builders.h"
+#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-pp.h"
namespace testing {
namespace internal {
template <typename T>
using identity_t = T;
+
+template <typename Pattern>
+struct ThisRefAdjuster {
+ template <typename T>
+ using AdjustT = typename std::conditional<
+ std::is_const<typename std::remove_reference<Pattern>::type>::value,
+ typename std::conditional<std::is_lvalue_reference<Pattern>::value,
+ const T&, const T&&>::type,
+ typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&,
+ T&&>::type>::type;
+
+ template <typename MockType>
+ static AdjustT<MockType> Adjust(const MockType& mock) {
+ return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock));
+ }
+};
+
} // namespace internal
+
+// The style guide prohibits "using" statements in a namespace scope
+// inside a header file. However, the FunctionMocker class template
+// is meant to be defined in the ::testing namespace. The following
+// line is just a trick for working around a bug in MSVC 8.0, which
+// cannot handle it if we define FunctionMocker in ::testing.
+using internal::FunctionMocker;
} // namespace testing
#define MOCK_METHOD(...) \
@@ -58,17 +86,17 @@ using identity_t = T;
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \
GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())
-#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \
- GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \
- GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \
- GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
- GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \
- GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
- GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
- GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
- GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
- GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \
- GMOCK_INTERNAL_GET_CALLTYPE(_Spec), \
+#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \
+ GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \
+ GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \
+ GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
+ GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \
+ GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
+ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
+ GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
+ GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
+ GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \
+ GMOCK_INTERNAL_GET_CALLTYPE(_Spec), GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \
(GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
@@ -102,19 +130,19 @@ using identity_t = T;
::testing::tuple_size<typename ::testing::internal::Function< \
__VA_ARGS__>::ArgumentTuple>::value == _N, \
"This method does not take " GMOCK_PP_STRINGIZE( \
- _N) " arguments. Parenthesize all types with unproctected commas.")
+ _N) " arguments. Parenthesize all types with unprotected commas.")
#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)
#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \
_Override, _Final, _NoexceptSpec, \
- _CallType, _Signature) \
+ _CallType, _RefSpec, _Signature) \
typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \
_Signature)>::Result \
GMOCK_INTERNAL_EXPAND(_CallType) \
_MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
- GMOCK_PP_IF(_Constness, const, ) _NoexceptSpec \
+ GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \
GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \
GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.SetOwnerAndName(this, #_MethodName); \
@@ -123,7 +151,7 @@ using identity_t = T;
} \
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \
- GMOCK_PP_IF(_Constness, const, ) { \
+ GMOCK_PP_IF(_Constness, const, ) _RefSpec { \
GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \
return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
.With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \
@@ -131,10 +159,10 @@ using identity_t = T;
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
const ::testing::internal::WithoutMatchers&, \
GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \
- GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _NoexceptSpec { \
- return GMOCK_PP_CAT(::testing::internal::AdjustConstness_, \
- GMOCK_PP_IF(_Constness, const, ))(this) \
- ->gmock_##_MethodName(GMOCK_PP_REPEAT( \
+ GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \
+ return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \
+ _Constness, const, ) int _RefSpec>::Adjust(*this) \
+ .gmock_##_MethodName(GMOCK_PP_REPEAT( \
GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
} \
mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
@@ -161,6 +189,13 @@ using identity_t = T;
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \
_elem, )
+#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \
+ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)
+
+#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \
+ GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
+ GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
+
#define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple)
@@ -170,6 +205,7 @@ using identity_t = T;
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \
+ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \
GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \
GMOCK_PP_STRINGIZE( \
_elem) " cannot be recognized as a valid specification modifier.");
@@ -195,6 +231,13 @@ using identity_t = T;
#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,
+#define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \
+ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem)
+
+#define GMOCK_INTERNAL_DETECT_REF_I_ref ,
+
+#define GMOCK_INTERNAL_UNPACK_ref(x) x
+
#define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \
GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \
GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
@@ -212,7 +255,7 @@ using identity_t = T;
GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \
GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \
- GMOCK_PP_CAT(GMOCK_PP_IDENTITY, _arg)
+ GMOCK_PP_IDENTITY _arg
#define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
@@ -241,36 +284,196 @@ using identity_t = T;
GMOCK_PP_IDENTITY) \
(_elem)
-#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
- GMOCK_PP_COMMA_IF(_i) \
- GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \
- GMOCK_PP_REMOVE_PARENS(_Signature)) \
+#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
+ GMOCK_PP_COMMA_IF(_i) \
+ GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i
-#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
- GMOCK_PP_COMMA_IF(_i) \
- ::std::forward<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \
- GMOCK_PP_REMOVE_PARENS(_Signature))>( \
- gmock_a##_i)
+#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
+ GMOCK_PP_COMMA_IF(_i) \
+ ::std::forward<GMOCK_INTERNAL_ARG_O( \
+ _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)
-#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
- GMOCK_PP_COMMA_IF(_i) \
- GMOCK_INTERNAL_MATCHER_O(typename, GMOCK_PP_INC(_i), \
- GMOCK_PP_REMOVE_PARENS(_Signature)) \
+#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
+ GMOCK_PP_COMMA_IF(_i) \
+ GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i
#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
GMOCK_PP_COMMA_IF(_i) \
gmock_a##_i
-#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
- GMOCK_PP_COMMA_IF(_i) \
- ::testing::A<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \
- GMOCK_PP_REMOVE_PARENS(_Signature))>()
-
-#define GMOCK_INTERNAL_ARG_O(_tn, _i, ...) GMOCK_ARG_(_tn, _i, __VA_ARGS__)
-
-#define GMOCK_INTERNAL_MATCHER_O(_tn, _i, ...) \
- GMOCK_MATCHER_(_tn, _i, __VA_ARGS__)
-
-#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
+#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
+ GMOCK_PP_COMMA_IF(_i) \
+ ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()
+
+#define GMOCK_INTERNAL_ARG_O(_i, ...) \
+ typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type
+
+#define GMOCK_INTERNAL_MATCHER_O(_i, ...) \
+ const ::testing::Matcher<typename ::testing::internal::Function< \
+ __VA_ARGS__>::template Arg<_i>::type>&
+
+#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)
+#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)
+#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)
+#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)
+#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)
+#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)
+#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)
+#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)
+#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)
+#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)
+#define MOCK_METHOD10(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)
+
+#define MOCK_CONST_METHOD0(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)
+#define MOCK_CONST_METHOD1(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)
+#define MOCK_CONST_METHOD2(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)
+#define MOCK_CONST_METHOD3(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)
+#define MOCK_CONST_METHOD4(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)
+#define MOCK_CONST_METHOD5(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)
+#define MOCK_CONST_METHOD6(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)
+#define MOCK_CONST_METHOD7(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)
+#define MOCK_CONST_METHOD8(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)
+#define MOCK_CONST_METHOD9(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)
+#define MOCK_CONST_METHOD10(m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)
+
+#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)
+#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)
+#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)
+#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)
+#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)
+#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)
+#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)
+#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)
+#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)
+#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)
+#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)
+
+#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)
+#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)
+
+#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)
+#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)
+#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)
+#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)
+#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)
+#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)
+#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)
+#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)
+#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)
+#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)
+#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)
+
+#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)
+#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)
+#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)
+#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)
+#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)
+#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)
+#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)
+#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)
+#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)
+#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)
+#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
+ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)
+
+#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+
+#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
+ MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
+
+#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \
+ GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
+ args_num, ::testing::internal::identity_t<__VA_ARGS__>); \
+ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
+ args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \
+ (::testing::internal::identity_t<__VA_ARGS__>))
+
+#define GMOCK_MOCKER_(arity, constness, Method) \
+ GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
+
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h
deleted file mode 100644
index 20b78cd4..00000000
--- a/googlemock/include/gmock/gmock-generated-actions.h
+++ /dev/null
@@ -1,1757 +0,0 @@
-// This file was GENERATED by command:
-// pump.py gmock-generated-actions.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 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"
-
-// The ACTION* family of macros can be used in a namespace scope to
-// define custom actions easily. The syntax:
-//
-// ACTION(name) { statements; }
-//
-// will define an action with the given name that executes the
-// statements. The value returned by the statements will be used as
-// the return value of the action. Inside the statements, you can
-// refer to the K-th (0-based) argument of the mock function by
-// 'argK', and refer to its type by 'argK_type'. For example:
-//
-// ACTION(IncrementArg1) {
-// arg1_type temp = arg1;
-// return ++(*temp);
-// }
-//
-// allows you to write
-//
-// ...WillOnce(IncrementArg1());
-//
-// You can also refer to the entire argument tuple and its type by
-// 'args' and 'args_type', and refer to the mock function type and its
-// return type by 'function_type' and 'return_type'.
-//
-// Note that you don't need to specify the types of the mock function
-// arguments. However rest assured that your code is still type-safe:
-// you'll get a compiler error if *arg1 doesn't support the ++
-// operator, or if the type of ++(*arg1) isn't compatible with the
-// mock function's return type, for example.
-//
-// Sometimes you'll want to parameterize the action. For that you can use
-// another macro:
-//
-// ACTION_P(name, param_name) { statements; }
-//
-// For example:
-//
-// ACTION_P(Add, n) { return arg0 + n; }
-//
-// will allow you to write:
-//
-// ...WillOnce(Add(5));
-//
-// Note that you don't need to provide the type of the parameter
-// either. If you need to reference the type of a parameter named
-// 'foo', you can write 'foo_type'. For example, in the body of
-// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
-// of 'n'.
-//
-// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
-// multi-parameter actions.
-//
-// For the purpose of typing, you can view
-//
-// ACTION_Pk(Foo, p1, ..., pk) { ... }
-//
-// as shorthand for
-//
-// template <typename p1_type, ..., typename pk_type>
-// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
-//
-// In particular, you can provide the template type arguments
-// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
-// although usually you can rely on the compiler to infer the types
-// for you automatically. You can assign the result of expression
-// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
-// pk_type>. This can be useful when composing actions.
-//
-// You can also overload actions with different numbers of parameters:
-//
-// ACTION_P(Plus, a) { ... }
-// ACTION_P2(Plus, a, b) { ... }
-//
-// While it's tempting to always use the ACTION* macros when defining
-// a new action, you should also consider implementing ActionInterface
-// or using MakePolymorphicAction() instead, especially if you need to
-// use the action a lot. While these approaches require more work,
-// they give you more control on the types of the mock function
-// arguments and the action parameters, which in general leads to
-// better compiler error messages that pay off in the long run. They
-// also allow overloading actions based on parameter types (as opposed
-// to just based on the number of parameters).
-//
-// CAVEAT:
-//
-// ACTION*() can only be used in a namespace scope as templates cannot be
-// declared inside of a local class.
-// Users can, however, define any local functors (e.g. a lambda) that
-// can be used as actions.
-//
-// MORE INFORMATION:
-//
-// To learn more about using these macros, please search for 'ACTION' on
-// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
-
-// An internal macro needed for implementing ACTION*().
-#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
- const args_type& args GTEST_ATTRIBUTE_UNUSED_, \
- const arg0_type& arg0 GTEST_ATTRIBUTE_UNUSED_, \
- const arg1_type& arg1 GTEST_ATTRIBUTE_UNUSED_, \
- const arg2_type& arg2 GTEST_ATTRIBUTE_UNUSED_, \
- const arg3_type& arg3 GTEST_ATTRIBUTE_UNUSED_, \
- const arg4_type& arg4 GTEST_ATTRIBUTE_UNUSED_, \
- const arg5_type& arg5 GTEST_ATTRIBUTE_UNUSED_, \
- const arg6_type& arg6 GTEST_ATTRIBUTE_UNUSED_, \
- const arg7_type& arg7 GTEST_ATTRIBUTE_UNUSED_, \
- const arg8_type& arg8 GTEST_ATTRIBUTE_UNUSED_, \
- const arg9_type& arg9 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.
-#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
-#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
- name1) kind0 name0, kind1 name1
-#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2) kind0 name0, kind1 name1, kind2 name2
-#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
- kind3 name3
-#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
- kind2 name2, kind3 name3, kind4 name4
-#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
- kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
-#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
- name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
- kind5 name5, kind6 name6
-#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
- kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
- kind4 name4, kind5 name5, kind6 name6, kind7 name7
-#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
- kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
- kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
- kind8 name8
-#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
- name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
- name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
- kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
- kind6 name6, kind7 name7, kind8 name8, kind9 name9
-
-// Lists the template parameters.
-#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
-#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
- name1) name0, name1
-#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2) name0, name1, name2
-#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3) name0, name1, name2, name3
-#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
- name4
-#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
- name2, name3, name4, name5
-#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
- name6) name0, name1, name2, name3, name4, name5, name6
-#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
- kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
-#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
- kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
- kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
- name6, name7, name8
-#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
- name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
- name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
- name3, name4, name5, name6, name7, name8, name9
-
-// Declares the types of value parameters.
-#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
- typename p0##_type, typename p1##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
- typename p0##_type, typename p1##_type, typename p2##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
- typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
- typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
- typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type
-#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
- typename p2##_type, typename p3##_type, typename p4##_type, \
- typename p5##_type, typename p6##_type, typename p7##_type, \
- typename p8##_type, typename p9##_type
-
-// Initializes the value parameters.
-#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
- ()
-#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
- (p0##_type gmock_p0) : p0(::std::move(gmock_p0))
-#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
- (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1))
-#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
- (p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
-#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
- (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3))
-#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
- (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
-#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
- (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5))
-#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
- (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
-#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
- (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
- p7(::std::move(gmock_p7))
-#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8)\
- (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6, p7##_type gmock_p7, \
- p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
- p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
-#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8, p9)\
- (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
- p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
- p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
- p9(::std::move(gmock_p9))
-
-// Declares the fields for storing the value parameters.
-#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
-#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
- p1##_type p1;
-#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
- p1##_type p1; p2##_type p2;
-#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
- p1##_type p1; p2##_type p2; p3##_type p3;
-#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
- p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
-#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
- p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
- p5##_type p5;
-#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
- p5##_type p5; p6##_type p6;
-#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
- p5##_type p5; p6##_type p6; p7##_type p7;
-#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
- p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
-#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
- p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
- p9##_type p9;
-
-// Lists the value parameters.
-#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
-#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
-#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
-#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
-#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
- p2, p3, p4
-#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
- p1, p2, p3, p4, p5
-#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6) p0, p1, p2, p3, p4, p5, p6
-#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7) p0, p1, p2, p3, p4, p5, p6, p7
-#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
-#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
-
-// Lists the value parameter types.
-#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
- p1##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
- p1##_type, p2##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
- p0##_type, p1##_type, p2##_type, p3##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
- p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
- p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
- p6##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, p7##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, p7##_type, p8##_type
-#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
-
-// Declares the value parameters.
-#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
-#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
- p1##_type p1
-#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
- p1##_type p1, p2##_type p2
-#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
- p1##_type p1, p2##_type p2, p3##_type p3
-#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
- p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
-#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
- p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
- p5##_type p5
-#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
- p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
- p5##_type p5, p6##_type p6
-#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
- p5##_type p5, p6##_type p6, p7##_type p7
-#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
-#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
- p9##_type p9
-
-// The suffix of the class template implementing the action template.
-#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
-#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
-#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
-#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
-#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
-#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
-#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
-#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
-#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7) P8
-#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8) P9
-#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
- p7, p8, p9) P10
-
-// The name of the class template implementing the action template.
-#define GMOCK_ACTION_CLASS_(name, value_params)\
- GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
-
-#define ACTION_TEMPLATE(name, template_params, value_params)\
- template <GMOCK_INTERNAL_DECL_##template_params\
- GMOCK_INTERNAL_DECL_TYPE_##value_params>\
- class GMOCK_ACTION_CLASS_(name, value_params) {\
- public:\
- explicit GMOCK_ACTION_CLASS_(name, value_params)\
- GMOCK_INTERNAL_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 {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) 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
-
-#define ACTION(name)\
- class name##Action {\
- public:\
- name##Action() {}\
- 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;\
- gmock_Impl() {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>());\
- }\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##Action);\
- };\
- inline name##Action name() {\
- return name##Action();\
- }\
- 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\
- name##Action::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P(name, p0)\
- template <typename p0##_type>\
- class name##ActionP {\
- public:\
- explicit name##ActionP(p0##_type gmock_p0) : \
- p0(::std::forward<p0##_type>(gmock_p0)) {}\
- 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(p0##_type gmock_p0) : \
- p0(::std::forward<p0##_type>(gmock_p0)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0));\
- }\
- p0##_type p0;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP);\
- };\
- template <typename p0##_type>\
- inline name##ActionP<p0##_type> name(p0##_type p0) {\
- return name##ActionP<p0##_type>(p0);\
- }\
- template <typename p0##_type>\
- 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\
- name##ActionP<p0##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P2(name, p0, p1)\
- template <typename p0##_type, typename p1##_type>\
- class name##ActionP2 {\
- public:\
- name##ActionP2(p0##_type gmock_p0, \
- p1##_type gmock_p1) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)) {}\
- 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;\
- gmock_Impl(p0##_type gmock_p0, \
- p1##_type gmock_p1) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP2);\
- };\
- template <typename p0##_type, typename p1##_type>\
- inline name##ActionP2<p0##_type, p1##_type> name(p0##_type p0, \
- p1##_type p1) {\
- return name##ActionP2<p0##_type, p1##_type>(p0, p1);\
- }\
- template <typename p0##_type, typename p1##_type>\
- 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\
- name##ActionP2<p0##_type, p1##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P3(name, p0, p1, p2)\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- class name##ActionP3 {\
- public:\
- name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)) {}\
- 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;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP3);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- inline name##ActionP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \
- p1##_type p1, p2##_type p2) {\
- return name##ActionP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- 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\
- name##ActionP3<p0##_type, p1##_type, \
- p2##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P4(name, p0, p1, p2, p3)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- class name##ActionP4 {\
- public:\
- name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, \
- p3##_type gmock_p3) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)) {}\
- 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;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP4);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- inline name##ActionP4<p0##_type, p1##_type, p2##_type, \
- p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
- p3##_type p3) {\
- return name##ActionP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, p1, \
- p2, p3);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- 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\
- name##ActionP4<p0##_type, p1##_type, p2##_type, \
- p3##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P5(name, p0, p1, p2, p3, p4)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- class name##ActionP5 {\
- public:\
- name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, \
- p4##_type gmock_p4) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)) {}\
- 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;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, \
- p4##_type gmock_p4) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP5);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- inline name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4) {\
- return name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>(p0, p1, p2, p3, p4);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- 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\
- name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P6(name, p0, p1, p2, p3, p4, p5)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- class name##ActionP6 {\
- public:\
- name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)) {}\
- 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;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP6);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- inline name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
- p3##_type p3, p4##_type p4, p5##_type p5) {\
- return name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- 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\
- name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- class name##ActionP7 {\
- public:\
- name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5, \
- p6##_type gmock_p6) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)) {}\
- 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;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
- p6));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP7);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- inline name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \
- p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
- p6##_type p6) {\
- return name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- 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\
- name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- class name##ActionP8 {\
- public:\
- name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5, p6##_type gmock_p6, \
- p7##_type gmock_p7) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)) {}\
- 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;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6, \
- p7##_type gmock_p7) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- p7##_type p7;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
- p6, p7));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- p7##_type p7;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP8);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- inline name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \
- p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
- p6##_type p6, p7##_type p7) {\
- return name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \
- p6, p7);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- 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\
- name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, \
- p7##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type>\
- class name##ActionP9 {\
- public:\
- name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
- p8##_type gmock_p8) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)), \
- p8(::std::forward<p8##_type>(gmock_p8)) {}\
- 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;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6, p7##_type gmock_p7, \
- p8##_type gmock_p8) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)), \
- p8(::std::forward<p8##_type>(gmock_p8)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- p7##_type p7;\
- p8##_type p8;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
- p6, p7, p8));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- p7##_type p7;\
- p8##_type p8;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP9);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type>\
- inline name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, \
- p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \
- p8##_type p8) {\
- return name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \
- p3, p4, p5, p6, p7, p8);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type>\
- 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\
- name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, p7##_type, \
- p8##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-#define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type, \
- typename p9##_type>\
- class name##ActionP10 {\
- public:\
- name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
- p8##_type gmock_p8, \
- p9##_type gmock_p9) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)), \
- p8(::std::forward<p8##_type>(gmock_p8)), \
- p9(::std::forward<p9##_type>(gmock_p9)) {}\
- 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;\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
- p9##_type gmock_p9) : p0(::std::forward<p0##_type>(gmock_p0)), \
- p1(::std::forward<p1##_type>(gmock_p1)), \
- p2(::std::forward<p2##_type>(gmock_p2)), \
- p3(::std::forward<p3##_type>(gmock_p3)), \
- p4(::std::forward<p4##_type>(gmock_p4)), \
- p5(::std::forward<p5##_type>(gmock_p5)), \
- p6(::std::forward<p6##_type>(gmock_p6)), \
- p7(::std::forward<p7##_type>(gmock_p7)), \
- p8(::std::forward<p8##_type>(gmock_p8)), \
- p9(::std::forward<p9##_type>(gmock_p9)) {}\
- return_type Perform(const args_type& args) override {\
- return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
- Perform(this, args);\
- }\
- 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>\
- return_type gmock_PerformImpl(const args_type& args, \
- const arg0_type& arg0, const arg1_type& arg1, \
- const arg2_type& arg2, const arg3_type& arg3, \
- const arg4_type& arg4, const arg5_type& arg5, \
- const arg6_type& arg6, const arg7_type& arg7, \
- const arg8_type& arg8, const arg9_type& arg9) const;\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- p7##_type p7;\
- p8##_type p8;\
- p9##_type p9;\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
- };\
- template <typename F> operator ::testing::Action<F>() const {\
- return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \
- p6, p7, p8, p9));\
- }\
- p0##_type p0;\
- p1##_type p1;\
- p2##_type p2;\
- p3##_type p3;\
- p4##_type p4;\
- p5##_type p5;\
- p6##_type p6;\
- p7##_type p7;\
- p8##_type p8;\
- p9##_type p9;\
- private:\
- GTEST_DISALLOW_ASSIGN_(name##ActionP10);\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type, \
- typename p9##_type>\
- inline name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
- p9##_type p9) {\
- return name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \
- p1, p2, p3, p4, p5, p6, p7, p8, p9);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type, \
- typename p9##_type>\
- 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\
- name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type>::gmock_Impl<F>::gmock_PerformImpl(\
- GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
-
-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/gmock-generated-actions.h header.
-
-template <typename R, typename F>
-R InvokeArgumentAdl(AdlTag, F f) {
- return f();
-}
-template <typename R, typename F, typename A1>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1) {
- return f(a1);
-}
-template <typename R, typename F, typename A1, typename A2>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) {
- return f(a1, a2);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) {
- return f(a1, a2, a3);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) {
- return f(a1, a2, a3, a4);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) {
- return f(a1, a2, a3, a4, a5);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) {
- return f(a1, a2, a3, a4, a5, a6);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6, typename A7>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
- A7 a7) {
- return f(a1, a2, a3, a4, a5, a6, a7);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6, typename A7, typename A8>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
- A7 a7, A8 a8) {
- return f(a1, a2, a3, a4, a5, a6, a7, a8);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6, typename A7, typename A8,
- typename A9>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
- A7 a7, A8 a8, A9 a9) {
- return f(a1, a2, a3, a4, a5, a6, a7, a8, a9);
-}
-template <typename R, typename F, typename A1, typename A2, typename A3,
- typename A4, typename A5, typename A6, typename A7, typename A8,
- typename A9, typename A10>
-R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
- A7 a7, A8 a8, A9 a9, A10 a10) {
- return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
-}
-} // namespace invoke_argument
-} // namespace internal
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_0_VALUE_PARAMS()) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args));
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_1_VALUE_PARAMS(p0)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_2_VALUE_PARAMS(p0, p1)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_3_VALUE_PARAMS(p0, p1, p2)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_4_VALUE_PARAMS(p0, p1, p2, p3)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8);
-}
-
-ACTION_TEMPLATE(InvokeArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) {
- using internal::invoke_argument::InvokeArgumentAdl;
- return InvokeArgumentAdl<return_type>(
- internal::invoke_argument::AdlTag(),
- ::std::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
-}
-
-// 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.
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_0_VALUE_PARAMS()) {
- return new T();
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_1_VALUE_PARAMS(p0)) {
- return new T(p0);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_2_VALUE_PARAMS(p0, p1)) {
- return new T(p0, p1);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_3_VALUE_PARAMS(p0, p1, p2)) {
- return new T(p0, p1, p2);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_4_VALUE_PARAMS(p0, p1, p2, p3)) {
- return new T(p0, p1, p2, p3);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) {
- return new T(p0, p1, p2, p3, p4);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) {
- return new T(p0, p1, p2, p3, p4, p5);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) {
- return new T(p0, p1, p2, p3, p4, p5, p6);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) {
- return new T(p0, p1, p2, p3, p4, p5, p6, p7);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) {
- return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) {
- return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
-}
-
-#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_
diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump
deleted file mode 100644
index 1121fbde..00000000
--- a/googlemock/include/gmock/gmock-generated-actions.h.pump
+++ /dev/null
@@ -1,579 +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"
-
-// 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 {}\
- return_type Perform(const args_type& args) override {\
- 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 {}\
- return_type Perform(const args_type& args) override {\
- 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/gmock-generated-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_
diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h
deleted file mode 100644
index cd957817..00000000
--- a/googlemock/include/gmock/gmock-generated-function-mockers.h
+++ /dev/null
@@ -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_
diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump
deleted file mode 100644
index a56e132f..00000000
--- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump
+++ /dev/null
@@ -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_
diff --git a/googlemock/include/gmock/gmock-generated-matchers.h b/googlemock/include/gmock/gmock-generated-matchers.h
deleted file mode 100644
index 61892380..00000000
--- a/googlemock/include/gmock/gmock-generated-matchers.h
+++ /dev/null
@@ -1,1097 +0,0 @@
-// This file was GENERATED by command:
-// pump.py gmock-generated-matchers.h.pump
-// DO NOT EDIT BY HAND!!!
-
-// 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_P10 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
-
-#define MATCHER(name, description)\
- class name##Matcher {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl()\
- {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- 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<>()));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>());\
- }\
- name##Matcher() {\
- }\
- private:\
- };\
- inline name##Matcher name() {\
- return name##Matcher();\
- }\
- template <typename arg_type>\
- bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P(name, p0, description)\
- template <typename p0##_type>\
- class name##MatcherP {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- explicit gmock_Impl(p0##_type gmock_p0)\
- : p0(::std::move(gmock_p0)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- 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<p0##_type>(p0)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0));\
- }\
- explicit name##MatcherP(p0##_type gmock_p0) : p0(::std::move(gmock_p0)) {\
- }\
- p0##_type const p0;\
- private:\
- };\
- template <typename p0##_type>\
- inline name##MatcherP<p0##_type> name(p0##_type p0) {\
- return name##MatcherP<p0##_type>(p0);\
- }\
- template <typename p0##_type>\
- template <typename arg_type>\
- bool name##MatcherP<p0##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P2(name, p0, p1, description)\
- template <typename p0##_type, typename p1##_type>\
- class name##MatcherP2 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- 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<p0##_type, p1##_type>(p0, p1)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1));\
- }\
- name##MatcherP2(p0##_type gmock_p0, \
- p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type>\
- inline name##MatcherP2<p0##_type, p1##_type> name(p0##_type p0, \
- p1##_type p1) {\
- return name##MatcherP2<p0##_type, p1##_type>(p0, p1);\
- }\
- template <typename p0##_type, typename p1##_type>\
- template <typename arg_type>\
- bool name##MatcherP2<p0##_type, \
- p1##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P3(name, p0, p1, p2, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- class name##MatcherP3 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \
- p2(::std::move(gmock_p2)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- 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<p0##_type, p1##_type, p2##_type>(p0, p1, p2)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2));\
- }\
- name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- inline name##MatcherP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \
- p1##_type p1, p2##_type p2) {\
- return name##MatcherP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type>\
- template <typename arg_type>\
- bool name##MatcherP3<p0##_type, p1##_type, \
- p2##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P4(name, p0, p1, p2, p3, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- class name##MatcherP4 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \
- p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- 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<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \
- p1, p2, p3)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3));\
- }\
- name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- inline name##MatcherP4<p0##_type, p1##_type, p2##_type, \
- p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
- p3##_type p3) {\
- return name##MatcherP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \
- p1, p2, p3);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type>\
- template <typename arg_type>\
- bool name##MatcherP4<p0##_type, p1##_type, p2##_type, \
- p3##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- class name##MatcherP5 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \
- p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \
- p4(::std::move(gmock_p4)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- 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<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>(p0, p1, p2, p3, p4)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4));\
- }\
- name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, \
- p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- inline name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4) {\
- return name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>(p0, p1, p2, p3, p4);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type>\
- template <typename arg_type>\
- bool name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- class name##MatcherP6 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \
- p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \
- p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- 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<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5));\
- }\
- name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- inline name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \
- p3##_type p3, p4##_type p4, p5##_type p5) {\
- return name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type>\
- template <typename arg_type>\
- bool name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- class name##MatcherP7 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \
- p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \
- p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \
- p6(::std::move(gmock_p6)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- 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<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, \
- p6)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6));\
- }\
- name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5, p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- inline name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \
- p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
- p6##_type p6) {\
- return name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type>\
- template <typename arg_type>\
- bool name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- class name##MatcherP8 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6, p7##_type gmock_p7)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \
- p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \
- p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \
- p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- 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<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, \
- p3, p4, p5, p6, p7)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7));\
- }\
- name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5, p6##_type gmock_p6, \
- p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
- p7(::std::move(gmock_p7)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- inline name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \
- p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \
- p6##_type p6, p7##_type p7) {\
- return name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \
- p6, p7);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type>\
- template <typename arg_type>\
- bool name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, \
- p7##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type>\
- class name##MatcherP9 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \
- p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \
- p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \
- p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)), \
- p8(::std::move(gmock_p8)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- p8##_type const p8;\
- 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<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, \
- p8##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8));\
- }\
- name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
- p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
- p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- p8##_type const p8;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type>\
- inline name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, \
- p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \
- p8##_type p8) {\
- return name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \
- p3, p4, p5, p6, p7, p8);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type>\
- template <typename arg_type>\
- bool name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
- p5##_type, p6##_type, p7##_type, \
- p8##_type>::gmock_Impl<arg_type>::MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
- const
-
-#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type, \
- typename p9##_type>\
- class name##MatcherP10 {\
- public:\
- template <typename arg_type>\
- class gmock_Impl : public ::testing::MatcherInterface<\
- GTEST_REFERENCE_TO_CONST_(arg_type)> {\
- public:\
- gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
- p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
- p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
- p9##_type gmock_p9)\
- : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \
- p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \
- p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \
- p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)), \
- p8(::std::move(gmock_p8)), p9(::std::move(gmock_p9)) {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(true);\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- p8##_type const p8;\
- p9##_type const p9;\
- 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<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\
- }\
- };\
- template <typename arg_type>\
- operator ::testing::Matcher<arg_type>() const {\
- return ::testing::Matcher<arg_type>(\
- new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\
- }\
- name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \
- p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \
- p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \
- p8##_type gmock_p8, p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
- p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
- p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
- p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
- p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
- p9(::std::move(gmock_p9)) {\
- }\
- p0##_type const p0;\
- p1##_type const p1;\
- p2##_type const p2;\
- p3##_type const p3;\
- p4##_type const p4;\
- p5##_type const p5;\
- p6##_type const p6;\
- p7##_type const p7;\
- p8##_type const p8;\
- p9##_type const p9;\
- private:\
- };\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type, \
- typename p9##_type>\
- inline name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
- p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
- p9##_type p9) {\
- return name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \
- p1, p2, p3, p4, p5, p6, p7, p8, p9);\
- }\
- template <typename p0##_type, typename p1##_type, typename p2##_type, \
- typename p3##_type, typename p4##_type, typename p5##_type, \
- typename p6##_type, typename p7##_type, typename p8##_type, \
- typename p9##_type>\
- template <typename arg_type>\
- bool name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \
- p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \
- p9##_type>::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_
diff --git a/googlemock/include/gmock/gmock-generated-matchers.h.pump b/googlemock/include/gmock/gmock-generated-matchers.h.pump
deleted file mode 100644
index 69d2ae41..00000000
--- a/googlemock/include/gmock/gmock-generated-matchers.h.pump
+++ /dev/null
@@ -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 {}\
- bool MatchAndExplain(\
- GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
- ::testing::MatchResultListener* result_listener) const override;\
- void DescribeTo(::std::ostream* gmock_os) const override {\
- *gmock_os << FormatDescription(false);\
- }\
- void DescribeNegationTo(::std::ostream* gmock_os) const override {\
- *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_
diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h
index 93f5ed3a..49aa10ee 100644
--- a/googlemock/include/gmock/gmock-matchers.h
+++ b/googlemock/include/gmock/gmock-matchers.h
@@ -30,7 +30,220 @@
// Google Mock - a framework for writing C++ mock classes.
//
-// This file implements some commonly used argument matchers. More
+// 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/docs/gmock_cook_book.md
+//
+// This file also implements some commonly used argument matchers. More
// matchers can be defined by the user implementing the
// MatcherInterface<T> interface if necessary.
//
@@ -39,8 +252,8 @@
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
#include <algorithm>
#include <cmath>
@@ -57,6 +270,7 @@
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h"
+#include "gmock/internal/gmock-pp.h"
#include "gtest/gtest.h"
// MSVC warning C5046 is new as of VS2017 version 15.8.
@@ -131,7 +345,7 @@ class MatcherCastImpl {
// constructor from M (this usually happens when T has an implicit
// constructor from any type).
//
- // It won't work to unconditionally implict_cast
+ // It won't work to unconditionally implicit_cast
// polymorphic_matcher_or_value to Matcher<T> because it won't trigger
// a user-defined conversion from M to T if one exists (assuming M is
// a value).
@@ -212,7 +426,14 @@ class MatcherCastImpl<T, Matcher<U> > {
!std::is_base_of<FromType, ToType>::value,
"Can't implicitly convert from <base> to <derived>");
- return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
+ // Do the cast to `U` explicitly if necessary.
+ // Otherwise, let implicit conversions do the trick.
+ using CastType =
+ typename std::conditional<std::is_convertible<T&, const U&>::value,
+ T&, U>::type;
+
+ return source_matcher_.MatchAndExplain(static_cast<CastType>(x),
+ listener);
}
void DescribeTo(::std::ostream* os) const override {
@@ -225,8 +446,6 @@ class MatcherCastImpl<T, Matcher<U> > {
private:
const Matcher<U> source_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
};
@@ -238,6 +457,50 @@ class MatcherCastImpl<T, Matcher<T> > {
static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
};
+// Template specialization for parameterless Matcher.
+template <typename Derived>
+class MatcherBaseImpl {
+ public:
+ MatcherBaseImpl() = default;
+
+ template <typename T>
+ operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)
+ return ::testing::Matcher<T>(new
+ typename Derived::template gmock_Impl<T>());
+ }
+};
+
+// Template specialization for Matcher with parameters.
+template <template <typename...> class Derived, typename... Ts>
+class MatcherBaseImpl<Derived<Ts...>> {
+ public:
+ // Mark the constructor explicit for single argument T to avoid implicit
+ // conversions.
+ template <typename E = std::enable_if<sizeof...(Ts) == 1>,
+ typename E::type* = nullptr>
+ explicit MatcherBaseImpl(Ts... params)
+ : params_(std::forward<Ts>(params)...) {}
+ template <typename E = std::enable_if<sizeof...(Ts) != 1>,
+ typename = typename E::type>
+ MatcherBaseImpl(Ts... params) // NOLINT
+ : params_(std::forward<Ts>(params)...) {}
+
+ template <typename F>
+ operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)
+ return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
+ }
+
+ private:
+ template <typename F, std::size_t... tuple_ids>
+ ::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const {
+ return ::testing::Matcher<F>(
+ new typename Derived<Ts...>::template gmock_Impl<F>(
+ std::get<tuple_ids>(params_)...));
+ }
+
+ const std::tuple<Ts...> params_;
+};
+
} // namespace internal
// In order to be safe and clear, casting between different matcher
@@ -268,8 +531,8 @@ inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {
template <typename T, typename U>
inline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
// Enforce that T can be implicitly converted to U.
- GTEST_COMPILE_ASSERT_((std::is_convertible<T, U>::value),
- "T must be implicitly convertible to U");
+ static_assert(std::is_convertible<const T&, const U&>::value,
+ "T must be implicitly convertible to U");
// Enforce that we are not converting a non-reference type T to a reference
// type U.
GTEST_COMPILE_ASSERT_(
@@ -474,31 +737,25 @@ OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
}
-// Implements A<T>().
-template <typename T>
-class AnyMatcherImpl : public MatcherInterface<const T&> {
- public:
- bool MatchAndExplain(const T& /* x */,
- MatchResultListener* /* listener */) const override {
- return true;
- }
- void DescribeTo(::std::ostream* os) const override { *os << "is anything"; }
- void DescribeNegationTo(::std::ostream* os) const override {
- // This is mostly for completeness' safe, as it's not very useful
- // to write Not(A<bool>()). However we cannot completely rule out
- // such a possibility, and it doesn't hurt to be prepared.
- *os << "never matches";
- }
-};
-
// Implements _, a matcher that matches any value of any
// type. This is a polymorphic matcher, so we need a template type
// conversion operator to make it appearing as a Matcher<T> for any
// type T.
class AnythingMatcher {
public:
+ using is_gtest_matcher = void;
+
template <typename T>
- operator Matcher<T>() const { return A<T>(); }
+ bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {
+ return true;
+ }
+ void DescribeTo(std::ostream* os) const { *os << "is anything"; }
+ void DescribeNegationTo(::std::ostream* os) const {
+ // This is mostly for completeness' sake, as it's not very useful
+ // to write Not(A<bool>()). However we cannot completely rule out
+ // such a possibility, and it doesn't hurt to be prepared.
+ *os << "never matches";
+ }
};
// Implements the polymorphic IsNull() matcher, which matches any raw or smart
@@ -598,13 +855,9 @@ class RefMatcher<T&> {
private:
const Super& object_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
T& object_;
-
- GTEST_DISALLOW_ASSIGN_(RefMatcher);
};
// Polymorphic helper functions for narrow and wide string matchers.
@@ -646,19 +899,20 @@ bool CaseInsensitiveStringEquals(const StringType& s1,
template <typename StringType>
class StrEqualityMatcher {
public:
- StrEqualityMatcher(const StringType& str, bool expect_eq,
- bool case_sensitive)
- : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
+ StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)
+ : string_(std::move(str)),
+ expect_eq_(expect_eq),
+ case_sensitive_(case_sensitive) {}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
- // This should fail to compile if absl::string_view is used with wide
+ // This should fail to compile if StringView is used with wide
// strings.
const StringType& str = std::string(s);
return MatchAndExplain(str, listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -676,11 +930,11 @@ class StrEqualityMatcher {
// Matches anything that can convert to StringType.
//
// This is a template, not just a plain function with const StringType&,
- // because absl::string_view has some interfering non-explicit constructors.
+ // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
- const StringType& s2(s);
+ const StringType s2(s);
const bool eq = case_sensitive_ ? s2 == string_ :
CaseInsensitiveStringEquals(s2, string_);
return expect_eq_ == eq;
@@ -707,8 +961,6 @@ class StrEqualityMatcher {
const StringType string_;
const bool expect_eq_;
const bool case_sensitive_;
-
- GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
};
// Implements the polymorphic HasSubstr(substring) matcher, which
@@ -720,15 +972,15 @@ class HasSubstrMatcher {
explicit HasSubstrMatcher(const StringType& substring)
: substring_(substring) {}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
- // This should fail to compile if absl::string_view is used with wide
+ // This should fail to compile if StringView is used with wide
// strings.
const StringType& str = std::string(s);
return MatchAndExplain(str, listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -743,7 +995,7 @@ class HasSubstrMatcher {
// Matches anything that can convert to StringType.
//
// This is a template, not just a plain function with const StringType&,
- // because absl::string_view has some interfering non-explicit constructors.
+ // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
@@ -763,8 +1015,6 @@ class HasSubstrMatcher {
private:
const StringType substring_;
-
- GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
};
// Implements the polymorphic StartsWith(substring) matcher, which
@@ -776,15 +1026,15 @@ class StartsWithMatcher {
explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
- // This should fail to compile if absl::string_view is used with wide
+ // This should fail to compile if StringView is used with wide
// strings.
const StringType& str = std::string(s);
return MatchAndExplain(str, listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -799,7 +1049,7 @@ class StartsWithMatcher {
// Matches anything that can convert to StringType.
//
// This is a template, not just a plain function with const StringType&,
- // because absl::string_view has some interfering non-explicit constructors.
+ // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
@@ -820,8 +1070,6 @@ class StartsWithMatcher {
private:
const StringType prefix_;
-
- GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
};
// Implements the polymorphic EndsWith(substring) matcher, which
@@ -832,15 +1080,15 @@ class EndsWithMatcher {
public:
explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
- // This should fail to compile if absl::string_view is used with wide
+ // This should fail to compile if StringView is used with wide
// strings.
const StringType& str = std::string(s);
return MatchAndExplain(str, listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -855,7 +1103,7 @@ class EndsWithMatcher {
// Matches anything that can convert to StringType.
//
// This is a template, not just a plain function with const StringType&,
- // because absl::string_view has some interfering non-explicit constructors.
+ // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
@@ -876,8 +1124,6 @@ class EndsWithMatcher {
private:
const StringType suffix_;
-
- GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
};
// Implements a matcher that compares the two fields of a 2-tuple
@@ -971,8 +1217,6 @@ class NotMatcherImpl : public MatcherInterface<const T&> {
private:
const Matcher<T> matcher_;
-
- GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
};
// Implements the Not(m) matcher, which matches a value that doesn't
@@ -991,8 +1235,6 @@ class NotMatcher {
private:
InnerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(NotMatcher);
};
// Implements the AllOf(m1, m2) matcher for a particular argument type
@@ -1054,8 +1296,6 @@ class AllOfMatcherImpl : public MatcherInterface<const T&> {
private:
const std::vector<Matcher<T> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl);
};
// VariadicMatcher is used for the variadic implementation of
@@ -1070,6 +1310,9 @@ class VariadicMatcher {
static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
}
+ VariadicMatcher(const VariadicMatcher&) = default;
+ VariadicMatcher& operator=(const VariadicMatcher&) = delete;
+
// This template type conversion operator allows an
// VariadicMatcher<Matcher1, Matcher2...> object to match any type that
// all of the provided matchers (Matcher1, Matcher2, ...) can match.
@@ -1094,8 +1337,6 @@ class VariadicMatcher {
std::integral_constant<size_t, sizeof...(Args)>) const {}
std::tuple<Args...> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
};
template <typename... Args>
@@ -1160,8 +1401,6 @@ class AnyOfMatcherImpl : public MatcherInterface<const T&> {
private:
const std::vector<Matcher<T> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl);
};
// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
@@ -1189,8 +1428,6 @@ class SomeOfArrayMatcher {
private:
const ::std::vector<T> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(SomeOfArrayMatcher);
};
template <typename T>
@@ -1212,7 +1449,7 @@ class TrulyMatcher {
// interested in the address of the argument.
template <typename T>
bool MatchAndExplain(T& x, // NOLINT
- MatchResultListener* /* listener */) const {
+ MatchResultListener* listener) const {
// Without the if-statement, MSVC sometimes warns about converting
// a value to bool (warning 4800).
//
@@ -1221,6 +1458,7 @@ class TrulyMatcher {
// having no operator!().
if (predicate_(x))
return true;
+ *listener << "didn't satisfy the given predicate";
return false;
}
@@ -1234,8 +1472,6 @@ class TrulyMatcher {
private:
Predicate predicate_;
-
- GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
};
// Used for implementing Matches(matcher), which turns a matcher into
@@ -1272,8 +1508,6 @@ class MatcherAsPredicate {
private:
M matcher_;
-
- GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
};
// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
@@ -1324,8 +1558,6 @@ class PredicateFormatterFromMatcher {
private:
const M matcher_;
-
- GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
};
// A helper function for converting a matcher to a predicate-formatter
@@ -1477,16 +1709,11 @@ class FloatingEqMatcher {
const bool nan_eq_nan_;
// max_abs_error will be used for value comparison when >= 0.
const FloatType max_abs_error_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
// The following 3 type conversion operators allow FloatEq(expected) and
// NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
// Matcher<const float&>, or a Matcher<float&>, but nothing else.
- // (While Google's C++ coding style doesn't allow arguments passed
- // by non-const reference, we may see them in code not conforming to
- // the style. Therefore Google Mock needs to support them.)
operator Matcher<FloatType>() const {
return MakeMatcher(
new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
@@ -1507,8 +1734,6 @@ class FloatingEqMatcher {
const bool nan_eq_nan_;
// max_abs_error will be used for value comparison when >= 0.
const FloatType max_abs_error_;
-
- GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
};
// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
@@ -1612,8 +1837,9 @@ class PointeeMatcher {
template <typename Pointer>
class Impl : public MatcherInterface<Pointer> {
public:
- typedef typename PointeeOf<GTEST_REMOVE_REFERENCE_AND_CONST_(Pointer)>::type
- Pointee;
+ using Pointee =
+ typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
+ Pointer)>::element_type;
explicit Impl(const InnerMatcher& matcher)
: matcher_(MatcherCast<const Pointee&>(matcher)) {}
@@ -1638,13 +1864,67 @@ class PointeeMatcher {
private:
const Matcher<const Pointee&> matcher_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const InnerMatcher matcher_;
+};
+
+// Implements the Pointer(m) matcher
+// Implements the Pointer(m) matcher for matching a pointer that matches matcher
+// m. The pointer can be either raw or smart, and will match `m` against the
+// raw pointer.
+template <typename InnerMatcher>
+class PointerMatcher {
+ public:
+ explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
+
+ // This type conversion operator template allows Pointer(m) to be
+ // used as a matcher for any pointer type whose pointer type is
+ // compatible with the inner matcher, where type PointerType can be
+ // either a raw pointer or a smart pointer.
+ //
+ // The reason we do this instead of relying on
+ // MakePolymorphicMatcher() is that the latter is not flexible
+ // enough for implementing the DescribeTo() method of Pointer().
+ template <typename PointerType>
+ operator Matcher<PointerType>() const { // NOLINT
+ return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));
+ }
+
+ private:
+ // The monomorphic implementation that works for a particular pointer type.
+ template <typename PointerType>
+ class Impl : public MatcherInterface<PointerType> {
+ public:
+ using Pointer =
+ const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(
+ PointerType)>::element_type*;
+
+ explicit Impl(const InnerMatcher& matcher)
+ : matcher_(MatcherCast<Pointer>(matcher)) {}
+
+ void DescribeTo(::std::ostream* os) const override {
+ *os << "is a pointer that ";
+ matcher_.DescribeTo(os);
+ }
- GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
+ void DescribeNegationTo(::std::ostream* os) const override {
+ *os << "is not a pointer that ";
+ matcher_.DescribeTo(os);
+ }
+
+ bool MatchAndExplain(PointerType pointer,
+ MatchResultListener* listener) const override {
+ *listener << "which is a pointer that ";
+ Pointer p = GetRawPointer(pointer);
+ return MatchPrintAndExplain(p, matcher_, listener);
+ }
+
+ private:
+ Matcher<Pointer> matcher_;
+ };
+
+ const InnerMatcher matcher_;
};
#if GTEST_HAS_RTTI
@@ -1681,8 +1961,6 @@ class WhenDynamicCastToMatcherBase {
static void GetCastTypeDescription(::std::ostream* os) {
*os << "when dynamic_cast to " << GetToName() << ", ";
}
-
- GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
};
// Primary template.
@@ -1780,8 +2058,6 @@ class FieldMatcher {
// Contains either "whose given field " if the name of the field is unknown
// or "whose field `name_of_field` " if the name is known.
const std::string whose_field_;
-
- GTEST_DISALLOW_ASSIGN_(FieldMatcher);
};
// Implements the Property() matcher for matching a property
@@ -1850,8 +2126,6 @@ class PropertyMatcher {
// Contains either "whose given property " if the name of the property is
// unknown or "whose property `name_of_property` " if the name is known.
const std::string whose_property_;
-
- GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
};
// Type traits specifying various features of different functors for ResultOf.
@@ -1941,14 +2215,10 @@ class ResultOfMatcher {
// how many times the callable will be invoked.
mutable CallableStorageType callable_;
const Matcher<ResultType> matcher_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
}; // class Impl
const CallableStorageType callable_;
const InnerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
};
// Implements a matcher that checks the size of an STL-style container.
@@ -1993,12 +2263,10 @@ class SizeIsMatcher {
private:
const Matcher<SizeType> size_matcher_;
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const SizeMatcher size_matcher_;
- GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
};
// Implements a matcher that checks the begin()..end() distance of an STL-style
@@ -2050,12 +2318,10 @@ class BeginEndDistanceIsMatcher {
private:
const Matcher<DistanceType> distance_matcher_;
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const DistanceMatcher distance_matcher_;
- GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
};
// Implements an equality matcher for any STL-style container whose elements
@@ -2148,8 +2414,6 @@ class ContainerEqMatcher {
private:
const StlContainer expected_;
-
- GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
};
// A comparator functor that uses the < operator to compare two values.
@@ -2231,8 +2495,6 @@ class WhenSortedByMatcher {
private:
const Comparator comparator_;
const ContainerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
};
// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
@@ -2348,15 +2610,11 @@ class PointwiseMatcher {
private:
const Matcher<InnerMatcherArg> mono_tuple_matcher_;
const RhsStlContainer rhs_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const TupleMatcher tuple_matcher_;
const RhsStlContainer rhs_;
-
- GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
};
// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
@@ -2399,8 +2657,6 @@ class QuantifierMatcherImpl : public MatcherInterface<Container> {
protected:
const Matcher<const Element&> inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
};
// Implements Contains(element_matcher) for the given argument type Container.
@@ -2427,9 +2683,6 @@ class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
MatchResultListener* listener) const override {
return this->MatchAndExplainImpl(false, container, listener);
}
-
- private:
- GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
};
// Implements Each(element_matcher) for the given argument type Container.
@@ -2456,9 +2709,6 @@ class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
MatchResultListener* listener) const override {
return this->MatchAndExplainImpl(true, container, listener);
}
-
- private:
- GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
};
// Implements polymorphic Contains(element_matcher).
@@ -2475,8 +2725,6 @@ class ContainsMatcher {
private:
const M inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
};
// Implements polymorphic Each(element_matcher).
@@ -2493,8 +2741,6 @@ class EachMatcher {
private:
const M inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(EachMatcher);
};
struct Rank1 {};
@@ -2565,8 +2811,6 @@ class KeyMatcherImpl : public MatcherInterface<PairType> {
private:
const Matcher<const KeyType&> inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
};
// Implements polymorphic Key(matcher_for_key).
@@ -2583,8 +2827,49 @@ class KeyMatcher {
private:
const M matcher_for_key_;
+};
+
+// Implements polymorphic Address(matcher_for_address).
+template <typename InnerMatcher>
+class AddressMatcher {
+ public:
+ explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}
+
+ template <typename Type>
+ operator Matcher<Type>() const { // NOLINT
+ return Matcher<Type>(new Impl<const Type&>(matcher_));
+ }
+
+ private:
+ // The monomorphic implementation that works for a particular object type.
+ template <typename Type>
+ class Impl : public MatcherInterface<Type> {
+ public:
+ using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;
+ explicit Impl(const InnerMatcher& matcher)
+ : matcher_(MatcherCast<Address>(matcher)) {}
+
+ void DescribeTo(::std::ostream* os) const override {
+ *os << "has address that ";
+ matcher_.DescribeTo(os);
+ }
+
+ void DescribeNegationTo(::std::ostream* os) const override {
+ *os << "does not have address that ";
+ matcher_.DescribeTo(os);
+ }
+
+ bool MatchAndExplain(Type object,
+ MatchResultListener* listener) const override {
+ *listener << "which has address ";
+ Address address = std::addressof(object);
+ return MatchPrintAndExplain(address, matcher_, listener);
+ }
- GTEST_DISALLOW_ASSIGN_(KeyMatcher);
+ private:
+ const Matcher<Address> matcher_;
+ };
+ const InnerMatcher matcher_;
};
// Implements Pair(first_matcher, second_matcher) for the given argument pair
@@ -2670,8 +2955,6 @@ class PairMatcherImpl : public MatcherInterface<PairType> {
const Matcher<const FirstType&> first_matcher_;
const Matcher<const SecondType&> second_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
};
// Implements polymorphic Pair(first_matcher, second_matcher).
@@ -2690,8 +2973,203 @@ class PairMatcher {
private:
const FirstMatcher first_matcher_;
const SecondMatcher second_matcher_;
+};
+
+template <typename T, size_t... I>
+auto UnpackStructImpl(const T& t, IndexSequence<I...>, int)
+ -> decltype(std::tie(get<I>(t)...)) {
+ static_assert(std::tuple_size<T>::value == sizeof...(I),
+ "Number of arguments doesn't match the number of fields.");
+ return std::tie(get<I>(t)...);
+}
+
+#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) {
+ const auto& [a] = t;
+ return std::tie(a);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) {
+ const auto& [a, b] = t;
+ return std::tie(a, b);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) {
+ const auto& [a, b, c] = t;
+ return std::tie(a, b, c);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) {
+ const auto& [a, b, c, d] = t;
+ return std::tie(a, b, c, d);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) {
+ const auto& [a, b, c, d, e] = t;
+ return std::tie(a, b, c, d, e);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) {
+ const auto& [a, b, c, d, e, f] = t;
+ return std::tie(a, b, c, d, e, f);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) {
+ const auto& [a, b, c, d, e, f, g] = t;
+ return std::tie(a, b, c, d, e, f, g);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) {
+ const auto& [a, b, c, d, e, f, g, h] = t;
+ return std::tie(a, b, c, d, e, f, g, h);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);
+}
+template <typename T>
+auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {
+ const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;
+ return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
+}
+#endif // defined(__cpp_structured_bindings)
- GTEST_DISALLOW_ASSIGN_(PairMatcher);
+template <size_t I, typename T>
+auto UnpackStruct(const T& t)
+ -> decltype((UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0)) {
+ return (UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0);
+}
+
+// Helper function to do comma folding in C++11.
+// The array ensures left-to-right order of evaluation.
+// Usage: VariadicExpand({expr...});
+template <typename T, size_t N>
+void VariadicExpand(const T (&)[N]) {}
+
+template <typename Struct, typename StructSize>
+class FieldsAreMatcherImpl;
+
+template <typename Struct, size_t... I>
+class FieldsAreMatcherImpl<Struct, IndexSequence<I...>>
+ : public MatcherInterface<Struct> {
+ using UnpackedType =
+ decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));
+ using MatchersType = std::tuple<
+ Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;
+
+ public:
+ template <typename Inner>
+ explicit FieldsAreMatcherImpl(const Inner& matchers)
+ : matchers_(testing::SafeMatcherCast<
+ const typename std::tuple_element<I, UnpackedType>::type&>(
+ std::get<I>(matchers))...) {}
+
+ void DescribeTo(::std::ostream* os) const override {
+ const char* separator = "";
+ VariadicExpand(
+ {(*os << separator << "has field #" << I << " that ",
+ std::get<I>(matchers_).DescribeTo(os), separator = ", and ")...});
+ }
+
+ void DescribeNegationTo(::std::ostream* os) const override {
+ const char* separator = "";
+ VariadicExpand({(*os << separator << "has field #" << I << " that ",
+ std::get<I>(matchers_).DescribeNegationTo(os),
+ separator = ", or ")...});
+ }
+
+ bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {
+ return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);
+ }
+
+ private:
+ bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {
+ if (!listener->IsInterested()) {
+ // If the listener is not interested, we don't need to construct the
+ // explanation.
+ bool good = true;
+ VariadicExpand({good = good && std::get<I>(matchers_).Matches(
+ std::get<I>(tuple))...});
+ return good;
+ }
+
+ size_t failed_pos = ~size_t{};
+
+ std::vector<StringMatchResultListener> inner_listener(sizeof...(I));
+
+ VariadicExpand(
+ {failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(
+ std::get<I>(tuple), &inner_listener[I])
+ ? failed_pos = I
+ : 0 ...});
+ if (failed_pos != ~size_t{}) {
+ *listener << "whose field #" << failed_pos << " does not match";
+ PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());
+ return false;
+ }
+
+ *listener << "whose all elements match";
+ const char* separator = ", where";
+ for (size_t index = 0; index < sizeof...(I); ++index) {
+ const std::string str = inner_listener[index].str();
+ if (!str.empty()) {
+ *listener << separator << " field #" << index << " is a value " << str;
+ separator = ", and";
+ }
+ }
+
+ return true;
+ }
+
+ MatchersType matchers_;
+};
+
+template <typename... Inner>
+class FieldsAreMatcher {
+ public:
+ explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}
+
+ template <typename Struct>
+ operator Matcher<Struct>() const { // NOLINT
+ return Matcher<Struct>(
+ new FieldsAreMatcherImpl<const Struct&, IndexSequenceFor<Inner...>>(
+ matchers_));
+ }
+
+ private:
+ std::tuple<Inner...> matchers_;
};
// Implements ElementsAre() and ElementsAreArray().
@@ -2837,8 +3315,6 @@ class ElementsAreMatcherImpl : public MatcherInterface<Container> {
size_t count() const { return matchers_.size(); }
::std::vector<Matcher<const Element&> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
};
// Connectivity matrix of (elements X matchers), in element-major order.
@@ -2941,8 +3417,6 @@ class GTEST_API_ UnorderedElementsAreMatcherImplBase {
private:
UnorderedMatcherRequire::Flags match_flags_;
MatcherDescriberVec matcher_describers_;
-
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
};
// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
@@ -2965,7 +3439,9 @@ class UnorderedElementsAreMatcherImpl
: UnorderedElementsAreMatcherImplBase(matcher_flags) {
for (; first != last; ++first) {
matchers_.push_back(MatcherCast<const Element&>(*first));
- matcher_describers().push_back(matchers_.back().GetDescriber());
+ }
+ for (const auto& m : matchers_) {
+ matcher_describers().push_back(m.GetDescriber());
}
}
@@ -3038,8 +3514,6 @@ class UnorderedElementsAreMatcherImpl
}
::std::vector<Matcher<const Element&> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
};
// Functor for use in TransformTuple.
@@ -3077,7 +3551,6 @@ class UnorderedElementsAreMatcher {
private:
const MatcherTuple matchers_;
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
};
// Implements ElementsAre.
@@ -3107,7 +3580,6 @@ class ElementsAreMatcher {
private:
const MatcherTuple matchers_;
- GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
};
// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
@@ -3129,8 +3601,6 @@ class UnorderedElementsAreArrayMatcher {
private:
UnorderedMatcherRequire::Flags match_flags_;
::std::vector<T> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
};
// Implements ElementsAreArray().
@@ -3152,8 +3622,6 @@ class ElementsAreArrayMatcher {
private:
const ::std::vector<T> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
};
// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
@@ -3215,8 +3683,6 @@ class BoundSecondMatcher {
private:
const Matcher<const ArgTuple&> mono_tuple2_matcher_;
const Second second_value_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const Tuple2Matcher tuple2_matcher_;
@@ -3289,12 +3755,10 @@ class OptionalMatcher {
private:
const Matcher<ValueType> value_matcher_;
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const ValueMatcher value_matcher_;
- GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
};
namespace variant_matcher {
@@ -3602,12 +4066,14 @@ const internal::AnythingMatcher _ = {};
// Creates a matcher that matches any value of the given type T.
template <typename T>
inline Matcher<T> A() {
- return Matcher<T>(new internal::AnyMatcherImpl<T>());
+ return _;
}
// Creates a matcher that matches any value of the given type T.
template <typename T>
-inline Matcher<T> An() { return A<T>(); }
+inline Matcher<T> An() {
+ return _;
+}
template <typename T, typename M>
Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl(
@@ -3822,52 +4288,60 @@ internal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(
// String matchers.
// Matches a string equal to str.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
- const std::string& str) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq(
+ const internal::StringLike<T>& str) {
return MakePolymorphicMatcher(
- internal::StrEqualityMatcher<std::string>(str, true, true));
+ internal::StrEqualityMatcher<std::string>(std::string(str), true, true));
}
// Matches a string not equal to str.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
- const std::string& str) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe(
+ const internal::StringLike<T>& str) {
return MakePolymorphicMatcher(
- internal::StrEqualityMatcher<std::string>(str, false, true));
+ internal::StrEqualityMatcher<std::string>(std::string(str), false, true));
}
// Matches a string equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
- const std::string& str) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq(
+ const internal::StringLike<T>& str) {
return MakePolymorphicMatcher(
- internal::StrEqualityMatcher<std::string>(str, true, false));
+ internal::StrEqualityMatcher<std::string>(std::string(str), true, false));
}
// Matches a string not equal to str, ignoring case.
-inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
- const std::string& str) {
- return MakePolymorphicMatcher(
- internal::StrEqualityMatcher<std::string>(str, false, false));
+template <typename T = std::string>
+PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe(
+ const internal::StringLike<T>& str) {
+ return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(
+ std::string(str), false, false));
}
// Creates a matcher that matches any string, std::string, or C string
// that contains the given substring.
-inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
- const std::string& substring) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr(
+ const internal::StringLike<T>& substring) {
return MakePolymorphicMatcher(
- internal::HasSubstrMatcher<std::string>(substring));
+ internal::HasSubstrMatcher<std::string>(std::string(substring)));
}
// Matches a string that starts with 'prefix' (case-sensitive).
-inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
- const std::string& prefix) {
+template <typename T = std::string>
+PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith(
+ const internal::StringLike<T>& prefix) {
return MakePolymorphicMatcher(
- internal::StartsWithMatcher<std::string>(prefix));
+ internal::StartsWithMatcher<std::string>(std::string(prefix)));
}
// Matches a string that ends with 'suffix' (case-sensitive).
-inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
- const std::string& suffix) {
- return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix));
+template <typename T = std::string>
+PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith(
+ const internal::StringLike<T>& suffix) {
+ return MakePolymorphicMatcher(
+ internal::EndsWithMatcher<std::string>(std::string(suffix)));
}
#if GTEST_HAS_STD_WSTRING
@@ -4337,6 +4811,35 @@ Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
first_matcher, second_matcher);
}
+namespace no_adl {
+// FieldsAre(matchers...) matches piecewise the fields of compatible structs.
+// These include those that support `get<I>(obj)`, and when structured bindings
+// are enabled any class that supports them.
+// In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.
+template <typename... M>
+internal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(
+ M&&... matchers) {
+ return internal::FieldsAreMatcher<typename std::decay<M>::type...>(
+ std::forward<M>(matchers)...);
+}
+
+// Creates a matcher that matches a pointer (raw or smart) that matches
+// inner_matcher.
+template <typename InnerMatcher>
+inline internal::PointerMatcher<InnerMatcher> Pointer(
+ const InnerMatcher& inner_matcher) {
+ return internal::PointerMatcher<InnerMatcher>(inner_matcher);
+}
+
+// Creates a matcher that matches an object that has an address that matches
+// inner_matcher.
+template <typename InnerMatcher>
+inline internal::AddressMatcher<InnerMatcher> Address(
+ const InnerMatcher& inner_matcher) {
+ return internal::AddressMatcher<InnerMatcher>(inner_matcher);
+}
+} // namespace no_adl
+
// Returns a predicate that is satisfied by anything that matches the
// given matcher.
template <typename M>
@@ -4521,7 +5024,7 @@ inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
// and is printable using 'PrintToString'. It is compatible with
// std::optional/std::experimental::optional.
// Note that to compare an optional type variable against nullopt you should
-// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
+// use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the
// optional value contains an optional itself.
template <typename ValueMatcher>
inline internal::OptionalMatcher<ValueMatcher> Optional(
@@ -4548,6 +5051,175 @@ PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
internal::variant_matcher::VariantMatcher<T>(matcher));
}
+#if GTEST_HAS_EXCEPTIONS
+
+// Anything inside the `internal` namespace is internal to the implementation
+// and must not be used in user code!
+namespace internal {
+
+class WithWhatMatcherImpl {
+ public:
+ WithWhatMatcherImpl(Matcher<std::string> matcher)
+ : matcher_(std::move(matcher)) {}
+
+ void DescribeTo(std::ostream* os) const {
+ *os << "contains .what() that ";
+ matcher_.DescribeTo(os);
+ }
+
+ void DescribeNegationTo(std::ostream* os) const {
+ *os << "contains .what() that does not ";
+ matcher_.DescribeTo(os);
+ }
+
+ template <typename Err>
+ bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {
+ *listener << "which contains .what() that ";
+ return matcher_.MatchAndExplain(err.what(), listener);
+ }
+
+ private:
+ const Matcher<std::string> matcher_;
+};
+
+inline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(
+ Matcher<std::string> m) {
+ return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));
+}
+
+template <typename Err>
+class ExceptionMatcherImpl {
+ class NeverThrown {
+ public:
+ const char* what() const noexcept {
+ return "this exception should never be thrown";
+ }
+ };
+
+ // If the matchee raises an exception of a wrong type, we'd like to
+ // catch it and print its message and type. To do that, we add an additional
+ // catch clause:
+ //
+ // try { ... }
+ // catch (const Err&) { /* an expected exception */ }
+ // catch (const std::exception&) { /* exception of a wrong type */ }
+ //
+ // However, if the `Err` itself is `std::exception`, we'd end up with two
+ // identical `catch` clauses:
+ //
+ // try { ... }
+ // catch (const std::exception&) { /* an expected exception */ }
+ // catch (const std::exception&) { /* exception of a wrong type */ }
+ //
+ // This can cause a warning or an error in some compilers. To resolve
+ // the issue, we use a fake error type whenever `Err` is `std::exception`:
+ //
+ // try { ... }
+ // catch (const std::exception&) { /* an expected exception */ }
+ // catch (const NeverThrown&) { /* exception of a wrong type */ }
+ using DefaultExceptionType = typename std::conditional<
+ std::is_same<typename std::remove_cv<
+ typename std::remove_reference<Err>::type>::type,
+ std::exception>::value,
+ const NeverThrown&, const std::exception&>::type;
+
+ public:
+ ExceptionMatcherImpl(Matcher<const Err&> matcher)
+ : matcher_(std::move(matcher)) {}
+
+ void DescribeTo(std::ostream* os) const {
+ *os << "throws an exception which is a " << GetTypeName<Err>();
+ *os << " which ";
+ matcher_.DescribeTo(os);
+ }
+
+ void DescribeNegationTo(std::ostream* os) const {
+ *os << "throws an exception which is not a " << GetTypeName<Err>();
+ *os << " which ";
+ matcher_.DescribeNegationTo(os);
+ }
+
+ template <typename T>
+ bool MatchAndExplain(T&& x, MatchResultListener* listener) const {
+ try {
+ (void)(std::forward<T>(x)());
+ } catch (const Err& err) {
+ *listener << "throws an exception which is a " << GetTypeName<Err>();
+ *listener << " ";
+ return matcher_.MatchAndExplain(err, listener);
+ } catch (DefaultExceptionType err) {
+#if GTEST_HAS_RTTI
+ *listener << "throws an exception of type " << GetTypeName(typeid(err));
+ *listener << " ";
+#else
+ *listener << "throws an std::exception-derived type ";
+#endif
+ *listener << "with description \"" << err.what() << "\"";
+ return false;
+ } catch (...) {
+ *listener << "throws an exception of an unknown type";
+ return false;
+ }
+
+ *listener << "does not throw any exception";
+ return false;
+ }
+
+ private:
+ const Matcher<const Err&> matcher_;
+};
+
+} // namespace internal
+
+// Throws()
+// Throws(exceptionMatcher)
+// ThrowsMessage(messageMatcher)
+//
+// This matcher accepts a callable and verifies that when invoked, it throws
+// an exception with the given type and properties.
+//
+// Examples:
+//
+// EXPECT_THAT(
+// []() { throw std::runtime_error("message"); },
+// Throws<std::runtime_error>());
+//
+// EXPECT_THAT(
+// []() { throw std::runtime_error("message"); },
+// ThrowsMessage<std::runtime_error>(HasSubstr("message")));
+//
+// EXPECT_THAT(
+// []() { throw std::runtime_error("message"); },
+// Throws<std::runtime_error>(
+// Property(&std::runtime_error::what, HasSubstr("message"))));
+
+template <typename Err>
+PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {
+ return MakePolymorphicMatcher(
+ internal::ExceptionMatcherImpl<Err>(A<const Err&>()));
+}
+
+template <typename Err, typename ExceptionMatcher>
+PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(
+ const ExceptionMatcher& exception_matcher) {
+ // Using matcher cast allows users to pass a matcher of a more broad type.
+ // For example user may want to pass Matcher<std::exception>
+ // to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.
+ return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(
+ SafeMatcherCast<const Err&>(exception_matcher)));
+}
+
+template <typename Err, typename MessageMatcher>
+PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
+ MessageMatcher&& message_matcher) {
+ static_assert(std::is_base_of<std::exception, Err>::value,
+ "expected an std::exception-derived type");
+ return Throws<Err>(internal::WithWhat(
+ MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));
+}
+
+#endif // GTEST_HAS_EXCEPTIONS
+
// These macros allow using matchers to check values in Google Test
// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
// succeed if and only if the value matches the matcher. If the assertion
@@ -4557,6 +5229,159 @@ PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
+// MATCHER* macroses itself are listed below.
+#define MATCHER(name, description) \
+ class name##Matcher \
+ : public ::testing::internal::MatcherBaseImpl<name##Matcher> { \
+ public: \
+ template <typename arg_type> \
+ class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
+ public: \
+ gmock_Impl() {} \
+ bool MatchAndExplain( \
+ const arg_type& arg, \
+ ::testing::MatchResultListener* result_listener) const override; \
+ void DescribeTo(::std::ostream* gmock_os) const override { \
+ *gmock_os << FormatDescription(false); \
+ } \
+ void DescribeNegationTo(::std::ostream* gmock_os) const override { \
+ *gmock_os << FormatDescription(true); \
+ } \
+ \
+ 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, \
+ {}); \
+ } \
+ }; \
+ }; \
+ GTEST_ATTRIBUTE_UNUSED_ inline name##Matcher name() { return {}; } \
+ template <typename arg_type> \
+ bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
+ const arg_type& arg, \
+ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \
+ const
+
+#define MATCHER_P(name, p0, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (p0))
+#define MATCHER_P2(name, p0, p1, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (p0, p1))
+#define MATCHER_P3(name, p0, p1, p2, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (p0, p1, p2))
+#define MATCHER_P4(name, p0, p1, p2, p3, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, (p0, p1, p2, p3))
+#define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \
+ (p0, p1, p2, p3, p4))
+#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \
+ (p0, p1, p2, p3, p4, p5))
+#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \
+ (p0, p1, p2, p3, p4, p5, p6))
+#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \
+ (p0, p1, p2, p3, p4, p5, p6, p7))
+#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \
+ (p0, p1, p2, p3, p4, p5, p6, p7, p8))
+#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \
+ GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \
+ (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))
+
+#define GMOCK_INTERNAL_MATCHER(name, full_name, description, args) \
+ template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
+ class full_name : public ::testing::internal::MatcherBaseImpl< \
+ full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \
+ public: \
+ using full_name::MatcherBaseImpl::MatcherBaseImpl; \
+ template <typename arg_type> \
+ class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
+ public: \
+ explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \
+ : GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \
+ bool MatchAndExplain( \
+ const arg_type& arg, \
+ ::testing::MatchResultListener* result_listener) const override; \
+ void DescribeTo(::std::ostream* gmock_os) const override { \
+ *gmock_os << FormatDescription(false); \
+ } \
+ void DescribeNegationTo(::std::ostream* gmock_os) const override { \
+ *gmock_os << FormatDescription(true); \
+ } \
+ GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
+ \
+ 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<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
+ GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \
+ } \
+ }; \
+ }; \
+ template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
+ inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \
+ GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \
+ return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
+ GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \
+ } \
+ template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
+ template <typename arg_type> \
+ bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl< \
+ arg_type>::MatchAndExplain(const arg_type& arg, \
+ ::testing::MatchResultListener* \
+ result_listener GTEST_ATTRIBUTE_UNUSED_) \
+ const
+
+#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \
+ GMOCK_PP_TAIL( \
+ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))
+#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \
+ , typename arg##_type
+
+#define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))
+#define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \
+ , arg##_type
+
+#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \
+ GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \
+ GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))
+#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \
+ , arg##_type gmock_p##i
+
+#define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))
+#define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \
+ , arg(::std::forward<arg##_type>(gmock_p##i))
+
+#define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
+ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)
+#define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \
+ const arg##_type arg;
+
+#define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))
+#define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg
+
+#define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \
+ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))
+#define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \
+ , gmock_p##i
+
+// To prevent ADL on certain functions we put them on a separate namespace.
+using namespace no_adl; // NOLINT
+
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
@@ -4566,4 +5391,4 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
// declarations from this file.
#include "gmock/internal/custom/gmock-matchers.h"
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
diff --git a/googlemock/include/gmock/gmock-more-actions.h b/googlemock/include/gmock/gmock-more-actions.h
index d42484ae..fd293358 100644
--- a/googlemock/include/gmock/gmock-more-actions.h
+++ b/googlemock/include/gmock/gmock-more-actions.h
@@ -30,38 +30,464 @@
// Google Mock - a framework for writing C++ mock classes.
//
-// This file implements some actions that depend on gmock-generated-actions.h.
+// This file implements some commonly used variadic actions.
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
-#include <algorithm>
-#include <type_traits>
+#include <memory>
+#include <utility>
-#include "gmock/gmock-generated-actions.h"
+#include "gmock/gmock-actions.h"
+#include "gmock/internal/gmock-port.h"
-namespace testing {
-namespace internal {
+// Include any custom callback actions added by the local installation.
+#include "gmock/internal/custom/gmock-generated-actions.h"
-// An internal replacement for std::copy which mimics its behavior. This is
-// necessary because Visual Studio deprecates ::std::copy, issuing warning 4996.
-// However Visual Studio 2010 and later do not honor #pragmas which disable that
-// warning.
-template<typename InputIterator, typename OutputIterator>
-inline OutputIterator CopyElements(InputIterator first,
- InputIterator last,
- OutputIterator output) {
- for (; first != last; ++first, ++output) {
- *output = *first;
- }
- return output;
-}
+// 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.
-} // namespace internal
+// Declares the template parameters.
+#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0
+#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
+ name1) kind0 name0, kind1 name1
+#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2) kind0 name0, kind1 name1, kind2 name2
+#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \
+ kind3 name3
+#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \
+ kind2 name2, kind3 name3, kind4 name4
+#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \
+ kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5
+#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
+ name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \
+ kind5 name5, kind6 name6
+#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
+ kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \
+ kind4 name4, kind5 name5, kind6 name6, kind7 name7
+#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
+ kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \
+ kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \
+ kind8 name8
+#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
+ name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
+ name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \
+ kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \
+ kind6 name6, kind7 name7, kind8 name8, kind9 name9
+
+// Lists the template parameters.
+#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0
+#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \
+ name1) name0, name1
+#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2) name0, name1, name2
+#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3) name0, name1, name2, name3
+#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \
+ name4
+#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \
+ name2, name3, name4, name5
+#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
+ name6) name0, name1, name2, name3, name4, name5, name6
+#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
+ kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7
+#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \
+ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \
+ kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \
+ name6, name7, name8
+#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \
+ name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \
+ name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \
+ name3, name4, name5, name6, name7, name8, name9
+
+// Declares the types of value parameters.
+#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()
+#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \
+ typename p0##_type, typename p1##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \
+ typename p0##_type, typename p1##_type, typename p2##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
+ typename p0##_type, typename p1##_type, typename p2##_type, \
+ typename p3##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
+ typename p0##_type, typename p1##_type, typename p2##_type, \
+ typename p3##_type, typename p4##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
+ typename p0##_type, typename p1##_type, typename p2##_type, \
+ typename p3##_type, typename p4##_type, typename p5##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6) , typename p0##_type, typename p1##_type, typename p2##_type, \
+ typename p3##_type, typename p4##_type, typename p5##_type, \
+ typename p6##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \
+ typename p3##_type, typename p4##_type, typename p5##_type, \
+ typename p6##_type, typename p7##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \
+ typename p3##_type, typename p4##_type, typename p5##_type, \
+ typename p6##_type, typename p7##_type, typename p8##_type
+#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \
+ typename p2##_type, typename p3##_type, typename p4##_type, \
+ typename p5##_type, typename p6##_type, typename p7##_type, \
+ typename p8##_type, typename p9##_type
+
+// Initializes the value parameters.
+#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\
+ ()
+#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\
+ (p0##_type gmock_p0) : p0(::std::move(gmock_p0))
+#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\
+ (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \
+ p1(::std::move(gmock_p1))
+#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\
+ (p0##_type gmock_p0, p1##_type gmock_p1, \
+ p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \
+ p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2))
+#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\
+ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
+ p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \
+ p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
+ p3(::std::move(gmock_p3))
+#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\
+ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
+ p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \
+ p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
+ p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4))
+#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\
+ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
+ p3##_type gmock_p3, p4##_type gmock_p4, \
+ p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \
+ p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
+ p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
+ p5(::std::move(gmock_p5))
+#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\
+ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
+ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
+ p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \
+ p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
+ p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
+ p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6))
+#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\
+ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
+ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
+ p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \
+ p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
+ p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
+ p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
+ p7(::std::move(gmock_p7))
+#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8)\
+ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
+ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
+ p6##_type gmock_p6, p7##_type gmock_p7, \
+ p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \
+ p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
+ p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
+ p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
+ p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8))
+#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8, p9)\
+ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \
+ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \
+ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \
+ p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \
+ p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \
+ p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \
+ p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \
+ p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \
+ p9(::std::move(gmock_p9))
-// Various overloads for Invoke().
+// Defines the copy constructor
+#define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \
+ {} // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134
+#define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default;
+#define GMOCK_INTERNAL_DEFN_COPY_AND_10_VALUE_PARAMS(...) = default;
+
+// Declares the fields for storing the value parameters.
+#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()
+#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;
+#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \
+ p1##_type p1;
+#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \
+ p1##_type p1; p2##_type p2;
+#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \
+ p1##_type p1; p2##_type p2; p3##_type p3;
+#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
+ p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4;
+#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
+ p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
+ p5##_type p5;
+#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
+ p5##_type p5; p6##_type p6;
+#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \
+ p5##_type p5; p6##_type p6; p7##_type p7;
+#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
+ p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8;
+#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \
+ p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \
+ p9##_type p9;
+
+// Lists the value parameters.
+#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()
+#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0
+#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1
+#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2
+#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3
+#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \
+ p2, p3, p4
+#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \
+ p1, p2, p3, p4, p5
+#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6) p0, p1, p2, p3, p4, p5, p6
+#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7) p0, p1, p2, p3, p4, p5, p6, p7
+#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8
+#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9
+
+// Lists the value parameter types.
+#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()
+#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \
+ p1##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \
+ p1##_type, p2##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \
+ p0##_type, p1##_type, p2##_type, p3##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \
+ p0##_type, p1##_type, p2##_type, p3##_type, p4##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \
+ p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \
+ p6##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
+ p5##_type, p6##_type, p7##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
+ p5##_type, p6##_type, p7##_type, p8##_type
+#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \
+ p5##_type, p6##_type, p7##_type, p8##_type, p9##_type
+
+// Declares the value parameters.
+#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()
+#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0
+#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \
+ p1##_type p1
+#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \
+ p1##_type p1, p2##_type p2
+#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \
+ p1##_type p1, p2##_type p2, p3##_type p3
+#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \
+ p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4
+#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \
+ p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
+ p5##_type p5
+#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \
+ p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
+ p5##_type p5, p6##_type p6
+#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \
+ p5##_type p5, p6##_type p6, p7##_type p7
+#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
+ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8
+#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \
+ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \
+ p9##_type p9
+
+// The suffix of the class template implementing the action template.
+#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()
+#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P
+#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2
+#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3
+#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4
+#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5
+#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6
+#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7
+#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7) P8
+#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8) P9
+#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \
+ p7, p8, p9) P10
+
+// The name of the class template implementing the action template.
+#define GMOCK_ACTION_CLASS_(name, value_params)\
+ GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)
+
+#define ACTION_TEMPLATE(name, template_params, value_params) \
+ template <GMOCK_INTERNAL_DECL_##template_params \
+ GMOCK_INTERNAL_DECL_TYPE_##value_params> \
+ class GMOCK_ACTION_CLASS_(name, value_params) { \
+ public: \
+ explicit GMOCK_ACTION_CLASS_(name, value_params)( \
+ GMOCK_INTERNAL_DECL_##value_params) \
+ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
+ = default; , \
+ : impl_(std::make_shared<gmock_Impl>( \
+ GMOCK_INTERNAL_LIST_##value_params)) { }) \
+ GMOCK_ACTION_CLASS_(name, value_params)( \
+ const GMOCK_ACTION_CLASS_(name, value_params)&) noexcept \
+ GMOCK_INTERNAL_DEFN_COPY_##value_params \
+ GMOCK_ACTION_CLASS_(name, value_params)( \
+ GMOCK_ACTION_CLASS_(name, value_params)&&) noexcept \
+ GMOCK_INTERNAL_DEFN_COPY_##value_params \
+ template <typename F> \
+ operator ::testing::Action<F>() const { \
+ return GMOCK_PP_IF( \
+ GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
+ (::testing::internal::MakeAction<F, gmock_Impl>()), \
+ (::testing::internal::MakeAction<F>(impl_))); \
+ } \
+ private: \
+ class gmock_Impl { \
+ public: \
+ explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {} \
+ template <typename function_type, typename return_type, \
+ typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
+ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
+ GMOCK_INTERNAL_DEFN_##value_params \
+ }; \
+ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
+ , std::shared_ptr<const gmock_Impl> impl_;) \
+ }; \
+ template <GMOCK_INTERNAL_DECL_##template_params \
+ GMOCK_INTERNAL_DECL_TYPE_##value_params> \
+ GMOCK_ACTION_CLASS_(name, value_params)< \
+ GMOCK_INTERNAL_LIST_##template_params \
+ GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
+ GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
+ template <GMOCK_INTERNAL_DECL_##template_params \
+ GMOCK_INTERNAL_DECL_TYPE_##value_params> \
+ inline GMOCK_ACTION_CLASS_(name, value_params)< \
+ GMOCK_INTERNAL_LIST_##template_params \
+ GMOCK_INTERNAL_LIST_TYPE_##value_params> name( \
+ GMOCK_INTERNAL_DECL_##value_params) { \
+ return GMOCK_ACTION_CLASS_(name, value_params)< \
+ GMOCK_INTERNAL_LIST_##template_params \
+ GMOCK_INTERNAL_LIST_TYPE_##value_params>( \
+ GMOCK_INTERNAL_LIST_##value_params); \
+ } \
+ template <GMOCK_INTERNAL_DECL_##template_params \
+ GMOCK_INTERNAL_DECL_TYPE_##value_params> \
+ template <typename function_type, typename return_type, typename args_type, \
+ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
+ return_type GMOCK_ACTION_CLASS_(name, value_params)< \
+ GMOCK_INTERNAL_LIST_##template_params \
+ GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::gmock_PerformImpl( \
+ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
+
+namespace testing {
// The ACTION*() macros trigger warning C4100 (unreferenced formal
// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
@@ -73,90 +499,75 @@ inline OutputIterator CopyElements(InputIterator first,
# pragma warning(disable:4100)
#endif
-// Action ReturnArg<k>() returns the k-th argument of the mock function.
-ACTION_TEMPLATE(ReturnArg,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_0_VALUE_PARAMS()) {
- return ::std::get<k>(args);
-}
+namespace internal {
-// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
-// mock function to *pointer.
-ACTION_TEMPLATE(SaveArg,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_1_VALUE_PARAMS(pointer)) {
- *pointer = ::std::get<k>(args);
+// internal::InvokeArgument - a helper for InvokeArgument action.
+// The basic overloads are provided here for generic functors.
+// Overloads for other custom-callables are provided in the
+// internal/custom/gmock-generated-actions.h header.
+template <typename F, typename... Args>
+auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {
+ return f(args...);
}
-// Action SaveArgPointee<k>(pointer) saves the value pointed to
-// by the k-th (0-based) argument of the mock function to *pointer.
-ACTION_TEMPLATE(SaveArgPointee,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_1_VALUE_PARAMS(pointer)) {
- *pointer = *::std::get<k>(args);
-}
+template <std::size_t index, typename... Params>
+struct InvokeArgumentAction {
+ template <typename... Args>
+ auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument(
+ std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
+ std::declval<const Params&>()...)) {
+ internal::FlatTuple<Args&&...> args_tuple(FlatTupleConstructTag{},
+ std::forward<Args>(args)...);
+ return params.Apply([&](const Params&... unpacked_params) {
+ auto&& callable = args_tuple.template Get<index>();
+ return internal::InvokeArgument(
+ std::forward<decltype(callable)>(callable), unpacked_params...);
+ });
+ }
-// Action SetArgReferee<k>(value) assigns 'value' to the variable
-// referenced by the k-th (0-based) argument of the mock function.
-ACTION_TEMPLATE(SetArgReferee,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_1_VALUE_PARAMS(value)) {
- typedef typename ::std::tuple_element<k, args_type>::type argk_type;
- // Ensures that argument #k is a reference. If you get a compiler
- // error on the next line, you are using SetArgReferee<k>(value) in
- // a mock function whose k-th (0-based) argument is not a reference.
- GTEST_COMPILE_ASSERT_(std::is_reference<argk_type>::value,
- SetArgReferee_must_be_used_with_a_reference_argument);
- ::std::get<k>(args) = value;
-}
+ internal::FlatTuple<Params...> params;
+};
-// Action SetArrayArgument<k>(first, last) copies the elements in
-// source range [first, last) to the array pointed to by the k-th
-// (0-based) argument, which can be either a pointer or an
-// iterator. The action does not take ownership of the elements in the
-// source range.
-ACTION_TEMPLATE(SetArrayArgument,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_2_VALUE_PARAMS(first, last)) {
- // Visual Studio deprecates ::std::copy, so we use our own copy in that case.
-#ifdef _MSC_VER
- internal::CopyElements(first, last, ::std::get<k>(args));
-#else
- ::std::copy(first, last, ::std::get<k>(args));
-#endif
-}
+} // namespace internal
-// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
-// function.
-ACTION_TEMPLATE(DeleteArg,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_0_VALUE_PARAMS()) {
- delete ::std::get<k>(args);
+// 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 std::ref(). For
+// example,
+//
+// InvokeArgument<1>(5, string("Hello"), std::ref(foo))
+//
+// passes 5 and string("Hello") by value, and passes foo by
+// reference.
+//
+// 2. If the callable takes an argument by reference but std::ref() is
+// not used, it will receive the reference to a copy of the value,
+// instead of the original value. For example, when the 0-th
+// argument of the mock function takes a const string&, the action
+//
+// InvokeArgument<0>(string("Hello"))
+//
+// makes a copy of the temporary string("Hello") object and passes a
+// reference of the copy, instead of the original temporary object,
+// to the callable. This makes it easy for a user to define an
+// InvokeArgument action from temporary values and have it performed
+// later.
+template <std::size_t index, typename... Params>
+internal::InvokeArgumentAction<index, typename std::decay<Params>::type...>
+InvokeArgument(Params&&... params) {
+ return {internal::FlatTuple<typename std::decay<Params>::type...>(
+ internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
}
-// This action returns the value pointed to by 'pointer'.
-ACTION_P(ReturnPointee, pointer) { return *pointer; }
-
-// Action Throw(exception) can be used in a mock function of any type
-// to throw the given exception. Any copyable value can be thrown.
-#if GTEST_HAS_EXCEPTIONS
-
-// Suppresses the 'unreachable code' warning that VC generates in opt modes.
-# ifdef _MSC_VER
-# pragma warning(push) // Saves the current warning state.
-# pragma warning(disable:4702) // Temporarily disables warning 4702.
-# endif
-ACTION_P(Throw, exception) { throw exception; }
-# ifdef _MSC_VER
-# pragma warning(pop) // Restores the warning state.
-# endif
-
-#endif // GTEST_HAS_EXCEPTIONS
-
#ifdef _MSC_VER
# pragma warning(pop)
#endif
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
diff --git a/googlemock/include/gmock/gmock-more-matchers.h b/googlemock/include/gmock/gmock-more-matchers.h
index 1c9a399a..dfc77e35 100644
--- a/googlemock/include/gmock/gmock-more-matchers.h
+++ b/googlemock/include/gmock/gmock-more-matchers.h
@@ -30,17 +30,17 @@
// Google Mock - a framework for writing C++ mock classes.
//
-// This file implements some matchers that depend on gmock-generated-matchers.h.
+// This file implements some matchers that depend on gmock-matchers.h.
//
// Note that tests are implemented in gmock-matchers_test.cc rather than
// gmock-more-matchers-test.cc.
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
-#include "gmock/gmock-generated-matchers.h"
+#include "gmock/gmock-matchers.h"
namespace testing {
@@ -89,4 +89,4 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
diff --git a/googlemock/include/gmock/gmock-nice-strict.h b/googlemock/include/gmock/gmock-nice-strict.h
index 5495a980..b03b770c 100644
--- a/googlemock/include/gmock/gmock-nice-strict.h
+++ b/googlemock/include/gmock/gmock-nice-strict.h
@@ -60,20 +60,91 @@
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
+
+#include <type_traits>
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-port.h"
namespace testing {
+template <class MockClass>
+class NiceMock;
+template <class MockClass>
+class NaggyMock;
+template <class MockClass>
+class StrictMock;
+
+namespace internal {
+template <typename T>
+std::true_type StrictnessModifierProbe(const NiceMock<T>&);
+template <typename T>
+std::true_type StrictnessModifierProbe(const NaggyMock<T>&);
+template <typename T>
+std::true_type StrictnessModifierProbe(const StrictMock<T>&);
+std::false_type StrictnessModifierProbe(...);
+
+template <typename T>
+constexpr bool HasStrictnessModifier() {
+ return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value;
+}
+
+// Base classes that register and deregister with testing::Mock to alter the
+// default behavior around uninteresting calls. Inheriting from one of these
+// classes first and then MockClass ensures the MockClass constructor is run
+// after registration, and that the MockClass destructor runs before
+// deregistration. This guarantees that MockClass's constructor and destructor
+// run with the same level of strictness as its instance methods.
+
+#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \
+ (defined(_MSC_VER) || defined(__clang__))
+// We need to mark these classes with this declspec to ensure that
+// the empty base class optimization is performed.
+#define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases)
+#else
+#define GTEST_INTERNAL_EMPTY_BASE_CLASS
+#endif
+
+template <typename Base>
+class NiceMockImpl {
+ public:
+ NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); }
+
+ ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
+};
+
+template <typename Base>
+class NaggyMockImpl {
+ public:
+ NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); }
+
+ ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
+};
+
+template <typename Base>
+class StrictMockImpl {
+ public:
+ StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); }
+
+ ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
+};
+
+} // namespace internal
template <class MockClass>
-class NiceMock : public MockClass {
+class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
+ : private internal::NiceMockImpl<MockClass>,
+ public MockClass {
public:
+ static_assert(!internal::HasStrictnessModifier<MockClass>(),
+ "Can't apply NiceMock to a class hierarchy that already has a "
+ "strictness modifier. See "
+ "https://google.github.io/googletest/"
+ "gmock_cook_book.html#NiceStrictNaggy");
NiceMock() : MockClass() {
- ::testing::Mock::AllowUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
// Ideally, we would inherit base class's constructors through a using
@@ -85,21 +156,16 @@ class NiceMock : public MockClass {
// made explicit.
template <typename A>
explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {
- ::testing::Mock::AllowUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
- template <typename A1, typename A2, typename... An>
- NiceMock(A1&& arg1, A2&& arg2, An&&... args)
- : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
+ template <typename TArg1, typename TArg2, typename... An>
+ NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
+ : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
std::forward<An>(args)...) {
- ::testing::Mock::AllowUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
- }
-
- ~NiceMock() { // NOLINT
- ::testing::Mock::UnregisterCallReaction(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
private:
@@ -107,11 +173,19 @@ class NiceMock : public MockClass {
};
template <class MockClass>
-class NaggyMock : public MockClass {
+class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
+ : private internal::NaggyMockImpl<MockClass>,
+ public MockClass {
+ static_assert(!internal::HasStrictnessModifier<MockClass>(),
+ "Can't apply NaggyMock to a class hierarchy that already has a "
+ "strictness modifier. See "
+ "https://google.github.io/googletest/"
+ "gmock_cook_book.html#NiceStrictNaggy");
+
public:
NaggyMock() : MockClass() {
- ::testing::Mock::WarnUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
// Ideally, we would inherit base class's constructors through a using
@@ -123,21 +197,16 @@ class NaggyMock : public MockClass {
// made explicit.
template <typename A>
explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) {
- ::testing::Mock::WarnUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
- template <typename A1, typename A2, typename... An>
- NaggyMock(A1&& arg1, A2&& arg2, An&&... args)
- : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
+ template <typename TArg1, typename TArg2, typename... An>
+ NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
+ : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
std::forward<An>(args)...) {
- ::testing::Mock::WarnUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
- }
-
- ~NaggyMock() { // NOLINT
- ::testing::Mock::UnregisterCallReaction(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
private:
@@ -145,11 +214,19 @@ class NaggyMock : public MockClass {
};
template <class MockClass>
-class StrictMock : public MockClass {
+class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
+ : private internal::StrictMockImpl<MockClass>,
+ public MockClass {
public:
+ static_assert(
+ !internal::HasStrictnessModifier<MockClass>(),
+ "Can't apply StrictMock to a class hierarchy that already has a "
+ "strictness modifier. See "
+ "https://google.github.io/googletest/"
+ "gmock_cook_book.html#NiceStrictNaggy");
StrictMock() : MockClass() {
- ::testing::Mock::FailUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
// Ideally, we would inherit base class's constructors through a using
@@ -161,55 +238,24 @@ class StrictMock : public MockClass {
// made explicit.
template <typename A>
explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) {
- ::testing::Mock::FailUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
- template <typename A1, typename A2, typename... An>
- StrictMock(A1&& arg1, A2&& arg2, An&&... args)
- : MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
+ template <typename TArg1, typename TArg2, typename... An>
+ StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args)
+ : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),
std::forward<An>(args)...) {
- ::testing::Mock::FailUninterestingCalls(
- internal::ImplicitCast_<MockClass*>(this));
- }
-
- ~StrictMock() { // NOLINT
- ::testing::Mock::UnregisterCallReaction(
- internal::ImplicitCast_<MockClass*>(this));
+ static_assert(sizeof(*this) == sizeof(MockClass),
+ "The impl subclass shouldn't introduce any padding");
}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
};
-// The following specializations catch some (relatively more common)
-// user errors of nesting nice and strict mocks. They do NOT catch
-// all possible errors.
-
-// These specializations are declared but not defined, as NiceMock,
-// NaggyMock, and StrictMock cannot be nested.
-
-template <typename MockClass>
-class NiceMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class NiceMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class NiceMock<StrictMock<MockClass> >;
-
-template <typename MockClass>
-class NaggyMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class NaggyMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class NaggyMock<StrictMock<MockClass> >;
-
-template <typename MockClass>
-class StrictMock<NiceMock<MockClass> >;
-template <typename MockClass>
-class StrictMock<NaggyMock<MockClass> >;
-template <typename MockClass>
-class StrictMock<StrictMock<MockClass> >;
+#undef GTEST_INTERNAL_EMPTY_BASE_CLASS
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h
index 718c9484..f1bd79cf 100644
--- a/googlemock/include/gmock/gmock-spec-builders.h
+++ b/googlemock/include/gmock/gmock-spec-builders.h
@@ -58,8 +58,8 @@
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#include <functional>
#include <map>
@@ -108,6 +108,14 @@ template <typename F> class TypedExpectation;
// Helper class for testing the Expectation class template.
class ExpectationTester;
+// Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
+template <typename MockClass>
+class NiceMockImpl;
+template <typename MockClass>
+class StrictMockImpl;
+template <typename MockClass>
+class NaggyMockImpl;
+
// Protects the mock object registry (in class Mock), all function
// mockers, and all expectations.
//
@@ -413,14 +421,12 @@ class GTEST_API_ Mock {
template <typename F>
friend class internal::FunctionMocker;
- template <typename M>
- friend class NiceMock;
-
- template <typename M>
- friend class NaggyMock;
-
- template <typename M>
- friend class StrictMock;
+ template <typename MockClass>
+ friend class internal::NiceMockImpl;
+ template <typename MockClass>
+ friend class internal::NaggyMockImpl;
+ template <typename MockClass>
+ friend class internal::StrictMockImpl;
// Tells Google Mock to allow uninteresting calls on the given mock
// object.
@@ -499,7 +505,10 @@ class GTEST_API_ Expectation {
public:
// Constructs a null object that doesn't reference any expectation.
Expectation();
-
+ Expectation(Expectation&&) = default;
+ Expectation(const Expectation&) = default;
+ Expectation& operator=(Expectation&&) = default;
+ Expectation& operator=(const Expectation&) = default;
~Expectation();
// This single-argument ctor must not be explicit, in order to support the
@@ -879,8 +888,6 @@ class GTEST_API_ ExpectationBase {
Clause last_clause_;
mutable bool action_count_checked_; // Under mutex_.
mutable Mutex mutex_; // Protects action_count_checked_.
-
- GTEST_DISALLOW_ASSIGN_(ExpectationBase);
}; // class ExpectationBase
// Impements an expectation for the given function type.
@@ -1295,8 +1302,6 @@ class MockSpec {
internal::FunctionMocker<F>* const function_mocker_;
// The argument matchers specified in the spec.
ArgumentMatcherTuple matchers_;
-
- GTEST_DISALLOW_ASSIGN_(MockSpec);
}; // class MockSpec
// Wrapper type for generically holding an ordinary value or lvalue reference.
@@ -1786,10 +1791,79 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
} // namespace internal
-// A MockFunction<F> class has one mock method whose type is F. It is
-// useful when you just want your test code to emit some messages and
-// have Google Mock verify the right messages are sent (and perhaps at
-// the right times). For example, if you are exercising code:
+namespace internal {
+
+template <typename F>
+class MockFunction;
+
+template <typename R, typename... Args>
+class MockFunction<R(Args...)> {
+ public:
+ MockFunction(const MockFunction&) = delete;
+ MockFunction& operator=(const MockFunction&) = delete;
+
+ std::function<R(Args...)> AsStdFunction() {
+ return [this](Args... args) -> R {
+ return this->Call(std::forward<Args>(args)...);
+ };
+ }
+
+ // Implementation detail: the expansion of the MOCK_METHOD macro.
+ R Call(Args... args) {
+ mock_.SetOwnerAndName(this, "Call");
+ return mock_.Invoke(std::forward<Args>(args)...);
+ }
+
+ MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
+ mock_.RegisterOwner(this);
+ return mock_.With(std::move(m)...);
+ }
+
+ MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
+ return this->gmock_Call(::testing::A<Args>()...);
+ }
+
+ protected:
+ MockFunction() = default;
+ ~MockFunction() = default;
+
+ private:
+ FunctionMocker<R(Args...)> mock_;
+};
+
+/*
+The SignatureOf<F> struct is a meta-function returning function signature
+corresponding to the provided F argument.
+
+It makes use of MockFunction easier by allowing it to accept more F arguments
+than just function signatures.
+
+Specializations provided here cover only a signature type itself and
+std::function. However, if need be it can be easily extended to cover also other
+types (like for example boost::function).
+*/
+
+template <typename F>
+struct SignatureOf;
+
+template <typename R, typename... Args>
+struct SignatureOf<R(Args...)> {
+ using type = R(Args...);
+};
+
+template <typename F>
+struct SignatureOf<std::function<F>> : SignatureOf<F> {};
+
+template <typename F>
+using SignatureOfT = typename SignatureOf<F>::type;
+
+} // namespace internal
+
+// A MockFunction<F> type has one mock method whose type is
+// internal::SignatureOfT<F>. It is useful when you just want your
+// test code to emit some messages and have Google Mock verify the
+// right messages are sent (and perhaps at the right times). For
+// example, if you are exercising code:
//
// Foo(1);
// Foo(2);
@@ -1823,49 +1897,34 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
// Bar("a") is called by which call to Foo().
//
// MockFunction<F> can also be used to exercise code that accepts
-// std::function<F> callbacks. To do so, use AsStdFunction() method
-// to create std::function proxy forwarding to original object's Call.
-// Example:
+// std::function<internal::SignatureOfT<F>> callbacks. To do so, use
+// AsStdFunction() method to create std::function proxy forwarding to
+// original object's Call. Example:
//
// TEST(FooTest, RunsCallbackWithBarArgument) {
// MockFunction<int(string)> callback;
// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
// Foo(callback.AsStdFunction());
// }
+//
+// The internal::SignatureOfT<F> indirection allows to use other types
+// than just function signature type. This is typically useful when
+// providing a mock for a predefined std::function type. Example:
+//
+// using FilterPredicate = std::function<bool(string)>;
+// void MyFilterAlgorithm(FilterPredicate predicate);
+//
+// TEST(FooTest, FilterPredicateAlwaysAccepts) {
+// MockFunction<FilterPredicate> predicateMock;
+// EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
+// MyFilterAlgorithm(predicateMock.AsStdFunction());
+// }
template <typename F>
-class MockFunction;
+class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
+ using Base = internal::MockFunction<internal::SignatureOfT<F>>;
-template <typename R, typename... Args>
-class MockFunction<R(Args...)> {
public:
- MockFunction() {}
- MockFunction(const MockFunction&) = delete;
- MockFunction& operator=(const MockFunction&) = delete;
-
- std::function<R(Args...)> AsStdFunction() {
- return [this](Args... args) -> R {
- return this->Call(std::forward<Args>(args)...);
- };
- }
-
- // Implementation detail: the expansion of the MOCK_METHOD macro.
- R Call(Args... args) {
- mock_.SetOwnerAndName(this, "Call");
- return mock_.Invoke(std::forward<Args>(args)...);
- }
-
- internal::MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
- mock_.RegisterOwner(this);
- return mock_.With(std::move(m)...);
- }
-
- internal::MockSpec<R(Args...)> gmock_Call(const internal::WithoutMatchers&,
- R (*)(Args...)) {
- return this->gmock_Call(::testing::A<Args>()...);
- }
-
- private:
- internal::FunctionMocker<R(Args...)> mock_;
+ using Base::Base;
};
// The style guide prohibits "using" statements in a namespace scope
@@ -1974,4 +2033,4 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#define EXPECT_CALL(obj, call) \
GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
diff --git a/googlemock/include/gmock/gmock.h b/googlemock/include/gmock/gmock.h
index 99c3d787..da1a4606 100644
--- a/googlemock/include/gmock/gmock.h
+++ b/googlemock/include/gmock/gmock.h
@@ -34,8 +34,10 @@
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_
-#define GMOCK_INCLUDE_GMOCK_GMOCK_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
+
+#define GMOCK_INCLUDE_GMOCK_GMOCK_H_ // Android: backwards compatibility.
// This file implements the following syntax:
//
@@ -59,9 +61,6 @@
#include "gmock/gmock-actions.h"
#include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-function-mocker.h"
-#include "gmock/gmock-generated-actions.h"
-#include "gmock/gmock-generated-function-mockers.h"
-#include "gmock/gmock-generated-matchers.h"
#include "gmock/gmock-matchers.h"
#include "gmock/gmock-more-actions.h"
#include "gmock/gmock-more-matchers.h"
@@ -98,4 +97,4 @@ GTEST_API_ void InitGoogleMock();
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_GMOCK_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h
index 92d910cf..63f89996 100644
--- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h
+++ b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h
@@ -1,10 +1,6 @@
-// This file was GENERATED by command:
-// pump.py gmock-generated-actions.h.pump
-// DO NOT EDIT BY HAND!!!
-
// GOOGLETEST_CM0002 DO NOT DELETE
-#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_
diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump
deleted file mode 100644
index 67c221f1..00000000
--- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump
+++ /dev/null
@@ -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_
diff --git a/googlemock/include/gmock/internal/custom/gmock-matchers.h b/googlemock/include/gmock/internal/custom/gmock-matchers.h
index 14aafaab..63842948 100644
--- a/googlemock/include/gmock/internal/custom/gmock-matchers.h
+++ b/googlemock/include/gmock/internal/custom/gmock-matchers.h
@@ -31,6 +31,6 @@
//
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
diff --git a/googlemock/include/gmock/internal/custom/gmock-port.h b/googlemock/include/gmock/internal/custom/gmock-port.h
index 0030fe91..14378692 100644
--- a/googlemock/include/gmock/internal/custom/gmock-port.h
+++ b/googlemock/include/gmock/internal/custom/gmock-port.h
@@ -33,7 +33,7 @@
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h
index 66cf857b..317544a7 100644
--- a/googlemock/include/gmock/internal/gmock-internal-utils.h
+++ b/googlemock/include/gmock/internal/gmock-internal-utils.h
@@ -36,8 +36,8 @@
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
#include <stdio.h>
#include <ostream> // NOLINT
@@ -71,20 +71,6 @@ GTEST_API_ std::string JoinAsTuple(const Strings& fields);
// "foo_bar_123" are converted to "foo bar 123".
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
-// PointeeOf<Pointer>::type is the type of a value pointed to by a
-// Pointer, which can be either a smart pointer or a raw pointer. The
-// following default implementation is for the case where Pointer is a
-// smart pointer.
-template <typename Pointer>
-struct PointeeOf {
- // Smart pointer classes define type element_type as the type of
- // their pointees.
- typedef typename Pointer::element_type type;
-};
-// This specialization is for the raw pointer case.
-template <typename T>
-struct PointeeOf<T*> { typedef T type; }; // NOLINT
-
// GetRawPointer(p) returns the raw pointer underlying p when p is a
// smart pointer, or returns p itself when p is already a raw pointer.
// The following default implementation is for the smart pointer case.
@@ -378,7 +364,8 @@ template <typename ElementPointer, typename Size>
class StlContainerView< ::std::tuple<ElementPointer, Size> > {
public:
typedef typename std::remove_const<
- typename internal::PointeeOf<ElementPointer>::type>::type RawElement;
+ typename std::pointer_traits<ElementPointer>::element_type>::type
+ RawElement;
typedef internal::NativeArray<RawElement> type;
typedef const type const_reference;
@@ -422,11 +409,13 @@ auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>) -> decltype(
// Apply the function to a tuple of arguments.
template <typename F, typename Tuple>
-auto Apply(F&& f, Tuple&& args)
- -> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
- MakeIndexSequence<std::tuple_size<Tuple>::value>())) {
+auto Apply(F&& f, Tuple&& args) -> decltype(
+ ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
+ MakeIndexSequence<std::tuple_size<
+ typename std::remove_reference<Tuple>::type>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
- MakeIndexSequence<std::tuple_size<Tuple>::value>());
+ MakeIndexSequence<std::tuple_size<
+ typename std::remove_reference<Tuple>::type>::value>());
}
// Template struct Function<F>, where F must be a function type, contains
@@ -467,4 +456,4 @@ constexpr size_t Function<R(Args...)>::ArgumentCount;
} // namespace internal
} // namespace testing
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h
index 70872ef3..367a44d3 100644
--- a/googlemock/include/gmock/internal/gmock-port.h
+++ b/googlemock/include/gmock/internal/gmock-port.h
@@ -37,8 +37,8 @@
// GOOGLETEST_CM0002 DO NOT DELETE
-#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
-#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
#include <assert.h>
#include <stdlib.h>
@@ -84,4 +84,4 @@
#endif // !defined(GMOCK_DECLARE_bool_)
-#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
diff --git a/googlemock/include/gmock/internal/gmock-pp.h b/googlemock/include/gmock/internal/gmock-pp.h
index c3759f66..94d61c09 100644
--- a/googlemock/include/gmock/internal/gmock-pp.h
+++ b/googlemock/include/gmock/internal/gmock-pp.h
@@ -1,5 +1,5 @@
-#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_
-#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_PP_H_
+#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
+#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
// Expands and concatenates the arguments. Constructed macros reevaluate.
#define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2)
@@ -28,16 +28,16 @@
// Requires: the number of arguments after expansion is at most 15.
#define GMOCK_PP_NARG(...) \
GMOCK_PP_INTERNAL_16TH( \
- (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1))
+ (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
// Returns 1 if the expansion of arguments has an unprotected comma. Otherwise
// returns 0. Requires no more than 15 unprotected commas.
#define GMOCK_PP_HAS_COMMA(...) \
GMOCK_PP_INTERNAL_16TH( \
- (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0))
+ (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0))
// Returns the first argument.
-#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__))
+#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg))
// Returns the tail. A variadic list of all arguments minus the first. Requires
// at least one argument.
@@ -86,6 +86,14 @@
#define GMOCK_PP_IF(_Cond, _Then, _Else) \
GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else)
+// Similar to GMOCK_PP_IF but takes _Then and _Else in parentheses.
+//
+// GMOCK_PP_GENERIC_IF(1, (a, b, c), (d, e, f)) => a, b, c
+// GMOCK_PP_GENERIC_IF(0, (a, b, c), (d, e, f)) => d, e, f
+//
+#define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \
+ GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else))
+
// Evaluates to the number of arguments after expansion. Identifies 'empty' as
// 0.
//
@@ -268,4 +276,4 @@
GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \
(GMOCK_PP_TAIL _Tuple))
-#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
+#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_
diff --git a/googlemock/scripts/fuse_gmock_files.py b/googlemock/scripts/fuse_gmock_files.py
index c33c7253..7fa9b3a5 100755
--- a/googlemock/scripts/fuse_gmock_files.py
+++ b/googlemock/scripts/fuse_gmock_files.py
@@ -28,8 +28,8 @@
# 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.
+"""fuse_gmock_files.py v0.1.0.
-"""fuse_gmock_files.py v0.1.0
Fuses Google Mock and Google Test source code into two .h files and a .cc file.
SYNOPSIS
@@ -55,27 +55,29 @@ EXAMPLES
This tool is experimental. In particular, it assumes that there is no
conditional inclusion of Google Mock or Google Test headers. Please
report any problems to googlemock@googlegroups.com. You can read
-https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md for more
+https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
+for more
information.
"""
-__author__ = 'wan@google.com (Zhanyong Wan)'
+from __future__ import print_function
import os
import re
-import sets
import sys
+__author__ = 'wan@google.com (Zhanyong Wan)'
+
# We assume that this file is in the scripts/ directory in the Google
# Mock root directory.
DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# We need to call into googletest/scripts/fuse_gtest_files.py.
sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, '../googletest/scripts'))
-import fuse_gtest_files
-gtest = fuse_gtest_files
+import fuse_gtest_files as gtest # pylint:disable=g-import-not-at-top
-# Regex for matching '#include "gmock/..."'.
+# Regex for matching
+# '#include "gmock/..."'.
INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gmock/.+)"')
# Where to find the source seed files.
@@ -98,6 +100,9 @@ def ValidateGMockRootDir(gmock_root):
"""Makes sure gmock_root points to a valid gmock root directory.
The function aborts the program on failure.
+
+ Args:
+ gmock_root: A string with the mock root directory.
"""
gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root))
@@ -109,6 +114,9 @@ def ValidateOutputDir(output_dir):
"""Makes sure output_dir points to a valid output directory.
The function aborts the program on failure.
+
+ Args:
+ output_dir: A string representing the output directory.
"""
gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT)
@@ -119,8 +127,8 @@ def ValidateOutputDir(output_dir):
def FuseGMockH(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock/gmock.h in output_dir."""
- output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
- processed_files = sets.Set() # Holds all gmock headers we've processed.
+ output_file = open(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
+ processed_files = set() # Holds all gmock headers we've processed.
def ProcessFile(gmock_header_path):
"""Processes the given gmock header file."""
@@ -132,25 +140,28 @@ def FuseGMockH(gmock_root, output_dir):
processed_files.add(gmock_header_path)
# Reads each line in the given gmock header.
- for line in file(os.path.join(gmock_root, gmock_header_path), 'r'):
- m = INCLUDE_GMOCK_FILE_REGEX.match(line)
- if m:
- # It's '#include "gmock/..."' - let's process it recursively.
- ProcessFile('include/' + m.group(1))
- else:
- m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
+
+ with open(os.path.join(gmock_root, gmock_header_path), 'r') as fh:
+ for line in fh:
+ m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m:
- # It's '#include "gtest/foo.h"'. We translate it to
- # "gtest/gtest.h", regardless of what foo is, since all
- # gtest headers are fused into gtest/gtest.h.
-
- # There is no need to #include gtest.h twice.
- if not gtest.GTEST_H_SEED in processed_files:
- processed_files.add(gtest.GTEST_H_SEED)
- output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,))
+ # '#include "gmock/..."'
+ # - let's process it recursively.
+ ProcessFile('include/' + m.group(1))
else:
- # Otherwise we copy the line unchanged to the output file.
- output_file.write(line)
+ m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
+ if m:
+ # '#include "gtest/foo.h"'
+ # We translate it to "gtest/gtest.h", regardless of what foo is,
+ # since all gtest headers are fused into gtest/gtest.h.
+
+ # There is no need to #include gtest.h twice.
+ if gtest.GTEST_H_SEED not in processed_files:
+ processed_files.add(gtest.GTEST_H_SEED)
+ output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,))
+ else:
+ # Otherwise we copy the line unchanged to the output file.
+ output_file.write(line)
ProcessFile(GMOCK_H_SEED)
output_file.close()
@@ -159,7 +170,7 @@ def FuseGMockH(gmock_root, output_dir):
def FuseGMockAllCcToFile(gmock_root, output_file):
"""Scans folder gmock_root to fuse gmock-all.cc into output_file."""
- processed_files = sets.Set()
+ processed_files = set()
def ProcessFile(gmock_source_file):
"""Processes the given gmock source file."""
@@ -171,32 +182,37 @@ def FuseGMockAllCcToFile(gmock_root, output_file):
processed_files.add(gmock_source_file)
# Reads each line in the given gmock source file.
- for line in file(os.path.join(gmock_root, gmock_source_file), 'r'):
- m = INCLUDE_GMOCK_FILE_REGEX.match(line)
- if m:
- # It's '#include "gmock/foo.h"'. We treat it as '#include
- # "gmock/gmock.h"', as all other gmock headers are being fused
- # into gmock.h and cannot be #included directly.
-
- # There is no need to #include "gmock/gmock.h" more than once.
- if not GMOCK_H_SEED in processed_files:
- processed_files.add(GMOCK_H_SEED)
- output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
- else:
- m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
+
+ with open(os.path.join(gmock_root, gmock_source_file), 'r') as fh:
+ for line in fh:
+ m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m:
- # It's '#include "gtest/..."'.
- # There is no need to #include gtest.h as it has been
- # #included by gtest-all.cc.
- pass
+ # '#include "gmock/foo.h"'
+ # We treat it as '#include "gmock/gmock.h"', as all other gmock
+ # headers are being fused into gmock.h and cannot be
+ # included directly. No need to
+ # #include "gmock/gmock.h"
+ # more than once.
+
+ if GMOCK_H_SEED not in processed_files:
+ processed_files.add(GMOCK_H_SEED)
+ output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
else:
- m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
+ m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
- # It's '#include "src/foo"' - let's process it recursively.
- ProcessFile(m.group(1))
+ # '#include "gtest/..."'
+ # There is no need to #include gtest.h as it has been
+ # #included by gtest-all.cc.
+
+ pass
else:
- # Otherwise we copy the line unchanged to the output file.
- output_file.write(line)
+ m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
+ if m:
+ # It's '#include "src/foo"' - let's process it recursively.
+ ProcessFile(m.group(1))
+ else:
+ # Otherwise we copy the line unchanged to the output file.
+ output_file.write(line)
ProcessFile(GMOCK_ALL_CC_SEED)
@@ -204,12 +220,12 @@ def FuseGMockAllCcToFile(gmock_root, output_file):
def FuseGMockGTestAllCc(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir."""
- output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w')
- # First, fuse gtest-all.cc into gmock-gtest-all.cc.
- gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
- # Next, append fused gmock-all.cc to gmock-gtest-all.cc.
- FuseGMockAllCcToFile(gmock_root, output_file)
- output_file.close()
+ with open(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT),
+ 'w') as output_file:
+ # First, fuse gtest-all.cc into gmock-gtest-all.cc.
+ gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
+ # Next, append fused gmock-all.cc to gmock-gtest-all.cc.
+ FuseGMockAllCcToFile(gmock_root, output_file)
def FuseGMock(gmock_root, output_dir):
@@ -232,7 +248,7 @@ def main():
# fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR
FuseGMock(sys.argv[1], sys.argv[2])
else:
- print __doc__
+ print(__doc__)
sys.exit(1)
diff --git a/googlemock/scripts/generator/cpp/ast.py b/googlemock/scripts/generator/cpp/ast.py
index f6331d80..0e770163 100755
--- a/googlemock/scripts/generator/cpp/ast.py
+++ b/googlemock/scripts/generator/cpp/ast.py
@@ -30,12 +30,13 @@
try:
- # Python 3.x
- import builtins
+ # Python 3.x
+ import builtins
except ImportError:
- # Python 2.x
- import __builtin__ as builtins
+ # Python 2.x
+ import __builtin__ as builtins
+import collections
import sys
import traceback
@@ -45,15 +46,15 @@ from cpp import utils
if not hasattr(builtins, 'reversed'):
- # Support Python 2.3 and earlier.
- def reversed(seq):
- for i in range(len(seq)-1, -1, -1):
- yield seq[i]
+ # Support Python 2.3 and earlier.
+ def reversed(seq):
+ for i in range(len(seq)-1, -1, -1):
+ yield seq[i]
if not hasattr(builtins, 'next'):
- # Support Python 2.5 and earlier.
- def next(obj):
- return obj.next()
+ # Support Python 2.5 and earlier.
+ def next(obj):
+ return obj.next()
VISIBILITY_PUBLIC, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE = range(3)
@@ -98,1598 +99,1609 @@ _NAMESPACE_POP = 'ns-pop'
# TODO(nnorwitz): use this as a singleton for templated_types, etc
# where we don't want to create a new empty dict each time. It is also const.
class _NullDict(object):
- __contains__ = lambda self: False
- keys = values = items = iterkeys = itervalues = iteritems = lambda self: ()
+ __contains__ = lambda self: False
+ keys = values = items = iterkeys = itervalues = iteritems = lambda self: ()
# TODO(nnorwitz): move AST nodes into a separate module.
class Node(object):
- """Base AST node."""
+ """Base AST node."""
- def __init__(self, start, end):
- self.start = start
- self.end = end
+ def __init__(self, start, end):
+ self.start = start
+ self.end = end
- def IsDeclaration(self):
- """Returns bool if this node is a declaration."""
- return False
+ def IsDeclaration(self):
+ """Returns bool if this node is a declaration."""
+ return False
- def IsDefinition(self):
- """Returns bool if this node is a definition."""
- return False
+ def IsDefinition(self):
+ """Returns bool if this node is a definition."""
+ return False
- def IsExportable(self):
- """Returns bool if this node exportable from a header file."""
- return False
+ def IsExportable(self):
+ """Returns bool if this node exportable from a header file."""
+ return False
- def Requires(self, node):
- """Does this AST node require the definition of the node passed in?"""
- return False
+ def Requires(self, node):
+ """Does this AST node require the definition of the node passed in?"""
+ return False
- def XXX__str__(self):
- return self._StringHelper(self.__class__.__name__, '')
+ def XXX__str__(self):
+ return self._StringHelper(self.__class__.__name__, '')
- def _StringHelper(self, name, suffix):
- if not utils.DEBUG:
- return '%s(%s)' % (name, suffix)
- return '%s(%d, %d, %s)' % (name, self.start, self.end, suffix)
+ def _StringHelper(self, name, suffix):
+ if not utils.DEBUG:
+ return '%s(%s)' % (name, suffix)
+ return '%s(%d, %d, %s)' % (name, self.start, self.end, suffix)
- def __repr__(self):
- return str(self)
+ def __repr__(self):
+ return str(self)
class Define(Node):
- def __init__(self, start, end, name, definition):
- Node.__init__(self, start, end)
- self.name = name
- self.definition = definition
+ def __init__(self, start, end, name, definition):
+ Node.__init__(self, start, end)
+ self.name = name
+ self.definition = definition
- def __str__(self):
- value = '%s %s' % (self.name, self.definition)
- return self._StringHelper(self.__class__.__name__, value)
+ def __str__(self):
+ value = '%s %s' % (self.name, self.definition)
+ return self._StringHelper(self.__class__.__name__, value)
class Include(Node):
- def __init__(self, start, end, filename, system):
- Node.__init__(self, start, end)
- self.filename = filename
- self.system = system
+ def __init__(self, start, end, filename, system):
+ Node.__init__(self, start, end)
+ self.filename = filename
+ self.system = system
- def __str__(self):
- fmt = '"%s"'
- if self.system:
- fmt = '<%s>'
- return self._StringHelper(self.__class__.__name__, fmt % self.filename)
+ def __str__(self):
+ fmt = '"%s"'
+ if self.system:
+ fmt = '<%s>'
+ return self._StringHelper(self.__class__.__name__, fmt % self.filename)
class Goto(Node):
- def __init__(self, start, end, label):
- Node.__init__(self, start, end)
- self.label = label
+ def __init__(self, start, end, label):
+ Node.__init__(self, start, end)
+ self.label = label
- def __str__(self):
- return self._StringHelper(self.__class__.__name__, str(self.label))
+ def __str__(self):
+ return self._StringHelper(self.__class__.__name__, str(self.label))
class Expr(Node):
- def __init__(self, start, end, expr):
- Node.__init__(self, start, end)
- self.expr = expr
+ def __init__(self, start, end, expr):
+ Node.__init__(self, start, end)
+ self.expr = expr
- def Requires(self, node):
- # TODO(nnorwitz): impl.
- return False
+ def Requires(self, node):
+ # TODO(nnorwitz): impl.
+ return False
- def __str__(self):
- return self._StringHelper(self.__class__.__name__, str(self.expr))
+ def __str__(self):
+ return self._StringHelper(self.__class__.__name__, str(self.expr))
class Return(Expr):
- pass
+ pass
class Delete(Expr):
- pass
+ pass
class Friend(Expr):
- def __init__(self, start, end, expr, namespace):
- Expr.__init__(self, start, end, expr)
- self.namespace = namespace[:]
+ def __init__(self, start, end, expr, namespace):
+ Expr.__init__(self, start, end, expr)
+ self.namespace = namespace[:]
class Using(Node):
- def __init__(self, start, end, names):
- Node.__init__(self, start, end)
- self.names = names
+ def __init__(self, start, end, names):
+ Node.__init__(self, start, end)
+ self.names = names
- def __str__(self):
- return self._StringHelper(self.__class__.__name__, str(self.names))
+ def __str__(self):
+ return self._StringHelper(self.__class__.__name__, str(self.names))
class Parameter(Node):
- def __init__(self, start, end, name, parameter_type, default):
- Node.__init__(self, start, end)
- self.name = name
- self.type = parameter_type
- self.default = default
+ def __init__(self, start, end, name, parameter_type, default):
+ Node.__init__(self, start, end)
+ self.name = name
+ self.type = parameter_type
+ self.default = default
- def Requires(self, node):
- # TODO(nnorwitz): handle namespaces, etc.
- return self.type.name == node.name
+ def Requires(self, node):
+ # TODO(nnorwitz): handle namespaces, etc.
+ return self.type.name == node.name
- def __str__(self):
- name = str(self.type)
- suffix = '%s %s' % (name, self.name)
- if self.default:
- suffix += ' = ' + ''.join([d.name for d in self.default])
- return self._StringHelper(self.__class__.__name__, suffix)
+ def __str__(self):
+ name = str(self.type)
+ suffix = '%s %s' % (name, self.name)
+ if self.default:
+ suffix += ' = ' + ''.join([d.name for d in self.default])
+ return self._StringHelper(self.__class__.__name__, suffix)
class _GenericDeclaration(Node):
- def __init__(self, start, end, name, namespace):
- Node.__init__(self, start, end)
- self.name = name
- self.namespace = namespace[:]
+ def __init__(self, start, end, name, namespace):
+ Node.__init__(self, start, end)
+ self.name = name
+ self.namespace = namespace[:]
- def FullName(self):
- prefix = ''
- if self.namespace and self.namespace[-1]:
- prefix = '::'.join(self.namespace) + '::'
- return prefix + self.name
+ def FullName(self):
+ prefix = ''
+ if self.namespace and self.namespace[-1]:
+ prefix = '::'.join(self.namespace) + '::'
+ return prefix + self.name
- def _TypeStringHelper(self, suffix):
- if self.namespace:
- names = [n or '<anonymous>' for n in self.namespace]
- suffix += ' in ' + '::'.join(names)
- return self._StringHelper(self.__class__.__name__, suffix)
+ def _TypeStringHelper(self, suffix):
+ if self.namespace:
+ names = [n or '<anonymous>' for n in self.namespace]
+ suffix += ' in ' + '::'.join(names)
+ return self._StringHelper(self.__class__.__name__, suffix)
# TODO(nnorwitz): merge with Parameter in some way?
class VariableDeclaration(_GenericDeclaration):
- def __init__(self, start, end, name, var_type, initial_value, namespace):
- _GenericDeclaration.__init__(self, start, end, name, namespace)
- self.type = var_type
- self.initial_value = initial_value
+ def __init__(self, start, end, name, var_type, initial_value, namespace):
+ _GenericDeclaration.__init__(self, start, end, name, namespace)
+ self.type = var_type
+ self.initial_value = initial_value
- def Requires(self, node):
- # TODO(nnorwitz): handle namespaces, etc.
- return self.type.name == node.name
+ def Requires(self, node):
+ # TODO(nnorwitz): handle namespaces, etc.
+ return self.type.name == node.name
- def ToString(self):
- """Return a string that tries to reconstitute the variable decl."""
- suffix = '%s %s' % (self.type, self.name)
- if self.initial_value:
- suffix += ' = ' + self.initial_value
- return suffix
+ def ToString(self):
+ """Return a string that tries to reconstitute the variable decl."""
+ suffix = '%s %s' % (self.type, self.name)
+ if self.initial_value:
+ suffix += ' = ' + self.initial_value
+ return suffix
- def __str__(self):
- return self._StringHelper(self.__class__.__name__, self.ToString())
+ def __str__(self):
+ return self._StringHelper(self.__class__.__name__, self.ToString())
class Typedef(_GenericDeclaration):
- def __init__(self, start, end, name, alias, namespace):
- _GenericDeclaration.__init__(self, start, end, name, namespace)
- self.alias = alias
+ def __init__(self, start, end, name, alias, namespace):
+ _GenericDeclaration.__init__(self, start, end, name, namespace)
+ self.alias = alias
- def IsDefinition(self):
- return True
+ def IsDefinition(self):
+ return True
- def IsExportable(self):
- return True
+ def IsExportable(self):
+ return True
- def Requires(self, node):
- # TODO(nnorwitz): handle namespaces, etc.
- name = node.name
- for token in self.alias:
- if token is not None and name == token.name:
- return True
- return False
+ def Requires(self, node):
+ # TODO(nnorwitz): handle namespaces, etc.
+ name = node.name
+ for token in self.alias:
+ if token is not None and name == token.name:
+ return True
+ return False
- def __str__(self):
- suffix = '%s, %s' % (self.name, self.alias)
- return self._TypeStringHelper(suffix)
+ def __str__(self):
+ suffix = '%s, %s' % (self.name, self.alias)
+ return self._TypeStringHelper(suffix)
class _NestedType(_GenericDeclaration):
- def __init__(self, start, end, name, fields, namespace):
- _GenericDeclaration.__init__(self, start, end, name, namespace)
- self.fields = fields
+ def __init__(self, start, end, name, fields, namespace):
+ _GenericDeclaration.__init__(self, start, end, name, namespace)
+ self.fields = fields
- def IsDefinition(self):
- return True
+ def IsDefinition(self):
+ return True
- def IsExportable(self):
- return True
+ def IsExportable(self):
+ return True
- def __str__(self):
- suffix = '%s, {%s}' % (self.name, self.fields)
- return self._TypeStringHelper(suffix)
+ def __str__(self):
+ suffix = '%s, {%s}' % (self.name, self.fields)
+ return self._TypeStringHelper(suffix)
class Union(_NestedType):
- pass
+ pass
class Enum(_NestedType):
- pass
+ pass
class Class(_GenericDeclaration):
- def __init__(self, start, end, name, bases, templated_types, body, namespace):
- _GenericDeclaration.__init__(self, start, end, name, namespace)
- self.bases = bases
- self.body = body
- self.templated_types = templated_types
-
- def IsDeclaration(self):
- return self.bases is None and self.body is None
-
- def IsDefinition(self):
- return not self.IsDeclaration()
-
- def IsExportable(self):
- return not self.IsDeclaration()
-
- def Requires(self, node):
- # TODO(nnorwitz): handle namespaces, etc.
- if self.bases:
- for token_list in self.bases:
- # TODO(nnorwitz): bases are tokens, do name comparision.
- for token in token_list:
- if token.name == node.name:
- return True
- # TODO(nnorwitz): search in body too.
- return False
-
- def __str__(self):
- name = self.name
- if self.templated_types:
- name += '<%s>' % self.templated_types
- suffix = '%s, %s, %s' % (name, self.bases, self.body)
- return self._TypeStringHelper(suffix)
+ def __init__(self, start, end, name, bases, templated_types, body, namespace):
+ _GenericDeclaration.__init__(self, start, end, name, namespace)
+ self.bases = bases
+ self.body = body
+ self.templated_types = templated_types
+
+ def IsDeclaration(self):
+ return self.bases is None and self.body is None
+
+ def IsDefinition(self):
+ return not self.IsDeclaration()
+
+ def IsExportable(self):
+ return not self.IsDeclaration()
+
+ def Requires(self, node):
+ # TODO(nnorwitz): handle namespaces, etc.
+ if self.bases:
+ for token_list in self.bases:
+ # TODO(nnorwitz): bases are tokens, do name comparison.
+ for token in token_list:
+ if token.name == node.name:
+ return True
+ # TODO(nnorwitz): search in body too.
+ return False
+
+ def __str__(self):
+ name = self.name
+ if self.templated_types:
+ name += '<%s>' % self.templated_types
+ suffix = '%s, %s, %s' % (name, self.bases, self.body)
+ return self._TypeStringHelper(suffix)
class Struct(Class):
- pass
+ pass
class Function(_GenericDeclaration):
- def __init__(self, start, end, name, return_type, parameters,
- modifiers, templated_types, body, namespace):
- _GenericDeclaration.__init__(self, start, end, name, namespace)
- converter = TypeConverter(namespace)
- self.return_type = converter.CreateReturnType(return_type)
- self.parameters = converter.ToParameters(parameters)
- self.modifiers = modifiers
- self.body = body
- self.templated_types = templated_types
-
- def IsDeclaration(self):
- return self.body is None
-
- def IsDefinition(self):
- return self.body is not None
-
- def IsExportable(self):
- if self.return_type and 'static' in self.return_type.modifiers:
- return False
- return None not in self.namespace
-
- def Requires(self, node):
- if self.parameters:
- # TODO(nnorwitz): parameters are tokens, do name comparision.
- for p in self.parameters:
- if p.name == node.name:
- return True
- # TODO(nnorwitz): search in body too.
- return False
-
- def __str__(self):
- # TODO(nnorwitz): add templated_types.
- suffix = ('%s %s(%s), 0x%02x, %s' %
- (self.return_type, self.name, self.parameters,
- self.modifiers, self.body))
- return self._TypeStringHelper(suffix)
+ def __init__(self, start, end, name, return_type, parameters,
+ modifiers, templated_types, body, namespace):
+ _GenericDeclaration.__init__(self, start, end, name, namespace)
+ converter = TypeConverter(namespace)
+ self.return_type = converter.CreateReturnType(return_type)
+ self.parameters = converter.ToParameters(parameters)
+ self.modifiers = modifiers
+ self.body = body
+ self.templated_types = templated_types
+
+ def IsDeclaration(self):
+ return self.body is None
+
+ def IsDefinition(self):
+ return self.body is not None
+
+ def IsExportable(self):
+ if self.return_type and 'static' in self.return_type.modifiers:
+ return False
+ return None not in self.namespace
+
+ def Requires(self, node):
+ if self.parameters:
+ # TODO(nnorwitz): parameters are tokens, do name comparison.
+ for p in self.parameters:
+ if p.name == node.name:
+ return True
+ # TODO(nnorwitz): search in body too.
+ return False
+
+ def __str__(self):
+ # TODO(nnorwitz): add templated_types.
+ suffix = ('%s %s(%s), 0x%02x, %s' %
+ (self.return_type, self.name, self.parameters,
+ self.modifiers, self.body))
+ return self._TypeStringHelper(suffix)
class Method(Function):
- def __init__(self, start, end, name, in_class, return_type, parameters,
- modifiers, templated_types, body, namespace):
- Function.__init__(self, start, end, name, return_type, parameters,
- modifiers, templated_types, body, namespace)
- # TODO(nnorwitz): in_class could also be a namespace which can
- # mess up finding functions properly.
- self.in_class = in_class
+ def __init__(self, start, end, name, in_class, return_type, parameters,
+ modifiers, templated_types, body, namespace):
+ Function.__init__(self, start, end, name, return_type, parameters,
+ modifiers, templated_types, body, namespace)
+ # TODO(nnorwitz): in_class could also be a namespace which can
+ # mess up finding functions properly.
+ self.in_class = in_class
class Type(_GenericDeclaration):
- """Type used for any variable (eg class, primitive, struct, etc)."""
+ """Type used for any variable (eg class, primitive, struct, etc)."""
- def __init__(self, start, end, name, templated_types, modifiers,
- reference, pointer, array):
- """
+ def __init__(self, start, end, name, templated_types, modifiers,
+ reference, pointer, array):
+ """
Args:
name: str name of main type
templated_types: [Class (Type?)] template type info between <>
modifiers: [str] type modifiers (keywords) eg, const, mutable, etc.
reference, pointer, array: bools
"""
- _GenericDeclaration.__init__(self, start, end, name, [])
- self.templated_types = templated_types
- if not name and modifiers:
- self.name = modifiers.pop()
- self.modifiers = modifiers
- self.reference = reference
- self.pointer = pointer
- self.array = array
-
- def __str__(self):
- prefix = ''
- if self.modifiers:
- prefix = ' '.join(self.modifiers) + ' '
- name = str(self.name)
- if self.templated_types:
- name += '<%s>' % self.templated_types
- suffix = prefix + name
- if self.reference:
- suffix += '&'
- if self.pointer:
- suffix += '*'
- if self.array:
- suffix += '[]'
- return self._TypeStringHelper(suffix)
-
- # By definition, Is* are always False. A Type can only exist in
- # some sort of variable declaration, parameter, or return value.
- def IsDeclaration(self):
- return False
-
- def IsDefinition(self):
- return False
-
- def IsExportable(self):
- return False
+ _GenericDeclaration.__init__(self, start, end, name, [])
+ self.templated_types = templated_types
+ if not name and modifiers:
+ self.name = modifiers.pop()
+ self.modifiers = modifiers
+ self.reference = reference
+ self.pointer = pointer
+ self.array = array
+
+ def __str__(self):
+ prefix = ''
+ if self.modifiers:
+ prefix = ' '.join(self.modifiers) + ' '
+ name = str(self.name)
+ if self.templated_types:
+ name += '<%s>' % self.templated_types
+ suffix = prefix + name
+ if self.reference:
+ suffix += '&'
+ if self.pointer:
+ suffix += '*'
+ if self.array:
+ suffix += '[]'
+ return self._TypeStringHelper(suffix)
+
+ # By definition, Is* are always False. A Type can only exist in
+ # some sort of variable declaration, parameter, or return value.
+ def IsDeclaration(self):
+ return False
+
+ def IsDefinition(self):
+ return False
+
+ def IsExportable(self):
+ return False
class TypeConverter(object):
- def __init__(self, namespace_stack):
- self.namespace_stack = namespace_stack
-
- def _GetTemplateEnd(self, tokens, start):
- count = 1
- end = start
- while 1:
- token = tokens[end]
- end += 1
- if token.name == '<':
- count += 1
- elif token.name == '>':
- count -= 1
- if count == 0:
- break
- return tokens[start:end-1], end
-
- def ToType(self, tokens):
- """Convert [Token,...] to [Class(...), ] useful for base classes.
+ def __init__(self, namespace_stack):
+ self.namespace_stack = namespace_stack
+
+ def _GetTemplateEnd(self, tokens, start):
+ count = 1
+ end = start
+ while 1:
+ token = tokens[end]
+ end += 1
+ if token.name == '<':
+ count += 1
+ elif token.name == '>':
+ count -= 1
+ if count == 0:
+ break
+ return tokens[start:end-1], end
+
+ def ToType(self, tokens):
+ """Convert [Token,...] to [Class(...), ] useful for base classes.
For example, code like class Foo : public Bar<x, y> { ... };
the "Bar<x, y>" portion gets converted to an AST.
Returns:
[Class(...), ...]
"""
- result = []
- name_tokens = []
+ result = []
+ name_tokens = []
+ reference = pointer = array = False
+
+ def AddType(templated_types):
+ # Partition tokens into name and modifier tokens.
+ names = []
+ modifiers = []
+ for t in name_tokens:
+ if keywords.IsKeyword(t.name):
+ modifiers.append(t.name)
+ else:
+ names.append(t.name)
+ name = ''.join(names)
+ if name_tokens:
+ result.append(Type(name_tokens[0].start, name_tokens[-1].end,
+ name, templated_types, modifiers,
+ reference, pointer, array))
+ del name_tokens[:]
+
+ i = 0
+ end = len(tokens)
+ while i < end:
+ token = tokens[i]
+ if token.name == '<':
+ new_tokens, new_end = self._GetTemplateEnd(tokens, i+1)
+ AddType(self.ToType(new_tokens))
+ # If there is a comma after the template, we need to consume
+ # that here otherwise it becomes part of the name.
+ i = new_end
reference = pointer = array = False
-
- def AddType(templated_types):
- # Partition tokens into name and modifier tokens.
- names = []
- modifiers = []
- for t in name_tokens:
- if keywords.IsKeyword(t.name):
- modifiers.append(t.name)
- else:
- names.append(t.name)
- name = ''.join(names)
- if name_tokens:
- result.append(Type(name_tokens[0].start, name_tokens[-1].end,
- name, templated_types, modifiers,
- reference, pointer, array))
- del name_tokens[:]
-
- i = 0
- end = len(tokens)
- while i < end:
- token = tokens[i]
- if token.name == '<':
- new_tokens, new_end = self._GetTemplateEnd(tokens, i+1)
- AddType(self.ToType(new_tokens))
- # If there is a comma after the template, we need to consume
- # that here otherwise it becomes part of the name.
- i = new_end
- reference = pointer = array = False
- elif token.name == ',':
- AddType([])
- reference = pointer = array = False
- elif token.name == '*':
- pointer = True
- elif token.name == '&':
- reference = True
- elif token.name == '[':
- pointer = True
- elif token.name == ']':
- pass
- else:
- name_tokens.append(token)
- i += 1
-
- if name_tokens:
- # No '<' in the tokens, just a simple name and no template.
- AddType([])
- return result
-
- def DeclarationToParts(self, parts, needs_name_removed):
- name = None
- default = []
- if needs_name_removed:
- # Handle default (initial) values properly.
- for i, t in enumerate(parts):
- if t.name == '=':
- default = parts[i+1:]
- name = parts[i-1].name
- if name == ']' and parts[i-2].name == '[':
- name = parts[i-3].name
- i -= 1
- parts = parts[:i-1]
- break
- else:
- if parts[-1].token_type == tokenize.NAME:
- name = parts.pop().name
- else:
- # TODO(nnorwitz): this is a hack that happens for code like
- # Register(Foo<T>); where it thinks this is a function call
- # but it's actually a declaration.
- name = '???'
- modifiers = []
- type_name = []
- other_tokens = []
- templated_types = []
- i = 0
- end = len(parts)
- while i < end:
- p = parts[i]
- if keywords.IsKeyword(p.name):
- modifiers.append(p.name)
- elif p.name == '<':
- templated_tokens, new_end = self._GetTemplateEnd(parts, i+1)
- templated_types = self.ToType(templated_tokens)
- i = new_end - 1
- # Don't add a spurious :: to data members being initialized.
- next_index = i + 1
- if next_index < end and parts[next_index].name == '::':
- i += 1
- elif p.name in ('[', ']', '='):
- # These are handled elsewhere.
- other_tokens.append(p)
- elif p.name not in ('*', '&', '>'):
- # Ensure that names have a space between them.
- if (type_name and type_name[-1].token_type == tokenize.NAME and
- p.token_type == tokenize.NAME):
- type_name.append(tokenize.Token(tokenize.SYNTAX, ' ', 0, 0))
- type_name.append(p)
- else:
- other_tokens.append(p)
- i += 1
- type_name = ''.join([t.name for t in type_name])
- return name, type_name, templated_types, modifiers, default, other_tokens
-
- def ToParameters(self, tokens):
- if not tokens:
- return []
-
- result = []
+ elif token.name == ',':
+ AddType([])
+ reference = pointer = array = False
+ elif token.name == '*':
+ pointer = True
+ elif token.name == '&':
+ reference = True
+ elif token.name == '[':
+ pointer = True
+ elif token.name == ']':
+ pass
+ else:
+ name_tokens.append(token)
+ i += 1
+
+ if name_tokens:
+ # No '<' in the tokens, just a simple name and no template.
+ AddType([])
+ return result
+
+ def DeclarationToParts(self, parts, needs_name_removed):
+ name = None
+ default = []
+ if needs_name_removed:
+ # Handle default (initial) values properly.
+ for i, t in enumerate(parts):
+ if t.name == '=':
+ default = parts[i+1:]
+ name = parts[i-1].name
+ if name == ']' and parts[i-2].name == '[':
+ name = parts[i-3].name
+ i -= 1
+ parts = parts[:i-1]
+ break
+ else:
+ if parts[-1].token_type == tokenize.NAME:
+ name = parts.pop().name
+ else:
+ # TODO(nnorwitz): this is a hack that happens for code like
+ # Register(Foo<T>); where it thinks this is a function call
+ # but it's actually a declaration.
+ name = '???'
+ modifiers = []
+ type_name = []
+ other_tokens = []
+ templated_types = []
+ i = 0
+ end = len(parts)
+ while i < end:
+ p = parts[i]
+ if keywords.IsKeyword(p.name):
+ modifiers.append(p.name)
+ elif p.name == '<':
+ templated_tokens, new_end = self._GetTemplateEnd(parts, i+1)
+ templated_types = self.ToType(templated_tokens)
+ i = new_end - 1
+ # Don't add a spurious :: to data members being initialized.
+ next_index = i + 1
+ if next_index < end and parts[next_index].name == '::':
+ i += 1
+ elif p.name in ('[', ']', '='):
+ # These are handled elsewhere.
+ other_tokens.append(p)
+ elif p.name not in ('*', '&', '>'):
+ # Ensure that names have a space between them.
+ if (type_name and type_name[-1].token_type == tokenize.NAME and
+ p.token_type == tokenize.NAME):
+ type_name.append(tokenize.Token(tokenize.SYNTAX, ' ', 0, 0))
+ type_name.append(p)
+ else:
+ other_tokens.append(p)
+ i += 1
+ type_name = ''.join([t.name for t in type_name])
+ return name, type_name, templated_types, modifiers, default, other_tokens
+
+ def ToParameters(self, tokens):
+ if not tokens:
+ return []
+
+ result = []
+ name = type_name = ''
+ type_modifiers = []
+ pointer = reference = array = False
+ first_token = None
+ default = []
+
+ def AddParameter(end):
+ if default:
+ del default[0] # Remove flag.
+ parts = self.DeclarationToParts(type_modifiers, True)
+ (name, type_name, templated_types, modifiers,
+ unused_default, unused_other_tokens) = parts
+ parameter_type = Type(first_token.start, first_token.end,
+ type_name, templated_types, modifiers,
+ reference, pointer, array)
+ p = Parameter(first_token.start, end, name,
+ parameter_type, default)
+ result.append(p)
+
+ template_count = 0
+ brace_count = 0
+ for s in tokens:
+ if not first_token:
+ first_token = s
+
+ # Check for braces before templates, as we can have unmatched '<>'
+ # inside default arguments.
+ if s.name == '{':
+ brace_count += 1
+ elif s.name == '}':
+ brace_count -= 1
+ if brace_count > 0:
+ type_modifiers.append(s)
+ continue
+
+ if s.name == '<':
+ template_count += 1
+ elif s.name == '>':
+ template_count -= 1
+ if template_count > 0:
+ type_modifiers.append(s)
+ continue
+
+ if s.name == ',':
+ AddParameter(s.start)
name = type_name = ''
type_modifiers = []
pointer = reference = array = False
first_token = None
default = []
-
- def AddParameter(end):
- if default:
- del default[0] # Remove flag.
- parts = self.DeclarationToParts(type_modifiers, True)
- (name, type_name, templated_types, modifiers,
- unused_default, unused_other_tokens) = parts
- parameter_type = Type(first_token.start, first_token.end,
- type_name, templated_types, modifiers,
- reference, pointer, array)
- p = Parameter(first_token.start, end, name,
- parameter_type, default)
- result.append(p)
-
- template_count = 0
- for s in tokens:
- if not first_token:
- first_token = s
- if s.name == '<':
- template_count += 1
- elif s.name == '>':
- template_count -= 1
- if template_count > 0:
- type_modifiers.append(s)
- continue
-
- if s.name == ',':
- AddParameter(s.start)
- name = type_name = ''
- type_modifiers = []
- pointer = reference = array = False
- first_token = None
- default = []
- elif s.name == '*':
- pointer = True
- elif s.name == '&':
- reference = True
- elif s.name == '[':
- array = True
- elif s.name == ']':
- pass # Just don't add to type_modifiers.
- elif s.name == '=':
- # Got a default value. Add any value (None) as a flag.
- default.append(None)
- elif default:
- default.append(s)
- else:
- type_modifiers.append(s)
- AddParameter(tokens[-1].end)
- return result
-
- def CreateReturnType(self, return_type_seq):
- if not return_type_seq:
- return None
- start = return_type_seq[0].start
- end = return_type_seq[-1].end
- _, name, templated_types, modifiers, default, other_tokens = \
- self.DeclarationToParts(return_type_seq, False)
- names = [n.name for n in other_tokens]
- reference = '&' in names
- pointer = '*' in names
- array = '[' in names
- return Type(start, end, name, templated_types, modifiers,
- reference, pointer, array)
-
- def GetTemplateIndices(self, names):
- # names is a list of strings.
- start = names.index('<')
- end = len(names) - 1
- while end > 0:
- if names[end] == '>':
- break
- end -= 1
- return start, end+1
+ elif s.name == '*':
+ pointer = True
+ elif s.name == '&':
+ reference = True
+ elif s.name == '[':
+ array = True
+ elif s.name == ']':
+ pass # Just don't add to type_modifiers.
+ elif s.name == '=':
+ # Got a default value. Add any value (None) as a flag.
+ default.append(None)
+ elif default:
+ default.append(s)
+ else:
+ type_modifiers.append(s)
+ AddParameter(tokens[-1].end)
+ return result
+
+ def CreateReturnType(self, return_type_seq):
+ if not return_type_seq:
+ return None
+ start = return_type_seq[0].start
+ end = return_type_seq[-1].end
+ _, name, templated_types, modifiers, default, other_tokens = \
+ self.DeclarationToParts(return_type_seq, False)
+ names = [n.name for n in other_tokens]
+ reference = '&' in names
+ pointer = '*' in names
+ array = '[' in names
+ return Type(start, end, name, templated_types, modifiers,
+ reference, pointer, array)
+
+ def GetTemplateIndices(self, names):
+ # names is a list of strings.
+ start = names.index('<')
+ end = len(names) - 1
+ while end > 0:
+ if names[end] == '>':
+ break
+ end -= 1
+ return start, end+1
class AstBuilder(object):
- def __init__(self, token_stream, filename, in_class='', visibility=None,
- namespace_stack=[]):
- self.tokens = token_stream
- self.filename = filename
- # TODO(nnorwitz): use a better data structure (deque) for the queue.
- # Switching directions of the "queue" improved perf by about 25%.
- # Using a deque should be even better since we access from both sides.
- self.token_queue = []
- self.namespace_stack = namespace_stack[:]
- self.in_class = in_class
- if in_class is None:
- self.in_class_name_only = None
- else:
- self.in_class_name_only = in_class.split('::')[-1]
- self.visibility = visibility
- self.in_function = False
- self.current_token = None
- # Keep the state whether we are currently handling a typedef or not.
- self._handling_typedef = False
-
- self.converter = TypeConverter(self.namespace_stack)
-
- def HandleError(self, msg, token):
- printable_queue = list(reversed(self.token_queue[-20:]))
- sys.stderr.write('Got %s in %s @ %s %s\n' %
- (msg, self.filename, token, printable_queue))
-
- def Generate(self):
- while 1:
- token = self._GetNextToken()
- if not token:
- break
-
- # Get the next token.
- self.current_token = token
-
- # Dispatch on the next token type.
- if token.token_type == _INTERNAL_TOKEN:
- if token.name == _NAMESPACE_POP:
- self.namespace_stack.pop()
- continue
-
- try:
- result = self._GenerateOne(token)
- if result is not None:
- yield result
- except:
- self.HandleError('exception', token)
- raise
-
- def _CreateVariable(self, pos_token, name, type_name, type_modifiers,
- ref_pointer_name_seq, templated_types, value=None):
- reference = '&' in ref_pointer_name_seq
- pointer = '*' in ref_pointer_name_seq
- array = '[' in ref_pointer_name_seq
- var_type = Type(pos_token.start, pos_token.end, type_name,
- templated_types, type_modifiers,
- reference, pointer, array)
- return VariableDeclaration(pos_token.start, pos_token.end,
- name, var_type, value, self.namespace_stack)
-
- def _GenerateOne(self, token):
- if token.token_type == tokenize.NAME:
- if (keywords.IsKeyword(token.name) and
- not keywords.IsBuiltinType(token.name)):
- if token.name == 'enum':
- # Pop the next token and only put it back if it's not
- # 'class'. This allows us to support the two-token
- # 'enum class' keyword as if it were simply 'enum'.
- next = self._GetNextToken()
- if next.name != 'class':
- self._AddBackToken(next)
-
- method = getattr(self, 'handle_' + token.name)
- return method()
- elif token.name == self.in_class_name_only:
- # The token name is the same as the class, must be a ctor if
- # there is a paren. Otherwise, it's the return type.
- # Peek ahead to get the next token to figure out which.
- next = self._GetNextToken()
- self._AddBackToken(next)
- if next.token_type == tokenize.SYNTAX and next.name == '(':
- return self._GetMethod([token], FUNCTION_CTOR, None, True)
- # Fall through--handle like any other method.
-
- # Handle data or function declaration/definition.
- syntax = tokenize.SYNTAX
- temp_tokens, last_token = \
- self._GetVarTokensUpToIgnoringTemplates(syntax,
- '(', ';', '{', '[')
- temp_tokens.insert(0, token)
- if last_token.name == '(':
- # If there is an assignment before the paren,
- # this is an expression, not a method.
- expr = bool([e for e in temp_tokens if e.name == '='])
- if expr:
- new_temp = self._GetTokensUpTo(tokenize.SYNTAX, ';')
- temp_tokens.append(last_token)
- temp_tokens.extend(new_temp)
- last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0)
-
- if last_token.name == '[':
- # Handle array, this isn't a method, unless it's an operator.
- # TODO(nnorwitz): keep the size somewhere.
- # unused_size = self._GetTokensUpTo(tokenize.SYNTAX, ']')
- temp_tokens.append(last_token)
- if temp_tokens[-2].name == 'operator':
- temp_tokens.append(self._GetNextToken())
- else:
- temp_tokens2, last_token = \
- self._GetVarTokensUpTo(tokenize.SYNTAX, ';')
- temp_tokens.extend(temp_tokens2)
-
- if last_token.name == ';':
- # Handle data, this isn't a method.
- parts = self.converter.DeclarationToParts(temp_tokens, True)
- (name, type_name, templated_types, modifiers, default,
- unused_other_tokens) = parts
-
- t0 = temp_tokens[0]
- names = [t.name for t in temp_tokens]
- if templated_types:
- start, end = self.converter.GetTemplateIndices(names)
- names = names[:start] + names[end:]
- default = ''.join([t.name for t in default])
- return self._CreateVariable(t0, name, type_name, modifiers,
- names, templated_types, default)
- if last_token.name == '{':
- self._AddBackTokens(temp_tokens[1:])
- self._AddBackToken(last_token)
- method_name = temp_tokens[0].name
- method = getattr(self, 'handle_' + method_name, None)
- if not method:
- # Must be declaring a variable.
- # TODO(nnorwitz): handle the declaration.
- return None
- return method()
- return self._GetMethod(temp_tokens, 0, None, False)
- elif token.token_type == tokenize.SYNTAX:
- if token.name == '~' and self.in_class:
- # Must be a dtor (probably not in method body).
- token = self._GetNextToken()
- # self.in_class can contain A::Name, but the dtor will only
- # be Name. Make sure to compare against the right value.
- if (token.token_type == tokenize.NAME and
- token.name == self.in_class_name_only):
- return self._GetMethod([token], FUNCTION_DTOR, None, True)
- # TODO(nnorwitz): handle a lot more syntax.
- elif token.token_type == tokenize.PREPROCESSOR:
- # TODO(nnorwitz): handle more preprocessor directives.
- # token starts with a #, so remove it and strip whitespace.
- name = token.name[1:].lstrip()
- if name.startswith('include'):
- # Remove "include".
- name = name[7:].strip()
- assert name
- # Handle #include \<newline> "header-on-second-line.h".
- if name.startswith('\\'):
- name = name[1:].strip()
- assert name[0] in '<"', token
- assert name[-1] in '>"', token
- system = name[0] == '<'
- filename = name[1:-1]
- return Include(token.start, token.end, filename, system)
- if name.startswith('define'):
- # Remove "define".
- name = name[6:].strip()
- assert name
- value = ''
- for i, c in enumerate(name):
- if c.isspace():
- value = name[i:].lstrip()
- name = name[:i]
- break
- return Define(token.start, token.end, name, value)
- if name.startswith('if') and name[2:3].isspace():
- condition = name[3:].strip()
- if condition.startswith('0') or condition.startswith('(0)'):
- self._SkipIf0Blocks()
- return None
-
- def _GetTokensUpTo(self, expected_token_type, expected_token):
- return self._GetVarTokensUpTo(expected_token_type, expected_token)[0]
-
- def _GetVarTokensUpTo(self, expected_token_type, *expected_tokens):
- last_token = self._GetNextToken()
- tokens = []
- while (last_token.token_type != expected_token_type or
- last_token.name not in expected_tokens):
- tokens.append(last_token)
- last_token = self._GetNextToken()
- return tokens, last_token
-
- # Same as _GetVarTokensUpTo, but skips over '<...>' which could contain an
- # expected token.
- def _GetVarTokensUpToIgnoringTemplates(self, expected_token_type,
- *expected_tokens):
- last_token = self._GetNextToken()
- tokens = []
- nesting = 0
- while (nesting > 0 or
- last_token.token_type != expected_token_type or
- last_token.name not in expected_tokens):
- tokens.append(last_token)
- last_token = self._GetNextToken()
- if last_token.name == '<':
- nesting += 1
- elif last_token.name == '>':
- nesting -= 1
- return tokens, last_token
-
- # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary.
- def _IgnoreUpTo(self, token_type, token):
- unused_tokens = self._GetTokensUpTo(token_type, token)
-
- def _SkipIf0Blocks(self):
- count = 1
- while 1:
- token = self._GetNextToken()
- if token.token_type != tokenize.PREPROCESSOR:
- continue
-
- name = token.name[1:].lstrip()
- if name.startswith('endif'):
- count -= 1
- if count == 0:
- break
- elif name.startswith('if'):
- count += 1
-
- def _GetMatchingChar(self, open_paren, close_paren, GetNextToken=None):
- if GetNextToken is None:
- GetNextToken = self._GetNextToken
- # Assumes the current token is open_paren and we will consume
- # and return up to the close_paren.
- count = 1
- token = GetNextToken()
- while 1:
- if token.token_type == tokenize.SYNTAX:
- if token.name == open_paren:
- count += 1
- elif token.name == close_paren:
- count -= 1
- if count == 0:
- break
- yield token
- token = GetNextToken()
- yield token
-
- def _GetParameters(self):
- return self._GetMatchingChar('(', ')')
-
- def GetScope(self):
- return self._GetMatchingChar('{', '}')
-
- def _GetNextToken(self):
- if self.token_queue:
- return self.token_queue.pop()
- try:
- return next(self.tokens)
- except StopIteration:
- return
-
- def _AddBackToken(self, token):
- if token.whence == tokenize.WHENCE_STREAM:
- token.whence = tokenize.WHENCE_QUEUE
- self.token_queue.insert(0, token)
+ def __init__(self, token_stream, filename, in_class='', visibility=None,
+ namespace_stack=[]):
+ self.tokens = token_stream
+ self.filename = filename
+ # TODO(nnorwitz): use a better data structure (deque) for the queue.
+ # Switching directions of the "queue" improved perf by about 25%.
+ # Using a deque should be even better since we access from both sides.
+ self.token_queue = []
+ self.namespace_stack = namespace_stack[:]
+ self.in_class = in_class
+ if in_class is None:
+ self.in_class_name_only = None
+ else:
+ self.in_class_name_only = in_class.split('::')[-1]
+ self.visibility = visibility
+ self.in_function = False
+ self.current_token = None
+ # Keep the state whether we are currently handling a typedef or not.
+ self._handling_typedef = False
+
+ self.converter = TypeConverter(self.namespace_stack)
+
+ def HandleError(self, msg, token):
+ printable_queue = list(reversed(self.token_queue[-20:]))
+ sys.stderr.write('Got %s in %s @ %s %s\n' %
+ (msg, self.filename, token, printable_queue))
+
+ def Generate(self):
+ while 1:
+ token = self._GetNextToken()
+ if not token:
+ break
+
+ # Get the next token.
+ self.current_token = token
+
+ # Dispatch on the next token type.
+ if token.token_type == _INTERNAL_TOKEN:
+ if token.name == _NAMESPACE_POP:
+ self.namespace_stack.pop()
+ continue
+
+ try:
+ result = self._GenerateOne(token)
+ if result is not None:
+ yield result
+ except:
+ self.HandleError('exception', token)
+ raise
+
+ def _CreateVariable(self, pos_token, name, type_name, type_modifiers,
+ ref_pointer_name_seq, templated_types, value=None):
+ reference = '&' in ref_pointer_name_seq
+ pointer = '*' in ref_pointer_name_seq
+ array = '[' in ref_pointer_name_seq
+ var_type = Type(pos_token.start, pos_token.end, type_name,
+ templated_types, type_modifiers,
+ reference, pointer, array)
+ return VariableDeclaration(pos_token.start, pos_token.end,
+ name, var_type, value, self.namespace_stack)
+
+ def _GenerateOne(self, token):
+ if token.token_type == tokenize.NAME:
+ if (keywords.IsKeyword(token.name) and
+ not keywords.IsBuiltinType(token.name)):
+ if token.name == 'enum':
+ # Pop the next token and only put it back if it's not
+ # 'class'. This allows us to support the two-token
+ # 'enum class' keyword as if it were simply 'enum'.
+ next = self._GetNextToken()
+ if next.name != 'class':
+ self._AddBackToken(next)
+
+ method = getattr(self, 'handle_' + token.name)
+ return method()
+ elif token.name == self.in_class_name_only:
+ # The token name is the same as the class, must be a ctor if
+ # there is a paren. Otherwise, it's the return type.
+ # Peek ahead to get the next token to figure out which.
+ next = self._GetNextToken()
+ self._AddBackToken(next)
+ if next.token_type == tokenize.SYNTAX and next.name == '(':
+ return self._GetMethod([token], FUNCTION_CTOR, None, True)
+ # Fall through--handle like any other method.
+
+ # Handle data or function declaration/definition.
+ syntax = tokenize.SYNTAX
+ temp_tokens, last_token = \
+ self._GetVarTokensUpToIgnoringTemplates(syntax,
+ '(', ';', '{', '[')
+ temp_tokens.insert(0, token)
+ if last_token.name == '(':
+ # If there is an assignment before the paren,
+ # this is an expression, not a method.
+ expr = bool([e for e in temp_tokens if e.name == '='])
+ if expr:
+ new_temp = self._GetTokensUpTo(tokenize.SYNTAX, ';')
+ temp_tokens.append(last_token)
+ temp_tokens.extend(new_temp)
+ last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0)
+
+ if last_token.name == '[':
+ # Handle array, this isn't a method, unless it's an operator.
+ # TODO(nnorwitz): keep the size somewhere.
+ # unused_size = self._GetTokensUpTo(tokenize.SYNTAX, ']')
+ temp_tokens.append(last_token)
+ if temp_tokens[-2].name == 'operator':
+ temp_tokens.append(self._GetNextToken())
else:
- assert token.whence == tokenize.WHENCE_QUEUE, token
- self.token_queue.append(token)
-
- def _AddBackTokens(self, tokens):
- if tokens:
- if tokens[-1].whence == tokenize.WHENCE_STREAM:
- for token in tokens:
- token.whence = tokenize.WHENCE_QUEUE
- self.token_queue[:0] = reversed(tokens)
- else:
- assert tokens[-1].whence == tokenize.WHENCE_QUEUE, tokens
- self.token_queue.extend(reversed(tokens))
-
- def GetName(self, seq=None):
- """Returns ([tokens], next_token_info)."""
- GetNextToken = self._GetNextToken
- if seq is not None:
- it = iter(seq)
- GetNextToken = lambda: next(it)
- next_token = GetNextToken()
- tokens = []
- last_token_was_name = False
- while (next_token.token_type == tokenize.NAME or
- (next_token.token_type == tokenize.SYNTAX and
- next_token.name in ('::', '<'))):
- # Two NAMEs in a row means the identifier should terminate.
- # It's probably some sort of variable declaration.
- if last_token_was_name and next_token.token_type == tokenize.NAME:
- break
- last_token_was_name = next_token.token_type == tokenize.NAME
- tokens.append(next_token)
- # Handle templated names.
- if next_token.name == '<':
- tokens.extend(self._GetMatchingChar('<', '>', GetNextToken))
- last_token_was_name = True
- next_token = GetNextToken()
- return tokens, next_token
-
- def GetMethod(self, modifiers, templated_types):
- return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
- assert len(return_type_and_name) >= 1
- return self._GetMethod(return_type_and_name, modifiers, templated_types,
- False)
-
- def _GetMethod(self, return_type_and_name, modifiers, templated_types,
- get_paren):
- template_portion = None
- if get_paren:
- token = self._GetNextToken()
- assert token.token_type == tokenize.SYNTAX, token
- if token.name == '<':
- # Handle templatized dtors.
- template_portion = [token]
- template_portion.extend(self._GetMatchingChar('<', '>'))
- token = self._GetNextToken()
- assert token.token_type == tokenize.SYNTAX, token
- assert token.name == '(', token
-
- name = return_type_and_name.pop()
- # Handle templatized ctors.
- if name.name == '>':
- index = 1
- while return_type_and_name[index].name != '<':
- index += 1
- template_portion = return_type_and_name[index:] + [name]
- del return_type_and_name[index:]
- name = return_type_and_name.pop()
- elif name.name == ']':
- rt = return_type_and_name
- assert rt[-1].name == '[', return_type_and_name
- assert rt[-2].name == 'operator', return_type_and_name
- name_seq = return_type_and_name[-2:]
- del return_type_and_name[-2:]
- name = tokenize.Token(tokenize.NAME, 'operator[]',
- name_seq[0].start, name.end)
- # Get the open paren so _GetParameters() below works.
- unused_open_paren = self._GetNextToken()
-
- # TODO(nnorwitz): store template_portion.
- return_type = return_type_and_name
- indices = name
- if return_type:
- indices = return_type[0]
-
- # Force ctor for templatized ctors.
- if name.name == self.in_class and not modifiers:
- modifiers |= FUNCTION_CTOR
- parameters = list(self._GetParameters())
- del parameters[-1] # Remove trailing ')'.
-
- # Handling operator() is especially weird.
- if name.name == 'operator' and not parameters:
- token = self._GetNextToken()
- assert token.name == '(', token
- parameters = list(self._GetParameters())
- del parameters[-1] # Remove trailing ')'.
-
+ temp_tokens2, last_token = \
+ self._GetVarTokensUpTo(tokenize.SYNTAX, ';')
+ temp_tokens.extend(temp_tokens2)
+
+ if last_token.name == ';':
+ # Handle data, this isn't a method.
+ parts = self.converter.DeclarationToParts(temp_tokens, True)
+ (name, type_name, templated_types, modifiers, default,
+ unused_other_tokens) = parts
+
+ t0 = temp_tokens[0]
+ names = [t.name for t in temp_tokens]
+ if templated_types:
+ start, end = self.converter.GetTemplateIndices(names)
+ names = names[:start] + names[end:]
+ default = ''.join([t.name for t in default])
+ return self._CreateVariable(t0, name, type_name, modifiers,
+ names, templated_types, default)
+ if last_token.name == '{':
+ self._AddBackTokens(temp_tokens[1:])
+ self._AddBackToken(last_token)
+ method_name = temp_tokens[0].name
+ method = getattr(self, 'handle_' + method_name, None)
+ if not method:
+ # Must be declaring a variable.
+ # TODO(nnorwitz): handle the declaration.
+ return None
+ return method()
+ return self._GetMethod(temp_tokens, 0, None, False)
+ elif token.token_type == tokenize.SYNTAX:
+ if token.name == '~' and self.in_class:
+ # Must be a dtor (probably not in method body).
+ token = self._GetNextToken()
+ # self.in_class can contain A::Name, but the dtor will only
+ # be Name. Make sure to compare against the right value.
+ if (token.token_type == tokenize.NAME and
+ token.name == self.in_class_name_only):
+ return self._GetMethod([token], FUNCTION_DTOR, None, True)
+ # TODO(nnorwitz): handle a lot more syntax.
+ elif token.token_type == tokenize.PREPROCESSOR:
+ # TODO(nnorwitz): handle more preprocessor directives.
+ # token starts with a #, so remove it and strip whitespace.
+ name = token.name[1:].lstrip()
+ if name.startswith('include'):
+ # Remove "include".
+ name = name[7:].strip()
+ assert name
+ # Handle #include \<newline> "header-on-second-line.h".
+ if name.startswith('\\'):
+ name = name[1:].strip()
+ assert name[0] in '<"', token
+ assert name[-1] in '>"', token
+ system = name[0] == '<'
+ filename = name[1:-1]
+ return Include(token.start, token.end, filename, system)
+ if name.startswith('define'):
+ # Remove "define".
+ name = name[6:].strip()
+ assert name
+ value = ''
+ for i, c in enumerate(name):
+ if c.isspace():
+ value = name[i:].lstrip()
+ name = name[:i]
+ break
+ return Define(token.start, token.end, name, value)
+ if name.startswith('if') and name[2:3].isspace():
+ condition = name[3:].strip()
+ if condition.startswith('0') or condition.startswith('(0)'):
+ self._SkipIf0Blocks()
+ return None
+
+ def _GetTokensUpTo(self, expected_token_type, expected_token):
+ return self._GetVarTokensUpTo(expected_token_type, expected_token)[0]
+
+ def _GetVarTokensUpTo(self, expected_token_type, *expected_tokens):
+ last_token = self._GetNextToken()
+ tokens = []
+ while (last_token.token_type != expected_token_type or
+ last_token.name not in expected_tokens):
+ tokens.append(last_token)
+ last_token = self._GetNextToken()
+ return tokens, last_token
+
+ # Same as _GetVarTokensUpTo, but skips over '<...>' which could contain an
+ # expected token.
+ def _GetVarTokensUpToIgnoringTemplates(self, expected_token_type,
+ *expected_tokens):
+ last_token = self._GetNextToken()
+ tokens = []
+ nesting = 0
+ while (nesting > 0 or
+ last_token.token_type != expected_token_type or
+ last_token.name not in expected_tokens):
+ tokens.append(last_token)
+ last_token = self._GetNextToken()
+ if last_token.name == '<':
+ nesting += 1
+ elif last_token.name == '>':
+ nesting -= 1
+ return tokens, last_token
+
+ # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necessary.
+ def _IgnoreUpTo(self, token_type, token):
+ unused_tokens = self._GetTokensUpTo(token_type, token)
+
+ def _SkipIf0Blocks(self):
+ count = 1
+ while 1:
+ token = self._GetNextToken()
+ if token.token_type != tokenize.PREPROCESSOR:
+ continue
+
+ name = token.name[1:].lstrip()
+ if name.startswith('endif'):
+ count -= 1
+ if count == 0:
+ break
+ elif name.startswith('if'):
+ count += 1
+
+ def _GetMatchingChar(self, open_paren, close_paren, GetNextToken=None):
+ if GetNextToken is None:
+ GetNextToken = self._GetNextToken
+ # Assumes the current token is open_paren and we will consume
+ # and return up to the close_paren.
+ count = 1
+ token = GetNextToken()
+ while 1:
+ if token.token_type == tokenize.SYNTAX:
+ if token.name == open_paren:
+ count += 1
+ elif token.name == close_paren:
+ count -= 1
+ if count == 0:
+ break
+ yield token
+ token = GetNextToken()
+ yield token
+
+ def _GetParameters(self):
+ return self._GetMatchingChar('(', ')')
+
+ def GetScope(self):
+ return self._GetMatchingChar('{', '}')
+
+ def _GetNextToken(self):
+ if self.token_queue:
+ return self.token_queue.pop()
+ try:
+ return next(self.tokens)
+ except StopIteration:
+ return
+
+ def _AddBackToken(self, token):
+ if token.whence == tokenize.WHENCE_STREAM:
+ token.whence = tokenize.WHENCE_QUEUE
+ self.token_queue.insert(0, token)
+ else:
+ assert token.whence == tokenize.WHENCE_QUEUE, token
+ self.token_queue.append(token)
+
+ def _AddBackTokens(self, tokens):
+ if tokens:
+ if tokens[-1].whence == tokenize.WHENCE_STREAM:
+ for token in tokens:
+ token.whence = tokenize.WHENCE_QUEUE
+ self.token_queue[:0] = reversed(tokens)
+ else:
+ assert tokens[-1].whence == tokenize.WHENCE_QUEUE, tokens
+ self.token_queue.extend(reversed(tokens))
+
+ def GetName(self, seq=None):
+ """Returns ([tokens], next_token_info)."""
+ GetNextToken = self._GetNextToken
+ if seq is not None:
+ it = iter(seq)
+ GetNextToken = lambda: next(it)
+ next_token = GetNextToken()
+ tokens = []
+ last_token_was_name = False
+ while (next_token.token_type == tokenize.NAME or
+ (next_token.token_type == tokenize.SYNTAX and
+ next_token.name in ('::', '<'))):
+ # Two NAMEs in a row means the identifier should terminate.
+ # It's probably some sort of variable declaration.
+ if last_token_was_name and next_token.token_type == tokenize.NAME:
+ break
+ last_token_was_name = next_token.token_type == tokenize.NAME
+ tokens.append(next_token)
+ # Handle templated names.
+ if next_token.name == '<':
+ tokens.extend(self._GetMatchingChar('<', '>', GetNextToken))
+ last_token_was_name = True
+ next_token = GetNextToken()
+ return tokens, next_token
+
+ def GetMethod(self, modifiers, templated_types):
+ return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
+ assert len(return_type_and_name) >= 1
+ return self._GetMethod(return_type_and_name, modifiers, templated_types,
+ False)
+
+ def _GetMethod(self, return_type_and_name, modifiers, templated_types,
+ get_paren):
+ template_portion = None
+ if get_paren:
+ token = self._GetNextToken()
+ assert token.token_type == tokenize.SYNTAX, token
+ if token.name == '<':
+ # Handle templatized dtors.
+ template_portion = [token]
+ template_portion.extend(self._GetMatchingChar('<', '>'))
+ token = self._GetNextToken()
+ assert token.token_type == tokenize.SYNTAX, token
+ assert token.name == '(', token
+
+ name = return_type_and_name.pop()
+ # Handle templatized ctors.
+ if name.name == '>':
+ index = 1
+ while return_type_and_name[index].name != '<':
+ index += 1
+ template_portion = return_type_and_name[index:] + [name]
+ del return_type_and_name[index:]
+ name = return_type_and_name.pop()
+ elif name.name == ']':
+ rt = return_type_and_name
+ assert rt[-1].name == '[', return_type_and_name
+ assert rt[-2].name == 'operator', return_type_and_name
+ name_seq = return_type_and_name[-2:]
+ del return_type_and_name[-2:]
+ name = tokenize.Token(tokenize.NAME, 'operator[]',
+ name_seq[0].start, name.end)
+ # Get the open paren so _GetParameters() below works.
+ unused_open_paren = self._GetNextToken()
+
+ # TODO(nnorwitz): store template_portion.
+ return_type = return_type_and_name
+ indices = name
+ if return_type:
+ indices = return_type[0]
+
+ # Force ctor for templatized ctors.
+ if name.name == self.in_class and not modifiers:
+ modifiers |= FUNCTION_CTOR
+ parameters = list(self._GetParameters())
+ del parameters[-1] # Remove trailing ')'.
+
+ # Handling operator() is especially weird.
+ if name.name == 'operator' and not parameters:
+ token = self._GetNextToken()
+ assert token.name == '(', token
+ parameters = list(self._GetParameters())
+ del parameters[-1] # Remove trailing ')'.
+
+ token = self._GetNextToken()
+ while token.token_type == tokenize.NAME:
+ modifier_token = token
+ token = self._GetNextToken()
+ if modifier_token.name == 'const':
+ modifiers |= FUNCTION_CONST
+ elif modifier_token.name == '__attribute__':
+ # TODO(nnorwitz): handle more __attribute__ details.
+ modifiers |= FUNCTION_ATTRIBUTE
+ assert token.name == '(', token
+ # Consume everything between the (parens).
+ unused_tokens = list(self._GetMatchingChar('(', ')'))
+ token = self._GetNextToken()
+ elif modifier_token.name == 'throw':
+ modifiers |= FUNCTION_THROW
+ assert token.name == '(', token
+ # Consume everything between the (parens).
+ unused_tokens = list(self._GetMatchingChar('(', ')'))
+ token = self._GetNextToken()
+ elif modifier_token.name == 'override':
+ modifiers |= FUNCTION_OVERRIDE
+ elif modifier_token.name == modifier_token.name.upper():
+ # HACK(nnorwitz): assume that all upper-case names
+ # are some macro we aren't expanding.
+ modifiers |= FUNCTION_UNKNOWN_ANNOTATION
+ else:
+ self.HandleError('unexpected token', modifier_token)
+
+ assert token.token_type == tokenize.SYNTAX, token
+ # Handle ctor initializers.
+ if token.name == ':':
+ # TODO(nnorwitz): anything else to handle for initializer list?
+ while token.name != ';' and token.name != '{':
token = self._GetNextToken()
- while token.token_type == tokenize.NAME:
- modifier_token = token
- token = self._GetNextToken()
- if modifier_token.name == 'const':
- modifiers |= FUNCTION_CONST
- elif modifier_token.name == '__attribute__':
- # TODO(nnorwitz): handle more __attribute__ details.
- modifiers |= FUNCTION_ATTRIBUTE
- assert token.name == '(', token
- # Consume everything between the (parens).
- unused_tokens = list(self._GetMatchingChar('(', ')'))
- token = self._GetNextToken()
- elif modifier_token.name == 'throw':
- modifiers |= FUNCTION_THROW
- assert token.name == '(', token
- # Consume everything between the (parens).
- unused_tokens = list(self._GetMatchingChar('(', ')'))
- token = self._GetNextToken()
- elif modifier_token.name == 'override':
- modifiers |= FUNCTION_OVERRIDE
- elif modifier_token.name == modifier_token.name.upper():
- # HACK(nnorwitz): assume that all upper-case names
- # are some macro we aren't expanding.
- modifiers |= FUNCTION_UNKNOWN_ANNOTATION
- else:
- self.HandleError('unexpected token', modifier_token)
+ # Handle pointer to functions that are really data but look
+ # like method declarations.
+ if token.name == '(':
+ if parameters[0].name == '*':
+ # name contains the return type.
+ name = parameters.pop()
+ # parameters contains the name of the data.
+ modifiers = [p.name for p in parameters]
+ # Already at the ( to open the parameter list.
+ function_parameters = list(self._GetMatchingChar('(', ')'))
+ del function_parameters[-1] # Remove trailing ')'.
+ # TODO(nnorwitz): store the function_parameters.
+ token = self._GetNextToken()
assert token.token_type == tokenize.SYNTAX, token
- # Handle ctor initializers.
- if token.name == ':':
- # TODO(nnorwitz): anything else to handle for initializer list?
- while token.name != ';' and token.name != '{':
- token = self._GetNextToken()
-
- # Handle pointer to functions that are really data but look
- # like method declarations.
- if token.name == '(':
- if parameters[0].name == '*':
- # name contains the return type.
- name = parameters.pop()
- # parameters contains the name of the data.
- modifiers = [p.name for p in parameters]
- # Already at the ( to open the parameter list.
- function_parameters = list(self._GetMatchingChar('(', ')'))
- del function_parameters[-1] # Remove trailing ')'.
- # TODO(nnorwitz): store the function_parameters.
- token = self._GetNextToken()
- assert token.token_type == tokenize.SYNTAX, token
- assert token.name == ';', token
- return self._CreateVariable(indices, name.name, indices.name,
- modifiers, '', None)
- # At this point, we got something like:
- # return_type (type::*name_)(params);
- # This is a data member called name_ that is a function pointer.
- # With this code: void (sq_type::*field_)(string&);
- # We get: name=void return_type=[] parameters=sq_type ... field_
- # TODO(nnorwitz): is return_type always empty?
- # TODO(nnorwitz): this isn't even close to being correct.
- # Just put in something so we don't crash and can move on.
- real_name = parameters[-1]
- modifiers = [p.name for p in self._GetParameters()]
- del modifiers[-1] # Remove trailing ')'.
- return self._CreateVariable(indices, real_name.name, indices.name,
- modifiers, '', None)
-
- if token.name == '{':
- body = list(self.GetScope())
- del body[-1] # Remove trailing '}'.
- else:
- body = None
- if token.name == '=':
- token = self._GetNextToken()
-
- if token.name == 'default' or token.name == 'delete':
- # Ignore explicitly defaulted and deleted special members
- # in C++11.
- token = self._GetNextToken()
- else:
- # Handle pure-virtual declarations.
- assert token.token_type == tokenize.CONSTANT, token
- assert token.name == '0', token
- modifiers |= FUNCTION_PURE_VIRTUAL
- token = self._GetNextToken()
-
- if token.name == '[':
- # TODO(nnorwitz): store tokens and improve parsing.
- # template <typename T, size_t N> char (&ASH(T (&seq)[N]))[N];
- tokens = list(self._GetMatchingChar('[', ']'))
- token = self._GetNextToken()
-
- assert token.name == ';', (token, return_type_and_name, parameters)
-
- # Looks like we got a method, not a function.
- if len(return_type) > 2 and return_type[-1].name == '::':
- return_type, in_class = \
- self._GetReturnTypeAndClassName(return_type)
- return Method(indices.start, indices.end, name.name, in_class,
- return_type, parameters, modifiers, templated_types,
- body, self.namespace_stack)
- return Function(indices.start, indices.end, name.name, return_type,
- parameters, modifiers, templated_types, body,
- self.namespace_stack)
-
- def _GetReturnTypeAndClassName(self, token_seq):
- # Splitting the return type from the class name in a method
- # can be tricky. For example, Return::Type::Is::Hard::To::Find().
- # Where is the return type and where is the class name?
- # The heuristic used is to pull the last name as the class name.
- # This includes all the templated type info.
- # TODO(nnorwitz): if there is only One name like in the
- # example above, punt and assume the last bit is the class name.
-
- # Ignore a :: prefix, if exists so we can find the first real name.
- i = 0
- if token_seq[0].name == '::':
- i = 1
- # Ignore a :: suffix, if exists.
- end = len(token_seq) - 1
- if token_seq[end-1].name == '::':
- end -= 1
-
- # Make a copy of the sequence so we can append a sentinel
- # value. This is required for GetName will has to have some
- # terminating condition beyond the last name.
- seq_copy = token_seq[i:end]
- seq_copy.append(tokenize.Token(tokenize.SYNTAX, '', 0, 0))
- names = []
- while i < end:
- # Iterate through the sequence parsing out each name.
- new_name, next = self.GetName(seq_copy[i:])
- assert new_name, 'Got empty new_name, next=%s' % next
- # We got a pointer or ref. Add it to the name.
- if next and next.token_type == tokenize.SYNTAX:
- new_name.append(next)
- names.append(new_name)
- i += len(new_name)
-
- # Now that we have the names, it's time to undo what we did.
-
- # Remove the sentinel value.
- names[-1].pop()
- # Flatten the token sequence for the return type.
- return_type = [e for seq in names[:-1] for e in seq]
- # The class name is the last name.
- class_name = names[-1]
- return return_type, class_name
-
- def handle_bool(self):
- pass
-
- def handle_char(self):
- pass
-
- def handle_int(self):
- pass
+ assert token.name == ';', token
+ return self._CreateVariable(indices, name.name, indices.name,
+ modifiers, '', None)
+ # At this point, we got something like:
+ # return_type (type::*name_)(params);
+ # This is a data member called name_ that is a function pointer.
+ # With this code: void (sq_type::*field_)(string&);
+ # We get: name=void return_type=[] parameters=sq_type ... field_
+ # TODO(nnorwitz): is return_type always empty?
+ # TODO(nnorwitz): this isn't even close to being correct.
+ # Just put in something so we don't crash and can move on.
+ real_name = parameters[-1]
+ modifiers = [p.name for p in self._GetParameters()]
+ del modifiers[-1] # Remove trailing ')'.
+ return self._CreateVariable(indices, real_name.name, indices.name,
+ modifiers, '', None)
+
+ if token.name == '{':
+ body = list(self.GetScope())
+ del body[-1] # Remove trailing '}'.
+ else:
+ body = None
+ if token.name == '=':
+ token = self._GetNextToken()
- def handle_long(self):
- pass
+ if token.name == 'default' or token.name == 'delete':
+ # Ignore explicitly defaulted and deleted special members
+ # in C++11.
+ token = self._GetNextToken()
+ else:
+ # Handle pure-virtual declarations.
+ assert token.token_type == tokenize.CONSTANT, token
+ assert token.name == '0', token
+ modifiers |= FUNCTION_PURE_VIRTUAL
+ token = self._GetNextToken()
+
+ if token.name == '[':
+ # TODO(nnorwitz): store tokens and improve parsing.
+ # template <typename T, size_t N> char (&ASH(T (&seq)[N]))[N];
+ tokens = list(self._GetMatchingChar('[', ']'))
+ token = self._GetNextToken()
- def handle_short(self):
- pass
+ assert token.name == ';', (token, return_type_and_name, parameters)
+
+ # Looks like we got a method, not a function.
+ if len(return_type) > 2 and return_type[-1].name == '::':
+ return_type, in_class = \
+ self._GetReturnTypeAndClassName(return_type)
+ return Method(indices.start, indices.end, name.name, in_class,
+ return_type, parameters, modifiers, templated_types,
+ body, self.namespace_stack)
+ return Function(indices.start, indices.end, name.name, return_type,
+ parameters, modifiers, templated_types, body,
+ self.namespace_stack)
+
+ def _GetReturnTypeAndClassName(self, token_seq):
+ # Splitting the return type from the class name in a method
+ # can be tricky. For example, Return::Type::Is::Hard::To::Find().
+ # Where is the return type and where is the class name?
+ # The heuristic used is to pull the last name as the class name.
+ # This includes all the templated type info.
+ # TODO(nnorwitz): if there is only One name like in the
+ # example above, punt and assume the last bit is the class name.
+
+ # Ignore a :: prefix, if exists so we can find the first real name.
+ i = 0
+ if token_seq[0].name == '::':
+ i = 1
+ # Ignore a :: suffix, if exists.
+ end = len(token_seq) - 1
+ if token_seq[end-1].name == '::':
+ end -= 1
+
+ # Make a copy of the sequence so we can append a sentinel
+ # value. This is required for GetName will has to have some
+ # terminating condition beyond the last name.
+ seq_copy = token_seq[i:end]
+ seq_copy.append(tokenize.Token(tokenize.SYNTAX, '', 0, 0))
+ names = []
+ while i < end:
+ # Iterate through the sequence parsing out each name.
+ new_name, next = self.GetName(seq_copy[i:])
+ assert new_name, 'Got empty new_name, next=%s' % next
+ # We got a pointer or ref. Add it to the name.
+ if next and next.token_type == tokenize.SYNTAX:
+ new_name.append(next)
+ names.append(new_name)
+ i += len(new_name)
+
+ # Now that we have the names, it's time to undo what we did.
+
+ # Remove the sentinel value.
+ names[-1].pop()
+ # Flatten the token sequence for the return type.
+ return_type = [e for seq in names[:-1] for e in seq]
+ # The class name is the last name.
+ class_name = names[-1]
+ return return_type, class_name
+
+ def handle_bool(self):
+ pass
- def handle_double(self):
- pass
+ def handle_char(self):
+ pass
- def handle_float(self):
- pass
+ def handle_int(self):
+ pass
- def handle_void(self):
- pass
+ def handle_long(self):
+ pass
- def handle_wchar_t(self):
- pass
+ def handle_short(self):
+ pass
- def handle_unsigned(self):
- pass
+ def handle_double(self):
+ pass
- def handle_signed(self):
- pass
+ def handle_float(self):
+ pass
- def _GetNestedType(self, ctor):
- name = None
- name_tokens, token = self.GetName()
- if name_tokens:
- name = ''.join([t.name for t in name_tokens])
-
- # Handle forward declarations.
- if token.token_type == tokenize.SYNTAX and token.name == ';':
- return ctor(token.start, token.end, name, None,
- self.namespace_stack)
-
- if token.token_type == tokenize.NAME and self._handling_typedef:
- self._AddBackToken(token)
- return ctor(token.start, token.end, name, None,
- self.namespace_stack)
-
- # Must be the type declaration.
- fields = list(self._GetMatchingChar('{', '}'))
- del fields[-1] # Remove trailing '}'.
- if token.token_type == tokenize.SYNTAX and token.name == '{':
- next = self._GetNextToken()
- new_type = ctor(token.start, token.end, name, fields,
- self.namespace_stack)
- # A name means this is an anonymous type and the name
- # is the variable declaration.
- if next.token_type != tokenize.NAME:
- return new_type
- name = new_type
- token = next
-
- # Must be variable declaration using the type prefixed with keyword.
- assert token.token_type == tokenize.NAME, token
- return self._CreateVariable(token, token.name, name, [], '', None)
-
- def handle_struct(self):
- # Special case the handling typedef/aliasing of structs here.
- # It would be a pain to handle in the class code.
- name_tokens, var_token = self.GetName()
- if name_tokens:
- next_token = self._GetNextToken()
- is_syntax = (var_token.token_type == tokenize.SYNTAX and
- var_token.name[0] in '*&')
- is_variable = (var_token.token_type == tokenize.NAME and
- next_token.name == ';')
- variable = var_token
- if is_syntax and not is_variable:
- variable = next_token
- temp = self._GetNextToken()
- if temp.token_type == tokenize.SYNTAX and temp.name == '(':
- # Handle methods declared to return a struct.
- t0 = name_tokens[0]
- struct = tokenize.Token(tokenize.NAME, 'struct',
- t0.start-7, t0.start-2)
- type_and_name = [struct]
- type_and_name.extend(name_tokens)
- type_and_name.extend((var_token, next_token))
- return self._GetMethod(type_and_name, 0, None, False)
- assert temp.name == ';', (temp, name_tokens, var_token)
- if is_syntax or (is_variable and not self._handling_typedef):
- modifiers = ['struct']
- type_name = ''.join([t.name for t in name_tokens])
- position = name_tokens[0]
- return self._CreateVariable(position, variable.name, type_name,
- modifiers, var_token.name, None)
- name_tokens.extend((var_token, next_token))
- self._AddBackTokens(name_tokens)
- else:
- self._AddBackToken(var_token)
- return self._GetClass(Struct, VISIBILITY_PUBLIC, None)
+ def handle_void(self):
+ pass
- def handle_union(self):
- return self._GetNestedType(Union)
+ def handle_wchar_t(self):
+ pass
- def handle_enum(self):
- return self._GetNestedType(Enum)
+ def handle_unsigned(self):
+ pass
- def handle_auto(self):
- # TODO(nnorwitz): warn about using auto? Probably not since it
- # will be reclaimed and useful for C++0x.
- pass
+ def handle_signed(self):
+ pass
- def handle_register(self):
- pass
+ def _GetNestedType(self, ctor):
+ name = None
+ name_tokens, token = self.GetName()
+ if name_tokens:
+ name = ''.join([t.name for t in name_tokens])
+
+ # Handle forward declarations.
+ if token.token_type == tokenize.SYNTAX and token.name == ';':
+ return ctor(token.start, token.end, name, None,
+ self.namespace_stack)
+
+ if token.token_type == tokenize.NAME and self._handling_typedef:
+ self._AddBackToken(token)
+ return ctor(token.start, token.end, name, None,
+ self.namespace_stack)
+
+ # Must be the type declaration.
+ fields = list(self._GetMatchingChar('{', '}'))
+ del fields[-1] # Remove trailing '}'.
+ if token.token_type == tokenize.SYNTAX and token.name == '{':
+ next = self._GetNextToken()
+ new_type = ctor(token.start, token.end, name, fields,
+ self.namespace_stack)
+ # A name means this is an anonymous type and the name
+ # is the variable declaration.
+ if next.token_type != tokenize.NAME:
+ return new_type
+ name = new_type
+ token = next
+
+ # Must be variable declaration using the type prefixed with keyword.
+ assert token.token_type == tokenize.NAME, token
+ return self._CreateVariable(token, token.name, name, [], '', None)
+
+ def handle_struct(self):
+ # Special case the handling typedef/aliasing of structs here.
+ # It would be a pain to handle in the class code.
+ name_tokens, var_token = self.GetName()
+ if name_tokens:
+ next_token = self._GetNextToken()
+ is_syntax = (var_token.token_type == tokenize.SYNTAX and
+ var_token.name[0] in '*&')
+ is_variable = (var_token.token_type == tokenize.NAME and
+ next_token.name == ';')
+ variable = var_token
+ if is_syntax and not is_variable:
+ variable = next_token
+ temp = self._GetNextToken()
+ if temp.token_type == tokenize.SYNTAX and temp.name == '(':
+ # Handle methods declared to return a struct.
+ t0 = name_tokens[0]
+ struct = tokenize.Token(tokenize.NAME, 'struct',
+ t0.start-7, t0.start-2)
+ type_and_name = [struct]
+ type_and_name.extend(name_tokens)
+ type_and_name.extend((var_token, next_token))
+ return self._GetMethod(type_and_name, 0, None, False)
+ assert temp.name == ';', (temp, name_tokens, var_token)
+ if is_syntax or (is_variable and not self._handling_typedef):
+ modifiers = ['struct']
+ type_name = ''.join([t.name for t in name_tokens])
+ position = name_tokens[0]
+ return self._CreateVariable(position, variable.name, type_name,
+ modifiers, var_token.name, None)
+ name_tokens.extend((var_token, next_token))
+ self._AddBackTokens(name_tokens)
+ else:
+ self._AddBackToken(var_token)
+ return self._GetClass(Struct, VISIBILITY_PUBLIC, None)
+
+ def handle_union(self):
+ return self._GetNestedType(Union)
+
+ def handle_enum(self):
+ return self._GetNestedType(Enum)
+
+ def handle_auto(self):
+ # TODO(nnorwitz): warn about using auto? Probably not since it
+ # will be reclaimed and useful for C++0x.
+ pass
- def handle_const(self):
- pass
+ def handle_register(self):
+ pass
- def handle_inline(self):
- pass
+ def handle_const(self):
+ pass
- def handle_extern(self):
- pass
+ def handle_inline(self):
+ pass
- def handle_static(self):
- pass
+ def handle_extern(self):
+ pass
- def handle_virtual(self):
- # What follows must be a method.
- token = token2 = self._GetNextToken()
- if token.name == 'inline':
- # HACK(nnorwitz): handle inline dtors by ignoring 'inline'.
- token2 = self._GetNextToken()
- if token2.token_type == tokenize.SYNTAX and token2.name == '~':
- return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None)
- assert token.token_type == tokenize.NAME or token.name == '::', token
- return_type_and_name, _ = self._GetVarTokensUpToIgnoringTemplates(
- tokenize.SYNTAX, '(') # )
- return_type_and_name.insert(0, token)
- if token2 is not token:
- return_type_and_name.insert(1, token2)
- return self._GetMethod(return_type_and_name, FUNCTION_VIRTUAL,
- None, False)
-
- def handle_volatile(self):
- pass
+ def handle_static(self):
+ pass
- def handle_mutable(self):
- pass
+ def handle_virtual(self):
+ # What follows must be a method.
+ token = token2 = self._GetNextToken()
+ if token.name == 'inline':
+ # HACK(nnorwitz): handle inline dtors by ignoring 'inline'.
+ token2 = self._GetNextToken()
+ if token2.token_type == tokenize.SYNTAX and token2.name == '~':
+ return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None)
+ assert token.token_type == tokenize.NAME or token.name == '::', token
+ return_type_and_name, _ = self._GetVarTokensUpToIgnoringTemplates(
+ tokenize.SYNTAX, '(') # )
+ return_type_and_name.insert(0, token)
+ if token2 is not token:
+ return_type_and_name.insert(1, token2)
+ return self._GetMethod(return_type_and_name, FUNCTION_VIRTUAL,
+ None, False)
+
+ def handle_volatile(self):
+ pass
- def handle_public(self):
- assert self.in_class
- self.visibility = VISIBILITY_PUBLIC
+ def handle_mutable(self):
+ pass
- def handle_protected(self):
- assert self.in_class
- self.visibility = VISIBILITY_PROTECTED
+ def handle_public(self):
+ assert self.in_class
+ self.visibility = VISIBILITY_PUBLIC
- def handle_private(self):
- assert self.in_class
- self.visibility = VISIBILITY_PRIVATE
+ def handle_protected(self):
+ assert self.in_class
+ self.visibility = VISIBILITY_PROTECTED
- def handle_friend(self):
- tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
- assert tokens
- t0 = tokens[0]
- return Friend(t0.start, t0.end, tokens, self.namespace_stack)
+ def handle_private(self):
+ assert self.in_class
+ self.visibility = VISIBILITY_PRIVATE
- def handle_static_cast(self):
- pass
+ def handle_friend(self):
+ tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
+ assert tokens
+ t0 = tokens[0]
+ return Friend(t0.start, t0.end, tokens, self.namespace_stack)
- def handle_const_cast(self):
- pass
+ def handle_static_cast(self):
+ pass
- def handle_dynamic_cast(self):
- pass
+ def handle_const_cast(self):
+ pass
- def handle_reinterpret_cast(self):
- pass
+ def handle_dynamic_cast(self):
+ pass
- def handle_new(self):
- pass
+ def handle_reinterpret_cast(self):
+ pass
- def handle_delete(self):
- tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
- assert tokens
- return Delete(tokens[0].start, tokens[0].end, tokens)
+ def handle_new(self):
+ pass
- def handle_typedef(self):
- token = self._GetNextToken()
- if (token.token_type == tokenize.NAME and
- keywords.IsKeyword(token.name)):
- # Token must be struct/enum/union/class.
- method = getattr(self, 'handle_' + token.name)
- self._handling_typedef = True
- tokens = [method()]
- self._handling_typedef = False
+ def handle_delete(self):
+ tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
+ assert tokens
+ return Delete(tokens[0].start, tokens[0].end, tokens)
+
+ def handle_typedef(self):
+ token = self._GetNextToken()
+ if (token.token_type == tokenize.NAME and
+ keywords.IsKeyword(token.name)):
+ # Token must be struct/enum/union/class.
+ method = getattr(self, 'handle_' + token.name)
+ self._handling_typedef = True
+ tokens = [method()]
+ self._handling_typedef = False
+ else:
+ tokens = [token]
+
+ # Get the remainder of the typedef up to the semi-colon.
+ tokens.extend(self._GetTokensUpTo(tokenize.SYNTAX, ';'))
+
+ # TODO(nnorwitz): clean all this up.
+ assert tokens
+ name = tokens.pop()
+ indices = name
+ if tokens:
+ indices = tokens[0]
+ if not indices:
+ indices = token
+ if name.name == ')':
+ # HACK(nnorwitz): Handle pointers to functions "properly".
+ if (len(tokens) >= 4 and
+ tokens[1].name == '(' and tokens[2].name == '*'):
+ tokens.append(name)
+ name = tokens[3]
+ elif name.name == ']':
+ # HACK(nnorwitz): Handle arrays properly.
+ if len(tokens) >= 2:
+ tokens.append(name)
+ name = tokens[1]
+ new_type = tokens
+ if tokens and isinstance(tokens[0], tokenize.Token):
+ new_type = self.converter.ToType(tokens)[0]
+ return Typedef(indices.start, indices.end, name.name,
+ new_type, self.namespace_stack)
+
+ def handle_typeid(self):
+ pass # Not needed yet.
+
+ def handle_typename(self):
+ pass # Not needed yet.
+
+ def _GetTemplatedTypes(self):
+ result = collections.OrderedDict()
+ tokens = list(self._GetMatchingChar('<', '>'))
+ len_tokens = len(tokens) - 1 # Ignore trailing '>'.
+ i = 0
+ while i < len_tokens:
+ key = tokens[i].name
+ i += 1
+ if keywords.IsKeyword(key) or key == ',':
+ continue
+ type_name = default = None
+ if i < len_tokens:
+ i += 1
+ if tokens[i-1].name == '=':
+ assert i < len_tokens, '%s %s' % (i, tokens)
+ default, unused_next_token = self.GetName(tokens[i:])
+ i += len(default)
else:
- tokens = [token]
-
- # Get the remainder of the typedef up to the semi-colon.
- tokens.extend(self._GetTokensUpTo(tokenize.SYNTAX, ';'))
-
- # TODO(nnorwitz): clean all this up.
- assert tokens
- name = tokens.pop()
- indices = name
- if tokens:
- indices = tokens[0]
- if not indices:
- indices = token
- if name.name == ')':
- # HACK(nnorwitz): Handle pointers to functions "properly".
- if (len(tokens) >= 4 and
- tokens[1].name == '(' and tokens[2].name == '*'):
- tokens.append(name)
- name = tokens[3]
- elif name.name == ']':
- # HACK(nnorwitz): Handle arrays properly.
- if len(tokens) >= 2:
- tokens.append(name)
- name = tokens[1]
- new_type = tokens
- if tokens and isinstance(tokens[0], tokenize.Token):
- new_type = self.converter.ToType(tokens)[0]
- return Typedef(indices.start, indices.end, name.name,
- new_type, self.namespace_stack)
-
- def handle_typeid(self):
- pass # Not needed yet.
-
- def handle_typename(self):
- pass # Not needed yet.
-
- def _GetTemplatedTypes(self):
- result = {}
- tokens = list(self._GetMatchingChar('<', '>'))
- len_tokens = len(tokens) - 1 # Ignore trailing '>'.
- i = 0
- while i < len_tokens:
- key = tokens[i].name
- i += 1
- if keywords.IsKeyword(key) or key == ',':
- continue
- type_name = default = None
- if i < len_tokens:
- i += 1
- if tokens[i-1].name == '=':
- assert i < len_tokens, '%s %s' % (i, tokens)
- default, unused_next_token = self.GetName(tokens[i:])
- i += len(default)
- else:
- if tokens[i-1].name != ',':
- # We got something like: Type variable.
- # Re-adjust the key (variable) and type_name (Type).
- key = tokens[i-1].name
- type_name = tokens[i-2]
-
- result[key] = (type_name, default)
- return result
-
- def handle_template(self):
- token = self._GetNextToken()
- assert token.token_type == tokenize.SYNTAX, token
- assert token.name == '<', token
- templated_types = self._GetTemplatedTypes()
- # TODO(nnorwitz): for now, just ignore the template params.
- token = self._GetNextToken()
- if token.token_type == tokenize.NAME:
- if token.name == 'class':
- return self._GetClass(Class, VISIBILITY_PRIVATE, templated_types)
- elif token.name == 'struct':
- return self._GetClass(Struct, VISIBILITY_PUBLIC, templated_types)
- elif token.name == 'friend':
- return self.handle_friend()
+ if tokens[i-1].name != ',':
+ # We got something like: Type variable.
+ # Re-adjust the key (variable) and type_name (Type).
+ key = tokens[i-1].name
+ type_name = tokens[i-2]
+
+ result[key] = (type_name, default)
+ return result
+
+ def handle_template(self):
+ token = self._GetNextToken()
+ assert token.token_type == tokenize.SYNTAX, token
+ assert token.name == '<', token
+ templated_types = self._GetTemplatedTypes()
+ # TODO(nnorwitz): for now, just ignore the template params.
+ token = self._GetNextToken()
+ if token.token_type == tokenize.NAME:
+ if token.name == 'class':
+ return self._GetClass(Class, VISIBILITY_PRIVATE, templated_types)
+ elif token.name == 'struct':
+ return self._GetClass(Struct, VISIBILITY_PUBLIC, templated_types)
+ elif token.name == 'friend':
+ return self.handle_friend()
+ self._AddBackToken(token)
+ tokens, last = self._GetVarTokensUpTo(tokenize.SYNTAX, '(', ';')
+ tokens.append(last)
+ self._AddBackTokens(tokens)
+ if last.name == '(':
+ return self.GetMethod(FUNCTION_NONE, templated_types)
+ # Must be a variable definition.
+ return None
+
+ def handle_true(self):
+ pass # Nothing to do.
+
+ def handle_false(self):
+ pass # Nothing to do.
+
+ def handle_asm(self):
+ pass # Not needed yet.
+
+ def handle_class(self):
+ return self._GetClass(Class, VISIBILITY_PRIVATE, None)
+
+ def _GetBases(self):
+ # Get base classes.
+ bases = []
+ while 1:
+ token = self._GetNextToken()
+ assert token.token_type == tokenize.NAME, token
+ # TODO(nnorwitz): store kind of inheritance...maybe.
+ if token.name not in ('public', 'protected', 'private'):
+ # If inheritance type is not specified, it is private.
+ # Just put the token back so we can form a name.
+ # TODO(nnorwitz): it would be good to warn about this.
self._AddBackToken(token)
- tokens, last = self._GetVarTokensUpTo(tokenize.SYNTAX, '(', ';')
- tokens.append(last)
- self._AddBackTokens(tokens)
- if last.name == '(':
- return self.GetMethod(FUNCTION_NONE, templated_types)
- # Must be a variable definition.
- return None
-
- def handle_true(self):
- pass # Nothing to do.
-
- def handle_false(self):
- pass # Nothing to do.
-
- def handle_asm(self):
- pass # Not needed yet.
-
- def handle_class(self):
- return self._GetClass(Class, VISIBILITY_PRIVATE, None)
-
- def _GetBases(self):
- # Get base classes.
- bases = []
- while 1:
- token = self._GetNextToken()
- assert token.token_type == tokenize.NAME, token
- # TODO(nnorwitz): store kind of inheritance...maybe.
- if token.name not in ('public', 'protected', 'private'):
- # If inheritance type is not specified, it is private.
- # Just put the token back so we can form a name.
- # TODO(nnorwitz): it would be good to warn about this.
- self._AddBackToken(token)
- else:
- # Check for virtual inheritance.
- token = self._GetNextToken()
- if token.name != 'virtual':
- self._AddBackToken(token)
- else:
- # TODO(nnorwitz): store that we got virtual for this base.
- pass
- base, next_token = self.GetName()
- bases_ast = self.converter.ToType(base)
- assert len(bases_ast) == 1, bases_ast
- bases.append(bases_ast[0])
- assert next_token.token_type == tokenize.SYNTAX, next_token
- if next_token.name == '{':
- token = next_token
- break
- # Support multiple inheritance.
- assert next_token.name == ',', next_token
- return bases, token
-
- def _GetClass(self, class_type, visibility, templated_types):
- class_name = None
- class_token = self._GetNextToken()
- if class_token.token_type != tokenize.NAME:
- assert class_token.token_type == tokenize.SYNTAX, class_token
- token = class_token
+ else:
+ # Check for virtual inheritance.
+ token = self._GetNextToken()
+ if token.name != 'virtual':
+ self._AddBackToken(token)
else:
- # Skip any macro (e.g. storage class specifiers) after the
- # 'class' keyword.
- next_token = self._GetNextToken()
- if next_token.token_type == tokenize.NAME:
- self._AddBackToken(next_token)
- else:
- self._AddBackTokens([class_token, next_token])
- name_tokens, token = self.GetName()
- class_name = ''.join([t.name for t in name_tokens])
- bases = None
- if token.token_type == tokenize.SYNTAX:
- if token.name == ';':
- # Forward declaration.
- return class_type(class_token.start, class_token.end,
- class_name, None, templated_types, None,
- self.namespace_stack)
- if token.name in '*&':
- # Inline forward declaration. Could be method or data.
- name_token = self._GetNextToken()
- next_token = self._GetNextToken()
- if next_token.name == ';':
- # Handle data
- modifiers = ['class']
- return self._CreateVariable(class_token, name_token.name,
- class_name,
- modifiers, token.name, None)
- else:
- # Assume this is a method.
- tokens = (class_token, token, name_token, next_token)
- self._AddBackTokens(tokens)
- return self.GetMethod(FUNCTION_NONE, None)
- if token.name == ':':
- bases, token = self._GetBases()
-
- body = None
- if token.token_type == tokenize.SYNTAX and token.name == '{':
- assert token.token_type == tokenize.SYNTAX, token
- assert token.name == '{', token
-
- ast = AstBuilder(self.GetScope(), self.filename, class_name,
- visibility, self.namespace_stack)
- body = list(ast.Generate())
-
- if not self._handling_typedef:
- token = self._GetNextToken()
- if token.token_type != tokenize.NAME:
- assert token.token_type == tokenize.SYNTAX, token
- assert token.name == ';', token
- else:
- new_class = class_type(class_token.start, class_token.end,
- class_name, bases, None,
- body, self.namespace_stack)
-
- modifiers = []
- return self._CreateVariable(class_token,
- token.name, new_class,
- modifiers, token.name, None)
+ # TODO(nnorwitz): store that we got virtual for this base.
+ pass
+ base, next_token = self.GetName()
+ bases_ast = self.converter.ToType(base)
+ assert len(bases_ast) == 1, bases_ast
+ bases.append(bases_ast[0])
+ assert next_token.token_type == tokenize.SYNTAX, next_token
+ if next_token.name == '{':
+ token = next_token
+ break
+ # Support multiple inheritance.
+ assert next_token.name == ',', next_token
+ return bases, token
+
+ def _GetClass(self, class_type, visibility, templated_types):
+ class_name = None
+ class_token = self._GetNextToken()
+ if class_token.token_type != tokenize.NAME:
+ assert class_token.token_type == tokenize.SYNTAX, class_token
+ token = class_token
+ else:
+ # Skip any macro (e.g. storage class specifiers) after the
+ # 'class' keyword.
+ next_token = self._GetNextToken()
+ if next_token.token_type == tokenize.NAME:
+ self._AddBackToken(next_token)
+ else:
+ self._AddBackTokens([class_token, next_token])
+ name_tokens, token = self.GetName()
+ class_name = ''.join([t.name for t in name_tokens])
+ bases = None
+ if token.token_type == tokenize.SYNTAX:
+ if token.name == ';':
+ # Forward declaration.
+ return class_type(class_token.start, class_token.end,
+ class_name, None, templated_types, None,
+ self.namespace_stack)
+ if token.name in '*&':
+ # Inline forward declaration. Could be method or data.
+ name_token = self._GetNextToken()
+ next_token = self._GetNextToken()
+ if next_token.name == ';':
+ # Handle data
+ modifiers = ['class']
+ return self._CreateVariable(class_token, name_token.name,
+ class_name,
+ modifiers, token.name, None)
else:
- if not self._handling_typedef:
- self.HandleError('non-typedef token', token)
- self._AddBackToken(token)
-
- return class_type(class_token.start, class_token.end, class_name,
- bases, templated_types, body, self.namespace_stack)
-
- def handle_namespace(self):
+ # Assume this is a method.
+ tokens = (class_token, token, name_token, next_token)
+ self._AddBackTokens(tokens)
+ return self.GetMethod(FUNCTION_NONE, None)
+ if token.name == ':':
+ bases, token = self._GetBases()
+
+ body = None
+ if token.token_type == tokenize.SYNTAX and token.name == '{':
+ assert token.token_type == tokenize.SYNTAX, token
+ assert token.name == '{', token
+
+ ast = AstBuilder(self.GetScope(), self.filename, class_name,
+ visibility, self.namespace_stack)
+ body = list(ast.Generate())
+
+ if not self._handling_typedef:
token = self._GetNextToken()
- # Support anonymous namespaces.
- name = None
- if token.token_type == tokenize.NAME:
- name = token.name
- token = self._GetNextToken()
- self.namespace_stack.append(name)
- assert token.token_type == tokenize.SYNTAX, token
- # Create an internal token that denotes when the namespace is complete.
- internal_token = tokenize.Token(_INTERNAL_TOKEN, _NAMESPACE_POP,
- None, None)
- internal_token.whence = token.whence
- if token.name == '=':
- # TODO(nnorwitz): handle aliasing namespaces.
- name, next_token = self.GetName()
- assert next_token.name == ';', next_token
- self._AddBackToken(internal_token)
+ if token.token_type != tokenize.NAME:
+ assert token.token_type == tokenize.SYNTAX, token
+ assert token.name == ';', token
else:
- assert token.name == '{', token
- tokens = list(self.GetScope())
- # Replace the trailing } with the internal namespace pop token.
- tokens[-1] = internal_token
- # Handle namespace with nothing in it.
- self._AddBackTokens(tokens)
- return None
-
- def handle_using(self):
- tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
- assert tokens
- return Using(tokens[0].start, tokens[0].end, tokens)
-
- def handle_explicit(self):
- assert self.in_class
- # Nothing much to do.
- # TODO(nnorwitz): maybe verify the method name == class name.
- # This must be a ctor.
- return self.GetMethod(FUNCTION_CTOR, None)
-
- def handle_this(self):
- pass # Nothing to do.
-
- def handle_operator(self):
- # Pull off the next token(s?) and make that part of the method name.
- pass
+ new_class = class_type(class_token.start, class_token.end,
+ class_name, bases, None,
+ body, self.namespace_stack)
+
+ modifiers = []
+ return self._CreateVariable(class_token,
+ token.name, new_class,
+ modifiers, token.name, None)
+ else:
+ if not self._handling_typedef:
+ self.HandleError('non-typedef token', token)
+ self._AddBackToken(token)
+
+ return class_type(class_token.start, class_token.end, class_name,
+ bases, templated_types, body, self.namespace_stack)
+
+ def handle_namespace(self):
+ # Support anonymous namespaces.
+ name = None
+ name_tokens, token = self.GetName()
+ if name_tokens:
+ name = ''.join([t.name for t in name_tokens])
+ self.namespace_stack.append(name)
+ assert token.token_type == tokenize.SYNTAX, token
+ # Create an internal token that denotes when the namespace is complete.
+ internal_token = tokenize.Token(_INTERNAL_TOKEN, _NAMESPACE_POP,
+ None, None)
+ internal_token.whence = token.whence
+ if token.name == '=':
+ # TODO(nnorwitz): handle aliasing namespaces.
+ name, next_token = self.GetName()
+ assert next_token.name == ';', next_token
+ self._AddBackToken(internal_token)
+ else:
+ assert token.name == '{', token
+ tokens = list(self.GetScope())
+ # Replace the trailing } with the internal namespace pop token.
+ tokens[-1] = internal_token
+ # Handle namespace with nothing in it.
+ self._AddBackTokens(tokens)
+ return None
+
+ def handle_using(self):
+ tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
+ assert tokens
+ return Using(tokens[0].start, tokens[0].end, tokens)
+
+ def handle_explicit(self):
+ assert self.in_class
+ # Nothing much to do.
+ # TODO(nnorwitz): maybe verify the method name == class name.
+ # This must be a ctor.
+ return self.GetMethod(FUNCTION_CTOR, None)
+
+ def handle_this(self):
+ pass # Nothing to do.
+
+ def handle_operator(self):
+ # Pull off the next token(s?) and make that part of the method name.
+ pass
- def handle_sizeof(self):
- pass
+ def handle_sizeof(self):
+ pass
- def handle_case(self):
- pass
+ def handle_case(self):
+ pass
- def handle_switch(self):
- pass
+ def handle_switch(self):
+ pass
- def handle_default(self):
- token = self._GetNextToken()
- assert token.token_type == tokenize.SYNTAX
- assert token.name == ':'
+ def handle_default(self):
+ token = self._GetNextToken()
+ assert token.token_type == tokenize.SYNTAX
+ assert token.name == ':'
- def handle_if(self):
- pass
+ def handle_if(self):
+ pass
- def handle_else(self):
- pass
+ def handle_else(self):
+ pass
- def handle_return(self):
- tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
- if not tokens:
- return Return(self.current_token.start, self.current_token.end, None)
- return Return(tokens[0].start, tokens[0].end, tokens)
+ def handle_return(self):
+ tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
+ if not tokens:
+ return Return(self.current_token.start, self.current_token.end, None)
+ return Return(tokens[0].start, tokens[0].end, tokens)
- def handle_goto(self):
- tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
- assert len(tokens) == 1, str(tokens)
- return Goto(tokens[0].start, tokens[0].end, tokens[0].name)
+ def handle_goto(self):
+ tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';')
+ assert len(tokens) == 1, str(tokens)
+ return Goto(tokens[0].start, tokens[0].end, tokens[0].name)
- def handle_try(self):
- pass # Not needed yet.
+ def handle_try(self):
+ pass # Not needed yet.
- def handle_catch(self):
- pass # Not needed yet.
+ def handle_catch(self):
+ pass # Not needed yet.
- def handle_throw(self):
- pass # Not needed yet.
+ def handle_throw(self):
+ pass # Not needed yet.
- def handle_while(self):
- pass
+ def handle_while(self):
+ pass
- def handle_do(self):
- pass
+ def handle_do(self):
+ pass
- def handle_for(self):
- pass
+ def handle_for(self):
+ pass
- def handle_break(self):
- self._IgnoreUpTo(tokenize.SYNTAX, ';')
+ def handle_break(self):
+ self._IgnoreUpTo(tokenize.SYNTAX, ';')
- def handle_continue(self):
- self._IgnoreUpTo(tokenize.SYNTAX, ';')
+ def handle_continue(self):
+ self._IgnoreUpTo(tokenize.SYNTAX, ';')
def BuilderFromSource(source, filename):
- """Utility method that returns an AstBuilder from source code.
+ """Utility method that returns an AstBuilder from source code.
Args:
source: 'C++ source code'
@@ -1698,64 +1710,64 @@ def BuilderFromSource(source, filename):
Returns:
AstBuilder
"""
- return AstBuilder(tokenize.GetTokens(source), filename)
+ return AstBuilder(tokenize.GetTokens(source), filename)
def PrintIndentifiers(filename, should_print):
- """Prints all identifiers for a C++ source file.
+ """Prints all identifiers for a C++ source file.
Args:
filename: 'file1'
should_print: predicate with signature: bool Function(token)
"""
- source = utils.ReadFile(filename, False)
- if source is None:
- sys.stderr.write('Unable to find: %s\n' % filename)
- return
-
- #print('Processing %s' % actual_filename)
- builder = BuilderFromSource(source, filename)
- try:
- for node in builder.Generate():
- if should_print(node):
- print(node.name)
- except KeyboardInterrupt:
- return
- except:
- pass
+ source = utils.ReadFile(filename, False)
+ if source is None:
+ sys.stderr.write('Unable to find: %s\n' % filename)
+ return
+
+ #print('Processing %s' % actual_filename)
+ builder = BuilderFromSource(source, filename)
+ try:
+ for node in builder.Generate():
+ if should_print(node):
+ print(node.name)
+ except KeyboardInterrupt:
+ return
+ except:
+ pass
def PrintAllIndentifiers(filenames, should_print):
- """Prints all identifiers for each C++ source file in filenames.
+ """Prints all identifiers for each C++ source file in filenames.
Args:
filenames: ['file1', 'file2', ...]
should_print: predicate with signature: bool Function(token)
"""
- for path in filenames:
- PrintIndentifiers(path, should_print)
+ for path in filenames:
+ PrintIndentifiers(path, should_print)
def main(argv):
- for filename in argv[1:]:
- source = utils.ReadFile(filename)
- if source is None:
- continue
-
- print('Processing %s' % filename)
- builder = BuilderFromSource(source, filename)
- try:
- entire_ast = filter(None, builder.Generate())
- except KeyboardInterrupt:
- return
- except:
- # Already printed a warning, print the traceback and continue.
- traceback.print_exc()
- else:
- if utils.DEBUG:
- for ast in entire_ast:
- print(ast)
+ for filename in argv[1:]:
+ source = utils.ReadFile(filename)
+ if source is None:
+ continue
+
+ print('Processing %s' % filename)
+ builder = BuilderFromSource(source, filename)
+ try:
+ entire_ast = filter(None, builder.Generate())
+ except KeyboardInterrupt:
+ return
+ except:
+ # Already printed a warning, print the traceback and continue.
+ traceback.print_exc()
+ else:
+ if utils.DEBUG:
+ for ast in entire_ast:
+ print(ast)
if __name__ == '__main__':
- main(sys.argv)
+ main(sys.argv)
diff --git a/googlemock/scripts/generator/cpp/gmock_class.py b/googlemock/scripts/generator/cpp/gmock_class.py
index 89862ae1..3e21022b 100755
--- a/googlemock/scripts/generator/cpp/gmock_class.py
+++ b/googlemock/scripts/generator/cpp/gmock_class.py
@@ -35,11 +35,11 @@ from cpp import utils
# Preserve compatibility with Python 2.3.
try:
- _dummy = set
+ _dummy = set
except NameError:
- import sets
+ import sets
- set = sets.Set
+ set = sets.Set
_VERSION = (1, 0, 1) # The version of this script.
# How many spaces to indent. Can set me with the INDENT environment variable.
@@ -47,202 +47,201 @@ _INDENT = 2
def _RenderType(ast_type):
- """Renders the potentially recursively templated type into a string.
+ """Renders the potentially recursively templated type into a string.
Args:
ast_type: The AST of the type.
Returns:
- Rendered string and a boolean to indicate whether we have multiple args
- (which is not handled correctly).
+ Rendered string of the type.
"""
- has_multiarg_error = False
- # Add modifiers like 'const'.
- modifiers = ''
- if ast_type.modifiers:
- modifiers = ' '.join(ast_type.modifiers) + ' '
- return_type = modifiers + ast_type.name
- if ast_type.templated_types:
- # Collect template args.
- template_args = []
- for arg in ast_type.templated_types:
- rendered_arg, e = _RenderType(arg)
- if e: has_multiarg_error = True
- template_args.append(rendered_arg)
- return_type += '<' + ', '.join(template_args) + '>'
- # We are actually not handling multi-template-args correctly. So mark it.
- if len(template_args) > 1:
- has_multiarg_error = True
- if ast_type.pointer:
- return_type += '*'
- if ast_type.reference:
- return_type += '&'
- return return_type, has_multiarg_error
-
-
-def _GetNumParameters(parameters, source):
- num_parameters = len(parameters)
- if num_parameters == 1:
- first_param = parameters[0]
- if source[first_param.start:first_param.end].strip() == 'void':
- # We must treat T(void) as a function with no parameters.
- return 0
- return num_parameters
+ # Add modifiers like 'const'.
+ modifiers = ''
+ if ast_type.modifiers:
+ modifiers = ' '.join(ast_type.modifiers) + ' '
+ return_type = modifiers + ast_type.name
+ if ast_type.templated_types:
+ # Collect template args.
+ template_args = []
+ for arg in ast_type.templated_types:
+ rendered_arg = _RenderType(arg)
+ template_args.append(rendered_arg)
+ return_type += '<' + ', '.join(template_args) + '>'
+ if ast_type.pointer:
+ return_type += '*'
+ if ast_type.reference:
+ return_type += '&'
+ return return_type
+
+
+def _GenerateArg(source):
+ """Strips out comments, default arguments, and redundant spaces from a single argument.
+
+ Args:
+ source: A string for a single argument.
+
+ Returns:
+ Rendered string of the argument.
+ """
+ # Remove end of line comments before eliminating newlines.
+ arg = re.sub(r'//.*', '', source)
+
+ # Remove c-style comments.
+ arg = re.sub(r'/\*.*\*/', '', arg)
+
+ # Remove default arguments.
+ arg = re.sub(r'=.*', '', arg)
+
+ # Collapse spaces and newlines into a single space.
+ arg = re.sub(r'\s+', ' ', arg)
+ return arg.strip()
+
+
+def _EscapeForMacro(s):
+ """Escapes a string for use as an argument to a C++ macro."""
+ paren_count = 0
+ for c in s:
+ if c == '(':
+ paren_count += 1
+ elif c == ')':
+ paren_count -= 1
+ elif c == ',' and paren_count == 0:
+ return '(' + s + ')'
+ return s
def _GenerateMethods(output_lines, source, class_node):
- function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL |
- ast.FUNCTION_OVERRIDE)
- ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
- indent = ' ' * _INDENT
-
- for node in class_node.body:
- # We only care about virtual functions.
- if (isinstance(node, ast.Function) and
- node.modifiers & function_type and
- not node.modifiers & ctor_or_dtor):
- # Pick out all the elements we need from the original function.
- const = ''
- if node.modifiers & ast.FUNCTION_CONST:
- const = 'CONST_'
- num_parameters = _GetNumParameters(node.parameters, source)
- return_type = 'void'
- if node.return_type:
- return_type, has_multiarg_error = _RenderType(node.return_type)
- if has_multiarg_error:
- for line in [
- '// The following line won\'t really compile, as the return',
- '// type has multiple template arguments. To fix it, use a',
- '// typedef for the return type.']:
- output_lines.append(indent + line)
- tmpl = ''
- if class_node.templated_types:
- tmpl = '_T'
- mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl)
-
- args = ''
- if node.parameters:
- # Get the full text of the parameters from the start
- # of the first parameter to the end of the last parameter.
- start = node.parameters[0].start
- end = node.parameters[-1].end
- # Remove // comments.
- args_strings = re.sub(r'//.*', '', source[start:end])
- # Remove /* comments */.
- args_strings = re.sub(r'/\*.*\*/', '', args_strings)
- # Remove default arguments.
- args_strings = re.sub(r'=.*,', ',', args_strings)
- args_strings = re.sub(r'=.*', '', args_strings)
- # Condense multiple spaces and eliminate newlines putting the
- # parameters together on a single line. Ensure there is a
- # space in an argument which is split by a newline without
- # intervening whitespace, e.g.: int\nBar
- args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
-
- # Create the mock method definition.
- output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name),
- '%s%s(%s));' % (indent * 3, return_type, args)])
+ function_type = (
+ ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | ast.FUNCTION_OVERRIDE)
+ ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
+ indent = ' ' * _INDENT
+
+ for node in class_node.body:
+ # We only care about virtual functions.
+ if (isinstance(node, ast.Function) and node.modifiers & function_type and
+ not node.modifiers & ctor_or_dtor):
+ # Pick out all the elements we need from the original function.
+ modifiers = 'override'
+ if node.modifiers & ast.FUNCTION_CONST:
+ modifiers = 'const, ' + modifiers
+
+ return_type = 'void'
+ if node.return_type:
+ return_type = _EscapeForMacro(_RenderType(node.return_type))
+
+ args = []
+ for p in node.parameters:
+ arg = _GenerateArg(source[p.start:p.end])
+ if arg != 'void':
+ args.append(_EscapeForMacro(arg))
+
+ # Create the mock method definition.
+ output_lines.extend([
+ '%sMOCK_METHOD(%s, %s, (%s), (%s));' %
+ (indent, return_type, node.name, ', '.join(args), modifiers)
+ ])
def _GenerateMocks(filename, source, ast_list, desired_class_names):
- processed_class_names = set()
- lines = []
- for node in ast_list:
- if (isinstance(node, ast.Class) and node.body and
- # desired_class_names being None means that all classes are selected.
- (not desired_class_names or node.name in desired_class_names)):
- class_name = node.name
- parent_name = class_name
- processed_class_names.add(class_name)
- class_node = node
- # Add namespace before the class.
- if class_node.namespace:
- lines.extend(['namespace %s {' % n for n in class_node.namespace]) # }
- lines.append('')
-
- # Add template args for templated classes.
- if class_node.templated_types:
- # TODO(paulchang): The AST doesn't preserve template argument order,
- # so we have to make up names here.
- # TODO(paulchang): Handle non-type template arguments (e.g.
- # template<typename T, int N>).
- template_arg_count = len(class_node.templated_types.keys())
- template_args = ['T%d' % n for n in range(template_arg_count)]
- template_decls = ['typename ' + arg for arg in template_args]
- lines.append('template <' + ', '.join(template_decls) + '>')
- parent_name += '<' + ', '.join(template_args) + '>'
-
- # Add the class prolog.
- lines.append('class Mock%s : public %s {' # }
- % (class_name, parent_name))
- lines.append('%spublic:' % (' ' * (_INDENT // 2)))
-
- # Add all the methods.
- _GenerateMethods(lines, source, class_node)
-
- # Close the class.
- if lines:
- # If there are no virtual methods, no need for a public label.
- if len(lines) == 2:
- del lines[-1]
-
- # Only close the class if there really is a class.
- lines.append('};')
- lines.append('') # Add an extra newline.
-
- # Close the namespace.
- if class_node.namespace:
- for i in range(len(class_node.namespace) - 1, -1, -1):
- lines.append('} // namespace %s' % class_node.namespace[i])
- lines.append('') # Add an extra newline.
-
- if desired_class_names:
- missing_class_name_list = list(desired_class_names - processed_class_names)
- if missing_class_name_list:
- missing_class_name_list.sort()
- sys.stderr.write('Class(es) not found in %s: %s\n' %
- (filename, ', '.join(missing_class_name_list)))
- elif not processed_class_names:
- sys.stderr.write('No class found in %s\n' % filename)
-
- return lines
+ processed_class_names = set()
+ lines = []
+ for node in ast_list:
+ if (isinstance(node, ast.Class) and node.body and
+ # desired_class_names being None means that all classes are selected.
+ (not desired_class_names or node.name in desired_class_names)):
+ class_name = node.name
+ parent_name = class_name
+ processed_class_names.add(class_name)
+ class_node = node
+ # Add namespace before the class.
+ if class_node.namespace:
+ lines.extend(['namespace %s {' % n for n in class_node.namespace]) # }
+ lines.append('')
+
+ # Add template args for templated classes.
+ if class_node.templated_types:
+ # TODO(paulchang): Handle non-type template arguments (e.g.
+ # template<typename T, int N>).
+
+ # class_node.templated_types is an OrderedDict from strings to a tuples.
+ # The key is the name of the template, and the value is
+ # (type_name, default). Both type_name and default could be None.
+ template_args = class_node.templated_types.keys()
+ template_decls = ['typename ' + arg for arg in template_args]
+ lines.append('template <' + ', '.join(template_decls) + '>')
+ parent_name += '<' + ', '.join(template_args) + '>'
+
+ # Add the class prolog.
+ lines.append('class Mock%s : public %s {' # }
+ % (class_name, parent_name))
+ lines.append('%spublic:' % (' ' * (_INDENT // 2)))
+
+ # Add all the methods.
+ _GenerateMethods(lines, source, class_node)
+
+ # Close the class.
+ if lines:
+ # If there are no virtual methods, no need for a public label.
+ if len(lines) == 2:
+ del lines[-1]
+
+ # Only close the class if there really is a class.
+ lines.append('};')
+ lines.append('') # Add an extra newline.
+
+ # Close the namespace.
+ if class_node.namespace:
+ for i in range(len(class_node.namespace) - 1, -1, -1):
+ lines.append('} // namespace %s' % class_node.namespace[i])
+ lines.append('') # Add an extra newline.
+
+ if desired_class_names:
+ missing_class_name_list = list(desired_class_names - processed_class_names)
+ if missing_class_name_list:
+ missing_class_name_list.sort()
+ sys.stderr.write('Class(es) not found in %s: %s\n' %
+ (filename, ', '.join(missing_class_name_list)))
+ elif not processed_class_names:
+ sys.stderr.write('No class found in %s\n' % filename)
+
+ return lines
def main(argv=sys.argv):
- if len(argv) < 2:
- sys.stderr.write('Google Mock Class Generator v%s\n\n' %
- '.'.join(map(str, _VERSION)))
- sys.stderr.write(__doc__)
- return 1
-
- global _INDENT
- try:
- _INDENT = int(os.environ['INDENT'])
- except KeyError:
- pass
- except:
- sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
-
- filename = argv[1]
- desired_class_names = None # None means all classes in the source file.
- if len(argv) >= 3:
- desired_class_names = set(argv[2:])
- source = utils.ReadFile(filename)
- if source is None:
- return 1
-
- builder = ast.BuilderFromSource(source, filename)
- try:
- entire_ast = filter(None, builder.Generate())
- except KeyboardInterrupt:
- return
- except:
- # An error message was already printed since we couldn't parse.
- sys.exit(1)
- else:
- lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
- sys.stdout.write('\n'.join(lines))
+ if len(argv) < 2:
+ sys.stderr.write('Google Mock Class Generator v%s\n\n' %
+ '.'.join(map(str, _VERSION)))
+ sys.stderr.write(__doc__)
+ return 1
+
+ global _INDENT
+ try:
+ _INDENT = int(os.environ['INDENT'])
+ except KeyError:
+ pass
+ except:
+ sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
+
+ filename = argv[1]
+ desired_class_names = None # None means all classes in the source file.
+ if len(argv) >= 3:
+ desired_class_names = set(argv[2:])
+ source = utils.ReadFile(filename)
+ if source is None:
+ return 1
+
+ builder = ast.BuilderFromSource(source, filename)
+ try:
+ entire_ast = filter(None, builder.Generate())
+ except KeyboardInterrupt:
+ return
+ except:
+ # An error message was already printed since we couldn't parse.
+ sys.exit(1)
+ else:
+ lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
+ sys.stdout.write('\n'.join(lines))
if __name__ == '__main__':
- main(sys.argv)
+ main(sys.argv)
diff --git a/googlemock/scripts/generator/cpp/gmock_class_test.py b/googlemock/scripts/generator/cpp/gmock_class_test.py
index 211a92dd..eff475f4 100755
--- a/googlemock/scripts/generator/cpp/gmock_class_test.py
+++ b/googlemock/scripts/generator/cpp/gmock_class_test.py
@@ -29,43 +29,43 @@ from cpp import gmock_class
class TestCase(unittest.TestCase):
- """Helper class that adds assert methods."""
+ """Helper class that adds assert methods."""
- @staticmethod
- def StripLeadingWhitespace(lines):
- """Strip leading whitespace in each line in 'lines'."""
- return '\n'.join([s.lstrip() for s in lines.split('\n')])
+ @staticmethod
+ def StripLeadingWhitespace(lines):
+ """Strip leading whitespace in each line in 'lines'."""
+ return '\n'.join([s.lstrip() for s in lines.split('\n')])
- def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines):
- """Specialized assert that ignores the indent level."""
- self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines))
+ def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines):
+ """Specialized assert that ignores the indent level."""
+ self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines))
class GenerateMethodsTest(TestCase):
- @staticmethod
- def GenerateMethodSource(cpp_source):
- """Convert C++ source to Google Mock output source lines."""
- method_source_lines = []
- # <test> is a pseudo-filename, it is not read or written.
- builder = ast.BuilderFromSource(cpp_source, '<test>')
- ast_list = list(builder.Generate())
- gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0])
- return '\n'.join(method_source_lines)
-
- def testSimpleMethod(self):
- source = """
+ @staticmethod
+ def GenerateMethodSource(cpp_source):
+ """Convert C++ source to Google Mock output source lines."""
+ method_source_lines = []
+ # <test> is a pseudo-filename, it is not read or written.
+ builder = ast.BuilderFromSource(cpp_source, '<test>')
+ ast_list = list(builder.Generate())
+ gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0])
+ return '\n'.join(method_source_lines)
+
+ def testSimpleMethod(self):
+ source = """
class Foo {
public:
virtual int Bar();
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint());',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (), (override));',
+ self.GenerateMethodSource(source))
- def testSimpleConstructorsAndDestructor(self):
- source = """
+ def testSimpleConstructorsAndDestructor(self):
+ source = """
class Foo {
public:
Foo();
@@ -76,26 +76,26 @@ class Foo {
virtual int Bar() = 0;
};
"""
- # The constructors and destructor should be ignored.
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint());',
- self.GenerateMethodSource(source))
+ # The constructors and destructor should be ignored.
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (), (override));',
+ self.GenerateMethodSource(source))
- def testVirtualDestructor(self):
- source = """
+ def testVirtualDestructor(self):
+ source = """
class Foo {
public:
virtual ~Foo();
virtual int Bar() = 0;
};
"""
- # The destructor should be ignored.
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint());',
- self.GenerateMethodSource(source))
+ # The destructor should be ignored.
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (), (override));',
+ self.GenerateMethodSource(source))
- def testExplicitlyDefaultedConstructorsAndDestructor(self):
- source = """
+ def testExplicitlyDefaultedConstructorsAndDestructor(self):
+ source = """
class Foo {
public:
Foo() = default;
@@ -105,13 +105,13 @@ class Foo {
virtual int Bar() = 0;
};
"""
- # The constructors and destructor should be ignored.
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint());',
- self.GenerateMethodSource(source))
+ # The constructors and destructor should be ignored.
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (), (override));',
+ self.GenerateMethodSource(source))
- def testExplicitlyDeletedConstructorsAndDestructor(self):
- source = """
+ def testExplicitlyDeletedConstructorsAndDestructor(self):
+ source = """
class Foo {
public:
Foo() = delete;
@@ -121,69 +121,69 @@ class Foo {
virtual int Bar() = 0;
};
"""
- # The constructors and destructor should be ignored.
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint());',
- self.GenerateMethodSource(source))
+ # The constructors and destructor should be ignored.
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (), (override));',
+ self.GenerateMethodSource(source))
- def testSimpleOverrideMethod(self):
- source = """
+ def testSimpleOverrideMethod(self):
+ source = """
class Foo {
public:
int Bar() override;
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint());',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (), (override));',
+ self.GenerateMethodSource(source))
- def testSimpleConstMethod(self):
- source = """
+ def testSimpleConstMethod(self):
+ source = """
class Foo {
public:
virtual void Bar(bool flag) const;
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(void, Bar, (bool flag), (const, override));',
+ self.GenerateMethodSource(source))
- def testExplicitVoid(self):
- source = """
+ def testExplicitVoid(self):
+ source = """
class Foo {
public:
virtual int Bar(void);
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0(Bar,\nint(void));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (), (override));',
+ self.GenerateMethodSource(source))
- def testStrangeNewlineInParameter(self):
- source = """
+ def testStrangeNewlineInParameter(self):
+ source = """
class Foo {
public:
virtual void Bar(int
a) = 0;
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nvoid(int a));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(void, Bar, (int a), (override));',
+ self.GenerateMethodSource(source))
- def testDefaultParameters(self):
- source = """
+ def testDefaultParameters(self):
+ source = """
class Foo {
public:
virtual void Bar(int a, char c = 'x') = 0;
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD2(Bar,\nvoid(int a, char c ));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(void, Bar, (int a, char c), (override));',
+ self.GenerateMethodSource(source))
- def testMultipleDefaultParameters(self):
- source = """
+ def testMultipleDefaultParameters(self):
+ source = """
class Foo {
public:
virtual void Bar(
@@ -195,47 +195,58 @@ class Foo {
int const *& rp = aDefaultPointer) = 0;
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- "MOCK_METHOD7(Bar,\n"
- "void(int a , char c , const int* const p , const std::string& s , char tab[] , int const *& rp ));",
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(void, Bar, '
+ '(int a, char c, const int* const p, const std::string& s, char tab[], int const *& rp), '
+ '(override));', self.GenerateMethodSource(source))
- def testConstDefaultParameter(self):
- source = """
+ def testMultipleSingleLineDefaultParameters(self):
+ source = """
+class Foo {
+ public:
+ virtual void Bar(int a = 42, int b = 43, int c = 44) = 0;
+};
+"""
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(void, Bar, (int a, int b, int c), (override));',
+ self.GenerateMethodSource(source))
+
+ def testConstDefaultParameter(self):
+ source = """
class Test {
public:
virtual bool Bar(const int test_arg = 42) = 0;
};
"""
- expected = 'MOCK_METHOD1(Bar,\nbool(const int test_arg ));'
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(bool, Bar, (const int test_arg), (override));',
+ self.GenerateMethodSource(source))
- def testConstRefDefaultParameter(self):
- source = """
+ def testConstRefDefaultParameter(self):
+ source = """
class Test {
public:
virtual bool Bar(const std::string& test_arg = "42" ) = 0;
};
"""
- expected = 'MOCK_METHOD1(Bar,\nbool(const std::string& test_arg ));'
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(bool, Bar, (const std::string& test_arg), (override));',
+ self.GenerateMethodSource(source))
- def testRemovesCommentsWhenDefaultsArePresent(self):
- source = """
+ def testRemovesCommentsWhenDefaultsArePresent(self):
+ source = """
class Foo {
public:
virtual void Bar(int a = 42 /* a comment */,
char /* other comment */ c= 'x') = 0;
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD2(Bar,\nvoid(int a , char c));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(void, Bar, (int a, char c), (override));',
+ self.GenerateMethodSource(source))
- def testDoubleSlashCommentsInParameterListAreRemoved(self):
- source = """
+ def testDoubleSlashCommentsInParameterListAreRemoved(self):
+ source = """
class Foo {
public:
virtual void Bar(int a, // inline comments should be elided.
@@ -243,219 +254,226 @@ class Foo {
) const = 0;
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(void, Bar, (int a, int b), (const, override));',
+ self.GenerateMethodSource(source))
- def testCStyleCommentsInParameterListAreNotRemoved(self):
- # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these
- # comments. Also note that C style comments after the last parameter
- # are still elided.
- source = """
+ def testCStyleCommentsInParameterListAreNotRemoved(self):
+ # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these
+ # comments. Also note that C style comments after the last parameter
+ # are still elided.
+ source = """
class Foo {
public:
virtual const string& Bar(int /* keeper */, int b);
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD2(Bar,\nconst string&(int , int b));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(const string&, Bar, (int, int b), (override));',
+ self.GenerateMethodSource(source))
- def testArgsOfTemplateTypes(self):
- source = """
+ def testArgsOfTemplateTypes(self):
+ source = """
class Foo {
public:
virtual int Bar(const vector<int>& v, map<int, string>* output);
};"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD2(Bar,\n'
- 'int(const vector<int>& v, map<int, string>* output));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (const vector<int>& v, (map<int, string>* output)), (override));',
+ self.GenerateMethodSource(source))
- def testReturnTypeWithOneTemplateArg(self):
- source = """
+ def testReturnTypeWithOneTemplateArg(self):
+ source = """
class Foo {
public:
virtual vector<int>* Bar(int n);
};"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nvector<int>*(int n));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(vector<int>*, Bar, (int n), (override));',
+ self.GenerateMethodSource(source))
- def testReturnTypeWithManyTemplateArgs(self):
- source = """
+ def testReturnTypeWithManyTemplateArgs(self):
+ source = """
class Foo {
public:
virtual map<int, string> Bar();
};"""
- # Comparing the comment text is brittle - we'll think of something
- # better in case this gets annoying, but for now let's keep it simple.
- self.assertEqualIgnoreLeadingWhitespace(
- '// The following line won\'t really compile, as the return\n'
- '// type has multiple template arguments. To fix it, use a\n'
- '// typedef for the return type.\n'
- 'MOCK_METHOD0(Bar,\nmap<int, string>());',
- self.GenerateMethodSource(source))
-
- def testSimpleMethodInTemplatedClass(self):
- source = """
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD((map<int, string>), Bar, (), (override));',
+ self.GenerateMethodSource(source))
+
+ def testSimpleMethodInTemplatedClass(self):
+ source = """
template<class T>
class Foo {
public:
virtual int Bar();
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD0_T(Bar,\nint());',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (), (override));',
+ self.GenerateMethodSource(source))
- def testPointerArgWithoutNames(self):
- source = """
+ def testPointerArgWithoutNames(self):
+ source = """
class Foo {
virtual int Bar(C*);
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nint(C*));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (C*), (override));',
+ self.GenerateMethodSource(source))
- def testReferenceArgWithoutNames(self):
- source = """
+ def testReferenceArgWithoutNames(self):
+ source = """
class Foo {
virtual int Bar(C&);
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nint(C&));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (C&), (override));',
+ self.GenerateMethodSource(source))
- def testArrayArgWithoutNames(self):
- source = """
+ def testArrayArgWithoutNames(self):
+ source = """
class Foo {
virtual int Bar(C[]);
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- 'MOCK_METHOD1(Bar,\nint(C[]));',
- self.GenerateMethodSource(source))
+ self.assertEqualIgnoreLeadingWhitespace(
+ 'MOCK_METHOD(int, Bar, (C[]), (override));',
+ self.GenerateMethodSource(source))
class GenerateMocksTest(TestCase):
- @staticmethod
- def GenerateMocks(cpp_source):
- """Convert C++ source to complete Google Mock output source."""
- # <test> is a pseudo-filename, it is not read or written.
- filename = '<test>'
- builder = ast.BuilderFromSource(cpp_source, filename)
- ast_list = list(builder.Generate())
- lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None)
- return '\n'.join(lines)
-
- def testNamespaces(self):
- source = """
+ @staticmethod
+ def GenerateMocks(cpp_source):
+ """Convert C++ source to complete Google Mock output source."""
+ # <test> is a pseudo-filename, it is not read or written.
+ filename = '<test>'
+ builder = ast.BuilderFromSource(cpp_source, filename)
+ ast_list = list(builder.Generate())
+ lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None)
+ return '\n'.join(lines)
+
+ def testNamespaces(self):
+ source = """
namespace Foo {
namespace Bar { class Forward; }
-namespace Baz {
+namespace Baz::Qux {
class Test {
public:
virtual void Foo();
};
-} // namespace Baz
+} // namespace Baz::Qux
} // namespace Foo
"""
- expected = """\
+ expected = """\
namespace Foo {
-namespace Baz {
+namespace Baz::Qux {
class MockTest : public Test {
public:
-MOCK_METHOD0(Foo,
-void());
+MOCK_METHOD(void, Foo, (), (override));
};
-} // namespace Baz
+} // namespace Baz::Qux
} // namespace Foo
"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
- def testClassWithStorageSpecifierMacro(self):
- source = """
+ def testClassWithStorageSpecifierMacro(self):
+ source = """
class STORAGE_SPECIFIER Test {
public:
virtual void Foo();
};
"""
- expected = """\
+ expected = """\
class MockTest : public Test {
public:
-MOCK_METHOD0(Foo,
-void());
+MOCK_METHOD(void, Foo, (), (override));
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
- def testTemplatedForwardDeclaration(self):
- source = """
+ def testTemplatedForwardDeclaration(self):
+ source = """
template <class T> class Forward; // Forward declaration should be ignored.
class Test {
public:
virtual void Foo();
};
"""
- expected = """\
+ expected = """\
class MockTest : public Test {
public:
-MOCK_METHOD0(Foo,
-void());
+MOCK_METHOD(void, Foo, (), (override));
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
- def testTemplatedClass(self):
- source = """
+ def testTemplatedClass(self):
+ source = """
template <typename S, typename T>
class Test {
public:
virtual void Foo();
};
"""
- expected = """\
-template <typename T0, typename T1>
-class MockTest : public Test<T0, T1> {
+ expected = """\
+template <typename S, typename T>
+class MockTest : public Test<S, T> {
public:
-MOCK_METHOD0_T(Foo,
-void());
+MOCK_METHOD(void, Foo, (), (override));
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
- def testTemplateInATemplateTypedef(self):
- source = """
+ def testTemplateInATemplateTypedef(self):
+ source = """
class Test {
public:
typedef std::vector<std::list<int>> FooType;
virtual void Bar(const FooType& test_arg);
};
"""
- expected = """\
+ expected = """\
class MockTest : public Test {
public:
-MOCK_METHOD1(Bar,
-void(const FooType& test_arg));
+MOCK_METHOD(void, Bar, (const FooType& test_arg), (override));
+};
+"""
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
+
+ def testTemplatedClassWithTemplatedArguments(self):
+ source = """
+template <typename S, typename T, typename U, typename V, typename W>
+class Test {
+ public:
+ virtual U Foo(T some_arg);
+};
+"""
+ expected = """\
+template <typename S, typename T, typename U, typename V, typename W>
+class MockTest : public Test<S, T, U, V, W> {
+public:
+MOCK_METHOD(U, Foo, (T some_arg), (override));
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
- def testTemplateInATemplateTypedefWithComma(self):
- source = """
+ def testTemplateInATemplateTypedefWithComma(self):
+ source = """
class Test {
public:
typedef std::function<void(
@@ -463,18 +481,33 @@ class Test {
virtual void Bar(const FooType& test_arg);
};
"""
- expected = """\
+ expected = """\
+class MockTest : public Test {
+public:
+MOCK_METHOD(void, Bar, (const FooType& test_arg), (override));
+};
+"""
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
+
+ def testParenthesizedCommaInArg(self):
+ source = """
+class Test {
+ public:
+ virtual void Bar(std::function<void(int, int)> f);
+};
+"""
+ expected = """\
class MockTest : public Test {
public:
-MOCK_METHOD1(Bar,
-void(const FooType& test_arg));
+MOCK_METHOD(void, Bar, (std::function<void(int, int)> f), (override));
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
- def testEnumType(self):
- source = """
+ def testEnumType(self):
+ source = """
class Test {
public:
enum Bar {
@@ -483,18 +516,17 @@ class Test {
virtual void Foo();
};
"""
- expected = """\
+ expected = """\
class MockTest : public Test {
public:
-MOCK_METHOD0(Foo,
-void());
+MOCK_METHOD(void, Foo, (), (override));
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
- def testEnumClassType(self):
- source = """
+ def testEnumClassType(self):
+ source = """
class Test {
public:
enum class Bar {
@@ -503,18 +535,17 @@ class Test {
virtual void Foo();
};
"""
- expected = """\
+ expected = """\
class MockTest : public Test {
public:
-MOCK_METHOD0(Foo,
-void());
+MOCK_METHOD(void, Foo, (), (override));
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
- def testStdFunction(self):
- source = """
+ def testStdFunction(self):
+ source = """
class Test {
public:
Test(std::function<int(std::string)> foo) : foo_(foo) {}
@@ -525,16 +556,15 @@ class Test {
std::function<int(std::string)> foo_;
};
"""
- expected = """\
+ expected = """\
class MockTest : public Test {
public:
-MOCK_METHOD0(foo,
-std::function<int (std::string)>());
+MOCK_METHOD(std::function<int (std::string)>, foo, (), (override));
};
"""
- self.assertEqualIgnoreLeadingWhitespace(
- expected, self.GenerateMocks(source))
+ self.assertEqualIgnoreLeadingWhitespace(expected,
+ self.GenerateMocks(source))
if __name__ == '__main__':
- unittest.main()
+ unittest.main()
diff --git a/googlemock/scripts/pump.py b/googlemock/scripts/pump.py
deleted file mode 100755
index 5523a19d..00000000
--- a/googlemock/scripts/pump.py
+++ /dev/null
@@ -1,856 +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.
-
-"""pump v0.2.0 - Pretty Useful for Meta Programming.
-
-A tool for preprocessor meta programming. Useful for generating
-repetitive boilerplate code. Especially useful for writing C++
-classes, functions, macros, and templates that need to work with
-various number of arguments.
-
-USAGE:
- pump.py SOURCE_FILE
-
-EXAMPLES:
- pump.py foo.cc.pump
- Converts foo.cc.pump to foo.cc.
-
-GRAMMAR:
- CODE ::= ATOMIC_CODE*
- ATOMIC_CODE ::= $var ID = EXPRESSION
- | $var ID = [[ CODE ]]
- | $range ID EXPRESSION..EXPRESSION
- | $for ID SEPARATOR [[ CODE ]]
- | $($)
- | $ID
- | $(EXPRESSION)
- | $if EXPRESSION [[ CODE ]] ELSE_BRANCH
- | [[ CODE ]]
- | RAW_CODE
- SEPARATOR ::= RAW_CODE | EMPTY
- ELSE_BRANCH ::= $else [[ CODE ]]
- | $elif EXPRESSION [[ CODE ]] ELSE_BRANCH
- | EMPTY
- EXPRESSION has Python syntax.
-"""
-
-from __future__ import print_function
-
-import io
-import os
-import re
-import sys
-
-
-TOKEN_TABLE = [
- (re.compile(r'\$var\s+'), '$var'),
- (re.compile(r'\$elif\s+'), '$elif'),
- (re.compile(r'\$else\s+'), '$else'),
- (re.compile(r'\$for\s+'), '$for'),
- (re.compile(r'\$if\s+'), '$if'),
- (re.compile(r'\$range\s+'), '$range'),
- (re.compile(r'\$[_A-Za-z]\w*'), '$id'),
- (re.compile(r'\$\(\$\)'), '$($)'),
- (re.compile(r'\$'), '$'),
- (re.compile(r'\[\[\n?'), '[['),
- (re.compile(r'\]\]\n?'), ']]'),
- ]
-
-
-class Cursor:
- """Represents a position (line and column) in a text file."""
-
- def __init__(self, line=-1, column=-1):
- self.line = line
- self.column = column
-
- def __eq__(self, rhs):
- return self.line == rhs.line and self.column == rhs.column
-
- def __ne__(self, rhs):
- return not self == rhs
-
- def __lt__(self, rhs):
- return self.line < rhs.line or (
- self.line == rhs.line and self.column < rhs.column)
-
- def __le__(self, rhs):
- return self < rhs or self == rhs
-
- def __gt__(self, rhs):
- return rhs < self
-
- def __ge__(self, rhs):
- return rhs <= self
-
- def __str__(self):
- if self == Eof():
- return 'EOF'
- else:
- return '%s(%s)' % (self.line + 1, self.column)
-
- def __add__(self, offset):
- return Cursor(self.line, self.column + offset)
-
- def __sub__(self, offset):
- return Cursor(self.line, self.column - offset)
-
- def Clone(self):
- """Returns a copy of self."""
-
- return Cursor(self.line, self.column)
-
-
-# Special cursor to indicate the end-of-file.
-def Eof():
- """Returns the special cursor to denote the end-of-file."""
- return Cursor(-1, -1)
-
-
-class Token:
- """Represents a token in a Pump source file."""
-
- def __init__(self, start=None, end=None, value=None, token_type=None):
- if start is None:
- self.start = Eof()
- else:
- self.start = start
- if end is None:
- self.end = Eof()
- else:
- self.end = end
- self.value = value
- self.token_type = token_type
-
- def __str__(self):
- return 'Token @%s: \'%s\' type=%s' % (
- self.start, self.value, self.token_type)
-
- def Clone(self):
- """Returns a copy of self."""
-
- return Token(self.start.Clone(), self.end.Clone(), self.value,
- self.token_type)
-
-
-def StartsWith(lines, pos, string):
- """Returns True iff the given position in lines starts with 'string'."""
-
- return lines[pos.line][pos.column:].startswith(string)
-
-
-def FindFirstInLine(line, token_table):
- best_match_start = -1
- for (regex, token_type) in token_table:
- m = regex.search(line)
- if m:
- # We found regex in lines
- if best_match_start < 0 or m.start() < best_match_start:
- best_match_start = m.start()
- best_match_length = m.end() - m.start()
- best_match_token_type = token_type
-
- if best_match_start < 0:
- return None
-
- return (best_match_start, best_match_length, best_match_token_type)
-
-
-def FindFirst(lines, token_table, cursor):
- """Finds the first occurrence of any string in strings in lines."""
-
- start = cursor.Clone()
- cur_line_number = cursor.line
- for line in lines[start.line:]:
- if cur_line_number == start.line:
- line = line[start.column:]
- m = FindFirstInLine(line, token_table)
- if m:
- # We found a regex in line.
- (start_column, length, token_type) = m
- if cur_line_number == start.line:
- start_column += start.column
- found_start = Cursor(cur_line_number, start_column)
- found_end = found_start + length
- return MakeToken(lines, found_start, found_end, token_type)
- cur_line_number += 1
- # We failed to find str in lines
- return None
-
-
-def SubString(lines, start, end):
- """Returns a substring in lines."""
-
- if end == Eof():
- end = Cursor(len(lines) - 1, len(lines[-1]))
-
- if start >= end:
- return ''
-
- if start.line == end.line:
- return lines[start.line][start.column:end.column]
-
- result_lines = ([lines[start.line][start.column:]] +
- lines[start.line + 1:end.line] +
- [lines[end.line][:end.column]])
- return ''.join(result_lines)
-
-
-def StripMetaComments(str):
- """Strip meta comments from each line in the given string."""
-
- # First, completely remove lines containing nothing but a meta
- # comment, including the trailing \n.
- str = re.sub(r'^\s*\$\$.*\n', '', str)
-
- # Then, remove meta comments from contentful lines.
- return re.sub(r'\s*\$\$.*', '', str)
-
-
-def MakeToken(lines, start, end, token_type):
- """Creates a new instance of Token."""
-
- return Token(start, end, SubString(lines, start, end), token_type)
-
-
-def ParseToken(lines, pos, regex, token_type):
- line = lines[pos.line][pos.column:]
- m = regex.search(line)
- if m and not m.start():
- return MakeToken(lines, pos, pos + m.end(), token_type)
- else:
- print('ERROR: %s expected at %s.' % (token_type, pos))
- sys.exit(1)
-
-
-ID_REGEX = re.compile(r'[_A-Za-z]\w*')
-EQ_REGEX = re.compile(r'=')
-REST_OF_LINE_REGEX = re.compile(r'.*?(?=$|\$\$)')
-OPTIONAL_WHITE_SPACES_REGEX = re.compile(r'\s*')
-WHITE_SPACE_REGEX = re.compile(r'\s')
-DOT_DOT_REGEX = re.compile(r'\.\.')
-
-
-def Skip(lines, pos, regex):
- line = lines[pos.line][pos.column:]
- m = re.search(regex, line)
- if m and not m.start():
- return pos + m.end()
- else:
- return pos
-
-
-def SkipUntil(lines, pos, regex, token_type):
- line = lines[pos.line][pos.column:]
- m = re.search(regex, line)
- if m:
- return pos + m.start()
- else:
- print ('ERROR: %s expected on line %s after column %s.' %
- (token_type, pos.line + 1, pos.column))
- sys.exit(1)
-
-
-def ParseExpTokenInParens(lines, pos):
- def ParseInParens(pos):
- pos = Skip(lines, pos, OPTIONAL_WHITE_SPACES_REGEX)
- pos = Skip(lines, pos, r'\(')
- pos = Parse(pos)
- pos = Skip(lines, pos, r'\)')
- return pos
-
- def Parse(pos):
- pos = SkipUntil(lines, pos, r'\(|\)', ')')
- if SubString(lines, pos, pos + 1) == '(':
- pos = Parse(pos + 1)
- pos = Skip(lines, pos, r'\)')
- return Parse(pos)
- else:
- return pos
-
- start = pos.Clone()
- pos = ParseInParens(pos)
- return MakeToken(lines, start, pos, 'exp')
-
-
-def RStripNewLineFromToken(token):
- if token.value.endswith('\n'):
- return Token(token.start, token.end, token.value[:-1], token.token_type)
- else:
- return token
-
-
-def TokenizeLines(lines, pos):
- while True:
- found = FindFirst(lines, TOKEN_TABLE, pos)
- if not found:
- yield MakeToken(lines, pos, Eof(), 'code')
- return
-
- if found.start == pos:
- prev_token = None
- prev_token_rstripped = None
- else:
- prev_token = MakeToken(lines, pos, found.start, 'code')
- prev_token_rstripped = RStripNewLineFromToken(prev_token)
-
- if found.token_type == '$var':
- if prev_token_rstripped:
- yield prev_token_rstripped
- yield found
- id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
- yield id_token
- pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
-
- eq_token = ParseToken(lines, pos, EQ_REGEX, '=')
- yield eq_token
- pos = Skip(lines, eq_token.end, r'\s*')
-
- if SubString(lines, pos, pos + 2) != '[[':
- exp_token = ParseToken(lines, pos, REST_OF_LINE_REGEX, 'exp')
- yield exp_token
- pos = Cursor(exp_token.end.line + 1, 0)
- elif found.token_type == '$for':
- if prev_token_rstripped:
- yield prev_token_rstripped
- yield found
- id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
- yield id_token
- pos = Skip(lines, id_token.end, WHITE_SPACE_REGEX)
- elif found.token_type == '$range':
- if prev_token_rstripped:
- yield prev_token_rstripped
- yield found
- id_token = ParseToken(lines, found.end, ID_REGEX, 'id')
- yield id_token
- pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX)
-
- dots_pos = SkipUntil(lines, pos, DOT_DOT_REGEX, '..')
- yield MakeToken(lines, pos, dots_pos, 'exp')
- yield MakeToken(lines, dots_pos, dots_pos + 2, '..')
- pos = dots_pos + 2
- new_pos = Cursor(pos.line + 1, 0)
- yield MakeToken(lines, pos, new_pos, 'exp')
- pos = new_pos
- elif found.token_type == '$':
- if prev_token:
- yield prev_token
- yield found
- exp_token = ParseExpTokenInParens(lines, found.end)
- yield exp_token
- pos = exp_token.end
- elif (found.token_type == ']]' or found.token_type == '$if' or
- found.token_type == '$elif' or found.token_type == '$else'):
- if prev_token_rstripped:
- yield prev_token_rstripped
- yield found
- pos = found.end
- else:
- if prev_token:
- yield prev_token
- yield found
- pos = found.end
-
-
-def Tokenize(s):
- """A generator that yields the tokens in the given string."""
- if s != '':
- lines = s.splitlines(True)
- for token in TokenizeLines(lines, Cursor(0, 0)):
- yield token
-
-
-class CodeNode:
- def __init__(self, atomic_code_list=None):
- self.atomic_code = atomic_code_list
-
-
-class VarNode:
- def __init__(self, identifier=None, atomic_code=None):
- self.identifier = identifier
- self.atomic_code = atomic_code
-
-
-class RangeNode:
- def __init__(self, identifier=None, exp1=None, exp2=None):
- self.identifier = identifier
- self.exp1 = exp1
- self.exp2 = exp2
-
-
-class ForNode:
- def __init__(self, identifier=None, sep=None, code=None):
- self.identifier = identifier
- self.sep = sep
- self.code = code
-
-
-class ElseNode:
- def __init__(self, else_branch=None):
- self.else_branch = else_branch
-
-
-class IfNode:
- def __init__(self, exp=None, then_branch=None, else_branch=None):
- self.exp = exp
- self.then_branch = then_branch
- self.else_branch = else_branch
-
-
-class RawCodeNode:
- def __init__(self, token=None):
- self.raw_code = token
-
-
-class LiteralDollarNode:
- def __init__(self, token):
- self.token = token
-
-
-class ExpNode:
- def __init__(self, token, python_exp):
- self.token = token
- self.python_exp = python_exp
-
-
-def PopFront(a_list):
- head = a_list[0]
- a_list[:1] = []
- return head
-
-
-def PushFront(a_list, elem):
- a_list[:0] = [elem]
-
-
-def PopToken(a_list, token_type=None):
- token = PopFront(a_list)
- if token_type is not None and token.token_type != token_type:
- print('ERROR: %s expected at %s' % (token_type, token.start))
- print('ERROR: %s found instead' % (token,))
- sys.exit(1)
-
- return token
-
-
-def PeekToken(a_list):
- if not a_list:
- return None
-
- return a_list[0]
-
-
-def ParseExpNode(token):
- python_exp = re.sub(r'([_A-Za-z]\w*)', r'self.GetValue("\1")', token.value)
- return ExpNode(token, python_exp)
-
-
-def ParseElseNode(tokens):
- def Pop(token_type=None):
- return PopToken(tokens, token_type)
-
- next = PeekToken(tokens)
- if not next:
- return None
- if next.token_type == '$else':
- Pop('$else')
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- return code_node
- elif next.token_type == '$elif':
- Pop('$elif')
- exp = Pop('code')
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- inner_else_node = ParseElseNode(tokens)
- return CodeNode([IfNode(ParseExpNode(exp), code_node, inner_else_node)])
- elif not next.value.strip():
- Pop('code')
- return ParseElseNode(tokens)
- else:
- return None
-
-
-def ParseAtomicCodeNode(tokens):
- def Pop(token_type=None):
- return PopToken(tokens, token_type)
-
- head = PopFront(tokens)
- t = head.token_type
- if t == 'code':
- return RawCodeNode(head)
- elif t == '$var':
- id_token = Pop('id')
- Pop('=')
- next = PeekToken(tokens)
- if next.token_type == 'exp':
- exp_token = Pop()
- return VarNode(id_token, ParseExpNode(exp_token))
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- return VarNode(id_token, code_node)
- elif t == '$for':
- id_token = Pop('id')
- next_token = PeekToken(tokens)
- if next_token.token_type == 'code':
- sep_token = next_token
- Pop('code')
- else:
- sep_token = None
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- return ForNode(id_token, sep_token, code_node)
- elif t == '$if':
- exp_token = Pop('code')
- Pop('[[')
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- else_node = ParseElseNode(tokens)
- return IfNode(ParseExpNode(exp_token), code_node, else_node)
- elif t == '$range':
- id_token = Pop('id')
- exp1_token = Pop('exp')
- Pop('..')
- exp2_token = Pop('exp')
- return RangeNode(id_token, ParseExpNode(exp1_token),
- ParseExpNode(exp2_token))
- elif t == '$id':
- return ParseExpNode(Token(head.start + 1, head.end, head.value[1:], 'id'))
- elif t == '$($)':
- return LiteralDollarNode(head)
- elif t == '$':
- exp_token = Pop('exp')
- return ParseExpNode(exp_token)
- elif t == '[[':
- code_node = ParseCodeNode(tokens)
- Pop(']]')
- return code_node
- else:
- PushFront(tokens, head)
- return None
-
-
-def ParseCodeNode(tokens):
- atomic_code_list = []
- while True:
- if not tokens:
- break
- atomic_code_node = ParseAtomicCodeNode(tokens)
- if atomic_code_node:
- atomic_code_list.append(atomic_code_node)
- else:
- break
- return CodeNode(atomic_code_list)
-
-
-def ParseToAST(pump_src_text):
- """Convert the given Pump source text into an AST."""
- tokens = list(Tokenize(pump_src_text))
- code_node = ParseCodeNode(tokens)
- return code_node
-
-
-class Env:
- def __init__(self):
- self.variables = []
- self.ranges = []
-
- def Clone(self):
- clone = Env()
- clone.variables = self.variables[:]
- clone.ranges = self.ranges[:]
- return clone
-
- def PushVariable(self, var, value):
- # If value looks like an int, store it as an int.
- try:
- int_value = int(value)
- if ('%s' % int_value) == value:
- value = int_value
- except Exception:
- pass
- self.variables[:0] = [(var, value)]
-
- def PopVariable(self):
- self.variables[:1] = []
-
- def PushRange(self, var, lower, upper):
- self.ranges[:0] = [(var, lower, upper)]
-
- def PopRange(self):
- self.ranges[:1] = []
-
- def GetValue(self, identifier):
- for (var, value) in self.variables:
- if identifier == var:
- return value
-
- print('ERROR: meta variable %s is undefined.' % (identifier,))
- sys.exit(1)
-
- def EvalExp(self, exp):
- try:
- result = eval(exp.python_exp)
- except Exception as e: # pylint: disable=broad-except
- print('ERROR: caught exception %s: %s' % (e.__class__.__name__, e))
- print('ERROR: failed to evaluate meta expression %s at %s' %
- (exp.python_exp, exp.token.start))
- sys.exit(1)
- return result
-
- def GetRange(self, identifier):
- for (var, lower, upper) in self.ranges:
- if identifier == var:
- return (lower, upper)
-
- print('ERROR: range %s is undefined.' % (identifier,))
- sys.exit(1)
-
-
-class Output:
- def __init__(self):
- self.string = ''
-
- def GetLastLine(self):
- index = self.string.rfind('\n')
- if index < 0:
- return ''
-
- return self.string[index + 1:]
-
- def Append(self, s):
- self.string += s
-
-
-def RunAtomicCode(env, node, output):
- if isinstance(node, VarNode):
- identifier = node.identifier.value.strip()
- result = Output()
- RunAtomicCode(env.Clone(), node.atomic_code, result)
- value = result.string
- env.PushVariable(identifier, value)
- elif isinstance(node, RangeNode):
- identifier = node.identifier.value.strip()
- lower = int(env.EvalExp(node.exp1))
- upper = int(env.EvalExp(node.exp2))
- env.PushRange(identifier, lower, upper)
- elif isinstance(node, ForNode):
- identifier = node.identifier.value.strip()
- if node.sep is None:
- sep = ''
- else:
- sep = node.sep.value
- (lower, upper) = env.GetRange(identifier)
- for i in range(lower, upper + 1):
- new_env = env.Clone()
- new_env.PushVariable(identifier, i)
- RunCode(new_env, node.code, output)
- if i != upper:
- output.Append(sep)
- elif isinstance(node, RawCodeNode):
- output.Append(node.raw_code.value)
- elif isinstance(node, IfNode):
- cond = env.EvalExp(node.exp)
- if cond:
- RunCode(env.Clone(), node.then_branch, output)
- elif node.else_branch is not None:
- RunCode(env.Clone(), node.else_branch, output)
- elif isinstance(node, ExpNode):
- value = env.EvalExp(node)
- output.Append('%s' % (value,))
- elif isinstance(node, LiteralDollarNode):
- output.Append('$')
- elif isinstance(node, CodeNode):
- RunCode(env.Clone(), node, output)
- else:
- print('BAD')
- print(node)
- sys.exit(1)
-
-
-def RunCode(env, code_node, output):
- for atomic_code in code_node.atomic_code:
- RunAtomicCode(env, atomic_code, output)
-
-
-def IsSingleLineComment(cur_line):
- return '//' in cur_line
-
-
-def IsInPreprocessorDirective(prev_lines, cur_line):
- if cur_line.lstrip().startswith('#'):
- return True
- return prev_lines and prev_lines[-1].endswith('\\')
-
-
-def WrapComment(line, output):
- loc = line.find('//')
- before_comment = line[:loc].rstrip()
- if before_comment == '':
- indent = loc
- else:
- output.append(before_comment)
- indent = len(before_comment) - len(before_comment.lstrip())
- prefix = indent*' ' + '// '
- max_len = 80 - len(prefix)
- comment = line[loc + 2:].strip()
- segs = [seg for seg in re.split(r'(\w+\W*)', comment) if seg != '']
- cur_line = ''
- for seg in segs:
- if len((cur_line + seg).rstrip()) < max_len:
- cur_line += seg
- else:
- if cur_line.strip() != '':
- output.append(prefix + cur_line.rstrip())
- cur_line = seg.lstrip()
- if cur_line.strip() != '':
- output.append(prefix + cur_line.strip())
-
-
-def WrapCode(line, line_concat, output):
- indent = len(line) - len(line.lstrip())
- prefix = indent*' ' # Prefix of the current line
- max_len = 80 - indent - len(line_concat) # Maximum length of the current line
- new_prefix = prefix + 4*' ' # Prefix of a continuation line
- new_max_len = max_len - 4 # Maximum length of a continuation line
- # Prefers to wrap a line after a ',' or ';'.
- segs = [seg for seg in re.split(r'([^,;]+[,;]?)', line.strip()) if seg != '']
- cur_line = '' # The current line without leading spaces.
- for seg in segs:
- # If the line is still too long, wrap at a space.
- while cur_line == '' and len(seg.strip()) > max_len:
- seg = seg.lstrip()
- split_at = seg.rfind(' ', 0, max_len)
- output.append(prefix + seg[:split_at].strip() + line_concat)
- seg = seg[split_at + 1:]
- prefix = new_prefix
- max_len = new_max_len
-
- if len((cur_line + seg).rstrip()) < max_len:
- cur_line = (cur_line + seg).lstrip()
- else:
- output.append(prefix + cur_line.rstrip() + line_concat)
- prefix = new_prefix
- max_len = new_max_len
- cur_line = seg.lstrip()
- if cur_line.strip() != '':
- output.append(prefix + cur_line.strip())
-
-
-def WrapPreprocessorDirective(line, output):
- WrapCode(line, ' \\', output)
-
-
-def WrapPlainCode(line, output):
- WrapCode(line, '', output)
-
-
-def IsMultiLineIWYUPragma(line):
- return re.search(r'/\* IWYU pragma: ', line)
-
-
-def IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
- return (re.match(r'^#(ifndef|define|endif\s*//)\s*[\w_]+\s*$', line) or
- re.match(r'^#include\s', line) or
- # Don't break IWYU pragmas, either; that causes iwyu.py problems.
- re.search(r'// IWYU pragma: ', line))
-
-
-def WrapLongLine(line, output):
- line = line.rstrip()
- if len(line) <= 80:
- output.append(line)
- elif IsSingleLineComment(line):
- if IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
- # The style guide made an exception to allow long header guard lines,
- # includes and IWYU pragmas.
- output.append(line)
- else:
- WrapComment(line, output)
- elif IsInPreprocessorDirective(output, line):
- if IsHeaderGuardIncludeOrOneLineIWYUPragma(line):
- # The style guide made an exception to allow long header guard lines,
- # includes and IWYU pragmas.
- output.append(line)
- else:
- WrapPreprocessorDirective(line, output)
- elif IsMultiLineIWYUPragma(line):
- output.append(line)
- else:
- WrapPlainCode(line, output)
-
-
-def BeautifyCode(string):
- lines = string.splitlines()
- output = []
- for line in lines:
- WrapLongLine(line, output)
- output2 = [line.rstrip() for line in output]
- return '\n'.join(output2) + '\n'
-
-
-def ConvertFromPumpSource(src_text):
- """Return the text generated from the given Pump source text."""
- ast = ParseToAST(StripMetaComments(src_text))
- output = Output()
- RunCode(Env(), ast, output)
- return BeautifyCode(output.string)
-
-
-def main(argv):
- if len(argv) == 1:
- print(__doc__)
- sys.exit(1)
-
- file_path = argv[-1]
- output_str = ConvertFromPumpSource(io.open(file_path, 'r').read())
- if file_path.endswith('.pump'):
- output_file_path = file_path[:-5]
- else:
- output_file_path = '-'
- if output_file_path == '-':
- print(output_str,)
- else:
- output_file = io.open(output_file_path, 'w')
- output_file.write(u'// This file was GENERATED by command:\n')
- output_file.write(u'// %s %s\n' %
- (os.path.basename(__file__), os.path.basename(file_path)))
- output_file.write(u'// DO NOT EDIT BY HAND!!!\n\n')
- output_file.write(output_str)
- output_file.close()
-
-
-if __name__ == '__main__':
- main(sys.argv)
diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc
index 4a3f7af2..dded437a 100644
--- a/googlemock/src/gmock-matchers.cc
+++ b/googlemock/src/gmock-matchers.cc
@@ -34,7 +34,6 @@
// utilities for defining matchers.
#include "gmock/gmock-matchers.h"
-#include "gmock/gmock-generated-matchers.h"
#include <string.h>
#include <iostream>
@@ -219,8 +218,6 @@ class MaxBipartiteMatchState {
// right_[left_[i]] = i.
::std::vector<size_t> left_;
::std::vector<size_t> right_;
-
- GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
};
const size_t MaxBipartiteMatchState::kUnused;
diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc
index 81ea9894..c7266a37 100644
--- a/googlemock/src/gmock-spec-builders.cc
+++ b/googlemock/src/gmock-spec-builders.cc
@@ -295,8 +295,8 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
"call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See "
- "https://github.com/google/googletest/blob/master/googlemock/"
- "docs/cook_book.md#"
+ "https://github.com/google/googletest/blob/master/docs/"
+ "gmock_cook_book.md#"
"knowing-when-to-expect for details.\n",
stack_frames_to_skip);
break;
@@ -433,10 +433,10 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
// The UntypedFindMatchingExpectation() function acquires and
// releases g_gmock_mutex.
+
const ExpectationBase* const untyped_expectation =
- this->UntypedFindMatchingExpectation(
- untyped_args, &untyped_action, &is_excessive,
- &ss, &why);
+ this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
+ &is_excessive, &ss, &why);
const bool found = untyped_expectation != nullptr;
// True if and only if we need to print the call's arguments
@@ -461,26 +461,42 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
untyped_expectation->DescribeLocationTo(&loc);
}
- UntypedActionResultHolderBase* const result =
- untyped_action == nullptr
- ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
- : this->UntypedPerformAction(untyped_action, untyped_args);
- if (result != nullptr) result->PrintAsActionResult(&ss);
- ss << "\n" << why.str();
-
- if (!found) {
- // No expectation matches this call - reports a failure.
- Expect(false, nullptr, -1, ss.str());
- } else if (is_excessive) {
- // We had an upper-bound violation and the failure message is in ss.
- Expect(false, untyped_expectation->file(),
- untyped_expectation->line(), ss.str());
- } else {
- // We had an expected call and the matching expectation is
- // described in ss.
- Log(kInfo, loc.str() + ss.str(), 2);
+ UntypedActionResultHolderBase* result = nullptr;
+
+ auto perform_action = [&] {
+ return untyped_action == nullptr
+ ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
+ : this->UntypedPerformAction(untyped_action, untyped_args);
+ };
+ auto handle_failures = [&] {
+ ss << "\n" << why.str();
+
+ if (!found) {
+ // No expectation matches this call - reports a failure.
+ Expect(false, nullptr, -1, ss.str());
+ } else if (is_excessive) {
+ // We had an upper-bound violation and the failure message is in ss.
+ Expect(false, untyped_expectation->file(), untyped_expectation->line(),
+ ss.str());
+ } else {
+ // We had an expected call and the matching expectation is
+ // described in ss.
+ Log(kInfo, loc.str() + ss.str(), 2);
+ }
+ };
+#if GTEST_HAS_EXCEPTIONS
+ try {
+ result = perform_action();
+ } catch (...) {
+ handle_failures();
+ throw;
}
+#else
+ result = perform_action();
+#endif
+ if (result != nullptr) result->PrintAsActionResult(&ss);
+ handle_failures();
return result;
}
@@ -624,7 +640,7 @@ class MockObjectRegistry {
if (leaked_count > 0) {
std::cout << "\nERROR: " << leaked_count << " leaked mock "
<< (leaked_count == 1 ? "object" : "objects")
- << " found at program exit. Expectations on a mock object is "
+ << " found at program exit. Expectations on a mock object are "
"verified when the object is destructed. Leaking a mock "
"means that its expectations aren't verified, which is "
"usually a test bug. If you really intend to leak a mock, "
diff --git a/googlemock/src/gmock.cc b/googlemock/src/gmock.cc
index 32b2a739..7bcdb0ba 100644
--- a/googlemock/src/gmock.cc
+++ b/googlemock/src/gmock.cc
@@ -124,7 +124,7 @@ static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
}
static bool ParseGoogleMockIntFlag(const char* str, const char* flag,
- int* value) {
+ int32_t* value) {
// Gets the value of the flag as a string.
const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
diff --git a/googlemock/test/Android.bp b/googlemock/test/Android.bp
index c288fa7d..17c5bca8 100644
--- a/googlemock/test/Android.bp
+++ b/googlemock/test/Android.bp
@@ -12,6 +12,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "external_googletest_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-BSD
+ default_applicable_licenses: ["external_googletest_license"],
+}
+
cc_defaults {
name: "gmock_test_defaults",
host_supported: true,
@@ -45,9 +54,6 @@ cc_test {
// Test is disabled because Android doesn't build gmock with exceptions.
//"gmock_ex_test.cc",
- "gmock-generated-actions_test.cc",
- "gmock-generated-function-mockers_test.cc",
- "gmock-generated-matchers_test.cc",
"gmock-internal-utils_test.cc",
"gmock-matchers_test.cc",
"gmock-more-actions_test.cc",
diff --git a/googlemock/test/BUILD.bazel b/googlemock/test/BUILD.bazel
index da95ed58..1f7bd067 100644
--- a/googlemock/test/BUILD.bazel
+++ b/googlemock/test/BUILD.bazel
@@ -28,8 +28,6 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
-# Author: misterg@google.com (Gennadiy Civil)
-#
# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
@@ -54,6 +52,9 @@ py_library(
name = "gmock_test_utils",
testonly = 1,
srcs = ["gmock_test_utils.py"],
+ deps = [
+ "//googletest/test:gtest_test_utils",
+ ],
)
cc_binary(
@@ -71,6 +72,10 @@ py_test(
":gmock_leak_test_",
":gmock_test_utils",
],
+ tags = [
+ "no_test_msvc2015",
+ "no_test_msvc2017",
+ ],
)
cc_test(
@@ -99,6 +104,10 @@ py_test(
":gmock_output_test_golden.txt",
],
python_version = "PY2",
+ tags = [
+ "no_test_msvc2015",
+ "no_test_msvc2017",
+ ],
deps = [":gmock_test_utils"],
)
diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc
index 58a2d35a..e1ca7fe2 100644
--- a/googlemock/test/gmock-actions_test.cc
+++ b/googlemock/test/gmock-actions_test.cc
@@ -32,11 +32,13 @@
//
// This file tests the built-in actions.
-// Silence C4800 (C4800: 'int *const ': forcing value
-// to bool 'true' or 'false') for MSVC 15
+// Silence C4100 (unreferenced formal parameter) for MSVC
#ifdef _MSC_VER
-#if _MSC_VER == 1900
# pragma warning(push)
+# pragma warning(disable:4100)
+#if _MSC_VER == 1900
+// and silence C4800 (C4800: 'int *const ': forcing value
+// to bool 'true' or 'false') for MSVC 15
# pragma warning(disable:4800)
#endif
#endif
@@ -54,35 +56,34 @@
namespace {
-// This list should be kept sorted.
-using testing::_;
-using testing::Action;
-using testing::ActionInterface;
-using testing::Assign;
-using testing::ByMove;
-using testing::ByRef;
-using testing::DefaultValue;
-using testing::DoAll;
-using testing::DoDefault;
-using testing::IgnoreResult;
-using testing::Invoke;
-using testing::InvokeWithoutArgs;
-using testing::MakePolymorphicAction;
-using testing::Ne;
-using testing::PolymorphicAction;
-using testing::Return;
-using testing::ReturnNull;
-using testing::ReturnRef;
-using testing::ReturnRefOfCopy;
-using testing::ReturnRoundRobin;
-using testing::SetArgPointee;
-using testing::SetArgumentPointee;
-using testing::Unused;
-using testing::WithArgs;
-using testing::internal::BuiltInDefaultValue;
+using ::testing::_;
+using ::testing::Action;
+using ::testing::ActionInterface;
+using ::testing::Assign;
+using ::testing::ByMove;
+using ::testing::ByRef;
+using ::testing::DefaultValue;
+using ::testing::DoAll;
+using ::testing::DoDefault;
+using ::testing::IgnoreResult;
+using ::testing::Invoke;
+using ::testing::InvokeWithoutArgs;
+using ::testing::MakePolymorphicAction;
+using ::testing::PolymorphicAction;
+using ::testing::Return;
+using ::testing::ReturnNew;
+using ::testing::ReturnNull;
+using ::testing::ReturnRef;
+using ::testing::ReturnRefOfCopy;
+using ::testing::ReturnRoundRobin;
+using ::testing::SetArgPointee;
+using ::testing::SetArgumentPointee;
+using ::testing::Unused;
+using ::testing::WithArgs;
+using ::testing::internal::BuiltInDefaultValue;
#if !GTEST_OS_WINDOWS_MOBILE
-using testing::SetErrnoAndReturn;
+using ::testing::SetErrnoAndReturn;
#endif
// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
@@ -575,8 +576,6 @@ class FromType {
private:
bool* const converted_;
-
- GTEST_DISALLOW_ASSIGN_(FromType);
};
class ToType {
@@ -796,7 +795,7 @@ TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
}
// Tests that DoDefault() returns the default value set by
-// DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
+// DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
DefaultValue<int>::Set(1);
MockClass mock;
@@ -1292,6 +1291,52 @@ TEST(ByRefTest, PrintsCorrectly) {
EXPECT_EQ(expected.str(), actual.str());
}
+struct UnaryConstructorClass {
+ explicit UnaryConstructorClass(int v) : value(v) {}
+ int value;
+};
+
+// Tests using ReturnNew() with a unary constructor.
+TEST(ReturnNewTest, Unary) {
+ Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
+ UnaryConstructorClass* c = a.Perform(std::make_tuple());
+ EXPECT_EQ(4000, c->value);
+ delete c;
+}
+
+TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
+ Action<UnaryConstructorClass*(bool, int)> a =
+ ReturnNew<UnaryConstructorClass>(4000);
+ UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
+ EXPECT_EQ(4000, c->value);
+ delete c;
+}
+
+TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
+ Action<const UnaryConstructorClass*()> a =
+ ReturnNew<UnaryConstructorClass>(4000);
+ const UnaryConstructorClass* c = a.Perform(std::make_tuple());
+ EXPECT_EQ(4000, c->value);
+ delete c;
+}
+
+class TenArgConstructorClass {
+ public:
+ TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
+ int a8, int a9, int a10)
+ : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
+ int value_;
+};
+
+// Tests using ReturnNew() with a 10-argument constructor.
+TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
+ Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(
+ 1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,
+ 0);
+ TenArgConstructorClass* c = a.Perform(std::make_tuple());
+ EXPECT_EQ(1234567890, c->value_);
+ delete c;
+}
std::unique_ptr<int> UniquePtrSource() {
return std::unique_ptr<int>(new int(19));
@@ -1470,8 +1515,19 @@ TEST(FunctorActionTest, TypeConversion) {
EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
// Also between the lambda and the action itself.
- const Action<bool(std::string)> x = [](Unused) { return 42; };
- EXPECT_TRUE(x.Perform(std::make_tuple("hello")));
+ const Action<bool(std::string)> x1 = [](Unused) { return 42; };
+ const Action<bool(std::string)> x2 = [] { return 42; };
+ EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));
+ EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));
+
+ // Ensure decay occurs where required.
+ std::function<int()> f = [] { return 7; };
+ Action<int(int)> d = f;
+ f = nullptr;
+ EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
+
+ // Ensure creation of an empty action succeeds.
+ Action<void(int)>(nullptr);
}
TEST(FunctorActionTest, UnusedArguments) {
@@ -1496,6 +1552,26 @@ TEST(MoveOnlyArgumentsTest, ReturningActions) {
EXPECT_EQ(x, 3);
}
+ACTION(ReturnArity) {
+ return std::tuple_size<args_type>::value;
+}
+
+TEST(ActionMacro, LargeArity) {
+ EXPECT_EQ(
+ 1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));
+ EXPECT_EQ(
+ 10,
+ testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(
+ ReturnArity())
+ .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));
+ EXPECT_EQ(
+ 20,
+ testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,
+ int, int, int, int, int, int, int, int, int)>(
+ ReturnArity())
+ .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
+ 14, 15, 16, 17, 18, 19)));
+}
} // Unnamed namespace
diff --git a/googlemock/test/gmock-function-mocker_nc.cc b/googlemock/test/gmock-function-mocker_nc.cc
deleted file mode 100644
index d38fe85e..00000000
--- a/googlemock/test/gmock-function-mocker_nc.cc
+++ /dev/null
@@ -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
diff --git a/googlemock/test/gmock-function-mocker_nc_test.py b/googlemock/test/gmock-function-mocker_nc_test.py
deleted file mode 100644
index 8ef6e09f..00000000
--- a/googlemock/test/gmock-function-mocker_nc_test.py
+++ /dev/null
@@ -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()
diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc
index 90d6b5f1..45a524e2 100644
--- a/googlemock/test/gmock-function-mocker_test.cc
+++ b/googlemock/test/gmock-function-mocker_test.cc
@@ -31,7 +31,7 @@
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the function mocker classes.
-#include "gmock/gmock-generated-function-mockers.h"
+#include "gmock/gmock-function-mocker.h"
#if GTEST_OS_WINDOWS
// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
@@ -40,6 +40,7 @@
# include <objbase.h>
#endif // GTEST_OS_WINDOWS
+#include <functional>
#include <map>
#include <string>
#include <type_traits>
@@ -107,6 +108,16 @@ class FooInterface {
using fn_ptr = int (*)(bool);
virtual fn_ptr ReturnsFunctionPointer2(int) = 0;
+ virtual int RefQualifiedConstRef() const& = 0;
+ virtual int RefQualifiedConstRefRef() const&& = 0;
+ virtual int RefQualifiedRef() & = 0;
+ virtual int RefQualifiedRefRef() && = 0;
+
+ virtual int RefQualifiedOverloaded() const& = 0;
+ virtual int RefQualifiedOverloaded() const&& = 0;
+ virtual int RefQualifiedOverloaded() & = 0;
+ virtual int RefQualifiedOverloaded() && = 0;
+
#if GTEST_OS_WINDOWS
STDMETHOD_(int, CTNullary)() = 0;
STDMETHOD_(bool, CTUnary)(int x) = 0;
@@ -180,189 +191,301 @@ class MockFoo : public FooInterface {
(Calltype(STDMETHODCALLTYPE)));
#endif // GTEST_OS_WINDOWS
+ // Test reference qualified functions.
+ MOCK_METHOD(int, RefQualifiedConstRef, (), (const, ref(&), override));
+ MOCK_METHOD(int, RefQualifiedConstRefRef, (), (const, ref(&&), override));
+ MOCK_METHOD(int, RefQualifiedRef, (), (ref(&), override));
+ MOCK_METHOD(int, RefQualifiedRefRef, (), (ref(&&), override));
+
+ MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&), override));
+ MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&&), override));
+ MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&), override));
+ MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&&), override));
+
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
};
+
+class LegacyMockFoo : public FooInterface {
+ public:
+ LegacyMockFoo() {}
+
+ // Makes sure that a mock function parameter can be named.
+ MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
+
+ MOCK_METHOD0(Nullary, int()); // NOLINT
+
+ // Makes sure that a mock function parameter can be unnamed.
+ MOCK_METHOD1(Unary, bool(int)); // NOLINT
+ MOCK_METHOD2(Binary, long(short, int)); // NOLINT
+ MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT
+ double, unsigned, char*, const std::string& str));
+
+ MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
+ MOCK_METHOD1(TakesConstReference, std::string(const int&));
+ MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT
+
+ // Tests that the function return type can contain unprotected comma.
+ MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());
+ MOCK_CONST_METHOD1(ReturnTypeWithComma,
+ std::map<int, std::string>(int)); // NOLINT
+
+ MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT
+ MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT
+
+ MOCK_METHOD1(OverloadedOnArgumentType, int(int)); // NOLINT
+ MOCK_METHOD1(OverloadedOnArgumentType, char(char)); // NOLINT
+
+ MOCK_METHOD0(OverloadedOnConstness, int()); // NOLINT
+ MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT
+
+ MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
+ MOCK_METHOD1(TypeWithComma,
+ int(const std::map<int, std::string>&)); // NOLINT
+ MOCK_METHOD1(TypeWithTemplatedCopyCtor,
+ int(const TemplatedCopyable<int>&)); // NOLINT
+
+ MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool));
+ MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int));
+
+#if GTEST_OS_WINDOWS
+ MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
+ MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); // NOLINT
+ MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
+ int(bool b, char c, short d, int e, // NOLINT
+ long f, float g, double h, // NOLINT
+ unsigned i, char* j, const std::string& k));
+ MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst,
+ char(int)); // NOLINT
+
+ // Tests that the function return type can contain unprotected comma.
+ MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
+ std::map<int, std::string>());
+#endif // GTEST_OS_WINDOWS
+
+ // We can't mock these with the old macros, but we need to define them to make
+ // it concrete.
+ int RefQualifiedConstRef() const& override { return 0; }
+ int RefQualifiedConstRefRef() const&& override { return 0; }
+ int RefQualifiedRef() & override { return 0; }
+ int RefQualifiedRefRef() && override { return 0; }
+ int RefQualifiedOverloaded() const& override { return 0; }
+ int RefQualifiedOverloaded() const&& override { return 0; }
+ int RefQualifiedOverloaded() & override { return 0; }
+ int RefQualifiedOverloaded() && override { return 0; }
+
+ private:
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockFoo);
+};
+
#ifdef _MSC_VER
# pragma warning(pop)
#endif
-class MockMethodFunctionMockerTest : public testing::Test {
+template <class T>
+class FunctionMockerTest : public testing::Test {
protected:
- MockMethodFunctionMockerTest() : foo_(&mock_foo_) {}
+ FunctionMockerTest() : foo_(&mock_foo_) {}
FooInterface* const foo_;
- MockFoo mock_foo_;
+ T mock_foo_;
};
+using FunctionMockerTestTypes = ::testing::Types<MockFoo, LegacyMockFoo>;
+TYPED_TEST_SUITE(FunctionMockerTest, FunctionMockerTestTypes);
// Tests mocking a void-returning function.
-TEST_F(MockMethodFunctionMockerTest, MocksVoidFunction) {
- EXPECT_CALL(mock_foo_, VoidReturning(Lt(100)));
- foo_->VoidReturning(0);
+TYPED_TEST(FunctionMockerTest, MocksVoidFunction) {
+ EXPECT_CALL(this->mock_foo_, VoidReturning(Lt(100)));
+ this->foo_->VoidReturning(0);
}
// Tests mocking a nullary function.
-TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunction) {
- EXPECT_CALL(mock_foo_, Nullary())
+TYPED_TEST(FunctionMockerTest, MocksNullaryFunction) {
+ EXPECT_CALL(this->mock_foo_, Nullary())
.WillOnce(DoDefault())
.WillOnce(Return(1));
- EXPECT_EQ(0, foo_->Nullary());
- EXPECT_EQ(1, foo_->Nullary());
+ EXPECT_EQ(0, this->foo_->Nullary());
+ EXPECT_EQ(1, this->foo_->Nullary());
}
// Tests mocking a unary function.
-TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunction) {
- EXPECT_CALL(mock_foo_, Unary(Eq(2)))
- .Times(2)
- .WillOnce(Return(true));
+TYPED_TEST(FunctionMockerTest, MocksUnaryFunction) {
+ EXPECT_CALL(this->mock_foo_, Unary(Eq(2))).Times(2).WillOnce(Return(true));
- EXPECT_TRUE(foo_->Unary(2));
- EXPECT_FALSE(foo_->Unary(2));
+ EXPECT_TRUE(this->foo_->Unary(2));
+ EXPECT_FALSE(this->foo_->Unary(2));
}
// Tests mocking a binary function.
-TEST_F(MockMethodFunctionMockerTest, MocksBinaryFunction) {
- EXPECT_CALL(mock_foo_, Binary(2, _))
- .WillOnce(Return(3));
+TYPED_TEST(FunctionMockerTest, MocksBinaryFunction) {
+ EXPECT_CALL(this->mock_foo_, Binary(2, _)).WillOnce(Return(3));
- EXPECT_EQ(3, foo_->Binary(2, 1));
+ EXPECT_EQ(3, this->foo_->Binary(2, 1));
}
// Tests mocking a decimal function.
-TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunction) {
- EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(),
- Lt(100), 5U, NULL, "hi"))
+TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) {
+ EXPECT_CALL(this->mock_foo_,
+ Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(5));
- EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
+ EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
}
// Tests mocking a function that takes a non-const reference.
-TEST_F(MockMethodFunctionMockerTest,
- MocksFunctionWithNonConstReferenceArgument) {
+TYPED_TEST(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
int a = 0;
- EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a)))
+ EXPECT_CALL(this->mock_foo_, TakesNonConstReference(Ref(a)))
.WillOnce(Return(true));
- EXPECT_TRUE(foo_->TakesNonConstReference(a));
+ EXPECT_TRUE(this->foo_->TakesNonConstReference(a));
}
// Tests mocking a function that takes a const reference.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
+TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
int a = 0;
- EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a)))
+ EXPECT_CALL(this->mock_foo_, TakesConstReference(Ref(a)))
.WillOnce(Return("Hello"));
- EXPECT_EQ("Hello", foo_->TakesConstReference(a));
+ EXPECT_EQ("Hello", this->foo_->TakesConstReference(a));
}
// Tests mocking a function that takes a const variable.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstArgument) {
- EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
- .WillOnce(DoDefault());
+TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstArgument) {
+ EXPECT_CALL(this->mock_foo_, TakesConst(Lt(10))).WillOnce(DoDefault());
- EXPECT_FALSE(foo_->TakesConst(5));
+ EXPECT_FALSE(this->foo_->TakesConst(5));
}
// Tests mocking functions overloaded on the number of arguments.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber())
+TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
+ EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber())
.WillOnce(Return(1));
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_))
+ EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber(_))
.WillOnce(Return(2));
- EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1));
- EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber());
+ EXPECT_EQ(2, this->foo_->OverloadedOnArgumentNumber(1));
+ EXPECT_EQ(1, this->foo_->OverloadedOnArgumentNumber());
}
// Tests mocking functions overloaded on the types of argument.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>()))
+TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
+ EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(An<int>()))
.WillOnce(Return(1));
- EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
+ EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
.WillOnce(Return('b'));
- EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0));
- EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a'));
+ EXPECT_EQ(1, this->foo_->OverloadedOnArgumentType(0));
+ EXPECT_EQ('b', this->foo_->OverloadedOnArgumentType('a'));
}
// Tests mocking functions overloaded on the const-ness of this object.
-TEST_F(MockMethodFunctionMockerTest,
- MocksFunctionsOverloadedOnConstnessOfThis) {
- EXPECT_CALL(mock_foo_, OverloadedOnConstness());
- EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
+TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
+ EXPECT_CALL(this->mock_foo_, OverloadedOnConstness());
+ EXPECT_CALL(Const(this->mock_foo_), OverloadedOnConstness())
.WillOnce(Return('a'));
- EXPECT_EQ(0, foo_->OverloadedOnConstness());
- EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
+ EXPECT_EQ(0, this->foo_->OverloadedOnConstness());
+ EXPECT_EQ('a', Const(*this->foo_).OverloadedOnConstness());
}
-TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithComma) {
+TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithComma) {
const std::map<int, std::string> a_map;
- EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
- .WillOnce(Return(a_map));
- EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
- .WillOnce(Return(a_map));
+ EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma()).WillOnce(Return(a_map));
+ EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma(42)).WillOnce(Return(a_map));
- EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
- EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
+ EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma());
+ EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma(42));
}
-TEST_F(MockMethodFunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
- EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true));
- EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
+TYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
+ EXPECT_CALL(this->mock_foo_, TypeWithTemplatedCopyCtor(_))
+ .WillOnce(Return(true));
+ EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
}
#if GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype.
-TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunctionWithCallType) {
- EXPECT_CALL(mock_foo_, CTNullary())
+TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
+ EXPECT_CALL(this->mock_foo_, CTNullary())
.WillOnce(Return(-1))
.WillOnce(Return(0));
- EXPECT_EQ(-1, foo_->CTNullary());
- EXPECT_EQ(0, foo_->CTNullary());
+ EXPECT_EQ(-1, this->foo_->CTNullary());
+ EXPECT_EQ(0, this->foo_->CTNullary());
}
// Tests mocking a unary function with calltype.
-TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunctionWithCallType) {
- EXPECT_CALL(mock_foo_, CTUnary(Eq(2)))
+TYPED_TEST(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
+ EXPECT_CALL(this->mock_foo_, CTUnary(Eq(2)))
.Times(2)
.WillOnce(Return(true))
.WillOnce(Return(false));
- EXPECT_TRUE(foo_->CTUnary(2));
- EXPECT_FALSE(foo_->CTUnary(2));
+ EXPECT_TRUE(this->foo_->CTUnary(2));
+ EXPECT_FALSE(this->foo_->CTUnary(2));
}
// Tests mocking a decimal function with calltype.
-TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunctionWithCallType) {
- EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
- Lt(100), 5U, NULL, "hi"))
+TYPED_TEST(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
+ EXPECT_CALL(this->mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
+ Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(10));
- EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
+ EXPECT_EQ(10, this->foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
}
// Tests mocking functions overloaded on the const-ness of this object.
-TEST_F(MockMethodFunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
- EXPECT_CALL(Const(mock_foo_), CTConst(_))
- .WillOnce(Return('a'));
+TYPED_TEST(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
+ EXPECT_CALL(Const(this->mock_foo_), CTConst(_)).WillOnce(Return('a'));
- EXPECT_EQ('a', Const(*foo_).CTConst(0));
+ EXPECT_EQ('a', Const(*this->foo_).CTConst(0));
}
-TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
+TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
const std::map<int, std::string> a_map;
- EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
- .WillOnce(Return(a_map));
+ EXPECT_CALL(this->mock_foo_, CTReturnTypeWithComma()).WillOnce(Return(a_map));
- EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
+ EXPECT_EQ(a_map, this->mock_foo_.CTReturnTypeWithComma());
}
#endif // GTEST_OS_WINDOWS
+TEST(FunctionMockerTest, RefQualified) {
+ MockFoo mock_foo;
+
+ EXPECT_CALL(mock_foo, RefQualifiedConstRef).WillOnce(Return(1));
+ EXPECT_CALL(std::move(mock_foo), // NOLINT
+ RefQualifiedConstRefRef)
+ .WillOnce(Return(2));
+ EXPECT_CALL(mock_foo, RefQualifiedRef).WillOnce(Return(3));
+ EXPECT_CALL(std::move(mock_foo), // NOLINT
+ RefQualifiedRefRef)
+ .WillOnce(Return(4));
+
+ EXPECT_CALL(static_cast<const MockFoo&>(mock_foo), RefQualifiedOverloaded())
+ .WillOnce(Return(5));
+ EXPECT_CALL(static_cast<const MockFoo&&>(mock_foo), RefQualifiedOverloaded())
+ .WillOnce(Return(6));
+ EXPECT_CALL(static_cast<MockFoo&>(mock_foo), RefQualifiedOverloaded())
+ .WillOnce(Return(7));
+ EXPECT_CALL(static_cast<MockFoo&&>(mock_foo), RefQualifiedOverloaded())
+ .WillOnce(Return(8));
+
+ EXPECT_EQ(mock_foo.RefQualifiedConstRef(), 1);
+ EXPECT_EQ(std::move(mock_foo).RefQualifiedConstRefRef(), 2); // NOLINT
+ EXPECT_EQ(mock_foo.RefQualifiedRef(), 3);
+ EXPECT_EQ(std::move(mock_foo).RefQualifiedRefRef(), 4); // NOLINT
+
+ EXPECT_EQ(std::cref(mock_foo).get().RefQualifiedOverloaded(), 5);
+ EXPECT_EQ(std::move(std::cref(mock_foo).get()) // NOLINT
+ .RefQualifiedOverloaded(),
+ 6);
+ EXPECT_EQ(mock_foo.RefQualifiedOverloaded(), 7);
+ EXPECT_EQ(std::move(mock_foo).RefQualifiedOverloaded(), 8); // NOLINT
+}
+
class MockB {
public:
MockB() {}
@@ -373,20 +496,33 @@ class MockB {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
};
+class LegacyMockB {
+ public:
+ LegacyMockB() {}
+
+ MOCK_METHOD0(DoB, void());
+
+ private:
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockB);
+};
+
+template <typename T>
+class ExpectCallTest : public ::testing::Test {};
+using ExpectCallTestTypes = ::testing::Types<MockB, LegacyMockB>;
+TYPED_TEST_SUITE(ExpectCallTest, ExpectCallTestTypes);
+
// Tests that functions with no EXPECT_CALL() rules can be called any
// number of times.
-TEST(MockMethodExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
- {
- MockB b;
- }
+TYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
+ { TypeParam b; }
{
- MockB b;
+ TypeParam b;
b.DoB();
}
{
- MockB b;
+ TypeParam b;
b.DoB();
b.DoB();
}
@@ -425,9 +561,33 @@ class MockStack : public StackInterface<T> {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
};
+template <typename T>
+class LegacyMockStack : public StackInterface<T> {
+ public:
+ LegacyMockStack() {}
+
+ MOCK_METHOD1_T(Push, void(const T& elem));
+ MOCK_METHOD0_T(Pop, void());
+ MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT
+ MOCK_CONST_METHOD0_T(GetTop, const T&());
+
+ // Tests that the function return type can contain unprotected comma.
+ MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
+ MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); // NOLINT
+
+ private:
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStack);
+};
+
+template <typename T>
+class TemplateMockTest : public ::testing::Test {};
+using TemplateMockTestTypes =
+ ::testing::Types<MockStack<int>, LegacyMockStack<int>>;
+TYPED_TEST_SUITE(TemplateMockTest, TemplateMockTestTypes);
+
// Tests that template mock works.
-TEST(MockMethodTemplateMockTest, Works) {
- MockStack<int> mock;
+TYPED_TEST(TemplateMockTest, Works) {
+ TypeParam mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
@@ -448,8 +608,8 @@ TEST(MockMethodTemplateMockTest, Works) {
EXPECT_EQ(0, mock.GetSize());
}
-TEST(MockMethodTemplateMockTest, MethodWithCommaInReturnTypeWorks) {
- MockStack<int> mock;
+TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
+ TypeParam mock;
const std::map<int, int> a_map;
EXPECT_CALL(mock, ReturnTypeWithComma())
@@ -493,9 +653,31 @@ class MockStackWithCallType : public StackInterfaceWithCallType<T> {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
};
+template <typename T>
+class LegacyMockStackWithCallType : public StackInterfaceWithCallType<T> {
+ public:
+ LegacyMockStackWithCallType() {}
+
+ MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
+ MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
+ MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
+ MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
+
+ private:
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStackWithCallType);
+};
+
+template <typename T>
+class TemplateMockTestWithCallType : public ::testing::Test {};
+using TemplateMockTestWithCallTypeTypes =
+ ::testing::Types<MockStackWithCallType<int>,
+ LegacyMockStackWithCallType<int>>;
+TYPED_TEST_SUITE(TemplateMockTestWithCallType,
+ TemplateMockTestWithCallTypeTypes);
+
// Tests that template mock with calltype works.
-TEST(MockMethodTemplateMockTestWithCallType, Works) {
- MockStackWithCallType<int> mock;
+TYPED_TEST(TemplateMockTestWithCallType, Works) {
+ TypeParam mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
@@ -522,6 +704,11 @@ TEST(MockMethodTemplateMockTestWithCallType, Works) {
MOCK_METHOD(int, Overloaded, (int), (const)); \
MOCK_METHOD(bool, Overloaded, (bool f, int n))
+#define LEGACY_MY_MOCK_METHODS1_ \
+ MOCK_METHOD0(Overloaded, void()); \
+ MOCK_CONST_METHOD1(Overloaded, int(int n)); \
+ MOCK_METHOD2(Overloaded, bool(bool f, int n))
+
class MockOverloadedOnArgNumber {
public:
MockOverloadedOnArgNumber() {}
@@ -532,8 +719,25 @@ class MockOverloadedOnArgNumber {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
};
-TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
- MockOverloadedOnArgNumber mock;
+class LegacyMockOverloadedOnArgNumber {
+ public:
+ LegacyMockOverloadedOnArgNumber() {}
+
+ LEGACY_MY_MOCK_METHODS1_;
+
+ private:
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockOverloadedOnArgNumber);
+};
+
+template <typename T>
+class OverloadedMockMethodTest : public ::testing::Test {};
+using OverloadedMockMethodTestTypes =
+ ::testing::Types<MockOverloadedOnArgNumber,
+ LegacyMockOverloadedOnArgNumber>;
+TYPED_TEST_SUITE(OverloadedMockMethodTest, OverloadedMockMethodTestTypes);
+
+TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
+ TypeParam mock;
EXPECT_CALL(mock, Overloaded());
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
@@ -641,6 +845,56 @@ TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) {
EXPECT_EQ(-1, call(foo.AsStdFunction(), i));
}
+namespace {
+
+template <typename Expected, typename F>
+static constexpr bool IsMockFunctionTemplateArgumentDeducedTo(
+ const MockFunction<F>&) {
+ return std::is_same<F, Expected>::value;
+}
+
+} // namespace
+
+template <typename F>
+class MockMethodMockFunctionSignatureTest : public Test {};
+
+using MockMethodMockFunctionSignatureTypes =
+ Types<void(), int(), void(int), int(int), int(bool, int),
+ int(bool, char, int, int, int, int, int, char, int, bool)>;
+TYPED_TEST_SUITE(MockMethodMockFunctionSignatureTest,
+ MockMethodMockFunctionSignatureTypes);
+
+TYPED_TEST(MockMethodMockFunctionSignatureTest,
+ IsMockFunctionTemplateArgumentDeducedForRawSignature) {
+ using Argument = TypeParam;
+ MockFunction<Argument> foo;
+ EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<Argument>(foo));
+}
+
+TYPED_TEST(MockMethodMockFunctionSignatureTest,
+ IsMockFunctionTemplateArgumentDeducedForStdFunction) {
+ using Argument = std::function<TypeParam>;
+ MockFunction<Argument> foo;
+ EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<Argument>(foo));
+}
+
+TYPED_TEST(
+ MockMethodMockFunctionSignatureTest,
+ IsMockFunctionCallMethodSignatureTheSameForRawSignatureAndStdFunction) {
+ using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
+ using ForStdFunction =
+ decltype(&MockFunction<std::function<TypeParam>>::Call);
+ EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
+}
+
+TYPED_TEST(
+ MockMethodMockFunctionSignatureTest,
+ IsMockFunctionAsStdFunctionMethodSignatureTheSameForRawSignatureAndStdFunction) {
+ using ForRawSignature = decltype(&MockFunction<TypeParam>::AsStdFunction);
+ using ForStdFunction =
+ decltype(&MockFunction<std::function<TypeParam>>::AsStdFunction);
+ EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
+}
struct MockMethodSizes0 {
MOCK_METHOD(void, func, ());
@@ -658,11 +912,35 @@ struct MockMethodSizes4 {
MOCK_METHOD(void, func, (int, int, int, int));
};
+struct LegacyMockMethodSizes0 {
+ MOCK_METHOD0(func, void());
+};
+struct LegacyMockMethodSizes1 {
+ MOCK_METHOD1(func, void(int));
+};
+struct LegacyMockMethodSizes2 {
+ MOCK_METHOD2(func, void(int, int));
+};
+struct LegacyMockMethodSizes3 {
+ MOCK_METHOD3(func, void(int, int, int));
+};
+struct LegacyMockMethodSizes4 {
+ MOCK_METHOD4(func, void(int, int, int, int));
+};
+
+
TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
+
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes1));
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes2));
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes3));
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes4));
+
+ EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(MockMethodSizes0));
}
void hasTwoParams(int, int);
diff --git a/googlemock/test/gmock-generated-actions_test.cc b/googlemock/test/gmock-generated-actions_test.cc
deleted file mode 100644
index 4c649a7e..00000000
--- a/googlemock/test/gmock-generated-actions_test.cc
+++ /dev/null
@@ -1,1064 +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 built-in actions generated by a script.
-
-#include "gmock/gmock-generated-actions.h"
-
-#include <functional>
-#include <memory>
-#include <sstream>
-#include <string>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace testing {
-namespace gmock_generated_actions_test {
-
-using ::std::plus;
-using ::std::string;
-using testing::_;
-using testing::Action;
-using testing::ActionInterface;
-using testing::ByRef;
-using testing::DoAll;
-using testing::Invoke;
-using testing::Return;
-using testing::ReturnNew;
-using testing::SetArgPointee;
-using testing::StaticAssertTypeEq;
-using testing::Unused;
-
-// For suppressing compiler warnings on conversion possibly losing precision.
-inline short Short(short n) { return n; } // NOLINT
-inline char Char(char ch) { return ch; }
-
-// Sample functions and functors for testing various actions.
-int Nullary() { return 1; }
-
-bool g_done = false;
-
-bool ByConstRef(const std::string& s) { return s == "Hi"; }
-
-const double g_double = 0;
-bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
-
-struct UnaryFunctor {
- int operator()(bool x) { return x ? 1 : -1; }
-};
-
-const char* Binary(const char* input, short n) { return input + n; } // NOLINT
-
-int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
-
-struct SumOf5Functor {
- int operator()(int a, int b, int c, int d, int e) {
- return a + b + c + d + e;
- }
-};
-
-std::string Concat5(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5) {
- return std::string(s1) + s2 + s3 + s4 + s5;
-}
-
-int SumOf6(int a, int b, int c, int d, int e, int f) {
- return a + b + c + d + e + f;
-}
-
-struct SumOf6Functor {
- int operator()(int a, int b, int c, int d, int e, int f) {
- return a + b + c + d + e + f;
- }
-};
-
-std::string Concat6(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6;
-}
-
-std::string Concat7(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6,
- const char* s7) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
-}
-
-std::string Concat8(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6,
- const char* s7, const char* s8) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
-}
-
-std::string Concat9(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6,
- const char* s7, const char* s8, const char* s9) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
-}
-
-std::string Concat10(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6,
- const char* s7, const char* s8, const char* s9,
- const char* s10) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
-}
-
-// A helper that turns the type of a C-string literal from const
-// char[N] to const char*.
-inline const char* CharPtr(const char* s) { return s; }
-
-// Tests InvokeArgument<N>(...).
-
-// Tests using InvokeArgument with a nullary function.
-TEST(InvokeArgumentTest, Function0) {
- Action<int(int, int(*)())> a = InvokeArgument<1>(); // NOLINT
- EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary)));
-}
-
-// Tests using InvokeArgument with a unary function.
-TEST(InvokeArgumentTest, Functor1) {
- Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT
- EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor())));
-}
-
-// Tests using InvokeArgument with a 5-ary function.
-TEST(InvokeArgumentTest, Function5) {
- Action<int(int(*)(int, int, int, int, int))> a = // NOLINT
- InvokeArgument<0>(10000, 2000, 300, 40, 5);
- EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5)));
-}
-
-// Tests using InvokeArgument with a 5-ary functor.
-TEST(InvokeArgumentTest, Functor5) {
- Action<int(SumOf5Functor)> a = // NOLINT
- InvokeArgument<0>(10000, 2000, 300, 40, 5);
- EXPECT_EQ(12345, a.Perform(std::make_tuple(SumOf5Functor())));
-}
-
-// Tests using InvokeArgument with a 6-ary function.
-TEST(InvokeArgumentTest, Function6) {
- Action<int(int(*)(int, int, int, int, int, int))> a = // NOLINT
- InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
- EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6)));
-}
-
-// Tests using InvokeArgument with a 6-ary functor.
-TEST(InvokeArgumentTest, Functor6) {
- Action<int(SumOf6Functor)> a = // NOLINT
- InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
- EXPECT_EQ(123456, a.Perform(std::make_tuple(SumOf6Functor())));
-}
-
-// Tests using InvokeArgument with a 7-ary function.
-TEST(InvokeArgumentTest, Function7) {
- Action<std::string(std::string(*)(const char*, const char*, const char*,
- const char*, const char*, const char*,
- const char*))>
- a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
- EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7)));
-}
-
-// Tests using InvokeArgument with a 8-ary function.
-TEST(InvokeArgumentTest, Function8) {
- Action<std::string(std::string(*)(const char*, const char*, const char*,
- const char*, const char*, const char*,
- const char*, const char*))>
- a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
- EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8)));
-}
-
-// Tests using InvokeArgument with a 9-ary function.
-TEST(InvokeArgumentTest, Function9) {
- Action<std::string(std::string(*)(const char*, const char*, const char*,
- const char*, const char*, const char*,
- const char*, const char*, const char*))>
- a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
- EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9)));
-}
-
-// Tests using InvokeArgument with a 10-ary function.
-TEST(InvokeArgumentTest, Function10) {
- Action<std::string(std::string(*)(
- const char*, const char*, const char*, const char*, const char*,
- const char*, const char*, const char*, const char*, const char*))>
- a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
- EXPECT_EQ("1234567890", a.Perform(std::make_tuple(&Concat10)));
-}
-
-// Tests using InvokeArgument with a function that takes a pointer argument.
-TEST(InvokeArgumentTest, ByPointerFunction) {
- Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT
- InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1));
- EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
-}
-
-// Tests using InvokeArgument with a function that takes a const char*
-// by passing it a C-string literal.
-TEST(InvokeArgumentTest, FunctionWithCStringLiteral) {
- Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT
- InvokeArgument<0>("Hi", Short(1));
- EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
-}
-
-// Tests using InvokeArgument with a function that takes a const reference.
-TEST(InvokeArgumentTest, ByConstReferenceFunction) {
- Action<bool(bool (*function)(const std::string& s))> a = // NOLINT
- InvokeArgument<0>(std::string("Hi"));
- // When action 'a' is constructed, it makes a copy of the temporary
- // string object passed to it, so it's OK to use 'a' later, when the
- // temporary object has already died.
- EXPECT_TRUE(a.Perform(std::make_tuple(&ByConstRef)));
-}
-
-// Tests using InvokeArgument with ByRef() and a function that takes a
-// const reference.
-TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {
- Action<bool(bool(*)(const double& x))> a = // NOLINT
- InvokeArgument<0>(ByRef(g_double));
- // The above line calls ByRef() on a const value.
- EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
-
- double x = 0;
- a = InvokeArgument<0>(ByRef(x)); // This calls ByRef() on a non-const.
- EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
-}
-
-// Tests DoAll(a1, a2).
-TEST(DoAllTest, TwoActions) {
- int n = 0;
- Action<int(int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT
- Return(2));
- EXPECT_EQ(2, a.Perform(std::make_tuple(&n)));
- EXPECT_EQ(1, n);
-}
-
-// Tests DoAll(a1, a2, a3).
-TEST(DoAllTest, ThreeActions) {
- int m = 0, n = 0;
- Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT
- SetArgPointee<1>(2),
- Return(3));
- EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
-}
-
-// Tests DoAll(a1, a2, a3, a4).
-TEST(DoAllTest, FourActions) {
- int m = 0, n = 0;
- char ch = '\0';
- Action<int(int*, int*, char*)> a = // NOLINT
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- Return(3));
- EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', ch);
-}
-
-// Tests DoAll(a1, a2, a3, a4, a5).
-TEST(DoAllTest, FiveActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0';
- Action<int(int*, int*, char*, char*)> action = // NOLINT
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
-}
-
-// Tests DoAll(a1, a2, ..., a6).
-TEST(DoAllTest, SixActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0';
- Action<int(int*, int*, char*, char*, char*)> action = // NOLINT
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
-}
-
-// Tests DoAll(a1, a2, ..., a7).
-TEST(DoAllTest, SevenActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0', d = '\0';
- Action<int(int*, int*, char*, char*, char*, char*)> action = // NOLINT
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- SetArgPointee<5>('d'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
- EXPECT_EQ('d', d);
-}
-
-// Tests DoAll(a1, a2, ..., a8).
-TEST(DoAllTest, EightActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0';
- Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
- char*)> action =
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- SetArgPointee<5>('d'),
- SetArgPointee<6>('e'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
- EXPECT_EQ('d', d);
- EXPECT_EQ('e', e);
-}
-
-// Tests DoAll(a1, a2, ..., a9).
-TEST(DoAllTest, NineActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0';
- Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
- char*, char*)> action =
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- SetArgPointee<5>('d'),
- SetArgPointee<6>('e'),
- SetArgPointee<7>('f'),
- Return(3));
- EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
- EXPECT_EQ('d', d);
- EXPECT_EQ('e', e);
- EXPECT_EQ('f', f);
-}
-
-// Tests DoAll(a1, a2, ..., a10).
-TEST(DoAllTest, TenActions) {
- int m = 0, n = 0;
- char a = '\0', b = '\0', c = '\0', d = '\0';
- char e = '\0', f = '\0', g = '\0';
- Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
- char*, char*, char*)> action =
- DoAll(SetArgPointee<0>(1),
- SetArgPointee<1>(2),
- SetArgPointee<2>('a'),
- SetArgPointee<3>('b'),
- SetArgPointee<4>('c'),
- SetArgPointee<5>('d'),
- SetArgPointee<6>('e'),
- SetArgPointee<7>('f'),
- SetArgPointee<8>('g'),
- Return(3));
- EXPECT_EQ(
- 3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g)));
- EXPECT_EQ(1, m);
- EXPECT_EQ(2, n);
- EXPECT_EQ('a', a);
- EXPECT_EQ('b', b);
- EXPECT_EQ('c', c);
- EXPECT_EQ('d', d);
- EXPECT_EQ('e', e);
- EXPECT_EQ('f', f);
- EXPECT_EQ('g', g);
-}
-
-// 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.
-// Also suppress C4503 decorated name length exceeded, name was truncated
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4100)
-# pragma warning(disable:4503)
-#endif
-// Tests the ACTION*() macro family.
-
-// Tests that ACTION() can define an action that doesn't reference the
-// mock function arguments.
-ACTION(Return5) { return 5; }
-
-TEST(ActionMacroTest, WorksWhenNotReferencingArguments) {
- Action<double()> a1 = Return5();
- EXPECT_DOUBLE_EQ(5, a1.Perform(std::make_tuple()));
-
- Action<int(double, bool)> a2 = Return5();
- EXPECT_EQ(5, a2.Perform(std::make_tuple(1, true)));
-}
-
-// Tests that ACTION() can define an action that returns void.
-ACTION(IncrementArg1) { (*arg1)++; }
-
-TEST(ActionMacroTest, WorksWhenReturningVoid) {
- Action<void(int, int*)> a1 = IncrementArg1();
- int n = 0;
- a1.Perform(std::make_tuple(5, &n));
- EXPECT_EQ(1, n);
-}
-
-// Tests that the body of ACTION() can reference the type of the
-// argument.
-ACTION(IncrementArg2) {
- StaticAssertTypeEq<int*, arg2_type>();
- arg2_type temp = arg2;
- (*temp)++;
-}
-
-TEST(ActionMacroTest, CanReferenceArgumentType) {
- Action<void(int, bool, int*)> a1 = IncrementArg2();
- int n = 0;
- a1.Perform(std::make_tuple(5, false, &n));
- EXPECT_EQ(1, n);
-}
-
-// Tests that the body of ACTION() can reference the argument tuple
-// via args_type and args.
-ACTION(Sum2) {
- StaticAssertTypeEq<std::tuple<int, char, int*>, args_type>();
- args_type args_copy = args;
- return std::get<0>(args_copy) + std::get<1>(args_copy);
-}
-
-TEST(ActionMacroTest, CanReferenceArgumentTuple) {
- Action<int(int, char, int*)> a1 = Sum2();
- int dummy = 0;
- EXPECT_EQ(11, a1.Perform(std::make_tuple(5, Char(6), &dummy)));
-}
-
-// Tests that the body of ACTION() can reference the mock function
-// type.
-int Dummy(bool flag) { return flag? 1 : 0; }
-
-ACTION(InvokeDummy) {
- StaticAssertTypeEq<int(bool), function_type>();
- function_type* fp = &Dummy;
- return (*fp)(true);
-}
-
-TEST(ActionMacroTest, CanReferenceMockFunctionType) {
- Action<int(bool)> a1 = InvokeDummy();
- EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));
- EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));
-}
-
-// Tests that the body of ACTION() can reference the mock function's
-// return type.
-ACTION(InvokeDummy2) {
- StaticAssertTypeEq<int, return_type>();
- return_type result = Dummy(true);
- return result;
-}
-
-TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) {
- Action<int(bool)> a1 = InvokeDummy2();
- EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));
- EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));
-}
-
-// Tests that ACTION() works for arguments passed by const reference.
-ACTION(ReturnAddrOfConstBoolReferenceArg) {
- StaticAssertTypeEq<const bool&, arg1_type>();
- return &arg1;
-}
-
-TEST(ActionMacroTest, WorksForConstReferenceArg) {
- Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg();
- const bool b = false;
- EXPECT_EQ(&b, a.Perform(std::tuple<int, const bool&>(0, b)));
-}
-
-// Tests that ACTION() works for arguments passed by non-const reference.
-ACTION(ReturnAddrOfIntReferenceArg) {
- StaticAssertTypeEq<int&, arg0_type>();
- return &arg0;
-}
-
-TEST(ActionMacroTest, WorksForNonConstReferenceArg) {
- Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg();
- int n = 0;
- EXPECT_EQ(&n, a.Perform(std::tuple<int&, bool, int>(n, true, 1)));
-}
-
-// Tests that ACTION() can be used in a namespace.
-namespace action_test {
-ACTION(Sum) { return arg0 + arg1; }
-} // namespace action_test
-
-TEST(ActionMacroTest, WorksInNamespace) {
- Action<int(int, int)> a1 = action_test::Sum();
- EXPECT_EQ(3, a1.Perform(std::make_tuple(1, 2)));
-}
-
-// Tests that the same ACTION definition works for mock functions with
-// different argument numbers.
-ACTION(PlusTwo) { return arg0 + 2; }
-
-TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) {
- Action<int(int)> a1 = PlusTwo();
- EXPECT_EQ(4, a1.Perform(std::make_tuple(2)));
-
- Action<double(float, void*)> a2 = PlusTwo();
- int dummy;
- EXPECT_DOUBLE_EQ(6, a2.Perform(std::make_tuple(4.0f, &dummy)));
-}
-
-// Tests that ACTION_P can define a parameterized action.
-ACTION_P(Plus, n) { return arg0 + n; }
-
-TEST(ActionPMacroTest, DefinesParameterizedAction) {
- Action<int(int m, bool t)> a1 = Plus(9);
- EXPECT_EQ(10, a1.Perform(std::make_tuple(1, true)));
-}
-
-// Tests that the body of ACTION_P can reference the argument types
-// and the parameter type.
-ACTION_P(TypedPlus, n) {
- arg0_type t1 = arg0;
- n_type t2 = n;
- return t1 + t2;
-}
-
-TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {
- Action<int(char m, bool t)> a1 = TypedPlus(9);
- EXPECT_EQ(10, a1.Perform(std::make_tuple(Char(1), true)));
-}
-
-// Tests that a parameterized action can be used in any mock function
-// whose type is compatible.
-TEST(ActionPMacroTest, WorksInCompatibleMockFunction) {
- Action<std::string(const std::string& s)> a1 = Plus("tail");
- const std::string re = "re";
- std::tuple<const std::string> dummy = std::make_tuple(re);
- EXPECT_EQ("retail", a1.Perform(dummy));
-}
-
-// Tests that we can use ACTION*() to define actions overloaded on the
-// number of parameters.
-
-ACTION(OverloadedAction) { return arg0 ? arg1 : "hello"; }
-
-ACTION_P(OverloadedAction, default_value) {
- return arg0 ? arg1 : default_value;
-}
-
-ACTION_P2(OverloadedAction, true_value, false_value) {
- return arg0 ? true_value : false_value;
-}
-
-TEST(ActionMacroTest, CanDefineOverloadedActions) {
- typedef Action<const char*(bool, const char*)> MyAction;
-
- const MyAction a1 = OverloadedAction();
- EXPECT_STREQ("hello", a1.Perform(std::make_tuple(false, CharPtr("world"))));
- EXPECT_STREQ("world", a1.Perform(std::make_tuple(true, CharPtr("world"))));
-
- const MyAction a2 = OverloadedAction("hi");
- EXPECT_STREQ("hi", a2.Perform(std::make_tuple(false, CharPtr("world"))));
- EXPECT_STREQ("world", a2.Perform(std::make_tuple(true, CharPtr("world"))));
-
- const MyAction a3 = OverloadedAction("hi", "you");
- EXPECT_STREQ("hi", a3.Perform(std::make_tuple(true, CharPtr("world"))));
- EXPECT_STREQ("you", a3.Perform(std::make_tuple(false, CharPtr("world"))));
-}
-
-// Tests ACTION_Pn where n >= 3.
-
-ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; }
-
-TEST(ActionPnMacroTest, WorksFor3Parameters) {
- Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4);
- EXPECT_DOUBLE_EQ(3123.4, a1.Perform(std::make_tuple(3000, true)));
-
- Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">");
- const std::string re = "re";
- std::tuple<const std::string> dummy = std::make_tuple(re);
- EXPECT_EQ("retail->", a2.Perform(dummy));
-}
-
-ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; }
-
-TEST(ActionPnMacroTest, WorksFor4Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; }
-
-TEST(ActionPnMacroTest, WorksFor5Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) {
- return arg0 + p0 + p1 + p2 + p3 + p4 + p5;
-}
-
-TEST(ActionPnMacroTest, WorksFor6Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) {
- return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6;
-}
-
-TEST(ActionPnMacroTest, WorksFor7Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) {
- return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7;
-}
-
-TEST(ActionPnMacroTest, WorksFor8Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
- a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) {
- return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8;
-}
-
-TEST(ActionPnMacroTest, WorksFor9Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
- a1.Perform(std::make_tuple(10)));
-}
-
-ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) {
- arg0_type t0 = arg0;
- last_param_type t9 = last_param;
- return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9;
-}
-
-TEST(ActionPnMacroTest, WorksFor10Parameters) {
- Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
- EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
- a1.Perform(std::make_tuple(10)));
-}
-
-// Tests that the action body can promote the parameter types.
-
-ACTION_P2(PadArgument, prefix, suffix) {
- // The following lines promote the two parameters to desired types.
- std::string prefix_str(prefix);
- char suffix_char = static_cast<char>(suffix);
- return prefix_str + arg0 + suffix_char;
-}
-
-TEST(ActionPnMacroTest, SimpleTypePromotion) {
- Action<std::string(const char*)> no_promo =
- PadArgument(std::string("foo"), 'r');
- Action<std::string(const char*)> promo =
- PadArgument("foo", static_cast<int>('r'));
- EXPECT_EQ("foobar", no_promo.Perform(std::make_tuple(CharPtr("ba"))));
- EXPECT_EQ("foobar", promo.Perform(std::make_tuple(CharPtr("ba"))));
-}
-
-// Tests that we can partially restrict parameter types using a
-// straight-forward pattern.
-
-// Defines a generic action that doesn't restrict the types of its
-// parameters.
-ACTION_P3(ConcatImpl, a, b, c) {
- std::stringstream ss;
- ss << a << b << c;
- return ss.str();
-}
-
-// Next, we try to restrict that either the first parameter is a
-// string, or the second parameter is an int.
-
-// Defines a partially specialized wrapper that restricts the first
-// parameter to std::string.
-template <typename T1, typename T2>
-// ConcatImplActionP3 is the class template ACTION_P3 uses to
-// implement ConcatImpl. We shouldn't change the name as this
-// pattern requires the user to use it directly.
-ConcatImplActionP3<std::string, T1, T2>
-Concat(const std::string& a, T1 b, T2 c) {
- GTEST_INTENTIONAL_CONST_COND_PUSH_()
- if (true) {
- GTEST_INTENTIONAL_CONST_COND_POP_()
- // This branch verifies that ConcatImpl() can be invoked without
- // explicit template arguments.
- return ConcatImpl(a, b, c);
- } else {
- // This branch verifies that ConcatImpl() can also be invoked with
- // explicit template arguments. It doesn't really need to be
- // executed as this is a compile-time verification.
- return ConcatImpl<std::string, T1, T2>(a, b, c);
- }
-}
-
-// Defines another partially specialized wrapper that restricts the
-// second parameter to int.
-template <typename T1, typename T2>
-ConcatImplActionP3<T1, int, T2>
-Concat(T1 a, int b, T2 c) {
- return ConcatImpl(a, b, c);
-}
-
-TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) {
- Action<const std::string()> a1 = Concat("Hello", "1", 2);
- EXPECT_EQ("Hello12", a1.Perform(std::make_tuple()));
-
- a1 = Concat(1, 2, 3);
- EXPECT_EQ("123", a1.Perform(std::make_tuple()));
-}
-
-// Verifies the type of an ACTION*.
-
-ACTION(DoFoo) {}
-ACTION_P(DoFoo, p) {}
-ACTION_P2(DoFoo, p0, p1) {}
-
-TEST(ActionPnMacroTest, TypesAreCorrect) {
- // DoFoo() must be assignable to a DoFooAction variable.
- DoFooAction a0 = DoFoo();
-
- // DoFoo(1) must be assignable to a DoFooActionP variable.
- DoFooActionP<int> a1 = DoFoo(1);
-
- // DoFoo(p1, ..., pk) must be assignable to a DoFooActionPk
- // variable, and so on.
- DoFooActionP2<int, char> a2 = DoFoo(1, '2');
- PlusActionP3<int, int, char> a3 = Plus(1, 2, '3');
- PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4');
- PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5');
- PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6');
- PlusActionP7<int, int, int, int, int, int, char> a7 =
- Plus(1, 2, 3, 4, 5, 6, '7');
- PlusActionP8<int, int, int, int, int, int, int, char> a8 =
- Plus(1, 2, 3, 4, 5, 6, 7, '8');
- PlusActionP9<int, int, int, int, int, int, int, int, char> a9 =
- Plus(1, 2, 3, 4, 5, 6, 7, 8, '9');
- PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 =
- Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
-
- // Avoid "unused variable" warnings.
- (void)a0;
- (void)a1;
- (void)a2;
- (void)a3;
- (void)a4;
- (void)a5;
- (void)a6;
- (void)a7;
- (void)a8;
- (void)a9;
- (void)a10;
-}
-
-// Tests that an ACTION_P*() action can be explicitly instantiated
-// with reference-typed parameters.
-
-ACTION_P(Plus1, x) { return x; }
-ACTION_P2(Plus2, x, y) { return x + y; }
-ACTION_P3(Plus3, x, y, z) { return x + y + z; }
-ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
- return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9;
-}
-
-TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) {
- int x = 1, y = 2, z = 3;
- const std::tuple<> empty = std::make_tuple();
-
- Action<int()> a = Plus1<int&>(x);
- EXPECT_EQ(1, a.Perform(empty));
-
- a = Plus2<const int&, int&>(x, y);
- EXPECT_EQ(3, a.Perform(empty));
-
- a = Plus3<int&, const int&, int&>(x, y, z);
- EXPECT_EQ(6, a.Perform(empty));
-
- int n[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
- a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&,
- int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7],
- n[8], n[9]);
- EXPECT_EQ(55, a.Perform(empty));
-}
-
-class NullaryConstructorClass {
- public:
- NullaryConstructorClass() : value_(123) {}
- int value_;
-};
-
-// Tests using ReturnNew() with a nullary constructor.
-TEST(ReturnNewTest, NoArgs) {
- Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>();
- NullaryConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(123, c->value_);
- delete c;
-}
-
-class UnaryConstructorClass {
- public:
- explicit UnaryConstructorClass(int value) : value_(value) {}
- int value_;
-};
-
-// Tests using ReturnNew() with a unary constructor.
-TEST(ReturnNewTest, Unary) {
- Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
- UnaryConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(4000, c->value_);
- delete c;
-}
-
-TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
- Action<UnaryConstructorClass*(bool, int)> a =
- ReturnNew<UnaryConstructorClass>(4000);
- UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
- EXPECT_EQ(4000, c->value_);
- delete c;
-}
-
-TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
- Action<const UnaryConstructorClass*()> a =
- ReturnNew<UnaryConstructorClass>(4000);
- const UnaryConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(4000, c->value_);
- delete c;
-}
-
-class TenArgConstructorClass {
- public:
- TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5,
- int a6, int a7, int a8, int a9, int a10)
- : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {
- }
- int value_;
-};
-
-// Tests using ReturnNew() with a 10-argument constructor.
-TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
- Action<TenArgConstructorClass*()> a =
- ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000,
- 4000000, 500000, 60000,
- 7000, 800, 90, 0);
- TenArgConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(1234567890, c->value_);
- delete c;
-}
-
-// Tests that ACTION_TEMPLATE works when there is no value parameter.
-ACTION_TEMPLATE(CreateNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_0_VALUE_PARAMS()) {
- return new T;
-}
-
-TEST(ActionTemplateTest, WorksWithoutValueParam) {
- const Action<int*()> a = CreateNew<int>();
- int* p = a.Perform(std::make_tuple());
- delete p;
-}
-
-// Tests that ACTION_TEMPLATE works when there are value parameters.
-ACTION_TEMPLATE(CreateNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_1_VALUE_PARAMS(a0)) {
- return new T(a0);
-}
-
-TEST(ActionTemplateTest, WorksWithValueParams) {
- const Action<int*()> a = CreateNew<int>(42);
- int* p = a.Perform(std::make_tuple());
- EXPECT_EQ(42, *p);
- delete p;
-}
-
-// Tests that ACTION_TEMPLATE works for integral template parameters.
-ACTION_TEMPLATE(MyDeleteArg,
- HAS_1_TEMPLATE_PARAMS(int, k),
- AND_0_VALUE_PARAMS()) {
- delete std::get<k>(args);
-}
-
-// Resets a bool variable in the destructor.
-class BoolResetter {
- public:
- explicit BoolResetter(bool* value) : value_(value) {}
- ~BoolResetter() { *value_ = false; }
- private:
- bool* value_;
-};
-
-TEST(ActionTemplateTest, WorksForIntegralTemplateParams) {
- const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>();
- int n = 0;
- bool b = true;
- BoolResetter* resetter = new BoolResetter(&b);
- a.Perform(std::make_tuple(&n, resetter));
- EXPECT_FALSE(b); // Verifies that resetter is deleted.
-}
-
-// Tests that ACTION_TEMPLATES works for template template parameters.
-ACTION_TEMPLATE(ReturnSmartPointer,
- HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class,
- Pointer),
- AND_1_VALUE_PARAMS(pointee)) {
- return Pointer<pointee_type>(new pointee_type(pointee));
-}
-
-TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) {
- const Action<std::shared_ptr<int>()> a =
- ReturnSmartPointer<std::shared_ptr>(42);
- std::shared_ptr<int> p = a.Perform(std::make_tuple());
- EXPECT_EQ(42, *p);
-}
-
-// Tests that ACTION_TEMPLATE works for 10 template parameters.
-template <typename T1, typename T2, typename T3, int k4, bool k5,
- unsigned int k6, typename T7, typename T8, typename T9>
-struct GiantTemplate {
- public:
- explicit GiantTemplate(int a_value) : value(a_value) {}
- int value;
-};
-
-ACTION_TEMPLATE(ReturnGiant,
- HAS_10_TEMPLATE_PARAMS(
- typename, T1,
- typename, T2,
- typename, T3,
- int, k4,
- bool, k5,
- unsigned int, k6,
- class, T7,
- class, T8,
- class, T9,
- template <typename T> class, T10),
- AND_1_VALUE_PARAMS(value)) {
- return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value);
-}
-
-TEST(ActionTemplateTest, WorksFor10TemplateParameters) {
- using Giant = GiantTemplate<std::shared_ptr<int>, bool, double, 5, true, 6,
- char, unsigned, int>;
- const Action<Giant()> a = ReturnGiant<int, bool, double, 5, true, 6, char,
- unsigned, int, std::shared_ptr>(42);
- Giant giant = a.Perform(std::make_tuple());
- EXPECT_EQ(42, giant.value);
-}
-
-// Tests that ACTION_TEMPLATE works for 10 value parameters.
-ACTION_TEMPLATE(ReturnSum,
- HAS_1_TEMPLATE_PARAMS(typename, Number),
- AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) {
- return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10;
-}
-
-TEST(ActionTemplateTest, WorksFor10ValueParameters) {
- const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
- EXPECT_EQ(55, a.Perform(std::make_tuple()));
-}
-
-// Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded
-// on the number of value parameters.
-
-ACTION(ReturnSum) { return 0; }
-
-ACTION_P(ReturnSum, x) { return x; }
-
-ACTION_TEMPLATE(ReturnSum,
- HAS_1_TEMPLATE_PARAMS(typename, Number),
- AND_2_VALUE_PARAMS(v1, v2)) {
- return static_cast<Number>(v1) + v2;
-}
-
-ACTION_TEMPLATE(ReturnSum,
- HAS_1_TEMPLATE_PARAMS(typename, Number),
- AND_3_VALUE_PARAMS(v1, v2, v3)) {
- return static_cast<Number>(v1) + v2 + v3;
-}
-
-ACTION_TEMPLATE(ReturnSum,
- HAS_2_TEMPLATE_PARAMS(typename, Number, int, k),
- AND_4_VALUE_PARAMS(v1, v2, v3, v4)) {
- return static_cast<Number>(v1) + v2 + v3 + v4 + k;
-}
-
-TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
- const Action<int()> a0 = ReturnSum();
- const Action<int()> a1 = ReturnSum(1);
- const Action<int()> a2 = ReturnSum<int>(1, 2);
- const Action<int()> a3 = ReturnSum<int>(1, 2, 3);
- const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5);
- EXPECT_EQ(0, a0.Perform(std::make_tuple()));
- EXPECT_EQ(1, a1.Perform(std::make_tuple()));
- EXPECT_EQ(3, a2.Perform(std::make_tuple()));
- EXPECT_EQ(6, a3.Perform(std::make_tuple()));
- EXPECT_EQ(12345, a4.Perform(std::make_tuple()));
-}
-
-
-} // namespace gmock_generated_actions_test
-} // namespace testing
diff --git a/googlemock/test/gmock-generated-function-mockers_test.cc b/googlemock/test/gmock-generated-function-mockers_test.cc
deleted file mode 100644
index dff3a9f0..00000000
--- a/googlemock/test/gmock-generated-function-mockers_test.cc
+++ /dev/null
@@ -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
diff --git a/googlemock/test/gmock-generated-matchers_test.cc b/googlemock/test/gmock-generated-matchers_test.cc
deleted file mode 100644
index 6783f8f8..00000000
--- a/googlemock/test/gmock-generated-matchers_test.cc
+++ /dev/null
@@ -1,1314 +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.
-
-// Google Mock - a framework for writing C++ mock classes.
-//
-// This file tests the built-in matchers generated by a script.
-
-// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
-// possible loss of data and C4100, unreferenced local parameter
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable:4244)
-# pragma warning(disable:4100)
-#endif
-
-#include "gmock/gmock-generated-matchers.h"
-
-#include <array>
-#include <iterator>
-#include <list>
-#include <map>
-#include <memory>
-#include <set>
-#include <sstream>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest-spi.h"
-#include "gtest/gtest.h"
-
-namespace {
-
-using std::list;
-using std::map;
-using std::pair;
-using std::set;
-using std::stringstream;
-using std::vector;
-using testing::_;
-using testing::AllOf;
-using testing::AllOfArray;
-using testing::AnyOf;
-using testing::AnyOfArray;
-using testing::Args;
-using testing::Contains;
-using testing::ElementsAre;
-using testing::ElementsAreArray;
-using testing::Eq;
-using testing::Ge;
-using testing::Gt;
-using testing::Le;
-using testing::Lt;
-using testing::MakeMatcher;
-using testing::Matcher;
-using testing::MatcherInterface;
-using testing::MatchResultListener;
-using testing::Ne;
-using testing::Not;
-using testing::Pointee;
-using testing::PrintToString;
-using testing::Ref;
-using testing::StaticAssertTypeEq;
-using testing::StrEq;
-using testing::Value;
-using testing::internal::ElementsAreArrayMatcher;
-
-// Returns the description of the given matcher.
-template <typename T>
-std::string Describe(const Matcher<T>& m) {
- stringstream ss;
- m.DescribeTo(&ss);
- return ss.str();
-}
-
-// Returns the description of the negation of the given matcher.
-template <typename T>
-std::string DescribeNegation(const Matcher<T>& m) {
- stringstream ss;
- m.DescribeNegationTo(&ss);
- return ss.str();
-}
-
-// Returns the reason why x matches, or doesn't match, m.
-template <typename MatcherType, typename Value>
-std::string Explain(const MatcherType& m, const Value& x) {
- stringstream ss;
- m.ExplainMatchResultTo(x, &ss);
- return ss.str();
-}
-
-// For testing ExplainMatchResultTo().
-class GreaterThanMatcher : public MatcherInterface<int> {
- public:
- explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
-
- void DescribeTo(::std::ostream* os) const override {
- *os << "is greater than " << rhs_;
- }
-
- bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
- const int diff = lhs - rhs_;
- if (diff > 0) {
- *listener << "which is " << diff << " more than " << rhs_;
- } else if (diff == 0) {
- *listener << "which is the same as " << rhs_;
- } else {
- *listener << "which is " << -diff << " less than " << rhs_;
- }
-
- return lhs > rhs_;
- }
-
- private:
- int rhs_;
-};
-
-Matcher<int> GreaterThan(int n) {
- return MakeMatcher(new GreaterThanMatcher(n));
-}
-
-// Tests for ElementsAre().
-
-TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
- Matcher<const vector<int>&> m = ElementsAre();
- EXPECT_EQ("is empty", Describe(m));
-}
-
-TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
- Matcher<vector<int> > m = ElementsAre(Gt(5));
- EXPECT_EQ("has 1 element that is > 5", Describe(m));
-}
-
-TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
- Matcher<list<std::string> > m = ElementsAre(StrEq("one"), "two");
- EXPECT_EQ("has 2 elements where\n"
- "element #0 is equal to \"one\",\n"
- "element #1 is equal to \"two\"", Describe(m));
-}
-
-TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
- Matcher<vector<int> > m = ElementsAre();
- EXPECT_EQ("isn't empty", DescribeNegation(m));
-}
-
-TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
- Matcher<const list<int>& > m = ElementsAre(Gt(5));
- EXPECT_EQ("doesn't have 1 element, or\n"
- "element #0 isn't > 5", DescribeNegation(m));
-}
-
-TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
- Matcher<const list<std::string>&> m = ElementsAre("one", "two");
- EXPECT_EQ("doesn't have 2 elements, or\n"
- "element #0 isn't equal to \"one\", or\n"
- "element #1 isn't equal to \"two\"", DescribeNegation(m));
-}
-
-TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
- Matcher<const list<int>& > m = ElementsAre(1, Ne(2));
-
- list<int> test_list;
- test_list.push_back(1);
- test_list.push_back(3);
- EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
-}
-
-TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
- Matcher<const vector<int>& > m =
- ElementsAre(GreaterThan(1), 0, GreaterThan(2));
-
- const int a[] = { 10, 0, 100 };
- vector<int> test_vector(std::begin(a), std::end(a));
- EXPECT_EQ("whose element #0 matches, which is 9 more than 1,\n"
- "and whose element #2 matches, which is 98 more than 2",
- Explain(m, test_vector));
-}
-
-TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
- Matcher<const list<int>& > m = ElementsAre(1, 3);
-
- list<int> test_list;
- // No need to explain when the container is empty.
- EXPECT_EQ("", Explain(m, test_list));
-
- test_list.push_back(1);
- EXPECT_EQ("which has 1 element", Explain(m, test_list));
-}
-
-TEST(ElementsAreTest, CanExplainMismatchRightSize) {
- Matcher<const vector<int>& > m = ElementsAre(1, GreaterThan(5));
-
- vector<int> v;
- v.push_back(2);
- v.push_back(1);
- EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
-
- v[0] = 1;
- EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
- Explain(m, v));
-}
-
-TEST(ElementsAreTest, MatchesOneElementVector) {
- vector<std::string> test_vector;
- test_vector.push_back("test string");
-
- EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
-}
-
-TEST(ElementsAreTest, MatchesOneElementList) {
- list<std::string> test_list;
- test_list.push_back("test string");
-
- EXPECT_THAT(test_list, ElementsAre("test string"));
-}
-
-TEST(ElementsAreTest, MatchesThreeElementVector) {
- vector<std::string> test_vector;
- test_vector.push_back("one");
- test_vector.push_back("two");
- test_vector.push_back("three");
-
- EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
-}
-
-TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
- vector<int> test_vector;
- test_vector.push_back(4);
-
- EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
-}
-
-TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
- vector<int> test_vector;
- test_vector.push_back(4);
-
- EXPECT_THAT(test_vector, ElementsAre(_));
-}
-
-TEST(ElementsAreTest, MatchesOneElementValue) {
- vector<int> test_vector;
- test_vector.push_back(4);
-
- EXPECT_THAT(test_vector, ElementsAre(4));
-}
-
-TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
- vector<int> test_vector;
- test_vector.push_back(1);
- test_vector.push_back(2);
- test_vector.push_back(3);
-
- EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
-}
-
-TEST(ElementsAreTest, MatchesTenElementVector) {
- const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
- vector<int> test_vector(std::begin(a), std::end(a));
-
- EXPECT_THAT(test_vector,
- // The element list can contain values and/or matchers
- // of different types.
- ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
-}
-
-TEST(ElementsAreTest, DoesNotMatchWrongSize) {
- vector<std::string> test_vector;
- test_vector.push_back("test string");
- test_vector.push_back("test string");
-
- Matcher<vector<std::string> > m = ElementsAre(StrEq("test string"));
- EXPECT_FALSE(m.Matches(test_vector));
-}
-
-TEST(ElementsAreTest, DoesNotMatchWrongValue) {
- vector<std::string> test_vector;
- test_vector.push_back("other string");
-
- Matcher<vector<std::string> > m = ElementsAre(StrEq("test string"));
- EXPECT_FALSE(m.Matches(test_vector));
-}
-
-TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
- vector<std::string> test_vector;
- test_vector.push_back("one");
- test_vector.push_back("three");
- test_vector.push_back("two");
-
- Matcher<vector<std::string> > m =
- ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
- EXPECT_FALSE(m.Matches(test_vector));
-}
-
-TEST(ElementsAreTest, WorksForNestedContainer) {
- constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
-
- vector<list<char> > nested;
- for (size_t i = 0; i < strings.size(); i++) {
- nested.push_back(list<char>(strings[i], strings[i] + strlen(strings[i])));
- }
-
- EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
- ElementsAre('w', 'o', _, _, 'd')));
- EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
- ElementsAre('w', 'o', _, _, 'd'))));
-}
-
-TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
- int a[] = { 0, 1, 2 };
- vector<int> v(std::begin(a), std::end(a));
-
- EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
- EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
-}
-
-TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
- int a[] = { 0, 1, 2 };
- vector<int> v(std::begin(a), std::end(a));
-
- EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
- EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
-}
-
-TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
- int array[] = { 0, 1, 2 };
- EXPECT_THAT(array, ElementsAre(0, 1, _));
- EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
- EXPECT_THAT(array, Not(ElementsAre(0, _)));
-}
-
-class NativeArrayPassedAsPointerAndSize {
- public:
- NativeArrayPassedAsPointerAndSize() {}
-
- MOCK_METHOD2(Helper, void(int* array, int size));
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
-};
-
-TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
- int array[] = { 0, 1 };
- ::std::tuple<int*, size_t> array_as_tuple(array, 2);
- EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
- EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
-
- NativeArrayPassedAsPointerAndSize helper;
- EXPECT_CALL(helper, Helper(_, _))
- .With(ElementsAre(0, 1));
- helper.Helper(array, 2);
-}
-
-TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
- const char a2[][3] = { "hi", "lo" };
- EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
- ElementsAre('l', 'o', '\0')));
- EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
- EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
- ElementsAre('l', 'o', '\0')));
-}
-
-TEST(ElementsAreTest, AcceptsStringLiteral) {
- std::string array[] = {"hi", "one", "two"};
- EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
- EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
-}
-
-// Declared here with the size unknown. Defined AFTER the following test.
-extern const char kHi[];
-
-TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
- // The size of kHi is not known in this test, but ElementsAre() should
- // still accept it.
-
- std::string array1[] = {"hi"};
- EXPECT_THAT(array1, ElementsAre(kHi));
-
- std::string array2[] = {"ho"};
- EXPECT_THAT(array2, Not(ElementsAre(kHi)));
-}
-
-const char kHi[] = "hi";
-
-TEST(ElementsAreTest, MakesCopyOfArguments) {
- int x = 1;
- int y = 2;
- // This should make a copy of x and y.
- ::testing::internal::ElementsAreMatcher<std::tuple<int, int> >
- polymorphic_matcher = ElementsAre(x, y);
- // Changing x and y now shouldn't affect the meaning of the above matcher.
- x = y = 0;
- const int array1[] = { 1, 2 };
- EXPECT_THAT(array1, polymorphic_matcher);
- const int array2[] = { 0, 0 };
- EXPECT_THAT(array2, Not(polymorphic_matcher));
-}
-
-
-// Tests for ElementsAreArray(). Since ElementsAreArray() shares most
-// of the implementation with ElementsAre(), we don't test it as
-// thoroughly here.
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
- const int a[] = { 1, 2, 3 };
-
- vector<int> test_vector(std::begin(a), std::end(a));
- EXPECT_THAT(test_vector, ElementsAreArray(a));
-
- test_vector[2] = 0;
- EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
- std::array<const char*, 3> a = {{"one", "two", "three"}};
-
- vector<std::string> test_vector(std::begin(a), std::end(a));
- EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
-
- const char** p = a.data();
- test_vector[0] = "1";
- EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
- const char* a[] = { "one", "two", "three" };
-
- vector<std::string> test_vector(std::begin(a), std::end(a));
- EXPECT_THAT(test_vector, ElementsAreArray(a));
-
- test_vector[0] = "1";
- EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
- const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
- StrEq("three")};
-
- vector<std::string> test_vector;
- test_vector.push_back("one");
- test_vector.push_back("two");
- test_vector.push_back("three");
- EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
-
- test_vector.push_back("three");
- EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
- const int a[] = { 1, 2, 3 };
- vector<int> test_vector(std::begin(a), std::end(a));
- const vector<int> expected(std::begin(a), std::end(a));
- EXPECT_THAT(test_vector, ElementsAreArray(expected));
- test_vector.push_back(4);
- EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
-}
-
-
-TEST(ElementsAreArrayTest, TakesInitializerList) {
- const int a[5] = { 1, 2, 3, 4, 5 };
- EXPECT_THAT(a, ElementsAreArray({ 1, 2, 3, 4, 5 }));
- EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 5, 4 })));
- EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 4, 6 })));
-}
-
-TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
- const std::string a[5] = {"a", "b", "c", "d", "e"};
- EXPECT_THAT(a, ElementsAreArray({ "a", "b", "c", "d", "e" }));
- EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "e", "d" })));
- EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "d", "ef" })));
-}
-
-TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
- const int a[5] = { 1, 2, 3, 4, 5 };
- EXPECT_THAT(a, ElementsAreArray(
- { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
- EXPECT_THAT(a, Not(ElementsAreArray(
- { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
-}
-
-TEST(ElementsAreArrayTest,
- TakesInitializerListOfDifferentTypedMatchers) {
- const int a[5] = { 1, 2, 3, 4, 5 };
- // The compiler cannot infer the type of the initializer list if its
- // elements have different types. We must explicitly specify the
- // unified element type in this case.
- EXPECT_THAT(a, ElementsAreArray<Matcher<int> >(
- { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
- EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int> >(
- { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
-}
-
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
- const int a[] = { 1, 2, 3 };
- const Matcher<int> kMatchers[] = { Eq(1), Eq(2), Eq(3) };
- vector<int> test_vector(std::begin(a), std::end(a));
- const vector<Matcher<int>> expected(std::begin(kMatchers),
- std::end(kMatchers));
- EXPECT_THAT(test_vector, ElementsAreArray(expected));
- test_vector.push_back(4);
- EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
-}
-
-TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
- const int a[] = { 1, 2, 3 };
- const vector<int> test_vector(std::begin(a), std::end(a));
- const vector<int> expected(std::begin(a), std::end(a));
- EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
- // Pointers are iterators, too.
- EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
- // The empty range of NULL pointers should also be okay.
- int* const null_int = nullptr;
- EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
- EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
-}
-
-// Since ElementsAre() and ElementsAreArray() share much of the
-// implementation, we only do a sanity test for native arrays here.
-TEST(ElementsAreArrayTest, WorksWithNativeArray) {
- ::std::string a[] = { "hi", "ho" };
- ::std::string b[] = { "hi", "ho" };
-
- EXPECT_THAT(a, ElementsAreArray(b));
- EXPECT_THAT(a, ElementsAreArray(b, 2));
- EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
-}
-
-TEST(ElementsAreArrayTest, SourceLifeSpan) {
- const int a[] = { 1, 2, 3 };
- vector<int> test_vector(std::begin(a), std::end(a));
- vector<int> expect(std::begin(a), std::end(a));
- ElementsAreArrayMatcher<int> matcher_maker =
- ElementsAreArray(expect.begin(), expect.end());
- EXPECT_THAT(test_vector, matcher_maker);
- // Changing in place the values that initialized matcher_maker should not
- // affect matcher_maker anymore. It should have made its own copy of them.
- typedef vector<int>::iterator Iter;
- for (Iter it = expect.begin(); it != expect.end(); ++it) { *it += 10; }
- EXPECT_THAT(test_vector, matcher_maker);
- test_vector.push_back(3);
- EXPECT_THAT(test_vector, Not(matcher_maker));
-}
-
-// Tests for the MATCHER*() macro family.
-
-// Tests that a simple MATCHER() definition works.
-
-MATCHER(IsEven, "") { return (arg % 2) == 0; }
-
-TEST(MatcherMacroTest, Works) {
- const Matcher<int> m = IsEven();
- EXPECT_TRUE(m.Matches(6));
- EXPECT_FALSE(m.Matches(7));
-
- EXPECT_EQ("is even", Describe(m));
- EXPECT_EQ("not (is even)", DescribeNegation(m));
- EXPECT_EQ("", Explain(m, 6));
- EXPECT_EQ("", Explain(m, 7));
-}
-
-// This also tests that the description string can reference 'negation'.
-MATCHER(IsEven2, negation ? "is odd" : "is even") {
- if ((arg % 2) == 0) {
- // Verifies that we can stream to result_listener, a listener
- // supplied by the MATCHER macro implicitly.
- *result_listener << "OK";
- return true;
- } else {
- *result_listener << "% 2 == " << (arg % 2);
- return false;
- }
-}
-
-// This also tests that the description string can reference matcher
-// parameters.
-MATCHER_P2(EqSumOf, x, y, std::string(negation ? "doesn't equal" : "equals") +
- " the sum of " + PrintToString(x) + " and " +
- PrintToString(y)) {
- if (arg == (x + y)) {
- *result_listener << "OK";
- return true;
- } else {
- // Verifies that we can stream to the underlying stream of
- // result_listener.
- if (result_listener->stream() != nullptr) {
- *result_listener->stream() << "diff == " << (x + y - arg);
- }
- return false;
- }
-}
-
-// Tests that the matcher description can reference 'negation' and the
-// matcher parameters.
-TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
- const Matcher<int> m1 = IsEven2();
- EXPECT_EQ("is even", Describe(m1));
- EXPECT_EQ("is odd", DescribeNegation(m1));
-
- const Matcher<int> m2 = EqSumOf(5, 9);
- EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
- EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
-}
-
-// Tests explaining match result in a MATCHER* macro.
-TEST(MatcherMacroTest, CanExplainMatchResult) {
- const Matcher<int> m1 = IsEven2();
- EXPECT_EQ("OK", Explain(m1, 4));
- EXPECT_EQ("% 2 == 1", Explain(m1, 5));
-
- const Matcher<int> m2 = EqSumOf(1, 2);
- EXPECT_EQ("OK", Explain(m2, 3));
- EXPECT_EQ("diff == -1", Explain(m2, 4));
-}
-
-// Tests that the body of MATCHER() can reference the type of the
-// value being matched.
-
-MATCHER(IsEmptyString, "") {
- StaticAssertTypeEq< ::std::string, arg_type>();
- return arg == "";
-}
-
-MATCHER(IsEmptyStringByRef, "") {
- StaticAssertTypeEq<const ::std::string&, arg_type>();
- return arg == "";
-}
-
-TEST(MatcherMacroTest, CanReferenceArgType) {
- const Matcher< ::std::string> m1 = IsEmptyString();
- EXPECT_TRUE(m1.Matches(""));
-
- const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
- EXPECT_TRUE(m2.Matches(""));
-}
-
-// Tests that MATCHER() can be used in a namespace.
-
-namespace matcher_test {
-MATCHER(IsOdd, "") { return (arg % 2) != 0; }
-} // namespace matcher_test
-
-TEST(MatcherMacroTest, WorksInNamespace) {
- Matcher<int> m = matcher_test::IsOdd();
- EXPECT_FALSE(m.Matches(4));
- EXPECT_TRUE(m.Matches(5));
-}
-
-// Tests that Value() can be used to compose matchers.
-MATCHER(IsPositiveOdd, "") {
- return Value(arg, matcher_test::IsOdd()) && arg > 0;
-}
-
-TEST(MatcherMacroTest, CanBeComposedUsingValue) {
- EXPECT_THAT(3, IsPositiveOdd());
- EXPECT_THAT(4, Not(IsPositiveOdd()));
- EXPECT_THAT(-1, Not(IsPositiveOdd()));
-}
-
-// Tests that a simple MATCHER_P() definition works.
-
-MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
-
-TEST(MatcherPMacroTest, Works) {
- const Matcher<int> m = IsGreaterThan32And(5);
- EXPECT_TRUE(m.Matches(36));
- EXPECT_FALSE(m.Matches(5));
-
- EXPECT_EQ("is greater than 32 and 5", Describe(m));
- EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
- EXPECT_EQ("", Explain(m, 36));
- EXPECT_EQ("", Explain(m, 5));
-}
-
-// Tests that the description is calculated correctly from the matcher name.
-MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
-
-TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
- const Matcher<int> m = _is_Greater_Than32and_(5);
-
- EXPECT_EQ("is greater than 32 and 5", Describe(m));
- EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
- EXPECT_EQ("", Explain(m, 36));
- EXPECT_EQ("", Explain(m, 5));
-}
-
-// Tests that a MATCHER_P matcher can be explicitly instantiated with
-// a reference parameter type.
-
-class UncopyableFoo {
- public:
- explicit UncopyableFoo(char value) : value_(value) {}
- private:
- UncopyableFoo(const UncopyableFoo&);
- void operator=(const UncopyableFoo&);
-
- char value_;
-};
-
-MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
-
-TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
- UncopyableFoo foo1('1'), foo2('2');
- const Matcher<const UncopyableFoo&> m =
- ReferencesUncopyable<const UncopyableFoo&>(foo1);
-
- EXPECT_TRUE(m.Matches(foo1));
- EXPECT_FALSE(m.Matches(foo2));
-
- // We don't want the address of the parameter printed, as most
- // likely it will just annoy the user. If the address is
- // interesting, the user should consider passing the parameter by
- // pointer instead.
- EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
-}
-
-
-// Tests that the body of MATCHER_Pn() can reference the parameter
-// types.
-
-MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
- StaticAssertTypeEq<int, foo_type>();
- StaticAssertTypeEq<long, bar_type>(); // NOLINT
- StaticAssertTypeEq<char, baz_type>();
- return arg == 0;
-}
-
-TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
- EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
-}
-
-// Tests that a MATCHER_Pn matcher can be explicitly instantiated with
-// reference parameter types.
-
-MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
- return &arg == &variable1 || &arg == &variable2;
-}
-
-TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
- UncopyableFoo foo1('1'), foo2('2'), foo3('3');
- const Matcher<const UncopyableFoo&> m =
- ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
-
- EXPECT_TRUE(m.Matches(foo1));
- EXPECT_TRUE(m.Matches(foo2));
- EXPECT_FALSE(m.Matches(foo3));
-}
-
-TEST(MatcherPnMacroTest,
- GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
- UncopyableFoo foo1('1'), foo2('2');
- const Matcher<const UncopyableFoo&> m =
- ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
-
- // We don't want the addresses of the parameters printed, as most
- // likely they will just annoy the user. If the addresses are
- // interesting, the user should consider passing the parameters by
- // pointers instead.
- EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
- Describe(m));
-}
-
-// Tests that a simple MATCHER_P2() definition works.
-
-MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
-
-TEST(MatcherPnMacroTest, Works) {
- const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT
- EXPECT_TRUE(m.Matches(36L));
- EXPECT_FALSE(m.Matches(15L));
-
- EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
- EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
- EXPECT_EQ("", Explain(m, 36L));
- EXPECT_EQ("", Explain(m, 15L));
-}
-
-// Tests that MATCHER*() definitions can be overloaded on the number
-// of parameters; also tests MATCHER_Pn() where n >= 3.
-
-MATCHER(EqualsSumOf, "") { return arg == 0; }
-MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
-MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
-MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
-MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
-MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
-MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
- return arg == a + b + c + d + e + f;
-}
-MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
- return arg == a + b + c + d + e + f + g;
-}
-MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
- return arg == a + b + c + d + e + f + g + h;
-}
-MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
- return arg == a + b + c + d + e + f + g + h + i;
-}
-MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
- return arg == a + b + c + d + e + f + g + h + i + j;
-}
-
-TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
- EXPECT_THAT(0, EqualsSumOf());
- EXPECT_THAT(1, EqualsSumOf(1));
- EXPECT_THAT(12, EqualsSumOf(10, 2));
- EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
- EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
- EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
- EXPECT_THAT("abcdef",
- EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
- EXPECT_THAT("abcdefg",
- EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
- EXPECT_THAT("abcdefgh",
- EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
- "h"));
- EXPECT_THAT("abcdefghi",
- EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
- "h", 'i'));
- EXPECT_THAT("abcdefghij",
- EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
- "h", 'i', ::std::string("j")));
-
- EXPECT_THAT(1, Not(EqualsSumOf()));
- EXPECT_THAT(-1, Not(EqualsSumOf(1)));
- EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
- EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
- EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
- EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
- EXPECT_THAT("abcdef ",
- Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
- EXPECT_THAT("abcdefg ",
- Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f',
- 'g')));
- EXPECT_THAT("abcdefgh ",
- Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
- "h")));
- EXPECT_THAT("abcdefghi ",
- Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
- "h", 'i')));
- EXPECT_THAT("abcdefghij ",
- Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
- "h", 'i', ::std::string("j"))));
-}
-
-// Tests that a MATCHER_Pn() definition can be instantiated with any
-// compatible parameter types.
-TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
- EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
- EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
-
- EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
- EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
-}
-
-// Tests that the matcher body can promote the parameter types.
-
-MATCHER_P2(EqConcat, prefix, suffix, "") {
- // The following lines promote the two parameters to desired types.
- std::string prefix_str(prefix);
- char suffix_char = static_cast<char>(suffix);
- return arg == prefix_str + suffix_char;
-}
-
-TEST(MatcherPnMacroTest, SimpleTypePromotion) {
- Matcher<std::string> no_promo =
- EqConcat(std::string("foo"), 't');
- Matcher<const std::string&> promo =
- EqConcat("foo", static_cast<int>('t'));
- EXPECT_FALSE(no_promo.Matches("fool"));
- EXPECT_FALSE(promo.Matches("fool"));
- EXPECT_TRUE(no_promo.Matches("foot"));
- EXPECT_TRUE(promo.Matches("foot"));
-}
-
-// Verifies the type of a MATCHER*.
-
-TEST(MatcherPnMacroTest, TypesAreCorrect) {
- // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
- EqualsSumOfMatcher a0 = EqualsSumOf();
-
- // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
- EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
-
- // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
- // variable, and so on.
- EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
- EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
- EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
- EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
- EqualsSumOf(1, 2, 3, 4, '5');
- EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
- EqualsSumOf(1, 2, 3, 4, 5, '6');
- EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
- EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
- EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
- EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
- EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
- EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
- EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
- EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
-
- // Avoid "unused variable" warnings.
- (void)a0;
- (void)a1;
- (void)a2;
- (void)a3;
- (void)a4;
- (void)a5;
- (void)a6;
- (void)a7;
- (void)a8;
- (void)a9;
- (void)a10;
-}
-
-// Tests that matcher-typed parameters can be used in Value() inside a
-// MATCHER_Pn definition.
-
-// Succeeds if arg matches exactly 2 of the 3 matchers.
-MATCHER_P3(TwoOf, m1, m2, m3, "") {
- const int count = static_cast<int>(Value(arg, m1))
- + static_cast<int>(Value(arg, m2)) + static_cast<int>(Value(arg, m3));
- return count == 2;
-}
-
-TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
- EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
- EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
-}
-
-// Tests Contains().
-
-TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
- list<int> some_list;
- some_list.push_back(3);
- some_list.push_back(1);
- some_list.push_back(2);
- EXPECT_THAT(some_list, Contains(1));
- EXPECT_THAT(some_list, Contains(Gt(2.5)));
- EXPECT_THAT(some_list, Contains(Eq(2.0f)));
-
- list<std::string> another_list;
- another_list.push_back("fee");
- another_list.push_back("fie");
- another_list.push_back("foe");
- another_list.push_back("fum");
- EXPECT_THAT(another_list, Contains(std::string("fee")));
-}
-
-TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
- list<int> some_list;
- some_list.push_back(3);
- some_list.push_back(1);
- EXPECT_THAT(some_list, Not(Contains(4)));
-}
-
-TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
- set<int> some_set;
- some_set.insert(3);
- some_set.insert(1);
- some_set.insert(2);
- EXPECT_THAT(some_set, Contains(Eq(1.0)));
- EXPECT_THAT(some_set, Contains(Eq(3.0f)));
- EXPECT_THAT(some_set, Contains(2));
-
- set<const char*> another_set;
- another_set.insert("fee");
- another_set.insert("fie");
- another_set.insert("foe");
- another_set.insert("fum");
- EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
-}
-
-TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
- set<int> some_set;
- some_set.insert(3);
- some_set.insert(1);
- EXPECT_THAT(some_set, Not(Contains(4)));
-
- set<const char*> c_string_set;
- c_string_set.insert("hello");
- EXPECT_THAT(c_string_set, Not(Contains(std::string("hello").c_str())));
-}
-
-TEST(ContainsTest, ExplainsMatchResultCorrectly) {
- const int a[2] = { 1, 2 };
- Matcher<const int (&)[2]> m = Contains(2);
- EXPECT_EQ("whose element #1 matches", Explain(m, a));
-
- m = Contains(3);
- EXPECT_EQ("", Explain(m, a));
-
- m = Contains(GreaterThan(0));
- EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
-
- m = Contains(GreaterThan(10));
- EXPECT_EQ("", Explain(m, a));
-}
-
-TEST(ContainsTest, DescribesItselfCorrectly) {
- Matcher<vector<int> > m = Contains(1);
- EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
-
- Matcher<vector<int> > m2 = Not(m);
- EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
-}
-
-TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
- map<const char*, int> my_map;
- const char* bar = "a string";
- my_map[bar] = 2;
- EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
-
- map<std::string, int> another_map;
- another_map["fee"] = 1;
- another_map["fie"] = 2;
- another_map["foe"] = 3;
- another_map["fum"] = 4;
- EXPECT_THAT(another_map,
- Contains(pair<const std::string, int>(std::string("fee"), 1)));
- EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
-}
-
-TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
- map<int, int> some_map;
- some_map[1] = 11;
- some_map[2] = 22;
- EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
-}
-
-TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
- const char* string_array[] = { "fee", "fie", "foe", "fum" };
- EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
-}
-
-TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
- int int_array[] = { 1, 2, 3, 4 };
- EXPECT_THAT(int_array, Not(Contains(5)));
-}
-
-TEST(ContainsTest, AcceptsMatcher) {
- const int a[] = { 1, 2, 3 };
- EXPECT_THAT(a, Contains(Gt(2)));
- EXPECT_THAT(a, Not(Contains(Gt(4))));
-}
-
-TEST(ContainsTest, WorksForNativeArrayAsTuple) {
- const int a[] = { 1, 2 };
- const int* const pointer = a;
- EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
- EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
-}
-
-TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
- int a[][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
- EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
- EXPECT_THAT(a, Contains(Contains(5)));
- EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
- EXPECT_THAT(a, Contains(Not(Contains(5))));
-}
-
-TEST(AllOfArrayTest, BasicForms) {
- // Iterator
- std::vector<int> v0{};
- std::vector<int> v1{1};
- std::vector<int> v2{2, 3};
- std::vector<int> v3{4, 4, 4};
- EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
- EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
- EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
- EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
- EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
- // Pointer + size
- int ar[6] = {1, 2, 3, 4, 4, 4};
- EXPECT_THAT(0, AllOfArray(ar, 0));
- EXPECT_THAT(1, AllOfArray(ar, 1));
- EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
- EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
- EXPECT_THAT(4, AllOfArray(ar + 3, 3));
- // Array
- // int ar0[0]; Not usable
- int ar1[1] = {1};
- int ar2[2] = {2, 3};
- int ar3[3] = {4, 4, 4};
- // EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work
- EXPECT_THAT(1, AllOfArray(ar1));
- EXPECT_THAT(2, Not(AllOfArray(ar1)));
- EXPECT_THAT(3, Not(AllOfArray(ar2)));
- EXPECT_THAT(4, AllOfArray(ar3));
- // Container
- EXPECT_THAT(0, AllOfArray(v0));
- EXPECT_THAT(1, AllOfArray(v1));
- EXPECT_THAT(2, Not(AllOfArray(v1)));
- EXPECT_THAT(3, Not(AllOfArray(v2)));
- EXPECT_THAT(4, AllOfArray(v3));
- // Initializer
- EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.
- EXPECT_THAT(1, AllOfArray({1}));
- EXPECT_THAT(2, Not(AllOfArray({1})));
- EXPECT_THAT(3, Not(AllOfArray({2, 3})));
- EXPECT_THAT(4, AllOfArray({4, 4, 4}));
-}
-
-TEST(AllOfArrayTest, Matchers) {
- // vector
- std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
- EXPECT_THAT(0, Not(AllOfArray(matchers)));
- EXPECT_THAT(1, AllOfArray(matchers));
- EXPECT_THAT(2, Not(AllOfArray(matchers)));
- // initializer_list
- EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
- EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
-}
-
-TEST(AnyOfArrayTest, BasicForms) {
- // Iterator
- std::vector<int> v0{};
- std::vector<int> v1{1};
- std::vector<int> v2{2, 3};
- EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
- EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
- EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
- EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
- EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
- // Pointer + size
- int ar[3] = {1, 2, 3};
- EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
- EXPECT_THAT(1, AnyOfArray(ar, 1));
- EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
- EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
- EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
- // Array
- // int ar0[0]; Not usable
- int ar1[1] = {1};
- int ar2[2] = {2, 3};
- // EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work
- EXPECT_THAT(1, AnyOfArray(ar1));
- EXPECT_THAT(2, Not(AnyOfArray(ar1)));
- EXPECT_THAT(3, AnyOfArray(ar2));
- EXPECT_THAT(4, Not(AnyOfArray(ar2)));
- // Container
- EXPECT_THAT(0, Not(AnyOfArray(v0)));
- EXPECT_THAT(1, AnyOfArray(v1));
- EXPECT_THAT(2, Not(AnyOfArray(v1)));
- EXPECT_THAT(3, AnyOfArray(v2));
- EXPECT_THAT(4, Not(AnyOfArray(v2)));
- // Initializer
- EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.
- EXPECT_THAT(1, AnyOfArray({1}));
- EXPECT_THAT(2, Not(AnyOfArray({1})));
- EXPECT_THAT(3, AnyOfArray({2, 3}));
- EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
-}
-
-TEST(AnyOfArrayTest, Matchers) {
- // We negate test AllOfArrayTest.Matchers.
- // vector
- std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
- EXPECT_THAT(0, AnyOfArray(matchers));
- EXPECT_THAT(1, Not(AnyOfArray(matchers)));
- EXPECT_THAT(2, AnyOfArray(matchers));
- // initializer_list
- EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
- EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
-}
-
-TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
- // AnyOfArray and AllOfArry use the same underlying template-template,
- // thus it is sufficient to test one here.
- const std::vector<int> v0{};
- const std::vector<int> v1{1};
- const std::vector<int> v2{2, 3};
- const Matcher<int> m0 = AnyOfArray(v0);
- const Matcher<int> m1 = AnyOfArray(v1);
- const Matcher<int> m2 = AnyOfArray(v2);
- EXPECT_EQ("", Explain(m0, 0));
- EXPECT_EQ("", Explain(m1, 1));
- EXPECT_EQ("", Explain(m1, 2));
- EXPECT_EQ("", Explain(m2, 3));
- EXPECT_EQ("", Explain(m2, 4));
- EXPECT_EQ("()", Describe(m0));
- EXPECT_EQ("(is equal to 1)", Describe(m1));
- EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
- EXPECT_EQ("()", DescribeNegation(m0));
- EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
- EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
- // Explain with matchers
- const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
- const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
- // Explains the first positiv match and all prior negative matches...
- EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
- EXPECT_EQ("which is the same as 1", Explain(g1, 1));
- EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
- EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
- Explain(g2, 0));
- EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
- Explain(g2, 1));
- EXPECT_EQ("which is 1 more than 1", // Only the first
- Explain(g2, 2));
-}
-
-TEST(AllOfTest, HugeMatcher) {
- // Verify that using AllOf with many arguments doesn't cause
- // the compiler to exceed template instantiation depth limit.
- EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
- testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
-}
-
-TEST(AnyOfTest, HugeMatcher) {
- // Verify that using AnyOf with many arguments doesn't cause
- // the compiler to exceed template instantiation depth limit.
- EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
- testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
-}
-
-namespace adl_test {
-
-// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
-// don't issue unqualified recursive calls. If they do, the argument dependent
-// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
-// as a candidate and the compilation will break due to an ambiguous overload.
-
-// The matcher must be in the same namespace as AllOf/AnyOf to make argument
-// dependent lookup find those.
-MATCHER(M, "") { return true; }
-
-template <typename T1, typename T2>
-bool AllOf(const T1& /*t1*/, const T2& /*t2*/) { return true; }
-
-TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
- EXPECT_THAT(42, testing::AllOf(
- M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
-}
-
-template <typename T1, typename T2> bool
-AnyOf(const T1& t1, const T2& t2) { return true; }
-
-TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
- EXPECT_THAT(42, testing::AnyOf(
- M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
-}
-
-} // namespace adl_test
-
-
-TEST(AllOfTest, WorksOnMoveOnlyType) {
- std::unique_ptr<int> p(new int(3));
- EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
- EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
-}
-
-TEST(AnyOfTest, WorksOnMoveOnlyType) {
- std::unique_ptr<int> p(new int(3));
- EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
- EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
-}
-
-MATCHER(IsNotNull, "") {
- return arg != nullptr;
-}
-
-// Verifies that a matcher defined using MATCHER() can work on
-// move-only types.
-TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
- std::unique_ptr<int> p(new int(3));
- EXPECT_THAT(p, IsNotNull());
- EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
-}
-
-MATCHER_P(UniquePointee, pointee, "") {
- return *arg == pointee;
-}
-
-// Verifies that a matcher defined using MATCHER_P*() can work on
-// move-only types.
-TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
- std::unique_ptr<int> p(new int(3));
- EXPECT_THAT(p, UniquePointee(3));
- EXPECT_THAT(p, Not(UniquePointee(2)));
-}
-
-
-} // namespace
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc
index 8019f4a3..0d15e8f4 100644
--- a/googlemock/test/gmock-internal-utils_test.cc
+++ b/googlemock/test/gmock-internal-utils_test.cc
@@ -124,20 +124,6 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
ConvertIdentifierNameToWords("_Chapter11Section_1_"));
}
-TEST(PointeeOfTest, WorksForSmartPointers) {
- EXPECT_TRUE(
- (std::is_same<int, PointeeOf<std::unique_ptr<int>>::type>::value));
- EXPECT_TRUE(
- (std::is_same<std::string,
- PointeeOf<std::shared_ptr<std::string>>::type>::value));
-}
-
-TEST(PointeeOfTest, WorksForRawPointers) {
- EXPECT_TRUE((std::is_same<int, PointeeOf<int*>::type>::value));
- EXPECT_TRUE((std::is_same<const char, PointeeOf<const char*>::type>::value));
- EXPECT_TRUE((std::is_void<PointeeOf<void*>::type>::value));
-}
-
TEST(GetRawPointerTest, WorksForSmartPointers) {
const char* const raw_p1 = new const char('a'); // NOLINT
const std::unique_ptr<const char> p1(raw_p1);
diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc
index e6e8c8f4..1f48a76c 100644
--- a/googlemock/test/gmock-matchers_test.cc
+++ b/googlemock/test/gmock-matchers_test.cc
@@ -60,6 +60,8 @@
#include <sstream>
#include <string>
#include <type_traits>
+#include <unordered_map>
+#include <unordered_set>
#include <utility>
#include <vector>
@@ -87,6 +89,7 @@ using std::vector;
using testing::internal::DummyMatchResultListener;
using testing::internal::ElementMatcherPair;
using testing::internal::ElementMatcherPairs;
+using testing::internal::ElementsAreArrayMatcher;
using testing::internal::ExplainMatchFailureTupleTo;
using testing::internal::FloatingEqMatcher;
using testing::internal::FormatMatcherDescription;
@@ -140,7 +143,7 @@ Matcher<int> GreaterThan(int n) {
std::string OfType(const std::string& type_name) {
#if GTEST_HAS_RTTI
- return " (of type " + type_name + ")";
+ return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
#else
return "";
#endif
@@ -351,43 +354,43 @@ TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
EXPECT_FALSE(m2.Matches("hello"));
}
-#if GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that a C-string literal can be implicitly converted to a
-// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
+// Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
- Matcher<absl::string_view> m1 = "cats";
+ Matcher<internal::StringView> m1 = "cats";
EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs"));
- Matcher<const absl::string_view&> m2 = "cats";
+ Matcher<const internal::StringView&> m2 = "cats";
EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs"));
}
// Tests that a std::string object can be implicitly converted to a
-// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
+// Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
- Matcher<absl::string_view> m1 = std::string("cats");
+ Matcher<internal::StringView> m1 = std::string("cats");
EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs"));
- Matcher<const absl::string_view&> m2 = std::string("cats");
+ Matcher<const internal::StringView&> m2 = std::string("cats");
EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs"));
}
-// Tests that a absl::string_view object can be implicitly converted to a
-// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
+// Tests that a StringView object can be implicitly converted to a
+// Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
- Matcher<absl::string_view> m1 = absl::string_view("cats");
+ Matcher<internal::StringView> m1 = internal::StringView("cats");
EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs"));
- Matcher<const absl::string_view&> m2 = absl::string_view("cats");
+ Matcher<const internal::StringView&> m2 = internal::StringView("cats");
EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs"));
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that a std::reference_wrapper<std::string> object can be implicitly
// converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
@@ -407,7 +410,7 @@ TEST(StringMatcherTest,
// MatcherInterface* without requiring the user to explicitly
// write the type.
TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
- const MatcherInterface<int>* dummy_impl = nullptr;
+ const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;
Matcher<int> m = MakeMatcher(dummy_impl);
}
@@ -765,10 +768,11 @@ TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
- Matcher<int> m1 = Eq(0);
- Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
- EXPECT_TRUE(m2.Matches(0));
- EXPECT_FALSE(m2.Matches(1));
+ Matcher<std::unique_ptr<int>> m1 = IsNull();
+ Matcher<const std::unique_ptr<int>&> m2 =
+ SafeMatcherCast<const std::unique_ptr<int>&>(m1);
+ EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
+ EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
}
// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
@@ -1070,7 +1074,12 @@ struct MoveHelper {
MOCK_METHOD1(Call, void(MoveOnly));
};
+// Disable this test in VS 2015 (version 14), where it fails when SEH is enabled
+#if defined(_MSC_VER) && (_MSC_VER < 1910)
+TEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {
+#else
TEST(ComparisonBaseTest, WorksWithMoveOnly) {
+#endif
MoveOnly m{0};
MoveHelper helper;
@@ -1225,6 +1234,25 @@ TEST(RefTest, ExplainsResult) {
// Tests string comparison matchers.
+template <typename T = std::string>
+std::string FromStringLike(internal::StringLike<T> str) {
+ return std::string(str);
+}
+
+TEST(StringLike, TestConversions) {
+ EXPECT_EQ("foo", FromStringLike("foo"));
+ EXPECT_EQ("foo", FromStringLike(std::string("foo")));
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
+
+ // Non deducible types.
+ EXPECT_EQ("", FromStringLike({}));
+ EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
+ const char buf[] = "foo";
+ EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
+}
+
TEST(StrEqTest, MatchesEqualString) {
Matcher<const char*> m = StrEq(std::string("Hello"));
EXPECT_TRUE(m.Matches("Hello"));
@@ -1235,17 +1263,18 @@ TEST(StrEqTest, MatchesEqualString) {
EXPECT_TRUE(m2.Matches("Hello"));
EXPECT_FALSE(m2.Matches("Hi"));
-#if GTEST_HAS_ABSL
- Matcher<const absl::string_view&> m3 = StrEq("Hello");
- EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
- EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
- EXPECT_FALSE(m3.Matches(absl::string_view()));
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ Matcher<const internal::StringView&> m3 =
+ StrEq(internal::StringView("Hello"));
+ EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
+ EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
+ EXPECT_FALSE(m3.Matches(internal::StringView()));
- Matcher<const absl::string_view&> m_empty = StrEq("");
- EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
- EXPECT_TRUE(m_empty.Matches(absl::string_view()));
- EXPECT_FALSE(m_empty.Matches(absl::string_view("hello")));
-#endif // GTEST_HAS_ABSL
+ Matcher<const internal::StringView&> m_empty = StrEq("");
+ EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
+ EXPECT_TRUE(m_empty.Matches(internal::StringView()));
+ EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StrEqTest, CanDescribeSelf) {
@@ -1272,12 +1301,12 @@ TEST(StrNeTest, MatchesUnequalString) {
EXPECT_TRUE(m2.Matches("hello"));
EXPECT_FALSE(m2.Matches("Hello"));
-#if GTEST_HAS_ABSL
- Matcher<const absl::string_view> m3 = StrNe("Hello");
- EXPECT_TRUE(m3.Matches(absl::string_view("")));
- EXPECT_TRUE(m3.Matches(absl::string_view()));
- EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
-#endif // GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
+ EXPECT_TRUE(m3.Matches(internal::StringView("")));
+ EXPECT_TRUE(m3.Matches(internal::StringView()));
+ EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StrNeTest, CanDescribeSelf) {
@@ -1296,13 +1325,14 @@ TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
EXPECT_TRUE(m2.Matches("hello"));
EXPECT_FALSE(m2.Matches("Hi"));
-#if GTEST_HAS_ABSL
- Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello"));
- EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
- EXPECT_TRUE(m3.Matches(absl::string_view("hello")));
- EXPECT_FALSE(m3.Matches(absl::string_view("Hi")));
- EXPECT_FALSE(m3.Matches(absl::string_view()));
-#endif // GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ Matcher<const internal::StringView&> m3 =
+ StrCaseEq(internal::StringView("Hello"));
+ EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
+ EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
+ EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
+ EXPECT_FALSE(m3.Matches(internal::StringView()));
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
@@ -1346,13 +1376,14 @@ TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
EXPECT_TRUE(m2.Matches(""));
EXPECT_FALSE(m2.Matches("Hello"));
-#if GTEST_HAS_ABSL
- Matcher<const absl::string_view> m3 = StrCaseNe("Hello");
- EXPECT_TRUE(m3.Matches(absl::string_view("Hi")));
- EXPECT_TRUE(m3.Matches(absl::string_view()));
- EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
- EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
-#endif // GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ Matcher<const internal::StringView> m3 =
+ StrCaseNe(internal::StringView("Hello"));
+ EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
+ EXPECT_TRUE(m3.Matches(internal::StringView()));
+ EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
+ EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StrCaseNeTest, CanDescribeSelf) {
@@ -1393,25 +1424,26 @@ TEST(HasSubstrTest, WorksForCStrings) {
EXPECT_FALSE(m_empty.Matches(nullptr));
}
-#if GTEST_HAS_ABSL
-// Tests that HasSubstr() works for matching absl::string_view-typed values.
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+// Tests that HasSubstr() works for matching StringView-typed values.
TEST(HasSubstrTest, WorksForStringViewClasses) {
- const Matcher<absl::string_view> m1 = HasSubstr("foo");
- EXPECT_TRUE(m1.Matches(absl::string_view("I love food.")));
- EXPECT_FALSE(m1.Matches(absl::string_view("tofo")));
- EXPECT_FALSE(m1.Matches(absl::string_view()));
+ const Matcher<internal::StringView> m1 =
+ HasSubstr(internal::StringView("foo"));
+ EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
+ EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
+ EXPECT_FALSE(m1.Matches(internal::StringView()));
- const Matcher<const absl::string_view&> m2 = HasSubstr("foo");
- EXPECT_TRUE(m2.Matches(absl::string_view("I love food.")));
- EXPECT_FALSE(m2.Matches(absl::string_view("tofo")));
- EXPECT_FALSE(m2.Matches(absl::string_view()));
+ const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
+ EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
+ EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
+ EXPECT_FALSE(m2.Matches(internal::StringView()));
- const Matcher<const absl::string_view&> m3 = HasSubstr("");
- EXPECT_TRUE(m3.Matches(absl::string_view("foo")));
- EXPECT_TRUE(m3.Matches(absl::string_view("")));
- EXPECT_TRUE(m3.Matches(absl::string_view()));
+ const Matcher<const internal::StringView&> m3 = HasSubstr("");
+ EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
+ EXPECT_TRUE(m3.Matches(internal::StringView("")));
+ EXPECT_TRUE(m3.Matches(internal::StringView()));
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that HasSubstr(s) describes itself properly.
TEST(HasSubstrTest, CanDescribeSelf) {
@@ -1616,6 +1648,147 @@ TEST(PairTest, InsideContainsUsingMap) {
EXPECT_THAT(container, Not(Contains(Pair(3, _))));
}
+TEST(FieldsAreTest, MatchesCorrectly) {
+ std::tuple<int, std::string, double> p(25, "foo", .5);
+
+ // All fields match.
+ EXPECT_THAT(p, FieldsAre(25, "foo", .5));
+ EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
+
+ // Some don't match.
+ EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
+ EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
+ EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
+}
+
+TEST(FieldsAreTest, CanDescribeSelf) {
+ Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
+ EXPECT_EQ(
+ "has field #0 that is equal to \"foo\""
+ ", and has field #1 that is equal to 42",
+ Describe(m1));
+ EXPECT_EQ(
+ "has field #0 that isn't equal to \"foo\""
+ ", or has field #1 that isn't equal to 42",
+ DescribeNegation(m1));
+}
+
+TEST(FieldsAreTest, CanExplainMatchResultTo) {
+ // The first one that fails is the one that gives the error.
+ Matcher<std::tuple<int, int, int>> m =
+ FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
+
+ EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
+ Explain(m, std::make_tuple(-1, -2, -3)));
+ EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
+ Explain(m, std::make_tuple(1, -2, -3)));
+ EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
+ Explain(m, std::make_tuple(1, 2, -3)));
+
+ // If they all match, we get a long explanation of success.
+ EXPECT_EQ(
+ "whose all elements match, "
+ "where field #0 is a value which is 1 more than 0"
+ ", and field #1 is a value which is 2 more than 0"
+ ", and field #2 is a value which is 3 more than 0",
+ Explain(m, std::make_tuple(1, 2, 3)));
+
+ // Only print those that have an explanation.
+ m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
+ EXPECT_EQ(
+ "whose all elements match, "
+ "where field #0 is a value which is 1 more than 0"
+ ", and field #2 is a value which is 3 more than 0",
+ Explain(m, std::make_tuple(1, 0, 3)));
+
+ // If only one has an explanation, then print that one.
+ m = FieldsAre(0, GreaterThan(0), 0);
+ EXPECT_EQ(
+ "whose all elements match, "
+ "where field #1 is a value which is 1 more than 0",
+ Explain(m, std::make_tuple(0, 1, 0)));
+}
+
+#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
+TEST(FieldsAreTest, StructuredBindings) {
+ // testing::FieldsAre can also match aggregates and such with C++17 and up.
+ struct MyType {
+ int i;
+ std::string str;
+ };
+ EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
+
+ // Test all the supported arities.
+ struct MyVarType1 {
+ int a;
+ };
+ EXPECT_THAT(MyVarType1{}, FieldsAre(0));
+ struct MyVarType2 {
+ int a, b;
+ };
+ EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
+ struct MyVarType3 {
+ int a, b, c;
+ };
+ EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
+ struct MyVarType4 {
+ int a, b, c, d;
+ };
+ EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
+ struct MyVarType5 {
+ int a, b, c, d, e;
+ };
+ EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
+ struct MyVarType6 {
+ int a, b, c, d, e, f;
+ };
+ EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
+ struct MyVarType7 {
+ int a, b, c, d, e, f, g;
+ };
+ EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType8 {
+ int a, b, c, d, e, f, g, h;
+ };
+ EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType9 {
+ int a, b, c, d, e, f, g, h, i;
+ };
+ EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType10 {
+ int a, b, c, d, e, f, g, h, i, j;
+ };
+ EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType11 {
+ int a, b, c, d, e, f, g, h, i, j, k;
+ };
+ EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType12 {
+ int a, b, c, d, e, f, g, h, i, j, k, l;
+ };
+ EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType13 {
+ int a, b, c, d, e, f, g, h, i, j, k, l, m;
+ };
+ EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType14 {
+ int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
+ };
+ EXPECT_THAT(MyVarType14{},
+ FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType15 {
+ int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
+ };
+ EXPECT_THAT(MyVarType15{},
+ FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+ struct MyVarType16 {
+ int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
+ };
+ EXPECT_THAT(MyVarType16{},
+ FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
+}
+#endif
+
TEST(ContainsTest, WorksWithMoveOnly) {
ContainerHelper helper;
EXPECT_CALL(helper, Call(Contains(Pointee(2))));
@@ -1648,12 +1821,13 @@ TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
EXPECT_FALSE(m2.Matches("H"));
EXPECT_FALSE(m2.Matches(" Hi"));
-#if GTEST_HAS_ABSL
- const Matcher<absl::string_view> m_empty = StartsWith("");
- EXPECT_TRUE(m_empty.Matches(absl::string_view()));
- EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
- EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty")));
-#endif // GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ const Matcher<internal::StringView> m_empty =
+ StartsWith(internal::StringView(""));
+ EXPECT_TRUE(m_empty.Matches(internal::StringView()));
+ EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
+ EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(StartsWithTest, CanDescribeSelf) {
@@ -1676,13 +1850,14 @@ TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
EXPECT_FALSE(m2.Matches("i"));
EXPECT_FALSE(m2.Matches("Hi "));
-#if GTEST_HAS_ABSL
- const Matcher<const absl::string_view&> m4 = EndsWith("");
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ const Matcher<const internal::StringView&> m4 =
+ EndsWith(internal::StringView(""));
EXPECT_TRUE(m4.Matches("Hi"));
EXPECT_TRUE(m4.Matches(""));
- EXPECT_TRUE(m4.Matches(absl::string_view()));
- EXPECT_TRUE(m4.Matches(absl::string_view("")));
-#endif // GTEST_HAS_ABSL
+ EXPECT_TRUE(m4.Matches(internal::StringView()));
+ EXPECT_TRUE(m4.Matches(internal::StringView("")));
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(EndsWithTest, CanDescribeSelf) {
@@ -1703,16 +1878,17 @@ TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
EXPECT_FALSE(m2.Matches("az1"));
EXPECT_FALSE(m2.Matches("1az"));
-#if GTEST_HAS_ABSL
- const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z");
- EXPECT_TRUE(m3.Matches(absl::string_view("az")));
- EXPECT_TRUE(m3.Matches(absl::string_view("abcz")));
- EXPECT_FALSE(m3.Matches(absl::string_view("1az")));
- EXPECT_FALSE(m3.Matches(absl::string_view()));
- const Matcher<const absl::string_view&> m4 = MatchesRegex("");
- EXPECT_TRUE(m4.Matches(absl::string_view("")));
- EXPECT_TRUE(m4.Matches(absl::string_view()));
-#endif // GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
+ EXPECT_TRUE(m3.Matches(internal::StringView("az")));
+ EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
+ EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
+ EXPECT_FALSE(m3.Matches(internal::StringView()));
+ const Matcher<const internal::StringView&> m4 =
+ MatchesRegex(internal::StringView(""));
+ EXPECT_TRUE(m4.Matches(internal::StringView("")));
+ EXPECT_TRUE(m4.Matches(internal::StringView()));
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(MatchesRegexTest, CanDescribeSelf) {
@@ -1722,10 +1898,10 @@ TEST(MatchesRegexTest, CanDescribeSelf) {
Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
-#if GTEST_HAS_ABSL
- Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*"));
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
// Tests ContainsRegex().
@@ -1741,16 +1917,18 @@ TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
EXPECT_TRUE(m2.Matches("az1"));
EXPECT_FALSE(m2.Matches("1a"));
-#if GTEST_HAS_ABSL
- const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z"));
- EXPECT_TRUE(m3.Matches(absl::string_view("azbz")));
- EXPECT_TRUE(m3.Matches(absl::string_view("az1")));
- EXPECT_FALSE(m3.Matches(absl::string_view("1a")));
- EXPECT_FALSE(m3.Matches(absl::string_view()));
- const Matcher<const absl::string_view&> m4 = ContainsRegex("");
- EXPECT_TRUE(m4.Matches(absl::string_view("")));
- EXPECT_TRUE(m4.Matches(absl::string_view()));
-#endif // GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ const Matcher<const internal::StringView&> m3 =
+ ContainsRegex(new RE("a.*z"));
+ EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
+ EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
+ EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
+ EXPECT_FALSE(m3.Matches(internal::StringView()));
+ const Matcher<const internal::StringView&> m4 =
+ ContainsRegex(internal::StringView(""));
+ EXPECT_TRUE(m4.Matches(internal::StringView("")));
+ EXPECT_TRUE(m4.Matches(internal::StringView()));
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
TEST(ContainsRegexTest, CanDescribeSelf) {
@@ -1760,10 +1938,10 @@ TEST(ContainsRegexTest, CanDescribeSelf) {
Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
-#if GTEST_HAS_ABSL
- Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*"));
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
// Tests for wide strings.
@@ -2811,6 +2989,13 @@ TEST(TrulyTest, WorksForByRefArguments) {
EXPECT_FALSE(m.Matches(n));
}
+// Tests that Truly(predicate) provides a helpful reason when it fails.
+TEST(TrulyTest, ExplainsFailures) {
+ StringMatchResultListener listener;
+ EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));
+ EXPECT_EQ(listener.str(), "didn't satisfy the given predicate");
+}
+
// Tests that Matches(m) is a predicate satisfied by whatever that
// matches matcher m.
TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
@@ -2875,6 +3060,33 @@ TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
EXPECT_EQ("", listener2.str());
}
+MATCHER(ConstructNoArg, "") { return true; }
+MATCHER_P(Construct1Arg, arg1, "") { return true; }
+MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
+
+TEST(MatcherConstruct, ExplicitVsImplicit) {
+ {
+ // No arg constructor can be constructed with empty brace.
+ ConstructNoArgMatcher m = {};
+ (void)m;
+ // And with no args
+ ConstructNoArgMatcher m2;
+ (void)m2;
+ }
+ {
+ // The one arg constructor has an explicit constructor.
+ // This is to prevent the implicit conversion.
+ using M = Construct1ArgMatcherP<int>;
+ EXPECT_TRUE((std::is_constructible<M, int>::value));
+ EXPECT_FALSE((std::is_convertible<int, M>::value));
+ }
+ {
+ // Multiple arg matchers can be constructed with an implicit construction.
+ Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
+ (void)m;
+ }
+}
+
MATCHER_P(Really, inner_matcher, "") {
return ExplainMatchResult(inner_matcher, arg, result_listener);
}
@@ -3516,6 +3728,105 @@ TEST(PointeeTest, ReferenceToNonConstRawPointer) {
EXPECT_FALSE(m.Matches(p));
}
+TEST(PointeeTest, SmartPointer) {
+ const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
+
+ std::unique_ptr<int> n(new int(1));
+ EXPECT_TRUE(m.Matches(n));
+}
+
+TEST(PointeeTest, SmartPointerToConst) {
+ const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));
+
+ // There's no implicit conversion from unique_ptr<int> to const
+ // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
+ // matcher.
+ std::unique_ptr<const int> n(new int(1));
+ EXPECT_TRUE(m.Matches(n));
+}
+
+TEST(PointerTest, RawPointer) {
+ int n = 1;
+ const Matcher<int*> m = Pointer(Eq(&n));
+
+ EXPECT_TRUE(m.Matches(&n));
+
+ int* p = nullptr;
+ EXPECT_FALSE(m.Matches(p));
+ EXPECT_FALSE(m.Matches(nullptr));
+}
+
+TEST(PointerTest, RawPointerToConst) {
+ int n = 1;
+ const Matcher<const int*> m = Pointer(Eq(&n));
+
+ EXPECT_TRUE(m.Matches(&n));
+
+ int* p = nullptr;
+ EXPECT_FALSE(m.Matches(p));
+ EXPECT_FALSE(m.Matches(nullptr));
+}
+
+TEST(PointerTest, SmartPointer) {
+ std::unique_ptr<int> n(new int(10));
+ int* raw_n = n.get();
+ const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
+
+ EXPECT_TRUE(m.Matches(n));
+}
+
+TEST(PointerTest, SmartPointerToConst) {
+ std::unique_ptr<const int> n(new int(10));
+ const int* raw_n = n.get();
+ const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));
+
+ // There's no implicit conversion from unique_ptr<int> to const
+ // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the
+ // matcher.
+ std::unique_ptr<const int> p(new int(10));
+ EXPECT_FALSE(m.Matches(p));
+}
+
+TEST(AddressTest, NonConst) {
+ int n = 1;
+ const Matcher<int> m = Address(Eq(&n));
+
+ EXPECT_TRUE(m.Matches(n));
+
+ int other = 5;
+
+ EXPECT_FALSE(m.Matches(other));
+
+ int& n_ref = n;
+
+ EXPECT_TRUE(m.Matches(n_ref));
+}
+
+TEST(AddressTest, Const) {
+ const int n = 1;
+ const Matcher<int> m = Address(Eq(&n));
+
+ EXPECT_TRUE(m.Matches(n));
+
+ int other = 5;
+
+ EXPECT_FALSE(m.Matches(other));
+}
+
+TEST(AddressTest, MatcherDoesntCopy) {
+ std::unique_ptr<int> n(new int(1));
+ const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
+
+ EXPECT_TRUE(m.Matches(n));
+}
+
+TEST(AddressTest, Describe) {
+ Matcher<int> matcher = Address(_);
+ EXPECT_EQ("has address that is anything", Describe(matcher));
+ EXPECT_EQ("does not have address that is anything",
+ DescribeNegation(matcher));
+}
+
MATCHER_P(FieldIIs, inner_matcher, "") {
return ExplainMatchResult(inner_matcher, arg.i, result_listener);
}
@@ -3717,17 +4028,11 @@ struct AStruct {
const double y; // A const field.
Uncopyable z; // An uncopyable field.
const char* p; // A pointer field.
-
- private:
- GTEST_DISALLOW_ASSIGN_(AStruct);
};
// A derived struct for testing Field().
struct DerivedStruct : public AStruct {
char ch;
-
- private:
- GTEST_DISALLOW_ASSIGN_(DerivedStruct);
};
// Tests that Field(&Foo::field, ...) works when field is non-const.
@@ -4697,20 +5002,18 @@ TEST(SizeIsTest, ExplainsResult) {
Matcher<vector<int> > m1 = SizeIs(2);
Matcher<vector<int> > m2 = SizeIs(Lt(2u));
Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
- Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
+ Matcher<vector<int> > m4 = SizeIs(Gt(1u));
vector<int> container;
EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
EXPECT_EQ("whose size 0 matches", Explain(m2, container));
EXPECT_EQ("whose size 0 matches", Explain(m3, container));
- EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
- Explain(m4, container));
+ EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
container.push_back(0);
container.push_back(0);
EXPECT_EQ("whose size 2 matches", Explain(m1, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
- EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
- Explain(m4, container));
+ EXPECT_EQ("whose size 2 matches", Explain(m4, container));
}
#if GTEST_HAS_TYPED_TEST
@@ -6885,7 +7188,8 @@ TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
EXPECT_FALSE(result); // Implicit cast to bool.
std::string expect =
"Value of: dummy-name\nExpected: [DescribeTo]\n"
- " Actual: 1, [MatchAndExplain]";
+ " Actual: 1" +
+ OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
EXPECT_EQ(expect, result.message());
}
@@ -6896,10 +7200,1359 @@ TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
"Value of: dummy-name\nExpected: [DescribeTo]\n"
" The matcher failed on the initial attempt; but passed when rerun to "
"generate the explanation.\n"
- " Actual: 2, [MatchAndExplain]";
+ " Actual: 2" +
+ OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
EXPECT_EQ(expect, result.message());
}
+// Tests for ElementsAre().
+
+TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
+ Matcher<const vector<int>&> m = ElementsAre();
+ EXPECT_EQ("is empty", Describe(m));
+}
+
+TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
+ Matcher<vector<int>> m = ElementsAre(Gt(5));
+ EXPECT_EQ("has 1 element that is > 5", Describe(m));
+}
+
+TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
+ Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
+ EXPECT_EQ(
+ "has 2 elements where\n"
+ "element #0 is equal to \"one\",\n"
+ "element #1 is equal to \"two\"",
+ Describe(m));
+}
+
+TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
+ Matcher<vector<int>> m = ElementsAre();
+ EXPECT_EQ("isn't empty", DescribeNegation(m));
+}
+
+TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
+ Matcher<const list<int>&> m = ElementsAre(Gt(5));
+ EXPECT_EQ(
+ "doesn't have 1 element, or\n"
+ "element #0 isn't > 5",
+ DescribeNegation(m));
+}
+
+TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
+ Matcher<const list<std::string>&> m = ElementsAre("one", "two");
+ EXPECT_EQ(
+ "doesn't have 2 elements, or\n"
+ "element #0 isn't equal to \"one\", or\n"
+ "element #1 isn't equal to \"two\"",
+ DescribeNegation(m));
+}
+
+TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
+ Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
+
+ list<int> test_list;
+ test_list.push_back(1);
+ test_list.push_back(3);
+ EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
+}
+
+TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
+ Matcher<const vector<int>&> m =
+ ElementsAre(GreaterThan(1), 0, GreaterThan(2));
+
+ const int a[] = {10, 0, 100};
+ vector<int> test_vector(std::begin(a), std::end(a));
+ EXPECT_EQ(
+ "whose element #0 matches, which is 9 more than 1,\n"
+ "and whose element #2 matches, which is 98 more than 2",
+ Explain(m, test_vector));
+}
+
+TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
+ Matcher<const list<int>&> m = ElementsAre(1, 3);
+
+ list<int> test_list;
+ // No need to explain when the container is empty.
+ EXPECT_EQ("", Explain(m, test_list));
+
+ test_list.push_back(1);
+ EXPECT_EQ("which has 1 element", Explain(m, test_list));
+}
+
+TEST(ElementsAreTest, CanExplainMismatchRightSize) {
+ Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
+
+ vector<int> v;
+ v.push_back(2);
+ v.push_back(1);
+ EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
+
+ v[0] = 1;
+ EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
+ Explain(m, v));
+}
+
+TEST(ElementsAreTest, MatchesOneElementVector) {
+ vector<std::string> test_vector;
+ test_vector.push_back("test string");
+
+ EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
+}
+
+TEST(ElementsAreTest, MatchesOneElementList) {
+ list<std::string> test_list;
+ test_list.push_back("test string");
+
+ EXPECT_THAT(test_list, ElementsAre("test string"));
+}
+
+TEST(ElementsAreTest, MatchesThreeElementVector) {
+ vector<std::string> test_vector;
+ test_vector.push_back("one");
+ test_vector.push_back("two");
+ test_vector.push_back("three");
+
+ EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
+}
+
+TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
+ vector<int> test_vector;
+ test_vector.push_back(4);
+
+ EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
+}
+
+TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
+ vector<int> test_vector;
+ test_vector.push_back(4);
+
+ EXPECT_THAT(test_vector, ElementsAre(_));
+}
+
+TEST(ElementsAreTest, MatchesOneElementValue) {
+ vector<int> test_vector;
+ test_vector.push_back(4);
+
+ EXPECT_THAT(test_vector, ElementsAre(4));
+}
+
+TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
+ vector<int> test_vector;
+ test_vector.push_back(1);
+ test_vector.push_back(2);
+ test_vector.push_back(3);
+
+ EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
+}
+
+TEST(ElementsAreTest, MatchesTenElementVector) {
+ const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
+ vector<int> test_vector(std::begin(a), std::end(a));
+
+ EXPECT_THAT(test_vector,
+ // The element list can contain values and/or matchers
+ // of different types.
+ ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
+}
+
+TEST(ElementsAreTest, DoesNotMatchWrongSize) {
+ vector<std::string> test_vector;
+ test_vector.push_back("test string");
+ test_vector.push_back("test string");
+
+ Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
+ EXPECT_FALSE(m.Matches(test_vector));
+}
+
+TEST(ElementsAreTest, DoesNotMatchWrongValue) {
+ vector<std::string> test_vector;
+ test_vector.push_back("other string");
+
+ Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
+ EXPECT_FALSE(m.Matches(test_vector));
+}
+
+TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
+ vector<std::string> test_vector;
+ test_vector.push_back("one");
+ test_vector.push_back("three");
+ test_vector.push_back("two");
+
+ Matcher<vector<std::string>> m =
+ ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
+ EXPECT_FALSE(m.Matches(test_vector));
+}
+
+TEST(ElementsAreTest, WorksForNestedContainer) {
+ constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
+
+ vector<list<char>> nested;
+ for (const auto& s : strings) {
+ nested.emplace_back(s, s + strlen(s));
+ }
+
+ EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
+ ElementsAre('w', 'o', _, _, 'd')));
+ EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
+ ElementsAre('w', 'o', _, _, 'd'))));
+}
+
+TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
+ int a[] = {0, 1, 2};
+ vector<int> v(std::begin(a), std::end(a));
+
+ EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
+ EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
+}
+
+TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
+ int a[] = {0, 1, 2};
+ vector<int> v(std::begin(a), std::end(a));
+
+ EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
+ EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
+}
+
+TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
+ int array[] = {0, 1, 2};
+ EXPECT_THAT(array, ElementsAre(0, 1, _));
+ EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
+ EXPECT_THAT(array, Not(ElementsAre(0, _)));
+}
+
+class NativeArrayPassedAsPointerAndSize {
+ public:
+ NativeArrayPassedAsPointerAndSize() {}
+
+ MOCK_METHOD(void, Helper, (int* array, int size));
+
+ private:
+ GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
+};
+
+TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
+ int array[] = {0, 1};
+ ::std::tuple<int*, size_t> array_as_tuple(array, 2);
+ EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
+ EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
+
+ NativeArrayPassedAsPointerAndSize helper;
+ EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
+ helper.Helper(array, 2);
+}
+
+TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
+ const char a2[][3] = {"hi", "lo"};
+ EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
+ ElementsAre('l', 'o', '\0')));
+ EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
+ EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
+ ElementsAre('l', 'o', '\0')));
+}
+
+TEST(ElementsAreTest, AcceptsStringLiteral) {
+ std::string array[] = {"hi", "one", "two"};
+ EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
+ EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
+}
+
+// Declared here with the size unknown. Defined AFTER the following test.
+extern const char kHi[];
+
+TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
+ // The size of kHi is not known in this test, but ElementsAre() should
+ // still accept it.
+
+ std::string array1[] = {"hi"};
+ EXPECT_THAT(array1, ElementsAre(kHi));
+
+ std::string array2[] = {"ho"};
+ EXPECT_THAT(array2, Not(ElementsAre(kHi)));
+}
+
+const char kHi[] = "hi";
+
+TEST(ElementsAreTest, MakesCopyOfArguments) {
+ int x = 1;
+ int y = 2;
+ // This should make a copy of x and y.
+ ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
+ polymorphic_matcher = ElementsAre(x, y);
+ // Changing x and y now shouldn't affect the meaning of the above matcher.
+ x = y = 0;
+ const int array1[] = {1, 2};
+ EXPECT_THAT(array1, polymorphic_matcher);
+ const int array2[] = {0, 0};
+ EXPECT_THAT(array2, Not(polymorphic_matcher));
+}
+
+// Tests for ElementsAreArray(). Since ElementsAreArray() shares most
+// of the implementation with ElementsAre(), we don't test it as
+// thoroughly here.
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
+ const int a[] = {1, 2, 3};
+
+ vector<int> test_vector(std::begin(a), std::end(a));
+ EXPECT_THAT(test_vector, ElementsAreArray(a));
+
+ test_vector[2] = 0;
+ EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
+ std::array<const char*, 3> a = {{"one", "two", "three"}};
+
+ vector<std::string> test_vector(std::begin(a), std::end(a));
+ EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
+
+ const char** p = a.data();
+ test_vector[0] = "1";
+ EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
+ const char* a[] = {"one", "two", "three"};
+
+ vector<std::string> test_vector(std::begin(a), std::end(a));
+ EXPECT_THAT(test_vector, ElementsAreArray(a));
+
+ test_vector[0] = "1";
+ EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
+ const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
+ StrEq("three")};
+
+ vector<std::string> test_vector;
+ test_vector.push_back("one");
+ test_vector.push_back("two");
+ test_vector.push_back("three");
+ EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
+
+ test_vector.push_back("three");
+ EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
+ const int a[] = {1, 2, 3};
+ vector<int> test_vector(std::begin(a), std::end(a));
+ const vector<int> expected(std::begin(a), std::end(a));
+ EXPECT_THAT(test_vector, ElementsAreArray(expected));
+ test_vector.push_back(4);
+ EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
+}
+
+TEST(ElementsAreArrayTest, TakesInitializerList) {
+ const int a[5] = {1, 2, 3, 4, 5};
+ EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
+ EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
+ EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
+}
+
+TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
+ const std::string a[5] = {"a", "b", "c", "d", "e"};
+ EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
+ EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
+ EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
+}
+
+TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
+ const int a[5] = {1, 2, 3, 4, 5};
+ EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
+ EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
+}
+
+TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
+ const int a[5] = {1, 2, 3, 4, 5};
+ // The compiler cannot infer the type of the initializer list if its
+ // elements have different types. We must explicitly specify the
+ // unified element type in this case.
+ EXPECT_THAT(
+ a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
+ EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
+ {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
+ const int a[] = {1, 2, 3};
+ const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
+ vector<int> test_vector(std::begin(a), std::end(a));
+ const vector<Matcher<int>> expected(std::begin(kMatchers),
+ std::end(kMatchers));
+ EXPECT_THAT(test_vector, ElementsAreArray(expected));
+ test_vector.push_back(4);
+ EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
+}
+
+TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
+ const int a[] = {1, 2, 3};
+ const vector<int> test_vector(std::begin(a), std::end(a));
+ const vector<int> expected(std::begin(a), std::end(a));
+ EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
+ // Pointers are iterators, too.
+ EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
+ // The empty range of NULL pointers should also be okay.
+ int* const null_int = nullptr;
+ EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
+ EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
+}
+
+// Since ElementsAre() and ElementsAreArray() share much of the
+// implementation, we only do a sanity test for native arrays here.
+TEST(ElementsAreArrayTest, WorksWithNativeArray) {
+ ::std::string a[] = {"hi", "ho"};
+ ::std::string b[] = {"hi", "ho"};
+
+ EXPECT_THAT(a, ElementsAreArray(b));
+ EXPECT_THAT(a, ElementsAreArray(b, 2));
+ EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
+}
+
+TEST(ElementsAreArrayTest, SourceLifeSpan) {
+ const int a[] = {1, 2, 3};
+ vector<int> test_vector(std::begin(a), std::end(a));
+ vector<int> expect(std::begin(a), std::end(a));
+ ElementsAreArrayMatcher<int> matcher_maker =
+ ElementsAreArray(expect.begin(), expect.end());
+ EXPECT_THAT(test_vector, matcher_maker);
+ // Changing in place the values that initialized matcher_maker should not
+ // affect matcher_maker anymore. It should have made its own copy of them.
+ for (int& i : expect) {
+ i += 10;
+ }
+ EXPECT_THAT(test_vector, matcher_maker);
+ test_vector.push_back(3);
+ EXPECT_THAT(test_vector, Not(matcher_maker));
+}
+
+// Tests for the MATCHER*() macro family.
+
+// Tests that a simple MATCHER() definition works.
+
+MATCHER(IsEven, "") { return (arg % 2) == 0; }
+
+TEST(MatcherMacroTest, Works) {
+ const Matcher<int> m = IsEven();
+ EXPECT_TRUE(m.Matches(6));
+ EXPECT_FALSE(m.Matches(7));
+
+ EXPECT_EQ("is even", Describe(m));
+ EXPECT_EQ("not (is even)", DescribeNegation(m));
+ EXPECT_EQ("", Explain(m, 6));
+ EXPECT_EQ("", Explain(m, 7));
+}
+
+// This also tests that the description string can reference 'negation'.
+MATCHER(IsEven2, negation ? "is odd" : "is even") {
+ if ((arg % 2) == 0) {
+ // Verifies that we can stream to result_listener, a listener
+ // supplied by the MATCHER macro implicitly.
+ *result_listener << "OK";
+ return true;
+ } else {
+ *result_listener << "% 2 == " << (arg % 2);
+ return false;
+ }
+}
+
+// This also tests that the description string can reference matcher
+// parameters.
+MATCHER_P2(EqSumOf, x, y,
+ std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
+ PrintToString(x) + " and " + PrintToString(y)) {
+ if (arg == (x + y)) {
+ *result_listener << "OK";
+ return true;
+ } else {
+ // Verifies that we can stream to the underlying stream of
+ // result_listener.
+ if (result_listener->stream() != nullptr) {
+ *result_listener->stream() << "diff == " << (x + y - arg);
+ }
+ return false;
+ }
+}
+
+// Tests that the matcher description can reference 'negation' and the
+// matcher parameters.
+TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
+ const Matcher<int> m1 = IsEven2();
+ EXPECT_EQ("is even", Describe(m1));
+ EXPECT_EQ("is odd", DescribeNegation(m1));
+
+ const Matcher<int> m2 = EqSumOf(5, 9);
+ EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
+ EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
+}
+
+// Tests explaining match result in a MATCHER* macro.
+TEST(MatcherMacroTest, CanExplainMatchResult) {
+ const Matcher<int> m1 = IsEven2();
+ EXPECT_EQ("OK", Explain(m1, 4));
+ EXPECT_EQ("% 2 == 1", Explain(m1, 5));
+
+ const Matcher<int> m2 = EqSumOf(1, 2);
+ EXPECT_EQ("OK", Explain(m2, 3));
+ EXPECT_EQ("diff == -1", Explain(m2, 4));
+}
+
+// Tests that the body of MATCHER() can reference the type of the
+// value being matched.
+
+MATCHER(IsEmptyString, "") {
+ StaticAssertTypeEq<::std::string, arg_type>();
+ return arg.empty();
+}
+
+MATCHER(IsEmptyStringByRef, "") {
+ StaticAssertTypeEq<const ::std::string&, arg_type>();
+ return arg.empty();
+}
+
+TEST(MatcherMacroTest, CanReferenceArgType) {
+ const Matcher<::std::string> m1 = IsEmptyString();
+ EXPECT_TRUE(m1.Matches(""));
+
+ const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
+ EXPECT_TRUE(m2.Matches(""));
+}
+
+// Tests that MATCHER() can be used in a namespace.
+
+namespace matcher_test {
+MATCHER(IsOdd, "") { return (arg % 2) != 0; }
+} // namespace matcher_test
+
+TEST(MatcherMacroTest, WorksInNamespace) {
+ Matcher<int> m = matcher_test::IsOdd();
+ EXPECT_FALSE(m.Matches(4));
+ EXPECT_TRUE(m.Matches(5));
+}
+
+// Tests that Value() can be used to compose matchers.
+MATCHER(IsPositiveOdd, "") {
+ return Value(arg, matcher_test::IsOdd()) && arg > 0;
+}
+
+TEST(MatcherMacroTest, CanBeComposedUsingValue) {
+ EXPECT_THAT(3, IsPositiveOdd());
+ EXPECT_THAT(4, Not(IsPositiveOdd()));
+ EXPECT_THAT(-1, Not(IsPositiveOdd()));
+}
+
+// Tests that a simple MATCHER_P() definition works.
+
+MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
+
+TEST(MatcherPMacroTest, Works) {
+ const Matcher<int> m = IsGreaterThan32And(5);
+ EXPECT_TRUE(m.Matches(36));
+ EXPECT_FALSE(m.Matches(5));
+
+ EXPECT_EQ("is greater than 32 and 5", Describe(m));
+ EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
+ EXPECT_EQ("", Explain(m, 36));
+ EXPECT_EQ("", Explain(m, 5));
+}
+
+// Tests that the description is calculated correctly from the matcher name.
+MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
+
+TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
+ const Matcher<int> m = _is_Greater_Than32and_(5);
+
+ EXPECT_EQ("is greater than 32 and 5", Describe(m));
+ EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
+ EXPECT_EQ("", Explain(m, 36));
+ EXPECT_EQ("", Explain(m, 5));
+}
+
+// Tests that a MATCHER_P matcher can be explicitly instantiated with
+// a reference parameter type.
+
+class UncopyableFoo {
+ public:
+ explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
+
+ UncopyableFoo(const UncopyableFoo&) = delete;
+ void operator=(const UncopyableFoo&) = delete;
+
+ private:
+ char value_;
+};
+
+MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
+
+TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
+ UncopyableFoo foo1('1'), foo2('2');
+ const Matcher<const UncopyableFoo&> m =
+ ReferencesUncopyable<const UncopyableFoo&>(foo1);
+
+ EXPECT_TRUE(m.Matches(foo1));
+ EXPECT_FALSE(m.Matches(foo2));
+
+ // We don't want the address of the parameter printed, as most
+ // likely it will just annoy the user. If the address is
+ // interesting, the user should consider passing the parameter by
+ // pointer instead.
+ EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
+}
+
+// Tests that the body of MATCHER_Pn() can reference the parameter
+// types.
+
+MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
+ StaticAssertTypeEq<int, foo_type>();
+ StaticAssertTypeEq<long, bar_type>(); // NOLINT
+ StaticAssertTypeEq<char, baz_type>();
+ return arg == 0;
+}
+
+TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
+ EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
+}
+
+// Tests that a MATCHER_Pn matcher can be explicitly instantiated with
+// reference parameter types.
+
+MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
+ return &arg == &variable1 || &arg == &variable2;
+}
+
+TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
+ UncopyableFoo foo1('1'), foo2('2'), foo3('3');
+ const Matcher<const UncopyableFoo&> const_m =
+ ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
+
+ EXPECT_TRUE(const_m.Matches(foo1));
+ EXPECT_TRUE(const_m.Matches(foo2));
+ EXPECT_FALSE(const_m.Matches(foo3));
+
+ const Matcher<UncopyableFoo&> m =
+ ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
+
+ EXPECT_TRUE(m.Matches(foo1));
+ EXPECT_TRUE(m.Matches(foo2));
+ EXPECT_FALSE(m.Matches(foo3));
+}
+
+TEST(MatcherPnMacroTest,
+ GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
+ UncopyableFoo foo1('1'), foo2('2');
+ const Matcher<const UncopyableFoo&> m =
+ ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
+
+ // We don't want the addresses of the parameters printed, as most
+ // likely they will just annoy the user. If the addresses are
+ // interesting, the user should consider passing the parameters by
+ // pointers instead.
+ EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
+ Describe(m));
+}
+
+// Tests that a simple MATCHER_P2() definition works.
+
+MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
+
+TEST(MatcherPnMacroTest, Works) {
+ const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT
+ EXPECT_TRUE(m.Matches(36L));
+ EXPECT_FALSE(m.Matches(15L));
+
+ EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
+ EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
+ EXPECT_EQ("", Explain(m, 36L));
+ EXPECT_EQ("", Explain(m, 15L));
+}
+
+// Tests that MATCHER*() definitions can be overloaded on the number
+// of parameters; also tests MATCHER_Pn() where n >= 3.
+
+MATCHER(EqualsSumOf, "") { return arg == 0; }
+MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
+MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
+MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
+MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
+MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
+MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
+ return arg == a + b + c + d + e + f;
+}
+MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
+ return arg == a + b + c + d + e + f + g;
+}
+MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
+ return arg == a + b + c + d + e + f + g + h;
+}
+MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
+ return arg == a + b + c + d + e + f + g + h + i;
+}
+MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
+ return arg == a + b + c + d + e + f + g + h + i + j;
+}
+
+TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
+ EXPECT_THAT(0, EqualsSumOf());
+ EXPECT_THAT(1, EqualsSumOf(1));
+ EXPECT_THAT(12, EqualsSumOf(10, 2));
+ EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
+ EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
+ EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
+ EXPECT_THAT("abcdef",
+ EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
+ EXPECT_THAT("abcdefg",
+ EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
+ EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
+ 'f', 'g', "h"));
+ EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
+ 'f', 'g', "h", 'i'));
+ EXPECT_THAT("abcdefghij",
+ EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
+ 'i', ::std::string("j")));
+
+ EXPECT_THAT(1, Not(EqualsSumOf()));
+ EXPECT_THAT(-1, Not(EqualsSumOf(1)));
+ EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
+ EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
+ EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
+ EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
+ EXPECT_THAT("abcdef ",
+ Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
+ EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
+ "e", 'f', 'g')));
+ EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
+ "e", 'f', 'g', "h")));
+ EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
+ "e", 'f', 'g', "h", 'i')));
+ EXPECT_THAT("abcdefghij ",
+ Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
+ "h", 'i', ::std::string("j"))));
+}
+
+// Tests that a MATCHER_Pn() definition can be instantiated with any
+// compatible parameter types.
+TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
+ EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
+ EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
+
+ EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
+ EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
+}
+
+// Tests that the matcher body can promote the parameter types.
+
+MATCHER_P2(EqConcat, prefix, suffix, "") {
+ // The following lines promote the two parameters to desired types.
+ std::string prefix_str(prefix);
+ char suffix_char = static_cast<char>(suffix);
+ return arg == prefix_str + suffix_char;
+}
+
+TEST(MatcherPnMacroTest, SimpleTypePromotion) {
+ Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
+ Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
+ EXPECT_FALSE(no_promo.Matches("fool"));
+ EXPECT_FALSE(promo.Matches("fool"));
+ EXPECT_TRUE(no_promo.Matches("foot"));
+ EXPECT_TRUE(promo.Matches("foot"));
+}
+
+// Verifies the type of a MATCHER*.
+
+TEST(MatcherPnMacroTest, TypesAreCorrect) {
+ // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
+ EqualsSumOfMatcher a0 = EqualsSumOf();
+
+ // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
+ EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
+
+ // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
+ // variable, and so on.
+ EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
+ EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
+ EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
+ EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
+ EqualsSumOf(1, 2, 3, 4, '5');
+ EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
+ EqualsSumOf(1, 2, 3, 4, 5, '6');
+ EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
+ EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
+ EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
+ EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
+ EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
+ EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
+ EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
+ EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
+
+ // Avoid "unused variable" warnings.
+ (void)a0;
+ (void)a1;
+ (void)a2;
+ (void)a3;
+ (void)a4;
+ (void)a5;
+ (void)a6;
+ (void)a7;
+ (void)a8;
+ (void)a9;
+ (void)a10;
+}
+
+// Tests that matcher-typed parameters can be used in Value() inside a
+// MATCHER_Pn definition.
+
+// Succeeds if arg matches exactly 2 of the 3 matchers.
+MATCHER_P3(TwoOf, m1, m2, m3, "") {
+ const int count = static_cast<int>(Value(arg, m1)) +
+ static_cast<int>(Value(arg, m2)) +
+ static_cast<int>(Value(arg, m3));
+ return count == 2;
+}
+
+TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
+ EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
+ EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
+}
+
+// Tests Contains().
+
+TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
+ list<int> some_list;
+ some_list.push_back(3);
+ some_list.push_back(1);
+ some_list.push_back(2);
+ EXPECT_THAT(some_list, Contains(1));
+ EXPECT_THAT(some_list, Contains(Gt(2.5)));
+ EXPECT_THAT(some_list, Contains(Eq(2.0f)));
+
+ list<std::string> another_list;
+ another_list.push_back("fee");
+ another_list.push_back("fie");
+ another_list.push_back("foe");
+ another_list.push_back("fum");
+ EXPECT_THAT(another_list, Contains(std::string("fee")));
+}
+
+TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
+ list<int> some_list;
+ some_list.push_back(3);
+ some_list.push_back(1);
+ EXPECT_THAT(some_list, Not(Contains(4)));
+}
+
+TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
+ set<int> some_set;
+ some_set.insert(3);
+ some_set.insert(1);
+ some_set.insert(2);
+ EXPECT_THAT(some_set, Contains(Eq(1.0)));
+ EXPECT_THAT(some_set, Contains(Eq(3.0f)));
+ EXPECT_THAT(some_set, Contains(2));
+
+ set<std::string> another_set;
+ another_set.insert("fee");
+ another_set.insert("fie");
+ another_set.insert("foe");
+ another_set.insert("fum");
+ EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
+}
+
+TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
+ set<int> some_set;
+ some_set.insert(3);
+ some_set.insert(1);
+ EXPECT_THAT(some_set, Not(Contains(4)));
+
+ set<std::string> c_string_set;
+ c_string_set.insert("hello");
+ EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
+}
+
+TEST(ContainsTest, ExplainsMatchResultCorrectly) {
+ const int a[2] = {1, 2};
+ Matcher<const int(&)[2]> m = Contains(2);
+ EXPECT_EQ("whose element #1 matches", Explain(m, a));
+
+ m = Contains(3);
+ EXPECT_EQ("", Explain(m, a));
+
+ m = Contains(GreaterThan(0));
+ EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
+
+ m = Contains(GreaterThan(10));
+ EXPECT_EQ("", Explain(m, a));
+}
+
+TEST(ContainsTest, DescribesItselfCorrectly) {
+ Matcher<vector<int>> m = Contains(1);
+ EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
+
+ Matcher<vector<int>> m2 = Not(m);
+ EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
+}
+
+TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
+ map<std::string, int> my_map;
+ const char* bar = "a string";
+ my_map[bar] = 2;
+ EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
+
+ map<std::string, int> another_map;
+ another_map["fee"] = 1;
+ another_map["fie"] = 2;
+ another_map["foe"] = 3;
+ another_map["fum"] = 4;
+ EXPECT_THAT(another_map,
+ Contains(pair<const std::string, int>(std::string("fee"), 1)));
+ EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
+}
+
+TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
+ map<int, int> some_map;
+ some_map[1] = 11;
+ some_map[2] = 22;
+ EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
+}
+
+TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
+ const char* string_array[] = {"fee", "fie", "foe", "fum"};
+ EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
+}
+
+TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
+ int int_array[] = {1, 2, 3, 4};
+ EXPECT_THAT(int_array, Not(Contains(5)));
+}
+
+TEST(ContainsTest, AcceptsMatcher) {
+ const int a[] = {1, 2, 3};
+ EXPECT_THAT(a, Contains(Gt(2)));
+ EXPECT_THAT(a, Not(Contains(Gt(4))));
+}
+
+TEST(ContainsTest, WorksForNativeArrayAsTuple) {
+ const int a[] = {1, 2};
+ const int* const pointer = a;
+ EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
+ EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
+}
+
+TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
+ int a[][3] = {{1, 2, 3}, {4, 5, 6}};
+ EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
+ EXPECT_THAT(a, Contains(Contains(5)));
+ EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
+ EXPECT_THAT(a, Contains(Not(Contains(5))));
+}
+
+TEST(AllOfArrayTest, BasicForms) {
+ // Iterator
+ std::vector<int> v0{};
+ std::vector<int> v1{1};
+ std::vector<int> v2{2, 3};
+ std::vector<int> v3{4, 4, 4};
+ EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
+ EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
+ EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
+ EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
+ EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
+ // Pointer + size
+ int ar[6] = {1, 2, 3, 4, 4, 4};
+ EXPECT_THAT(0, AllOfArray(ar, 0));
+ EXPECT_THAT(1, AllOfArray(ar, 1));
+ EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
+ EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
+ EXPECT_THAT(4, AllOfArray(ar + 3, 3));
+ // Array
+ // int ar0[0]; Not usable
+ int ar1[1] = {1};
+ int ar2[2] = {2, 3};
+ int ar3[3] = {4, 4, 4};
+ // EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work
+ EXPECT_THAT(1, AllOfArray(ar1));
+ EXPECT_THAT(2, Not(AllOfArray(ar1)));
+ EXPECT_THAT(3, Not(AllOfArray(ar2)));
+ EXPECT_THAT(4, AllOfArray(ar3));
+ // Container
+ EXPECT_THAT(0, AllOfArray(v0));
+ EXPECT_THAT(1, AllOfArray(v1));
+ EXPECT_THAT(2, Not(AllOfArray(v1)));
+ EXPECT_THAT(3, Not(AllOfArray(v2)));
+ EXPECT_THAT(4, AllOfArray(v3));
+ // Initializer
+ EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.
+ EXPECT_THAT(1, AllOfArray({1}));
+ EXPECT_THAT(2, Not(AllOfArray({1})));
+ EXPECT_THAT(3, Not(AllOfArray({2, 3})));
+ EXPECT_THAT(4, AllOfArray({4, 4, 4}));
+}
+
+TEST(AllOfArrayTest, Matchers) {
+ // vector
+ std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
+ EXPECT_THAT(0, Not(AllOfArray(matchers)));
+ EXPECT_THAT(1, AllOfArray(matchers));
+ EXPECT_THAT(2, Not(AllOfArray(matchers)));
+ // initializer_list
+ EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
+ EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
+}
+
+TEST(AnyOfArrayTest, BasicForms) {
+ // Iterator
+ std::vector<int> v0{};
+ std::vector<int> v1{1};
+ std::vector<int> v2{2, 3};
+ EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
+ EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
+ EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
+ EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
+ EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
+ // Pointer + size
+ int ar[3] = {1, 2, 3};
+ EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
+ EXPECT_THAT(1, AnyOfArray(ar, 1));
+ EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
+ EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
+ EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
+ // Array
+ // int ar0[0]; Not usable
+ int ar1[1] = {1};
+ int ar2[2] = {2, 3};
+ // EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work
+ EXPECT_THAT(1, AnyOfArray(ar1));
+ EXPECT_THAT(2, Not(AnyOfArray(ar1)));
+ EXPECT_THAT(3, AnyOfArray(ar2));
+ EXPECT_THAT(4, Not(AnyOfArray(ar2)));
+ // Container
+ EXPECT_THAT(0, Not(AnyOfArray(v0)));
+ EXPECT_THAT(1, AnyOfArray(v1));
+ EXPECT_THAT(2, Not(AnyOfArray(v1)));
+ EXPECT_THAT(3, AnyOfArray(v2));
+ EXPECT_THAT(4, Not(AnyOfArray(v2)));
+ // Initializer
+ EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.
+ EXPECT_THAT(1, AnyOfArray({1}));
+ EXPECT_THAT(2, Not(AnyOfArray({1})));
+ EXPECT_THAT(3, AnyOfArray({2, 3}));
+ EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
+}
+
+TEST(AnyOfArrayTest, Matchers) {
+ // We negate test AllOfArrayTest.Matchers.
+ // vector
+ std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
+ EXPECT_THAT(0, AnyOfArray(matchers));
+ EXPECT_THAT(1, Not(AnyOfArray(matchers)));
+ EXPECT_THAT(2, AnyOfArray(matchers));
+ // initializer_list
+ EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
+ EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
+}
+
+TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
+ // AnyOfArray and AllOfArry use the same underlying template-template,
+ // thus it is sufficient to test one here.
+ const std::vector<int> v0{};
+ const std::vector<int> v1{1};
+ const std::vector<int> v2{2, 3};
+ const Matcher<int> m0 = AnyOfArray(v0);
+ const Matcher<int> m1 = AnyOfArray(v1);
+ const Matcher<int> m2 = AnyOfArray(v2);
+ EXPECT_EQ("", Explain(m0, 0));
+ EXPECT_EQ("", Explain(m1, 1));
+ EXPECT_EQ("", Explain(m1, 2));
+ EXPECT_EQ("", Explain(m2, 3));
+ EXPECT_EQ("", Explain(m2, 4));
+ EXPECT_EQ("()", Describe(m0));
+ EXPECT_EQ("(is equal to 1)", Describe(m1));
+ EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
+ EXPECT_EQ("()", DescribeNegation(m0));
+ EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
+ EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
+ // Explain with matchers
+ const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
+ const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
+ // Explains the first positiv match and all prior negative matches...
+ EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
+ EXPECT_EQ("which is the same as 1", Explain(g1, 1));
+ EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
+ EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
+ Explain(g2, 0));
+ EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
+ Explain(g2, 1));
+ EXPECT_EQ("which is 1 more than 1", // Only the first
+ Explain(g2, 2));
+}
+
+TEST(AllOfTest, HugeMatcher) {
+ // Verify that using AllOf with many arguments doesn't cause
+ // the compiler to exceed template instantiation depth limit.
+ EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
+ testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
+}
+
+TEST(AnyOfTest, HugeMatcher) {
+ // Verify that using AnyOf with many arguments doesn't cause
+ // the compiler to exceed template instantiation depth limit.
+ EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
+ testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
+}
+
+namespace adl_test {
+
+// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
+// don't issue unqualified recursive calls. If they do, the argument dependent
+// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
+// as a candidate and the compilation will break due to an ambiguous overload.
+
+// The matcher must be in the same namespace as AllOf/AnyOf to make argument
+// dependent lookup find those.
+MATCHER(M, "") {
+ (void)arg;
+ return true;
+}
+
+template <typename T1, typename T2>
+bool AllOf(const T1& /*t1*/, const T2& /*t2*/) {
+ return true;
+}
+
+TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
+ EXPECT_THAT(42,
+ testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
+}
+
+template <typename T1, typename T2>
+bool AnyOf(const T1&, const T2&) {
+ return true;
+}
+
+TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
+ EXPECT_THAT(42,
+ testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
+}
+
+} // namespace adl_test
+
+TEST(AllOfTest, WorksOnMoveOnlyType) {
+ std::unique_ptr<int> p(new int(3));
+ EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
+ EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
+}
+
+TEST(AnyOfTest, WorksOnMoveOnlyType) {
+ std::unique_ptr<int> p(new int(3));
+ EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
+ EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
+}
+
+MATCHER(IsNotNull, "") { return arg != nullptr; }
+
+// Verifies that a matcher defined using MATCHER() can work on
+// move-only types.
+TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
+ std::unique_ptr<int> p(new int(3));
+ EXPECT_THAT(p, IsNotNull());
+ EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
+}
+
+MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
+
+// Verifies that a matcher defined using MATCHER_P*() can work on
+// move-only types.
+TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
+ std::unique_ptr<int> p(new int(3));
+ EXPECT_THAT(p, UniquePointee(3));
+ EXPECT_THAT(p, Not(UniquePointee(2)));
+}
+
+#if GTEST_HAS_EXCEPTIONS
+
+// std::function<void()> is used below for compatibility with older copies of
+// GCC. Normally, a raw lambda is all that is needed.
+
+// Test that examples from documentation compile
+TEST(ThrowsTest, Examples) {
+ EXPECT_THAT(
+ std::function<void()>([]() { throw std::runtime_error("message"); }),
+ Throws<std::runtime_error>());
+
+ EXPECT_THAT(
+ std::function<void()>([]() { throw std::runtime_error("message"); }),
+ ThrowsMessage<std::runtime_error>(HasSubstr("message")));
+}
+
+TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
+ EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
+ Throws<std::exception>());
+}
+
+TEST(ThrowsTest, CallableExecutedExactlyOnce) {
+ size_t a = 0;
+
+ EXPECT_THAT(std::function<void()>([&a]() {
+ a++;
+ throw 10;
+ }),
+ Throws<int>());
+ EXPECT_EQ(a, 1u);
+
+ EXPECT_THAT(std::function<void()>([&a]() {
+ a++;
+ throw std::runtime_error("message");
+ }),
+ Throws<std::runtime_error>());
+ EXPECT_EQ(a, 2u);
+
+ EXPECT_THAT(std::function<void()>([&a]() {
+ a++;
+ throw std::runtime_error("message");
+ }),
+ ThrowsMessage<std::runtime_error>(HasSubstr("message")));
+ EXPECT_EQ(a, 3u);
+
+ EXPECT_THAT(std::function<void()>([&a]() {
+ a++;
+ throw std::runtime_error("message");
+ }),
+ Throws<std::runtime_error>(
+ Property(&std::runtime_error::what, HasSubstr("message"))));
+ EXPECT_EQ(a, 4u);
+}
+
+TEST(ThrowsTest, Describe) {
+ Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+ std::stringstream ss;
+ matcher.DescribeTo(&ss);
+ auto explanation = ss.str();
+ EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
+}
+
+TEST(ThrowsTest, Success) {
+ Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+ StringMatchResultListener listener;
+ EXPECT_TRUE(matcher.MatchAndExplain(
+ []() { throw std::runtime_error("error message"); }, &listener));
+ EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
+}
+
+TEST(ThrowsTest, FailWrongType) {
+ Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+ StringMatchResultListener listener;
+ EXPECT_FALSE(matcher.MatchAndExplain(
+ []() { throw std::logic_error("error message"); }, &listener));
+ EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
+ EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
+}
+
+TEST(ThrowsTest, FailWrongTypeNonStd) {
+ Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+ StringMatchResultListener listener;
+ EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
+ EXPECT_THAT(listener.str(),
+ HasSubstr("throws an exception of an unknown type"));
+}
+
+TEST(ThrowsTest, FailNoThrow) {
+ Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
+ StringMatchResultListener listener;
+ EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
+ EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
+}
+
+class ThrowsPredicateTest
+ : public TestWithParam<Matcher<std::function<void()>>> {};
+
+TEST_P(ThrowsPredicateTest, Describe) {
+ Matcher<std::function<void()>> matcher = GetParam();
+ std::stringstream ss;
+ matcher.DescribeTo(&ss);
+ auto explanation = ss.str();
+ EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
+ EXPECT_THAT(explanation, HasSubstr("error message"));
+}
+
+TEST_P(ThrowsPredicateTest, Success) {
+ Matcher<std::function<void()>> matcher = GetParam();
+ StringMatchResultListener listener;
+ EXPECT_TRUE(matcher.MatchAndExplain(
+ []() { throw std::runtime_error("error message"); }, &listener));
+ EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
+}
+
+TEST_P(ThrowsPredicateTest, FailWrongType) {
+ Matcher<std::function<void()>> matcher = GetParam();
+ StringMatchResultListener listener;
+ EXPECT_FALSE(matcher.MatchAndExplain(
+ []() { throw std::logic_error("error message"); }, &listener));
+ EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
+ EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
+}
+
+TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
+ Matcher<std::function<void()>> matcher = GetParam();
+ StringMatchResultListener listener;
+ EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
+ EXPECT_THAT(listener.str(),
+ HasSubstr("throws an exception of an unknown type"));
+}
+
+TEST_P(ThrowsPredicateTest, FailWrongMessage) {
+ Matcher<std::function<void()>> matcher = GetParam();
+ StringMatchResultListener listener;
+ EXPECT_FALSE(matcher.MatchAndExplain(
+ []() { throw std::runtime_error("wrong message"); }, &listener));
+ EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
+ EXPECT_THAT(listener.str(), Not(HasSubstr("wrong message")));
+}
+
+TEST_P(ThrowsPredicateTest, FailNoThrow) {
+ Matcher<std::function<void()>> matcher = GetParam();
+ StringMatchResultListener listener;
+ EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
+ EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ AllMessagePredicates, ThrowsPredicateTest,
+ Values(Matcher<std::function<void()>>(
+ ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
+
+// Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
+TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
+ {
+ Matcher<std::function<void()>> matcher =
+ ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
+ EXPECT_TRUE(
+ matcher.Matches([]() { throw std::runtime_error("error message"); }));
+ EXPECT_FALSE(
+ matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
+ }
+
+ {
+ Matcher<uint64_t> inner = Eq(10);
+ Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
+ EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
+ EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
+ }
+}
+
+// Tests that ThrowsMessage("message") is equivalent
+// to ThrowsMessage(Eq<std::string>("message")).
+TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
+ Matcher<std::function<void()>> matcher =
+ ThrowsMessage<std::runtime_error>("error message");
+ EXPECT_TRUE(
+ matcher.Matches([]() { throw std::runtime_error("error message"); }));
+ EXPECT_FALSE(matcher.Matches(
+ []() { throw std::runtime_error("wrong error message"); }));
+}
+
+#endif // GTEST_HAS_EXCEPTIONS
+
} // namespace
} // namespace gmock_matchers_test
} // namespace testing
diff --git a/googlemock/test/gmock-more-actions_test.cc b/googlemock/test/gmock-more-actions_test.cc
index 97ec5cf0..53bb029f 100644
--- a/googlemock/test/gmock-more-actions_test.cc
+++ b/googlemock/test/gmock-more-actions_test.cc
@@ -27,10 +27,14 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
// Google Mock - a framework for writing C++ mock classes.
//
-// This file tests the built-in actions in gmock-more-actions.h.
+// This file tests the built-in actions in gmock-actions.h.
+
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4577)
+#endif
#include "gmock/gmock-more-actions.h"
@@ -38,7 +42,9 @@
#include <memory>
#include <sstream>
#include <string>
+
#include "gmock/gmock.h"
+#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
namespace testing {
@@ -46,12 +52,9 @@ namespace gmock_more_actions_test {
using ::std::plus;
using ::std::string;
-using testing::_;
using testing::Action;
-using testing::ActionInterface;
using testing::DeleteArg;
using testing::Invoke;
-using testing::Return;
using testing::ReturnArg;
using testing::ReturnPointee;
using testing::SaveArg;
@@ -68,55 +71,27 @@ inline char Char(char ch) { return ch; }
// Sample functions and functors for testing Invoke() and etc.
int Nullary() { return 1; }
-class NullaryFunctor {
- public:
- int operator()() { return 2; }
-};
-
bool g_done = false;
-void VoidNullary() { g_done = true; }
-
-class VoidNullaryFunctor {
- public:
- void operator()() { g_done = true; }
-};
bool Unary(int x) { return x < 0; }
-const char* Plus1(const char* s) { return s + 1; }
-
-void VoidUnary(int /* n */) { g_done = true; }
-
bool ByConstRef(const std::string& s) { return s == "Hi"; }
const double g_double = 0;
bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
-std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT
-
struct UnaryFunctor {
int operator()(bool x) { return x ? 1 : -1; }
};
const char* Binary(const char* input, short n) { return input + n; } // NOLINT
-void VoidBinary(int, char) { g_done = true; }
-
int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
-void VoidTernary(int, char, bool) { g_done = true; }
-
int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; }
-void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; }
-
-std::string Concat4(const char* s1, const char* s2, const char* s3,
- const char* s4) {
- return std::string(s1) + s2 + s3 + s4;
-}
-
int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
struct SumOf5Functor {
@@ -125,11 +100,6 @@ struct SumOf5Functor {
}
};
-std::string Concat5(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5) {
- return std::string(s1) + s2 + s3 + s4 + s5;
-}
-
int SumOf6(int a, int b, int c, int d, int e, int f) {
return a + b + c + d + e + f;
}
@@ -140,11 +110,6 @@ struct SumOf6Functor {
}
};
-std::string Concat6(const char* s1, const char* s2, const char* s3,
- const char* s4, const char* s5, const char* s6) {
- return std::string(s1) + s2 + s3 + s4 + s5 + s6;
-}
-
std::string Concat7(const char* s1, const char* s2, const char* s3,
const char* s4, const char* s5, const char* s6,
const char* s7) {
@@ -604,12 +569,39 @@ TEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) {
EXPECT_THROW(a.Perform(std::make_tuple()), MyException);
}
+class Object {
+ public:
+ virtual ~Object() {}
+ virtual void Func() {}
+};
+
+class MockObject : public Object {
+ public:
+ ~MockObject() override {}
+ MOCK_METHOD(void, Func, (), (override));
+};
+
+TEST(ThrowActionTest, Times0) {
+ EXPECT_NONFATAL_FAILURE(
+ [] {
+ try {
+ MockObject m;
+ ON_CALL(m, Func()).WillByDefault([] { throw "something"; });
+ EXPECT_CALL(m, Func()).Times(0);
+ m.Func();
+ } catch (...) {
+ // Exception is caught but Times(0) still triggers a failure.
+ }
+ }(),
+ "");
+}
+
#endif // GTEST_HAS_EXCEPTIONS
// Tests that SetArrayArgument<N>(first, last) sets the elements of the array
// pointed to by the N-th (0-based) argument to values in range [first, last).
TEST(SetArrayArgumentTest, SetsTheNthArray) {
- typedef void MyFunction(bool, int*, char*);
+ using MyFunction = void(bool, int*, char*);
int numbers[] = { 1, 2, 3 };
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3);
@@ -645,7 +637,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) {
// Tests SetArrayArgument<N>(first, last) where first == last.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
- typedef void MyFunction(bool, int*);
+ using MyFunction = void(bool, int*);
int numbers[] = { 1, 2, 3 };
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers);
@@ -661,7 +653,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
// Tests SetArrayArgument<N>(first, last) where *first is convertible
// (but not equal) to the argument type.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
- typedef void MyFunction(bool, int*);
+ using MyFunction = void(bool, int*);
char chars[] = { 97, 98, 99 };
Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3);
@@ -676,7 +668,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
// Test SetArrayArgument<N>(first, last) with iterator as argument.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) {
- typedef void MyFunction(bool, std::back_insert_iterator<std::string>);
+ using MyFunction = void(bool, std::back_insert_iterator<std::string>);
std::string letters = "abc";
Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end());
@@ -694,5 +686,862 @@ TEST(ReturnPointeeTest, Works) {
EXPECT_EQ(43, a.Perform(std::make_tuple()));
}
-} // namespace gmock_generated_actions_test
+// Tests InvokeArgument<N>(...).
+
+// Tests using InvokeArgument with a nullary function.
+TEST(InvokeArgumentTest, Function0) {
+ Action<int(int, int (*)())> a = InvokeArgument<1>(); // NOLINT
+ EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary)));
+}
+
+// Tests using InvokeArgument with a unary function.
+TEST(InvokeArgumentTest, Functor1) {
+ Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT
+ EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor())));
+}
+
+// Tests using InvokeArgument with a 5-ary function.
+TEST(InvokeArgumentTest, Function5) {
+ Action<int(int (*)(int, int, int, int, int))> a = // NOLINT
+ InvokeArgument<0>(10000, 2000, 300, 40, 5);
+ EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5)));
+}
+
+// Tests using InvokeArgument with a 5-ary functor.
+TEST(InvokeArgumentTest, Functor5) {
+ Action<int(SumOf5Functor)> a = // NOLINT
+ InvokeArgument<0>(10000, 2000, 300, 40, 5);
+ EXPECT_EQ(12345, a.Perform(std::make_tuple(SumOf5Functor())));
+}
+
+// Tests using InvokeArgument with a 6-ary function.
+TEST(InvokeArgumentTest, Function6) {
+ Action<int(int (*)(int, int, int, int, int, int))> a = // NOLINT
+ InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
+ EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6)));
+}
+
+// Tests using InvokeArgument with a 6-ary functor.
+TEST(InvokeArgumentTest, Functor6) {
+ Action<int(SumOf6Functor)> a = // NOLINT
+ InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);
+ EXPECT_EQ(123456, a.Perform(std::make_tuple(SumOf6Functor())));
+}
+
+// Tests using InvokeArgument with a 7-ary function.
+TEST(InvokeArgumentTest, Function7) {
+ Action<std::string(std::string(*)(const char*, const char*, const char*,
+ const char*, const char*, const char*,
+ const char*))>
+ a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
+ EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7)));
+}
+
+// Tests using InvokeArgument with a 8-ary function.
+TEST(InvokeArgumentTest, Function8) {
+ Action<std::string(std::string(*)(const char*, const char*, const char*,
+ const char*, const char*, const char*,
+ const char*, const char*))>
+ a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
+ EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8)));
+}
+
+// Tests using InvokeArgument with a 9-ary function.
+TEST(InvokeArgumentTest, Function9) {
+ Action<std::string(std::string(*)(const char*, const char*, const char*,
+ const char*, const char*, const char*,
+ const char*, const char*, const char*))>
+ a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
+ EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9)));
+}
+
+// Tests using InvokeArgument with a 10-ary function.
+TEST(InvokeArgumentTest, Function10) {
+ Action<std::string(std::string(*)(
+ const char*, const char*, const char*, const char*, const char*,
+ const char*, const char*, const char*, const char*, const char*))>
+ a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
+ EXPECT_EQ("1234567890", a.Perform(std::make_tuple(&Concat10)));
+}
+
+// Tests using InvokeArgument with a function that takes a pointer argument.
+TEST(InvokeArgumentTest, ByPointerFunction) {
+ Action<const char*(const char* (*)(const char* input, short n))> // NOLINT
+ a = InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1));
+ EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
+}
+
+// Tests using InvokeArgument with a function that takes a const char*
+// by passing it a C-string literal.
+TEST(InvokeArgumentTest, FunctionWithCStringLiteral) {
+ Action<const char*(const char* (*)(const char* input, short n))> // NOLINT
+ a = InvokeArgument<0>("Hi", Short(1));
+ EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary)));
+}
+
+// Tests using InvokeArgument with a function that takes a const reference.
+TEST(InvokeArgumentTest, ByConstReferenceFunction) {
+ Action<bool(bool (*function)(const std::string& s))> a = // NOLINT
+ InvokeArgument<0>(std::string("Hi"));
+ // When action 'a' is constructed, it makes a copy of the temporary
+ // string object passed to it, so it's OK to use 'a' later, when the
+ // temporary object has already died.
+ EXPECT_TRUE(a.Perform(std::make_tuple(&ByConstRef)));
+}
+
+// Tests using InvokeArgument with ByRef() and a function that takes a
+// const reference.
+TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {
+ Action<bool(bool (*)(const double& x))> a = // NOLINT
+ InvokeArgument<0>(ByRef(g_double));
+ // The above line calls ByRef() on a const value.
+ EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
+
+ double x = 0;
+ a = InvokeArgument<0>(ByRef(x)); // This calls ByRef() on a non-const.
+ EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
+}
+
+// Tests DoAll(a1, a2).
+TEST(DoAllTest, TwoActions) {
+ int n = 0;
+ Action<int(int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT
+ Return(2));
+ EXPECT_EQ(2, a.Perform(std::make_tuple(&n)));
+ EXPECT_EQ(1, n);
+}
+
+// Tests DoAll(a1, a2, a3).
+TEST(DoAllTest, ThreeActions) {
+ int m = 0, n = 0;
+ Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT
+ SetArgPointee<1>(2), Return(3));
+ EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+}
+
+// Tests DoAll(a1, a2, a3, a4).
+TEST(DoAllTest, FourActions) {
+ int m = 0, n = 0;
+ char ch = '\0';
+ Action<int(int*, int*, char*)> a = // NOLINT
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ Return(3));
+ EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', ch);
+}
+
+// Tests DoAll(a1, a2, a3, a4, a5).
+TEST(DoAllTest, FiveActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0';
+ Action<int(int*, int*, char*, char*)> action = // NOLINT
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+}
+
+// Tests DoAll(a1, a2, ..., a6).
+TEST(DoAllTest, SixActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0';
+ Action<int(int*, int*, char*, char*, char*)> action = // NOLINT
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), SetArgPointee<4>('c'), Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+}
+
+// Tests DoAll(a1, a2, ..., a7).
+TEST(DoAllTest, SevenActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0', d = '\0';
+ Action<int(int*, int*, char*, char*, char*, char*)> action = // NOLINT
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'),
+ Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+ EXPECT_EQ('d', d);
+}
+
+// Tests DoAll(a1, a2, ..., a8).
+TEST(DoAllTest, EightActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0';
+ Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
+ char*)>
+ action =
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), SetArgPointee<4>('c'),
+ SetArgPointee<5>('d'), SetArgPointee<6>('e'), Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+ EXPECT_EQ('d', d);
+ EXPECT_EQ('e', e);
+}
+
+// Tests DoAll(a1, a2, ..., a9).
+TEST(DoAllTest, NineActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0';
+ Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
+ char*, char*)>
+ action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2),
+ SetArgPointee<2>('a'), SetArgPointee<3>('b'),
+ SetArgPointee<4>('c'), SetArgPointee<5>('d'),
+ SetArgPointee<6>('e'), SetArgPointee<7>('f'), Return(3));
+ EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+ EXPECT_EQ('d', d);
+ EXPECT_EQ('e', e);
+ EXPECT_EQ('f', f);
+}
+
+// Tests DoAll(a1, a2, ..., a10).
+TEST(DoAllTest, TenActions) {
+ int m = 0, n = 0;
+ char a = '\0', b = '\0', c = '\0', d = '\0';
+ char e = '\0', f = '\0', g = '\0';
+ Action<int(int*, int*, char*, char*, char*, char*, // NOLINT
+ char*, char*, char*)>
+ action =
+ DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),
+ SetArgPointee<3>('b'), SetArgPointee<4>('c'),
+ SetArgPointee<5>('d'), SetArgPointee<6>('e'),
+ SetArgPointee<7>('f'), SetArgPointee<8>('g'), Return(3));
+ EXPECT_EQ(
+ 3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g)));
+ EXPECT_EQ(1, m);
+ EXPECT_EQ(2, n);
+ EXPECT_EQ('a', a);
+ EXPECT_EQ('b', b);
+ EXPECT_EQ('c', c);
+ EXPECT_EQ('d', d);
+ EXPECT_EQ('e', e);
+ EXPECT_EQ('f', f);
+ EXPECT_EQ('g', g);
+}
+
+TEST(DoAllTest, NoArgs) {
+ bool ran_first = false;
+ Action<bool()> a =
+ DoAll([&] { ran_first = true; }, [&] { return ran_first; });
+ EXPECT_TRUE(a.Perform({}));
+}
+
+TEST(DoAllTest, MoveOnlyArgs) {
+ bool ran_first = false;
+ Action<int(std::unique_ptr<int>)> a =
+ DoAll(InvokeWithoutArgs([&] { ran_first = true; }),
+ [](std::unique_ptr<int> p) { return *p; });
+ EXPECT_EQ(7, a.Perform(std::make_tuple(std::unique_ptr<int>(new int(7)))));
+ EXPECT_TRUE(ran_first);
+}
+
+TEST(DoAllTest, ImplicitlyConvertsActionArguments) {
+ bool ran_first = false;
+ // Action<void(std::vector<int>)> isn't an
+ // Action<void(const std::vector<int>&) but can be converted.
+ Action<void(std::vector<int>)> first = [&] { ran_first = true; };
+ Action<int(std::vector<int>)> a =
+ DoAll(first, [](std::vector<int> arg) { return arg.front(); });
+ EXPECT_EQ(7, a.Perform(std::make_tuple(std::vector<int>{7})));
+ EXPECT_TRUE(ran_first);
+}
+
+// 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.
+// Also suppress C4503 decorated name length exceeded, name was truncated
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4100)
+#pragma warning(disable : 4503)
+#endif
+// Tests the ACTION*() macro family.
+
+// Tests that ACTION() can define an action that doesn't reference the
+// mock function arguments.
+ACTION(Return5) { return 5; }
+
+TEST(ActionMacroTest, WorksWhenNotReferencingArguments) {
+ Action<double()> a1 = Return5();
+ EXPECT_DOUBLE_EQ(5, a1.Perform(std::make_tuple()));
+
+ Action<int(double, bool)> a2 = Return5();
+ EXPECT_EQ(5, a2.Perform(std::make_tuple(1, true)));
+}
+
+// Tests that ACTION() can define an action that returns void.
+ACTION(IncrementArg1) { (*arg1)++; }
+
+TEST(ActionMacroTest, WorksWhenReturningVoid) {
+ Action<void(int, int*)> a1 = IncrementArg1();
+ int n = 0;
+ a1.Perform(std::make_tuple(5, &n));
+ EXPECT_EQ(1, n);
+}
+
+// Tests that the body of ACTION() can reference the type of the
+// argument.
+ACTION(IncrementArg2) {
+ StaticAssertTypeEq<int*, arg2_type>();
+ arg2_type temp = arg2;
+ (*temp)++;
+}
+
+TEST(ActionMacroTest, CanReferenceArgumentType) {
+ Action<void(int, bool, int*)> a1 = IncrementArg2();
+ int n = 0;
+ a1.Perform(std::make_tuple(5, false, &n));
+ EXPECT_EQ(1, n);
+}
+
+// Tests that the body of ACTION() can reference the argument tuple
+// via args_type and args.
+ACTION(Sum2) {
+ StaticAssertTypeEq<std::tuple<int, char, int*>, args_type>();
+ args_type args_copy = args;
+ return std::get<0>(args_copy) + std::get<1>(args_copy);
+}
+
+TEST(ActionMacroTest, CanReferenceArgumentTuple) {
+ Action<int(int, char, int*)> a1 = Sum2();
+ int dummy = 0;
+ EXPECT_EQ(11, a1.Perform(std::make_tuple(5, Char(6), &dummy)));
+}
+
+namespace {
+
+// Tests that the body of ACTION() can reference the mock function
+// type.
+int Dummy(bool flag) { return flag ? 1 : 0; }
+
+} // namespace
+
+ACTION(InvokeDummy) {
+ StaticAssertTypeEq<int(bool), function_type>();
+ function_type* fp = &Dummy;
+ return (*fp)(true);
+}
+
+TEST(ActionMacroTest, CanReferenceMockFunctionType) {
+ Action<int(bool)> a1 = InvokeDummy();
+ EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));
+ EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));
+}
+
+// Tests that the body of ACTION() can reference the mock function's
+// return type.
+ACTION(InvokeDummy2) {
+ StaticAssertTypeEq<int, return_type>();
+ return_type result = Dummy(true);
+ return result;
+}
+
+TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) {
+ Action<int(bool)> a1 = InvokeDummy2();
+ EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));
+ EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));
+}
+
+// Tests that ACTION() works for arguments passed by const reference.
+ACTION(ReturnAddrOfConstBoolReferenceArg) {
+ StaticAssertTypeEq<const bool&, arg1_type>();
+ return &arg1;
+}
+
+TEST(ActionMacroTest, WorksForConstReferenceArg) {
+ Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg();
+ const bool b = false;
+ EXPECT_EQ(&b, a.Perform(std::tuple<int, const bool&>(0, b)));
+}
+
+// Tests that ACTION() works for arguments passed by non-const reference.
+ACTION(ReturnAddrOfIntReferenceArg) {
+ StaticAssertTypeEq<int&, arg0_type>();
+ return &arg0;
+}
+
+TEST(ActionMacroTest, WorksForNonConstReferenceArg) {
+ Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg();
+ int n = 0;
+ EXPECT_EQ(&n, a.Perform(std::tuple<int&, bool, int>(n, true, 1)));
+}
+
+// Tests that ACTION() can be used in a namespace.
+namespace action_test {
+ACTION(Sum) { return arg0 + arg1; }
+} // namespace action_test
+
+TEST(ActionMacroTest, WorksInNamespace) {
+ Action<int(int, int)> a1 = action_test::Sum();
+ EXPECT_EQ(3, a1.Perform(std::make_tuple(1, 2)));
+}
+
+// Tests that the same ACTION definition works for mock functions with
+// different argument numbers.
+ACTION(PlusTwo) { return arg0 + 2; }
+
+TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) {
+ Action<int(int)> a1 = PlusTwo();
+ EXPECT_EQ(4, a1.Perform(std::make_tuple(2)));
+
+ Action<double(float, void*)> a2 = PlusTwo();
+ int dummy;
+ EXPECT_DOUBLE_EQ(6, a2.Perform(std::make_tuple(4.0f, &dummy)));
+}
+
+// Tests that ACTION_P can define a parameterized action.
+ACTION_P(Plus, n) { return arg0 + n; }
+
+TEST(ActionPMacroTest, DefinesParameterizedAction) {
+ Action<int(int m, bool t)> a1 = Plus(9);
+ EXPECT_EQ(10, a1.Perform(std::make_tuple(1, true)));
+}
+
+// Tests that the body of ACTION_P can reference the argument types
+// and the parameter type.
+ACTION_P(TypedPlus, n) {
+ arg0_type t1 = arg0;
+ n_type t2 = n;
+ return t1 + t2;
+}
+
+TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {
+ Action<int(char m, bool t)> a1 = TypedPlus(9);
+ EXPECT_EQ(10, a1.Perform(std::make_tuple(Char(1), true)));
+}
+
+// Tests that a parameterized action can be used in any mock function
+// whose type is compatible.
+TEST(ActionPMacroTest, WorksInCompatibleMockFunction) {
+ Action<std::string(const std::string& s)> a1 = Plus("tail");
+ const std::string re = "re";
+ std::tuple<const std::string> dummy = std::make_tuple(re);
+ EXPECT_EQ("retail", a1.Perform(dummy));
+}
+
+// Tests that we can use ACTION*() to define actions overloaded on the
+// number of parameters.
+
+ACTION(OverloadedAction) { return arg0 ? arg1 : "hello"; }
+
+ACTION_P(OverloadedAction, default_value) {
+ return arg0 ? arg1 : default_value;
+}
+
+ACTION_P2(OverloadedAction, true_value, false_value) {
+ return arg0 ? true_value : false_value;
+}
+
+TEST(ActionMacroTest, CanDefineOverloadedActions) {
+ using MyAction = Action<const char*(bool, const char*)>;
+
+ const MyAction a1 = OverloadedAction();
+ EXPECT_STREQ("hello", a1.Perform(std::make_tuple(false, CharPtr("world"))));
+ EXPECT_STREQ("world", a1.Perform(std::make_tuple(true, CharPtr("world"))));
+
+ const MyAction a2 = OverloadedAction("hi");
+ EXPECT_STREQ("hi", a2.Perform(std::make_tuple(false, CharPtr("world"))));
+ EXPECT_STREQ("world", a2.Perform(std::make_tuple(true, CharPtr("world"))));
+
+ const MyAction a3 = OverloadedAction("hi", "you");
+ EXPECT_STREQ("hi", a3.Perform(std::make_tuple(true, CharPtr("world"))));
+ EXPECT_STREQ("you", a3.Perform(std::make_tuple(false, CharPtr("world"))));
+}
+
+// Tests ACTION_Pn where n >= 3.
+
+ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; }
+
+TEST(ActionPnMacroTest, WorksFor3Parameters) {
+ Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4);
+ EXPECT_DOUBLE_EQ(3123.4, a1.Perform(std::make_tuple(3000, true)));
+
+ Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">");
+ const std::string re = "re";
+ std::tuple<const std::string> dummy = std::make_tuple(re);
+ EXPECT_EQ("retail->", a2.Perform(dummy));
+}
+
+ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; }
+
+TEST(ActionPnMacroTest, WorksFor4Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; }
+
+TEST(ActionPnMacroTest, WorksFor5Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) {
+ return arg0 + p0 + p1 + p2 + p3 + p4 + p5;
+}
+
+TEST(ActionPnMacroTest, WorksFor6Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) {
+ return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6;
+}
+
+TEST(ActionPnMacroTest, WorksFor7Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) {
+ return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7;
+}
+
+TEST(ActionPnMacroTest, WorksFor8Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
+ a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) {
+ return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8;
+}
+
+TEST(ActionPnMacroTest, WorksFor9Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
+ a1.Perform(std::make_tuple(10)));
+}
+
+ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) {
+ arg0_type t0 = arg0;
+ last_param_type t9 = last_param;
+ return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9;
+}
+
+TEST(ActionPnMacroTest, WorksFor10Parameters) {
+ Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
+ a1.Perform(std::make_tuple(10)));
+}
+
+// Tests that the action body can promote the parameter types.
+
+ACTION_P2(PadArgument, prefix, suffix) {
+ // The following lines promote the two parameters to desired types.
+ std::string prefix_str(prefix);
+ char suffix_char = static_cast<char>(suffix);
+ return prefix_str + arg0 + suffix_char;
+}
+
+TEST(ActionPnMacroTest, SimpleTypePromotion) {
+ Action<std::string(const char*)> no_promo =
+ PadArgument(std::string("foo"), 'r');
+ Action<std::string(const char*)> promo =
+ PadArgument("foo", static_cast<int>('r'));
+ EXPECT_EQ("foobar", no_promo.Perform(std::make_tuple(CharPtr("ba"))));
+ EXPECT_EQ("foobar", promo.Perform(std::make_tuple(CharPtr("ba"))));
+}
+
+// Tests that we can partially restrict parameter types using a
+// straight-forward pattern.
+
+// Defines a generic action that doesn't restrict the types of its
+// parameters.
+ACTION_P3(ConcatImpl, a, b, c) {
+ std::stringstream ss;
+ ss << a << b << c;
+ return ss.str();
+}
+
+// Next, we try to restrict that either the first parameter is a
+// string, or the second parameter is an int.
+
+// Defines a partially specialized wrapper that restricts the first
+// parameter to std::string.
+template <typename T1, typename T2>
+// ConcatImplActionP3 is the class template ACTION_P3 uses to
+// implement ConcatImpl. We shouldn't change the name as this
+// pattern requires the user to use it directly.
+ConcatImplActionP3<std::string, T1, T2> Concat(const std::string& a, T1 b,
+ T2 c) {
+ GTEST_INTENTIONAL_CONST_COND_PUSH_()
+ if (true) {
+ GTEST_INTENTIONAL_CONST_COND_POP_()
+ // This branch verifies that ConcatImpl() can be invoked without
+ // explicit template arguments.
+ return ConcatImpl(a, b, c);
+ } else {
+ // This branch verifies that ConcatImpl() can also be invoked with
+ // explicit template arguments. It doesn't really need to be
+ // executed as this is a compile-time verification.
+ return ConcatImpl<std::string, T1, T2>(a, b, c);
+ }
+}
+
+// Defines another partially specialized wrapper that restricts the
+// second parameter to int.
+template <typename T1, typename T2>
+ConcatImplActionP3<T1, int, T2> Concat(T1 a, int b, T2 c) {
+ return ConcatImpl(a, b, c);
+}
+
+TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) {
+ Action<const std::string()> a1 = Concat("Hello", "1", 2);
+ EXPECT_EQ("Hello12", a1.Perform(std::make_tuple()));
+
+ a1 = Concat(1, 2, 3);
+ EXPECT_EQ("123", a1.Perform(std::make_tuple()));
+}
+
+// Verifies the type of an ACTION*.
+
+ACTION(DoFoo) {}
+ACTION_P(DoFoo, p) {}
+ACTION_P2(DoFoo, p0, p1) {}
+
+TEST(ActionPnMacroTest, TypesAreCorrect) {
+ // DoFoo() must be assignable to a DoFooAction variable.
+ DoFooAction a0 = DoFoo();
+
+ // DoFoo(1) must be assignable to a DoFooActionP variable.
+ DoFooActionP<int> a1 = DoFoo(1);
+
+ // DoFoo(p1, ..., pk) must be assignable to a DoFooActionPk
+ // variable, and so on.
+ DoFooActionP2<int, char> a2 = DoFoo(1, '2');
+ PlusActionP3<int, int, char> a3 = Plus(1, 2, '3');
+ PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4');
+ PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5');
+ PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6');
+ PlusActionP7<int, int, int, int, int, int, char> a7 =
+ Plus(1, 2, 3, 4, 5, 6, '7');
+ PlusActionP8<int, int, int, int, int, int, int, char> a8 =
+ Plus(1, 2, 3, 4, 5, 6, 7, '8');
+ PlusActionP9<int, int, int, int, int, int, int, int, char> a9 =
+ Plus(1, 2, 3, 4, 5, 6, 7, 8, '9');
+ PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 =
+ Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
+
+ // Avoid "unused variable" warnings.
+ (void)a0;
+ (void)a1;
+ (void)a2;
+ (void)a3;
+ (void)a4;
+ (void)a5;
+ (void)a6;
+ (void)a7;
+ (void)a8;
+ (void)a9;
+ (void)a10;
+}
+
+// Tests that an ACTION_P*() action can be explicitly instantiated
+// with reference-typed parameters.
+
+ACTION_P(Plus1, x) { return x; }
+ACTION_P2(Plus2, x, y) { return x + y; }
+ACTION_P3(Plus3, x, y, z) { return x + y + z; }
+ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
+ return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9;
+}
+
+TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) {
+ int x = 1, y = 2, z = 3;
+ const std::tuple<> empty = std::make_tuple();
+
+ Action<int()> a = Plus1<int&>(x);
+ EXPECT_EQ(1, a.Perform(empty));
+
+ a = Plus2<const int&, int&>(x, y);
+ EXPECT_EQ(3, a.Perform(empty));
+
+ a = Plus3<int&, const int&, int&>(x, y, z);
+ EXPECT_EQ(6, a.Perform(empty));
+
+ int n[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
+ a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&,
+ int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6],
+ n[7], n[8], n[9]);
+ EXPECT_EQ(55, a.Perform(empty));
+}
+
+class TenArgConstructorClass {
+ public:
+ TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
+ int a8, int a9, int a10)
+ : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
+ int value_;
+};
+
+// Tests that ACTION_TEMPLATE works when there is no value parameter.
+ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T),
+ AND_0_VALUE_PARAMS()) {
+ return new T;
+}
+
+TEST(ActionTemplateTest, WorksWithoutValueParam) {
+ const Action<int*()> a = CreateNew<int>();
+ int* p = a.Perform(std::make_tuple());
+ delete p;
+}
+
+// Tests that ACTION_TEMPLATE works when there are value parameters.
+ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T),
+ AND_1_VALUE_PARAMS(a0)) {
+ return new T(a0);
+}
+
+TEST(ActionTemplateTest, WorksWithValueParams) {
+ const Action<int*()> a = CreateNew<int>(42);
+ int* p = a.Perform(std::make_tuple());
+ EXPECT_EQ(42, *p);
+ delete p;
+}
+
+// Tests that ACTION_TEMPLATE works for integral template parameters.
+ACTION_TEMPLATE(MyDeleteArg, HAS_1_TEMPLATE_PARAMS(int, k),
+ AND_0_VALUE_PARAMS()) {
+ delete std::get<k>(args);
+}
+
+// Resets a bool variable in the destructor.
+class BoolResetter {
+ public:
+ explicit BoolResetter(bool* value) : value_(value) {}
+ ~BoolResetter() { *value_ = false; }
+
+ private:
+ bool* value_;
+};
+
+TEST(ActionTemplateTest, WorksForIntegralTemplateParams) {
+ const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>();
+ int n = 0;
+ bool b = true;
+ auto* resetter = new BoolResetter(&b);
+ a.Perform(std::make_tuple(&n, resetter));
+ EXPECT_FALSE(b); // Verifies that resetter is deleted.
+}
+
+// Tests that ACTION_TEMPLATES works for template template parameters.
+ACTION_TEMPLATE(ReturnSmartPointer,
+ HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class,
+ Pointer),
+ AND_1_VALUE_PARAMS(pointee)) {
+ return Pointer<pointee_type>(new pointee_type(pointee));
+}
+
+TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) {
+ const Action<std::shared_ptr<int>()> a =
+ ReturnSmartPointer<std::shared_ptr>(42);
+ std::shared_ptr<int> p = a.Perform(std::make_tuple());
+ EXPECT_EQ(42, *p);
+}
+
+// Tests that ACTION_TEMPLATE works for 10 template parameters.
+template <typename T1, typename T2, typename T3, int k4, bool k5,
+ unsigned int k6, typename T7, typename T8, typename T9>
+struct GiantTemplate {
+ public:
+ explicit GiantTemplate(int a_value) : value(a_value) {}
+ int value;
+};
+
+ACTION_TEMPLATE(ReturnGiant,
+ HAS_10_TEMPLATE_PARAMS(typename, T1, typename, T2, typename, T3,
+ int, k4, bool, k5, unsigned int, k6,
+ class, T7, class, T8, class, T9,
+ template <typename T> class, T10),
+ AND_1_VALUE_PARAMS(value)) {
+ return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value);
+}
+
+TEST(ActionTemplateTest, WorksFor10TemplateParameters) {
+ using Giant = GiantTemplate<std::shared_ptr<int>, bool, double, 5, true, 6,
+ char, unsigned, int>;
+ const Action<Giant()> a = ReturnGiant<int, bool, double, 5, true, 6, char,
+ unsigned, int, std::shared_ptr>(42);
+ Giant giant = a.Perform(std::make_tuple());
+ EXPECT_EQ(42, giant.value);
+}
+
+// Tests that ACTION_TEMPLATE works for 10 value parameters.
+ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),
+ AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) {
+ return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10;
+}
+
+TEST(ActionTemplateTest, WorksFor10ValueParameters) {
+ const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ EXPECT_EQ(55, a.Perform(std::make_tuple()));
+}
+
+// Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded
+// on the number of value parameters.
+
+ACTION(ReturnSum) { return 0; }
+
+ACTION_P(ReturnSum, x) { return x; }
+
+ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),
+ AND_2_VALUE_PARAMS(v1, v2)) {
+ return static_cast<Number>(v1) + v2;
+}
+
+ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),
+ AND_3_VALUE_PARAMS(v1, v2, v3)) {
+ return static_cast<Number>(v1) + v2 + v3;
+}
+
+ACTION_TEMPLATE(ReturnSum, HAS_2_TEMPLATE_PARAMS(typename, Number, int, k),
+ AND_4_VALUE_PARAMS(v1, v2, v3, v4)) {
+ return static_cast<Number>(v1) + v2 + v3 + v4 + k;
+}
+
+TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
+ const Action<int()> a0 = ReturnSum();
+ const Action<int()> a1 = ReturnSum(1);
+ const Action<int()> a2 = ReturnSum<int>(1, 2);
+ const Action<int()> a3 = ReturnSum<int>(1, 2, 3);
+ const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5);
+ EXPECT_EQ(0, a0.Perform(std::make_tuple()));
+ EXPECT_EQ(1, a1.Perform(std::make_tuple()));
+ EXPECT_EQ(3, a2.Perform(std::make_tuple()));
+ EXPECT_EQ(6, a3.Perform(std::make_tuple()));
+ EXPECT_EQ(12345, a4.Perform(std::make_tuple()));
+}
+
+} // namespace gmock_more_actions_test
} // namespace testing
diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc
index 0a201ed7..25558ebf 100644
--- a/googlemock/test/gmock-nice-strict_test.cc
+++ b/googlemock/test/gmock-nice-strict_test.cc
@@ -67,6 +67,12 @@ class NotDefaultConstructible {
explicit NotDefaultConstructible(int) {}
};
+class CallsMockMethodInDestructor {
+ public:
+ ~CallsMockMethodInDestructor() { OnDestroy(); }
+ MOCK_METHOD(void, OnDestroy, ());
+};
+
// Defines some mock classes needed by the tests.
class Foo {
@@ -302,6 +308,13 @@ TEST(NiceMockTest, AcceptsClassNamedMock) {
nice.DoThis();
}
+TEST(NiceMockTest, IsNiceInDestructor) {
+ {
+ NiceMock<CallsMockMethodInDestructor> nice_on_destroy;
+ // Don't add an expectation for the call before the mock goes out of scope.
+ }
+}
+
TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) {
NiceMock<MockFoo> nice_foo;
EXPECT_FALSE(Mock::IsNaggy(&nice_foo));
@@ -405,6 +418,22 @@ TEST(NaggyMockTest, AcceptsClassNamedMock) {
naggy.DoThis();
}
+TEST(NaggyMockTest, IsNaggyInDestructor) {
+ const std::string saved_flag = GMOCK_FLAG(verbose);
+ GMOCK_FLAG(verbose) = "warning";
+ CaptureStdout();
+
+ {
+ NaggyMock<CallsMockMethodInDestructor> naggy_on_destroy;
+ // Don't add an expectation for the call before the mock goes out of scope.
+ }
+
+ EXPECT_THAT(GetCapturedStdout(),
+ HasSubstr("Uninteresting mock function call"));
+
+ GMOCK_FLAG(verbose) = saved_flag;
+}
+
TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) {
NaggyMock<MockFoo> naggy_foo;
EXPECT_TRUE(Mock::IsNaggy(&naggy_foo));
@@ -489,6 +518,16 @@ TEST(StrictMockTest, AcceptsClassNamedMock) {
strict.DoThis();
}
+TEST(StrictMockTest, IsStrictInDestructor) {
+ EXPECT_NONFATAL_FAILURE(
+ {
+ StrictMock<CallsMockMethodInDestructor> strict_on_destroy;
+ // Don't add an expectation for the call before the mock goes out of
+ // scope.
+ },
+ "Uninteresting mock function call");
+}
+
TEST(StrictMockTest, IsNaggy_IsNice_IsStrict) {
StrictMock<MockFoo> strict_foo;
EXPECT_FALSE(Mock::IsNaggy(&strict_foo));
diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc
index 791a2476..fa974113 100644
--- a/googlemock/test/gmock-spec-builders_test.cc
+++ b/googlemock/test/gmock-spec-builders_test.cc
@@ -2179,8 +2179,8 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
"call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. "
"See "
- "https://github.com/google/googletest/blob/master/googlemock/docs/"
- "cook_book.md#"
+ "https://github.com/google/googletest/blob/master/docs/"
+ "gmock_cook_book.md#"
"knowing-when-to-expect for details.";
// A void-returning function.
diff --git a/googlemock/test/gmock_all_test.cc b/googlemock/test/gmock_all_test.cc
index b2b2027d..fffbb8b6 100644
--- a/googlemock/test/gmock_all_test.cc
+++ b/googlemock/test/gmock_all_test.cc
@@ -37,9 +37,6 @@
// below list of actual *_test.cc files might change).
#include "test/gmock-actions_test.cc"
#include "test/gmock-cardinalities_test.cc"
-#include "test/gmock-generated-actions_test.cc"
-#include "test/gmock-generated-function-mockers_test.cc"
-#include "test/gmock-generated-matchers_test.cc"
#include "test/gmock-internal-utils_test.cc"
#include "test/gmock-matchers_test.cc"
#include "test/gmock-more-actions_test.cc"
diff --git a/googlemock/test/gmock_link_test.h b/googlemock/test/gmock_link_test.h
index 175d2bdd..5734b2e1 100644
--- a/googlemock/test/gmock_link_test.h
+++ b/googlemock/test/gmock_link_test.h
@@ -112,8 +112,8 @@
// is defined as LinkTest1 in gmock_link_test.cc and as LinkTest2 in
// gmock_link2_test.cc to avoid producing linker errors.
-#ifndef GMOCK_TEST_GMOCK_LINK_TEST_H_
-#define GMOCK_TEST_GMOCK_LINK_TEST_H_
+#ifndef GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
+#define GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
#include "gmock/gmock.h"
@@ -687,4 +687,4 @@ TEST(LinkTest, TestMatcherCast) {
EXPECT_TRUE(m.Matches(nullptr));
}
-#endif // GMOCK_TEST_GMOCK_LINK_TEST_H_
+#endif // GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_
diff --git a/googlemock/test/gmock_output_test_golden.txt b/googlemock/test/gmock_output_test_golden.txt
index 4c90b41a..4846c124 100644
--- a/googlemock/test/gmock_output_test_golden.txt
+++ b/googlemock/test/gmock_output_test_golden.txt
@@ -75,14 +75,14 @@ GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: Bar2(0, 1)
Returns: false
-NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
+NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCall
[ RUN ] GMockOutputTest.UninterestingCallToVoidFunction
GMOCK WARNING:
Uninteresting mock function call - returning directly.
Function call: Bar3(0, 1)
-NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
+NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure
@@ -266,14 +266,14 @@ Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(2, 2)
Returns: true
-NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
+NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
FILE:#:
Function call: Bar2(1, 1)
Returns: false
-NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#knowing-when-to-expect for details.
+NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
@@ -314,4 +314,4 @@ Expected: is pair (is >= 48, true)
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
FILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.
-ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object is verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
+ERROR: 3 leaked mock objects found at program exit. Expectations on a mock object are verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
diff --git a/googlemock/test/pump_test.py b/googlemock/test/pump_test.py
deleted file mode 100755
index eb5a1313..00000000
--- a/googlemock/test/pump_test.py
+++ /dev/null
@@ -1,182 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2010, Google Inc.
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""Tests for the Pump meta-programming tool."""
-
-from google3.testing.pybase import googletest
-import google3.third_party.googletest.googlemock.scripts.pump
-
-pump = google3.third_party.googletest.googlemock.scripts.pump
-Convert = pump.ConvertFromPumpSource
-StripMetaComments = pump.StripMetaComments
-
-
-class PumpTest(googletest.TestCase):
-
- def testConvertsEmptyToEmpty(self):
- self.assertEquals('', Convert('').strip())
-
- def testConvertsPlainCodeToSame(self):
- self.assertEquals('#include <stdio.h>\n',
- Convert('#include <stdio.h>\n'))
-
- def testConvertsLongIWYUPragmaToSame(self):
- long_line = '// IWYU pragma: private, include "' + (80*'a') + '.h"\n'
- self.assertEquals(long_line, Convert(long_line))
-
- def testConvertsIWYUPragmaWithLeadingSpaceToSame(self):
- long_line = ' // IWYU pragma: private, include "' + (80*'a') + '.h"\n'
- self.assertEquals(long_line, Convert(long_line))
-
- def testConvertsIWYUPragmaWithSlashStarLeaderToSame(self):
- long_line = '/* IWYU pragma: private, include "' + (80*'a') + '.h"\n'
- self.assertEquals(long_line, Convert(long_line))
-
- def testConvertsIWYUPragmaWithSlashStarAndSpacesToSame(self):
- long_line = ' /* IWYU pragma: private, include "' + (80*'a') + '.h"\n'
- self.assertEquals(long_line, Convert(long_line))
-
- def testIgnoresMetaComment(self):
- self.assertEquals('',
- Convert('$$ This is a Pump meta comment.\n').strip())
-
- def testSimpleVarDeclarationWorks(self):
- self.assertEquals('3\n',
- Convert('$var m = 3\n'
- '$m\n'))
-
- def testVarDeclarationCanReferenceEarlierVar(self):
- self.assertEquals('43 != 3;\n',
- Convert('$var a = 42\n'
- '$var b = a + 1\n'
- '$var c = (b - a)*3\n'
- '$b != $c;\n'))
-
- def testSimpleLoopWorks(self):
- self.assertEquals('1, 2, 3, 4, 5\n',
- Convert('$var n = 5\n'
- '$range i 1..n\n'
- '$for i, [[$i]]\n'))
-
- def testSimpleLoopWithCommentWorks(self):
- self.assertEquals('1, 2, 3, 4, 5\n',
- Convert('$var n = 5 $$ This is comment 1.\n'
- '$range i 1..n $$ This is comment 2.\n'
- '$for i, [[$i]]\n'))
-
- def testNonTrivialRangeExpressionsWork(self):
- self.assertEquals('1, 2, 3, 4\n',
- Convert('$var n = 5\n'
- '$range i (n/n)..(n - 1)\n'
- '$for i, [[$i]]\n'))
-
- def testLoopWithoutSeparatorWorks(self):
- self.assertEquals('a + 1 + 2 + 3;\n',
- Convert('$range i 1..3\n'
- 'a$for i [[ + $i]];\n'))
-
- def testCanGenerateDollarSign(self):
- self.assertEquals('$\n', Convert('$($)\n'))
-
- def testCanIterpolateExpressions(self):
- self.assertEquals('a[2] = 3;\n',
- Convert('$var i = 1\n'
- 'a[$(i + 1)] = $(i*4 - 1);\n'))
-
- def testConditionalWithoutElseBranchWorks(self):
- self.assertEquals('true\n',
- Convert('$var n = 5\n'
- '$if n > 0 [[true]]\n'))
-
- def testConditionalWithElseBranchWorks(self):
- self.assertEquals('true -- really false\n',
- Convert('$var n = 5\n'
- '$if n > 0 [[true]]\n'
- '$else [[false]] -- \n'
- '$if n > 10 [[really true]]\n'
- '$else [[really false]]\n'))
-
- def testConditionalWithCascadingElseBranchWorks(self):
- self.assertEquals('a\n',
- Convert('$var n = 5\n'
- '$if n > 0 [[a]]\n'
- '$elif n > 10 [[b]]\n'
- '$else [[c]]\n'))
- self.assertEquals('b\n',
- Convert('$var n = 5\n'
- '$if n > 10 [[a]]\n'
- '$elif n > 0 [[b]]\n'
- '$else [[c]]\n'))
- self.assertEquals('c\n',
- Convert('$var n = 5\n'
- '$if n > 10 [[a]]\n'
- '$elif n > 8 [[b]]\n'
- '$else [[c]]\n'))
-
- def testNestedLexicalBlocksWork(self):
- self.assertEquals('a = 5;\n',
- Convert('$var n = 5\n'
- 'a = [[$if n > 0 [[$n]]]];\n'))
-
-
-class StripMetaCommentsTest(googletest.TestCase):
-
- def testReturnsSameStringIfItContainsNoComment(self):
- self.assertEquals('', StripMetaComments(''))
- self.assertEquals(' blah ', StripMetaComments(' blah '))
- self.assertEquals('A single $ is fine.',
- StripMetaComments('A single $ is fine.'))
- self.assertEquals('multiple\nlines',
- StripMetaComments('multiple\nlines'))
-
- def testStripsSimpleComment(self):
- self.assertEquals('yes\n', StripMetaComments('yes $$ or no?\n'))
-
- def testStripsSimpleCommentWithMissingNewline(self):
- self.assertEquals('yes', StripMetaComments('yes $$ or no?'))
-
- def testStripsPureCommentLinesEntirely(self):
- self.assertEquals('yes\n',
- StripMetaComments('$$ a pure comment line.\n'
- 'yes $$ or no?\n'
- ' $$ another comment line.\n'))
-
- def testStripsCommentsFromMultiLineText(self):
- self.assertEquals('multi-\n'
- 'line\n'
- 'text is fine.',
- StripMetaComments('multi- $$ comment 1\n'
- 'line\n'
- 'text is fine. $$ comment 2'))
-
-
-if __name__ == '__main__':
- googletest.main()
diff --git a/googletest/Android.bp b/googletest/Android.bp
index a9bf8a01..6be1f26f 100644
--- a/googletest/Android.bp
+++ b/googletest/Android.bp
@@ -12,6 +12,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "external_googletest_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-BSD
+ default_applicable_licenses: ["external_googletest_license"],
+}
+
cc_defaults {
name: "libgtest_defaults",
export_include_dirs: ["include"],
@@ -57,6 +66,7 @@ cc_library_static {
defaults: ["libgtest_defaults", "libgtest_host_defaults"],
host_supported: true,
vendor_available: true,
+ product_available: true,
native_bridge_supported: true,
srcs: ["src/gtest-all.cc"],
rtti: true,
@@ -67,6 +77,7 @@ cc_library_static {
defaults: ["libgtest_defaults", "libgtest_host_defaults"],
host_supported: true,
vendor_available: true,
+ product_available: true,
native_bridge_supported: true,
srcs: ["src/gtest_main.cc"],
}
@@ -84,13 +95,15 @@ cc_library_host_static {
defaults: ["libgtest_host_defaults"],
}
-cc_defaults {
- name: "libgtest_prod_defaults",
+cc_library_headers {
+ name: "libgtest_prod_headers",
defaults: ["libgtest_defaults", "libgtest_host_defaults"],
host_supported: true,
native_bridge_supported: true,
recovery_available: true,
+ vendor_ramdisk_available: true,
vendor_available: true,
+ product_available: true,
export_include_dirs: ["include"],
apex_available: [
"//apex_available:anyapex",
@@ -99,15 +112,4 @@ cc_defaults {
min_sdk_version: "apex_inherit",
}
-// Deprecated; use libgtest_prod_headers instead.
-cc_library {
- name: "libgtest_prod",
- defaults: ["libgtest_prod_defaults"],
-}
-
-cc_library_headers {
- name: "libgtest_prod_headers",
- defaults: ["libgtest_prod_defaults"],
-}
-
// Tests are in the Android.mk. Run with external/googletest/run_tests.py.
diff --git a/googletest/Android.mk b/googletest/Android.mk
index 38a44db8..19060e8c 100644
--- a/googletest/Android.mk
+++ b/googletest/Android.mk
@@ -85,6 +85,9 @@ endef
include $(CLEAR_VARS)
LOCAL_MODULE := libgtest
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-BSD
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/../LICENSE
LOCAL_SRC_FILES := src/gtest-all.cc
LOCAL_C_INCLUDES := $(LOCAL_PATH)/src $(LOCAL_PATH)/include
LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
@@ -95,6 +98,9 @@ include $(BUILD_STATIC_LIBRARY)
# Users don't need to manually depend on both.
include $(CLEAR_VARS)
LOCAL_MODULE := libgtest_main
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-BSD
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/../LICENSE
LOCAL_SRC_FILES := src/gtest_main.cc
LOCAL_C_INCLUDES := $(LOCAL_PATH)/src $(LOCAL_PATH)/include
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
@@ -108,6 +114,9 @@ include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := googletest_static
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-BSD
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/../LICENSE
LOCAL_SRC_FILES := src/gtest-all.cc
LOCAL_C_INCLUDES := $(LOCAL_PATH)/src $(LOCAL_PATH)/include
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
@@ -116,6 +125,9 @@ include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := libgoogletest_main
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-BSD
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/../LICENSE
LOCAL_CPP_EXTENSION := .cc
LOCAL_SRC_FILES := src/gtest_main.cc
LOCAL_C_INCLUDES := $(LOCAL_PATH)/src $(LOCAL_PATH)/include
@@ -128,6 +140,9 @@ include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := googletest_shared
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-BSD
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/../LICENSE
LOCAL_SRC_FILES := src/gtest-all.cc
LOCAL_C_INCLUDES := $(LOCAL_PATH)/src $(LOCAL_PATH)/include
LOCAL_CFLAGS := -DGTEST_CREATE_SHARED_LIBRARY
@@ -137,6 +152,9 @@ include $(BUILD_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := googletest_main_shared
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-BSD
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/../LICENSE
LOCAL_SRC_FILES := src/gtest_main.cc
LOCAL_C_INCLUDES := $(LOCAL_PATH)/src $(LOCAL_PATH)/include
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt
index 4fd7b526..abdd98b7 100644
--- a/googletest/CMakeLists.txt
+++ b/googletest/CMakeLists.txt
@@ -53,7 +53,7 @@ else()
cmake_policy(SET CMP0048 NEW)
project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
endif()
-cmake_minimum_required(VERSION 2.6.4)
+cmake_minimum_required(VERSION 2.8.12)
if (POLICY CMP0063) # Visibility
cmake_policy(SET CMP0063 NEW)
@@ -92,10 +92,13 @@ include(cmake/internal_utils.cmake)
config_compiler_and_linker() # Defined in internal_utils.cmake.
+# Needed to set the namespace for both the export targets and the
+# alias libraries
+set(cmake_package_name GTest CACHE INTERNAL "")
+
# Create the CMake package file descriptors.
if (INSTALL_GTEST)
include(CMakePackageConfigHelpers)
- set(cmake_package_name GTest)
set(targets_export_name ${cmake_package_name}Targets CACHE INTERNAL "")
set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated" CACHE INTERNAL "")
set(cmake_files_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${cmake_package_name}")
@@ -126,7 +129,9 @@ include_directories(${gtest_build_include_dirs})
# are used for other targets, to ensure that gtest can be compiled by a user
# aggressive about warnings.
cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
+set_target_properties(gtest PROPERTIES VERSION ${GOOGLETEST_VERSION})
cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
+set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
# If the CMake version supports it, attach header directory information
# to the targets for when we are part of a parent build (ie being pulled
# in via add_subdirectory() rather than being a standalone build).
@@ -182,20 +187,6 @@ if (gtest_build_tests)
# 'make test' or ctest.
enable_testing()
- if (WIN32)
- file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1"
- CONTENT
-"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$<CONFIG>\"
-$env:Path = \"$project_bin;$env:Path\"
-& $args")
- elseif (MINGW OR CYGWIN)
- file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1"
- CONTENT
-"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin)
-$env:Path = \"$project_bin;$env:Path\"
-& $args")
- endif()
-
############################################################
# C++ tests built with standard compiler flags.
@@ -318,6 +309,9 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_executable(googletest-uninitialized-test_ test gtest)
py_test(googletest-uninitialized-test)
+ cxx_executable(gtest_list_output_unittest_ test gtest)
+ py_test(gtest_list_output_unittest)
+
cxx_executable(gtest_xml_outfile1_test_ test gtest_main)
cxx_executable(gtest_xml_outfile2_test_ test gtest_main)
py_test(gtest_xml_outfiles_test)
diff --git a/googletest/LICENSE b/googletest/LICENSE
index 1941a11f..ea5b6064 100644..120000
--- a/googletest/LICENSE
+++ b/googletest/LICENSE
@@ -1,28 +1 @@
-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.
+../LICENSE \ No newline at end of file
diff --git a/googletest/NOTICE b/googletest/NOTICE
index 7a694c96..ea5b6064 120000
--- a/googletest/NOTICE
+++ b/googletest/NOTICE
@@ -1 +1 @@
-LICENSE \ No newline at end of file
+../LICENSE \ No newline at end of file
diff --git a/googletest/README.md b/googletest/README.md
index 904048f4..1f8b349a 100644
--- a/googletest/README.md
+++ b/googletest/README.md
@@ -2,39 +2,51 @@
#### Setup
-To build Google Test and your tests that use it, you need to tell your build
+To build GoogleTest and your tests that use it, you need to tell your build
system where to find its headers and source files. The exact way to do it
depends on which build system you use, and is usually straightforward.
### Build with CMake
-Google Test comes with a CMake build script
+GoogleTest comes with a CMake build script
([CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt))
that can be used on a wide range of platforms ("C" stands for cross-platform.).
If you don't have CMake installed already, you can download it for free from
<http://www.cmake.org/>.
CMake works by generating native makefiles or build projects that can be used in
-the compiler environment of your choice. You can either build Google Test as a
+the compiler environment of your choice. You can either build GoogleTest as a
standalone project or it can be incorporated into an existing CMake build for
another project.
#### Standalone CMake Project
-When building Google Test as a standalone project, the typical workflow starts
-with:
+When building GoogleTest as a standalone project, the typical workflow starts
+with
- mkdir mybuild # Create a directory to hold the build output.
- cd mybuild
- cmake ${GTEST_DIR} # Generate native build scripts.
+```
+git clone https://github.com/google/googletest.git -b release-1.10.0
+cd googletest # Main directory of the cloned repository.
+mkdir build # Create a directory to hold the build output.
+cd build
+cmake .. # Generate native build scripts for GoogleTest.
+```
-If you want to build Google Test's samples, you should replace the last command
-with
+The above command also includes GoogleMock by default. And so, if you want to
+build only GoogleTest, you should replace the last command with
- cmake -Dgtest_build_samples=ON ${GTEST_DIR}
+```
+cmake .. -DBUILD_GMOCK=OFF
+```
If you are on a \*nix system, you should now see a Makefile in the current
-directory. Just type 'make' to build gtest.
+directory. Just type `make` to build GoogleTest. And then you can simply install
+GoogleTest if you are a system administrator.
+
+```
+make
+sudo make install # Install in /usr/local/ by default
+```
If you use Windows and have Visual Studio installed, a `gtest.sln` file and
several `.vcproj` files will be created. You can then build them using Visual
@@ -44,13 +56,19 @@ On Mac OS X with Xcode installed, a `.xcodeproj` file will be generated.
#### Incorporating Into An Existing CMake Project
-If you want to use gtest in a project which already uses CMake, then a more
-robust and flexible approach is to build gtest as part of that project directly.
-This is done by making the GoogleTest source code available to the main build
-and adding it using CMake's `add_subdirectory()` command. This has the
-significant advantage that the same compiler and linker settings are used
-between gtest and the rest of your project, so issues associated with using
-incompatible libraries (eg debug/release), etc. are avoided. This is
+If you want to use GoogleTest in a project which already uses CMake, the easiest
+way is to get installed libraries and headers.
+
+* Import GoogleTest by using `find_package` (or `pkg_check_modules`). For
+ example, if `find_package(GTest CONFIG REQUIRED)` succeeds, you can use the
+ libraries as `GTest::gtest`, `GTest::gmock`.
+
+And a more robust and flexible approach is to build GoogleTest as part of that
+project directly. This is done by making the GoogleTest source code available to
+the main build and adding it using CMake's `add_subdirectory()` command. This
+has the significant advantage that the same compiler and linker settings are
+used between GoogleTest and the rest of your project, so issues associated with
+using incompatible libraries (eg debug/release), etc. are avoided. This is
particularly useful on Windows. Making GoogleTest's source code available to the
main build can be done a few different ways:
@@ -64,68 +82,23 @@ main build can be done a few different ways:
possible or appropriate. Git submodules, for example, have their own set of
advantages and drawbacks.
* Use CMake to download GoogleTest as part of the build's configure step. This
- is just a little more complex, but doesn't have the limitations of the other
- methods.
+ approach doesn't have the limitations of the other methods.
-The last of the above methods is implemented with a small piece of CMake code in
-a separate file (e.g. `CMakeLists.txt.in`) which is copied to the build area and
-then invoked as a sub-build _during the CMake stage_. That directory is then
-pulled into the main build with `add_subdirectory()`. For example:
+The last of the above methods is implemented with a small piece of CMake code
+that downloads and pulls the GoogleTest code into the main build.
-New file `CMakeLists.txt.in`:
+Just add to your `CMakeLists.txt`:
```cmake
-cmake_minimum_required(VERSION 2.8.2)
-
-project(googletest-download NONE)
-
-include(ExternalProject)
-ExternalProject_Add(googletest
- GIT_REPOSITORY https://github.com/google/googletest.git
- GIT_TAG master
- SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-src"
- BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-build"
- CONFIGURE_COMMAND ""
- BUILD_COMMAND ""
- INSTALL_COMMAND ""
- TEST_COMMAND ""
+include(FetchContent)
+FetchContent_Declare(
+ googletest
+ # Specify the commit you depend on and update it regularly.
+ URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)
-```
-
-Existing build's `CMakeLists.txt`:
-
-```cmake
-# Download and unpack googletest at configure time
-configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
-execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
- RESULT_VARIABLE result
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
-if(result)
- message(FATAL_ERROR "CMake step for googletest failed: ${result}")
-endif()
-execute_process(COMMAND ${CMAKE_COMMAND} --build .
- RESULT_VARIABLE result
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
-if(result)
- message(FATAL_ERROR "Build step for googletest failed: ${result}")
-endif()
-
-# Prevent overriding the parent project's compiler/linker
-# settings on Windows
+# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
-
-# Add googletest directly to our build. This defines
-# the gtest and gtest_main targets.
-add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/googletest-src
- ${CMAKE_CURRENT_BINARY_DIR}/googletest-build
- EXCLUDE_FROM_ALL)
-
-# The gtest/gtest_main targets carry header search path
-# dependencies automatically when using CMake 2.8.11 or
-# later. Otherwise we have to add them here ourselves.
-if (CMAKE_VERSION VERSION_LESS 2.8.11)
- include_directories("${gtest_SOURCE_DIR}/include")
-endif()
+FetchContent_MakeAvailable(googletest)
# Now simply link against gtest or gtest_main as needed. Eg
add_executable(example example.cpp)
@@ -133,20 +106,18 @@ target_link_libraries(example gtest_main)
add_test(NAME example_test COMMAND example)
```
-Note that this approach requires CMake 2.8.2 or later due to its use of the
-`ExternalProject_Add()` command. The above technique is discussed in more detail
-in [this separate article](http://crascit.com/2015/07/25/cmake-gtest/) which
-also contains a link to a fully generalized implementation of the technique.
+Note that this approach requires CMake 3.14 or later due to its use of the
+`FetchContent_MakeAvailable()` command.
##### Visual Studio Dynamic vs Static Runtimes
By default, new Visual Studio projects link the C runtimes dynamically but
-Google Test links them statically. This will generate an error that looks
+GoogleTest links them statically. This will generate an error that looks
something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch
detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value
'MDd_DynamicDebug' in main.obj
-Google Test already has a CMake option for this: `gtest_force_shared_crt`
+GoogleTest already has a CMake option for this: `gtest_force_shared_crt`
Enabling this option will make gtest link the runtimes dynamically too, and
match the project in which it is included.
@@ -154,17 +125,17 @@ match the project in which it is included.
#### C++ Standard Version
An environment that supports C++11 is required in order to successfully build
-Google Test. One way to ensure this is to specify the standard in the top-level
+GoogleTest. One way to ensure this is to specify the standard in the top-level
project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command. If this
-is not feasible, for example in a C project using Google Test for validation,
+is not feasible, for example in a C project using GoogleTest for validation,
then it can be specified by adding it to the options for cmake via the
`DCMAKE_CXX_FLAGS` option.
-### Tweaking Google Test
+### Tweaking GoogleTest
-Google Test can be used in diverse environments. The default configuration may
+GoogleTest can be used in diverse environments. The default configuration may
not work (or may not work well) out of the box in some environments. However,
-you can easily tweak Google Test by defining control macros on the compiler
+you can easily tweak GoogleTest by defining control macros on the compiler
command line. Generally, these macros are named like `GTEST_XYZ` and you define
them to either 1 or 0 to enable or disable a certain feature.
@@ -173,12 +144,12 @@ We list the most frequently used macros below. For a complete list, see file
### Multi-threaded Tests
-Google Test is thread-safe where the pthread library is available. After
+GoogleTest is thread-safe where the pthread library is available. After
`#include "gtest/gtest.h"`, you can check the
`GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is
`#defined` to 1, no if it's undefined.).
-If Google Test doesn't correctly detect whether pthread is available in your
+If GoogleTest doesn't correctly detect whether pthread is available in your
environment, you can force it with
-DGTEST_HAS_PTHREAD=1
@@ -187,16 +158,16 @@ or
-DGTEST_HAS_PTHREAD=0
-When Google Test uses pthread, you may need to add flags to your compiler and/or
+When GoogleTest uses pthread, you may need to add flags to your compiler and/or
linker to select the pthread library, or you'll get link errors. If you use the
-CMake script or the deprecated Autotools script, this is taken care of for you.
-If you use your own build script, you'll need to read your compiler and linker's
-manual to figure out what flags to add.
+CMake script, this is taken care of for you. If you use your own build script,
+you'll need to read your compiler and linker's manual to figure out what flags
+to add.
### As a Shared Library (DLL)
-Google Test is compact, so most users can build and link it as a static library
-for the simplicity. You can choose to use Google Test as a shared library (known
+GoogleTest is compact, so most users can build and link it as a static library
+for the simplicity. You can choose to use GoogleTest as a shared library (known
as a DLL on Windows) if you prefer.
To compile *gtest* as a shared library, add
@@ -216,22 +187,22 @@ Note: while the above steps aren't technically necessary today when using some
compilers (e.g. GCC), they may become necessary in the future, if we decide to
improve the speed of loading the library (see
<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended
-to always add the above flags when using Google Test as a shared library.
-Otherwise a future release of Google Test may break your build script.
+to always add the above flags when using GoogleTest as a shared library.
+Otherwise a future release of GoogleTest may break your build script.
### Avoiding Macro Name Clashes
In C++, macros don't obey namespaces. Therefore two libraries that both define a
macro of the same name will clash if you `#include` both definitions. In case a
-Google Test macro clashes with another library, you can force Google Test to
+GoogleTest macro clashes with another library, you can force GoogleTest to
rename its macro to avoid the conflict.
-Specifically, if both Google Test and some other code define macro FOO, you can
+Specifically, if both GoogleTest and some other code define macro FOO, you can
add
-DGTEST_DONT_DEFINE_FOO=1
-to the compiler flags to tell Google Test to change the macro's name from `FOO`
+to the compiler flags to tell GoogleTest to change the macro's name from `FOO`
to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For
example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
diff --git a/googletest/cmake/gtest_main.pc.in b/googletest/cmake/gtest_main.pc.in
index 1e01bd19..38c88c54 100644
--- a/googletest/cmake/gtest_main.pc.in
+++ b/googletest/cmake/gtest_main.pc.in
@@ -5,6 +5,6 @@ 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@
diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake
index 2f70f0b0..8d8d60a8 100644
--- a/googletest/cmake/internal_utils.cmake
+++ b/googletest/cmake/internal_utils.cmake
@@ -72,7 +72,7 @@ macro(config_compiler_and_linker)
if (MSVC)
# Newlines inside flags variables break CMake's NMake generator.
# TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds.
- set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J -Zi")
+ set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J")
set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32")
set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN")
set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1")
@@ -81,6 +81,8 @@ macro(config_compiler_and_linker)
# Suppress "unreachable code" warning
# http://stackoverflow.com/questions/3232669 explains the issue.
set(cxx_base_flags "${cxx_base_flags} -wd4702")
+ # Ensure MSVC treats source files as UTF-8 encoded.
+ set(cxx_base_flags "${cxx_base_flags} -utf-8")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(cxx_base_flags "-Wall -Wshadow -Werror -Wconversion")
set(cxx_exception_flags "-fexceptions")
@@ -148,6 +150,7 @@ function(cxx_library_with_type name type cxx_flags)
# type can be either STATIC or SHARED to denote a static or shared library.
# ARGN refers to additional arguments after 'cxx_flags'.
add_library(${name} ${type} ${ARGN})
+ add_library(${cmake_package_name}::${name} ALIAS ${name})
set_target_properties(${name}
PROPERTIES
COMPILE_FLAGS "${cxx_flags}")
@@ -188,6 +191,10 @@ function(cxx_library_with_type name type cxx_flags)
endif()
target_link_libraries(${name} PUBLIC ${threads_spec})
endif()
+
+ if (NOT "${CMAKE_VERSION}" VERSION_LESS "3.8")
+ target_compile_features(${name} PUBLIC cxx_std_11)
+ endif()
endfunction()
########################################################################
@@ -240,7 +247,13 @@ function(cxx_executable name dir libs)
endfunction()
# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
-find_package(PythonInterp)
+if ("${CMAKE_VERSION}" VERSION_LESS "3.12.0")
+ find_package(PythonInterp)
+else()
+ find_package(Python COMPONENTS Interpreter)
+ set(PYTHONINTERP_FOUND ${Python_Interpreter_FOUND})
+ set(PYTHON_EXECUTABLE ${Python_EXECUTABLE})
+endif()
# cxx_test_with_flags(name cxx_flags libs srcs...)
#
@@ -248,13 +261,7 @@ find_package(PythonInterp)
# from the given source files with the given compiler flags.
function(cxx_test_with_flags name cxx_flags libs)
cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN})
- if (WIN32 OR MINGW)
- add_test(NAME ${name}
- COMMAND "powershell" "-Command" "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1" "$<TARGET_FILE:${name}>")
- else()
- add_test(NAME ${name}
- COMMAND "$<TARGET_FILE:${name}>")
- endif()
+ add_test(NAME ${name} COMMAND "$<TARGET_FILE:${name}>")
endfunction()
# cxx_test(name libs srcs...)
@@ -278,45 +285,24 @@ function(py_test name)
# Multi-configuration build generators as for Visual Studio save
# output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug,
# Release etc.), so we have to provide it here.
- if (WIN32 OR MINGW)
- add_test(NAME ${name}
- COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/RunTest.ps1
- ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
- else()
- add_test(NAME ${name}
- COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
+ add_test(NAME ${name}
+ COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
- endif()
else (CMAKE_CONFIGURATION_TYPES)
# Single-configuration build generators like Makefile generators
# don't have subdirs below CMAKE_CURRENT_BINARY_DIR.
- if (WIN32 OR MINGW)
- add_test(NAME ${name}
- COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1
- ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
- else()
- add_test(NAME ${name}
- COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
- endif()
+ add_test(NAME ${name}
+ COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
+ --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
endif (CMAKE_CONFIGURATION_TYPES)
else()
# ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can
# directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
# only at ctest runtime (by calling ctest -c <Configuration>), so
# we have to escape $ to delay variable substitution here.
- if (WIN32 OR MINGW)
- add_test(NAME ${name}
- COMMAND powershell -Command ${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1
- ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
- else()
- add_test(NAME ${name}
- COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
- --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
- endif()
+ add_test(NAME ${name}
+ COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
+ --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
endif()
endif(PYTHONINTERP_FOUND)
endfunction()
diff --git a/googletest/docs/README.md b/googletest/docs/README.md
new file mode 100644
index 00000000..1bc57b79
--- /dev/null
+++ b/googletest/docs/README.md
@@ -0,0 +1,4 @@
+# Content Moved
+
+We are working on updates to the GoogleTest documentation, which has moved to
+the top-level [docs](../../docs) directory.
diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h
index dc878ffb..adfb1921 100644
--- a/googletest/include/gtest/gtest-death-test.h
+++ b/googletest/include/gtest/gtest-death-test.h
@@ -35,8 +35,8 @@
// directly.
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
#include "gtest/internal/gtest-death-test-internal.h"
@@ -190,11 +190,10 @@ GTEST_API_ bool InDeathTestChild();
class GTEST_API_ ExitedWithCode {
public:
explicit ExitedWithCode(int exit_code);
+ ExitedWithCode(const ExitedWithCode&) = default;
+ void operator=(const ExitedWithCode& other) = delete;
bool operator()(int exit_status) const;
private:
- // No implementation - assignment is unsupported.
- void operator=(const ExitedWithCode& other);
-
const int exit_code_;
};
@@ -340,4 +339,4 @@ class GTEST_API_ KilledBySignal {
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h
index d9b28e08..2bd3dcf6 100644
--- a/googletest/include/gtest/gtest-matchers.h
+++ b/googletest/include/gtest/gtest-matchers.h
@@ -32,13 +32,10 @@
// This file implements just enough of the matcher interface to allow
// EXPECT_DEATH and friends to accept a matcher argument.
-// IWYU pragma: private, include "testing/base/public/gunit.h"
-// IWYU pragma: friend third_party/googletest/googlemock/.*
-// IWYU pragma: friend third_party/googletest/googletest/.*
-
-#ifndef GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
-#define GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
+#include <atomic>
#include <memory>
#include <ostream>
#include <string>
@@ -63,20 +60,16 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(
namespace testing {
// To implement a matcher Foo for type T, define:
-// 1. a class FooMatcherImpl that implements the
-// MatcherInterface<T> interface, and
-// 2. a factory function that creates a Matcher<T> object from a
-// FooMatcherImpl*.
-//
-// The two-level delegation design makes it possible to allow a user
-// to write "v" instead of "Eq(v)" where a Matcher is expected, which
-// is impossible if we pass matchers by pointers. It also eases
-// ownership management as Matcher objects can now be copied like
-// plain values.
-
-// MatchResultListener is an abstract class. Its << operator can be
-// used by a matcher to explain why a value matches or doesn't match.
+// 1. a class FooMatcherMatcher that implements the matcher interface:
+// using is_gtest_matcher = void;
+// bool MatchAndExplain(const T&, std::ostream*);
+// (MatchResultListener* can also be used instead of std::ostream*)
+// void DescribeTo(std::ostream*);
+// void DescribeNegationTo(std::ostream*);
//
+// 2. a factory function that creates a Matcher<T> object from a
+// FooMatcherMatcher.
+
class MatchResultListener {
public:
// Creates a listener object with the given underlying ostream. The
@@ -181,31 +174,6 @@ class MatcherInterface : public MatcherDescriberInterface {
namespace internal {
-// Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
-template <typename T>
-class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
- public:
- explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
- : impl_(impl) {}
- ~MatcherInterfaceAdapter() override { delete impl_; }
-
- void DescribeTo(::std::ostream* os) const override { impl_->DescribeTo(os); }
-
- void DescribeNegationTo(::std::ostream* os) const override {
- impl_->DescribeNegationTo(os);
- }
-
- bool MatchAndExplain(const T& x,
- MatchResultListener* listener) const override {
- return impl_->MatchAndExplain(x, listener);
- }
-
- private:
- const MatcherInterface<T>* const impl_;
-
- GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
-};
-
struct AnyEq {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const { return a == b; }
@@ -252,16 +220,35 @@ class StreamMatchResultListener : public MatchResultListener {
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
};
+struct SharedPayloadBase {
+ std::atomic<int> ref{1};
+ void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
+ bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
+};
+
+template <typename T>
+struct SharedPayload : SharedPayloadBase {
+ explicit SharedPayload(const T& v) : value(v) {}
+ explicit SharedPayload(T&& v) : value(std::move(v)) {}
+
+ static void Destroy(SharedPayloadBase* shared) {
+ delete static_cast<SharedPayload*>(shared);
+ }
+
+ T value;
+};
+
// An internal class for implementing Matcher<T>, which will derive
// from it. We put functionalities common to all Matcher<T>
// specializations here to avoid code duplication.
template <typename T>
-class MatcherBase {
+class MatcherBase : private MatcherDescriberInterface {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener'.
bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
- return impl_->MatchAndExplain(x, listener);
+ GTEST_CHECK_(vtable_ != nullptr);
+ return vtable_->match_and_explain(*this, x, listener);
}
// Returns true if and only if this matcher matches x.
@@ -271,11 +258,15 @@ class MatcherBase {
}
// Describes this matcher to an ostream.
- void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
+ void DescribeTo(::std::ostream* os) const final {
+ GTEST_CHECK_(vtable_ != nullptr);
+ vtable_->describe(*this, os, false);
+ }
// Describes the negation of this matcher to an ostream.
- void DescribeNegationTo(::std::ostream* os) const {
- impl_->DescribeNegationTo(os);
+ void DescribeNegationTo(::std::ostream* os) const final {
+ GTEST_CHECK_(vtable_ != nullptr);
+ vtable_->describe(*this, os, true);
}
// Explains why x matches, or doesn't match, the matcher.
@@ -288,31 +279,194 @@ class MatcherBase {
// of the describer, which is only guaranteed to be alive when
// this matcher object is alive.
const MatcherDescriberInterface* GetDescriber() const {
- return impl_.get();
+ if (vtable_ == nullptr) return nullptr;
+ return vtable_->get_describer(*this);
}
protected:
- MatcherBase() {}
+ MatcherBase() : vtable_(nullptr) {}
// Constructs a matcher from its implementation.
- explicit MatcherBase(const MatcherInterface<const T&>* impl) : impl_(impl) {}
-
template <typename U>
- explicit MatcherBase(
- const MatcherInterface<U>* impl,
- typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
- nullptr)
- : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
+ explicit MatcherBase(const MatcherInterface<U>* impl) {
+ Init(impl);
+ }
+
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ MatcherBase(M&& m) { // NOLINT
+ Init(std::forward<M>(m));
+ }
+
+ MatcherBase(const MatcherBase& other)
+ : vtable_(other.vtable_), buffer_(other.buffer_) {
+ if (IsShared()) buffer_.shared->Ref();
+ }
+
+ MatcherBase& operator=(const MatcherBase& other) {
+ if (this == &other) return *this;
+ Destroy();
+ vtable_ = other.vtable_;
+ buffer_ = other.buffer_;
+ if (IsShared()) buffer_.shared->Ref();
+ return *this;
+ }
- MatcherBase(const MatcherBase&) = default;
- MatcherBase& operator=(const MatcherBase&) = default;
- MatcherBase(MatcherBase&&) = default;
- MatcherBase& operator=(MatcherBase&&) = default;
+ MatcherBase(MatcherBase&& other)
+ : vtable_(other.vtable_), buffer_(other.buffer_) {
+ other.vtable_ = nullptr;
+ }
+
+ MatcherBase& operator=(MatcherBase&& other) {
+ if (this == &other) return *this;
+ Destroy();
+ vtable_ = other.vtable_;
+ buffer_ = other.buffer_;
+ other.vtable_ = nullptr;
+ return *this;
+ }
- virtual ~MatcherBase() {}
+ ~MatcherBase() override { Destroy(); }
private:
- std::shared_ptr<const MatcherInterface<const T&>> impl_;
+ struct VTable {
+ bool (*match_and_explain)(const MatcherBase&, const T&,
+ MatchResultListener*);
+ void (*describe)(const MatcherBase&, std::ostream*, bool negation);
+ // Returns the captured object if it implements the interface, otherwise
+ // returns the MatcherBase itself.
+ const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
+ // Called on shared instances when the reference count reaches 0.
+ void (*shared_destroy)(SharedPayloadBase*);
+ };
+
+ bool IsShared() const {
+ return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
+ }
+
+ // If the implementation uses a listener, call that.
+ template <typename P>
+ static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
+ MatchResultListener* listener)
+ -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
+ return P::Get(m).MatchAndExplain(value, listener->stream());
+ }
+
+ template <typename P>
+ static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
+ MatchResultListener* listener)
+ -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
+ return P::Get(m).MatchAndExplain(value, listener);
+ }
+
+ template <typename P>
+ static void DescribeImpl(const MatcherBase& m, std::ostream* os,
+ bool negation) {
+ if (negation) {
+ P::Get(m).DescribeNegationTo(os);
+ } else {
+ P::Get(m).DescribeTo(os);
+ }
+ }
+
+ template <typename P>
+ static const MatcherDescriberInterface* GetDescriberImpl(
+ const MatcherBase& m) {
+ // If the impl is a MatcherDescriberInterface, then return it.
+ // Otherwise use MatcherBase itself.
+ // This allows us to implement the GetDescriber() function without support
+ // from the impl, but some users really want to get their impl back when
+ // they call GetDescriber().
+ // We use std::get on a tuple as a workaround of not having `if constexpr`.
+ return std::get<(
+ std::is_convertible<decltype(&P::Get(m)),
+ const MatcherDescriberInterface*>::value
+ ? 1
+ : 0)>(std::make_tuple(&m, &P::Get(m)));
+ }
+
+ template <typename P>
+ const VTable* GetVTable() {
+ static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
+ &DescribeImpl<P>, &GetDescriberImpl<P>,
+ P::shared_destroy};
+ return &kVTable;
+ }
+
+ union Buffer {
+ // Add some types to give Buffer some common alignment/size use cases.
+ void* ptr;
+ double d;
+ int64_t i;
+ // And add one for the out-of-line cases.
+ SharedPayloadBase* shared;
+ };
+
+ void Destroy() {
+ if (IsShared() && buffer_.shared->Unref()) {
+ vtable_->shared_destroy(buffer_.shared);
+ }
+ }
+
+ template <typename M>
+ static constexpr bool IsInlined() {
+ return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
+ std::is_trivially_copy_constructible<M>::value &&
+ std::is_trivially_destructible<M>::value;
+ }
+
+ template <typename M, bool = MatcherBase::IsInlined<M>()>
+ struct ValuePolicy {
+ static const M& Get(const MatcherBase& m) {
+ // When inlined along with Init, need to be explicit to avoid violating
+ // strict aliasing rules.
+ const M *ptr = static_cast<const M*>(
+ static_cast<const void*>(&m.buffer_));
+ return *ptr;
+ }
+ static void Init(MatcherBase& m, M impl) {
+ ::new (static_cast<void*>(&m.buffer_)) M(impl);
+ }
+ static constexpr auto shared_destroy = nullptr;
+ };
+
+ template <typename M>
+ struct ValuePolicy<M, false> {
+ using Shared = SharedPayload<M>;
+ static const M& Get(const MatcherBase& m) {
+ return static_cast<Shared*>(m.buffer_.shared)->value;
+ }
+ template <typename Arg>
+ static void Init(MatcherBase& m, Arg&& arg) {
+ m.buffer_.shared = new Shared(std::forward<Arg>(arg));
+ }
+ static constexpr auto shared_destroy = &Shared::Destroy;
+ };
+
+ template <typename U, bool B>
+ struct ValuePolicy<const MatcherInterface<U>*, B> {
+ using M = const MatcherInterface<U>;
+ using Shared = SharedPayload<std::unique_ptr<M>>;
+ static const M& Get(const MatcherBase& m) {
+ return *static_cast<Shared*>(m.buffer_.shared)->value;
+ }
+ static void Init(MatcherBase& m, M* impl) {
+ m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
+ }
+
+ static constexpr auto shared_destroy = &Shared::Destroy;
+ };
+
+ template <typename M>
+ void Init(M&& m) {
+ using MM = typename std::decay<M>::type;
+ using Policy = ValuePolicy<MM>;
+ vtable_ = GetVTable<Policy>();
+ Policy::Init(*this, std::forward<M>(m));
+ }
+
+ const VTable* vtable_;
+ Buffer buffer_;
};
} // namespace internal
@@ -340,6 +494,10 @@ class Matcher : public internal::MatcherBase<T> {
nullptr)
: internal::MatcherBase<T>(impl) {}
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
+
// Implicit constructor here allows people to write
// EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
Matcher(T value); // NOLINT
@@ -357,6 +515,11 @@ class GTEST_API_ Matcher<const std::string&>
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<const std::string&>(impl) {}
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) // NOLINT
+ : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
+
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
Matcher(const std::string& s); // NOLINT
@@ -376,6 +539,11 @@ class GTEST_API_ Matcher<std::string>
explicit Matcher(const MatcherInterface<std::string>* impl)
: internal::MatcherBase<std::string>(impl) {}
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) // NOLINT
+ : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
+
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a string object.
Matcher(const std::string& s); // NOLINT
@@ -384,18 +552,24 @@ class GTEST_API_ Matcher<std::string>
Matcher(const char* s); // NOLINT
};
-#if GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
// The following two specializations allow the user to write str
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
// matcher is expected.
template <>
-class GTEST_API_ Matcher<const absl::string_view&>
- : public internal::MatcherBase<const absl::string_view&> {
+class GTEST_API_ Matcher<const internal::StringView&>
+ : public internal::MatcherBase<const internal::StringView&> {
public:
Matcher() {}
- explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
- : internal::MatcherBase<const absl::string_view&>(impl) {}
+ explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
+ : internal::MatcherBase<const internal::StringView&>(impl) {}
+
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) // NOLINT
+ : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
+ }
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
@@ -404,20 +578,25 @@ class GTEST_API_ Matcher<const absl::string_view&>
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
- // Allows the user to pass absl::string_views directly.
- Matcher(absl::string_view s); // NOLINT
+ // Allows the user to pass absl::string_views or std::string_views directly.
+ Matcher(internal::StringView s); // NOLINT
};
template <>
-class GTEST_API_ Matcher<absl::string_view>
- : public internal::MatcherBase<absl::string_view> {
+class GTEST_API_ Matcher<internal::StringView>
+ : public internal::MatcherBase<internal::StringView> {
public:
Matcher() {}
- explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
- : internal::MatcherBase<absl::string_view>(impl) {}
- explicit Matcher(const MatcherInterface<absl::string_view>* impl)
- : internal::MatcherBase<absl::string_view>(impl) {}
+ explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
+ : internal::MatcherBase<internal::StringView>(impl) {}
+ explicit Matcher(const MatcherInterface<internal::StringView>* impl)
+ : internal::MatcherBase<internal::StringView>(impl) {}
+
+ template <typename M, typename = typename std::remove_reference<
+ M>::type::is_gtest_matcher>
+ Matcher(M&& m) // NOLINT
+ : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object.
@@ -426,10 +605,10 @@ class GTEST_API_ Matcher<absl::string_view>
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
- // Allows the user to pass absl::string_views directly.
- Matcher(absl::string_view s); // NOLINT
+ // Allows the user to pass absl::string_views or std::string_views directly.
+ Matcher(internal::StringView s); // NOLINT
};
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Prints a matcher in a human-readable format.
template <typename T>
@@ -529,37 +708,32 @@ template <typename D, typename Rhs, typename Op>
class ComparisonBase {
public:
explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
+
+ using is_gtest_matcher = void;
+
template <typename Lhs>
- operator Matcher<Lhs>() const {
- return Matcher<Lhs>(new Impl<const Lhs&>(rhs_));
+ bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
+ return Op()(lhs, Unwrap(rhs_));
+ }
+ void DescribeTo(std::ostream* os) const {
+ *os << D::Desc() << " ";
+ UniversalPrint(Unwrap(rhs_), os);
+ }
+ void DescribeNegationTo(std::ostream* os) const {
+ *os << D::NegatedDesc() << " ";
+ UniversalPrint(Unwrap(rhs_), os);
}
private:
template <typename T>
- static const T& Unwrap(const T& v) { return v; }
+ static const T& Unwrap(const T& v) {
+ return v;
+ }
template <typename T>
- static const T& Unwrap(std::reference_wrapper<T> v) { return v; }
-
- template <typename Lhs, typename = Rhs>
- class Impl : public MatcherInterface<Lhs> {
- public:
- explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
- bool MatchAndExplain(Lhs lhs,
- MatchResultListener* /* listener */) const override {
- return Op()(lhs, Unwrap(rhs_));
- }
- void DescribeTo(::std::ostream* os) const override {
- *os << D::Desc() << " ";
- UniversalPrint(Unwrap(rhs_), os);
- }
- void DescribeNegationTo(::std::ostream* os) const override {
- *os << D::NegatedDesc() << " ";
- UniversalPrint(Unwrap(rhs_), os);
- }
+ static const T& Unwrap(std::reference_wrapper<T> v) {
+ return v;
+ }
- private:
- Rhs rhs_;
- };
Rhs rhs_;
};
@@ -612,6 +786,10 @@ class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
static const char* NegatedDesc() { return "isn't >="; }
};
+template <typename T, typename = typename std::enable_if<
+ std::is_constructible<std::string, T>::value>::type>
+using StringLike = T;
+
// Implements polymorphic matchers MatchesRegex(regex) and
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
// T can be converted to a string.
@@ -620,12 +798,12 @@ class MatchesRegexMatcher {
MatchesRegexMatcher(const RE* regex, bool full_match)
: regex_(regex), full_match_(full_match) {}
-#if GTEST_HAS_ABSL
- bool MatchAndExplain(const absl::string_view& s,
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly:
// const char*
@@ -672,9 +850,10 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
}
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
- const std::string& regex) {
- return MatchesRegex(new internal::RE(regex));
+template <typename T = std::string>
+PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
+ const internal::StringLike<T>& regex) {
+ return MatchesRegex(new internal::RE(std::string(regex)));
}
// Matches a string that contains regular expression 'regex'.
@@ -683,9 +862,10 @@ inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const internal::RE* regex) {
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
}
-inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
- const std::string& regex) {
- return ContainsRegex(new internal::RE(regex));
+template <typename T = std::string>
+PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
+ const internal::StringLike<T>& regex) {
+ return ContainsRegex(new internal::RE(std::string(regex)));
}
// Creates a polymorphic matcher that matches anything equal to x.
@@ -747,4 +927,4 @@ inline internal::NeMatcher<Rhs> Ne(Rhs x) {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
-#endif // GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h
index 21899232..becfd49f 100644
--- a/googletest/include/gtest/gtest-message.h
+++ b/googletest/include/gtest/gtest-message.h
@@ -44,8 +44,8 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
-#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
#include <limits>
#include <memory>
@@ -216,4 +216,4 @@ std::string StreamableToString(const T& streamable) {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h
index 70593da5..804e7028 100644
--- a/googletest/include/gtest/gtest-param-test.h
+++ b/googletest/include/gtest/gtest-param-test.h
@@ -30,12 +30,9 @@
// Macros and functions for implementing parameterized tests
// in Google C++ Testing and Mocking Framework (Google Test)
//
-// This file is generated by a SCRIPT. DO NOT EDIT BY HAND!
-//
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
-
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
// Value-parameterized tests allow you to test your code with different
// parameters without writing multiple copies of the same test.
@@ -371,8 +368,6 @@ inline internal::ParamGenerator<bool> Bool() {
// std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types
// of elements from sequences produces by gen1, gen2, ..., genN.
//
-// Combine can have up to 10 arguments.
-//
// Example:
//
// This will instantiate tests in test suite AnimalTest each one with
@@ -428,7 +423,8 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
->AddTestPattern( \
GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \
new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \
- test_suite_name, test_name)>()); \
+ test_suite_name, test_name)>(), \
+ ::testing::internal::CodeLocation(__FILE__, __LINE__)); \
return 0; \
} \
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
@@ -491,6 +487,13 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
&gtest_##prefix##test_suite_name##_EvalGenerateName_, \
__FILE__, __LINE__)
+
+// Allow Marking a Parameterized test class as not needing to be instantiated.
+#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
+ namespace gtest_do_not_use_outside_namespace_scope {} \
+ static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
+ GTEST_STRINGIFY_(T))
+
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#define INSTANTIATE_TEST_CASE_P \
@@ -501,4 +504,4 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h
index c443625f..978420e8 100644
--- a/googletest/include/gtest/gtest-printers.h
+++ b/googletest/include/gtest/gtest-printers.h
@@ -97,10 +97,11 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
-#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#include <functional>
+#include <memory>
#include <ostream> // NOLINT
#include <sstream>
#include <string>
@@ -108,64 +109,124 @@
#include <type_traits>
#include <utility>
#include <vector>
+
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
-#if GTEST_HAS_ABSL
-#include "absl/strings/string_view.h"
-#include "absl/types/optional.h"
-#include "absl/types/variant.h"
-#endif // GTEST_HAS_ABSL
-
namespace testing {
-// Definitions in the 'internal' and 'internal2' name spaces are
-// subject to change without notice. DO NOT USE THEM IN USER CODE!
-namespace internal2 {
+// Definitions in the internal* namespaces are subject to change without notice.
+// DO NOT USE THEM IN USER CODE!
+namespace internal {
-// Prints the given number of bytes in the given object to the given
-// ostream.
-GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
- size_t count,
- ::std::ostream* os);
+template <typename T>
+void UniversalPrint(const T& value, ::std::ostream* os);
-// For selecting which printer to use when a given type has neither <<
-// nor PrintTo().
-enum TypeKind {
- kProtobuf, // a protobuf type
- kConvertibleToInteger, // a type implicitly convertible to BiggestInt
- // (e.g. a named or unnamed enum type)
-#if GTEST_HAS_ABSL
- kConvertibleToStringView, // a type implicitly convertible to
- // absl::string_view
-#endif
- kOtherType // anything else
+// Used to print an STL-style container when the user doesn't define
+// a PrintTo() for it.
+struct ContainerPrinter {
+ template <typename T,
+ typename = typename std::enable_if<
+ (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
+ !IsRecursiveContainer<T>::value>::type>
+ static void PrintValue(const T& container, std::ostream* os) {
+ const size_t kMaxCount = 32; // The maximum number of elements to print.
+ *os << '{';
+ size_t count = 0;
+ for (auto&& elem : container) {
+ if (count > 0) {
+ *os << ',';
+ if (count == kMaxCount) { // Enough has been printed.
+ *os << " ...";
+ break;
+ }
+ }
+ *os << ' ';
+ // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
+ // handle `elem` being a native array.
+ internal::UniversalPrint(elem, os);
+ ++count;
+ }
+
+ if (count > 0) {
+ *os << ' ';
+ }
+ *os << '}';
+ }
};
-// TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
-// by the universal printer to print a value of type T when neither
-// operator<< nor PrintTo() is defined for T, where kTypeKind is the
-// "kind" of T as defined by enum TypeKind.
-template <typename T, TypeKind kTypeKind>
-class TypeWithoutFormatter {
- public:
- // This default version is called when kTypeKind is kOtherType.
+// Used to print a pointer that is neither a char pointer nor a member
+// pointer, when the user doesn't define PrintTo() for it. (A member
+// variable pointer or member function pointer doesn't really point to
+// a location in the address space. Their representation is
+// implementation-defined. Therefore they will be printed as raw
+// bytes.)
+struct FunctionPointerPrinter {
+ template <typename T, typename = typename std::enable_if<
+ std::is_function<T>::value>::type>
+ static void PrintValue(T* p, ::std::ostream* os) {
+ if (p == nullptr) {
+ *os << "NULL";
+ } else {
+ // T is a function type, so '*os << p' doesn't do what we want
+ // (it just prints p as bool). We want to print p as a const
+ // void*.
+ *os << reinterpret_cast<const void*>(p);
+ }
+ }
+};
+
+struct PointerPrinter {
+ template <typename T>
+ static void PrintValue(T* p, ::std::ostream* os) {
+ if (p == nullptr) {
+ *os << "NULL";
+ } else {
+ // T is not a function type. We just call << to print p,
+ // relying on ADL to pick up user-defined << for their pointer
+ // types, if any.
+ *os << p;
+ }
+ }
+};
+
+namespace internal_stream_operator_without_lexical_name_lookup {
+
+// The presence of an operator<< here will terminate lexical scope lookup
+// straight away (even though it cannot be a match because of its argument
+// types). Thus, the two operator<< calls in StreamPrinter will find only ADL
+// candidates.
+struct LookupBlocker {};
+void operator<<(LookupBlocker, LookupBlocker);
+
+struct StreamPrinter {
+ template <typename T,
+ // Don't accept member pointers here. We'd print them via implicit
+ // conversion to bool, which isn't useful.
+ typename = typename std::enable_if<
+ !std::is_member_pointer<T>::value>::type,
+ // Only accept types for which we can find a streaming operator via
+ // ADL (possibly involving implicit conversions).
+ typename = decltype(std::declval<std::ostream&>()
+ << std::declval<const T&>())>
static void PrintValue(const T& value, ::std::ostream* os) {
- PrintBytesInObjectTo(
- static_cast<const unsigned char*>(
- reinterpret_cast<const void*>(std::addressof(value))),
- sizeof(value), os);
+ // Call streaming operator found by ADL, possibly with implicit conversions
+ // of the arguments.
+ *os << value;
}
};
-// We print a protobuf using its ShortDebugString() when the string
-// doesn't exceed this many characters; otherwise we print it using
-// DebugString() for better readability.
-const size_t kProtobufOneLinerMaxLength = 50;
+} // namespace internal_stream_operator_without_lexical_name_lookup
-template <typename T>
-class TypeWithoutFormatter<T, kProtobuf> {
- public:
+struct ProtobufPrinter {
+ // We print a protobuf using its ShortDebugString() when the string
+ // doesn't exceed this many characters; otherwise we print it using
+ // DebugString() for better readability.
+ static const size_t kProtobufOneLinerMaxLength = 50;
+
+ template <typename T,
+ typename = typename std::enable_if<
+ internal::HasDebugStringAndShortDebugString<T>::value>::type>
static void PrintValue(const T& value, ::std::ostream* os) {
std::string pretty_str = value.ShortDebugString();
if (pretty_str.length() > kProtobufOneLinerMaxLength) {
@@ -175,9 +236,7 @@ class TypeWithoutFormatter<T, kProtobuf> {
}
};
-template <typename T>
-class TypeWithoutFormatter<T, kConvertibleToInteger> {
- public:
+struct ConvertibleToIntegerPrinter {
// Since T has no << operator or PrintTo() but can be implicitly
// converted to BiggestInt, we print it as a BiggestInt.
//
@@ -185,110 +244,73 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> {
// case printing it as an integer is the desired behavior. In case
// T is not an enum, printing it as an integer is the best we can do
// given that it has no user-defined printer.
- static void PrintValue(const T& value, ::std::ostream* os) {
- const internal::BiggestInt kBigInt = value;
- *os << kBigInt;
+ static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
+ *os << value;
}
};
-#if GTEST_HAS_ABSL
-template <typename T>
-class TypeWithoutFormatter<T, kConvertibleToStringView> {
- public:
- // Since T has neither operator<< nor PrintTo() but can be implicitly
- // converted to absl::string_view, we print it as a absl::string_view.
- //
- // Note: the implementation is further below, as it depends on
- // internal::PrintTo symbol which is defined later in the file.
- static void PrintValue(const T& value, ::std::ostream* os);
-};
+struct ConvertibleToStringViewPrinter {
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ static void PrintValue(internal::StringView value, ::std::ostream* os) {
+ internal::UniversalPrint(value, os);
+ }
#endif
+};
-// Prints the given value to the given ostream. If the value is a
-// protocol message, its debug string is printed; if it's an enum or
-// of a type implicitly convertible to BiggestInt, it's printed as an
-// integer; otherwise the bytes in the value are printed. This is
-// what UniversalPrinter<T>::Print() does when it knows nothing about
-// type T and T has neither << operator nor PrintTo().
-//
-// A user can override this behavior for a class type Foo by defining
-// a << operator in the namespace where Foo is defined.
-//
-// We put this operator in namespace 'internal2' instead of 'internal'
-// to simplify the implementation, as much code in 'internal' needs to
-// use << in STL, which would conflict with our own << were it defined
-// in 'internal'.
-//
-// Note that this operator<< takes a generic std::basic_ostream<Char,
-// CharTraits> type instead of the more restricted std::ostream. If
-// we define it to take an std::ostream instead, we'll get an
-// "ambiguous overloads" compiler error when trying to print a type
-// Foo that supports streaming to std::basic_ostream<Char,
-// CharTraits>, as the compiler cannot tell whether
-// operator<<(std::ostream&, const T&) or
-// operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
-// specific.
-template <typename Char, typename CharTraits, typename T>
-::std::basic_ostream<Char, CharTraits>& operator<<(
- ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
- TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
- ? kProtobuf
- : std::is_convertible<
- const T&, internal::BiggestInt>::value
- ? kConvertibleToInteger
- :
-#if GTEST_HAS_ABSL
- std::is_convertible<
- const T&, absl::string_view>::value
- ? kConvertibleToStringView
- :
-#endif
- kOtherType)>::PrintValue(x, &os);
- return os;
-}
-} // namespace internal2
-} // namespace testing
+// Prints the given number of bytes in the given object to the given
+// ostream.
+GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
+ size_t count,
+ ::std::ostream* os);
+struct RawBytesPrinter {
+ // SFINAE on `sizeof` to make sure we have a complete type.
+ template <typename T, size_t = sizeof(T)>
+ static void PrintValue(const T& value, ::std::ostream* os) {
+ PrintBytesInObjectTo(
+ static_cast<const unsigned char*>(
+ // Load bearing cast to void* to support iOS
+ reinterpret_cast<const void*>(std::addressof(value))),
+ sizeof(value), os);
+ }
+};
-// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
-// magic needed for implementing UniversalPrinter won't work.
-namespace testing_internal {
+struct FallbackPrinter {
+ template <typename T>
+ static void PrintValue(const T&, ::std::ostream* os) {
+ *os << "(incomplete type)";
+ }
+};
-// Used to print a value that is not an STL-style container when the
-// user doesn't define PrintTo() for it.
-template <typename T>
-void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
- // With the following statement, during unqualified name lookup,
- // testing::internal2::operator<< appears as if it was declared in
- // the nearest enclosing namespace that contains both
- // ::testing_internal and ::testing::internal2, i.e. the global
- // namespace. For more details, refer to the C++ Standard section
- // 7.3.4-1 [namespace.udir]. This allows us to fall back onto
- // testing::internal2::operator<< in case T doesn't come with a <<
- // operator.
-
- using ::testing::internal2::operator<<;
-
- // Assuming T is defined in namespace foo, in the next statement,
- // the compiler will consider all of:
- //
- // 1. foo::operator<< (thanks to Koenig look-up),
- // 2. ::operator<< (as the current namespace is enclosed in ::),
- // 3. testing::internal2::operator<< (thanks to the using statement above).
- //
- // The operator<< whose type matches T best will be picked.
- //
- // We deliberately allow #2 to be a candidate, as sometimes it's
- // impossible to define #1 (e.g. when foo is ::std, defining
- // anything in it is undefined behavior unless you are a compiler
- // vendor.).
- *os << value;
-}
+// Try every printer in order and return the first one that works.
+template <typename T, typename E, typename Printer, typename... Printers>
+struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
-} // namespace testing_internal
+template <typename T, typename Printer, typename... Printers>
+struct FindFirstPrinter<
+ T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
+ Printer, Printers...> {
+ using type = Printer;
+};
-namespace testing {
-namespace internal {
+// Select the best printer in the following order:
+// - Print containers (they have begin/end/etc).
+// - Print function pointers.
+// - Print object pointers.
+// - Use the stream operator, if available.
+// - Print protocol buffers.
+// - Print types convertible to BiggestInt.
+// - Print types convertible to StringView, if available.
+// - Fallback to printing the raw bytes of the object.
+template <typename T>
+void PrintWithFallback(const T& value, ::std::ostream* os) {
+ using Printer = typename FindFirstPrinter<
+ T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
+ internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
+ ProtobufPrinter, ConvertibleToIntegerPrinter,
+ ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
+ Printer::PrintValue(value, os);
+}
// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
// value of type ToPrint that is an operand of a comparison assertion
@@ -338,6 +360,14 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
+#ifdef __cpp_char8_t
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
+#endif
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
+GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
@@ -355,6 +385,14 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
+#ifdef __cpp_char8_t
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
+#endif
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
+GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
#if GTEST_HAS_STD_WSTRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
@@ -387,85 +425,6 @@ std::string FormatForComparisonFailureMessage(
template <typename T>
class UniversalPrinter;
-template <typename T>
-void UniversalPrint(const T& value, ::std::ostream* os);
-
-enum DefaultPrinterType {
- kPrintContainer,
- kPrintPointer,
- kPrintFunctionPointer,
- kPrintOther,
-};
-template <DefaultPrinterType type> struct WrapPrinterType {};
-
-// Used to print an STL-style container when the user doesn't define
-// a PrintTo() for it.
-template <typename C>
-void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
- const C& container, ::std::ostream* os) {
- const size_t kMaxCount = 32; // The maximum number of elements to print.
- *os << '{';
- size_t count = 0;
- for (typename C::const_iterator it = container.begin();
- it != container.end(); ++it, ++count) {
- if (count > 0) {
- *os << ',';
- if (count == kMaxCount) { // Enough has been printed.
- *os << " ...";
- break;
- }
- }
- *os << ' ';
- // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
- // handle *it being a native array.
- internal::UniversalPrint(*it, os);
- }
-
- if (count > 0) {
- *os << ' ';
- }
- *os << '}';
-}
-
-// Used to print a pointer that is neither a char pointer nor a member
-// pointer, when the user doesn't define PrintTo() for it. (A member
-// variable pointer or member function pointer doesn't really point to
-// a location in the address space. Their representation is
-// implementation-defined. Therefore they will be printed as raw
-// bytes.)
-template <typename T>
-void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
- T* p, ::std::ostream* os) {
- if (p == nullptr) {
- *os << "NULL";
- } else {
- // T is not a function type. We just call << to print p,
- // relying on ADL to pick up user-defined << for their pointer
- // types, if any.
- *os << p;
- }
-}
-template <typename T>
-void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
- T* p, ::std::ostream* os) {
- if (p == nullptr) {
- *os << "NULL";
- } else {
- // T is a function type, so '*os << p' doesn't do what we want
- // (it just prints p as bool). We want to print p as a const
- // void*.
- *os << reinterpret_cast<const void*>(p);
- }
-}
-
-// Used to print a non-container, non-pointer value when the user
-// doesn't define PrintTo() for it.
-template <typename T>
-void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
- const T& value, ::std::ostream* os) {
- ::testing_internal::DefaultPrintNonContainerTo(value, os);
-}
-
// Prints the given value using the << operator if it has one;
// otherwise prints the bytes in it. This is what
// UniversalPrinter<T>::Print() does when PrintTo() is not specialized
@@ -479,36 +438,7 @@ void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
// wants).
template <typename T>
void PrintTo(const T& value, ::std::ostream* os) {
- // DefaultPrintTo() is overloaded. The type of its first argument
- // determines which version will be picked.
- //
- // Note that we check for container types here, prior to we check
- // for protocol message types in our operator<<. The rationale is:
- //
- // For protocol messages, we want to give people a chance to
- // override Google Mock's format by defining a PrintTo() or
- // operator<<. For STL containers, other formats can be
- // incompatible with Google Mock's format for the container
- // elements; therefore we check for container types here to ensure
- // that our format is used.
- //
- // Note that MSVC and clang-cl do allow an implicit conversion from
- // pointer-to-function to pointer-to-object, but clang-cl warns on it.
- // So don't use ImplicitlyConvertible if it can be helped since it will
- // cause this warning, and use a separate overload of DefaultPrintTo for
- // function pointers so that the `*os << p` in the object pointer overload
- // doesn't cause that warning either.
- DefaultPrintTo(
- WrapPrinterType <
- (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
- !IsRecursiveContainer<T>::value
- ? kPrintContainer
- : !std::is_pointer<T>::value
- ? kPrintOther
- : std::is_function<typename std::remove_pointer<T>::type>::value
- ? kPrintFunctionPointer
- : kPrintPointer > (),
- value, os);
+ internal::PrintWithFallback(value, os);
}
// The following list of PrintTo() overloads tells
@@ -539,6 +469,16 @@ inline void PrintTo(bool x, ::std::ostream* os) {
// is implemented as an unsigned type.
GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
+GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
+inline void PrintTo(char16_t c, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<char32_t>(c), os);
+}
+#ifdef __cpp_char8_t
+inline void PrintTo(char8_t c, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<char32_t>(c), os);
+}
+#endif
+
// Overloads for C strings.
GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
inline void PrintTo(char* s, ::std::ostream* os) {
@@ -559,6 +499,23 @@ inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
inline void PrintTo(unsigned char* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const void*>(s), os);
}
+#ifdef __cpp_char8_t
+// Overloads for u8 strings.
+void PrintTo(const char8_t* s, ::std::ostream* os);
+inline void PrintTo(char8_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const char8_t*>(s), os);
+}
+#endif
+// Overloads for u16 strings.
+void PrintTo(const char16_t* s, ::std::ostream* os);
+inline void PrintTo(char16_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const char16_t*>(s), os);
+}
+// Overloads for u32 strings.
+void PrintTo(const char32_t* s, ::std::ostream* os);
+inline void PrintTo(char32_t* s, ::std::ostream* os) {
+ PrintTo(ImplicitCast_<const char32_t*>(s), os);
+}
// MSVC can be configured to define wchar_t as a typedef of unsigned
// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
@@ -593,6 +550,26 @@ inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
PrintStringTo(s, os);
}
+// Overloads for ::std::u8string
+#ifdef __cpp_char8_t
+GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
+inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
+ PrintU8StringTo(s, os);
+}
+#endif
+
+// Overloads for ::std::u16string
+GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
+inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
+ PrintU16StringTo(s, os);
+}
+
+// Overloads for ::std::u32string
+GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
+inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
+ PrintU32StringTo(s, os);
+}
+
// Overloads for ::std::wstring.
#if GTEST_HAS_STD_WSTRING
GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
@@ -601,12 +578,12 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
}
#endif // GTEST_HAS_STD_WSTRING
-#if GTEST_HAS_ABSL
-// Overload for absl::string_view.
-inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+// Overload for internal::StringView.
+inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
PrintTo(::std::string(sp), os);
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
@@ -615,6 +592,43 @@ void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
UniversalPrinter<T&>::Print(ref.get(), os);
}
+inline const void* VoidifyPointer(const void* p) { return p; }
+inline const void* VoidifyPointer(volatile const void* p) {
+ return const_cast<const void*>(p);
+}
+
+template <typename T, typename Ptr>
+void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
+ if (ptr == nullptr) {
+ *os << "(nullptr)";
+ } else {
+ // We can't print the value. Just print the pointer..
+ *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
+ }
+}
+template <typename T, typename Ptr,
+ typename = typename std::enable_if<!std::is_void<T>::value &&
+ !std::is_array<T>::value>::type>
+void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
+ if (ptr == nullptr) {
+ *os << "(nullptr)";
+ } else {
+ *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
+ UniversalPrinter<T>::Print(*ptr, os);
+ *os << ")";
+ }
+}
+
+template <typename T, typename D>
+void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
+ (PrintSmartPointer<T>)(ptr, os, 0);
+}
+
+template <typename T>
+void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
+ (PrintSmartPointer<T>)(ptr, os, 0);
+}
+
// Helper function for printing a tuple. T must be instantiated with
// a tuple type.
template <typename T>
@@ -680,14 +694,46 @@ class UniversalPrinter {
GTEST_DISABLE_MSC_WARNINGS_POP_()
};
-#if GTEST_HAS_ABSL
+// Remove any const-qualifiers before passing a type to UniversalPrinter.
+template <typename T>
+class UniversalPrinter<const T> : public UniversalPrinter<T> {};
-// Printer for absl::optional
+#if GTEST_INTERNAL_HAS_ANY
+
+// Printer for std::any / absl::any
+
+template <>
+class UniversalPrinter<Any> {
+ public:
+ static void Print(const Any& value, ::std::ostream* os) {
+ if (value.has_value()) {
+ *os << "value of type " << GetTypeName(value);
+ } else {
+ *os << "no value";
+ }
+ }
+
+ private:
+ static std::string GetTypeName(const Any& value) {
+#if GTEST_HAS_RTTI
+ return internal::GetTypeName(value.type());
+#else
+ static_cast<void>(value); // possibly unused
+ return "<unknown_type>";
+#endif // GTEST_HAS_RTTI
+ }
+};
+
+#endif // GTEST_INTERNAL_HAS_ANY
+
+#if GTEST_INTERNAL_HAS_OPTIONAL
+
+// Printer for std::optional / absl::optional
template <typename T>
-class UniversalPrinter<::absl::optional<T>> {
+class UniversalPrinter<Optional<T>> {
public:
- static void Print(const ::absl::optional<T>& value, ::std::ostream* os) {
+ static void Print(const Optional<T>& value, ::std::ostream* os) {
*os << '(';
if (!value) {
*os << "nullopt";
@@ -698,14 +744,22 @@ class UniversalPrinter<::absl::optional<T>> {
}
};
-// Printer for absl::variant
+#endif // GTEST_INTERNAL_HAS_OPTIONAL
+
+#if GTEST_INTERNAL_HAS_VARIANT
+
+// Printer for std::variant / absl::variant
template <typename... T>
-class UniversalPrinter<::absl::variant<T...>> {
+class UniversalPrinter<Variant<T...>> {
public:
- static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) {
+ static void Print(const Variant<T...>& value, ::std::ostream* os) {
*os << '(';
- absl::visit(Visitor{os}, value);
+#if GTEST_HAS_ABSL
+ absl::visit(Visitor{os, value.index()}, value);
+#else
+ std::visit(Visitor{os, value.index()}, value);
+#endif // GTEST_HAS_ABSL
*os << ')';
}
@@ -713,14 +767,16 @@ class UniversalPrinter<::absl::variant<T...>> {
struct Visitor {
template <typename U>
void operator()(const U& u) const {
- *os << "'" << GetTypeName<U>() << "' with value ";
+ *os << "'" << GetTypeName<U>() << "(index = " << index
+ << ")' with value ";
UniversalPrint(u, os);
}
::std::ostream* os;
+ std::size_t index;
};
};
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_VARIANT
// UniversalPrintArray(begin, len, os) prints an array of 'len'
// elements, starting at address 'begin'.
@@ -749,6 +805,20 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
GTEST_API_ void UniversalPrintArray(
const char* begin, size_t len, ::std::ostream* os);
+#ifdef __cpp_char8_t
+// This overload prints a (const) char8_t array compactly.
+GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
+ ::std::ostream* os);
+#endif
+
+// This overload prints a (const) char16_t array compactly.
+GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
+ ::std::ostream* os);
+
+// This overload prints a (const) char32_t array compactly.
+GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
+ ::std::ostream* os);
+
// This overload prints a (const) wchar_t array compactly.
GTEST_API_ void UniversalPrintArray(
const wchar_t* begin, size_t len, ::std::ostream* os);
@@ -821,12 +891,55 @@ class UniversalTersePrinter<const char*> {
}
};
template <>
-class UniversalTersePrinter<char*> {
+class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
+};
+
+#ifdef __cpp_char8_t
+template <>
+class UniversalTersePrinter<const char8_t*> {
+ public:
+ static void Print(const char8_t* str, ::std::ostream* os) {
+ if (str == nullptr) {
+ *os << "NULL";
+ } else {
+ UniversalPrint(::std::u8string(str), os);
+ }
+ }
+};
+template <>
+class UniversalTersePrinter<char8_t*>
+ : public UniversalTersePrinter<const char8_t*> {};
+#endif
+
+template <>
+class UniversalTersePrinter<const char16_t*> {
public:
- static void Print(char* str, ::std::ostream* os) {
- UniversalTersePrinter<const char*>::Print(str, os);
+ static void Print(const char16_t* str, ::std::ostream* os) {
+ if (str == nullptr) {
+ *os << "NULL";
+ } else {
+ UniversalPrint(::std::u16string(str), os);
+ }
}
};
+template <>
+class UniversalTersePrinter<char16_t*>
+ : public UniversalTersePrinter<const char16_t*> {};
+
+template <>
+class UniversalTersePrinter<const char32_t*> {
+ public:
+ static void Print(const char32_t* str, ::std::ostream* os) {
+ if (str == nullptr) {
+ *os << "NULL";
+ } else {
+ UniversalPrint(::std::u32string(str), os);
+ }
+ }
+};
+template <>
+class UniversalTersePrinter<char32_t*>
+ : public UniversalTersePrinter<const char32_t*> {};
#if GTEST_HAS_STD_WSTRING
template <>
@@ -899,16 +1012,6 @@ Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
} // namespace internal
-#if GTEST_HAS_ABSL
-namespace internal2 {
-template <typename T>
-void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
- const T& value, ::std::ostream* os) {
- internal::PrintTo(absl::string_view(value), os);
-}
-} // namespace internal2
-#endif
-
template <typename T>
::std::string PrintToString(const T& value) {
::std::stringstream ss;
@@ -923,4 +1026,4 @@ template <typename T>
// declarations from this file.
#include "gtest/internal/custom/gtest-printers.h"
-#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h
index aa38870e..eacef446 100644
--- a/googletest/include/gtest/gtest-spi.h
+++ b/googletest/include/gtest/gtest-spi.h
@@ -33,8 +33,8 @@
// GOOGLETEST_CM0004 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
-#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
#include "gtest/gtest.h"
@@ -235,4 +235,4 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
}\
} while (::testing::internal::AlwaysFalse())
-#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
diff --git a/googletest/include/gtest/gtest-test-part.h b/googletest/include/gtest/gtest-test-part.h
index 05a79853..203fdf98 100644
--- a/googletest/include/gtest/gtest-test-part.h
+++ b/googletest/include/gtest/gtest-test-part.h
@@ -29,8 +29,8 @@
//
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
-#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
#include <iosfwd>
#include <vector>
@@ -181,4 +181,4 @@ class GTEST_API_ HasNewFatalFailureHelper
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h
index 3ffa50b7..9fdc6be1 100644
--- a/googletest/include/gtest/gtest-typed-test.h
+++ b/googletest/include/gtest/gtest-typed-test.h
@@ -29,8 +29,8 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
// This header implements typed tests and type-parameterized tests.
@@ -175,8 +175,6 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
// Implements typed tests.
-#if GTEST_HAS_TYPED_TEST
-
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Expands to the name of the typedef for the type parameters of the
@@ -230,12 +228,8 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
TYPED_TEST_SUITE
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
-#endif // GTEST_HAS_TYPED_TEST
-
// Implements type-parameterized tests.
-#if GTEST_HAS_TYPED_TEST_P
-
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Expands to the namespace name that the type-parameterized tests for
@@ -332,6 +326,4 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
INSTANTIATE_TYPED_TEST_SUITE_P
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
-#endif // GTEST_HAS_TYPED_TEST_P
-
-#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h
index eb44c4cd..7a5d057c 100644
--- a/googletest/include/gtest/gtest.h
+++ b/googletest/include/gtest/gtest.h
@@ -49,8 +49,8 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
-#define GTEST_INCLUDE_GTEST_GTEST_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
#include <cstddef>
#include <limits>
@@ -101,6 +101,10 @@ GTEST_DECLARE_bool_(catch_exceptions);
// to let Google Test decide.
GTEST_DECLARE_string_(color);
+// This flag controls whether the test runner should continue execution past
+// first failure.
+GTEST_DECLARE_bool_(fail_fast);
+
// This flag sets up the filter to select by name using a glob pattern
// the tests to run. If the filter is not given all tests are executed.
GTEST_DECLARE_string_(filter);
@@ -117,6 +121,9 @@ GTEST_DECLARE_bool_(list_tests);
// in addition to its normal textual output.
GTEST_DECLARE_string_(output);
+// This flags control whether Google Test prints only test failures.
+GTEST_DECLARE_bool_(brief);
+
// This flags control whether Google Test prints the elapsed time for each
// test.
GTEST_DECLARE_bool_(print_time);
@@ -177,6 +184,7 @@ class FuchsiaDeathTest;
class UnitTestImpl* GetUnitTestImpl();
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message);
+std::set<std::string>* GetIgnoredParameterizedTestSuites();
} // namespace internal
@@ -278,7 +286,11 @@ class GTEST_API_ AssertionResult {
// Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult& other);
-#if defined(_MSC_VER) && _MSC_VER < 1910
+// C4800 is a level 3 warning in Visual Studio 2015 and earlier.
+// This warning is not emitted in Visual Studio 2017.
+// This warning is off by default starting in Visual Studio 2019 but can be
+// enabled with command-line options.
+#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
#endif
@@ -298,7 +310,7 @@ class GTEST_API_ AssertionResult {
= nullptr)
: success_(success) {}
-#if defined(_MSC_VER) && _MSC_VER < 1910
+#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
GTEST_DISABLE_MSC_WARNINGS_POP_()
#endif
@@ -406,10 +418,10 @@ class GTEST_API_ Test {
// The d'tor is virtual as we intend to inherit from Test.
virtual ~Test();
- // Sets up the stuff shared by all tests in this test case.
+ // Sets up the stuff shared by all tests in this test suite.
//
// Google Test will call Foo::SetUpTestSuite() before running the first
- // test in test case Foo. Hence a sub-class can define its own
+ // test in test suite Foo. Hence a sub-class can define its own
// SetUpTestSuite() method to shadow the one defined in the super
// class.
static void SetUpTestSuite() {}
@@ -417,12 +429,13 @@ class GTEST_API_ Test {
// Tears down the stuff shared by all tests in this test suite.
//
// Google Test will call Foo::TearDownTestSuite() after running the last
- // test in test case Foo. Hence a sub-class can define its own
+ // test in test suite Foo. Hence a sub-class can define its own
// TearDownTestSuite() method to shadow the one defined in the super
// class.
static void TearDownTestSuite() {}
- // Legacy API is deprecated but still available
+ // Legacy API is deprecated but still available. Use SetUpTestSuite and
+ // TearDownTestSuite instead.
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
static void TearDownTestCase() {}
static void SetUpTestCase() {}
@@ -660,7 +673,7 @@ class GTEST_API_ TestResult {
// Protects mutable state of the property vector and of owned
// properties, whose values may be updated.
- internal::Mutex test_properites_mutex_;
+ internal::Mutex test_properties_mutex_;
// The vector of TestPartResults
std::vector<TestPartResult> test_part_results_;
@@ -790,6 +803,9 @@ class GTEST_API_ TestInfo {
// deletes it.
void Run();
+ // Skip and records the test result for this object.
+ void Skip();
+
static void ClearTestResult(TestInfo* test_info) {
test_info->result_.Clear();
}
@@ -938,6 +954,9 @@ class GTEST_API_ TestSuite {
// Runs every test in this TestSuite.
void Run();
+ // Skips the execution of tests under this TestSuite
+ void Skip();
+
// Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
// for catching exceptions thrown from SetUpTestSuite().
void RunSetUpTestSuite() {
@@ -1418,6 +1437,7 @@ class GTEST_API_ UnitTest {
friend class internal::StreamingListenerTest;
friend class internal::UnitTestRecordPropertyTestHelper;
friend Environment* AddGlobalTestEnvironment(Environment* env);
+ friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
friend internal::UnitTestImpl* internal::GetUnitTestImpl();
friend void internal::ReportFailureInUnknownLocation(
TestPartResult::Type result_type,
@@ -1529,14 +1549,6 @@ AssertionResult CmpHelperEQ(const char* lhs_expression,
return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
}
-// With this overloaded version, we allow anonymous enums to be used
-// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
-// can be implicitly cast to BiggestInt.
-GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression,
- const char* rhs_expression,
- BiggestInt lhs,
- BiggestInt rhs);
-
class EqHelper {
public:
// This templatized version is for the general case.
@@ -1593,11 +1605,6 @@ AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
// of similar code.
//
-// For each templatized helper function, we also define an overloaded
-// version for BiggestInt in order to reduce code bloat and allow
-// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
-// with gcc 4.
-//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
@@ -1609,22 +1616,20 @@ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
} else {\
return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
}\
-}\
-GTEST_API_ AssertionResult CmpHelper##op_name(\
- const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2)
+}
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
// Implements the helper function for {ASSERT|EXPECT}_NE
-GTEST_IMPL_CMP_HELPER_(NE, !=);
+GTEST_IMPL_CMP_HELPER_(NE, !=)
// Implements the helper function for {ASSERT|EXPECT}_LE
-GTEST_IMPL_CMP_HELPER_(LE, <=);
+GTEST_IMPL_CMP_HELPER_(LE, <=)
// Implements the helper function for {ASSERT|EXPECT}_LT
-GTEST_IMPL_CMP_HELPER_(LT, <);
+GTEST_IMPL_CMP_HELPER_(LT, <)
// Implements the helper function for {ASSERT|EXPECT}_GE
-GTEST_IMPL_CMP_HELPER_(GE, >=);
+GTEST_IMPL_CMP_HELPER_(GE, >=)
// Implements the helper function for {ASSERT|EXPECT}_GT
-GTEST_IMPL_CMP_HELPER_(GT, >);
+GTEST_IMPL_CMP_HELPER_(GT, >)
#undef GTEST_IMPL_CMP_HELPER_
@@ -1801,12 +1806,6 @@ class GTEST_API_ AssertHelper {
GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
};
-enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW };
-
-GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color,
- const char* fmt,
- ...);
-
} // namespace internal
// The pure interface class that all value-parameterized tests inherit from.
@@ -1963,19 +1962,38 @@ class TestWithParam : public Test, public WithParamInterface<T> {
// Boolean assertions. Condition can be either a Boolean expression or an
// AssertionResult. For more information on how to use AssertionResult with
// these macros see comments on that class.
-#define EXPECT_TRUE(condition) \
+#define GTEST_EXPECT_TRUE(condition) \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_NONFATAL_FAILURE_)
-#define EXPECT_FALSE(condition) \
+#define GTEST_EXPECT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_NONFATAL_FAILURE_)
-#define ASSERT_TRUE(condition) \
+#define GTEST_ASSERT_TRUE(condition) \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_FATAL_FAILURE_)
-#define ASSERT_FALSE(condition) \
+#define GTEST_ASSERT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_FATAL_FAILURE_)
+// Define these macros to 1 to omit the definition of the corresponding
+// EXPECT or ASSERT, which clashes with some users' own code.
+
+#if !GTEST_DONT_DEFINE_EXPECT_TRUE
+#define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
+#endif
+
+#if !GTEST_DONT_DEFINE_EXPECT_FALSE
+#define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
+#endif
+
+#if !GTEST_DONT_DEFINE_ASSERT_TRUE
+#define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
+#endif
+
+#if !GTEST_DONT_DEFINE_ASSERT_FALSE
+#define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
+#endif
+
// Macros for testing equalities and inequalities.
//
// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
@@ -2362,9 +2380,11 @@ constexpr bool StaticAssertTypeEq() noexcept {
// }
//
// GOOGLETEST_CM0011 DO NOT DELETE
+#if !GTEST_DONT_DEFINE_TEST
#define TEST_F(test_fixture, test_name)\
GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>())
+#endif // !GTEST_DONT_DEFINE_TEST
// Returns a path to temporary directory.
// Tries to determine an appropriate directory for the platform.
@@ -2472,4 +2492,4 @@ inline int RUN_ALL_TESTS() {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GTEST_INCLUDE_GTEST_GTEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_
diff --git a/googletest/include/gtest/gtest_pred_impl.h b/googletest/include/gtest/gtest_pred_impl.h
index d514255c..5029a9bb 100644
--- a/googletest/include/gtest/gtest_pred_impl.h
+++ b/googletest/include/gtest/gtest_pred_impl.h
@@ -33,8 +33,8 @@
// Implements a family of generic predicate assertion macros.
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
-#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
#include "gtest/gtest.h"
@@ -356,4 +356,4 @@ AssertionResult AssertPred5Helper(const char* pred_text,
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h
index e651671e..38b9d85a 100644
--- a/googletest/include/gtest/gtest_prod.h
+++ b/googletest/include/gtest/gtest_prod.h
@@ -31,8 +31,8 @@
// Google C++ Testing and Mocking Framework definitions useful in production code.
// GOOGLETEST_CM0003 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
-#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
+#define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
// When you need to test the private or protected members of a class,
// use the FRIEND_TEST macro to declare your tests as friends of the
@@ -58,4 +58,4 @@
#define FRIEND_TEST(test_case_name, test_name)\
friend class test_case_name##_##test_name##_Test
-#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
diff --git a/googletest/include/gtest/internal/custom/gtest-port.h b/googletest/include/gtest/internal/custom/gtest-port.h
index d941209a..c4ba098e 100644
--- a/googletest/include/gtest/internal/custom/gtest-port.h
+++ b/googletest/include/gtest/internal/custom/gtest-port.h
@@ -31,10 +31,10 @@
//
// ** Custom implementation starts here **
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
// Suppress warnings for deprecated *_TEST_CASE_* macros.
#define GTEST_INTERNAL_DEPRECATED(message)
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
diff --git a/googletest/include/gtest/internal/custom/gtest-printers.h b/googletest/include/gtest/internal/custom/gtest-printers.h
index eb4467ab..b9495d83 100644
--- a/googletest/include/gtest/internal/custom/gtest-printers.h
+++ b/googletest/include/gtest/internal/custom/gtest-printers.h
@@ -36,7 +36,7 @@
//
// ** Custom implementation starts here **
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
diff --git a/googletest/include/gtest/internal/custom/gtest.h b/googletest/include/gtest/internal/custom/gtest.h
index b134fc76..67ce67f1 100644
--- a/googletest/include/gtest/internal/custom/gtest.h
+++ b/googletest/include/gtest/internal/custom/gtest.h
@@ -31,10 +31,10 @@
//
// ** Custom implementation starts here **
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
-#if !GTEST_OS_WINDOWS
+#if GTEST_OS_LINUX_ANDROID
# define GTEST_CUSTOM_TEMPDIR_FUNCTION_ GetAndroidTempDir
# include <unistd.h>
static inline std::string GetAndroidTempDir() {
@@ -54,6 +54,6 @@ static inline std::string GetAndroidTempDir() {
}
return result;
}
-#endif //GTEST_OS_WINDOWS
+#endif //GTEST_OS_LINUX_ANDROID
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h
index 68bd3530..490296df 100644
--- a/googletest/include/gtest/internal/gtest-death-test-internal.h
+++ b/googletest/include/gtest/internal/gtest-death-test-internal.h
@@ -33,8 +33,8 @@
// death tests. They are subject to change without notice.
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#include "gtest/gtest-matchers.h"
#include "gtest/internal/gtest-internal.h"
@@ -301,4 +301,4 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
} // namespace internal
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h
index c11b1015..0c033abc 100644
--- a/googletest/include/gtest/internal/gtest-filepath.h
+++ b/googletest/include/gtest/internal/gtest-filepath.h
@@ -37,8 +37,8 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#include "gtest/internal/gtest-string.h"
@@ -195,7 +195,7 @@ class GTEST_API_ FilePath {
void Normalize();
- // Returns a pointer to the last occurence of a valid path separator in
+ // Returns a pointer to the last occurrence of a valid path separator in
// the FilePath. On Windows, for example, both '/' and '\' are valid path
// separators. Returns NULL if no path separator was found.
const char* FindLastPathSeparator() const;
@@ -208,4 +208,4 @@ class GTEST_API_ FilePath {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h
index 41c94f44..f8cbdbd8 100644
--- a/googletest/include/gtest/internal/gtest-internal.h
+++ b/googletest/include/gtest/internal/gtest-internal.h
@@ -34,8 +34,8 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
#include "gtest/internal/gtest-port.h"
@@ -90,7 +90,9 @@
#define GTEST_STRINGIFY_HELPER_(name, ...) #name
#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
-namespace proto2 { class Message; }
+namespace proto2 {
+class MessageLite;
+}
namespace testing {
@@ -285,7 +287,7 @@ class FloatingPoint {
//
// See the following article for more details on ULP:
// http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
- static const size_t kMaxUlps = 4;
+ static const uint32_t kMaxUlps = 4;
// Constructs a FloatingPoint from a raw floating-point number.
//
@@ -518,6 +520,7 @@ struct SuiteApiResolver : T {
static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,
int line_num) {
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
SetUpTearDownSuiteFuncType test_case_fp =
GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
SetUpTearDownSuiteFuncType test_suite_fp =
@@ -529,10 +532,16 @@ struct SuiteApiResolver : T {
<< filename << ":" << line_num;
return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
+#else
+ (void)(filename);
+ (void)(line_num);
+ return &T::SetUpTestSuite;
+#endif
}
static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,
int line_num) {
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
SetUpTearDownSuiteFuncType test_case_fp =
GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
SetUpTearDownSuiteFuncType test_suite_fp =
@@ -544,6 +553,11 @@ struct SuiteApiResolver : T {
<< filename << ":" << line_num;
return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
+#else
+ (void)(filename);
+ (void)(line_num);
+ return &T::TearDownTestSuite;
+#endif
}
};
@@ -552,11 +566,11 @@ struct SuiteApiResolver : T {
//
// Arguments:
//
-// test_suite_name: name of the test suite
+// test_suite_name: name of the test suite
// name: name of the test
-// type_param the name of the test's type parameter, or NULL if
+// type_param: the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test.
-// value_param text representation of the test's value parameter,
+// value_param: text representation of the test's value parameter,
// or NULL if this is not a type-parameterized test.
// code_location: code location where the test is defined
// fixture_class_id: ID of the test fixture class
@@ -576,8 +590,6 @@ GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
// and returns false. None of pstr, *pstr, and prefix can be NULL.
GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
-#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@@ -809,8 +821,6 @@ class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
}
};
-#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
// Returns the current OS stack trace as an std::string.
//
// The maximum number of stack frames to be included is specified by
@@ -844,7 +854,7 @@ struct GTEST_API_ ConstCharPtr {
// Helper for declaring std::string within 'if' statement
// in pre C++17 build environment.
-struct GTEST_API_ TrueWithString {
+struct TrueWithString {
TrueWithString() = default;
explicit TrueWithString(const char* str) : value(str) {}
explicit TrueWithString(const std::string& str) : value(str) {}
@@ -878,11 +888,34 @@ class GTEST_API_ Random {
#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
typename std::remove_const<typename std::remove_reference<T>::type>::type
-// IsAProtocolMessage<T>::value is a compile-time bool constant that's
-// true if and only if T is type proto2::Message or a subclass of it.
+// HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
+// that's true if and only if T has methods DebugString() and ShortDebugString()
+// that return std::string.
template <typename T>
-struct IsAProtocolMessage
- : public std::is_convertible<const T*, const ::proto2::Message*> {};
+class HasDebugStringAndShortDebugString {
+ private:
+ template <typename C>
+ static auto CheckDebugString(C*) -> typename std::is_same<
+ std::string, decltype(std::declval<const C>().DebugString())>::type;
+ template <typename>
+ static std::false_type CheckDebugString(...);
+
+ template <typename C>
+ static auto CheckShortDebugString(C*) -> typename std::is_same<
+ std::string, decltype(std::declval<const C>().ShortDebugString())>::type;
+ template <typename>
+ static std::false_type CheckShortDebugString(...);
+
+ using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));
+ using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));
+
+ public:
+ static constexpr bool value =
+ HasDebugStringType::value && HasShortDebugStringType::value;
+};
+
+template <typename T>
+constexpr bool HasDebugStringAndShortDebugString<T>::value;
// When the compiler sees expression IsContainerTest<C>(0), if C is an
// STL-style container class, the first overload of IsContainerTest
@@ -1118,8 +1151,6 @@ class NativeArray {
const Element* array_;
size_t size_;
void (NativeArray::*clone_)(const Element*, size_t);
-
- GTEST_DISALLOW_ASSIGN_(NativeArray);
};
// Backport of std::index_sequence.
@@ -1143,12 +1174,18 @@ struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
// Backport of std::make_index_sequence.
// It uses O(ln(N)) instantiation depth.
template <size_t N>
-struct MakeIndexSequence
- : DoubleSequence<N % 2 == 1, typename MakeIndexSequence<N / 2>::type,
+struct MakeIndexSequenceImpl
+ : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
N / 2>::type {};
template <>
-struct MakeIndexSequence<0> : IndexSequence<> {};
+struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
+
+template <size_t N>
+using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
+
+template <typename... T>
+using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
template <size_t>
struct Ignore {
@@ -1174,6 +1211,8 @@ struct ElemFromList {
static_cast<T (*)()>(nullptr)...));
};
+struct FlatTupleConstructTag {};
+
template <typename... T>
class FlatTuple;
@@ -1184,7 +1223,9 @@ template <typename... T, size_t I>
struct FlatTupleElemBase<FlatTuple<T...>, I> {
using value_type = typename ElemFromList<I, T...>::type;
FlatTupleElemBase() = default;
- explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {}
+ template <typename Arg>
+ explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)
+ : value(std::forward<Arg>(t)) {}
value_type value;
};
@@ -1196,8 +1237,30 @@ struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
: FlatTupleElemBase<FlatTuple<T...>, Idx>... {
using Indices = IndexSequence<Idx...>;
FlatTupleBase() = default;
- explicit FlatTupleBase(T... t)
- : FlatTupleElemBase<FlatTuple<T...>, Idx>(std::move(t))... {}
+ template <typename... Args>
+ explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
+ : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},
+ std::forward<Args>(args))... {}
+
+ template <size_t I>
+ const typename ElemFromList<I, T...>::type& Get() const {
+ return FlatTupleElemBase<FlatTuple<T...>, I>::value;
+ }
+
+ template <size_t I>
+ typename ElemFromList<I, T...>::type& Get() {
+ return FlatTupleElemBase<FlatTuple<T...>, I>::value;
+ }
+
+ template <typename F>
+ auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
+ return std::forward<F>(f)(Get<Idx>()...);
+ }
+
+ template <typename F>
+ auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {
+ return std::forward<F>(f)(Get<Idx>()...);
+ }
};
// Analog to std::tuple but with different tradeoffs.
@@ -1218,17 +1281,12 @@ class FlatTuple
public:
FlatTuple() = default;
- explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {}
+ template <typename... Args>
+ explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)
+ : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}
- template <size_t I>
- const typename ElemFromList<I, T...>::type& Get() const {
- return static_cast<const FlatTupleElemBase<FlatTuple, I>*>(this)->value;
- }
-
- template <size_t I>
- typename ElemFromList<I, T...>::type& Get() {
- return static_cast<FlatTupleElemBase<FlatTuple, I>*>(this)->value;
- }
+ using FlatTuple::FlatTupleBase::Apply;
+ using FlatTuple::FlatTupleBase::Get;
};
// Utility functions to be called with static_assert to induce deprecation
@@ -1261,6 +1319,22 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
} // namespace internal
} // namespace testing
+namespace std {
+// Some standard library implementations use `struct tuple_size` and some use
+// `class tuple_size`. Clang warns about the mismatch.
+// https://reviews.llvm.org/D55466
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wmismatched-tags"
+#endif
+template <typename... Ts>
+struct tuple_size<testing::internal::FlatTuple<Ts...>>
+ : std::integral_constant<size_t, sizeof...(Ts)> {};
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+} // namespace std
+
#define GTEST_MESSAGE_AT_(file, line, message, result_type) \
::testing::internal::AssertHelper(result_type, file, line, message) \
= ::testing::Message()
@@ -1283,44 +1357,98 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
// Suppress MSVC warning 4072 (unreachable code) for the code following
// statement if it returns or throws (or doesn't return or throw in some
// situations).
+// NOTE: The "else" is important to keep this expansion to prevent a top-level
+// "else" from attaching to our "if".
#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
- if (::testing::internal::AlwaysTrue()) { statement; }
+ if (::testing::internal::AlwaysTrue()) { \
+ statement; \
+ } else /* NOLINT */ \
+ static_assert(true, "") // User must have a semicolon after expansion.
-#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
- GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
- if (::testing::internal::ConstCharPtr gtest_msg = "") { \
- bool gtest_caught_expected = false; \
- try { \
- GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
- } \
- catch (expected_exception const&) { \
- gtest_caught_expected = true; \
- } \
- catch (...) { \
- gtest_msg.value = \
- "Expected: " #statement " throws an exception of type " \
- #expected_exception ".\n Actual: it throws a different type."; \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- if (!gtest_caught_expected) { \
- gtest_msg.value = \
- "Expected: " #statement " throws an exception of type " \
- #expected_exception ".\n Actual: it throws nothing."; \
- goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
- } \
- } else \
- GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
- fail(gtest_msg.value)
+#if GTEST_HAS_EXCEPTIONS
+
+namespace testing {
+namespace internal {
+
+class NeverThrown {
+ public:
+ const char* what() const noexcept {
+ return "this exception should never be thrown";
+ }
+};
+
+} // namespace internal
+} // namespace testing
+
+#if GTEST_HAS_RTTI
+
+#define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
+
+#else // GTEST_HAS_RTTI
+
+#define GTEST_EXCEPTION_TYPE_(e) \
+ std::string { "an std::exception-derived error" }
+
+#endif // GTEST_HAS_RTTI
+
+#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
+ catch (typename std::conditional< \
+ std::is_same<typename std::remove_cv<typename std::remove_reference< \
+ expected_exception>::type>::type, \
+ std::exception>::value, \
+ const ::testing::internal::NeverThrown&, const std::exception&>::type \
+ e) { \
+ gtest_msg.value = "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws "; \
+ gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
+ gtest_msg.value += " with description \""; \
+ gtest_msg.value += e.what(); \
+ gtest_msg.value += "\"."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ }
+
+#else // GTEST_HAS_EXCEPTIONS
+
+#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
+
+#endif // GTEST_HAS_EXCEPTIONS
+
+#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
+ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
+ if (::testing::internal::TrueWithString gtest_msg{}) { \
+ bool gtest_caught_expected = false; \
+ try { \
+ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
+ } catch (expected_exception const&) { \
+ gtest_caught_expected = true; \
+ } \
+ GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
+ catch (...) { \
+ gtest_msg.value = "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws a different type."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ if (!gtest_caught_expected) { \
+ gtest_msg.value = "Expected: " #statement \
+ " throws an exception of type " #expected_exception \
+ ".\n Actual: it throws nothing."; \
+ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
+ } \
+ } else /*NOLINT*/ \
+ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
+ : fail(gtest_msg.value.c_str())
#if GTEST_HAS_EXCEPTIONS
-#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
- catch (std::exception const& e) { \
- gtest_msg.value = ( \
- "it throws std::exception-derived exception with description: \"" \
- ); \
- gtest_msg.value += e.what(); \
- gtest_msg.value += "\"."; \
+#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
+ catch (std::exception const& e) { \
+ gtest_msg.value = "it throws "; \
+ gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
+ gtest_msg.value += " with description \""; \
+ gtest_msg.value += e.what(); \
+ gtest_msg.value += "\"."; \
goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
}
@@ -1367,7 +1495,7 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
// Implements Boolean test assertions such as EXPECT_TRUE. expression can be
// either a boolean expression or an AssertionResult. text is a textual
-// represenation of expression as it was passed into the EXPECT_TRUE.
+// representation of expression as it was passed into the EXPECT_TRUE.
#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (const ::testing::AssertionResult gtest_ar_ = \
@@ -1404,8 +1532,8 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
: public parent_class { \
public: \
- GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
- ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
+ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
+ ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)); \
GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
@@ -1429,4 +1557,4 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
test_suite_name, test_name)>); \
void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h
index ffa7d72c..3e49a6ba 100644
--- a/googletest/include/gtest/internal/gtest-param-util.h
+++ b/googletest/include/gtest/internal/gtest-param-util.h
@@ -32,8 +32,8 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
#include <ctype.h>
@@ -459,7 +459,7 @@ class ParameterizedTestSuiteInfoBase {
// Base part of test suite name for display purposes.
virtual const std::string& GetTestSuiteName() const = 0;
- // Test case id to verify identity.
+ // Test suite id to verify identity.
virtual TypeId GetTestSuiteTypeId() const = 0;
// UnitTest class invokes this method to register tests in this
// test suite right before running them in RUN_ALL_TESTS macro.
@@ -474,8 +474,16 @@ class ParameterizedTestSuiteInfoBase {
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
};
+// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
+//
+// Report a the name of a test_suit as safe to ignore
+// as the side effect of construction of this type.
+struct MarkAsIgnored {
+ explicit MarkAsIgnored(const char* test_suite);
+};
+
GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
- CodeLocation location);
+ CodeLocation location, bool has_test_p);
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
@@ -499,11 +507,11 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
CodeLocation code_location)
: test_suite_name_(name), code_location_(code_location) {}
- // Test case base name for display purposes.
+ // Test suite base name for display purposes.
const std::string& GetTestSuiteName() const override {
return test_suite_name_;
}
- // Test case id to verify identity.
+ // Test suite id to verify identity.
TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }
// TEST_P macro uses AddTestPattern() to record information
// about a single test in a LocalTestInfo structure.
@@ -512,9 +520,10 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
// parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
// test suite base name and DoBar is test base name.
void AddTestPattern(const char* test_suite_name, const char* test_base_name,
- TestMetaFactoryBase<ParamType>* meta_factory) {
- tests_.push_back(std::shared_ptr<TestInfo>(
- new TestInfo(test_suite_name, test_base_name, meta_factory)));
+ TestMetaFactoryBase<ParamType>* meta_factory,
+ CodeLocation code_location) {
+ tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
+ test_suite_name, test_base_name, meta_factory, code_location)));
}
// INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
// about a generator.
@@ -581,7 +590,7 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
MakeAndRegisterTestInfo(
test_suite_name.c_str(), test_name_stream.GetString().c_str(),
nullptr, // No type parameter.
- PrintToString(*param_it).c_str(), code_location_,
+ PrintToString(*param_it).c_str(), test_info->code_location,
GetTestSuiteTypeId(),
SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
@@ -592,7 +601,8 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
if (!generated_instantiations) {
// There are no generaotrs, or they all generate nothing ...
- InsertSyntheticTestCase(GetTestSuiteName(), code_location_);
+ InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
+ !tests_.empty());
}
} // RegisterTests
@@ -601,14 +611,17 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
// with TEST_P macro.
struct TestInfo {
TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
- TestMetaFactoryBase<ParamType>* a_test_meta_factory)
+ TestMetaFactoryBase<ParamType>* a_test_meta_factory,
+ CodeLocation a_code_location)
: test_suite_base_name(a_test_suite_base_name),
test_base_name(a_test_base_name),
- test_meta_factory(a_test_meta_factory) {}
+ test_meta_factory(a_test_meta_factory),
+ code_location(a_code_location) {}
const std::string test_suite_base_name;
const std::string test_base_name;
const std::unique_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
+ const CodeLocation code_location;
};
using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
// Records data received from INSTANTIATE_TEST_SUITE_P macros:
@@ -770,10 +783,15 @@ internal::ParamGenerator<typename Container::value_type> ValuesIn(
namespace internal {
// Used in the Values() function to provide polymorphic capabilities.
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4100)
+#endif
+
template <typename... Ts>
class ValueArray {
public:
- ValueArray(Ts... v) : v_{std::move(v)...} {}
+ explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
template <typename T>
operator ParamGenerator<T>() const { // NOLINT
@@ -789,6 +807,10 @@ class ValueArray {
FlatTuple<Ts...> v_;
};
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
template <typename... T>
class CartesianProductGenerator
: public ParamGeneratorInterface<::std::tuple<T...>> {
@@ -922,4 +944,4 @@ class CartesianProductHolder {
} // namespace internal
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h
index d3239b25..dd845915 100644
--- a/googletest/include/gtest/internal/gtest-port-arch.h
+++ b/googletest/include/gtest/internal/gtest-port-arch.h
@@ -32,8 +32,8 @@
// This header file defines the GTEST_OS_* macro.
// It is separate from gtest-port.h so that custom/gtest-port.h can include it.
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
// Determines the platform on which Google Test is compiled.
#ifdef __CYGWIN__
@@ -68,6 +68,7 @@
# define GTEST_OS_OS2 1
#elif defined __APPLE__
# define GTEST_OS_MAC 1
+# include <TargetConditionals.h>
# if TARGET_OS_IPHONE
# define GTEST_OS_IOS 1
# endif
@@ -106,6 +107,8 @@
#define GTEST_OS_ESP8266 1
#elif defined ESP32
#define GTEST_OS_ESP32 1
+#elif defined(__XTENSA__)
+#define GTEST_OS_XTENSA 1
#endif // __CYGWIN__
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h
index 0543da54..0953a781 100644
--- a/googletest/include/gtest/internal/gtest-port.h
+++ b/googletest/include/gtest/internal/gtest-port.h
@@ -40,8 +40,8 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
// Environment-describing macros
// -----------------------------
@@ -199,6 +199,18 @@
// suppressed (constant conditional).
// GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
// is suppressed.
+// GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
+// UniversalPrinter<absl::any> specializations.
+// GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
+// or
+// UniversalPrinter<absl::optional>
+// specializations.
+// GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
+// Matcher<absl::string_view>
+// specializations.
+// GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
+// UniversalPrinter<absl::variant>
+// specializations.
//
// Synchronization:
// Mutex, MutexLock, ThreadLocal, GetThreadCount()
@@ -249,6 +261,8 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+
+#include <cerrno>
#include <cstdint>
#include <limits>
#include <type_traits>
@@ -264,6 +278,7 @@
#endif
#include <iostream> // NOLINT
+#include <locale>
#include <memory>
#include <string> // NOLINT
#include <tuple>
@@ -344,6 +359,10 @@ typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.
typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#endif
+#elif GTEST_OS_XTENSA
+#include <unistd.h>
+// Xtensa toolchains define strcasecmp in the string.h header instead of
+// strings.h. string.h is already included.
#else
// This assumes that non-Windows OSes provide unistd.h. For OSes where this
// is not the case, we need to include headers that provide the functions
@@ -364,7 +383,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// On Android, <regex.h> is only available starting with Gingerbread.
# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)
# else
-# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS)
+#define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)
# endif
#endif
@@ -449,7 +468,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// no support for it at least as recent as Froyo (2.2).
#define GTEST_HAS_STD_WSTRING \
(!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \
- GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266))
+ GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA))
#endif // GTEST_HAS_STD_WSTRING
@@ -574,7 +593,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// By default, we assume that stream redirection is supported on all
// platforms except known mobile ones.
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
- GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266
+ GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
# define GTEST_HAS_STREAM_REDIRECTION 0
# else
# define GTEST_HAS_STREAM_REDIRECTION 1
@@ -676,8 +695,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// A macro to disallow copy constructor and operator=
// This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
- type(type const &) = delete; \
- GTEST_DISALLOW_ASSIGN_(type)
+ type(type const&) = delete; \
+ type& operator=(type const&) = delete
// A macro to disallow move operator=
// This should be used in the private: declarations for a class.
@@ -687,8 +706,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// A macro to disallow move constructor and operator=
// This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
- type(type &&) noexcept = delete; \
- GTEST_DISALLOW_MOVE_ASSIGN_(type)
+ type(type&&) noexcept = delete; \
+ type& operator=(type&&) noexcept = delete
// Tell the compiler to warn about unused return values for functions declared
// with this macro. The macro should be used on function declarations
@@ -915,8 +934,6 @@ class GTEST_API_ RE {
const char* full_pattern_; // For FullMatch();
# endif
-
- GTEST_DISALLOW_ASSIGN_(RE);
};
#endif // GTEST_USES_PCRE
@@ -1923,6 +1940,19 @@ inline bool IsUpper(char ch) {
inline bool IsXDigit(char ch) {
return isxdigit(static_cast<unsigned char>(ch)) != 0;
}
+#ifdef __cpp_char8_t
+inline bool IsXDigit(char8_t ch) {
+ return isxdigit(static_cast<unsigned char>(ch)) != 0;
+}
+#endif
+inline bool IsXDigit(char16_t ch) {
+ const unsigned char low_byte = static_cast<unsigned char>(ch);
+ return ch == low_byte && isxdigit(low_byte) != 0;
+}
+inline bool IsXDigit(char32_t ch) {
+ const unsigned char low_byte = static_cast<unsigned char>(ch);
+ return ch == low_byte && isxdigit(low_byte) != 0;
+}
inline bool IsXDigit(wchar_t ch) {
const unsigned char low_byte = static_cast<unsigned char>(ch);
return ch == low_byte && isxdigit(low_byte) != 0;
@@ -1957,16 +1987,16 @@ namespace posix {
typedef struct _stat StatStruct;
# ifdef __BORLANDC__
-inline int IsATTY(int fd) { return isatty(fd); }
+inline int DoIsATTY(int fd) { return isatty(fd); }
inline int StrCaseCmp(const char* s1, const char* s2) {
return stricmp(s1, s2);
}
inline char* StrDup(const char* src) { return strdup(src); }
# else // !__BORLANDC__
# if GTEST_OS_WINDOWS_MOBILE
-inline int IsATTY(int /* fd */) { return 0; }
+inline int DoIsATTY(int /* fd */) { return 0; }
# else
-inline int IsATTY(int fd) { return _isatty(fd); }
+inline int DoIsATTY(int fd) { return _isatty(fd); }
# endif // GTEST_OS_WINDOWS_MOBILE
inline int StrCaseCmp(const char* s1, const char* s2) {
return _stricmp(s1, s2);
@@ -1991,7 +2021,7 @@ inline bool IsDir(const StatStruct& st) {
typedef struct stat StatStruct;
inline int FileNo(FILE* file) { return fileno(file); }
-inline int IsATTY(int fd) { return isatty(fd); }
+inline int DoIsATTY(int fd) { return isatty(fd); }
inline int Stat(const char* path, StatStruct* buf) {
// stat function not implemented on ESP8266
return 0;
@@ -2008,7 +2038,7 @@ inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
typedef struct stat StatStruct;
inline int FileNo(FILE* file) { return fileno(file); }
-inline int IsATTY(int fd) { return isatty(fd); }
+inline int DoIsATTY(int fd) { return isatty(fd); }
inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
inline int StrCaseCmp(const char* s1, const char* s2) {
return strcasecmp(s1, s2);
@@ -2019,6 +2049,17 @@ inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }
#endif // GTEST_OS_WINDOWS
+inline int IsATTY(int fd) {
+ // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout
+ // to a file on Linux), which is unexpected, so save the previous value, and
+ // restore it after the call.
+ int savedErrno = errno;
+ int isAttyValue = DoIsATTY(fd);
+ errno = savedErrno;
+
+ return isAttyValue;
+}
+
// Functions deprecated by MSVC 8.0.
GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
@@ -2027,11 +2068,20 @@ GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
// StrError() aren't needed on Windows CE at this time and thus not
// defined there.
-#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
+#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \
+ !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA
inline int ChDir(const char* dir) { return chdir(dir); }
#endif
inline FILE* FOpen(const char* path, const char* mode) {
+#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
+ struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
+ std::wstring_convert<wchar_codecvt> converter;
+ std::wstring wide_path = converter.from_bytes(path);
+ std::wstring wide_mode = converter.from_bytes(mode);
+ return _wfopen(wide_path.c_str(), wide_mode.c_str());
+#else // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
return fopen(path, mode);
+#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
}
#if !GTEST_OS_WINDOWS_MOBILE
inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
@@ -2052,7 +2102,7 @@ inline const char* StrError(int errnum) { return strerror(errnum); }
#endif
inline const char* GetEnv(const char* name) {
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
- GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266
+ GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA
// We are on an embedded platform, which has no environment variables.
static_cast<void>(name); // To prevent 'unused argument' warning.
return nullptr;
@@ -2188,7 +2238,8 @@ using TimeInMillis = int64_t; // Represents time in milliseconds.
// Parses 'str' for a 32-bit signed integer. If successful, writes the result
// to *value and returns true; otherwise leaves *value unchanged and returns
// false.
-bool ParseInt32(const Message& src_text, const char* str, int32_t* value);
+GTEST_API_ bool ParseInt32(const Message& src_text, const char* str,
+ int32_t* value);
// Parses a bool/int32_t/string from the environment variable
// corresponding to the given Google Test flag.
@@ -2220,4 +2271,119 @@ const char* StringFromGTestEnv(const char* flag, const char* default_val);
#endif // !defined(GTEST_INTERNAL_DEPRECATED)
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
+#if GTEST_HAS_ABSL
+// Always use absl::any for UniversalPrinter<> specializations if googletest
+// is built with absl support.
+#define GTEST_INTERNAL_HAS_ANY 1
+#include "absl/types/any.h"
+namespace testing {
+namespace internal {
+using Any = ::absl::any;
+} // namespace internal
+} // namespace testing
+#else
+#ifdef __has_include
+#if __has_include(<any>) && __cplusplus >= 201703L
+// Otherwise for C++17 and higher use std::any for UniversalPrinter<>
+// specializations.
+#define GTEST_INTERNAL_HAS_ANY 1
+#include <any>
+namespace testing {
+namespace internal {
+using Any = ::std::any;
+} // namespace internal
+} // namespace testing
+// The case where absl is configured NOT to alias std::any is not
+// supported.
+#endif // __has_include(<any>) && __cplusplus >= 201703L
+#endif // __has_include
+#endif // GTEST_HAS_ABSL
+
+#if GTEST_HAS_ABSL
+// Always use absl::optional for UniversalPrinter<> specializations if
+// googletest is built with absl support.
+#define GTEST_INTERNAL_HAS_OPTIONAL 1
+#include "absl/types/optional.h"
+namespace testing {
+namespace internal {
+template <typename T>
+using Optional = ::absl::optional<T>;
+} // namespace internal
+} // namespace testing
+#else
+#ifdef __has_include
+#if __has_include(<optional>) && __cplusplus >= 201703L
+// Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
+// specializations.
+#define GTEST_INTERNAL_HAS_OPTIONAL 1
+#include <optional>
+namespace testing {
+namespace internal {
+template <typename T>
+using Optional = ::std::optional<T>;
+} // namespace internal
+} // namespace testing
+// The case where absl is configured NOT to alias std::optional is not
+// supported.
+#endif // __has_include(<optional>) && __cplusplus >= 201703L
+#endif // __has_include
+#endif // GTEST_HAS_ABSL
+
+#if GTEST_HAS_ABSL
+// Always use absl::string_view for Matcher<> specializations if googletest
+// is built with absl support.
+# define GTEST_INTERNAL_HAS_STRING_VIEW 1
+#include "absl/strings/string_view.h"
+namespace testing {
+namespace internal {
+using StringView = ::absl::string_view;
+} // namespace internal
+} // namespace testing
+#else
+# ifdef __has_include
+# if __has_include(<string_view>) && __cplusplus >= 201703L
+// Otherwise for C++17 and higher use std::string_view for Matcher<>
+// specializations.
+# define GTEST_INTERNAL_HAS_STRING_VIEW 1
+#include <string_view>
+namespace testing {
+namespace internal {
+using StringView = ::std::string_view;
+} // namespace internal
+} // namespace testing
+// The case where absl is configured NOT to alias std::string_view is not
+// supported.
+# endif // __has_include(<string_view>) && __cplusplus >= 201703L
+# endif // __has_include
+#endif // GTEST_HAS_ABSL
+
+#if GTEST_HAS_ABSL
+// Always use absl::variant for UniversalPrinter<> specializations if googletest
+// is built with absl support.
+#define GTEST_INTERNAL_HAS_VARIANT 1
+#include "absl/types/variant.h"
+namespace testing {
+namespace internal {
+template <typename... T>
+using Variant = ::absl::variant<T...>;
+} // namespace internal
+} // namespace testing
+#else
+#ifdef __has_include
+#if __has_include(<variant>) && __cplusplus >= 201703L
+// Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
+// specializations.
+#define GTEST_INTERNAL_HAS_VARIANT 1
+#include <variant>
+namespace testing {
+namespace internal {
+template <typename... T>
+using Variant = ::std::variant<T...>;
+} // namespace internal
+} // namespace testing
+// The case where absl is configured NOT to alias std::variant is not supported.
+#endif // __has_include(<variant>) && __cplusplus >= 201703L
+#endif // __has_include
+#endif // GTEST_HAS_ABSL
+
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h
index 0b2a91a5..10f774f9 100644
--- a/googletest/include/gtest/internal/gtest-string.h
+++ b/googletest/include/gtest/internal/gtest-string.h
@@ -38,8 +38,8 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
#ifdef __BORLANDC__
// string.h is not guaranteed to provide strcpy on C++ Builder.
@@ -149,6 +149,9 @@ class GTEST_API_ String {
// Formats an int value as "%02d".
static std::string FormatIntWidth2(int value); // "%02d" for width == 2
+ // Formats an int value to given width with leading zeros.
+ static std::string FormatIntWidthN(int value, int width);
+
// Formats an int value as "%X".
static std::string FormatHexInt(int value);
@@ -169,4 +172,4 @@ GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
} // namespace internal
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h
index 082fdad1..b87a2e2c 100644
--- a/googletest/include/gtest/internal/gtest-type-util.h
+++ b/googletest/include/gtest/internal/gtest-type-util.h
@@ -32,8 +32,8 @@
// GOOGLETEST_CM0001 DO NOT DELETE
-#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
-#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
+#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
+#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#include "gtest/internal/gtest-port.h"
@@ -64,38 +64,40 @@ inline std::string CanonicalizeForStdLibVersioning(std::string s) {
return s;
}
-// GetTypeName<T>() returns a human-readable name of type T.
-// NB: This function is also used in Google Mock, so don't move it inside of
-// the typed-test-only section below.
-template <typename T>
-std::string GetTypeName() {
-# if GTEST_HAS_RTTI
-
- const char* const name = typeid(T).name();
-# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
+#if GTEST_HAS_RTTI
+// GetTypeName(const std::type_info&) returns a human-readable name of type T.
+inline std::string GetTypeName(const std::type_info& type) {
+ const char* const name = type.name();
+#if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)
int status = 0;
// gcc's implementation of typeid(T).name() mangles the type name,
// so we have to demangle it.
-# if GTEST_HAS_CXXABI_H_
+#if GTEST_HAS_CXXABI_H_
using abi::__cxa_demangle;
-# endif // GTEST_HAS_CXXABI_H_
+#endif // GTEST_HAS_CXXABI_H_
char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);
const std::string name_str(status == 0 ? readable_name : name);
free(readable_name);
return CanonicalizeForStdLibVersioning(name_str);
-# else
+#else
return name;
-# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
-
-# else
+#endif // GTEST_HAS_CXXABI_H_ || __HP_aCC
+}
+#endif // GTEST_HAS_RTTI
+// GetTypeName<T>() returns a human-readable name of type T if and only if
+// RTTI is enabled, otherwise it returns a dummy type name.
+// NB: This function is also used in Google Mock, so don't move it inside of
+// the typed-test-only section below.
+template <typename T>
+std::string GetTypeName() {
+#if GTEST_HAS_RTTI
+ return GetTypeName(typeid(T));
+#else
return "<type>";
-
-# endif // GTEST_HAS_RTTI
+#endif // GTEST_HAS_RTTI
}
-#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
// A unique type indicating an empty node
struct None {};
@@ -171,8 +173,6 @@ struct GenerateTypeList {
using type = typename proxy::type;
};
-#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
-
} // namespace internal
template <typename... Ts>
@@ -180,4 +180,4 @@ using Types = internal::ProxyTypeList<Ts...>;
} // namespace testing
-#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
+#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
diff --git a/googletest/samples/prime_tables.h b/googletest/samples/prime_tables.h
index 72539bf1..3a10352b 100644
--- a/googletest/samples/prime_tables.h
+++ b/googletest/samples/prime_tables.h
@@ -33,8 +33,8 @@
// prime and determines a next prime number. This interface is used
// in Google Test samples demonstrating use of parameterized tests.
-#ifndef GTEST_SAMPLES_PRIME_TABLES_H_
-#define GTEST_SAMPLES_PRIME_TABLES_H_
+#ifndef GOOGLETEST_SAMPLES_PRIME_TABLES_H_
+#define GOOGLETEST_SAMPLES_PRIME_TABLES_H_
#include <algorithm>
@@ -66,11 +66,11 @@ class OnTheFlyPrimeTable : public PrimeTable {
}
int GetNextPrime(int p) const override {
- for (int n = p + 1; n > 0; n++) {
+ if (p < 0) return -1;
+
+ for (int n = p + 1;; n++) {
if (IsPrime(n)) return n;
}
-
- return -1;
}
};
@@ -123,4 +123,4 @@ class PreCalculatedPrimeTable : public PrimeTable {
void operator=(const PreCalculatedPrimeTable& rhs);
};
-#endif // GTEST_SAMPLES_PRIME_TABLES_H_
+#endif // GOOGLETEST_SAMPLES_PRIME_TABLES_H_
diff --git a/googletest/samples/sample1.h b/googletest/samples/sample1.h
index 12e49dea..ba392cfb 100644
--- a/googletest/samples/sample1.h
+++ b/googletest/samples/sample1.h
@@ -29,8 +29,8 @@
// A sample program demonstrating using Google C++ testing framework.
-#ifndef GTEST_SAMPLES_SAMPLE1_H_
-#define GTEST_SAMPLES_SAMPLE1_H_
+#ifndef GOOGLETEST_SAMPLES_SAMPLE1_H_
+#define GOOGLETEST_SAMPLES_SAMPLE1_H_
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
int Factorial(int n);
@@ -38,4 +38,4 @@ int Factorial(int n);
// Returns true if and only if n is a prime number.
bool IsPrime(int n);
-#endif // GTEST_SAMPLES_SAMPLE1_H_
+#endif // GOOGLETEST_SAMPLES_SAMPLE1_H_
diff --git a/googletest/samples/sample2.h b/googletest/samples/sample2.h
index e9a5a705..0f986895 100644
--- a/googletest/samples/sample2.h
+++ b/googletest/samples/sample2.h
@@ -29,8 +29,8 @@
// A sample program demonstrating using Google C++ testing framework.
-#ifndef GTEST_SAMPLES_SAMPLE2_H_
-#define GTEST_SAMPLES_SAMPLE2_H_
+#ifndef GOOGLETEST_SAMPLES_SAMPLE2_H_
+#define GOOGLETEST_SAMPLES_SAMPLE2_H_
#include <string.h>
@@ -77,5 +77,4 @@ class MyString {
void Set(const char* c_string);
};
-
-#endif // GTEST_SAMPLES_SAMPLE2_H_
+#endif // GOOGLETEST_SAMPLES_SAMPLE2_H_
diff --git a/googletest/samples/sample3-inl.h b/googletest/samples/sample3-inl.h
index 80ba6b92..659e0f0b 100644
--- a/googletest/samples/sample3-inl.h
+++ b/googletest/samples/sample3-inl.h
@@ -29,8 +29,8 @@
// A sample program demonstrating using Google C++ testing framework.
-#ifndef GTEST_SAMPLES_SAMPLE3_INL_H_
-#define GTEST_SAMPLES_SAMPLE3_INL_H_
+#ifndef GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
+#define GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
#include <stddef.h>
@@ -169,4 +169,4 @@ class Queue {
const Queue& operator = (const Queue&);
};
-#endif // GTEST_SAMPLES_SAMPLE3_INL_H_
+#endif // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
diff --git a/googletest/samples/sample4.h b/googletest/samples/sample4.h
index e256f406..0c4ed92e 100644
--- a/googletest/samples/sample4.h
+++ b/googletest/samples/sample4.h
@@ -28,8 +28,8 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// A sample program demonstrating using Google C++ testing framework.
-#ifndef GTEST_SAMPLES_SAMPLE4_H_
-#define GTEST_SAMPLES_SAMPLE4_H_
+#ifndef GOOGLETEST_SAMPLES_SAMPLE4_H_
+#define GOOGLETEST_SAMPLES_SAMPLE4_H_
// A simple monotonic counter.
class Counter {
@@ -50,4 +50,4 @@ class Counter {
void Print() const;
};
-#endif // GTEST_SAMPLES_SAMPLE4_H_
+#endif // GOOGLETEST_SAMPLES_SAMPLE4_H_
diff --git a/googletest/samples/sample6_unittest.cc b/googletest/samples/sample6_unittest.cc
index 0266e27e..da317eed 100644
--- a/googletest/samples/sample6_unittest.cc
+++ b/googletest/samples/sample6_unittest.cc
@@ -73,8 +73,6 @@ class PrimeTableTest : public testing::Test {
PrimeTable* const table_;
};
-#if GTEST_HAS_TYPED_TEST
-
using testing::Types;
// Google Test offers two ways for reusing tests for different types.
@@ -134,10 +132,6 @@ TYPED_TEST(PrimeTableTest, CanGetNextPrime) {
// in the type list specified in TYPED_TEST_SUITE. Sit back and be
// happy that you don't have to define them multiple times.
-#endif // GTEST_HAS_TYPED_TEST
-
-#if GTEST_HAS_TYPED_TEST_P
-
using testing::Types;
// Sometimes, however, you don't yet know all the types that you want
@@ -220,5 +214,4 @@ INSTANTIATE_TYPED_TEST_SUITE_P(OnTheFlyAndPreCalculated, // Instance name
PrimeTableTest2, // Test case name
PrimeTableImplementations); // Type list
-#endif // GTEST_HAS_TYPED_TEST_P
} // namespace
diff --git a/googletest/scripts/release_docs.py b/googletest/scripts/release_docs.py
index 1291347f..8d24f28f 100755
--- a/googletest/scripts/release_docs.py
+++ b/googletest/scripts/release_docs.py
@@ -37,7 +37,7 @@ SYNOPSIS
interlinked wiki files. When we release a new version of
Google Test or Google Mock, we need to branch the wiki files
such that users of a specific version of Google Test/Mock can
- look up documenation relevant for that version. This script
+ look up documentation relevant for that version. This script
automates that process by:
- branching the current wiki pages (which document the
diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc
index 5d1031be..d3d5feb7 100644
--- a/googletest/src/gtest-death-test.cc
+++ b/googletest/src/gtest-death-test.cc
@@ -32,6 +32,7 @@
#include "gtest/gtest-death-test.h"
+#include <functional>
#include <utility>
#include "gtest/internal/gtest-port.h"
@@ -247,7 +248,7 @@ static std::string DeathTestThreadWarning(size_t thread_count) {
msg << "detected " << thread_count << " threads.";
}
msg << " See "
- "https://github.com/google/googletest/blob/master/googletest/docs/"
+ "https://github.com/google/googletest/blob/master/docs/"
"advanced.md#death-tests-and-threads"
<< " for more explanation and suggested solutions, especially if"
<< " this is the last message you see before your test times out.";
@@ -864,7 +865,7 @@ class Arguments {
}
int size() {
- return args_.size() - 1;
+ return static_cast<int>(args_.size()) - 1;
}
private:
@@ -890,18 +891,17 @@ int FuchsiaDeathTest::Wait() {
// Register to wait for the child process to terminate.
status_zx = child_process_.wait_async(
- port, kProcessKey, ZX_PROCESS_TERMINATED, ZX_WAIT_ASYNC_ONCE);
+ port, kProcessKey, ZX_PROCESS_TERMINATED, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for the socket to be readable or closed.
status_zx = stderr_socket_.wait_async(
- port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
- ZX_WAIT_ASYNC_ONCE);
+ port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
// Register to wait for an exception.
status_zx = exception_channel_.wait_async(
- port, kExceptionKey, ZX_CHANNEL_READABLE, ZX_WAIT_ASYNC_ONCE);
+ port, kExceptionKey, ZX_CHANNEL_READABLE, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
bool process_terminated = false;
@@ -941,8 +941,7 @@ int FuchsiaDeathTest::Wait() {
} else {
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);
status_zx = stderr_socket_.wait_async(
- port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
- ZX_WAIT_ASYNC_ONCE);
+ port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
}
} else {
@@ -954,13 +953,13 @@ int FuchsiaDeathTest::Wait() {
ReadAndInterpretStatusByte();
- zx_info_process_t buffer;
+ zx_info_process_v2_t buffer;
status_zx = child_process_.get_info(
- ZX_INFO_PROCESS, &buffer, sizeof(buffer), nullptr, nullptr);
+ ZX_INFO_PROCESS_V2, &buffer, sizeof(buffer), nullptr, nullptr);
GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);
- GTEST_DEATH_TEST_CHECK_(buffer.exited);
- set_status(buffer.return_code);
+ GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);
+ set_status(static_cast<int>(buffer.return_code));
return status();
}
@@ -1225,21 +1224,9 @@ struct ExecDeathTestArgs {
int close_fd; // File descriptor to close; the read end of a pipe
};
-# if GTEST_OS_MAC
-inline char** GetEnviron() {
- // When Google Test is built as a framework on MacOS X, the environ variable
- // is unavailable. Apple's documentation (man environ) recommends using
- // _NSGetEnviron() instead.
- return *_NSGetEnviron();
-}
-# else
-// Some POSIX platforms expect you to declare environ. extern "C" makes
-// it reside in the global namespace.
+# if GTEST_OS_QNX
extern "C" char** environ;
-inline char** GetEnviron() { return environ; }
-# endif // GTEST_OS_MAC
-
-# if !GTEST_OS_QNX
+# else // GTEST_OS_QNX
// The main function for a threadsafe-style death test child process.
// This function is called in a clone()-ed process and thus must avoid
// any potentially unsafe operations like malloc or libc functions.
@@ -1259,18 +1246,18 @@ static int ExecDeathTestChildMain(void* child_arg) {
return EXIT_FAILURE;
}
- // We can safely call execve() as it's a direct system call. We
+ // We can safely call execv() as it's almost a direct system call. We
// cannot use execvp() as it's a libc function and thus potentially
- // unsafe. Since execve() doesn't search the PATH, the user must
+ // unsafe. Since execv() doesn't search the PATH, the user must
// invoke the test program via a valid path that contains at least
// one path separator.
- execve(args->argv[0], args->argv, GetEnviron());
- DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
+ execv(args->argv[0], args->argv);
+ DeathTestAbort(std::string("execv(") + args->argv[0] + ", ...) in " +
original_dir + " failed: " +
GetLastErrnoDescription());
return EXIT_FAILURE;
}
-# endif // !GTEST_OS_QNX
+# endif // GTEST_OS_QNX
# if GTEST_HAS_CLONE
// Two utility routines that together determine the direction the stack
@@ -1284,19 +1271,24 @@ static int ExecDeathTestChildMain(void* child_arg) {
// correct answer.
static void StackLowerThanAddress(const void* ptr,
bool* result) GTEST_NO_INLINE_;
+// Make sure sanitizers do not tamper with the stack here.
+// Ideally, we want to use `__builtin_frame_address` instead of a local variable
+// address with sanitizer disabled, but it does not work when the
+// compiler optimizes the stack frame out, which happens on PowerPC targets.
// HWAddressSanitizer add a random tag to the MSB of the local variable address,
// making comparison result unpredictable.
+GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
static void StackLowerThanAddress(const void* ptr, bool* result) {
- int dummy;
- *result = (&dummy < ptr);
+ int dummy = 0;
+ *result = std::less<const void*>()(&dummy, ptr);
}
// Make sure AddressSanitizer does not tamper with the stack here.
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
static bool StackGrowsDown() {
- int dummy;
+ int dummy = 0;
bool result;
StackLowerThanAddress(&dummy, &result);
return result;
@@ -1339,8 +1331,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
fd_flags | FD_CLOEXEC));
struct inheritance inherit = {0};
// spawn is a system call.
- child_pid =
- spawn(args.argv[0], 0, nullptr, &inherit, args.argv, GetEnviron());
+ child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);
// Restores the current working directory.
GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc
index 9aad12fb..9504f0f5 100644
--- a/googletest/src/gtest-filepath.cc
+++ b/googletest/src/gtest-filepath.cc
@@ -92,8 +92,9 @@ static bool IsPathSeparator(char c) {
// Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() {
-#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
- GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32
+#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
+ GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
+ GTEST_OS_XTENSA
// These platforms do not have a current directory, so we just return
// something reasonable.
return FilePath(kCurrentDirectoryString);
@@ -323,7 +324,7 @@ bool FilePath::CreateFolder() const {
delete [] unicode;
#elif GTEST_OS_WINDOWS
int result = _mkdir(pathname_.c_str());
-#elif GTEST_OS_ESP8266
+#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
// do nothing
int result = 0;
#else
@@ -349,33 +350,19 @@ FilePath FilePath::RemoveTrailingPathSeparator() const {
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
void FilePath::Normalize() {
- if (pathname_.c_str() == nullptr) {
- pathname_ = "";
- return;
- }
- const char* src = pathname_.c_str();
- char* const dest = new char[pathname_.length() + 1];
- char* dest_ptr = dest;
- memset(dest_ptr, 0, pathname_.length() + 1);
-
- while (*src != '\0') {
- *dest_ptr = *src;
- if (!IsPathSeparator(*src)) {
- src++;
+ auto out = pathname_.begin();
+
+ for (const char character : pathname_) {
+ if (!IsPathSeparator(character)) {
+ *(out++) = character;
+ } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
+ *(out++) = kPathSeparator;
} else {
-#if GTEST_HAS_ALT_PATH_SEP_
- if (*dest_ptr == kAlternatePathSeparator) {
- *dest_ptr = kPathSeparator;
- }
-#endif
- while (IsPathSeparator(*src))
- src++;
+ continue;
}
- dest_ptr++;
}
- *dest_ptr = '\0';
- pathname_ = dest;
- delete[] dest;
+
+ pathname_.erase(out, pathname_.end());
}
} // namespace internal
diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h
index d0ebe0c5..6d8cecbb 100644
--- a/googletest/src/gtest-internal-inl.h
+++ b/googletest/src/gtest-internal-inl.h
@@ -31,8 +31,8 @@
// This file contains purely Google Test's internal implementation. Please
// DO NOT #INCLUDE IT IN A USER PROGRAM.
-#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
-#define GTEST_SRC_GTEST_INTERNAL_INL_H_
+#ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
+#define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
#ifndef _WIN32_WCE
# include <errno.h>
@@ -84,9 +84,11 @@ const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
const char kBreakOnFailureFlag[] = "break_on_failure";
const char kCatchExceptionsFlag[] = "catch_exceptions";
const char kColorFlag[] = "color";
+const char kFailFast[] = "fail_fast";
const char kFilterFlag[] = "filter";
const char kListTestsFlag[] = "list_tests";
const char kOutputFlag[] = "output";
+const char kBriefFlag[] = "brief";
const char kPrintTimeFlag[] = "print_time";
const char kPrintUTF8Flag[] = "print_utf8";
const char kRandomSeedFlag[] = "random_seed";
@@ -164,10 +166,12 @@ class GTestFlagSaver {
color_ = GTEST_FLAG(color);
death_test_style_ = GTEST_FLAG(death_test_style);
death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
+ fail_fast_ = GTEST_FLAG(fail_fast);
filter_ = GTEST_FLAG(filter);
internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
list_tests_ = GTEST_FLAG(list_tests);
output_ = GTEST_FLAG(output);
+ brief_ = GTEST_FLAG(brief);
print_time_ = GTEST_FLAG(print_time);
print_utf8_ = GTEST_FLAG(print_utf8);
random_seed_ = GTEST_FLAG(random_seed);
@@ -187,9 +191,11 @@ class GTestFlagSaver {
GTEST_FLAG(death_test_style) = death_test_style_;
GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
GTEST_FLAG(filter) = filter_;
+ GTEST_FLAG(fail_fast) = fail_fast_;
GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
GTEST_FLAG(list_tests) = list_tests_;
GTEST_FLAG(output) = output_;
+ GTEST_FLAG(brief) = brief_;
GTEST_FLAG(print_time) = print_time_;
GTEST_FLAG(print_utf8) = print_utf8_;
GTEST_FLAG(random_seed) = random_seed_;
@@ -208,10 +214,12 @@ class GTestFlagSaver {
std::string color_;
std::string death_test_style_;
bool death_test_use_fork_;
+ bool fail_fast_;
std::string filter_;
std::string internal_run_death_test_;
bool list_tests_;
std::string output_;
+ bool brief_;
bool print_time_;
bool print_utf8_;
int32_t random_seed_;
@@ -386,13 +394,6 @@ class GTEST_API_ UnitTestOptions {
// Functions for processing the gtest_filter flag.
- // Returns true if and only if the wildcard pattern matches the string.
- // The first ':' or '\0' character in pattern marks the end of it.
- //
- // This recursive algorithm isn't very efficient, but is clear and
- // works well enough for matching test names, which are short.
- static bool PatternMatchesString(const char *pattern, const char *str);
-
// Returns true if and only if the user-specified filter matches the test
// suite name and the test name.
static bool FilterMatchesTest(const std::string& test_suite_name,
@@ -647,10 +648,10 @@ class GTEST_API_ UnitTestImpl {
// Arguments:
//
// test_suite_name: name of the test suite
- // type_param: the name of the test's type parameter, or NULL if
- // this is not a typed or a type-parameterized test.
- // set_up_tc: pointer to the function that sets up the test suite
- // tear_down_tc: pointer to the function that tears down the test suite
+ // type_param: the name of the test's type parameter, or NULL if
+ // this is not a typed or a type-parameterized test.
+ // set_up_tc: pointer to the function that sets up the test suite
+ // tear_down_tc: pointer to the function that tears down the test suite
TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc);
@@ -674,6 +675,7 @@ class GTEST_API_ UnitTestImpl {
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc,
TestInfo* test_info) {
+#if GTEST_HAS_DEATH_TEST
// In order to support thread-safe death tests, we need to
// remember the original working directory when the test program
// was first invoked. We cannot do this in RUN_ALL_TESTS(), as
@@ -686,6 +688,7 @@ class GTEST_API_ UnitTestImpl {
GTEST_CHECK_(!original_working_dir_.IsEmpty())
<< "Failed to get the current working directory.";
}
+#endif // GTEST_HAS_DEATH_TEST
GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
set_up_tc, tear_down_tc)
@@ -698,6 +701,10 @@ class GTEST_API_ UnitTestImpl {
return parameterized_test_registry_;
}
+ std::set<std::string>* ignored_parameterized_test_suites() {
+ return &ignored_parameterized_test_suites_;
+ }
+
// Returns TypeParameterizedTestSuiteRegistry object used to keep track of
// type-parameterized tests and instantiations of them.
internal::TypeParameterizedTestSuiteRegistry&
@@ -884,6 +891,10 @@ class GTEST_API_ UnitTestImpl {
internal::TypeParameterizedTestSuiteRegistry
type_parameterized_test_registry_;
+ // The set holding the name of parameterized
+ // test suites that may go uninstantiated.
+ std::set<std::string> ignored_parameterized_test_suites_;
+
// Indicates whether RegisterParameterizedTests() has been called already.
bool parameterized_tests_registered_;
@@ -1153,13 +1164,13 @@ class StreamingListener : public EmptyTestEventListener {
}
// Note that "event=TestCaseStart" is a wire format and has to remain
- // "case" for compatibilty
+ // "case" for compatibility
void OnTestCaseStart(const TestCase& test_case) override {
SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
}
// Note that "event=TestCaseEnd" is a wire format and has to remain
- // "case" for compatibilty
+ // "case" for compatibility
void OnTestCaseEnd(const TestCase& test_case) override {
SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
"&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
@@ -1207,4 +1218,4 @@ class StreamingListener : public EmptyTestEventListener {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
-#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
+#endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
diff --git a/googletest/src/gtest-matchers.cc b/googletest/src/gtest-matchers.cc
index 7d2fb685..65104eba 100644
--- a/googletest/src/gtest-matchers.cc
+++ b/googletest/src/gtest-matchers.cc
@@ -58,40 +58,40 @@ Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
// s.
Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
-#if GTEST_HAS_ABSL
-// Constructs a matcher that matches a const absl::string_view& whose value is
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+// Constructs a matcher that matches a const StringView& whose value is
// equal to s.
-Matcher<const absl::string_view&>::Matcher(const std::string& s) {
+Matcher<const internal::StringView&>::Matcher(const std::string& s) {
*this = Eq(s);
}
-// Constructs a matcher that matches a const absl::string_view& whose value is
+// Constructs a matcher that matches a const StringView& whose value is
// equal to s.
-Matcher<const absl::string_view&>::Matcher(const char* s) {
+Matcher<const internal::StringView&>::Matcher(const char* s) {
*this = Eq(std::string(s));
}
-// Constructs a matcher that matches a const absl::string_view& whose value is
+// Constructs a matcher that matches a const StringView& whose value is
// equal to s.
-Matcher<const absl::string_view&>::Matcher(absl::string_view s) {
+Matcher<const internal::StringView&>::Matcher(internal::StringView s) {
*this = Eq(std::string(s));
}
-// Constructs a matcher that matches a absl::string_view whose value is equal to
+// Constructs a matcher that matches a StringView whose value is equal to
// s.
-Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); }
+Matcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); }
-// Constructs a matcher that matches a absl::string_view whose value is equal to
+// Constructs a matcher that matches a StringView whose value is equal to
// s.
-Matcher<absl::string_view>::Matcher(const char* s) {
+Matcher<internal::StringView>::Matcher(const char* s) {
*this = Eq(std::string(s));
}
-// Constructs a matcher that matches a absl::string_view whose value is equal to
+// Constructs a matcher that matches a StringView whose value is equal to
// s.
-Matcher<absl::string_view>::Matcher(absl::string_view s) {
+Matcher<internal::StringView>::Matcher(internal::StringView s) {
*this = Eq(std::string(s));
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
} // namespace testing
diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc
index 7b591a13..78f7587b 100644
--- a/googletest/src/gtest-port.cc
+++ b/googletest/src/gtest-port.cc
@@ -80,6 +80,10 @@
# include <zircon/syscalls.h>
#endif // GTEST_OS_FUCHSIA
+#if GTEST_OS_IOS
+#import <Foundation/Foundation.h>
+#endif // GTEST_OS_IOS
+
#include "gtest/gtest-spi.h"
#include "gtest/gtest-message.h"
#include "gtest/internal/gtest-internal.h"
@@ -198,7 +202,8 @@ size_t GetThreadCount() {
if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {
return 0;
}
- mib[5] = size / mib[4];
+
+ mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));
// populate array of structs
struct kinfo_proc info[mib[5]];
@@ -207,8 +212,8 @@ size_t GetThreadCount() {
}
// exclude empty members
- int nthreads = 0;
- for (int i = 0; i < size / mib[4]; i++) {
+ size_t nthreads = 0;
+ for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {
if (info[i].p_tid != -1)
nthreads++;
}
@@ -1110,9 +1115,15 @@ class CapturedStream {
// guaranteed to be mounted, or may have a delay in mounting.
::std::string name_template_buf = TempDir() + "gtest_captured_stream.XXXXXX";
char* name_template = &name_template_buf[0];
+# elif GTEST_OS_IOS
+ NSString* temp_path = [NSTemporaryDirectory()
+ stringByAppendingPathComponent:@"gtest_captured_stream.XXXXXX"];
+
+ char name_template[PATH_MAX + 1];
+ strncpy(name_template, [temp_path UTF8String], PATH_MAX);
# else
char name_template[] = "/tmp/captured_stream.XXXXXX";
-# endif // GTEST_OS_LINUX_ANDROID
+# endif
const int captured_fd = mkstemp(name_template);
if (captured_fd == -1) {
GTEST_LOG_(WARNING)
diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc
index 3337be31..1b68fcb5 100644
--- a/googletest/src/gtest-printers.cc
+++ b/googletest/src/gtest-printers.cc
@@ -42,11 +42,16 @@
// defines Foo.
#include "gtest/gtest-printers.h"
+
#include <stdio.h>
+
#include <cctype>
+#include <cstdint>
#include <cwchar>
#include <ostream> // NOLINT
#include <string>
+#include <type_traits>
+
#include "gtest/internal/gtest-port.h"
#include "src/gtest-internal-inl.h"
@@ -102,9 +107,19 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
*os << ">";
}
+// Helpers for widening a character to char32_t. Since the standard does not
+// specify if char / wchar_t is signed or unsigned, it is important to first
+// convert it to the unsigned type of the same width before widening it to
+// char32_t.
+template <typename CharType>
+char32_t ToChar32(CharType in) {
+ return static_cast<char32_t>(
+ static_cast<typename std::make_unsigned<CharType>::type>(in));
+}
+
} // namespace
-namespace internal2 {
+namespace internal {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
@@ -116,10 +131,6 @@ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
-} // namespace internal2
-
-namespace internal {
-
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
@@ -134,18 +145,15 @@ enum CharFormat {
// Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
-inline bool IsPrintableAscii(wchar_t c) {
- return 0x20 <= c && c <= 0x7E;
-}
+inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
-// Prints a wide or narrow char c as a character literal without the
-// quotes, escaping it when necessary; returns how c was formatted.
-// The template argument UnsignedChar is the unsigned version of Char,
-// which is the type of c.
-template <typename UnsignedChar, typename Char>
+// Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
+// character literal without the quotes, escaping it when necessary; returns how
+// c was formatted.
+template <typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
- wchar_t w_c = static_cast<wchar_t>(c);
- switch (w_c) {
+ const char32_t u_c = ToChar32(c);
+ switch (u_c) {
case L'\0':
*os << "\\0";
break;
@@ -177,13 +185,12 @@ static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
*os << "\\v";
break;
default:
- if (IsPrintableAscii(w_c)) {
+ if (IsPrintableAscii(u_c)) {
*os << static_cast<char>(c);
return kAsIs;
} else {
ostream::fmtflags flags = os->flags();
- *os << "\\x" << std::hex << std::uppercase
- << static_cast<int>(static_cast<UnsignedChar>(c));
+ *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
os->flags(flags);
return kHexEscape;
}
@@ -191,9 +198,9 @@ static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
return kSpecialEscape;
}
-// Prints a wchar_t c as if it's part of a string literal, escaping it when
+// Prints a char32_t c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
-static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
+static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
switch (c) {
case L'\'':
*os << "'";
@@ -202,26 +209,68 @@ static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
*os << "\\\"";
return kSpecialEscape;
default:
- return PrintAsCharLiteralTo<wchar_t>(c, os);
+ return PrintAsCharLiteralTo(c, os);
}
}
+static const char* GetCharWidthPrefix(char) {
+ return "";
+}
+
+static const char* GetCharWidthPrefix(signed char) {
+ return "";
+}
+
+static const char* GetCharWidthPrefix(unsigned char) {
+ return "";
+}
+
+#ifdef __cpp_char8_t
+static const char* GetCharWidthPrefix(char8_t) {
+ return "u8";
+}
+#endif
+
+static const char* GetCharWidthPrefix(char16_t) {
+ return "u";
+}
+
+static const char* GetCharWidthPrefix(char32_t) {
+ return "U";
+}
+
+static const char* GetCharWidthPrefix(wchar_t) {
+ return "L";
+}
+
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
- return PrintAsStringLiteralTo(
- static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
+ return PrintAsStringLiteralTo(ToChar32(c), os);
+}
+
+#ifdef __cpp_char8_t
+static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
+ return PrintAsStringLiteralTo(ToChar32(c), os);
+}
+#endif
+
+static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
+ return PrintAsStringLiteralTo(ToChar32(c), os);
}
-// Prints a wide or narrow character c and its code. '\0' is printed
-// as "'\\0'", other unprintable characters are also properly escaped
-// using the standard C++ escape sequence. The template argument
-// UnsignedChar is the unsigned version of Char, which is the type of c.
-template <typename UnsignedChar, typename Char>
+static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
+ return PrintAsStringLiteralTo(ToChar32(c), os);
+}
+
+// Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
+// and its code. '\0' is printed as "'\\0'", other unprintable characters are
+// also properly escaped using the standard C++ escape sequence.
+template <typename Char>
void PrintCharAndCodeTo(Char c, ostream* os) {
// First, print c as a literal in the most readable form we can find.
- *os << ((sizeof(c) > 1) ? "L'" : "'");
- const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
+ *os << GetCharWidthPrefix(c) << "'";
+ const CharFormat format = PrintAsCharLiteralTo(c, os);
*os << "'";
// To aid user debugging, we also print c's code in decimal, unless
@@ -242,21 +291,21 @@ void PrintCharAndCodeTo(Char c, ostream* os) {
*os << ")";
}
-void PrintTo(unsigned char c, ::std::ostream* os) {
- PrintCharAndCodeTo<unsigned char>(c, os);
-}
-void PrintTo(signed char c, ::std::ostream* os) {
- PrintCharAndCodeTo<unsigned char>(c, os);
-}
+void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
+void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
-void PrintTo(wchar_t wc, ostream* os) {
- PrintCharAndCodeTo<wchar_t>(wc, os);
+void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }
+
+// TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
+void PrintTo(char32_t c, ::std::ostream* os) {
+ *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
+ << static_cast<uint32_t>(c);
}
// Prints the given array of characters to the ostream. CharType must be either
-// char or wchar_t.
+// char, char8_t, char16_t, char32_t, or wchar_t.
// The array starts at begin, the length is len, it may include '\0' characters
// and may not be NUL-terminated.
template <typename CharType>
@@ -266,8 +315,8 @@ GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
static CharFormat PrintCharsAsStringTo(
const CharType* begin, size_t len, ostream* os) {
- const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
- *os << kQuoteBegin;
+ const char* const quote_prefix = GetCharWidthPrefix(*begin);
+ *os << quote_prefix << "\"";
bool is_previous_hex = false;
CharFormat print_format = kAsIs;
for (size_t index = 0; index < len; ++index) {
@@ -276,7 +325,7 @@ static CharFormat PrintCharsAsStringTo(
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
- *os << "\" " << kQuoteBegin;
+ *os << "\" " << quote_prefix << "\"";
}
is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
// Remember if any characters required hex escaping.
@@ -322,22 +371,57 @@ void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os);
}
+#ifdef __cpp_char8_t
+// Prints a (const) char8_t array of 'len' elements, starting at address
+// 'begin'.
+void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
+ UniversalPrintCharArray(begin, len, os);
+}
+#endif
+
+// Prints a (const) char16_t array of 'len' elements, starting at address
+// 'begin'.
+void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
+ UniversalPrintCharArray(begin, len, os);
+}
+
+// Prints a (const) char32_t array of 'len' elements, starting at address
+// 'begin'.
+void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
+ UniversalPrintCharArray(begin, len, os);
+}
+
// Prints a (const) wchar_t array of 'len' elements, starting at address
// 'begin'.
void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os);
}
-// Prints the given C string to the ostream.
-void PrintTo(const char* s, ostream* os) {
+namespace {
+
+// Prints a null-terminated C-style string to the ostream.
+template <typename Char>
+void PrintCStringTo(const Char* s, ostream* os) {
if (s == nullptr) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
- PrintCharsAsStringTo(s, strlen(s), os);
+ PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
}
}
+} // anonymous namespace
+
+void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
+
+#ifdef __cpp_char8_t
+void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
+#endif
+
+void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }
+
+void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }
+
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
@@ -346,14 +430,7 @@ void PrintTo(const char* s, ostream* os) {
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Prints the given wide C string to the ostream.
-void PrintTo(const wchar_t* s, ostream* os) {
- if (s == nullptr) {
- *os << "NULL";
- } else {
- *os << ImplicitCast_<const void*>(s) << " pointing to ";
- PrintCharsAsStringTo(s, wcslen(s), os);
- }
-}
+void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
#endif // wchar_t is native
namespace {
@@ -431,6 +508,20 @@ void PrintStringTo(const ::std::string& s, ostream* os) {
}
}
+#ifdef __cpp_char8_t
+void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
+ PrintCharsAsStringTo(s.data(), s.size(), os);
+}
+#endif
+
+void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
+ PrintCharsAsStringTo(s.data(), s.size(), os);
+}
+
+void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
+ PrintCharsAsStringTo(s.data(), s.size(), os);
+}
+
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc
index 1b1cfb0d..c02c3df6 100644
--- a/googletest/src/gtest-typed-test.cc
+++ b/googletest/src/gtest-typed-test.cc
@@ -35,8 +35,6 @@
namespace testing {
namespace internal {
-#if GTEST_HAS_TYPED_TEST_P
-
// Skips to the first non-space char in str. Returns an empty string if str
// contains only whitespace characters.
static const char* SkipSpaces(const char* str) {
@@ -78,17 +76,7 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames(
continue;
}
- bool found = false;
- for (RegisteredTestIter it = registered_tests_.begin();
- it != registered_tests_.end();
- ++it) {
- if (name == it->first) {
- found = true;
- break;
- }
- }
-
- if (found) {
+ if (registered_tests_.count(name) != 0) {
tests.insert(name);
} else {
errors << "No test named " << name
@@ -115,7 +103,5 @@ const char* TypedTestSuitePState::VerifyRegisteredTestNames(
return registered_tests;
}
-#endif // GTEST_HAS_TYPED_TEST_P
-
} // namespace internal
} // namespace testing
diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc
index 07015cba..21c611af 100644
--- a/googletest/src/gtest.cc
+++ b/googletest/src/gtest.cc
@@ -35,7 +35,6 @@
#include "gtest/gtest-spi.h"
#include <ctype.h>
-#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@@ -44,6 +43,8 @@
#include <wctype.h>
#include <algorithm>
+#include <chrono> // NOLINT
+#include <cmath>
#include <cstdint>
#include <iomanip>
#include <limits>
@@ -55,8 +56,6 @@
#if GTEST_OS_LINUX
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-
# include <fcntl.h> // NOLINT
# include <limits.h> // NOLINT
# include <sched.h> // NOLINT
@@ -68,7 +67,6 @@
# include <string>
#elif GTEST_OS_ZOS
-# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <sys/time.h> // NOLINT
// On z/OS we additionally need strings.h for strcasecmp.
@@ -86,7 +84,6 @@
#ifdef _MSC_VER
# include <crtdbg.h> // NOLINT
-# include <debugapi.h> // NOLINT
#endif
# include <io.h> // NOLINT
@@ -95,16 +92,11 @@
# include <sys/stat.h> // NOLINT
# if GTEST_OS_WINDOWS_MINGW
-// MinGW has gettimeofday() but not _ftime64().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <sys/time.h> // NOLINT
# endif // GTEST_OS_WINDOWS_MINGW
#else
-// Assume other platforms have gettimeofday().
-# define GTEST_HAS_GETTIMEOFDAY_ 1
-
// cpplint thinks that the header is already included, so we want to
// silence it.
# include <sys/time.h> // NOLINT
@@ -213,6 +205,21 @@ static const char* GetDefaultFilter() {
return kUniversalFilter;
}
+// Bazel passes in the argument to '--test_runner_fail_fast' via the
+// TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
+static bool GetDefaultFailFast() {
+ const char* const testbridge_test_runner_fail_fast =
+ internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
+ if (testbridge_test_runner_fail_fast != nullptr) {
+ return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
+ }
+ return false;
+}
+
+GTEST_DEFINE_bool_(
+ fail_fast, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()),
+ "True if and only if a test failure should stop further test execution.");
+
GTEST_DEFINE_bool_(
also_run_disabled_tests,
internal::BoolFromGTestEnv("also_run_disabled_tests", false),
@@ -273,6 +280,10 @@ GTEST_DEFINE_string_(
"executable's name and, if necessary, made unique by adding "
"digits.");
+GTEST_DEFINE_bool_(
+ brief, internal::BoolFromGTestEnv("brief", false),
+ "True if only test failures should be displayed in text output.");
+
GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
"True if and only if " GTEST_NAME_
" should display elapsed time in text output.");
@@ -414,8 +425,8 @@ namespace {
// inserted to report ether an error or a log message.
//
// This configuration bit will likely be removed at some point.
-constexpr bool kErrorOnUninstantiatedParameterizedTest = false;
-constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = false;
+constexpr bool kErrorOnUninstantiatedParameterizedTest = true;
+constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;
// A test that fails at a given file/line location with a given message.
class FailureTest : public Test {
@@ -444,11 +455,23 @@ class FailureTest : public Test {
} // namespace
+std::set<std::string>* GetIgnoredParameterizedTestSuites() {
+ return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
+}
+
+// Add a given test_suit to the list of them allow to go un-instantiated.
+MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
+ GetIgnoredParameterizedTestSuites()->insert(test_suite);
+}
+
// If this parameterized test suite has no instantiations (and that
// has not been marked as okay), emit a test case reporting that.
-void InsertSyntheticTestCase(const std::string &name, CodeLocation location) {
- std::string message =
- "Paramaterized test suite " + name +
+void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
+ bool has_test_p) {
+ const auto& ignored = *GetIgnoredParameterizedTestSuites();
+ if (ignored.find(name) != ignored.end()) return;
+
+ const char kMissingInstantiation[] = //
" is defined via TEST_P, but never instantiated. None of the test cases "
"will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
"ones provided expand to nothing."
@@ -457,7 +480,25 @@ void InsertSyntheticTestCase(const std::string &name, CodeLocation location) {
"binaries that intend to use them. (As opposed to, for example, being "
"placed in a library that may be linked in to get other utilities.)";
- std::string full_name = "UninstantiatedParamaterizedTestSuite<" + name + ">";
+ const char kMissingTestCase[] = //
+ " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
+ "defined via TEST_P . No test cases will run."
+ "\n\n"
+ "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
+ "code that always depend on code that provides TEST_P. Failing to do "
+ "so is often an indication of dead code, e.g. the last TEST_P was "
+ "removed but the rest got left behind.";
+
+ std::string message =
+ "Parameterized test suite " + name +
+ (has_test_p ? kMissingInstantiation : kMissingTestCase) +
+ "\n\n"
+ "To suppress this error for this test suite, insert the following line "
+ "(in a non-header) in the namespace it is defined in:"
+ "\n\n"
+ "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");";
+
+ std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">";
RegisterTest( //
"GoogleTestVerification", full_name.c_str(),
nullptr, // No type parameter.
@@ -498,21 +539,29 @@ void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
}
void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
+ const auto& ignored = *GetIgnoredParameterizedTestSuites();
for (const auto& testcase : suites_) {
if (testcase.second.instantiated) continue;
+ if (ignored.find(testcase.first) != ignored.end()) continue;
std::string message =
- "Type paramaterized test suite " + testcase.first +
+ "Type parameterized test suite " + testcase.first +
" is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
"via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
"\n\n"
"Ideally, TYPED_TEST_P definitions should only ever be included as "
"part of binaries that intend to use them. (As opposed to, for "
"example, being placed in a library that may be linked in to get other "
- "utilities.)";
+ "utilities.)"
+ "\n\n"
+ "To suppress this error for this test suite, insert the following line "
+ "(in a non-header) in the namespace it is defined in:"
+ "\n\n"
+ "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
+ testcase.first + ");";
std::string full_name =
- "UninstantiatedTypeParamaterizedTestSuite<" + testcase.first + ">";
+ "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">";
RegisterTest( //
"GoogleTestVerification", full_name.c_str(),
nullptr, // No type parameter.
@@ -597,47 +646,82 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
return result.string();
}
-// Returns true if and only if the wildcard pattern matches the string.
-// The first ':' or '\0' character in pattern marks the end of it.
+// Returns true if and only if the wildcard pattern matches the string. Each
+// pattern consists of regular characters, single-character wildcards (?), and
+// multi-character wildcards (*).
//
-// This recursive algorithm isn't very efficient, but is clear and
-// works well enough for matching test names, which are short.
-bool UnitTestOptions::PatternMatchesString(const char *pattern,
- const char *str) {
- switch (*pattern) {
- case '\0':
- case ':': // Either ':' or '\0' marks the end of the pattern.
- return *str == '\0';
- case '?': // Matches any single character.
- return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
- case '*': // Matches any string (possibly empty) of characters.
- return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
- PatternMatchesString(pattern + 1, str);
- default: // Non-special character. Matches itself.
- return *pattern == *str &&
- PatternMatchesString(pattern + 1, str + 1);
- }
-}
-
-bool UnitTestOptions::MatchesFilter(
- const std::string& name, const char* filter) {
- const char *cur_pattern = filter;
- for (;;) {
- if (PatternMatchesString(cur_pattern, name.c_str())) {
- return true;
+// This function implements a linear-time string globbing algorithm based on
+// https://research.swtch.com/glob.
+static bool PatternMatchesString(const std::string& name_str,
+ const char* pattern, const char* pattern_end) {
+ const char* name = name_str.c_str();
+ const char* const name_begin = name;
+ const char* const name_end = name + name_str.size();
+
+ const char* pattern_next = pattern;
+ const char* name_next = name;
+
+ while (pattern < pattern_end || name < name_end) {
+ if (pattern < pattern_end) {
+ switch (*pattern) {
+ default: // Match an ordinary character.
+ if (name < name_end && *name == *pattern) {
+ ++pattern;
+ ++name;
+ continue;
+ }
+ break;
+ case '?': // Match any single character.
+ if (name < name_end) {
+ ++pattern;
+ ++name;
+ continue;
+ }
+ break;
+ case '*':
+ // Match zero or more characters. Start by skipping over the wildcard
+ // and matching zero characters from name. If that fails, restart and
+ // match one more character than the last attempt.
+ pattern_next = pattern;
+ name_next = name + 1;
+ ++pattern;
+ continue;
+ }
+ }
+ // Failed to match a character. Restart if possible.
+ if (name_begin < name_next && name_next <= name_end) {
+ pattern = pattern_next;
+ name = name_next;
+ continue;
}
+ return false;
+ }
+ return true;
+}
- // Finds the next pattern in the filter.
- cur_pattern = strchr(cur_pattern, ':');
+bool UnitTestOptions::MatchesFilter(const std::string& name_str,
+ const char* filter) {
+ // The filter is a list of patterns separated by colons (:).
+ const char* pattern = filter;
+ while (true) {
+ // Find the bounds of this pattern.
+ const char* const next_sep = strchr(pattern, ':');
+ const char* const pattern_end =
+ next_sep != nullptr ? next_sep : pattern + strlen(pattern);
- // Returns if no more pattern can be found.
- if (cur_pattern == nullptr) {
- return false;
+ // Check if this pattern matches name_str.
+ if (PatternMatchesString(name_str, pattern, pattern_end)) {
+ return true;
}
- // Skips the pattern separater (the ':' character).
- cur_pattern++;
+ // Give up on this pattern. However, if we found a pattern separator (:),
+ // advance to the next pattern (skipping over the separator) and restart.
+ if (next_sep == nullptr) {
+ return false;
+ }
+ pattern = next_sep + 1;
}
+ return true;
}
// Returns true if and only if the user-specified filter matches the test
@@ -947,44 +1031,30 @@ std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
); // NOLINT
}
-// Returns the current time in milliseconds.
+// A helper class for measuring elapsed times.
+class Timer {
+ public:
+ Timer() : start_(std::chrono::steady_clock::now()) {}
+
+ // Return time elapsed in milliseconds since the timer was created.
+ TimeInMillis Elapsed() {
+ return std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::steady_clock::now() - start_)
+ .count();
+ }
+
+ private:
+ std::chrono::steady_clock::time_point start_;
+};
+
+// Returns a timestamp as milliseconds since the epoch. Note this time may jump
+// around subject to adjustments by the system, to measure elapsed time use
+// Timer instead.
TimeInMillis GetTimeInMillis() {
-#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
- // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
- // http://analogous.blogspot.com/2005/04/epoch.html
- const TimeInMillis kJavaEpochToWinFileTimeDelta =
- static_cast<TimeInMillis>(116444736UL) * 100000UL;
- const DWORD kTenthMicrosInMilliSecond = 10000;
-
- SYSTEMTIME now_systime;
- FILETIME now_filetime;
- ULARGE_INTEGER now_int64;
- GetSystemTime(&now_systime);
- if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
- now_int64.LowPart = now_filetime.dwLowDateTime;
- now_int64.HighPart = now_filetime.dwHighDateTime;
- now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
- kJavaEpochToWinFileTimeDelta;
- return now_int64.QuadPart;
- }
- return 0;
-#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
- __timeb64 now;
-
- // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
- // (deprecated function) there.
- GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
- _ftime64(&now);
- GTEST_DISABLE_MSC_DEPRECATED_POP_()
-
- return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
-#elif GTEST_HAS_GETTIMEOFDAY_
- struct timeval now;
- gettimeofday(&now, nullptr);
- return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
-#else
-# error "Don't know how to get the current time on your system."
-#endif
+ return std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::system_clock::now() -
+ std::chrono::system_clock::from_time_t(0))
+ .count();
}
// Utilities
@@ -1499,6 +1569,31 @@ AssertionResult DoubleNearPredFormat(const char* expr1,
const double diff = fabs(val1 - val2);
if (diff <= abs_error) return AssertionSuccess();
+ // Find the value which is closest to zero.
+ const double min_abs = std::min(fabs(val1), fabs(val2));
+ // Find the distance to the next double from that value.
+ const double epsilon =
+ nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;
+ // Detect the case where abs_error is so small that EXPECT_NEAR is
+ // effectively the same as EXPECT_EQUAL, and give an informative error
+ // message so that the situation can be more easily understood without
+ // requiring exotic floating-point knowledge.
+ // Don't do an epsilon check if abs_error is zero because that implies
+ // that an equality check was actually intended.
+ if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&
+ abs_error < epsilon) {
+ return AssertionFailure()
+ << "The difference between " << expr1 << " and " << expr2 << " is "
+ << diff << ", where\n"
+ << expr1 << " evaluates to " << val1 << ",\n"
+ << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter "
+ << abs_error_expr << " evaluates to " << abs_error
+ << " which is smaller than the minimum distance between doubles for "
+ "numbers of this magnitude which is "
+ << epsilon
+ << ", thus making this EXPECT_NEAR check equivalent to "
+ "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.";
+ }
return AssertionFailure()
<< "The difference between " << expr1 << " and " << expr2
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
@@ -1561,57 +1656,6 @@ AssertionResult DoubleLE(const char* expr1, const char* expr2,
namespace internal {
-// The helper function for {ASSERT|EXPECT}_EQ with int or enum
-// arguments.
-AssertionResult CmpHelperEQ(const char* lhs_expression,
- const char* rhs_expression,
- BiggestInt lhs,
- BiggestInt rhs) {
- if (lhs == rhs) {
- return AssertionSuccess();
- }
-
- return EqFailure(lhs_expression,
- rhs_expression,
- FormatForComparisonFailureMessage(lhs, rhs),
- FormatForComparisonFailureMessage(rhs, lhs),
- false);
-}
-
-// A macro for implementing the helper functions needed to implement
-// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
-// just to avoid copy-and-paste of similar code.
-#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
-AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
- BiggestInt val1, BiggestInt val2) {\
- if (val1 op val2) {\
- return AssertionSuccess();\
- } else {\
- return AssertionFailure() \
- << "Expected: (" << expr1 << ") " #op " (" << expr2\
- << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
- << " vs " << FormatForComparisonFailureMessage(val2, val1);\
- }\
-}
-
-// Implements the helper function for {ASSERT|EXPECT}_NE with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(NE, !=)
-// Implements the helper function for {ASSERT|EXPECT}_LE with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(LE, <=)
-// Implements the helper function for {ASSERT|EXPECT}_LT with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(LT, < )
-// Implements the helper function for {ASSERT|EXPECT}_GE with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(GE, >=)
-// Implements the helper function for {ASSERT|EXPECT}_GT with int or
-// enum arguments.
-GTEST_IMPL_CMP_HELPER_(GT, > )
-
-#undef GTEST_IMPL_CMP_HELPER_
-
// The helper function for {ASSERT|EXPECT}_STREQ.
AssertionResult CmpHelperSTREQ(const char* lhs_expression,
const char* rhs_expression,
@@ -2085,8 +2129,13 @@ bool String::EndsWithCaseInsensitive(
// Formats an int value as "%02d".
std::string String::FormatIntWidth2(int value) {
+ return FormatIntWidthN(value, 2);
+}
+
+// Formats an int value to given width with leading zeros.
+std::string String::FormatIntWidthN(int value, int width) {
std::stringstream ss;
- ss << std::setfill('0') << std::setw(2) << value;
+ ss << std::setfill('0') << std::setw(width) << value;
return ss.str();
}
@@ -2138,7 +2187,9 @@ std::string AppendUserMessage(const std::string& gtest_msg,
if (user_msg_string.empty()) {
return gtest_msg;
}
-
+ if (gtest_msg.empty()) {
+ return user_msg_string;
+ }
return gtest_msg + "\n" + user_msg_string;
}
@@ -2190,7 +2241,7 @@ void TestResult::RecordProperty(const std::string& xml_element,
if (!ValidateTestProperty(xml_element, test_property)) {
return;
}
- internal::MutexLock lock(&test_properites_mutex_);
+ internal::MutexLock lock(&test_properties_mutex_);
const std::vector<TestProperty>::iterator property_with_matching_key =
std::find_if(test_properties_.begin(), test_properties_.end(),
internal::TestPropertyKeyIs(test_property.key()));
@@ -2217,7 +2268,8 @@ static const char* const kReservedTestSuitesAttributes[] = {
// The list of reserved attributes used in the <testsuite> element of XML
// output.
static const char* const kReservedTestSuiteAttributes[] = {
- "disabled", "errors", "failures", "name", "tests", "time", "timestamp"};
+ "disabled", "errors", "failures", "name",
+ "tests", "time", "timestamp", "skipped"};
// The list of reserved attributes used in the <testcase> element of XML output.
static const char* const kReservedTestCaseAttributes[] = {
@@ -2230,7 +2282,7 @@ static const char* const kReservedOutputTestCaseAttributes[] = {
"classname", "name", "status", "time", "type_param",
"value_param", "file", "line", "result", "timestamp"};
-template <int kSize>
+template <size_t kSize>
std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
return std::vector<std::string>(array, array + kSize);
}
@@ -2674,6 +2726,7 @@ TestInfo::TestInfo(const std::string& a_test_suite_name,
should_run_(false),
is_disabled_(false),
matches_filter_(false),
+ is_in_another_shard_(false),
factory_(factory),
result_() {}
@@ -2687,7 +2740,7 @@ namespace internal {
//
// Arguments:
//
-// test_suite_name: name of the test suite
+// test_suite_name: name of the test suite
// name: name of the test
// type_param: the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test.
@@ -2789,7 +2842,8 @@ void TestInfo::Run() {
// Notifies the unit test event listeners that a test is about to start.
repeater->OnTestStart(*this);
- const TimeInMillis start = internal::GetTimeInMillis();
+ result_.set_start_timestamp(internal::GetTimeInMillis());
+ internal::Timer timer;
impl->os_stack_trace_getter()->UponLeavingGTest();
@@ -2814,8 +2868,7 @@ void TestInfo::Run() {
test, &Test::DeleteSelf_, "the test fixture's destructor");
}
- result_.set_start_timestamp(start);
- result_.set_elapsed_time(internal::GetTimeInMillis() - start);
+ result_.set_elapsed_time(timer.Elapsed());
// Notifies the unit test event listener that a test has just finished.
repeater->OnTestEnd(*this);
@@ -2825,6 +2878,28 @@ void TestInfo::Run() {
impl->set_current_test_info(nullptr);
}
+// Skip and records a skipped test result for this object.
+void TestInfo::Skip() {
+ if (!should_run_) return;
+
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
+ impl->set_current_test_info(this);
+
+ TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
+
+ // Notifies the unit test event listeners that a test is about to start.
+ repeater->OnTestStart(*this);
+
+ const TestPartResult test_part_result =
+ TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
+ impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
+ test_part_result);
+
+ // Notifies the unit test event listener that a test has just finished.
+ repeater->OnTestEnd(*this);
+ impl->set_current_test_info(nullptr);
+}
+
// class TestSuite
// Gets the number of successful tests in this test suite.
@@ -2871,7 +2946,7 @@ int TestSuite::total_test_count() const {
//
// Arguments:
//
-// name: name of the test suite
+// a_name: name of the test suite
// a_type_param: the name of the test suite's type parameter, or NULL if
// this is not a typed or a type-parameterized test suite.
// set_up_tc: pointer to the function that sets up the test suite
@@ -2926,19 +3001,26 @@ void TestSuite::Run() {
// Call both legacy and the new API
repeater->OnTestSuiteStart(*this);
// Legacy API is deprecated but still available
-#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
repeater->OnTestCaseStart(*this);
-#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
start_timestamp_ = internal::GetTimeInMillis();
+ internal::Timer timer;
for (int i = 0; i < total_test_count(); i++) {
GetMutableTestInfo(i)->Run();
+ if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) {
+ for (int j = i + 1; j < total_test_count(); j++) {
+ GetMutableTestInfo(j)->Skip();
+ }
+ break;
+ }
}
- elapsed_time_ = internal::GetTimeInMillis() - start_timestamp_;
+ elapsed_time_ = timer.Elapsed();
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
@@ -2947,9 +3029,39 @@ void TestSuite::Run() {
// Call both legacy and the new API
repeater->OnTestSuiteEnd(*this);
// Legacy API is deprecated but still available
-#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ repeater->OnTestCaseEnd(*this);
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+
+ impl->set_current_test_suite(nullptr);
+}
+
+// Skips all tests under this TestSuite.
+void TestSuite::Skip() {
+ if (!should_run_) return;
+
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
+ impl->set_current_test_suite(this);
+
+ TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
+
+ // Call both legacy and the new API
+ repeater->OnTestSuiteStart(*this);
+// Legacy API is deprecated but still available
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ repeater->OnTestCaseStart(*this);
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+
+ for (int i = 0; i < total_test_count(); i++) {
+ GetMutableTestInfo(i)->Skip();
+ }
+
+ // Call both legacy and the new API
+ repeater->OnTestSuiteEnd(*this);
+ // Legacy API is deprecated but still available
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
repeater->OnTestCaseEnd(*this);
-#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
impl->set_current_test_suite(nullptr);
}
@@ -3001,7 +3113,7 @@ static std::string FormatTestSuiteCount(int test_suite_count) {
static const char * TestPartResultTypeToString(TestPartResult::Type type) {
switch (type) {
case TestPartResult::kSkip:
- return "Skipped";
+ return "Skipped\n";
case TestPartResult::kSuccess:
return "Success";
@@ -3018,6 +3130,9 @@ static const char * TestPartResultTypeToString(TestPartResult::Type type) {
}
namespace internal {
+namespace {
+enum class GTestColor { kDefault, kRed, kGreen, kYellow };
+} // namespace
// Prints a TestPartResult to an std::string.
static std::string PrintTestPartResultToString(
@@ -3055,9 +3170,12 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) {
// Returns the character attribute for the given color.
static WORD GetColorAttribute(GTestColor color) {
switch (color) {
- case COLOR_RED: return FOREGROUND_RED;
- case COLOR_GREEN: return FOREGROUND_GREEN;
- case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
+ case GTestColor::kRed:
+ return FOREGROUND_RED;
+ case GTestColor::kGreen:
+ return FOREGROUND_GREEN;
+ case GTestColor::kYellow:
+ return FOREGROUND_RED | FOREGROUND_GREEN;
default: return 0;
}
}
@@ -3095,13 +3213,16 @@ static WORD GetNewColor(GTestColor color, WORD old_color_attrs) {
#else
-// Returns the ANSI color code for the given color. COLOR_DEFAULT is
+// Returns the ANSI color code for the given color. GTestColor::kDefault is
// an invalid input.
static const char* GetAnsiColorCode(GTestColor color) {
switch (color) {
- case COLOR_RED: return "1";
- case COLOR_GREEN: return "2";
- case COLOR_YELLOW: return "3";
+ case GTestColor::kRed:
+ return "1";
+ case GTestColor::kGreen:
+ return "2";
+ case GTestColor::kYellow:
+ return "3";
default:
return nullptr;
}
@@ -3150,7 +3271,9 @@ bool ShouldUseColor(bool stdout_is_tty) {
// cannot simply emit special characters and have the terminal change colors.
// This routine must actually emit the characters rather than return a string
// that would be colored when printed, as can be done on Linux.
-void ColoredPrintf(GTestColor color, const char* fmt, ...) {
+
+GTEST_ATTRIBUTE_PRINTF_(2, 3)
+static void ColoredPrintf(GTestColor color, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
@@ -3160,7 +3283,7 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) {
#else
static const bool in_color_mode =
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
- const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
+ const bool use_color = in_color_mode && (color != GTestColor::kDefault);
#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
if (!use_color) {
@@ -3272,25 +3395,24 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart(
// Prints the filter if it's not *. This reminds the user that some
// tests may be skipped.
if (!String::CStringEquals(filter, kUniversalFilter)) {
- ColoredPrintf(COLOR_YELLOW,
- "Note: %s filter = %s\n", GTEST_NAME_, filter);
+ ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_,
+ filter);
}
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
- ColoredPrintf(COLOR_YELLOW,
- "Note: This is test shard %d of %s.\n",
+ ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n",
static_cast<int>(shard_index) + 1,
internal::posix::GetEnv(kTestTotalShards));
}
if (GTEST_FLAG(shuffle)) {
- ColoredPrintf(COLOR_YELLOW,
+ ColoredPrintf(GTestColor::kYellow,
"Note: Randomizing tests' orders with a seed of %d .\n",
unit_test.random_seed());
}
- ColoredPrintf(COLOR_GREEN, "[==========] ");
+ ColoredPrintf(GTestColor::kGreen, "[==========] ");
printf("Running %s from %s.\n",
FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
@@ -3299,7 +3421,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationStart(
void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
const UnitTest& /*unit_test*/) {
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("Global test environment set-up.\n");
fflush(stdout);
}
@@ -3308,7 +3430,7 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s", counts.c_str(), test_case.name());
if (test_case.type_param() == nullptr) {
printf("\n");
@@ -3322,7 +3444,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteStart(
const TestSuite& test_suite) {
const std::string counts =
FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s", counts.c_str(), test_suite.name());
if (test_suite.type_param() == nullptr) {
printf("\n");
@@ -3334,7 +3456,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteStart(
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
- ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ RUN ] ");
PrintTestName(test_info.test_suite_name(), test_info.name());
printf("\n");
fflush(stdout);
@@ -3357,11 +3479,11 @@ void PrettyUnitTestResultPrinter::OnTestPartResult(
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
if (test_info.result()->Passed()) {
- ColoredPrintf(COLOR_GREEN, "[ OK ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ OK ] ");
} else if (test_info.result()->Skipped()) {
- ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
} else {
- ColoredPrintf(COLOR_RED, "[ FAILED ] ");
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
}
PrintTestName(test_info.test_suite_name(), test_info.name());
if (test_info.result()->Failed())
@@ -3382,7 +3504,7 @@ void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
internal::StreamableToString(test_case.elapsed_time()).c_str());
fflush(stdout);
@@ -3393,7 +3515,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
const std::string counts =
FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests");
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(),
internal::StreamableToString(test_suite.elapsed_time()).c_str());
fflush(stdout);
@@ -3402,7 +3524,7 @@ void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {
void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
const UnitTest& /*unit_test*/) {
- ColoredPrintf(COLOR_GREEN, "[----------] ");
+ ColoredPrintf(GTestColor::kGreen, "[----------] ");
printf("Global test environment tear-down\n");
fflush(stdout);
}
@@ -3410,7 +3532,7 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
// Internal helper for printing the list of failed tests.
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
const int failed_test_count = unit_test.failed_test_count();
- ColoredPrintf(COLOR_RED, "[ FAILED ] ");
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
@@ -3423,7 +3545,7 @@ void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
if (!test_info.should_run() || !test_info.result()->Failed()) {
continue;
}
- ColoredPrintf(COLOR_RED, "[ FAILED ] ");
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
printf("%s.%s", test_suite.name(), test_info.name());
PrintFullTestCommentIfPresent(test_info);
printf("\n");
@@ -3444,7 +3566,7 @@ void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
continue;
}
if (test_suite.ad_hoc_test_result().Failed()) {
- ColoredPrintf(COLOR_RED, "[ FAILED ] ");
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
++suite_failure_count;
}
@@ -3472,7 +3594,7 @@ void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
if (!test_info.should_run() || !test_info.result()->Skipped()) {
continue;
}
- ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
printf("%s.%s", test_suite.name(), test_info.name());
printf("\n");
}
@@ -3481,7 +3603,7 @@ void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) {
- ColoredPrintf(COLOR_GREEN, "[==========] ");
+ ColoredPrintf(GTestColor::kGreen, "[==========] ");
printf("%s from %s ran.",
FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
@@ -3490,12 +3612,12 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
internal::StreamableToString(unit_test.elapsed_time()).c_str());
}
printf("\n");
- ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
const int skipped_test_count = unit_test.skipped_test_count();
if (skipped_test_count > 0) {
- ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] ");
+ ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str());
PrintSkippedTests(unit_test);
}
@@ -3510,10 +3632,8 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
if (unit_test.Passed()) {
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
}
- ColoredPrintf(COLOR_YELLOW,
- " YOU HAVE %d DISABLED %s\n\n",
- num_disabled,
- num_disabled == 1 ? "TEST" : "TESTS");
+ ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
+ num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
}
// Ensure that Google Test output is printed before, e.g., heapchecker output.
fflush(stdout);
@@ -3521,6 +3641,110 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
// End PrettyUnitTestResultPrinter
+// This class implements the TestEventListener interface.
+//
+// Class BriefUnitTestResultPrinter is copyable.
+class BriefUnitTestResultPrinter : public TestEventListener {
+ public:
+ BriefUnitTestResultPrinter() {}
+ static void PrintTestName(const char* test_suite, const char* test) {
+ printf("%s.%s", test_suite, test);
+ }
+
+ // The following methods override what's in the TestEventListener class.
+ void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
+ void OnTestIterationStart(const UnitTest& /*unit_test*/,
+ int /*iteration*/) override {}
+ void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
+ void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ void OnTestCaseStart(const TestCase& /*test_case*/) override {}
+#else
+ void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
+#endif // OnTestCaseStart
+
+ void OnTestStart(const TestInfo& /*test_info*/) override {}
+
+ void OnTestPartResult(const TestPartResult& result) override;
+ void OnTestEnd(const TestInfo& test_info) override;
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
+#else
+ void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+
+ void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
+ void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
+ void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
+ void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
+};
+
+// Called after an assertion failure.
+void BriefUnitTestResultPrinter::OnTestPartResult(
+ const TestPartResult& result) {
+ switch (result.type()) {
+ // If the test part succeeded, we don't need to do anything.
+ case TestPartResult::kSuccess:
+ return;
+ default:
+ // Print failure message from the assertion
+ // (e.g. expected this and got that).
+ PrintTestPartResult(result);
+ fflush(stdout);
+ }
+}
+
+void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
+ if (test_info.result()->Failed()) {
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
+ PrintTestName(test_info.test_suite_name(), test_info.name());
+ PrintFullTestCommentIfPresent(test_info);
+
+ if (GTEST_FLAG(print_time)) {
+ printf(" (%s ms)\n",
+ internal::StreamableToString(test_info.result()->elapsed_time())
+ .c_str());
+ } else {
+ printf("\n");
+ }
+ fflush(stdout);
+ }
+}
+
+void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
+ int /*iteration*/) {
+ ColoredPrintf(GTestColor::kGreen, "[==========] ");
+ printf("%s from %s ran.",
+ FormatTestCount(unit_test.test_to_run_count()).c_str(),
+ FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
+ if (GTEST_FLAG(print_time)) {
+ printf(" (%s ms total)",
+ internal::StreamableToString(unit_test.elapsed_time()).c_str());
+ }
+ printf("\n");
+ ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
+ printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
+
+ const int skipped_test_count = unit_test.skipped_test_count();
+ if (skipped_test_count > 0) {
+ ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
+ printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
+ }
+
+ int num_disabled = unit_test.reportable_disabled_test_count();
+ if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
+ if (unit_test.Passed()) {
+ printf("\n"); // Add a spacer if no FAILURE banner is displayed.
+ }
+ ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
+ num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
+ }
+ // Ensure that Google Test output is printed before, e.g., heapchecker output.
+ fflush(stdout);
+}
+
+// End BriefUnitTestResultPrinter
+
// class TestEventRepeater
//
// This class forwards events to other event listeners.
@@ -3704,6 +3928,16 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener {
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
+ // Streams a test suite XML stanza containing the given test result.
+ //
+ // Requires: result.Failed()
+ static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,
+ const TestResult& result);
+
+ // Streams an XML representation of a TestResult object.
+ static void OutputXmlTestResult(::std::ostream* stream,
+ const TestResult& result);
+
// Streams an XML representation of a TestInfo object.
static void OutputXmlTestInfo(::std::ostream* stream,
const char* test_suite_name,
@@ -3862,6 +4096,10 @@ static bool PortableLocaltime(time_t seconds, struct tm* out) {
if (tm_ptr == nullptr) return false;
*out = *tm_ptr;
return true;
+#elif defined(__STDC_LIB_EXT1__)
+ // Uses localtime_s when available as localtime_r is only available from
+ // C23 standard.
+ return localtime_s(&seconds, out) != nullptr;
#else
return localtime_r(&seconds, out) != nullptr;
#endif
@@ -3873,13 +4111,14 @@ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
struct tm time_struct;
if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
return "";
- // YYYY-MM-DDThh:mm:ss
+ // YYYY-MM-DDThh:mm:ss.sss
return StreamableToString(time_struct.tm_year + 1900) + "-" +
String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
String::FormatIntWidth2(time_struct.tm_mday) + "T" +
String::FormatIntWidth2(time_struct.tm_hour) + ":" +
String::FormatIntWidth2(time_struct.tm_min) + ":" +
- String::FormatIntWidth2(time_struct.tm_sec);
+ String::FormatIntWidth2(time_struct.tm_sec) + "." +
+ String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);
}
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
@@ -3918,6 +4157,43 @@ void XmlUnitTestResultPrinter::OutputXmlAttribute(
*stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
}
+// Streams a test suite XML stanza containing the given test result.
+void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(
+ ::std::ostream* stream, const TestResult& result) {
+ // Output the boilerplate for a minimal test suite with one test.
+ *stream << " <testsuite";
+ OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure");
+ OutputXmlAttribute(stream, "testsuite", "tests", "1");
+ OutputXmlAttribute(stream, "testsuite", "failures", "1");
+ OutputXmlAttribute(stream, "testsuite", "disabled", "0");
+ OutputXmlAttribute(stream, "testsuite", "skipped", "0");
+ OutputXmlAttribute(stream, "testsuite", "errors", "0");
+ OutputXmlAttribute(stream, "testsuite", "time",
+ FormatTimeInMillisAsSeconds(result.elapsed_time()));
+ OutputXmlAttribute(
+ stream, "testsuite", "timestamp",
+ FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
+ *stream << ">";
+
+ // Output the boilerplate for a minimal test case with a single test.
+ *stream << " <testcase";
+ OutputXmlAttribute(stream, "testcase", "name", "");
+ OutputXmlAttribute(stream, "testcase", "status", "run");
+ OutputXmlAttribute(stream, "testcase", "result", "completed");
+ OutputXmlAttribute(stream, "testcase", "classname", "");
+ OutputXmlAttribute(stream, "testcase", "time",
+ FormatTimeInMillisAsSeconds(result.elapsed_time()));
+ OutputXmlAttribute(
+ stream, "testcase", "timestamp",
+ FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
+
+ // Output the actual test result.
+ OutputXmlTestResult(stream, result);
+
+ // Complete the test suite.
+ *stream << " </testsuite>\n";
+}
+
// Prints an XML representation of a TestInfo object.
void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
const char* test_suite_name,
@@ -3961,11 +4237,17 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));
OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
+ OutputXmlTestResult(stream, result);
+}
+
+void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,
+ const TestResult& result) {
int failures = 0;
+ int skips = 0;
for (int i = 0; i < result.total_part_count(); ++i) {
const TestPartResult& part = result.GetTestPartResult(i);
if (part.failed()) {
- if (++failures == 1) {
+ if (++failures == 1 && skips == 0) {
*stream << ">\n";
}
const std::string location =
@@ -3973,18 +4255,31 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
part.line_number());
const std::string summary = location + "\n" + part.summary();
*stream << " <failure message=\""
- << EscapeXmlAttribute(summary.c_str())
+ << EscapeXmlAttribute(summary)
<< "\" type=\"\">";
const std::string detail = location + "\n" + part.message();
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
*stream << "</failure>\n";
+ } else if (part.skipped()) {
+ if (++skips == 1 && failures == 0) {
+ *stream << ">\n";
+ }
+ const std::string location =
+ internal::FormatCompilerIndependentFileLocation(part.file_name(),
+ part.line_number());
+ const std::string summary = location + "\n" + part.summary();
+ *stream << " <skipped message=\""
+ << EscapeXmlAttribute(summary.c_str()) << "\">";
+ const std::string detail = location + "\n" + part.message();
+ OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
+ *stream << "</skipped>\n";
}
}
- if (failures == 0 && result.test_property_count() == 0) {
+ if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
*stream << " />\n";
} else {
- if (failures == 0) {
+ if (failures == 0 && skips == 0) {
*stream << ">\n";
}
OutputXmlTestProperties(stream, result);
@@ -4006,7 +4301,11 @@ void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,
OutputXmlAttribute(
stream, kTestsuite, "disabled",
StreamableToString(test_suite.reportable_disabled_test_count()));
+ OutputXmlAttribute(stream, kTestsuite, "skipped",
+ StreamableToString(test_suite.skipped_test_count()));
+
OutputXmlAttribute(stream, kTestsuite, "errors", "0");
+
OutputXmlAttribute(stream, kTestsuite, "time",
FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
OutputXmlAttribute(
@@ -4057,6 +4356,13 @@ void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)
PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));
}
+
+ // If there was a test failure outside of one of the test suites (like in a
+ // test environment) include that in the output.
+ if (unit_test.ad_hoc_test_result().Failed()) {
+ OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
+ }
+
*stream << "</" << kTestsuites << ">\n";
}
@@ -4147,6 +4453,16 @@ class JsonUnitTestResultPrinter : public EmptyTestEventListener {
const std::string& indent,
bool comma = true);
+ // Streams a test suite JSON stanza containing the given test result.
+ //
+ // Requires: result.Failed()
+ static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,
+ const TestResult& result);
+
+ // Streams a JSON representation of a TestResult object.
+ static void OutputJsonTestResult(::std::ostream* stream,
+ const TestResult& result);
+
// Streams a JSON representation of a TestInfo object.
static void OutputJsonTestInfo(::std::ostream* stream,
const char* test_suite_name,
@@ -4297,6 +4613,48 @@ void JsonUnitTestResultPrinter::OutputJsonKey(
*stream << ",\n";
}
+// Streams a test suite JSON stanza containing the given test result.
+void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(
+ ::std::ostream* stream, const TestResult& result) {
+ // Output the boilerplate for a new test suite.
+ *stream << Indent(4) << "{\n";
+ OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6));
+ OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6));
+ if (!GTEST_FLAG(list_tests)) {
+ OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6));
+ OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6));
+ OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6));
+ OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6));
+ OutputJsonKey(stream, "testsuite", "time",
+ FormatTimeInMillisAsDuration(result.elapsed_time()),
+ Indent(6));
+ OutputJsonKey(stream, "testsuite", "timestamp",
+ FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
+ Indent(6));
+ }
+ *stream << Indent(6) << "\"testsuite\": [\n";
+
+ // Output the boilerplate for a new test case.
+ *stream << Indent(8) << "{\n";
+ OutputJsonKey(stream, "testcase", "name", "", Indent(10));
+ OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10));
+ OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10));
+ OutputJsonKey(stream, "testcase", "timestamp",
+ FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),
+ Indent(10));
+ OutputJsonKey(stream, "testcase", "time",
+ FormatTimeInMillisAsDuration(result.elapsed_time()),
+ Indent(10));
+ OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false);
+ *stream << TestPropertiesAsJson(result, Indent(10));
+
+ // Output the actual test result.
+ OutputJsonTestResult(stream, result);
+
+ // Finish the test suite.
+ *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}";
+}
+
// Prints a JSON representation of a TestInfo object.
void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
const char* test_suite_name,
@@ -4339,6 +4697,13 @@ void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,
false);
*stream << TestPropertiesAsJson(result, kIndent);
+ OutputJsonTestResult(stream, result);
+}
+
+void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,
+ const TestResult& result) {
+ const std::string kIndent = Indent(10);
+
int failures = 0;
for (int i = 0; i < result.total_part_count(); ++i) {
const TestPartResult& part = result.GetTestPartResult(i);
@@ -4449,6 +4814,12 @@ void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,
}
}
+ // If there was a test failure outside of one of the test suites (like in a
+ // test environment) include that in the output.
+ if (unit_test.ad_hoc_test_result().Failed()) {
+ OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());
+ }
+
*stream << "\n" << kIndent << "]\n" << "}\n";
}
@@ -5271,6 +5642,10 @@ void UnitTestImpl::PostFlagParsingInit() {
// to shut down the default XML output before invoking RUN_ALL_TESTS.
ConfigureXmlOutput();
+ if (GTEST_FLAG(brief)) {
+ listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
+ }
+
#if GTEST_CAN_STREAM_RESULTS_
// Configures listeners for streaming test results to the specified server.
ConfigureStreamingOutput();
@@ -5316,10 +5691,10 @@ class TestSuiteNameIs {
// Arguments:
//
// test_suite_name: name of the test suite
-// type_param: the name of the test suite's type parameter, or NULL if
-// this is not a typed or a type-parameterized test suite.
-// set_up_tc: pointer to the function that sets up the test suite
-// tear_down_tc: pointer to the function that tears down the test suite
+// type_param: the name of the test suite's type parameter, or NULL if
+// this is not a typed or a type-parameterized test suite.
+// set_up_tc: pointer to the function that sets up the test suite
+// tear_down_tc: pointer to the function that tears down the test suite
TestSuite* UnitTestImpl::GetTestSuite(
const char* test_suite_name, const char* type_param,
internal::SetUpTestSuiteFunc set_up_tc,
@@ -5437,7 +5812,7 @@ bool UnitTestImpl::RunAllTests() {
// assertions executed before RUN_ALL_TESTS().
ClearNonAdHocTestResult();
- const TimeInMillis start = GetTimeInMillis();
+ Timer timer;
// Shuffles test suites and tests if requested.
if (has_tests_to_run && GTEST_FLAG(shuffle)) {
@@ -5478,6 +5853,21 @@ bool UnitTestImpl::RunAllTests() {
for (int test_index = 0; test_index < total_test_suite_count();
test_index++) {
GetMutableSuiteCase(test_index)->Run();
+ if (GTEST_FLAG(fail_fast) &&
+ GetMutableSuiteCase(test_index)->Failed()) {
+ for (int j = test_index + 1; j < total_test_suite_count(); j++) {
+ GetMutableSuiteCase(j)->Skip();
+ }
+ break;
+ }
+ }
+ } else if (Test::HasFatalFailure()) {
+ // If there was a fatal failure during the global setup then we know we
+ // aren't going to run any tests. Explicitly mark all of the tests as
+ // skipped to make this obvious in the output.
+ for (int test_index = 0; test_index < total_test_suite_count();
+ test_index++) {
+ GetMutableSuiteCase(test_index)->Skip();
}
}
@@ -5488,7 +5878,7 @@ bool UnitTestImpl::RunAllTests() {
repeater->OnEnvironmentsTearDownEnd(*parent_);
}
- elapsed_time_ = GetTimeInMillis() - start;
+ elapsed_time_ = timer.Elapsed();
// Tells the unit test event listener that the tests have just finished.
repeater->OnTestIterationEnd(*parent_, i);
@@ -5516,14 +5906,14 @@ bool UnitTestImpl::RunAllTests() {
if (!gtest_is_initialized_before_run_all_tests) {
ColoredPrintf(
- COLOR_RED,
+ GTestColor::kRed,
"\nIMPORTANT NOTICE - DO NOT IGNORE:\n"
"This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_
"() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_
" will start to enforce the valid usage. "
"Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT
#if GTEST_FOR_GOOGLE_
- ColoredPrintf(COLOR_RED,
+ ColoredPrintf(GTestColor::kRed,
"For more details, see http://wiki/Main/ValidGUnitMain.\n");
#endif // GTEST_FOR_GOOGLE_
}
@@ -5540,7 +5930,7 @@ void WriteToShardStatusFileIfNeeded() {
if (test_shard_file != nullptr) {
FILE* const file = posix::FOpen(test_shard_file, "w");
if (file == nullptr) {
- ColoredPrintf(COLOR_RED,
+ ColoredPrintf(GTestColor::kRed,
"Could not write to the test shard status file \"%s\" "
"specified by the %s environment variable.\n",
test_shard_file, kTestShardStatusFile);
@@ -5574,7 +5964,7 @@ bool ShouldShard(const char* total_shards_env,
<< "Invalid environment variables: you have "
<< kTestShardIndex << " = " << shard_index
<< ", but have left " << kTestTotalShards << " unset.\n";
- ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
+ ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (total_shards != -1 && shard_index == -1) {
@@ -5582,7 +5972,7 @@ bool ShouldShard(const char* total_shards_env,
<< "Invalid environment variables: you have "
<< kTestTotalShards << " = " << total_shards
<< ", but have left " << kTestShardIndex << " unset.\n";
- ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
+ ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (shard_index < 0 || shard_index >= total_shards) {
@@ -5591,7 +5981,7 @@ bool ShouldShard(const char* total_shards_env,
<< kTestShardIndex << " < " << kTestTotalShards
<< ", but you have " << kTestShardIndex << "=" << shard_index
<< ", " << kTestTotalShards << "=" << total_shards << ".\n";
- ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str());
+ ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
}
@@ -5981,7 +6371,7 @@ static bool HasGoogleTestFlagPrefix(const char* str) {
// @D changes to the default terminal text color.
//
static void PrintColorEncoded(const char* str) {
- GTestColor color = COLOR_DEFAULT; // The current color.
+ GTestColor color = GTestColor::kDefault; // The current color.
// Conceptually, we split the string into segments divided by escape
// sequences. Then we print one segment at a time. At the end of
@@ -6001,13 +6391,13 @@ static void PrintColorEncoded(const char* str) {
if (ch == '@') {
ColoredPrintf(color, "@");
} else if (ch == 'D') {
- color = COLOR_DEFAULT;
+ color = GTestColor::kDefault;
} else if (ch == 'R') {
- color = COLOR_RED;
+ color = GTestColor::kRed;
} else if (ch == 'G') {
- color = COLOR_GREEN;
+ color = GTestColor::kGreen;
} else if (ch == 'Y') {
- color = COLOR_YELLOW;
+ color = GTestColor::kYellow;
} else {
--str;
}
@@ -6015,98 +6405,126 @@ static void PrintColorEncoded(const char* str) {
}
static const char kColorEncodedHelpMessage[] =
-"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
-"following command line flags to control its behavior:\n"
-"\n"
-"Test Selection:\n"
-" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
-" List the names of all tests instead of running them. The name of\n"
-" TEST(Foo, Bar) is \"Foo.Bar\".\n"
-" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
+ "This program contains tests written using " GTEST_NAME_
+ ". You can use the\n"
+ "following command line flags to control its behavior:\n"
+ "\n"
+ "Test Selection:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "list_tests@D\n"
+ " List the names of all tests instead of running them. The name of\n"
+ " TEST(Foo, Bar) is \"Foo.Bar\".\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "filter=@YPOSITIVE_PATTERNS"
"[@G-@YNEGATIVE_PATTERNS]@D\n"
-" Run only the tests whose name matches one of the positive patterns but\n"
-" none of the negative patterns. '?' matches any single character; '*'\n"
-" matches any substring; ':' separates two patterns.\n"
-" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
-" Run all disabled tests too.\n"
-"\n"
-"Test Execution:\n"
-" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
-" Run the tests repeatedly; use a negative count to repeat forever.\n"
-" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
-" Randomize tests' orders on every iteration.\n"
-" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
-" Random number seed to use for shuffling test orders (between 1 and\n"
-" 99999, or 0 to use a seed based on the current time).\n"
-"\n"
-"Test Output:\n"
-" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
-" Enable/disable colored output. The default is @Gauto@D.\n"
-" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
-" Don't print the elapsed time of each test.\n"
-" @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
- GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
-" Generate a JSON or XML report in the given directory or with the given\n"
-" file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
+ " Run only the tests whose name matches one of the positive patterns "
+ "but\n"
+ " none of the negative patterns. '?' matches any single character; "
+ "'*'\n"
+ " matches any substring; ':' separates two patterns.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "also_run_disabled_tests@D\n"
+ " Run all disabled tests too.\n"
+ "\n"
+ "Test Execution:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "repeat=@Y[COUNT]@D\n"
+ " Run the tests repeatedly; use a negative count to repeat forever.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "shuffle@D\n"
+ " Randomize tests' orders on every iteration.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "random_seed=@Y[NUMBER]@D\n"
+ " Random number seed to use for shuffling test orders (between 1 and\n"
+ " 99999, or 0 to use a seed based on the current time).\n"
+ "\n"
+ "Test Output:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
+ " Enable/disable colored output. The default is @Gauto@D.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "brief=1@D\n"
+ " Only print test failures.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "print_time=0@D\n"
+ " Don't print the elapsed time of each test.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
+ "@Y|@G:@YFILE_PATH]@D\n"
+ " Generate a JSON or XML report in the given directory or with the "
+ "given\n"
+ " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
# if GTEST_CAN_STREAM_RESULTS_
-" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
-" Stream test results to the given server.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "stream_result_to=@YHOST@G:@YPORT@D\n"
+ " Stream test results to the given server.\n"
# endif // GTEST_CAN_STREAM_RESULTS_
-"\n"
-"Assertion Behavior:\n"
+ "\n"
+ "Assertion Behavior:\n"
# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
-" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
-" Set the default death test style.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
+ " Set the default death test style.\n"
# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
-" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
-" Turn assertion failures into debugger break-points.\n"
-" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
-" Turn assertion failures into C++ exceptions for use by an external\n"
-" test framework.\n"
-" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
-" Do not report exceptions as test failures. Instead, allow them\n"
-" to crash the program or throw a pop-up (on Windows).\n"
-"\n"
-"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
+ " @G--" GTEST_FLAG_PREFIX_
+ "break_on_failure@D\n"
+ " Turn assertion failures into debugger break-points.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "throw_on_failure@D\n"
+ " Turn assertion failures into C++ exceptions for use by an external\n"
+ " test framework.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "catch_exceptions=0@D\n"
+ " Do not report exceptions as test failures. Instead, allow them\n"
+ " to crash the program or throw a pop-up (on Windows).\n"
+ "\n"
+ "Except for @G--" GTEST_FLAG_PREFIX_
+ "list_tests@D, you can alternatively set "
"the corresponding\n"
-"environment variable of a flag (all letters in upper-case). For example, to\n"
-"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
+ "environment variable of a flag (all letters in upper-case). For example, "
+ "to\n"
+ "disable colored text output, you can either specify "
+ "@G--" GTEST_FLAG_PREFIX_
"color=no@D or set\n"
-"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
-"\n"
-"For more information, please read the " GTEST_NAME_ " documentation at\n"
-"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
-"(not one in your own code or tests), please report it to\n"
-"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
+ "the @G" GTEST_FLAG_PREFIX_UPPER_
+ "COLOR@D environment variable to @Gno@D.\n"
+ "\n"
+ "For more information, please read the " GTEST_NAME_
+ " documentation at\n"
+ "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
+ "\n"
+ "(not one in your own code or tests), please report it to\n"
+ "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
static bool ParseGoogleTestFlag(const char* const arg) {
return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
&GTEST_FLAG(also_run_disabled_tests)) ||
- ParseBoolFlag(arg, kBreakOnFailureFlag,
- &GTEST_FLAG(break_on_failure)) ||
- ParseBoolFlag(arg, kCatchExceptionsFlag,
- &GTEST_FLAG(catch_exceptions)) ||
- ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
- ParseStringFlag(arg, kDeathTestStyleFlag,
- &GTEST_FLAG(death_test_style)) ||
- ParseBoolFlag(arg, kDeathTestUseFork,
- &GTEST_FLAG(death_test_use_fork)) ||
- ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
- ParseStringFlag(arg, kInternalRunDeathTestFlag,
- &GTEST_FLAG(internal_run_death_test)) ||
- ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
- ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
- ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
- ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
- ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
- ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
- ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
- ParseInt32Flag(arg, kStackTraceDepthFlag,
- &GTEST_FLAG(stack_trace_depth)) ||
- ParseStringFlag(arg, kStreamResultToFlag,
- &GTEST_FLAG(stream_result_to)) ||
- ParseBoolFlag(arg, kThrowOnFailureFlag,
- &GTEST_FLAG(throw_on_failure));
+ ParseBoolFlag(arg, kBreakOnFailureFlag,
+ &GTEST_FLAG(break_on_failure)) ||
+ ParseBoolFlag(arg, kCatchExceptionsFlag,
+ &GTEST_FLAG(catch_exceptions)) ||
+ ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
+ ParseStringFlag(arg, kDeathTestStyleFlag,
+ &GTEST_FLAG(death_test_style)) ||
+ ParseBoolFlag(arg, kDeathTestUseFork,
+ &GTEST_FLAG(death_test_use_fork)) ||
+ ParseBoolFlag(arg, kFailFast, &GTEST_FLAG(fail_fast)) ||
+ ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
+ ParseStringFlag(arg, kInternalRunDeathTestFlag,
+ &GTEST_FLAG(internal_run_death_test)) ||
+ ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
+ ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
+ ParseBoolFlag(arg, kBriefFlag, &GTEST_FLAG(brief)) ||
+ ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
+ ParseBoolFlag(arg, kPrintUTF8Flag, &GTEST_FLAG(print_utf8)) ||
+ ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
+ ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
+ ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
+ ParseInt32Flag(arg, kStackTraceDepthFlag,
+ &GTEST_FLAG(stack_trace_depth)) ||
+ ParseStringFlag(arg, kStreamResultToFlag,
+ &GTEST_FLAG(stream_result_to)) ||
+ ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure));
}
#if GTEST_USE_OWN_FLAGFILE_FLAG_
@@ -6276,20 +6694,31 @@ void InitGoogleTest() {
std::string TempDir() {
#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)
return GTEST_CUSTOM_TEMPDIR_FUNCTION_();
-#endif
-
-#if GTEST_OS_WINDOWS_MOBILE
+#elif GTEST_OS_WINDOWS_MOBILE
return "\\temp\\";
#elif GTEST_OS_WINDOWS
const char* temp_dir = internal::posix::GetEnv("TEMP");
- if (temp_dir == nullptr || temp_dir[0] == '\0')
+ if (temp_dir == nullptr || temp_dir[0] == '\0') {
return "\\temp\\";
- else if (temp_dir[strlen(temp_dir) - 1] == '\\')
+ } else if (temp_dir[strlen(temp_dir) - 1] == '\\') {
return temp_dir;
- else
+ } else {
return std::string(temp_dir) + "\\";
+ }
#elif GTEST_OS_LINUX_ANDROID
- return "/sdcard/";
+ const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
+ if (temp_dir == nullptr || temp_dir[0] == '\0') {
+ return "/data/local/tmp/";
+ } else {
+ return temp_dir;
+ }
+#elif GTEST_OS_LINUX
+ const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
+ if (temp_dir == nullptr || temp_dir[0] == '\0') {
+ return "/tmp/";
+ } else {
+ return temp_dir;
+ }
#else
return "/tmp/";
#endif // GTEST_OS_WINDOWS_MOBILE
diff --git a/googletest/test/Android.bp b/googletest/test/Android.bp
index 6a36a068..4b000128 100644
--- a/googletest/test/Android.bp
+++ b/googletest/test/Android.bp
@@ -12,6 +12,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "external_googletest_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-BSD
+ default_applicable_licenses: ["external_googletest_license"],
+}
+
cc_defaults {
name: "gtest_test_defaults",
host_supported: true,
diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel
index 15f7eef8..b06a00a1 100644
--- a/googletest/test/BUILD.bazel
+++ b/googletest/test/BUILD.bazel
@@ -28,8 +28,6 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
-# Author: misterg@google.com (Gennadiy Civil)
-#
# Bazel BUILD for The Google C++ Testing Framework (Google Test)
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
@@ -37,6 +35,8 @@ load("@rules_python//python:defs.bzl", "py_library", "py_test")
licenses(["notice"])
+package(default_visibility = ["//:__subpackages__"])
+
#on windows exclude gtest-tuple.h
cc_test(
name = "gtest_all_test",
@@ -56,10 +56,13 @@ cc_test(
"gtest-listener_test.cc",
"gtest-unittest-api_test.cc",
"googletest-param-test-test.cc",
+ "googletest-param-test2-test.cc",
"googletest-catch-exceptions-test_.cc",
"googletest-color-test_.cc",
"googletest-env-var-test_.cc",
+ "googletest-failfast-unittest_.cc",
"googletest-filter-unittest_.cc",
+ "googletest-global-environment-unittest_.cc",
"googletest-break-on-failure-unittest_.cc",
"googletest-listener-test.cc",
"googletest-output-test_.cc",
@@ -80,6 +83,10 @@ cc_test(
copts = select({
"//:windows": ["-DGTEST_USE_OWN_TR1_TUPLE=0"],
"//conditions:default": ["-DGTEST_USE_OWN_TR1_TUPLE=1"],
+ }) + select({
+ # Ensure MSVC treats source files as UTF-8 encoded.
+ "//:msvc_compiler": ["-utf-8"],
+ "//conditions:default": [],
}),
includes = [
"googletest",
@@ -143,7 +150,6 @@ cc_test(
name = "gtest_unittest",
size = "small",
srcs = ["gtest_unittest.cc"],
- args = ["--heap_check=strict"],
shard_count = 2,
deps = ["//:gtest_main"],
)
@@ -154,6 +160,7 @@ py_library(
name = "gtest_test_utils",
testonly = 1,
srcs = ["gtest_test_utils.py"],
+ imports = ["."],
)
cc_binary(
@@ -224,6 +231,21 @@ py_test(
)
cc_binary(
+ name = "googletest-failfast-unittest_",
+ testonly = 1,
+ srcs = ["googletest-failfast-unittest_.cc"],
+ deps = ["//:gtest"],
+)
+
+py_test(
+ name = "googletest-failfast-unittest",
+ size = "medium",
+ srcs = ["googletest-failfast-unittest.py"],
+ data = [":googletest-failfast-unittest_"],
+ deps = [":gtest_test_utils"],
+)
+
+cc_binary(
name = "googletest-filter-unittest_",
testonly = 1,
srcs = ["googletest-filter-unittest_.cc"],
@@ -239,6 +261,21 @@ py_test(
)
cc_binary(
+ name = "googletest-global-environment-unittest_",
+ testonly = 1,
+ srcs = ["googletest-global-environment-unittest_.cc"],
+ deps = ["//:gtest"],
+)
+
+py_test(
+ name = "googletest-global-environment-unittest",
+ size = "medium",
+ srcs = ["googletest-global-environment-unittest.py"],
+ data = [":googletest-global-environment-unittest_"],
+ deps = [":gtest_test_utils"],
+)
+
+cc_binary(
name = "googletest-break-on-failure-unittest_",
testonly = 1,
srcs = ["googletest-break-on-failure-unittest_.cc"],
@@ -533,6 +570,10 @@ py_test(
size = "small",
srcs = ["googletest-param-test-invalid-name1-test.py"],
data = [":googletest-param-test-invalid-name1-test_"],
+ tags = [
+ "no_test_msvc2015",
+ "no_test_msvc2017",
+ ],
deps = [":gtest_test_utils"],
)
@@ -541,5 +582,9 @@ py_test(
size = "small",
srcs = ["googletest-param-test-invalid-name2-test.py"],
data = [":googletest-param-test-invalid-name2-test_"],
+ tags = [
+ "no_test_msvc2015",
+ "no_test_msvc2017",
+ ],
deps = [":gtest_test_utils"],
)
diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc
index cba906cc..c0b3d1f2 100644
--- a/googletest/test/googletest-death-test-test.cc
+++ b/googletest/test/googletest-death-test-test.cc
@@ -298,6 +298,13 @@ TEST(ExitStatusPredicateTest, KilledBySignal) {
# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
@@ -321,6 +328,9 @@ TEST_F(TestForDeathTest, SingleStatement) {
else
EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
# if GTEST_USES_PCRE
@@ -391,17 +401,19 @@ void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
void SetSigprofActionAndTimer() {
- struct itimerval timer;
- timer.it_interval.tv_sec = 0;
- timer.it_interval.tv_usec = 1;
- timer.it_value = timer.it_interval;
- ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
struct sigaction signal_action;
memset(&signal_action, 0, sizeof(signal_action));
sigemptyset(&signal_action.sa_mask);
signal_action.sa_sigaction = SigprofAction;
signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, nullptr));
+ // timer comes second, to avoid SIGPROF premature delivery, as suggested at
+ // https://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html
+ struct itimerval timer;
+ timer.it_interval.tv_sec = 0;
+ timer.it_interval.tv_usec = 1;
+ timer.it_value = timer.it_interval;
+ ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
}
// Disables ITIMER_PROF timer and ignores SIGPROF signal.
@@ -1374,7 +1386,11 @@ void DieWithMessage(const char* message) {
TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) {
// googletest tests this, of course; here we ensure that including googlemock
// has not broken it.
+#if GTEST_USES_POSIX_RE
EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e");
+#else
+ EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I di?e");
+#endif
}
TEST(MatcherDeathTest, MonomorphicMatcherMatches) {
@@ -1462,6 +1478,13 @@ TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
namespace {
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
@@ -1487,6 +1510,9 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
else
EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
// Tests that conditional death test macros expand to code which interacts
// well with switch statements.
diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc
index 7ea5b946..7219680d 100644
--- a/googletest/test/googletest-death-test_ex_test.cc
+++ b/googletest/test/googletest-death-test_ex_test.cc
@@ -59,7 +59,7 @@ TEST(CxxExceptionDeathTest, ExceptionIsFailure) {
class TestException : public std::exception {
public:
- const char* what() const throw() override { return "exceptional message"; }
+ const char* what() const noexcept override { return "exceptional message"; }
};
TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
diff --git a/googletest/test/googletest-env-var-test.py b/googletest/test/googletest-env-var-test.py
index 2f0e406a..02c3655c 100755
--- a/googletest/test/googletest-env-var-test.py
+++ b/googletest/test/googletest-env-var-test.py
@@ -85,9 +85,12 @@ class GTestEnvVarTest(gtest_test_utils.TestCase):
TestFlag('break_on_failure', '1', '0')
TestFlag('color', 'yes', 'auto')
+ SetEnvVar('TESTBRIDGE_TEST_RUNNER_FAIL_FAST', None) # For 'fail_fast' test
+ TestFlag('fail_fast', '1', '0')
TestFlag('filter', 'FooTest.Bar', '*')
SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test
TestFlag('output', 'xml:tmp/foo.xml', '')
+ TestFlag('brief', '1', '0')
TestFlag('print_time', '0', '1')
TestFlag('repeat', '999', '1')
TestFlag('throw_on_failure', '1', '0')
diff --git a/googletest/test/googletest-env-var-test_.cc b/googletest/test/googletest-env-var-test_.cc
index fd2aa82f..52f95864 100644
--- a/googletest/test/googletest-env-var-test_.cc
+++ b/googletest/test/googletest-env-var-test_.cc
@@ -72,6 +72,11 @@ void PrintFlag(const char* flag) {
return;
}
+ if (strcmp(flag, "fail_fast") == 0) {
+ cout << GTEST_FLAG(fail_fast);
+ return;
+ }
+
if (strcmp(flag, "filter") == 0) {
cout << GTEST_FLAG(filter);
return;
@@ -82,6 +87,11 @@ void PrintFlag(const char* flag) {
return;
}
+ if (strcmp(flag, "brief") == 0) {
+ cout << GTEST_FLAG(brief);
+ return;
+ }
+
if (strcmp(flag, "print_time") == 0) {
cout << GTEST_FLAG(print_time);
return;
diff --git a/googletest/test/googletest-failfast-unittest.py b/googletest/test/googletest-failfast-unittest.py
new file mode 100755
index 00000000..3aeb2dff
--- /dev/null
+++ b/googletest/test/googletest-failfast-unittest.py
@@ -0,0 +1,410 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google Inc. All Rights Reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Unit test for Google Test fail_fast.
+
+A user can specify if a Google Test program should continue test execution
+after a test failure via the GTEST_FAIL_FAST environment variable or the
+--gtest_fail_fast flag. The default value of the flag can also be changed
+by Bazel fail fast environment variable TESTBRIDGE_TEST_RUNNER_FAIL_FAST.
+
+This script tests such functionality by invoking googletest-failfast-unittest_
+(a program written with Google Test) with different environments and command
+line flags.
+"""
+
+import os
+import gtest_test_utils
+
+# Constants.
+
+# Bazel testbridge environment variable for fail fast
+BAZEL_FAIL_FAST_ENV_VAR = 'TESTBRIDGE_TEST_RUNNER_FAIL_FAST'
+
+# The environment variable for specifying fail fast.
+FAIL_FAST_ENV_VAR = 'GTEST_FAIL_FAST'
+
+# The command line flag for specifying fail fast.
+FAIL_FAST_FLAG = 'gtest_fail_fast'
+
+# The command line flag to run disabled tests.
+RUN_DISABLED_FLAG = 'gtest_also_run_disabled_tests'
+
+# The command line flag for specifying a filter.
+FILTER_FLAG = 'gtest_filter'
+
+# Command to run the googletest-failfast-unittest_ program.
+COMMAND = gtest_test_utils.GetTestExecutablePath(
+ 'googletest-failfast-unittest_')
+
+# The command line flag to tell Google Test to output the list of tests it
+# will run.
+LIST_TESTS_FLAG = '--gtest_list_tests'
+
+# Indicates whether Google Test supports death tests.
+SUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess(
+ [COMMAND, LIST_TESTS_FLAG]).output
+
+# Utilities.
+
+environ = os.environ.copy()
+
+
+def SetEnvVar(env_var, value):
+ """Sets the env variable to 'value'; unsets it when 'value' is None."""
+
+ if value is not None:
+ environ[env_var] = value
+ elif env_var in environ:
+ del environ[env_var]
+
+
+def RunAndReturnOutput(test_suite=None, fail_fast=None, run_disabled=False):
+ """Runs the test program and returns its output."""
+
+ args = []
+ xml_path = os.path.join(gtest_test_utils.GetTempDir(),
+ '.GTestFailFastUnitTest.xml')
+ args += ['--gtest_output=xml:' + xml_path]
+ if fail_fast is not None:
+ if isinstance(fail_fast, str):
+ args += ['--%s=%s' % (FAIL_FAST_FLAG, fail_fast)]
+ elif fail_fast:
+ args += ['--%s' % FAIL_FAST_FLAG]
+ else:
+ args += ['--no%s' % FAIL_FAST_FLAG]
+ if test_suite:
+ args += ['--%s=%s.*' % (FILTER_FLAG, test_suite)]
+ if run_disabled:
+ args += ['--%s' % RUN_DISABLED_FLAG]
+ txt_out = gtest_test_utils.Subprocess([COMMAND] + args, env=environ).output
+ with open(xml_path) as xml_file:
+ return txt_out, xml_file.read()
+
+
+# The unit test.
+class GTestFailFastUnitTest(gtest_test_utils.TestCase):
+ """Tests the env variable or the command line flag for fail_fast."""
+
+ def testDefaultBehavior(self):
+ """Tests the behavior of not specifying the fail_fast."""
+
+ txt, _ = RunAndReturnOutput()
+ self.assertIn('22 FAILED TEST', txt)
+
+ def testGoogletestFlag(self):
+ txt, _ = RunAndReturnOutput(test_suite='HasSimpleTest', fail_fast=True)
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+
+ txt, _ = RunAndReturnOutput(test_suite='HasSimpleTest', fail_fast=False)
+ self.assertIn('4 FAILED TEST', txt)
+ self.assertNotIn('[ SKIPPED ]', txt)
+
+ def testGoogletestEnvVar(self):
+ """Tests the behavior of specifying fail_fast via Googletest env var."""
+
+ try:
+ SetEnvVar(FAIL_FAST_ENV_VAR, '1')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+
+ SetEnvVar(FAIL_FAST_ENV_VAR, '0')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('4 FAILED TEST', txt)
+ self.assertNotIn('[ SKIPPED ]', txt)
+ finally:
+ SetEnvVar(FAIL_FAST_ENV_VAR, None)
+
+ def testBazelEnvVar(self):
+ """Tests the behavior of specifying fail_fast via Bazel testbridge."""
+
+ try:
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '1')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '0')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('4 FAILED TEST', txt)
+ self.assertNotIn('[ SKIPPED ]', txt)
+ finally:
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, None)
+
+ def testFlagOverridesEnvVar(self):
+ """Tests precedence of flag over env var."""
+
+ try:
+ SetEnvVar(FAIL_FAST_ENV_VAR, '0')
+ txt, _ = RunAndReturnOutput('HasSimpleTest', True)
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+ finally:
+ SetEnvVar(FAIL_FAST_ENV_VAR, None)
+
+ def testGoogletestEnvVarOverridesBazelEnvVar(self):
+ """Tests that the Googletest native env var over Bazel testbridge."""
+
+ try:
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '0')
+ SetEnvVar(FAIL_FAST_ENV_VAR, '1')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+ finally:
+ SetEnvVar(FAIL_FAST_ENV_VAR, None)
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, None)
+
+ def testEventListener(self):
+ txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=True)
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+ for expected_count, callback in [(1, 'OnTestSuiteStart'),
+ (5, 'OnTestStart'),
+ (5, 'OnTestEnd'),
+ (5, 'OnTestPartResult'),
+ (1, 'OnTestSuiteEnd')]:
+ self.assertEqual(
+ expected_count, txt.count(callback),
+ 'Expected %d calls to callback %s match count on output: %s ' %
+ (expected_count, callback, txt))
+
+ txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=False)
+ self.assertIn('3 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 1 test', txt)
+ for expected_count, callback in [(1, 'OnTestSuiteStart'),
+ (5, 'OnTestStart'),
+ (5, 'OnTestEnd'),
+ (5, 'OnTestPartResult'),
+ (1, 'OnTestSuiteEnd')]:
+ self.assertEqual(
+ expected_count, txt.count(callback),
+ 'Expected %d calls to callback %s match count on output: %s ' %
+ (expected_count, callback, txt))
+
+ def assertXmlResultCount(self, result, count, xml):
+ self.assertEqual(
+ count, xml.count('result="%s"' % result),
+ 'Expected \'result="%s"\' match count of %s: %s ' %
+ (result, count, xml))
+
+ def assertXmlStatusCount(self, status, count, xml):
+ self.assertEqual(
+ count, xml.count('status="%s"' % status),
+ 'Expected \'status="%s"\' match count of %s: %s ' %
+ (status, count, xml))
+
+ def assertFailFastXmlAndTxtOutput(self,
+ fail_fast,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False):
+ """Assert XML and text output of a test execution."""
+
+ txt, xml = RunAndReturnOutput(test_suite, fail_fast, run_disabled)
+ if failure_count > 0:
+ self.assertIn('%s FAILED TEST' % failure_count, txt)
+ if suppressed_count > 0:
+ self.assertIn('%s DISABLED TEST' % suppressed_count, txt)
+ if skipped_count > 0:
+ self.assertIn('[ SKIPPED ] %s tests' % skipped_count, txt)
+ self.assertXmlStatusCount('run',
+ passed_count + failure_count + skipped_count, xml)
+ self.assertXmlStatusCount('notrun', suppressed_count, xml)
+ self.assertXmlResultCount('completed', passed_count + failure_count, xml)
+ self.assertXmlResultCount('skipped', skipped_count, xml)
+ self.assertXmlResultCount('suppressed', suppressed_count, xml)
+
+ def assertFailFastBehavior(self,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False):
+ """Assert --fail_fast via flag."""
+
+ for fail_fast in ('true', '1', 't', True):
+ self.assertFailFastXmlAndTxtOutput(fail_fast, test_suite, passed_count,
+ failure_count, skipped_count,
+ suppressed_count, run_disabled)
+
+ def assertNotFailFastBehavior(self,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False):
+ """Assert --nofail_fast via flag."""
+
+ for fail_fast in ('false', '0', 'f', False):
+ self.assertFailFastXmlAndTxtOutput(fail_fast, test_suite, passed_count,
+ failure_count, skipped_count,
+ suppressed_count, run_disabled)
+
+ def testFlag_HasFixtureTest(self):
+ """Tests the behavior of fail_fast and TEST_F."""
+ self.assertFailFastBehavior(
+ test_suite='HasFixtureTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0)
+ self.assertNotFailFastBehavior(
+ test_suite='HasFixtureTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0)
+
+ def testFlag_HasSimpleTest(self):
+ """Tests the behavior of fail_fast and TEST."""
+ self.assertFailFastBehavior(
+ test_suite='HasSimpleTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0)
+ self.assertNotFailFastBehavior(
+ test_suite='HasSimpleTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0)
+
+ def testFlag_HasParametersTest(self):
+ """Tests the behavior of fail_fast and TEST_P."""
+ self.assertFailFastBehavior(
+ test_suite='HasParametersSuite/HasParametersTest',
+ passed_count=0,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0)
+ self.assertNotFailFastBehavior(
+ test_suite='HasParametersSuite/HasParametersTest',
+ passed_count=0,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0)
+
+ def testFlag_HasDisabledTest(self):
+ """Tests the behavior of fail_fast and Disabled test cases."""
+ self.assertFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=2,
+ suppressed_count=1,
+ run_disabled=False)
+ self.assertNotFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=3,
+ skipped_count=0,
+ suppressed_count=1,
+ run_disabled=False)
+
+ def testFlag_HasDisabledRunDisabledTest(self):
+ """Tests the behavior of fail_fast and Disabled test cases enabled."""
+ self.assertFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ run_disabled=True)
+ self.assertNotFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ run_disabled=True)
+
+ def testFlag_HasDisabledSuiteTest(self):
+ """Tests the behavior of fail_fast and Disabled test suites."""
+ self.assertFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=0,
+ failure_count=0,
+ skipped_count=0,
+ suppressed_count=5,
+ run_disabled=False)
+ self.assertNotFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=0,
+ failure_count=0,
+ skipped_count=0,
+ suppressed_count=5,
+ run_disabled=False)
+
+ def testFlag_HasDisabledSuiteRunDisabledTest(self):
+ """Tests the behavior of fail_fast and Disabled test suites enabled."""
+ self.assertFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ run_disabled=True)
+ self.assertNotFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ run_disabled=True)
+
+ if SUPPORTS_DEATH_TESTS:
+
+ def testFlag_HasDeathTest(self):
+ """Tests the behavior of fail_fast and death tests."""
+ self.assertFailFastBehavior(
+ test_suite='HasDeathTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0)
+ self.assertNotFailFastBehavior(
+ test_suite='HasDeathTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0)
+
+
+if __name__ == '__main__':
+ gtest_test_utils.Main()
diff --git a/googletest/test/googletest-failfast-unittest_.cc b/googletest/test/googletest-failfast-unittest_.cc
new file mode 100644
index 00000000..0b2c951b
--- /dev/null
+++ b/googletest/test/googletest-failfast-unittest_.cc
@@ -0,0 +1,167 @@
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+// Unit test for Google Test test filters.
+//
+// A user can specify which test(s) in a Google Test program to run via
+// either the GTEST_FILTER environment variable or the --gtest_filter
+// flag. This is used for testing such functionality.
+//
+// The program will be invoked from a Python unit test. Don't run it
+// directly.
+
+#include "gtest/gtest.h"
+
+namespace {
+
+// Test HasFixtureTest.
+
+class HasFixtureTest : public testing::Test {};
+
+TEST_F(HasFixtureTest, Test0) {}
+
+TEST_F(HasFixtureTest, Test1) { FAIL() << "Expected failure."; }
+
+TEST_F(HasFixtureTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST_F(HasFixtureTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST_F(HasFixtureTest, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasSimpleTest.
+
+TEST(HasSimpleTest, Test0) {}
+
+TEST(HasSimpleTest, Test1) { FAIL() << "Expected failure."; }
+
+TEST(HasSimpleTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST(HasSimpleTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST(HasSimpleTest, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasDisabledTest.
+
+TEST(HasDisabledTest, Test0) {}
+
+TEST(HasDisabledTest, DISABLED_Test1) { FAIL() << "Expected failure."; }
+
+TEST(HasDisabledTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST(HasDisabledTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST(HasDisabledTest, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasDeathTest
+
+TEST(HasDeathTest, Test0) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
+
+TEST(HasDeathTest, Test1) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+TEST(HasDeathTest, Test2) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+TEST(HasDeathTest, Test3) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+TEST(HasDeathTest, Test4) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+// Test DISABLED_HasDisabledSuite
+
+TEST(DISABLED_HasDisabledSuite, Test0) {}
+
+TEST(DISABLED_HasDisabledSuite, Test1) { FAIL() << "Expected failure."; }
+
+TEST(DISABLED_HasDisabledSuite, Test2) { FAIL() << "Expected failure."; }
+
+TEST(DISABLED_HasDisabledSuite, Test3) { FAIL() << "Expected failure."; }
+
+TEST(DISABLED_HasDisabledSuite, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasParametersTest
+
+class HasParametersTest : public testing::TestWithParam<int> {};
+
+TEST_P(HasParametersTest, Test1) { FAIL() << "Expected failure."; }
+
+TEST_P(HasParametersTest, Test2) { FAIL() << "Expected failure."; }
+
+INSTANTIATE_TEST_SUITE_P(HasParametersSuite, HasParametersTest,
+ testing::Values(1, 2));
+
+class MyTestListener : public ::testing::EmptyTestEventListener {
+ void OnTestSuiteStart(const ::testing::TestSuite& test_suite) override {
+ printf("We are in OnTestSuiteStart of %s.\n", test_suite.name());
+ }
+
+ void OnTestStart(const ::testing::TestInfo& test_info) override {
+ printf("We are in OnTestStart of %s.%s.\n", test_info.test_suite_name(),
+ test_info.name());
+ }
+
+ void OnTestPartResult(
+ const ::testing::TestPartResult& test_part_result) override {
+ printf("We are in OnTestPartResult %s:%d.\n", test_part_result.file_name(),
+ test_part_result.line_number());
+ }
+
+ void OnTestEnd(const ::testing::TestInfo& test_info) override {
+ printf("We are in OnTestEnd of %s.%s.\n", test_info.test_suite_name(),
+ test_info.name());
+ }
+
+ void OnTestSuiteEnd(const ::testing::TestSuite& test_suite) override {
+ printf("We are in OnTestSuiteEnd of %s.\n", test_suite.name());
+ }
+};
+
+TEST(HasSkipTest, Test0) { SUCCEED() << "Expected success."; }
+
+TEST(HasSkipTest, Test1) { GTEST_SKIP() << "Expected skip."; }
+
+TEST(HasSkipTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST(HasSkipTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; }
+
+} // namespace
+
+int main(int argc, char **argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener());
+ return RUN_ALL_TESTS();
+}
diff --git a/ci/log-config.sh b/googletest/test/googletest-global-environment-unittest.py
index 5fef1194..32ba6285 100755..100644
--- a/ci/log-config.sh
+++ b/googletest/test/googletest-global-environment-unittest.py
@@ -1,7 +1,4 @@
-#!/usr/bin/env bash
-# Copyright 2017 Google Inc.
-# All Rights Reserved.
-#
+# Copyright 2021 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
@@ -28,24 +25,48 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+"""Unit test for Google Test's global test environment behavior.
+
+A user can specify a global test environment via
+testing::AddGlobalTestEnvironment. Failures in the global environment should
+result in all unit tests being skipped.
+
+This script tests such functionality by invoking
+googletest-global-environment-unittest_ (a program written with Google Test).
+"""
+
+import gtest_test_utils
+
+
+def RunAndReturnOutput():
+ """Runs the test program and returns its output."""
+
+ return gtest_test_utils.Subprocess([
+ gtest_test_utils.GetTestExecutablePath(
+ 'googletest-global-environment-unittest_')
+ ]).output
+
+
+class GTestGlobalEnvironmentUnitTest(gtest_test_utils.TestCase):
+ """Tests global test environment failures."""
+
+ def testEnvironmentSetUpFails(self):
+ """Tests the behavior of not specifying the fail_fast."""
-set -e
+ # Run the test.
+ txt = RunAndReturnOutput()
-# ccache on OS X needs installation first
-# reset ccache statistics
-ccache --zero-stats
+ # We should see the text of the global environment setup error.
+ self.assertIn('Canned environment setup error', txt)
-echo PATH=${PATH}
+ # Our test should have been skipped due to the error, and not treated as a
+ # pass.
+ self.assertIn('[ SKIPPED ] 1 test', txt)
+ self.assertIn('[ PASSED ] 0 tests', txt)
-echo "Compiler configuration:"
-echo CXX=${CXX}
-echo CC=${CC}
-echo CXXFLAGS=${CXXFLAGS}
+ # The test case shouldn't have been run.
+ self.assertNotIn('Unexpected call', txt)
-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"
+if __name__ == '__main__':
+ gtest_test_utils.Main()
diff --git a/googletest/test/googletest-test2_test.cc b/googletest/test/googletest-global-environment-unittest_.cc
index 2e425dae..f401b2fa 100644
--- a/googletest/test/googletest-test2_test.cc
+++ b/googletest/test/googletest-global-environment-unittest_.cc
@@ -1,4 +1,4 @@
-// Copyright 2008, Google Inc.
+// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
@@ -27,35 +27,32 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Unit test for Google Test global test environments.
//
-// Tests for Google Test itself. This verifies that the basic constructs of
-// Google Test work.
+// The program will be invoked from a Python unit test. Don't run it
+// directly.
#include "gtest/gtest.h"
-#include "googletest-param-test-test.h"
-
-using ::testing::Values;
-using ::testing::internal::ParamGenerator;
-
-// Tests that generators defined in a different translation unit
-// are functional. The test using extern_gen_2 is defined
-// in googletest-param-test-test.cc.
-ParamGenerator<int> extern_gen_2 = Values(33);
-
-// Tests that a parameterized test case can be defined in one translation unit
-// and instantiated in another. The test is defined in
-// googletest-param-test-test.cc and ExternalInstantiationTest fixture class is
-// defined in gtest-param-test_test.h.
-INSTANTIATE_TEST_SUITE_P(MultiplesOf33,
- ExternalInstantiationTest,
- Values(33, 66));
-
-// Tests that a parameterized test case can be instantiated
-// in multiple translation units. Another instantiation is defined
-// in googletest-param-test-test.cc and
-// InstantiationInMultipleTranslationUnitsTest fixture is defined in
-// gtest-param-test_test.h
-INSTANTIATE_TEST_SUITE_P(Sequence2,
- InstantiationInMultipleTranslationUnitsTest,
- Values(42*3, 42*4, 42*5));
+namespace {
+
+// An environment that always fails in its SetUp method.
+class FailingEnvironment final : public ::testing::Environment {
+ public:
+ void SetUp() override { FAIL() << "Canned environment setup error"; }
+};
+
+// Register the environment.
+auto* const g_environment_ =
+ ::testing::AddGlobalTestEnvironment(new FailingEnvironment);
+
+// A test that doesn't actually run.
+TEST(SomeTest, DoesFoo) { FAIL() << "Unexpected call"; }
+
+} // namespace
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/googletest/test/googletest-json-output-unittest.py b/googletest/test/googletest-json-output-unittest.py
index 15861f75..41c85651 100644
--- a/googletest/test/googletest-json-output-unittest.py
+++ b/googletest/test/googletest-json-output-unittest.py
@@ -58,9 +58,9 @@ else:
EXPECTED_NON_EMPTY = {
u'tests':
- 24,
+ 26,
u'failures':
- 4,
+ 5,
u'disabled':
2,
u'errors':
@@ -158,9 +158,9 @@ EXPECTED_NON_EMPTY = {
u'name':
u'SkippedTest',
u'tests':
- 1,
+ 3,
u'failures':
- 0,
+ 1,
u'disabled':
0,
u'errors':
@@ -176,6 +176,32 @@ EXPECTED_NON_EMPTY = {
u'time': u'*',
u'timestamp': u'*',
u'classname': u'SkippedTest'
+ }, {
+ u'name': u'SkippedWithMessage',
+ u'status': u'RUN',
+ u'result': u'SKIPPED',
+ u'time': u'*',
+ u'timestamp': u'*',
+ u'classname': u'SkippedTest'
+ }, {
+ u'name':
+ u'SkippedAfterFailure',
+ u'status':
+ u'RUN',
+ u'result':
+ u'COMPLETED',
+ u'time':
+ u'*',
+ u'timestamp':
+ u'*',
+ u'classname':
+ u'SkippedTest',
+ u'failures': [{
+ u'failure': u'gtest_xml_output_unittest_.cc:*\n'
+ u'Expected equality of these values:\n'
+ u' 1\n 2' + STACK_TRACE_TEMPLATE,
+ u'type': u''
+ }]
}]
}, {
u'name':
@@ -586,15 +612,59 @@ EXPECTED_FILTERED = {
}],
}
-EXPECTED_EMPTY = {
- u'tests': 0,
- u'failures': 0,
- u'disabled': 0,
- u'errors': 0,
- u'time': u'*',
- u'timestamp': u'*',
- u'name': u'AllTests',
- u'testsuites': [],
+EXPECTED_NO_TEST = {
+ u'tests':
+ 0,
+ u'failures':
+ 0,
+ u'disabled':
+ 0,
+ u'errors':
+ 0,
+ u'time':
+ u'*',
+ u'timestamp':
+ u'*',
+ u'name':
+ u'AllTests',
+ u'testsuites': [{
+ u'name':
+ u'NonTestSuiteFailure',
+ u'tests':
+ 1,
+ u'failures':
+ 1,
+ u'disabled':
+ 0,
+ u'skipped':
+ 0,
+ u'errors':
+ 0,
+ u'time':
+ u'*',
+ u'timestamp':
+ u'*',
+ u'testsuite': [{
+ u'name':
+ u'',
+ u'status':
+ u'RUN',
+ u'result':
+ u'COMPLETED',
+ u'time':
+ u'*',
+ u'timestamp':
+ u'*',
+ u'classname':
+ u'',
+ u'failures': [{
+ u'failure': u'gtest_no_test_unittest.cc:*\n'
+ u'Expected equality of these values:\n'
+ u' 1\n 2' + STACK_TRACE_TEMPLATE,
+ u'type': u'',
+ }]
+ }]
+ }],
}
GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
@@ -619,14 +689,14 @@ class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
"""
self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1)
- def testEmptyJsonOutput(self):
+ def testNoTestJsonOutput(self):
"""Verifies JSON output for a Google Test binary without actual tests.
- Runs a test program that generates an empty JSON output, and
- tests that the JSON output is expected.
+ Runs a test program that generates an JSON output for a binary with no
+ tests, and tests that the JSON output is expected.
"""
- self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_EMPTY, 0)
+ self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_NO_TEST, 0)
def testTimestampValue(self):
"""Checks whether the timestamp attribute in the JSON output is valid.
diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc
index 2b959c26..c09d5723 100644
--- a/googletest/test/googletest-options-test.cc
+++ b/googletest/test/googletest-options-test.cc
@@ -42,6 +42,9 @@
# include <windows.h>
#elif GTEST_OS_WINDOWS
# include <direct.h>
+#elif GTEST_OS_OS2
+// For strcasecmp on OS/2
+#include <strings.h>
#endif // GTEST_OS_WINDOWS_MOBILE
#include "src/gtest-internal-inl.h"
diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt
index c1db004c..3fab3b97 100644
--- a/googletest/test/googletest-output-test-golden-lin.txt
+++ b/googletest/test/googletest-output-test-golden-lin.txt
@@ -12,7 +12,7 @@ Expected equality of these values:
3
Stack trace: (omitted)
-[==========] Running 87 tests from 41 test suites.
+[==========] Running 88 tests from 41 test suites.
[----------] Global test environment set-up.
FooEnvironment::SetUp() called.
BarEnvironment::SetUp() called.
@@ -982,17 +982,43 @@ Expected failure
Stack trace: (omitted)
[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
-[----------] 2 tests from GoogleTestVerification
-[ RUN ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<DetectNotInstantiatedTest>
-Paramaterized test suite DetectNotInstantiatedTest is defined via TEST_P, but never instantiated. None of the test cases will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only ones provided expand to nothing.
+[----------] 3 tests from GoogleTestVerification
+[ RUN ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>
+googletest-output-test_.cc:#: Failure
+Parameterized test suite NoTests is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are defined via TEST_P . No test cases will run.
+
+Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from code that always depend on code that provides TEST_P. Failing to do so is often an indication of dead code, e.g. the last TEST_P was removed but the rest got left behind.
+
+To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NoTests);
+Stack trace: (omitted)
+
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>
+[ RUN ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>
+googletest-output-test_.cc:#: Failure
+Parameterized test suite DetectNotInstantiatedTest is defined via TEST_P, but never instantiated. None of the test cases will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only ones provided expand to nothing.
Ideally, TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)
-[ OK ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<DetectNotInstantiatedTest>
-[ RUN ] GoogleTestVerification.UninstantiatedTypeParamaterizedTestSuite<DetectNotInstantiatedTypesTest>
-Type paramaterized test suite DetectNotInstantiatedTypesTest is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run.
+
+To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTest);
+Stack trace: (omitted)
+
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>
+[ RUN ] GoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
+googletest-output-test_.cc:#: Failure
+Type parameterized test suite DetectNotInstantiatedTypesTest is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run.
Ideally, TYPED_TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)
-[ OK ] GoogleTestVerification.UninstantiatedTypeParamaterizedTestSuite<DetectNotInstantiatedTypesTest>
+
+To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTypesTest);
+Stack trace: (omitted)
+
+[ FAILED ] GoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
[----------] Global test environment tear-down
BarEnvironment::TearDown() called.
googletest-output-test_.cc:#: Failure
@@ -1006,9 +1032,9 @@ Failed
Expected fatal failure.
Stack trace: (omitted)
-[==========] 87 tests from 41 test suites ran.
-[ PASSED ] 33 tests.
-[ FAILED ] 54 tests, listed below:
+[==========] 88 tests from 41 test suites ran.
+[ PASSED ] 31 tests.
+[ FAILED ] 57 tests, listed below:
[ FAILED ] NonfatalFailureTest.EscapesStringOperands
[ FAILED ] NonfatalFailureTest.DiffForLongStrings
[ FAILED ] FatalFailureTest.FatalFailureInSubroutine
@@ -1063,8 +1089,11 @@ Stack trace: (omitted)
[ FAILED ] BadDynamicFixture2.Derived
[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>
+[ FAILED ] GoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>
+[ FAILED ] GoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>
-54 FAILED TESTS
+57 FAILED TESTS
 YOU HAVE 1 DISABLED TEST
Note: Google Test filter = FatalFailureTest.*:LoggingTest.*
diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc
index b1d66f9f..074f64ef 100644
--- a/googletest/test/googletest-output-test_.cc
+++ b/googletest/test/googletest-output-test_.cc
@@ -476,63 +476,6 @@ TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
GTEST_FAIL_AT("foo.cc", 42) << "Expected fatal failure in foo.cc";
}
-#if GTEST_IS_THREADSAFE
-
-// A unary function that may die.
-void DieIf(bool should_die) {
- GTEST_CHECK_(!should_die) << " - death inside DieIf().";
-}
-
-// Tests running death tests in a multi-threaded context.
-
-// Used for coordination between the main and the spawn thread.
-struct SpawnThreadNotifications {
- SpawnThreadNotifications() {}
-
- Notification spawn_thread_started;
- Notification spawn_thread_ok_to_terminate;
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications);
-};
-
-// The function to be executed in the thread spawn by the
-// MultipleThreads test (below).
-static void ThreadRoutine(SpawnThreadNotifications* notifications) {
- // Signals the main thread that this thread has started.
- notifications->spawn_thread_started.Notify();
-
- // Waits for permission to finish from the main thread.
- notifications->spawn_thread_ok_to_terminate.WaitForNotification();
-}
-
-// This is a death-test test, but it's not named with a DeathTest
-// suffix. It starts threads which might interfere with later
-// death tests, so it must run after all other death tests.
-class DeathTestAndMultiThreadsTest : public testing::Test {
- protected:
- // Starts a thread and waits for it to begin.
- void SetUp() override {
- thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>(
- &ThreadRoutine, &notifications_, nullptr));
- notifications_.spawn_thread_started.WaitForNotification();
- }
- // Tells the thread to finish, and reaps it.
- // Depending on the version of the thread library in use,
- // a manager thread might still be left running that will interfere
- // with later death tests. This is unfortunate, but this class
- // cleans up after itself as best it can.
- void TearDown() override {
- notifications_.spawn_thread_ok_to_terminate.Notify();
- }
-
- private:
- SpawnThreadNotifications notifications_;
- std::unique_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_;
-};
-
-#endif // GTEST_IS_THREADSAFE
-
// The MixedUpTestSuiteTest test case verifies that Google Test will fail a
// test if it uses a different fixture class than what other tests in
// the same test case use. It deliberately contains two fixture
@@ -790,6 +733,10 @@ INSTANTIATE_TEST_SUITE_P(PrintingStrings,
testing::Values(std::string("a")),
ParamNameFunc);
+// The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.
+using NoTests = ParamTest;
+INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello"));
+
// fails under kErrorOnUninstantiatedParameterizedTest=true
class DetectNotInstantiatedTest : public testing::TestWithParam<int> {};
TEST_P(DetectNotInstantiatedTest, Used) { }
@@ -797,9 +744,6 @@ TEST_P(DetectNotInstantiatedTest, Used) { }
// This would make the test failure from the above go away.
// INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));
-// This #ifdef block tests the output of typed tests.
-#if GTEST_HAS_TYPED_TEST
-
template <typename T>
class TypedTest : public testing::Test {
};
@@ -836,11 +780,6 @@ TYPED_TEST(TypedTestWithNames, Success) {}
TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
-#endif // GTEST_HAS_TYPED_TEST
-
-// This #ifdef block tests the output of type-parameterized tests.
-#if GTEST_HAS_TYPED_TEST_P
-
template <typename T>
class TypedTestP : public testing::Test {
};
@@ -891,8 +830,6 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
// typedef ::testing::Types<char, int, unsigned int> MyTypes;
// INSTANTIATE_TYPED_TEST_SUITE_P(All, DetectNotInstantiatedTypesTest, MyTypes);
-#endif // GTEST_HAS_TYPED_TEST_P
-
#if GTEST_HAS_DEATH_TEST
// We rely on the golden file to verify that tests whose test case
@@ -901,8 +838,6 @@ REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
TEST(ADeathTest, ShouldRunFirst) {
}
-# if GTEST_HAS_TYPED_TEST
-
// We rely on the golden file to verify that typed tests whose test
// case name ends with DeathTest are run first.
@@ -916,10 +851,6 @@ TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes);
TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {
}
-# endif // GTEST_HAS_TYPED_TEST
-
-# if GTEST_HAS_TYPED_TEST_P
-
// We rely on the golden file to verify that type-parameterized tests
// whose test case name ends with DeathTest are run first.
@@ -937,8 +868,6 @@ REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst);
INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);
-# endif // GTEST_HAS_TYPED_TEST_P
-
#endif // GTEST_HAS_DEATH_TEST
// Tests various failure conditions of
@@ -1100,7 +1029,7 @@ auto dynamic_test = (
"BadDynamicFixture1", "TestBase", nullptr, nullptr, __FILE__, __LINE__,
[]() -> testing::Test* { return new DynamicTest<true>; }),
- // Register two tests with the same fixture incorrectly by ommiting the
+ // Register two tests with the same fixture incorrectly by omitting the
// return type.
testing::RegisterTest(
"BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__,
diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc
index f92eb316..023aa46d 100644
--- a/googletest/test/googletest-param-test-test.cc
+++ b/googletest/test/googletest-param-test-test.cc
@@ -490,16 +490,17 @@ TEST(CombineTest, CombineWithMaxNumberOfParameters) {
class NonDefaultConstructAssignString {
public:
NonDefaultConstructAssignString(const std::string& s) : str_(s) {}
+ NonDefaultConstructAssignString() = delete;
+ NonDefaultConstructAssignString(const NonDefaultConstructAssignString&) =
+ default;
+ NonDefaultConstructAssignString& operator=(
+ const NonDefaultConstructAssignString&) = delete;
+ ~NonDefaultConstructAssignString() = default;
const std::string& str() const { return str_; }
private:
std::string str_;
-
- // Not default constructible
- NonDefaultConstructAssignString();
- // Not assignable
- void operator=(const NonDefaultConstructAssignString&);
};
TEST(CombineTest, NonDefaultConstructAssign) {
@@ -834,14 +835,14 @@ TEST(MacroNameing, LookupNames) {
}
}
- // Check that the expected form of the test suit name actualy exists.
+ // Check that the expected form of the test suit name actually exists.
EXPECT_NE( //
know_suite_names.find("FortyTwo/MacroNamingTest"),
know_suite_names.end());
EXPECT_NE(
know_suite_names.find("MacroNamingTestNonParametrized"),
know_suite_names.end());
- // Check that the expected form of the test name actualy exists.
+ // Check that the expected form of the test name actually exists.
EXPECT_NE( //
know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"),
know_test_names.end());
@@ -1077,6 +1078,27 @@ class NotUsedTest : public testing::TestWithParam<int> {};
template <typename T>
class NotUsedTypeTest : public testing::Test {};
TYPED_TEST_SUITE_P(NotUsedTypeTest);
+
+// Used but not instantiated, this would fail. but...
+class NotInstantiatedTest : public testing::TestWithParam<int> {};
+// ... we mark is as allowed.
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest);
+
+TEST_P(NotInstantiatedTest, Used) { }
+
+using OtherName = NotInstantiatedTest;
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName);
+TEST_P(OtherName, Used) { }
+
+// Used but not instantiated, this would fail. but...
+template <typename T>
+class NotInstantiatedTypeTest : public testing::Test {};
+TYPED_TEST_SUITE_P(NotInstantiatedTypeTest);
+// ... we mark is as allowed.
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest);
+
+TYPED_TEST_P(NotInstantiatedTypeTest, Used) { }
+REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used);
} // namespace works_here
int main(int argc, char **argv) {
diff --git a/googletest/test/googletest-param-test-test.h b/googletest/test/googletest-param-test-test.h
index 64805701..89193753 100644
--- a/googletest/test/googletest-param-test-test.h
+++ b/googletest/test/googletest-param-test-test.h
@@ -32,8 +32,8 @@
// This header file provides classes and functions used internally
// for testing Google Test itself.
-#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
-#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
+#ifndef GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_
+#define GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_
#include "gtest/gtest.h"
@@ -48,4 +48,4 @@ class InstantiationInMultipleTranslationUnitsTest
: public ::testing::TestWithParam<int> {
};
-#endif // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
+#endif // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_
diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc
index 60d637c3..1e0c8616 100644
--- a/googletest/test/googletest-port-test.cc
+++ b/googletest/test/googletest-port-test.cc
@@ -90,10 +90,10 @@ TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
class Base {
public:
- // Copy constructor and assignment operator do exactly what we need, so we
- // use them.
Base() : member_(0) {}
explicit Base(int n) : member_(n) {}
+ Base(const Base&) = default;
+ Base& operator=(const Base&) = default;
virtual ~Base() {}
int member() { return member_; }
@@ -201,6 +201,13 @@ TEST(ImplicitCastTest, CanUseImplicitConstructor) {
EXPECT_TRUE(converted);
}
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
if (AlwaysFalse())
GTEST_CHECK_(false) << "This should never be executed; "
@@ -216,6 +223,9 @@ TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
else
GTEST_CHECK_(true) << "";
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
switch (0) {
@@ -363,8 +373,6 @@ TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
#if GTEST_USES_POSIX_RE
-# if GTEST_HAS_TYPED_TEST
-
template <typename Str>
class RETest : public ::testing::Test {};
@@ -420,8 +428,6 @@ TYPED_TEST(RETest, PartialMatchWorks) {
EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
}
-# endif // GTEST_HAS_TYPED_TEST
-
#elif GTEST_USES_SIMPLE_RE
TEST(IsInSetTest, NulCharIsNotInAnySet) {
@@ -1180,8 +1186,6 @@ class DestructorTracker {
return DestructorCall::List().size() - 1;
}
const size_t index_;
-
- GTEST_DISALLOW_ASSIGN_(DestructorTracker);
};
typedef ThreadLocal<DestructorTracker>* ThreadParam;
diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc
index bf37fb45..e1e8e1c7 100644
--- a/googletest/test/googletest-printers-test.cc
+++ b/googletest/test/googletest-printers-test.cc
@@ -32,15 +32,16 @@
//
// This file tests the universal value printer.
-#include <ctype.h>
-#include <string.h>
#include <algorithm>
+#include <cctype>
#include <cstdint>
+#include <cstring>
#include <deque>
#include <forward_list>
#include <limits>
#include <list>
#include <map>
+#include <memory>
#include <set>
#include <sstream>
#include <string>
@@ -90,6 +91,18 @@ class BiggestIntConvertible {
operator ::testing::internal::BiggestInt() const { return 42; }
};
+// A parent class with two child classes. The parent and one of the kids have
+// stream operators.
+class ParentClass {};
+class ChildClassWithStreamOperator : public ParentClass {};
+class ChildClassWithoutStreamOperator : public ParentClass {};
+static void operator<<(std::ostream& os, const ParentClass&) {
+ os << "ParentClass";
+}
+static void operator<<(std::ostream& os, const ChildClassWithStreamOperator&) {
+ os << "ChildClassWithStreamOperator";
+}
+
// A user-defined unprintable class template in the global namespace.
template <typename T>
class UnprintableTemplateInGlobal {
@@ -177,7 +190,18 @@ inline ::std::ostream& operator<<(::std::ostream& os,
return os << "StreamableTemplateInFoo: " << x.value();
}
-// A user-defined streamable but recursivly-defined container type in
+// A user-defined streamable type in a user namespace whose operator<< is
+// templated on the type of the output stream.
+struct TemplatedStreamableInFoo {};
+
+template <typename OutputStream>
+OutputStream& operator<<(OutputStream& os,
+ const TemplatedStreamableInFoo& /*ts*/) {
+ os << "TemplatedStreamableInFoo";
+ return os;
+}
+
+// A user-defined streamable but recursively-defined container type in
// a user namespace, it mimics therefore std::filesystem::path or
// boost::filesystem::path.
class PathLike {
@@ -205,6 +229,33 @@ class PathLike {
} // namespace foo
namespace testing {
+namespace {
+template <typename T>
+class Wrapper {
+ public:
+ explicit Wrapper(T&& value) : value_(std::forward<T>(value)) {}
+
+ const T& value() const { return value_; }
+
+ private:
+ T value_;
+};
+
+} // namespace
+
+namespace internal {
+template <typename T>
+class UniversalPrinter<Wrapper<T>> {
+ public:
+ static void Print(const Wrapper<T>& w, ::std::ostream* os) {
+ *os << "Wrapper(";
+ UniversalPrint(w.value(), os);
+ *os << ')';
+ }
+};
+} // namespace internal
+
+
namespace gtest_printers_test {
using ::std::deque;
@@ -310,6 +361,20 @@ TEST(PrintCharTest, UnsignedChar) {
Print(static_cast<unsigned char>('b')));
}
+TEST(PrintCharTest, Char16) {
+ EXPECT_EQ("U+0041", Print(u'A'));
+}
+
+TEST(PrintCharTest, Char32) {
+ EXPECT_EQ("U+0041", Print(U'A'));
+}
+
+#ifdef __cpp_char8_t
+TEST(PrintCharTest, Char8) {
+ EXPECT_EQ("U+0041", Print(u8'A'));
+}
+#endif
+
// Tests printing other simple, built-in types.
// bool.
@@ -359,6 +424,20 @@ TEST(PrintBuiltInTypeTest, Integer) {
Print(std::numeric_limits<uint64_t>::max())); // uint64
EXPECT_EQ("-9223372036854775808",
Print(std::numeric_limits<int64_t>::min())); // int64
+#ifdef __cpp_char8_t
+ EXPECT_EQ("U+0000",
+ Print(std::numeric_limits<char8_t>::min())); // char8_t
+ EXPECT_EQ("U+00FF",
+ Print(std::numeric_limits<char8_t>::max())); // char8_t
+#endif
+ EXPECT_EQ("U+0000",
+ Print(std::numeric_limits<char16_t>::min())); // char16_t
+ EXPECT_EQ("U+FFFF",
+ Print(std::numeric_limits<char16_t>::max())); // char16_t
+ EXPECT_EQ("U+0000",
+ Print(std::numeric_limits<char32_t>::min())); // char32_t
+ EXPECT_EQ("U+FFFFFFFF",
+ Print(std::numeric_limits<char32_t>::max())); // char32_t
}
// Size types.
@@ -414,6 +493,92 @@ TEST(PrintCStringTest, EscapesProperly) {
Print(p));
}
+#ifdef __cpp_char8_t
+// const char8_t*.
+TEST(PrintU8StringTest, Const) {
+ const char8_t* p = u8"界";
+ EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE7\\x95\\x8C\"", Print(p));
+}
+
+// char8_t*.
+TEST(PrintU8StringTest, NonConst) {
+ char8_t p[] = u8"世";
+ EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE4\\xB8\\x96\"",
+ Print(static_cast<char8_t*>(p)));
+}
+
+// NULL u8 string.
+TEST(PrintU8StringTest, Null) {
+ const char8_t* p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// Tests that u8 strings are escaped properly.
+TEST(PrintU8StringTest, EscapesProperly) {
+ const char8_t* p = u8"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
+ EXPECT_EQ(PrintPointer(p) +
+ " pointing to u8\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
+ "hello \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
+ Print(p));
+}
+#endif
+
+// const char16_t*.
+TEST(PrintU16StringTest, Const) {
+ const char16_t* p = u"界";
+ EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x754C\"", Print(p));
+}
+
+// char16_t*.
+TEST(PrintU16StringTest, NonConst) {
+ char16_t p[] = u"世";
+ EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x4E16\"",
+ Print(static_cast<char16_t*>(p)));
+}
+
+// NULL u16 string.
+TEST(PrintU16StringTest, Null) {
+ const char16_t* p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// Tests that u16 strings are escaped properly.
+TEST(PrintU16StringTest, EscapesProperly) {
+ const char16_t* p = u"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 世界";
+ EXPECT_EQ(PrintPointer(p) +
+ " pointing to u\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
+ "hello \\x4E16\\x754C\"",
+ Print(p));
+}
+
+// const char32_t*.
+TEST(PrintU32StringTest, Const) {
+ const char32_t* p = U"🗺️";
+ EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F5FA\\xFE0F\"", Print(p));
+}
+
+// char32_t*.
+TEST(PrintU32StringTest, NonConst) {
+ char32_t p[] = U"🌌";
+ EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F30C\"",
+ Print(static_cast<char32_t*>(p)));
+}
+
+// NULL u32 string.
+TEST(PrintU32StringTest, Null) {
+ const char32_t* p = nullptr;
+ EXPECT_EQ("NULL", Print(p));
+}
+
+// Tests that u32 strings are escaped properly.
+TEST(PrintU32StringTest, EscapesProperly) {
+ const char32_t* p = U"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello 🗺️";
+ EXPECT_EQ(PrintPointer(p) +
+ " pointing to U\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
+ "hello \\x1F5FA\\xFE0F\"",
+ Print(p));
+}
+
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
@@ -624,21 +789,66 @@ TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
}
-// const char array with terminating NUL.
-TEST(PrintArrayTest, ConstCharArrayWithTerminatingNul) {
+// char array with terminating NUL.
+TEST(PrintArrayTest, CharArrayWithTerminatingNul) {
const char a[] = "\0Hi";
EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
}
-// const wchar_t array without terminating NUL.
+#ifdef __cpp_char8_t
+// char_t array without terminating NUL.
+TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
+ // Array a contains '\0' in the middle and doesn't end with '\0'.
+ const char8_t a[] = {u8'H', u8'\0', u8'i'};
+ EXPECT_EQ("u8\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
+}
+
+// char8_t array with terminating NUL.
+TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
+ const char8_t a[] = u8"\0世界";
+ EXPECT_EQ(
+ "u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
+ PrintArrayHelper(a));
+}
+#endif
+
+// const char16_t array without terminating NUL.
+TEST(PrintArrayTest, Char16ArrayWithNoTerminatingNul) {
+ // Array a contains '\0' in the middle and doesn't end with '\0'.
+ const char16_t a[] = {u'こ', u'\0', u'ん', u'に', u'ち', u'は'};
+ EXPECT_EQ("u\"\\x3053\\0\\x3093\\x306B\\x3061\\x306F\" (no terminating NUL)",
+ PrintArrayHelper(a));
+}
+
+// char16_t array with terminating NUL.
+TEST(PrintArrayTest, Char16ArrayWithTerminatingNul) {
+ const char16_t a[] = u"\0こんにちは";
+ EXPECT_EQ("u\"\\0\\x3053\\x3093\\x306B\\x3061\\x306F\"", PrintArrayHelper(a));
+}
+
+// char32_t array without terminating NUL.
+TEST(PrintArrayTest, Char32ArrayWithNoTerminatingNul) {
+ // Array a contains '\0' in the middle and doesn't end with '\0'.
+ const char32_t a[] = {U'👋', U'\0', U'🌌'};
+ EXPECT_EQ("U\"\\x1F44B\\0\\x1F30C\" (no terminating NUL)",
+ PrintArrayHelper(a));
+}
+
+// char32_t array with terminating NUL.
+TEST(PrintArrayTest, Char32ArrayWithTerminatingNul) {
+ const char32_t a[] = U"\0👋🌌";
+ EXPECT_EQ("U\"\\0\\x1F44B\\x1F30C\"", PrintArrayHelper(a));
+}
+
+// wchar_t array without terminating NUL.
TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
// Array a contains '\0' in the middle and doesn't end with '\0'.
- const wchar_t a[] = { L'H', L'\0', L'i' };
+ const wchar_t a[] = {L'H', L'\0', L'i'};
EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
}
// wchar_t array with terminating NUL.
-TEST(PrintArrayTest, WConstCharArrayWithTerminatingNul) {
+TEST(PrintArrayTest, WCharArrayWithTerminatingNul) {
const wchar_t a[] = L"\0Hi";
EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
}
@@ -702,6 +912,26 @@ TEST(PrintWideStringTest, StringAmbiguousHex) {
}
#endif // GTEST_HAS_STD_WSTRING
+#ifdef __cpp_char8_t
+TEST(PrintStringTest, U8String) {
+ std::u8string str = u8"Hello, 世界";
+ EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
+ EXPECT_EQ("u8\"Hello, \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", Print(str));
+}
+#endif
+
+TEST(PrintStringTest, U16String) {
+ std::u16string str = u"Hello, 世界";
+ EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type.
+ EXPECT_EQ("u\"Hello, \\x4E16\\x754C\"", Print(str));
+}
+
+TEST(PrintStringTest, U32String) {
+ std::u32string str = U"Hello, 🗺️";
+ EXPECT_EQ(str, str); // Verify EXPECT_EQ compiles with this type
+ EXPECT_EQ("U\"Hello, \\x1F5FA\\xFE0F\"", Print(str));
+}
+
// Tests printing types that support generic streaming (i.e. streaming
// to std::basic_ostream<Char, CharTraits> for any valid Char and
// CharTraits types).
@@ -760,22 +990,22 @@ TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
}
-#if GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_STRING_VIEW
-// Tests printing ::absl::string_view.
+// Tests printing internal::StringView.
TEST(PrintStringViewTest, SimpleStringView) {
- const ::absl::string_view sp = "Hello";
+ const internal::StringView sp = "Hello";
EXPECT_EQ("\"Hello\"", Print(sp));
}
TEST(PrintStringViewTest, UnprintableCharacters) {
const char str[] = "NUL (\0) and \r\t";
- const ::absl::string_view sp(str, sizeof(str) - 1);
+ const internal::StringView sp(str, sizeof(str) - 1);
EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Tests printing STL containers.
@@ -1065,6 +1295,20 @@ TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
Print(::foo::StreamableTemplateInFoo<int>()));
}
+TEST(PrintStreamableTypeTest, TypeInUserNamespaceWithTemplatedStreamOperator) {
+ EXPECT_EQ("TemplatedStreamableInFoo",
+ Print(::foo::TemplatedStreamableInFoo()));
+}
+
+TEST(PrintStreamableTypeTest, SubclassUsesSuperclassStreamOperator) {
+ ParentClass parent;
+ ChildClassWithStreamOperator child_stream;
+ ChildClassWithoutStreamOperator child_no_stream;
+ EXPECT_EQ("ParentClass", Print(parent));
+ EXPECT_EQ("ChildClassWithStreamOperator", Print(child_stream));
+ EXPECT_EQ("ParentClass", Print(child_no_stream));
+}
+
// Tests printing a user-defined recursive container type that has a <<
// operator.
TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
@@ -1473,6 +1717,13 @@ TEST(UniversalPrintTest, WorksForReference) {
EXPECT_EQ("123", ss.str());
}
+TEST(UniversalPrintTest, WorksForPairWithConst) {
+ std::pair<const Wrapper<std::string>, int> p(Wrapper<std::string>("abc"), 1);
+ ::std::stringstream ss;
+ UniversalPrint(p, &ss);
+ EXPECT_EQ("(Wrapper(\"abc\"), 1)", ss.str());
+}
+
TEST(UniversalPrintTest, WorksForCString) {
const char* s1 = "abc";
::std::stringstream ss1;
@@ -1502,6 +1753,63 @@ TEST(UniversalPrintTest, WorksForCharArray) {
EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
}
+TEST(UniversalPrintTest, IncompleteType) {
+ struct Incomplete;
+ char some_object = 0;
+ EXPECT_EQ("(incomplete type)",
+ PrintToString(reinterpret_cast<Incomplete&>(some_object)));
+}
+
+TEST(UniversalPrintTest, SmartPointers) {
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
+ std::unique_ptr<int> p(new int(17));
+ EXPECT_EQ("(ptr = " + PrintPointer(p.get()) + ", value = 17)",
+ PrintToString(p));
+ std::unique_ptr<int[]> p2(new int[2]);
+ EXPECT_EQ("(" + PrintPointer(p2.get()) + ")", PrintToString(p2));
+
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
+ std::shared_ptr<int> p3(new int(1979));
+ EXPECT_EQ("(ptr = " + PrintPointer(p3.get()) + ", value = 1979)",
+ PrintToString(p3));
+#if __cpp_lib_shared_ptr_arrays >= 201611L
+ std::shared_ptr<int[]> p4(new int[2]);
+ EXPECT_EQ("(" + PrintPointer(p4.get()) + ")", PrintToString(p4));
+#endif
+
+ // modifiers
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile const int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int[]>()));
+ EXPECT_EQ("(nullptr)",
+ PrintToString(std::unique_ptr<volatile const int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile const int>()));
+#if __cpp_lib_shared_ptr_arrays >= 201611L
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int[]>()));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int[]>()));
+ EXPECT_EQ("(nullptr)",
+ PrintToString(std::shared_ptr<volatile const int[]>()));
+#endif
+
+ // void
+ EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<void, void (*)(void*)>(
+ nullptr, nullptr)));
+ EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
+ PrintToString(
+ std::unique_ptr<void, void (*)(void*)>(p.get(), [](void*) {})));
+ EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<void>()));
+ EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
+ PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));
+}
+
TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
EXPECT_EQ(0u, result.size());
@@ -1531,32 +1839,65 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
EXPECT_EQ("\"a\"", result[1]);
}
-#if GTEST_HAS_ABSL
+#if GTEST_INTERNAL_HAS_ANY
+class PrintAnyTest : public ::testing::Test {
+ protected:
+ template <typename T>
+ static std::string ExpectedTypeName() {
+#if GTEST_HAS_RTTI
+ return internal::GetTypeName<T>();
+#else
+ return "<unknown_type>";
+#endif // GTEST_HAS_RTTI
+ }
+};
+
+TEST_F(PrintAnyTest, Empty) {
+ internal::Any any;
+ EXPECT_EQ("no value", PrintToString(any));
+}
+
+TEST_F(PrintAnyTest, NonEmpty) {
+ internal::Any any;
+ constexpr int val1 = 10;
+ const std::string val2 = "content";
+
+ any = val1;
+ EXPECT_EQ("value of type " + ExpectedTypeName<int>(), PrintToString(any));
+
+ any = val2;
+ EXPECT_EQ("value of type " + ExpectedTypeName<std::string>(),
+ PrintToString(any));
+}
+#endif // GTEST_INTERNAL_HAS_ANY
+#if GTEST_INTERNAL_HAS_OPTIONAL
TEST(PrintOptionalTest, Basic) {
- absl::optional<int> value;
+ internal::Optional<int> value;
EXPECT_EQ("(nullopt)", PrintToString(value));
value = {7};
EXPECT_EQ("(7)", PrintToString(value));
- EXPECT_EQ("(1.1)", PrintToString(absl::optional<double>{1.1}));
- EXPECT_EQ("(\"A\")", PrintToString(absl::optional<std::string>{"A"}));
+ EXPECT_EQ("(1.1)", PrintToString(internal::Optional<double>{1.1}));
+ EXPECT_EQ("(\"A\")", PrintToString(internal::Optional<std::string>{"A"}));
}
+#endif // GTEST_INTERNAL_HAS_OPTIONAL
+#if GTEST_INTERNAL_HAS_VARIANT
struct NonPrintable {
unsigned char contents = 17;
};
TEST(PrintOneofTest, Basic) {
- using Type = absl::variant<int, StreamableInGlobal, NonPrintable>;
- EXPECT_EQ("('int' with value 7)", PrintToString(Type(7)));
- EXPECT_EQ("('StreamableInGlobal' with value StreamableInGlobal)",
+ using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;
+ EXPECT_EQ("('int(index = 0)' with value 7)", PrintToString(Type(7)));
+ EXPECT_EQ("('StreamableInGlobal(index = 1)' with value StreamableInGlobal)",
PrintToString(Type(StreamableInGlobal{})));
EXPECT_EQ(
- "('testing::gtest_printers_test::NonPrintable' with value 1-byte object "
- "<11>)",
+ "('testing::gtest_printers_test::NonPrintable(index = 2)' with value "
+ "1-byte object <11>)",
PrintToString(Type(NonPrintable{})));
}
-#endif // GTEST_HAS_ABSL
+#endif // GTEST_INTERNAL_HAS_VARIANT
namespace {
class string_ref;
diff --git a/googletest/test/googletest-shuffle-test_.cc b/googletest/test/googletest-shuffle-test_.cc
index c1fc1066..4505663a 100644
--- a/googletest/test/googletest-shuffle-test_.cc
+++ b/googletest/test/googletest-shuffle-test_.cc
@@ -82,7 +82,7 @@ class TestNamePrinter : public EmptyTestEventListener {
}
void OnTestStart(const TestInfo& test_info) override {
- printf("%s.%s\n", test_info.test_case_name(), test_info.name());
+ printf("%s.%s\n", test_info.test_suite_name(), test_info.name());
}
};
diff --git a/googletest/test/gtest-typed-test2_test.cc b/googletest/test/gtest-typed-test2_test.cc
index 70001604..e83ca2e1 100644
--- a/googletest/test/gtest-typed-test2_test.cc
+++ b/googletest/test/gtest-typed-test2_test.cc
@@ -33,12 +33,8 @@
#include "test/gtest-typed-test_test.h"
#include "gtest/gtest.h"
-#if GTEST_HAS_TYPED_TEST_P
-
// Tests that the same type-parameterized test case can be
// instantiated in different translation units linked together.
// (ContainerTest is also instantiated in gtest-typed-test_test.cc.)
INSTANTIATE_TYPED_TEST_SUITE_P(Vector, ContainerTest,
testing::Types<std::vector<int> >);
-
-#endif // GTEST_HAS_TYPED_TEST_P
diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc
index 0c1f660f..5fc678cb 100644
--- a/googletest/test/gtest-typed-test_test.cc
+++ b/googletest/test/gtest-typed-test_test.cc
@@ -88,9 +88,6 @@ class CommonTest : public Test {
template <typename T>
T* CommonTest<T>::shared_ = nullptr;
-// This #ifdef block tests typed tests.
-#if GTEST_HAS_TYPED_TEST
-
using testing::Types;
// Tests that SetUpTestSuite()/TearDownTestSuite(), fixture ctor/dtor,
@@ -193,22 +190,17 @@ TYPED_TEST(TypedTestWithNames, TestSuiteName) {
if (std::is_same<TypeParam, char>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"TypedTestWithNames/char0");
}
if (std::is_same<TypeParam, int>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"TypedTestWithNames/int1");
}
}
-#endif // GTEST_HAS_TYPED_TEST
-
-// This #ifdef block tests type-parameterized tests.
-#if GTEST_HAS_TYPED_TEST_P
-
using testing::Types;
using testing::internal::TypedTestSuitePState;
@@ -315,13 +307,13 @@ TYPED_TEST_P(TypeParametrizedTestWithNames, TestSuiteName) {
if (std::is_same<TypeParam, char>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"CustomName/TypeParametrizedTestWithNames/parChar0");
}
if (std::is_same<TypeParam, int>::value) {
EXPECT_STREQ(::testing::UnitTest::GetInstance()
->current_test_info()
- ->test_case_name(),
+ ->test_suite_name(),
"CustomName/TypeParametrizedTestWithNames/parInt1");
}
}
@@ -443,20 +435,3 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, TrimmedTest, TrimTypes);
} // namespace library2
-#endif // GTEST_HAS_TYPED_TEST_P
-
-#if !defined(GTEST_HAS_TYPED_TEST) && !defined(GTEST_HAS_TYPED_TEST_P)
-
-// Google Test may not support type-parameterized tests with some
-// compilers. If we use conditional compilation to compile out all
-// code referring to the gtest_main library, MSVC linker will not link
-// that library at all and consequently complain about missing entry
-// point defined in that library (fatal error LNK1561: entry point
-// must be defined). This dummy test keeps gtest_main linked in.
-TEST(DummyTest, TypedTestsAreNotSupportedOnThisPlatform) {}
-
-#if _MSC_VER
-GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
-#endif // _MSC_VER
-
-#endif // #if !defined(GTEST_HAS_TYPED_TEST) && !defined(GTEST_HAS_TYPED_TEST_P)
diff --git a/googletest/test/gtest-typed-test_test.h b/googletest/test/gtest-typed-test_test.h
index 23137b7e..8ce559c9 100644
--- a/googletest/test/gtest-typed-test_test.h
+++ b/googletest/test/gtest-typed-test_test.h
@@ -27,14 +27,11 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
-#define GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
+#ifndef GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_
+#define GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_
#include "gtest/gtest.h"
-#if GTEST_HAS_TYPED_TEST_P
-
using testing::Test;
// For testing that the same type-parameterized test case can be
@@ -60,6 +57,4 @@ TYPED_TEST_P(ContainerTest, InitialSizeIsZero) {
REGISTER_TYPED_TEST_SUITE_P(ContainerTest,
CanBeDefaultConstructed, InitialSizeIsZero);
-#endif // GTEST_HAS_TYPED_TEST_P
-
-#endif // GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
+#endif // GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_
diff --git a/googletest/test/gtest-unittest-api_test.cc b/googletest/test/gtest-unittest-api_test.cc
index 7d2d8cc9..8ef50583 100644
--- a/googletest/test/gtest-unittest-api_test.cc
+++ b/googletest/test/gtest-unittest-api_test.cc
@@ -55,8 +55,8 @@ class UnitTestHelper {
// name. The caller is responsible for deleting the array.
static TestSuite const** GetSortedTestSuites() {
UnitTest& unit_test = *UnitTest::GetInstance();
- auto const** const test_suites =
- new const TestSuite*[unit_test.total_test_suite_count()];
+ auto const** const test_suites = new const TestSuite*[static_cast<size_t>(
+ unit_test.total_test_suite_count())];
for (int i = 0; i < unit_test.total_test_suite_count(); ++i)
test_suites[i] = unit_test.GetTestSuite(i);
@@ -83,8 +83,8 @@ class UnitTestHelper {
// sorted by the test name. The caller is responsible for deleting the
// array.
static TestInfo const** GetSortedTests(const TestSuite* test_suite) {
- TestInfo const** const tests =
- new const TestInfo*[test_suite->total_test_count()];
+ TestInfo const** const tests = new const TestInfo*[static_cast<size_t>(
+ test_suite->total_test_count())];
for (int i = 0; i < test_suite->total_test_count(); ++i)
tests[i] = test_suite->GetTestInfo(i);
@@ -95,17 +95,12 @@ class UnitTestHelper {
}
};
-#if GTEST_HAS_TYPED_TEST
template <typename T> class TestSuiteWithCommentTest : public Test {};
TYPED_TEST_SUITE(TestSuiteWithCommentTest, Types<int>);
TYPED_TEST(TestSuiteWithCommentTest, Dummy) {}
const int kTypedTestSuites = 1;
const int kTypedTests = 1;
-#else
-const int kTypedTestSuites = 0;
-const int kTypedTests = 0;
-#endif // GTEST_HAS_TYPED_TEST
// We can only test the accessors that do not change value while tests run.
// Since tests can be run in any order, the values the accessors that track
@@ -123,9 +118,7 @@ TEST(ApiTest, UnitTestImmutableAccessorsWork) {
EXPECT_STREQ("ApiTest", test_suites[0]->name());
EXPECT_STREQ("DISABLED_Test", test_suites[1]->name());
-#if GTEST_HAS_TYPED_TEST
EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suites[2]->name());
-#endif // GTEST_HAS_TYPED_TEST
delete[] test_suites;
@@ -183,7 +176,6 @@ TEST(ApiTest, TestSuiteImmutableAccessorsWork) {
delete[] tests;
tests = nullptr;
-#if GTEST_HAS_TYPED_TEST
test_suite = UnitTestHelper::FindTestSuite("TestSuiteWithCommentTest/0");
ASSERT_TRUE(test_suite != nullptr);
@@ -203,7 +195,6 @@ TEST(ApiTest, TestSuiteImmutableAccessorsWork) {
EXPECT_TRUE(tests[0]->should_run());
delete[] tests;
-#endif // GTEST_HAS_TYPED_TEST
}
TEST(ApiTest, TestSuiteDisabledAccessorsWork) {
@@ -263,7 +254,6 @@ class FinalSuccessChecker : public Environment {
EXPECT_EQ(0, test_suites[1]->successful_test_count());
EXPECT_EQ(0, test_suites[1]->failed_test_count());
-#if GTEST_HAS_TYPED_TEST
EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suites[2]->name());
EXPECT_STREQ(GetTypeName<Types<int>>().c_str(),
test_suites[2]->type_param());
@@ -274,7 +264,6 @@ class FinalSuccessChecker : public Environment {
EXPECT_EQ(0, test_suites[2]->failed_test_count());
EXPECT_TRUE(test_suites[2]->Passed());
EXPECT_FALSE(test_suites[2]->Failed());
-#endif // GTEST_HAS_TYPED_TEST
const TestSuite* test_suite = UnitTestHelper::FindTestSuite("ApiTest");
const TestInfo** tests = UnitTestHelper::GetSortedTests(test_suite);
@@ -311,7 +300,6 @@ class FinalSuccessChecker : public Environment {
delete[] tests;
-#if GTEST_HAS_TYPED_TEST
test_suite = UnitTestHelper::FindTestSuite("TestSuiteWithCommentTest/0");
tests = UnitTestHelper::GetSortedTests(test_suite);
@@ -324,7 +312,6 @@ class FinalSuccessChecker : public Environment {
EXPECT_EQ(0, tests[0]->result()->test_property_count());
delete[] tests;
-#endif // GTEST_HAS_TYPED_TEST
delete[] test_suites;
}
};
diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py
index 582d24c2..8d953bbd 100755
--- a/googletest/test/gtest_help_test.py
+++ b/googletest/test/gtest_help_test.py
@@ -43,6 +43,7 @@ import gtest_test_utils
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
+IS_GNUKFREEBSD = os.name == 'posix' and os.uname()[0] == 'GNU/kFreeBSD'
IS_WINDOWS = os.name == 'nt'
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_')
@@ -68,6 +69,7 @@ HELP_REGEX = re.compile(
FLAG_PREFIX + r'shuffle.*' +
FLAG_PREFIX + r'random_seed=.*' +
FLAG_PREFIX + r'color=.*' +
+ FLAG_PREFIX + r'brief.*' +
FLAG_PREFIX + r'print_time.*' +
FLAG_PREFIX + r'output=.*' +
FLAG_PREFIX + r'break_on_failure.*' +
@@ -110,7 +112,7 @@ class GTestHelpTest(gtest_test_utils.TestCase):
self.assertEquals(0, exit_code)
self.assert_(HELP_REGEX.search(output), output)
- if IS_LINUX:
+ if IS_LINUX or IS_GNUKFREEBSD:
self.assert_(STREAM_RESULT_TO_FLAG in output, output)
else:
self.assert_(STREAM_RESULT_TO_FLAG not in output, output)
diff --git a/googletest/test/gtest_list_output_unittest.py b/googletest/test/gtest_list_output_unittest.py
index 3bba7ea2..a442fc16 100644
--- a/googletest/test/gtest_list_output_unittest.py
+++ b/googletest/test/gtest_list_output_unittest.py
@@ -46,16 +46,42 @@ GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
GTEST_OUTPUT_FLAG = '--gtest_output'
EXPECTED_XML = """<\?xml version="1.0" encoding="UTF-8"\?>
-<testsuites tests="2" name="AllTests">
+<testsuites tests="16" name="AllTests">
<testsuite name="FooTest" tests="2">
<testcase name="Test1" file=".*gtest_list_output_unittest_.cc" line="43" />
<testcase name="Test2" file=".*gtest_list_output_unittest_.cc" line="45" />
</testsuite>
+ <testsuite name="FooTestFixture" tests="2">
+ <testcase name="Test3" file=".*gtest_list_output_unittest_.cc" line="48" />
+ <testcase name="Test4" file=".*gtest_list_output_unittest_.cc" line="49" />
+ </testsuite>
+ <testsuite name="TypedTest/0" tests="2">
+ <testcase name="Test7" type_param="int" file=".*gtest_list_output_unittest_.cc" line="60" />
+ <testcase name="Test8" type_param="int" file=".*gtest_list_output_unittest_.cc" line="61" />
+ </testsuite>
+ <testsuite name="TypedTest/1" tests="2">
+ <testcase name="Test7" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="60" />
+ <testcase name="Test8" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="61" />
+ </testsuite>
+ <testsuite name="Single/TypeParameterizedTestSuite/0" tests="2">
+ <testcase name="Test9" type_param="int" file=".*gtest_list_output_unittest_.cc" line="66" />
+ <testcase name="Test10" type_param="int" file=".*gtest_list_output_unittest_.cc" line="67" />
+ </testsuite>
+ <testsuite name="Single/TypeParameterizedTestSuite/1" tests="2">
+ <testcase name="Test9" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="66" />
+ <testcase name="Test10" type_param="bool" file=".*gtest_list_output_unittest_.cc" line="67" />
+ </testsuite>
+ <testsuite name="ValueParam/ValueParamTest" tests="4">
+ <testcase name="Test5/0" value_param="33" file=".*gtest_list_output_unittest_.cc" line="52" />
+ <testcase name="Test5/1" value_param="42" file=".*gtest_list_output_unittest_.cc" line="52" />
+ <testcase name="Test6/0" value_param="33" file=".*gtest_list_output_unittest_.cc" line="53" />
+ <testcase name="Test6/1" value_param="42" file=".*gtest_list_output_unittest_.cc" line="53" />
+ </testsuite>
</testsuites>
"""
EXPECTED_JSON = """{
- "tests": 2,
+ "tests": 16,
"name": "AllTests",
"testsuites": \[
{
@@ -73,6 +99,124 @@ EXPECTED_JSON = """{
"line": 45
}
\]
+ },
+ {
+ "name": "FooTestFixture",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test3",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 48
+ },
+ {
+ "name": "Test4",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 49
+ }
+ \]
+ },
+ {
+ "name": "TypedTest\\\\/0",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test7",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 60
+ },
+ {
+ "name": "Test8",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 61
+ }
+ \]
+ },
+ {
+ "name": "TypedTest\\\\/1",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test7",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 60
+ },
+ {
+ "name": "Test8",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 61
+ }
+ \]
+ },
+ {
+ "name": "Single\\\\/TypeParameterizedTestSuite\\\\/0",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test9",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 66
+ },
+ {
+ "name": "Test10",
+ "type_param": "int",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 67
+ }
+ \]
+ },
+ {
+ "name": "Single\\\\/TypeParameterizedTestSuite\\\\/1",
+ "tests": 2,
+ "testsuite": \[
+ {
+ "name": "Test9",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 66
+ },
+ {
+ "name": "Test10",
+ "type_param": "bool",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 67
+ }
+ \]
+ },
+ {
+ "name": "ValueParam\\\\/ValueParamTest",
+ "tests": 4,
+ "testsuite": \[
+ {
+ "name": "Test5\\\\/0",
+ "value_param": "33",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 52
+ },
+ {
+ "name": "Test5\\\\/1",
+ "value_param": "42",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 52
+ },
+ {
+ "name": "Test6\\\\/0",
+ "value_param": "33",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 53
+ },
+ {
+ "name": "Test6\\\\/1",
+ "value_param": "42",
+ "file": ".*gtest_list_output_unittest_.cc",
+ "line": 53
+ }
+ \]
}
\]
}
@@ -114,8 +258,9 @@ class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
p = gtest_test_utils.Subprocess(
command, env=environ_copy, working_dir=gtest_test_utils.GetTempDir())
- self.assert_(p.exited)
- self.assertEquals(0, p.exit_code)
+ self.assertTrue(p.exited)
+ self.assertEqual(0, p.exit_code)
+ self.assertTrue(os.path.isfile(file_path))
with open(file_path) as f:
result = f.read()
return result
@@ -128,7 +273,7 @@ class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):
for actual_line in actual_lines:
expected_line = expected_lines[line_count]
expected_line_re = re.compile(expected_line.strip())
- self.assert_(
+ self.assertTrue(
expected_line_re.match(actual_line.strip()),
('actual output of "%s",\n'
'which does not match expected regex of "%s"\n'
diff --git a/googletest/test/gtest_list_output_unittest_.cc b/googletest/test/gtest_list_output_unittest_.cc
index b1c7b4de..92b9d4f2 100644
--- a/googletest/test/gtest_list_output_unittest_.cc
+++ b/googletest/test/gtest_list_output_unittest_.cc
@@ -44,6 +44,32 @@ TEST(FooTest, Test1) {}
TEST(FooTest, Test2) {}
+class FooTestFixture : public ::testing::Test {};
+TEST_F(FooTestFixture, Test3) {}
+TEST_F(FooTestFixture, Test4) {}
+
+class ValueParamTest : public ::testing::TestWithParam<int> {};
+TEST_P(ValueParamTest, Test5) {}
+TEST_P(ValueParamTest, Test6) {}
+INSTANTIATE_TEST_SUITE_P(ValueParam, ValueParamTest, ::testing::Values(33, 42));
+
+template <typename T>
+class TypedTest : public ::testing::Test {};
+typedef testing::Types<int, bool> TypedTestTypes;
+TYPED_TEST_SUITE(TypedTest, TypedTestTypes);
+TYPED_TEST(TypedTest, Test7) {}
+TYPED_TEST(TypedTest, Test8) {}
+
+template <typename T>
+class TypeParameterizedTestSuite : public ::testing::Test {};
+TYPED_TEST_SUITE_P(TypeParameterizedTestSuite);
+TYPED_TEST_P(TypeParameterizedTestSuite, Test9) {}
+TYPED_TEST_P(TypeParameterizedTestSuite, Test10) {}
+REGISTER_TYPED_TEST_SUITE_P(TypeParameterizedTestSuite, Test9, Test10);
+typedef testing::Types<int, bool> TypeParameterizedTestSuiteTypes; // NOLINT
+INSTANTIATE_TYPED_TEST_SUITE_P(Single, TypeParameterizedTestSuite,
+ TypeParameterizedTestSuiteTypes);
+
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py
index ef9363c3..d0c24466 100755
--- a/googletest/test/gtest_test_utils.py
+++ b/googletest/test/gtest_test_utils.py
@@ -217,7 +217,6 @@ class Subprocess:
following attributes:
terminated_by_signal True if and only if the child process has been
terminated by a signal.
- signal Sygnal that terminated the child process.
exited True if and only if the child process exited
normally.
exit_code The code with which the child process exited.
@@ -289,10 +288,9 @@ class Subprocess:
else: # os.WIFEXITED(ret_code) should return True here.
self._return_code = os.WEXITSTATUS(ret_code)
- if self._return_code < 0:
+ if bool(self._return_code & 0x80000000):
self.terminated_by_signal = True
self.exited = False
- self.signal = -self._return_code
else:
self.terminated_by_signal = False
self.exited = True
diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc
index 06c5e671..1730e8b8 100644
--- a/googletest/test/gtest_unittest.cc
+++ b/googletest/test/gtest_unittest.cc
@@ -37,21 +37,22 @@
// code once "gtest.h" has been #included.
// Do not move it after other gtest #includes.
TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
- bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
- || testing::GTEST_FLAG(break_on_failure)
- || testing::GTEST_FLAG(catch_exceptions)
- || testing::GTEST_FLAG(color) != "unknown"
- || testing::GTEST_FLAG(filter) != "unknown"
- || testing::GTEST_FLAG(list_tests)
- || testing::GTEST_FLAG(output) != "unknown"
- || testing::GTEST_FLAG(print_time)
- || testing::GTEST_FLAG(random_seed)
- || testing::GTEST_FLAG(repeat) > 0
- || testing::GTEST_FLAG(show_internal_stack_frames)
- || testing::GTEST_FLAG(shuffle)
- || testing::GTEST_FLAG(stack_trace_depth) > 0
- || testing::GTEST_FLAG(stream_result_to) != "unknown"
- || testing::GTEST_FLAG(throw_on_failure);
+ bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) ||
+ testing::GTEST_FLAG(break_on_failure) ||
+ testing::GTEST_FLAG(catch_exceptions) ||
+ testing::GTEST_FLAG(color) != "unknown" ||
+ testing::GTEST_FLAG(fail_fast) ||
+ testing::GTEST_FLAG(filter) != "unknown" ||
+ testing::GTEST_FLAG(list_tests) ||
+ testing::GTEST_FLAG(output) != "unknown" ||
+ testing::GTEST_FLAG(brief) || testing::GTEST_FLAG(print_time) ||
+ testing::GTEST_FLAG(random_seed) ||
+ testing::GTEST_FLAG(repeat) > 0 ||
+ testing::GTEST_FLAG(show_internal_stack_frames) ||
+ testing::GTEST_FLAG(shuffle) ||
+ testing::GTEST_FLAG(stack_trace_depth) > 0 ||
+ testing::GTEST_FLAG(stream_result_to) != "unknown" ||
+ testing::GTEST_FLAG(throw_on_failure);
EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
}
@@ -63,6 +64,7 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
#include <cstdint>
#include <map>
#include <ostream>
+#include <string>
#include <type_traits>
#include <unordered_set>
#include <vector>
@@ -202,9 +204,11 @@ using testing::GTEST_FLAG(break_on_failure);
using testing::GTEST_FLAG(catch_exceptions);
using testing::GTEST_FLAG(color);
using testing::GTEST_FLAG(death_test_use_fork);
+using testing::GTEST_FLAG(fail_fast);
using testing::GTEST_FLAG(filter);
using testing::GTEST_FLAG(list_tests);
using testing::GTEST_FLAG(output);
+using testing::GTEST_FLAG(brief);
using testing::GTEST_FLAG(print_time);
using testing::GTEST_FLAG(random_seed);
using testing::GTEST_FLAG(repeat);
@@ -215,17 +219,18 @@ using testing::GTEST_FLAG(stream_result_to);
using testing::GTEST_FLAG(throw_on_failure);
using testing::IsNotSubstring;
using testing::IsSubstring;
+using testing::kMaxStackTraceDepth;
using testing::Message;
using testing::ScopedFakeTestPartResultReporter;
using testing::StaticAssertTypeEq;
using testing::Test;
-using testing::TestCase;
using testing::TestEventListeners;
using testing::TestInfo;
using testing::TestPartResult;
using testing::TestPartResultArray;
using testing::TestProperty;
using testing::TestResult;
+using testing::TestSuite;
using testing::TimeInMillis;
using testing::UnitTest;
using testing::internal::AlwaysFalse;
@@ -241,7 +246,6 @@ using testing::internal::FloatingPoint;
using testing::internal::ForEach;
using testing::internal::FormatEpochTimeInMillisAsIso8601;
using testing::internal::FormatTimeInMillisAsSeconds;
-using testing::internal::GTestFlagSaver;
using testing::internal::GetCurrentOsStackTraceExceptTop;
using testing::internal::GetElementOr;
using testing::internal::GetNextRandomSeed;
@@ -250,11 +254,14 @@ using testing::internal::GetTestTypeId;
using testing::internal::GetTimeInMillis;
using testing::internal::GetTypeId;
using testing::internal::GetUnitTestImpl;
+using testing::internal::GTestFlagSaver;
+using testing::internal::HasDebugStringAndShortDebugString;
using testing::internal::Int32FromEnvOrDie;
-using testing::internal::IsAProtocolMessage;
using testing::internal::IsContainer;
using testing::internal::IsContainerTest;
using testing::internal::IsNotContainer;
+using testing::internal::kMaxRandomSeed;
+using testing::internal::kTestTypeIdInGoogleTest;
using testing::internal::NativeArray;
using testing::internal::OsStackTraceGetter;
using testing::internal::OsStackTraceGetterInterface;
@@ -276,9 +283,6 @@ using testing::internal::WideStringToUtf8;
using testing::internal::edit_distance::CalculateOptimalEdits;
using testing::internal::edit_distance::CreateUnifiedDiff;
using testing::internal::edit_distance::EditType;
-using testing::internal::kMaxRandomSeed;
-using testing::internal::kTestTypeIdInGoogleTest;
-using testing::kMaxStackTraceDepth;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStdout;
@@ -482,28 +486,28 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test {
const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
- EXPECT_EQ("2011-10-31T18:52:42",
+ EXPECT_EQ("2011-10-31T18:52:42.000",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
}
-TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) {
+TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
EXPECT_EQ(
- "2011-10-31T18:52:42",
+ "2011-10-31T18:52:42.234",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
- EXPECT_EQ("2011-09-03T05:07:02",
+ EXPECT_EQ("2011-09-03T05:07:02.000",
FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
- EXPECT_EQ("2011-09-28T17:08:22",
+ EXPECT_EQ("2011-09-28T17:08:22.000",
FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
- EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0));
+ EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
}
# ifdef __BORLANDC__
@@ -1598,9 +1602,11 @@ class GTestFlagSaverTest : public Test {
GTEST_FLAG(catch_exceptions) = false;
GTEST_FLAG(death_test_use_fork) = false;
GTEST_FLAG(color) = "auto";
+ GTEST_FLAG(fail_fast) = false;
GTEST_FLAG(filter) = "";
GTEST_FLAG(list_tests) = false;
GTEST_FLAG(output) = "";
+ GTEST_FLAG(brief) = false;
GTEST_FLAG(print_time) = true;
GTEST_FLAG(random_seed) = 0;
GTEST_FLAG(repeat) = 1;
@@ -1625,9 +1631,11 @@ class GTestFlagSaverTest : public Test {
EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
+ EXPECT_FALSE(GTEST_FLAG(fail_fast));
EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
EXPECT_FALSE(GTEST_FLAG(list_tests));
EXPECT_STREQ("", GTEST_FLAG(output).c_str());
+ EXPECT_FALSE(GTEST_FLAG(brief));
EXPECT_TRUE(GTEST_FLAG(print_time));
EXPECT_EQ(0, GTEST_FLAG(random_seed));
EXPECT_EQ(1, GTEST_FLAG(repeat));
@@ -1641,9 +1649,11 @@ class GTestFlagSaverTest : public Test {
GTEST_FLAG(catch_exceptions) = true;
GTEST_FLAG(color) = "no";
GTEST_FLAG(death_test_use_fork) = true;
+ GTEST_FLAG(fail_fast) = true;
GTEST_FLAG(filter) = "abc";
GTEST_FLAG(list_tests) = true;
GTEST_FLAG(output) = "xml:foo.xml";
+ GTEST_FLAG(brief) = true;
GTEST_FLAG(print_time) = false;
GTEST_FLAG(random_seed) = 1;
GTEST_FLAG(repeat) = 100;
@@ -2758,7 +2768,7 @@ class FloatingPointTest : public Test {
typedef typename Floating::Bits Bits;
void SetUp() override {
- const size_t max_ulps = Floating::kMaxUlps;
+ const uint32_t max_ulps = Floating::kMaxUlps;
// The bits that represent 0.0.
const Bits zero_bits = Floating(0).bits();
@@ -3075,6 +3085,13 @@ TEST_F(DoubleTest, EXPECT_NEAR) {
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25");
+ // At this magnitude adjacent doubles are 512.0 apart, so this triggers a
+ // slightly different failure reporting path.
+ EXPECT_NONFATAL_FAILURE(
+ EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
+ "The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
+ "minimum distance between doubles for numbers of this magnitude which is "
+ "512");
}
// Tests ASSERT_NEAR.
@@ -3170,8 +3187,6 @@ TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
// Tests that disabled typed tests aren't run.
-#if GTEST_HAS_TYPED_TEST
-
template <typename T>
class TypedTest : public Test {
};
@@ -3193,12 +3208,8 @@ TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
FAIL() << "Unexpected failure: Disabled typed test should not run.";
}
-#endif // GTEST_HAS_TYPED_TEST
-
// Tests that disabled type-parameterized tests aren't run.
-#if GTEST_HAS_TYPED_TEST_P
-
template <typename T>
class TypedTestP : public Test {
};
@@ -3229,8 +3240,6 @@ REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
-#endif // GTEST_HAS_TYPED_TEST_P
-
// Tests that assertion macros evaluate their arguments exactly once.
class SingleEvaluationTest : public Test {
@@ -3336,6 +3345,20 @@ TEST_F(SingleEvaluationTest, OtherCases) {
#if GTEST_HAS_EXCEPTIONS
+#if GTEST_HAS_RTTI
+
+#ifdef _MSC_VER
+#define ERROR_DESC "class std::runtime_error"
+#else
+#define ERROR_DESC "std::runtime_error"
+#endif
+
+#else // GTEST_HAS_RTTI
+
+#define ERROR_DESC "an std::exception-derived error"
+
+#endif // GTEST_HAS_RTTI
+
void ThrowAnInteger() {
throw 1;
}
@@ -3359,31 +3382,38 @@ TEST_F(SingleEvaluationTest, ExceptionTests) {
}, bool), "throws a different type");
EXPECT_EQ(2, a_);
+ // failed EXPECT_THROW, throws runtime error
+ EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
+ a_++;
+ ThrowRuntimeError("A description");
+ }, bool), "throws " ERROR_DESC " with description \"A description\"");
+ EXPECT_EQ(3, a_);
+
// failed EXPECT_THROW, throws nothing
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
- EXPECT_EQ(3, a_);
+ EXPECT_EQ(4, a_);
// successful EXPECT_NO_THROW
EXPECT_NO_THROW(a_++);
- EXPECT_EQ(4, a_);
+ EXPECT_EQ(5, a_);
// failed EXPECT_NO_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
a_++;
ThrowAnInteger();
}), "it throws");
- EXPECT_EQ(5, a_);
+ EXPECT_EQ(6, a_);
// successful EXPECT_ANY_THROW
EXPECT_ANY_THROW({ // NOLINT
a_++;
ThrowAnInteger();
});
- EXPECT_EQ(6, a_);
+ EXPECT_EQ(7, a_);
// failed EXPECT_ANY_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
- EXPECT_EQ(7, a_);
+ EXPECT_EQ(8, a_);
}
#endif // GTEST_HAS_EXCEPTIONS
@@ -3803,6 +3833,12 @@ TEST(AssertionTest, ASSERT_THROW) {
ASSERT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of type bool.\n"
" Actual: it throws a different type.");
+ EXPECT_FATAL_FAILURE(
+ ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
+ "Expected: ThrowRuntimeError(\"A description\") "
+ "throws an exception of type std::logic_error.\n "
+ "Actual: it throws " ERROR_DESC " "
+ "with description \"A description\".");
# endif
EXPECT_FATAL_FAILURE(
@@ -3820,8 +3856,8 @@ TEST(AssertionTest, ASSERT_NO_THROW) {
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n "
- "Actual: it throws std::exception-derived exception "
- "with description: \"A description\".");
+ "Actual: it throws " ERROR_DESC " "
+ "with description \"A description\".");
}
// Tests ASSERT_ANY_THROW.
@@ -4091,11 +4127,13 @@ TEST(HRESULTAssertionTest, Streaming) {
#endif // GTEST_OS_WINDOWS
-#ifdef __BORLANDC__
-// Silences warnings: "Condition is always true", "Unreachable code"
-# pragma option push -w-ccc -w-rch
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
#endif
-
// Tests that the assertion macros behave like single statements.
TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
@@ -4115,6 +4153,9 @@ TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
else
EXPECT_GT(3, 2) << "";
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
#if GTEST_HAS_EXCEPTIONS
// Tests that the compiler will not complain about unreachable code in the
@@ -4131,6 +4172,17 @@ TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
}
+TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
+ EXPECT_THROW(throw std::exception(), std::exception);
+}
+
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
EXPECT_THROW(ThrowNothing(), bool);
@@ -4156,8 +4208,19 @@ TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
else
; // NOLINT
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
+
#endif // GTEST_HAS_EXCEPTIONS
+// The following code intentionally tests a suboptimal syntax.
+#ifdef __GNUC__
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdangling-else"
+#pragma GCC diagnostic ignored "-Wempty-body"
+#pragma GCC diagnostic ignored "-Wpragmas"
+#endif
TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
@@ -4180,6 +4243,9 @@ TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
else
ASSERT_NO_FATAL_FAILURE(SUCCEED());
}
+#ifdef __GNUC__
+#pragma GCC diagnostic pop
+#endif
// Tests that the assertion macros work well with switch statements.
TEST(AssertionSyntaxTest, WorksWithSwitch) {
@@ -4541,6 +4607,12 @@ TEST(ExpectTest, EXPECT_THROW) {
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of "
"type bool.\n Actual: it throws a different type.");
+ EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"),
+ std::logic_error),
+ "Expected: ThrowRuntimeError(\"A description\") "
+ "throws an exception of type std::logic_error.\n "
+ "Actual: it throws " ERROR_DESC " "
+ "with description \"A description\".");
EXPECT_NONFATAL_FAILURE(
EXPECT_THROW(ThrowNothing(), bool),
"Expected: ThrowNothing() throws an exception of type bool.\n"
@@ -4556,8 +4628,8 @@ TEST(ExpectTest, EXPECT_NO_THROW) {
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n "
- "Actual: it throws std::exception-derived exception "
- "with description: \"A description\".");
+ "Actual: it throws " ERROR_DESC " "
+ "with description \"A description\".");
}
// Tests EXPECT_ANY_THROW.
@@ -5297,7 +5369,7 @@ class TestInfoTest : public Test {
TEST_F(TestInfoTest, Names) {
const TestInfo* const test_info = GetTestInfo("Names");
- ASSERT_STREQ("TestInfoTest", test_info->test_case_name());
+ ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
ASSERT_STREQ("Names", test_info->name());
}
@@ -5367,7 +5439,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
// Tests setting up and tearing down a test case.
// Legacy API is deprecated but still available
-#ifndef REMOVE_LEGACY_TEST_CASEAPI
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
class SetUpTestCaseTest : public Test {
protected:
// This will be called once before the first test in this test case
@@ -5426,7 +5498,7 @@ TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
TEST_F(SetUpTestCaseTest, Test2) {
EXPECT_STREQ("123", shared_resource_);
}
-#endif // REMOVE_LEGACY_TEST_CASEAPI
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Tests SetupTestSuite/TearDown TestSuite
class SetUpTestSuiteTest : public Test {
@@ -5495,20 +5567,23 @@ TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
// The Flags struct stores a copy of all Google Test flags.
struct Flags {
// Constructs a Flags struct where each flag has its default value.
- Flags() : also_run_disabled_tests(false),
- break_on_failure(false),
- catch_exceptions(false),
- death_test_use_fork(false),
- filter(""),
- list_tests(false),
- output(""),
- print_time(true),
- random_seed(0),
- repeat(1),
- shuffle(false),
- stack_trace_depth(kMaxStackTraceDepth),
- stream_result_to(""),
- throw_on_failure(false) {}
+ Flags()
+ : also_run_disabled_tests(false),
+ break_on_failure(false),
+ catch_exceptions(false),
+ death_test_use_fork(false),
+ fail_fast(false),
+ filter(""),
+ list_tests(false),
+ output(""),
+ brief(false),
+ print_time(true),
+ random_seed(0),
+ repeat(1),
+ shuffle(false),
+ stack_trace_depth(kMaxStackTraceDepth),
+ stream_result_to(""),
+ throw_on_failure(false) {}
// Factory methods.
@@ -5544,6 +5619,14 @@ struct Flags {
return flags;
}
+ // Creates a Flags struct where the gtest_fail_fast flag has
+ // the given value.
+ static Flags FailFast(bool fail_fast) {
+ Flags flags;
+ flags.fail_fast = fail_fast;
+ return flags;
+ }
+
// Creates a Flags struct where the gtest_filter flag has the given
// value.
static Flags Filter(const char* filter) {
@@ -5568,6 +5651,14 @@ struct Flags {
return flags;
}
+ // Creates a Flags struct where the gtest_brief flag has the given
+ // value.
+ static Flags Brief(bool brief) {
+ Flags flags;
+ flags.brief = brief;
+ return flags;
+ }
+
// Creates a Flags struct where the gtest_print_time flag has the given
// value.
static Flags PrintTime(bool print_time) {
@@ -5629,9 +5720,11 @@ struct Flags {
bool break_on_failure;
bool catch_exceptions;
bool death_test_use_fork;
+ bool fail_fast;
const char* filter;
bool list_tests;
const char* output;
+ bool brief;
bool print_time;
int32_t random_seed;
int32_t repeat;
@@ -5650,9 +5743,11 @@ class ParseFlagsTest : public Test {
GTEST_FLAG(break_on_failure) = false;
GTEST_FLAG(catch_exceptions) = false;
GTEST_FLAG(death_test_use_fork) = false;
+ GTEST_FLAG(fail_fast) = false;
GTEST_FLAG(filter) = "";
GTEST_FLAG(list_tests) = false;
GTEST_FLAG(output) = "";
+ GTEST_FLAG(brief) = false;
GTEST_FLAG(print_time) = true;
GTEST_FLAG(random_seed) = 0;
GTEST_FLAG(repeat) = 1;
@@ -5680,9 +5775,11 @@ class ParseFlagsTest : public Test {
EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
+ EXPECT_EQ(expected.fail_fast, GTEST_FLAG(fail_fast));
EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
+ EXPECT_EQ(expected.brief, GTEST_FLAG(brief));
EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
@@ -5766,6 +5863,15 @@ TEST_F(ParseFlagsTest, NoFlag) {
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}
+// Tests parsing --gtest_fail_fast.
+TEST_F(ParseFlagsTest, FailFast) {
+ const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
+}
+
// Tests parsing a bad --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterBad) {
const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
@@ -5965,6 +6071,33 @@ TEST_F(ParseFlagsTest, OutputXmlDirectory) {
Flags::Output("xml:directory/path/"), false);
}
+// Tests having a --gtest_brief flag
+TEST_F(ParseFlagsTest, BriefFlag) {
+ const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
+}
+
+// Tests having a --gtest_brief flag with a "true" value
+TEST_F(ParseFlagsTest, BriefFlagTrue) {
+ const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
+}
+
+// Tests having a --gtest_brief flag with a "false" value
+TEST_F(ParseFlagsTest, BriefFlagFalse) {
+ const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
+}
+
// Tests having a --gtest_print_time flag
TEST_F(ParseFlagsTest, PrintTimeFlag) {
const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
@@ -6271,8 +6404,8 @@ TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo.";
- EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
- << "Expected the name of the currently running test case.";
+ EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
+ << "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
@@ -6286,8 +6419,8 @@ TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo.";
- EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name())
- << "Expected the name of the currently running test case.";
+ EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
+ << "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
@@ -7075,24 +7208,71 @@ GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
class ConversionHelperBase {};
class ConversionHelperDerived : public ConversionHelperBase {};
-// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
-TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
- GTEST_COMPILE_ASSERT_(IsAProtocolMessage<::proto2::Message>::value,
- const_true);
- GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
-}
+struct HasDebugStringMethods {
+ std::string DebugString() const { return ""; }
+ std::string ShortDebugString() const { return ""; }
+};
+
+struct InheritsDebugStringMethods : public HasDebugStringMethods {};
+
+struct WrongTypeDebugStringMethod {
+ std::string DebugString() const { return ""; }
+ int ShortDebugString() const { return 1; }
+};
-// Tests that IsAProtocolMessage<T>::value is true when T is
-// proto2::Message or a sub-class of it.
-TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
- EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
+struct NotConstDebugStringMethod {
+ std::string DebugString() { return ""; }
+ std::string ShortDebugString() const { return ""; }
+};
+
+struct MissingDebugStringMethod {
+ std::string DebugString() { return ""; }
+};
+
+struct IncompleteType;
+
+// Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
+// constant.
+TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
+ GTEST_COMPILE_ASSERT_(
+ HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
+ const_true);
+ GTEST_COMPILE_ASSERT_(
+ HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
+ const_true);
+ GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString<
+ const InheritsDebugStringMethods>::value,
+ const_true);
+ GTEST_COMPILE_ASSERT_(
+ !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
+ const_false);
+ GTEST_COMPILE_ASSERT_(
+ !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
+ const_false);
+ GTEST_COMPILE_ASSERT_(
+ !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
+ const_false);
+ GTEST_COMPILE_ASSERT_(
+ !HasDebugStringAndShortDebugString<IncompleteType>::value, const_false);
+ GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value,
+ const_false);
+}
+
+// Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
+// needed methods.
+TEST(HasDebugStringAndShortDebugStringTest,
+ ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
+ EXPECT_TRUE(
+ HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
}
-// Tests that IsAProtocolMessage<T>::value is false when T is neither
-// ::proto2::Message nor a sub-class of it.
-TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) {
- EXPECT_FALSE(IsAProtocolMessage<int>::value);
- EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value);
+// Tests that HasDebugStringAndShortDebugString<T>::value is false when T
+// doesn't have needed methods.
+TEST(HasDebugStringAndShortDebugStringTest,
+ ValueIsFalseWhenTypeIsNotAProtocolMessage) {
+ EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
+ EXPECT_FALSE(
+ HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
}
// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
@@ -7367,7 +7547,8 @@ TEST(FlatTuple, Basic) {
EXPECT_EQ(0.0, tuple.Get<1>());
EXPECT_EQ(nullptr, tuple.Get<2>());
- tuple = FlatTuple<int, double, const char*>(7, 3.2, "Foo");
+ tuple = FlatTuple<int, double, const char*>(
+ testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
EXPECT_EQ(7, tuple.Get<0>());
EXPECT_EQ(3.2, tuple.Get<1>());
EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
@@ -7376,6 +7557,147 @@ TEST(FlatTuple, Basic) {
EXPECT_EQ(5.1, tuple.Get<1>());
}
+namespace {
+std::string AddIntToString(int i, const std::string& s) {
+ return s + std::to_string(i);
+}
+} // namespace
+
+TEST(FlatTuple, Apply) {
+ using testing::internal::FlatTuple;
+
+ FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
+ 5, "Hello"};
+
+ // Lambda.
+ EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
+ return i == static_cast<int>(s.size());
+ }));
+
+ // Function.
+ EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
+
+ // Mutating operations.
+ tuple.Apply([](int& i, std::string& s) {
+ ++i;
+ s += s;
+ });
+ EXPECT_EQ(tuple.Get<0>(), 6);
+ EXPECT_EQ(tuple.Get<1>(), "HelloHello");
+}
+
+struct ConstructionCounting {
+ ConstructionCounting() { ++default_ctor_calls; }
+ ~ConstructionCounting() { ++dtor_calls; }
+ ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
+ ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
+ ConstructionCounting& operator=(const ConstructionCounting&) {
+ ++copy_assignment_calls;
+ return *this;
+ }
+ ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
+ ++move_assignment_calls;
+ return *this;
+ }
+
+ static void Reset() {
+ default_ctor_calls = 0;
+ dtor_calls = 0;
+ copy_ctor_calls = 0;
+ move_ctor_calls = 0;
+ copy_assignment_calls = 0;
+ move_assignment_calls = 0;
+ }
+
+ static int default_ctor_calls;
+ static int dtor_calls;
+ static int copy_ctor_calls;
+ static int move_ctor_calls;
+ static int copy_assignment_calls;
+ static int move_assignment_calls;
+};
+
+int ConstructionCounting::default_ctor_calls = 0;
+int ConstructionCounting::dtor_calls = 0;
+int ConstructionCounting::copy_ctor_calls = 0;
+int ConstructionCounting::move_ctor_calls = 0;
+int ConstructionCounting::copy_assignment_calls = 0;
+int ConstructionCounting::move_assignment_calls = 0;
+
+TEST(FlatTuple, ConstructorCalls) {
+ using testing::internal::FlatTuple;
+
+ // Default construction.
+ ConstructionCounting::Reset();
+ { FlatTuple<ConstructionCounting> tuple; }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Copy construction.
+ ConstructionCounting::Reset();
+ {
+ ConstructionCounting elem;
+ FlatTuple<ConstructionCounting> tuple{
+ testing::internal::FlatTupleConstructTag{}, elem};
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Move construction.
+ ConstructionCounting::Reset();
+ {
+ FlatTuple<ConstructionCounting> tuple{
+ testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Copy assignment.
+ // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
+ // elements
+ ConstructionCounting::Reset();
+ {
+ FlatTuple<ConstructionCounting> tuple;
+ ConstructionCounting elem;
+ tuple.Get<0>() = elem;
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
+
+ // Move assignment.
+ // TODO(ofats): it should be testing assignment operator of FlatTuple, not its
+ // elements
+ ConstructionCounting::Reset();
+ {
+ FlatTuple<ConstructionCounting> tuple;
+ tuple.Get<0>() = ConstructionCounting{};
+ }
+ EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
+ EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
+ EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
+ EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
+
+ ConstructionCounting::Reset();
+}
+
TEST(FlatTuple, ManyTypes) {
using testing::internal::FlatTuple;
diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py
index e093f6f0..ac66feb6 100755
--- a/googletest/test/gtest_xml_outfiles_test.py
+++ b/googletest/test/gtest_xml_outfiles_test.py
@@ -42,7 +42,7 @@ GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_"
EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
- <testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="PropertyOne" tests="1" failures="0" skipped="0" disabled="0" errors="0" time="*" timestamp="*">
<testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyOne">
<properties>
<property name="SetUpProp" value="1"/>
@@ -56,7 +56,7 @@ EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
- <testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="PropertyTwo" tests="1" failures="0" skipped="0" disabled="0" errors="0" time="*" timestamp="*">
<testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo">
<properties>
<property name="SetUpProp" value="2"/>
diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py
index 63b1af0b..eade7aac 100755
--- a/googletest/test/gtest_xml_output_unittest.py
+++ b/googletest/test/gtest_xml_output_unittest.py
@@ -65,11 +65,11 @@ else:
sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
-<testsuites tests="24" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
- <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+<testsuites tests="26" failures="5" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
+ <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
- <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="FailedTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="FailedTest">
<failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
@@ -77,7 +77,7 @@ Expected equality of these values:
2%(stack)s]]></failure>
</testcase>
</testsuite>
- <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*" timestamp="*">
+ <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/>
<testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest">
<failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
@@ -91,27 +91,43 @@ Expected equality of these values:
</testcase>
<testcase name="DISABLED_test" status="notrun" result="suppressed" time="*" timestamp="*" classname="MixedResultTest"/>
</testsuite>
- <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="OutputsCData" status="run" result="completed" time="*" timestamp="*" classname="XmlQuotingTest">
<failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]&gt;<![CDATA[</top>%(stack)s]]></failure>
</testcase>
</testsuite>
- <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="InvalidCharactersInMessage" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest">
<failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []%(stack)s]]></failure>
</testcase>
</testsuite>
- <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*" timestamp="*">
+ <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="DISABLED_test_not_run" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/>
</testsuite>
- <testsuite name="SkippedTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="Skipped" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest"/>
+ <testsuite name="SkippedTest" tests="3" failures="1" disabled="0" skipped="2" errors="0" time="*" timestamp="*">
+ <testcase name="Skipped" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest">
+ <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;"><![CDATA[gtest_xml_output_unittest_.cc:*
+%(stack)s]]></skipped>
+ </testcase>
+ <testcase name="SkippedWithMessage" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest">
+ <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test."><![CDATA[gtest_xml_output_unittest_.cc:*
+It is good practice to tell why you skip a test.%(stack)s]]></skipped>
+ </testcase>
+ <testcase name="SkippedAfterFailure" status="run" result="completed" time="*" timestamp="*" classname="SkippedTest">
+ <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+Expected equality of these values:
+ 1
+ 2%(stack)s]]></failure>
+ <skipped message="gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test."><![CDATA[gtest_xml_output_unittest_.cc:*
+It is good practice to tell why you skip a test.%(stack)s]]></skipped>
+ </testcase>
+
</testsuite>
- <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
+ <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
<testcase name="OneProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
<property name="key_1" value="1"/>
@@ -135,7 +151,7 @@ Invalid characters in brackets []%(stack)s]]></failure>
</properties>
</testcase>
</testsuite>
- <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="RecordProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
<properties>
<property name="key" value="1"/>
@@ -152,22 +168,22 @@ Invalid characters in brackets []%(stack)s]]></failure>
</properties>
</testcase>
</testsuite>
- <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="HasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
</testsuite>
- <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" />
</testsuite>
- <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" />
</testsuite>
- <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
</testsuite>
- <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
</testsuite>
</testsuites>""" % {
@@ -177,7 +193,7 @@ Invalid characters in brackets []%(stack)s]]></failure>
EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*"
timestamp="*" name="AllTests" ad_hoc_property="42">
- <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0"
+ <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0"
errors="0" time="*" timestamp="*">
<testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
@@ -185,25 +201,35 @@ EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
EXPECTED_SHARDED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
- <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
- <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
- <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
+ <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
+ <testcase name="IntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
- <property name="key_1" value="2"/>
+ <property name="key_int" value="1"/>
</properties>
</testcase>
</testsuite>
- <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+ <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
</testsuite>
</testsuites>"""
-EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
+EXPECTED_NO_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="0" failures="0" disabled="0" errors="0" time="*"
timestamp="*" name="AllTests">
-</testsuites>"""
+ <testsuite name="NonTestSuiteFailure" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="" status="run" result="completed" time="*" timestamp="*" classname="">
+ <failure message="gtest_no_test_unittest.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_no_test_unittest.cc:*
+Expected equality of these values:
+ 1
+ 2%(stack)s]]></failure>
+ </testcase>
+ </testsuite>
+</testsuites>""" % {
+ 'stack': STACK_TRACE_TEMPLATE
+}
GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
@@ -226,14 +252,14 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
"""
self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)
- def testEmptyXmlOutput(self):
+ def testNoTestXmlOutput(self):
"""Verifies XML output for a Google Test binary without actual tests.
- Runs a test program that generates an empty XML output, and
- tests that the XML output is expected.
+ Runs a test program that generates an XML output for a binary without tests,
+ and tests that the XML output is expected.
"""
- self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0)
+ self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_NO_TEST_XML, 0)
def testTimestampValue(self):
"""Checks whether the timestamp attribute in the XML output is valid.
diff --git a/googletest/test/gtest_xml_output_unittest_.cc b/googletest/test/gtest_xml_output_unittest_.cc
index c95fd66c..c0036aae 100644
--- a/googletest/test/gtest_xml_output_unittest_.cc
+++ b/googletest/test/gtest_xml_output_unittest_.cc
@@ -74,6 +74,15 @@ TEST_F(SkippedTest, Skipped) {
GTEST_SKIP();
}
+TEST_F(SkippedTest, SkippedWithMessage) {
+ GTEST_SKIP() << "It is good practice to tell why you skip a test.";
+}
+
+TEST_F(SkippedTest, SkippedAfterFailure) {
+ EXPECT_EQ(1, 2);
+ GTEST_SKIP() << "It is good practice to tell why you skip a test.";
+}
+
TEST(MixedResultTest, Succeeds) {
EXPECT_EQ(1, 1);
ASSERT_EQ(1, 1);
@@ -154,16 +163,13 @@ TEST_P(ValueParamTest, HasValueParamAttribute) {}
TEST_P(ValueParamTest, AnotherTestThatHasValueParamAttribute) {}
INSTANTIATE_TEST_SUITE_P(Single, ValueParamTest, Values(33, 42));
-#if GTEST_HAS_TYPED_TEST
// Verifies that the type parameter name is output in the 'type_param'
// XML attribute for typed tests.
template <typename T> class TypedTest : public Test {};
typedef testing::Types<int, long> TypedTestTypes;
TYPED_TEST_SUITE(TypedTest, TypedTestTypes);
TYPED_TEST(TypedTest, HasTypeParamAttribute) {}
-#endif
-#if GTEST_HAS_TYPED_TEST_P
// Verifies that the type parameter name is output in the 'type_param'
// XML attribute for type-parameterized tests.
template <typename T>
@@ -174,7 +180,6 @@ REGISTER_TYPED_TEST_SUITE_P(TypeParameterizedTestSuite, HasTypeParamAttribute);
typedef testing::Types<int, long> TypeParameterizedTestSuiteTypes; // NOLINT
INSTANTIATE_TYPED_TEST_SUITE_P(Single, TypeParameterizedTestSuite,
TypeParameterizedTestSuiteTypes);
-#endif
int main(int argc, char** argv) {
InitGoogleTest(&argc, argv);
diff --git a/googletest/test/gtest_xml_test_utils.py b/googletest/test/gtest_xml_test_utils.py
index 9914a49e..ec42c62c 100755
--- a/googletest/test/gtest_xml_test_utils.py
+++ b/googletest/test/gtest_xml_test_utils.py
@@ -70,7 +70,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
self.assertEquals(expected_node.tagName, actual_node.tagName)
expected_attributes = expected_node.attributes
- actual_attributes = actual_node .attributes
+ actual_attributes = actual_node.attributes
self.assertEquals(
expected_attributes.length, actual_attributes.length,
'attribute numbers differ in element %s:\nExpected: %r\nActual: %r' % (
@@ -78,7 +78,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
actual_attributes.keys()))
for i in range(expected_attributes.length):
expected_attr = expected_attributes.item(i)
- actual_attr = actual_attributes.get(expected_attr.name)
+ actual_attr = actual_attributes.get(expected_attr.name)
self.assert_(
actual_attr is not None,
'expected attribute %s not found in element %s' %
@@ -105,6 +105,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
'testsuite': 'name',
'testcase': 'name',
'failure': 'message',
+ 'skipped': 'message',
'property': 'name',
}
@@ -171,7 +172,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
if element.tagName in ('testsuites', 'testsuite', 'testcase'):
timestamp = element.getAttributeNode('timestamp')
- timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$',
+ timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d\d\d$',
'*', timestamp.value)
if element.tagName in ('testsuites', 'testsuite', 'testcase'):
time = element.getAttributeNode('time')
@@ -179,7 +180,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
type_param = element.getAttributeNode('type_param')
if type_param and type_param.value:
type_param.value = '*'
- elif element.tagName == 'failure':
+ elif element.tagName == 'failure' or element.tagName == 'skipped':
source_line_pat = r'^.*[/\\](.*:)\d+\n'
# Replaces the source line information with a normalized form.
message = element.getAttributeNode('message')
diff --git a/googletest/test/production.h b/googletest/test/production.h
index 542723b7..41a54722 100644
--- a/googletest/test/production.h
+++ b/googletest/test/production.h
@@ -30,8 +30,8 @@
//
// This is part of the unit test for gtest_prod.h.
-#ifndef GTEST_TEST_PRODUCTION_H_
-#define GTEST_TEST_PRODUCTION_H_
+#ifndef GOOGLETEST_TEST_PRODUCTION_H_
+#define GOOGLETEST_TEST_PRODUCTION_H_
#include "gtest/gtest_prod.h"
@@ -51,4 +51,4 @@ class PrivateCode {
int x_;
};
-#endif // GTEST_TEST_PRODUCTION_H_
+#endif // GOOGLETEST_TEST_PRODUCTION_H_
diff --git a/library.json b/library.json
index 91169b7f..f61bf003 100644
--- a/library.json
+++ b/library.json
@@ -25,14 +25,10 @@
"ci",
"googlemock/cmake",
"googlemock/scripts",
- "googlemock/src/gmock-all.cc",
- "googlemock/src/gmock_main.cc",
"googlemock/test",
"googlemock/CMakeLists.txt",
"googletest/cmake",
"googletest/scripts",
- "googletest/src/gtest-all.cc",
- "googletest/src/gtest_main.cc",
"googletest/test",
"googletest/CMakeLists.txt"
]
diff --git a/platformio.ini b/platformio.ini
deleted file mode 100644
index 7be1f7d5..00000000
--- a/platformio.ini
+++ /dev/null
@@ -1,47 +0,0 @@
-; PlatformIO Project Configuration File
-;
-; Build options: build flags, source filter
-; Upload options: custom upload port, speed and extra flags
-; Library options: dependencies, extra library storages
-; Advanced options: extra scripting
-;
-; Please visit documentation for the other options and examples
-; http://docs.platformio.org/page/projectconf.html
-
-
-[platformio]
-#src_dir = ./googlemock
-#src_dir = ./googletest
-src_dir = .
-
-[env:googletest_esp32]
-platform = espressif32
-board = esp32dev
-framework = arduino
-build_flags = -I./googletest/include -I./googletest
-src_filter = +<*> -<.git/> -<googlemock> -<googletest/samples> -<googletest/test/> -<googletest/src> +<googletest/src/gtest-all.cc> +<googletest/src/gtest_main.cc>
-upload_speed = 921600
-
-[env:googlemock_esp32]
-platform = espressif32
-board = esp32dev
-framework = arduino
-build_flags = -I./googlemock/include -I./googletest/include -I./googletest -I./googlemock
-src_filter = +<*> -<.git/> -<googletest> -<googlemock/test/> -<googlemock/src> +<googlemock/src/gmock-all.cc> +<googletest/src/gtest-all.cc> +<googlemock/src/gmock_main.cc>
-upload_speed = 921600
-
-[env:googletest_esp8266]
-platform = espressif8266
-board = huzzah
-framework = arduino
-build_flags = -I./googletest/include -I./googletest
-src_filter = +<*> -<.git/> -<googlemock> -<googletest/codegear/> -<googletest/samples> -<googletest/test/> -<googletest/xcode> -<googletest/src> +<googletest/src/gtest-all.cc> +<googletest/src/gtest_main.cc>
-upload_speed = 921600
-
-[env:googlemock_esp8266]
-platform = espressif8266
-board = huzzah
-framework = arduino
-build_flags = -I./googlemock/include -I./googletest/include -I./googletest -I./googlemock
-src_filter = +<*> -<.git/> -<googletest> -<googlemock/test/> -<googlemock/src> +<googlemock/src/gmock-all.cc> +<googletest/src/gtest-all.cc> +<googlemock/src/gmock_main.cc>
-upload_speed = 921600 \ No newline at end of file