Commit 2f86d137 by Christoph Grüninger Committed by Jesse Beder

Update googletest to 1.13

Fix issue with CMake 4.0
parent c9371de7
test/gtest-1.11.0 test/googletest-1.13.0
...@@ -8,7 +8,7 @@ EXAMPLE_PATH = ...@@ -8,7 +8,7 @@ EXAMPLE_PATH =
# One or more directories and files to exclude from documentation generation. # One or more directories and files to exclude from documentation generation.
# Use relative paths with respect to the repository root directory. # Use relative paths with respect to the repository root directory.
EXCLUDE = test/gtest-1.8.0/ EXCLUDE = test/googletest-1.13.0/
# One or more wildcard patterns to exclude files and directories from document # One or more wildcard patterns to exclude files and directories from document
# generation. # generation.
......
...@@ -11,9 +11,9 @@ if(YAML_USE_SYSTEM_GTEST) ...@@ -11,9 +11,9 @@ if(YAML_USE_SYSTEM_GTEST)
endif() endif()
else() else()
add_subdirectory( add_subdirectory(
"${CMAKE_CURRENT_SOURCE_DIR}/gtest-1.11.0" "${CMAKE_CURRENT_SOURCE_DIR}/googletest-1.13.0"
"${CMAKE_CURRENT_BINARY_DIR}/prefix") "${CMAKE_CURRENT_BINARY_DIR}/prefix")
include_directories(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/gtest-1.11.0/googletest/include") include_directories(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/googletest-1.13.0/googletest/include")
endif() endif()
set(test-new-api-pattern "new-api/*.cpp") set(test-new-api-pattern "new-api/*.cpp")
......
name: Bug Report
description: Let us know that something does not work as expected.
title: "[Bug]: Please title this bug report"
body:
- type: textarea
id: what-happened
attributes:
label: Describe the issue
description: What happened, and what did you expect to happen?
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce the problem
description: It is important that we are able to reproduce the problem that you are experiencing. Please provide all code and relevant steps to reproduce the problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the problem are also helpful.
validations:
required: true
- type: textarea
id: version
attributes:
label: What version of GoogleTest are you using?
description: Please include the output of `git rev-parse HEAD` or the GoogleTest release version number that you are using.
validations:
required: true
- type: textarea
id: os
attributes:
label: What operating system and version are you using?
description: If you are using a Linux distribution please include the name and version of the distribution as well.
validations:
required: true
- type: textarea
id: compiler
attributes:
label: What compiler and version are you using?
description: Please include the output of `gcc -v` or `clang -v`, or the equivalent for your compiler.
validations:
required: true
- type: textarea
id: buildsystem
attributes:
label: What build system are you using?
description: Please include the output of `bazel --version` or `cmake --version`, or the equivalent for your build system.
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional context
description: Add any other context about the problem here.
validations:
required: false
name: Feature request
description: Propose a new feature.
title: "[FR]: Please title this feature request"
labels: "enhancement"
body:
- type: textarea
id: version
attributes:
label: Does the feature exist in the most recent commit?
description: We recommend using the latest commit from GitHub in your projects.
validations:
required: true
- type: textarea
id: why
attributes:
label: Why do we need this feature?
description: Ideally, explain why a combination of existing features cannot be used instead.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Describe the proposal.
description: Include a detailed description of the feature, with usage examples.
validations:
required: true
- type: textarea
id: platform
attributes:
label: Is the feature specific to an operating system, compiler, or build system version?
description: If it is, please specify which versions.
validations:
required: true
blank_issues_enabled: false
contact_links:
- name: Get Help
url: https://github.com/google/googletest/discussions
about: Please ask and answer questions here.
name: ci
on:
push:
pull_request:
env:
BAZEL_CXXOPTS: -std=c++14
jobs:
Linux:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Tests
run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ...
macOS:
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Tests
run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ...
Windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Tests
run: bazel test --cxxopt=/std:c++14 --features=external_include_paths --test_output=errors ...
...@@ -30,8 +30,6 @@ ...@@ -30,8 +30,6 @@
# #
# Bazel Build for Google C++ Testing Framework(Google Test) # Bazel Build for Google C++ Testing Framework(Google Test)
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
package(default_visibility = ["//visibility:public"]) package(default_visibility = ["//visibility:public"])
licenses(["notice"]) licenses(["notice"])
...@@ -39,11 +37,26 @@ licenses(["notice"]) ...@@ -39,11 +37,26 @@ licenses(["notice"])
exports_files(["LICENSE"]) exports_files(["LICENSE"])
config_setting( config_setting(
name = "qnx",
constraint_values = ["@platforms//os:qnx"],
)
config_setting(
name = "windows", name = "windows",
constraint_values = ["@platforms//os:windows"], constraint_values = ["@platforms//os:windows"],
) )
config_setting( config_setting(
name = "freebsd",
constraint_values = ["@platforms//os:freebsd"],
)
config_setting(
name = "openbsd",
constraint_values = ["@platforms//os:openbsd"],
)
config_setting(
name = "msvc_compiler", name = "msvc_compiler",
flag_values = { flag_values = {
"@bazel_tools//tools/cpp:compiler": "msvc-cl", "@bazel_tools//tools/cpp:compiler": "msvc-cl",
...@@ -86,6 +99,7 @@ cc_library( ...@@ -86,6 +99,7 @@ cc_library(
"googlemock/include/gmock/*.h", "googlemock/include/gmock/*.h",
]), ]),
copts = select({ copts = select({
":qnx": [],
":windows": [], ":windows": [],
"//conditions:default": ["-pthread"], "//conditions:default": ["-pthread"],
}), }),
...@@ -104,7 +118,16 @@ cc_library( ...@@ -104,7 +118,16 @@ cc_library(
"googletest/include", "googletest/include",
], ],
linkopts = select({ linkopts = select({
":qnx": ["-lregex"],
":windows": [], ":windows": [],
":freebsd": [
"-lm",
"-pthread",
],
":openbsd": [
"-lm",
"-pthread",
],
"//conditions:default": ["-pthread"], "//conditions:default": ["-pthread"],
}), }),
deps = select({ deps = select({
...@@ -112,10 +135,15 @@ cc_library( ...@@ -112,10 +135,15 @@ cc_library(
"@com_google_absl//absl/debugging:failure_signal_handler", "@com_google_absl//absl/debugging:failure_signal_handler",
"@com_google_absl//absl/debugging:stacktrace", "@com_google_absl//absl/debugging:stacktrace",
"@com_google_absl//absl/debugging:symbolize", "@com_google_absl//absl/debugging:symbolize",
"@com_google_absl//absl/flags:flag",
"@com_google_absl//absl/flags:parse",
"@com_google_absl//absl/flags:reflection",
"@com_google_absl//absl/flags:usage",
"@com_google_absl//absl/strings", "@com_google_absl//absl/strings",
"@com_google_absl//absl/types:any", "@com_google_absl//absl/types:any",
"@com_google_absl//absl/types:optional", "@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:variant", "@com_google_absl//absl/types:variant",
"@com_googlesource_code_re2//:re2",
], ],
"//conditions:default": [], "//conditions:default": [],
}), }),
......
# Note: CMake support is community-based. The maintainers do not use CMake # Note: CMake support is community-based. The maintainers do not use CMake
# internally. # internally.
cmake_minimum_required(VERSION 2.8.12) cmake_minimum_required(VERSION 3.5)
if (POLICY CMP0048) if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW) cmake_policy(SET CMP0048 NEW)
endif (POLICY CMP0048) endif (POLICY CMP0048)
if (POLICY CMP0069)
cmake_policy(SET CMP0069 NEW)
endif (POLICY CMP0069)
if (POLICY CMP0077)
cmake_policy(SET CMP0077 NEW)
endif (POLICY CMP0077)
project(googletest-distribution) project(googletest-distribution)
set(GOOGLETEST_VERSION 1.11.0) set(GOOGLETEST_VERSION 1.13.0)
if (CMAKE_VERSION VERSION_GREATER "3.0.2") if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_EXTENSIONS OFF)
endif()
endif() endif()
enable_testing() enable_testing()
...@@ -24,6 +30,7 @@ include(GNUInstallDirs) ...@@ -24,6 +30,7 @@ include(GNUInstallDirs)
#Note that googlemock target already builds googletest #Note that googlemock target already builds googletest
option(BUILD_GMOCK "Builds the googlemock subproject" ON) option(BUILD_GMOCK "Builds the googlemock subproject" ON)
option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON)
option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF)
if(BUILD_GMOCK) if(BUILD_GMOCK)
add_subdirectory( googlemock ) add_subdirectory( googlemock )
......
...@@ -21,8 +21,8 @@ accept your pull requests. ...@@ -21,8 +21,8 @@ accept your pull requests.
## Are you a Googler? ## Are you a Googler?
If you are a Googler, please make an attempt to submit an internal change rather If you are a Googler, please make an attempt to submit an internal contribution
than a GitHub Pull Request. If you are not able to submit an internal change a rather than a GitHub Pull Request. If you are not able to submit internally, a
PR is acceptable as an alternative. PR is acceptable as an alternative.
## Contributing A Patch ## Contributing A Patch
...@@ -36,7 +36,8 @@ PR is acceptable as an alternative. ...@@ -36,7 +36,8 @@ PR is acceptable as an alternative.
This ensures that work isn't being duplicated and communicating your plan This ensures that work isn't being duplicated and communicating your plan
early also generally leads to better patches. early also generally leads to better patches.
4. If your proposed change is accepted, and you haven't already done so, sign a 4. If your proposed change is accepted, and you haven't already done so, sign a
Contributor License Agreement (see details above). Contributor License Agreement
([see details above](#contributor-license-agreements)).
5. Fork the desired repo, develop and test your code changes. 5. Fork the desired repo, develop and test your code changes.
6. Ensure that your code adheres to the existing style in the sample to which 6. Ensure that your code adheres to the existing style in the sample to which
you are contributing. you are contributing.
...@@ -79,8 +80,8 @@ fairly rigid coding style, as defined by the ...@@ -79,8 +80,8 @@ fairly rigid coding style, as defined by the
[google-styleguide](https://github.com/google/styleguide) project. All patches [google-styleguide](https://github.com/google/styleguide) project. All patches
will be expected to conform to the style outlined will be expected to conform to the style outlined
[here](https://google.github.io/styleguide/cppguide.html). Use [here](https://google.github.io/styleguide/cppguide.html). Use
[.clang-format](https://github.com/google/googletest/blob/master/.clang-format) [.clang-format](https://github.com/google/googletest/blob/main/.clang-format) to
to check your formatting. check your formatting.
## Requirements for Contributors ## Requirements for Contributors
......
...@@ -34,6 +34,7 @@ Manuel Klimek <klimek@google.com> ...@@ -34,6 +34,7 @@ Manuel Klimek <klimek@google.com>
Mario Tanev <radix@google.com> Mario Tanev <radix@google.com>
Mark Paskin Mark Paskin
Markus Heule <markus.heule@gmail.com> Markus Heule <markus.heule@gmail.com>
Martijn Vels <mvels@google.com>
Matthew Simmons <simmonmt@acm.org> Matthew Simmons <simmonmt@acm.org>
Mika Raento <mikie@iki.fi> Mika Raento <mikie@iki.fi>
Mike Bland <mbland@google.com> Mike Bland <mbland@google.com>
...@@ -55,6 +56,7 @@ Russ Rufer <russ@pentad.com> ...@@ -55,6 +56,7 @@ Russ Rufer <russ@pentad.com>
Sean Mcafee <eefacm@gmail.com> Sean Mcafee <eefacm@gmail.com>
Sigurður Ásgeirsson <siggi@google.com> Sigurður Ásgeirsson <siggi@google.com>
Sverre Sundsdal <sundsdal@gmail.com> Sverre Sundsdal <sundsdal@gmail.com>
Szymon Sobik <sobik.szymon@gmail.com>
Takeshi Yoshino <tyoshino@google.com> Takeshi Yoshino <tyoshino@google.com>
Tracy Bialik <tracy@pentad.com> Tracy Bialik <tracy@pentad.com>
Vadim Berman <vadimb@google.com> Vadim Berman <vadimb@google.com>
......
...@@ -6,7 +6,8 @@ ...@@ -6,7 +6,8 @@
GoogleTest now follows the GoogleTest now follows the
[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support). [Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
We recommend using the latest commit in the `master` branch in your projects. We recommend
[updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it).
#### Documentation Updates #### Documentation Updates
...@@ -14,11 +15,14 @@ Our documentation is now live on GitHub Pages at ...@@ -14,11 +15,14 @@ Our documentation is now live on GitHub Pages at
https://google.github.io/googletest/. We recommend browsing the documentation on https://google.github.io/googletest/. We recommend browsing the documentation on
GitHub Pages rather than directly in the repository. GitHub Pages rather than directly in the repository.
#### Release 1.10.x #### Release 1.12.1
[Release 1.10.x](https://github.com/google/googletest/releases/tag/release-1.10.0) [Release 1.12.1](https://github.com/google/googletest/releases/tag/release-1.12.1)
is now available. is now available.
The 1.12.x branch will be the last to support C++11. Future releases will
require at least C++14.
#### Coming Soon #### Coming Soon
* We are planning to take a dependency on * We are planning to take a dependency on
...@@ -55,39 +59,12 @@ More information about building GoogleTest can be found at ...@@ -55,39 +59,12 @@ More information about building GoogleTest can be found at
## Supported Platforms ## Supported Platforms
GoogleTest requires a codebase and compiler compliant with the C++11 standard or GoogleTest follows Google's
newer. [Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See
The GoogleTest code is officially supported on the following platforms. [this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
Operating systems or tools not listed below are community-supported. For for a list of currently supported versions compilers, platforms, and build
community-supported platforms, patches that do not complicate the code may be tools.
considered.
If you notice any problems on your platform, please file an issue on the
[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
Pull requests containing fixes are welcome!
### Operating Systems
* Linux
* macOS
* Windows
### Compilers
* gcc 5.0+
* clang 5.0+
* MSVC 2015+
**macOS users:** Xcode 9.3+ provides clang 5.0+.
### Build Systems
* [Bazel](https://bazel.build/)
* [CMake](https://cmake.org/)
**Note:** Bazel is the build system used by the team internally and in tests.
CMake is supported on a best-effort basis and by the community.
## Who Is Using GoogleTest? ## Who Is Using GoogleTest?
...@@ -109,8 +86,8 @@ Windows and Linux platforms. ...@@ -109,8 +86,8 @@ Windows and Linux platforms.
[GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that [GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that
runs your test binary, allows you to track its progress via a progress bar, and runs your test binary, allows you to track its progress via a progress bar, and
displays a list of test failures. Clicking on one shows failure text. Google displays a list of test failures. Clicking on one shows failure text. GoogleTest
Test UI is written in C#. UI is written in C#.
[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event [GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event
listener for GoogleTest that implements the listener for GoogleTest that implements the
...@@ -121,11 +98,11 @@ result output. If your test runner understands TAP, you may find it useful. ...@@ -121,11 +98,11 @@ result output. If your test runner understands TAP, you may find it useful.
runs tests from your binary in parallel to provide significant speed-up. runs tests from your binary in parallel to provide significant speed-up.
[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) [GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter)
is a VS Code extension allowing to view GoogleTest in a tree view, and run/debug is a VS Code extension allowing to view GoogleTest in a tree view and run/debug
your tests. your tests.
[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS [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 Code extension allowing to view GoogleTest in a tree view and run/debug your
tests. tests.
[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser [Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser
...@@ -134,7 +111,7 @@ that generates stub code for GoogleTest. ...@@ -134,7 +111,7 @@ that generates stub code for GoogleTest.
## Contributing Changes ## Contributing Changes
Please read Please read
[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/master/CONTRIBUTING.md) [`CONTRIBUTING.md`](https://github.com/google/googletest/blob/main/CONTRIBUTING.md)
for details on how to contribute to this project. for details on how to contribute to this project.
Happy testing! Happy testing!
workspace(name = "com_google_googletest")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "com_google_absl", # 2023-01-10T21:08:25Z
sha256 = "f9a4e749f42c386a32a90fddf0e2913ed408d10c42f7f33ccf4c59ac4f0d1d05",
strip_prefix = "abseil-cpp-52835439ca90d86b27bf8cd1708296e95604d724",
urls = ["https://github.com/abseil/abseil-cpp/archive/52835439ca90d86b27bf8cd1708296e95604d724.zip"],
)
# Note this must use a commit from the `abseil` branch of the RE2 project.
# https://github.com/google/re2/tree/abseil
http_archive(
name = "com_googlesource_code_re2", # 2022-12-21T14:29:10Z
sha256 = "b9ce3a51beebb38534d11d40f8928d40509b9e18a735f6a4a97ad3d014c87cb5",
strip_prefix = "re2-d0b1f8f2ecc2ea74956c7608b6f915175314ff0e",
urls = ["https://github.com/google/re2/archive/d0b1f8f2ecc2ea74956c7608b6f915175314ff0e.zip"],
)
http_archive(
name = "rules_python", # 2023-01-10T22:00:51Z
sha256 = "5de54486a60ad8948dabe49605bb1c08053e04001a431ab3e96745b4d97a4419",
strip_prefix = "rules_python-70cce26432187a60b4e950118791385e6fb3c26f",
urls = ["https://github.com/bazelbuild/rules_python/archive/70cce26432187a60b4e950118791385e6fb3c26f.zip"],
)
http_archive(
name = "bazel_skylib", # 2022-11-16T18:29:32Z
sha256 = "a22290c26d29d3ecca286466f7f295ac6cbe32c0a9da3a91176a90e0725e3649",
strip_prefix = "bazel-skylib-5bfcb1a684550626ce138fe0fe8f5f702b3764c3",
urls = ["https://github.com/bazelbuild/bazel-skylib/archive/5bfcb1a684550626ce138fe0fe8f5f702b3764c3.zip"],
)
http_archive(
name = "platforms", # 2022-11-09T19:18:22Z
sha256 = "b4a3b45dc4202e2b3e34e3bc49d2b5b37295fc23ea58d88fb9e01f3642ad9b55",
strip_prefix = "platforms-3fbc687756043fb58a407c2ea8c944bc2fe1d922",
urls = ["https://github.com/bazelbuild/platforms/archive/3fbc687756043fb58a407c2ea8c944bc2fe1d922.zip"],
)
...@@ -31,15 +31,15 @@ ...@@ -31,15 +31,15 @@
set -euox pipefail set -euox pipefail
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20210525" readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20220217"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20201015" readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20220621"
if [[ -z ${GTEST_ROOT:-} ]]; then if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)" GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi fi
if [[ -z ${STD:-} ]]; then if [[ -z ${STD:-} ]]; then
STD="c++11 c++14 c++17 c++20" STD="c++14 c++17 c++20"
fi fi
# Test the CMake build # Test the CMake build
...@@ -55,7 +55,7 @@ for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do ...@@ -55,7 +55,7 @@ for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
${LINUX_LATEST_CONTAINER} \ ${LINUX_LATEST_CONTAINER} \
/bin/bash -c " /bin/bash -c "
cmake /src \ cmake /src \
-DCMAKE_CXX_STANDARD=11 \ -DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \ -Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \ -Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \ -Dgmock_build_tests=ON \
...@@ -72,11 +72,15 @@ time docker run \ ...@@ -72,11 +72,15 @@ time docker run \
--workdir="/src" \ --workdir="/src" \
--rm \ --rm \
--env="CC=/usr/local/bin/gcc" \ --env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=c++14" \
${LINUX_GCC_FLOOR_CONTAINER} \ ${LINUX_GCC_FLOOR_CONTAINER} \
/usr/local/bin/bazel test ... \ /usr/local/bin/bazel test ... \
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wno-error=pragmas" \ --copt="-Wno-error=pragmas" \
--distdir="/bazel-distdir" \
--features=external_include_paths \
--keep_going \ --keep_going \
--show_timestamps \ --show_timestamps \
--test_output=errors --test_output=errors
...@@ -94,8 +98,10 @@ for std in ${STD}; do ...@@ -94,8 +98,10 @@ for std in ${STD}; do
/usr/local/bin/bazel test ... \ /usr/local/bin/bazel test ... \
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wuninitialized" \
--define="absl=${absl}" \ --define="absl=${absl}" \
--distdir="/bazel-distdir" \ --distdir="/bazel-distdir" \
--features=external_include_paths \
--keep_going \ --keep_going \
--show_timestamps \ --show_timestamps \
--test_output=errors --test_output=errors
...@@ -116,8 +122,10 @@ for std in ${STD}; do ...@@ -116,8 +122,10 @@ for std in ${STD}; do
--copt="--gcc-toolchain=/usr/local" \ --copt="--gcc-toolchain=/usr/local" \
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wuninitialized" \
--define="absl=${absl}" \ --define="absl=${absl}" \
--distdir="/bazel-distdir" \ --distdir="/bazel-distdir" \
--features=external_include_paths \
--keep_going \ --keep_going \
--linkopt="--gcc-toolchain=/usr/local" \ --linkopt="--gcc-toolchain=/usr/local" \
--show_timestamps \ --show_timestamps \
......
...@@ -40,7 +40,7 @@ for cmake_off_on in OFF ON; do ...@@ -40,7 +40,7 @@ for cmake_off_on in OFF ON; do
BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX) BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)
cd ${BUILD_DIR} cd ${BUILD_DIR}
time cmake ${GTEST_ROOT} \ time cmake ${GTEST_ROOT} \
-DCMAKE_CXX_STANDARD=11 \ -DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \ -Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \ -Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \ -Dgmock_build_tests=ON \
...@@ -53,7 +53,7 @@ done ...@@ -53,7 +53,7 @@ done
# Test the Bazel build # Test the Bazel build
# If we are running on Kokoro, check for a versioned Bazel binary. # If we are running on Kokoro, check for a versioned Bazel binary.
KOKORO_GFILE_BAZEL_BIN="bazel-3.7.0-darwin-x86_64" KOKORO_GFILE_BAZEL_BIN="bazel-5.1.1-darwin-x86_64"
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then
BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}" BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}"
chmod +x ${BAZEL_BIN} chmod +x ${BAZEL_BIN}
...@@ -66,7 +66,9 @@ for absl in 0 1; do ...@@ -66,7 +66,9 @@ for absl in 0 1; do
${BAZEL_BIN} test ... \ ${BAZEL_BIN} test ... \
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--cxxopt="-std=c++14" \
--define="absl=${absl}" \ --define="absl=${absl}" \
--features=external_include_paths \
--keep_going \ --keep_going \
--show_timestamps \ --show_timestamps \
--test_output=errors --test_output=errors
......
SETLOCAL ENABLEDELAYEDEXPANSION
SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-5.1.1-windows-x86_64.exe
SET PATH=C:\Python37;%PATH%
SET BAZEL_PYTHON=C:\python37\python.exe
SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe
SET CMAKE_BIN="C:\Program Files\CMake\bin\cmake.exe"
SET CTEST_BIN="C:\Program Files\CMake\bin\ctest.exe"
SET CTEST_OUTPUT_ON_FAILURE=1
IF EXIST git\googletest (
CD git\googletest
) ELSE IF EXIST github\googletest (
CD github\googletest
)
IF %errorlevel% neq 0 EXIT /B 1
:: ----------------------------------------------------------------------------
:: CMake Visual Studio 15 2017 Win64
MKDIR cmake_msvc2017
CD cmake_msvc2017
%CMAKE_BIN% .. ^
-G "Visual Studio 15 2017 Win64" ^
-DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^
-DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^
-DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^
-Dgtest_build_samples=ON ^
-Dgtest_build_tests=ON ^
-Dgmock_build_tests=ON
IF %errorlevel% neq 0 EXIT /B 1
%CMAKE_BIN% --build . --target ALL_BUILD --config Debug -- -maxcpucount
IF %errorlevel% neq 0 EXIT /B 1
%CTEST_BIN% -C Debug --timeout 600
IF %errorlevel% neq 0 EXIT /B 1
CD ..
RMDIR /S /Q cmake_msvc2017
:: ----------------------------------------------------------------------------
:: Bazel Visual Studio 15 2017 Win64
SET BAZEL_VC=C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC
%BAZEL_EXE% test ... ^
--compilation_mode=dbg ^
--copt=/std:c++14 ^
--copt=/WX ^
--features=external_include_paths ^
--keep_going ^
--test_output=errors ^
--test_tag_filters=-no_test_msvc2017
IF %errorlevel% neq 0 EXIT /B 1
...@@ -48,7 +48,7 @@ ...@@ -48,7 +48,7 @@
<div class="footer"> <div class="footer">
GoogleTest &middot; GoogleTest &middot;
<a href="https://github.com/google/googletest">GitHub Repository</a> &middot; <a href="https://github.com/google/googletest">GitHub Repository</a> &middot;
<a href="https://github.com/google/googletest/blob/master/LICENSE">License</a> &middot; <a href="https://github.com/google/googletest/blob/main/LICENSE">License</a> &middot;
<a href="https://policies.google.com/privacy">Privacy Policy</a> <a href="https://policies.google.com/privacy">Privacy Policy</a>
</div> </div>
</div> </div>
......
...@@ -8,7 +8,7 @@ Given ...@@ -8,7 +8,7 @@ Given
```cpp ```cpp
class Foo { class Foo {
... public:
virtual ~Foo(); virtual ~Foo();
virtual int GetSize() const = 0; virtual int GetSize() const = 0;
virtual string Describe(const char* name) = 0; virtual string Describe(const char* name) = 0;
...@@ -23,7 +23,7 @@ class Foo { ...@@ -23,7 +23,7 @@ class Foo {
#include "gmock/gmock.h" #include "gmock/gmock.h"
class MockFoo : public Foo { class MockFoo : public Foo {
... public:
MOCK_METHOD(int, GetSize, (), (const, override)); MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(string, Describe, (const char* name), (override)); MOCK_METHOD(string, Describe, (const char* name), (override));
MOCK_METHOD(string, Describe, (int type), (override)); MOCK_METHOD(string, Describe, (int type), (override));
...@@ -58,7 +58,7 @@ To mock ...@@ -58,7 +58,7 @@ To mock
```cpp ```cpp
template <typename Elem> template <typename Elem>
class StackInterface { class StackInterface {
... public:
virtual ~StackInterface(); virtual ~StackInterface();
virtual int GetSize() const = 0; virtual int GetSize() const = 0;
virtual void Push(const Elem& x) = 0; virtual void Push(const Elem& x) = 0;
...@@ -71,7 +71,7 @@ class StackInterface { ...@@ -71,7 +71,7 @@ class StackInterface {
```cpp ```cpp
template <typename Elem> template <typename Elem>
class MockStack : public StackInterface<Elem> { class MockStack : public StackInterface<Elem> {
... public:
MOCK_METHOD(int, GetSize, (), (const, override)); MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(void, Push, (const Elem& x), (override)); MOCK_METHOD(void, Push, (const Elem& x), (override));
}; };
...@@ -140,7 +140,7 @@ To customize the default action for functions with return type `T`, use ...@@ -140,7 +140,7 @@ To customize the default action for functions with return type `T`, use
// Sets the default action for return type std::unique_ptr<Buzz> to // Sets the default action for return type std::unique_ptr<Buzz> to
// creating a new Buzz every time. // creating a new Buzz every time.
DefaultValue<std::unique_ptr<Buzz>>::SetFactory( DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
[] { return MakeUnique<Buzz>(AccessLevel::kInternal); }); [] { return std::make_unique<Buzz>(AccessLevel::kInternal); });
// When this fires, the default action of MakeBuzz() will run, which // When this fires, the default action of MakeBuzz() will run, which
// will return a new Buzz object. // will return a new Buzz object.
...@@ -230,7 +230,7 @@ class MockFunction<R(A1, ..., An)> { ...@@ -230,7 +230,7 @@ class MockFunction<R(A1, ..., An)> {
}; };
``` ```
See this [recipe](gmock_cook_book.md#using-check-points) for one application of See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of
it. it.
## Flags ## Flags
......
...@@ -369,8 +369,8 @@ Usually, if your action is for a particular function type, defining it using ...@@ -369,8 +369,8 @@ Usually, if your action is for a particular function type, defining it using
different types (e.g. if you are defining `Return(*value*)`), different types (e.g. if you are defining `Return(*value*)`),
`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what `MakePolymorphicAction()` is easiest. Sometimes you want precise control on what
types of functions the action can be used in, and implementing `ActionInterface` types of functions the action can be used in, and implementing `ActionInterface`
is the way to go here. See the implementation of `Return()` in is the way to go here. See the implementation of `Return()` in `gmock-actions.h`
`testing/base/public/gmock-actions.h` for an example. for an example.
### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean? ### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean?
......
...@@ -190,10 +190,10 @@ Some people put it in a `_test.cc`. This is fine when the interface being mocked ...@@ -190,10 +190,10 @@ Some people put it in a `_test.cc`. This is fine when the interface being mocked
`Foo` changes it, your test could break. (You can't really expect `Foo`'s `Foo` changes it, your test could break. (You can't really expect `Foo`'s
maintainer to fix every test that uses `Foo`, can you?) maintainer to fix every test that uses `Foo`, can you?)
So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, Generally, you should not mock classes you don't own. If you must mock such a
define the mock class in `Foo`'s package (better, in a `testing` sub-package class owned by others, define the mock class in `Foo`'s Bazel package (usually
such that you can clearly separate production code and testing utilities), put the same directory or a `testing` sub-directory), and put it in a `.h` and a
it in a `.h` and a `cc_library`. Then everyone can reference them from their `cc_library` with `testonly=True`. Then everyone can reference them from their
tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and
only tests that depend on the changed methods need to be fixed. only tests that depend on the changed methods need to be fixed.
...@@ -480,8 +480,8 @@ the *default* action for the function every time (unless, of course, you have a ...@@ -480,8 +480,8 @@ the *default* action for the function every time (unless, of course, you have a
`WillRepeatedly()`.). `WillRepeatedly()`.).
What can we do inside `WillOnce()` besides `Return()`? You can return a What can we do inside `WillOnce()` besides `Return()`? You can return a
reference using `ReturnRef(*variable*)`, or invoke a pre-defined function, among reference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function,
[others](gmock_cook_book.md#using-actions). among [others](gmock_cook_book.md#using-actions).
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause **Important note:** The `EXPECT_CALL()` statement evaluates the action clause
only once, even though the action may be performed many times. Therefore you only once, even though the action may be performed many times. Therefore you
......
...@@ -105,7 +105,7 @@ includedir=/usr/include ...@@ -105,7 +105,7 @@ includedir=/usr/include
Name: gtest Name: gtest
Description: GoogleTest (without main() function) Description: GoogleTest (without main() function)
Version: 1.10.0 Version: 1.11.0
URL: https://github.com/google/googletest URL: https://github.com/google/googletest
Libs: -L${libdir} -lgtest -lpthread Libs: -L${libdir} -lgtest -lpthread
Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread
......
...@@ -162,9 +162,9 @@ TEST(TestSuiteName, TestName) { ...@@ -162,9 +162,9 @@ TEST(TestSuiteName, TestName) {
`TEST()` arguments go from general to specific. The *first* argument is the name `TEST()` arguments go from general to specific. The *first* argument is the name
of the test suite, and the *second* argument is the test's name within the test of the test suite, and the *second* argument is the test's name within the test
suite. Both names must be valid C++ identifiers, and they should not contain suite. Both names must be valid C++ identifiers, and they should not contain any
any underscores (`_`). A test's *full name* consists of its containing test suite and underscores (`_`). A test's *full name* consists of its containing test suite
its individual name. Tests from different test suites can have the same and its individual name. Tests from different test suites can have the same
individual name. individual name.
For example, let's take a simple integer function: For example, let's take a simple integer function:
...@@ -245,8 +245,8 @@ Also, you must first define a test fixture class before using it in a ...@@ -245,8 +245,8 @@ Also, you must first define a test fixture class before using it in a
declaration`". declaration`".
For each test defined with `TEST_F()`, googletest will create a *fresh* test For each test defined with `TEST_F()`, googletest will create a *fresh* test
fixture at runtime, immediately initialize it via `SetUp()`, run the test, fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean
clean up by calling `TearDown()`, and then delete the test fixture. Note that up by calling `TearDown()`, and then delete the test fixture. Note that
different tests in the same test suite have different test fixture objects, and different tests in the same test suite have different test fixture objects, and
googletest always deletes a test fixture before it creates the next one. googletest always deletes a test fixture before it creates the next one.
googletest does **not** reuse the same test fixture for multiple tests. Any googletest does **not** reuse the same test fixture for multiple tests. Any
...@@ -274,6 +274,7 @@ First, define a fixture class. By convention, you should give it the name ...@@ -274,6 +274,7 @@ First, define a fixture class. By convention, you should give it the name
class QueueTest : public ::testing::Test { class QueueTest : public ::testing::Test {
protected: protected:
void SetUp() override { void SetUp() override {
// q0_ remains empty
q1_.Enqueue(1); q1_.Enqueue(1);
q2_.Enqueue(2); q2_.Enqueue(2);
q2_.Enqueue(3); q2_.Enqueue(3);
...@@ -342,8 +343,8 @@ your defined tests in order to run them. ...@@ -342,8 +343,8 @@ your defined tests in order to run them.
After defining your tests, you can run them with `RUN_ALL_TESTS()`, which After defining your tests, you can run them with `RUN_ALL_TESTS()`, which
returns `0` if all the tests are successful, or `1` otherwise. Note that returns `0` if all the tests are successful, or `1` otherwise. Note that
`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from `RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different
different test suites, or even different source files. test suites, or even different source files.
When invoked, the `RUN_ALL_TESTS()` macro: When invoked, the `RUN_ALL_TESTS()` macro:
...@@ -456,8 +457,8 @@ int main(int argc, char **argv) { ...@@ -456,8 +457,8 @@ int main(int argc, char **argv) {
The `::testing::InitGoogleTest()` function parses the command line for The `::testing::InitGoogleTest()` function parses the command line for
googletest flags, and removes all recognized flags. This allows the user to googletest flags, and removes all recognized flags. This allows the user to
control a test program's behavior via various flags, which we'll cover in control a test program's behavior via various flags, which we'll cover in the
the [AdvancedGuide](advanced.md). You **must** call this function before calling [AdvancedGuide](advanced.md). You **must** call this function before calling
`RUN_ALL_TESTS()`, or the flags won't be properly initialized. `RUN_ALL_TESTS()`, or the flags won't be properly initialized.
On Windows, `InitGoogleTest()` also works with wide strings, so it can be used On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
......
...@@ -9,7 +9,7 @@ we recommend this tutorial as a starting point. ...@@ -9,7 +9,7 @@ we recommend this tutorial as a starting point.
To complete this tutorial, you'll need: To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows). * A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++11. * A compatible C++ compiler that supports at least C++14.
* [Bazel](https://bazel.build/), the preferred build system used by the * [Bazel](https://bazel.build/), the preferred build system used by the
GoogleTest team. GoogleTest team.
...@@ -17,16 +17,15 @@ See [Supported Platforms](platforms.md) for more information about platforms ...@@ -17,16 +17,15 @@ See [Supported Platforms](platforms.md) for more information about platforms
compatible with GoogleTest. compatible with GoogleTest.
If you don't already have Bazel installed, see the If you don't already have Bazel installed, see the
[Bazel installation guide](https://docs.bazel.build/versions/master/install.html). [Bazel installation guide](https://bazel.build/install).
{: .callout .note} {: .callout .note} Note: The terminal commands in this tutorial show a Unix
Note: The terminal commands in this tutorial show a Unix shell prompt, but the shell prompt, but the commands work on the Windows command line as well.
commands work on the Windows command line as well.
## Set up a Bazel workspace ## Set up a Bazel workspace
A A
[Bazel workspace](https://docs.bazel.build/versions/master/build-ref.html#workspace) [Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace)
is a directory on your filesystem that you use to manage source files for the is a directory on your filesystem that you use to manage source files for the
software you want to build. Each workspace directory has a text file named software you want to build. Each workspace directory has a text file named
`WORKSPACE` which may be empty, or may contain references to external `WORKSPACE` which may be empty, or may contain references to external
...@@ -40,9 +39,9 @@ $ mkdir my_workspace && cd my_workspace ...@@ -40,9 +39,9 @@ $ mkdir my_workspace && cd my_workspace
Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and
recommended way to depend on GoogleTest is to use a recommended way to depend on GoogleTest is to use a
[Bazel external dependency](https://docs.bazel.build/versions/master/external.html) [Bazel external dependency](https://docs.bazel.build/versions/main/external.html)
via the via the
[`http_archive` rule](https://docs.bazel.build/versions/master/repo/http.html#http_archive). [`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive).
To do this, in the root directory of your workspace (`my_workspace/`), create a To do this, in the root directory of your workspace (`my_workspace/`), create a
file named `WORKSPACE` with the following contents: file named `WORKSPACE` with the following contents:
...@@ -51,28 +50,16 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") ...@@ -51,28 +50,16 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive( http_archive(
name = "com_google_googletest", name = "com_google_googletest",
urls = ["https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip"], urls = ["https://github.com/google/googletest/archive/5ab508a01f9eb089207ee87fd547d290da39d015.zip"],
strip_prefix = "googletest-609281088cfefc76f9d0ce82e1ff6c30cc3591e5", strip_prefix = "googletest-5ab508a01f9eb089207ee87fd547d290da39d015",
) )
``` ```
The above configuration declares a dependency on GoogleTest which is downloaded The above configuration declares a dependency on GoogleTest which is downloaded
as a ZIP archive from GitHub. In the above example, as a ZIP archive from GitHub. In the above example,
`609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is the Git commit hash of the `5ab508a01f9eb089207ee87fd547d290da39d015` is the Git commit hash of the
GoogleTest version to use; we recommend updating the hash often to point to the GoogleTest version to use; we recommend updating the hash often to point to the
latest version. latest version. Use a recent hash on the `main` branch.
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. Now you're ready to build C++ code that uses GoogleTest.
...@@ -104,8 +91,6 @@ To build the code, create a file named `BUILD` in the same directory with the ...@@ -104,8 +91,6 @@ To build the code, create a file named `BUILD` in the same directory with the
following contents: following contents:
``` ```
load("@rules_cc//cc:defs.bzl", "cc_test")
cc_test( cc_test(
name = "hello_test", name = "hello_test",
size = "small", size = "small",
...@@ -118,7 +103,7 @@ This `cc_test` rule declares the C++ test binary you want to build, and links to ...@@ -118,7 +103,7 @@ 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` GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE`
file (`@com_google_googletest`). For more information about Bazel `BUILD` files, file (`@com_google_googletest`). For more information about Bazel `BUILD` files,
see the see the
[Bazel C++ Tutorial](https://docs.bazel.build/versions/master/tutorial/cpp.html). [Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html).
Now you can build and run your test: Now you can build and run your test:
......
...@@ -10,7 +10,7 @@ this tutorial as a starting point. If your project uses Bazel, see the ...@@ -10,7 +10,7 @@ this tutorial as a starting point. If your project uses Bazel, see the
To complete this tutorial, you'll need: To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows). * A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++11. * A compatible C++ compiler that supports at least C++14.
* [CMake](https://cmake.org/) and a compatible build tool for building the * [CMake](https://cmake.org/) and a compatible build tool for building the
project. project.
* Compatible build tools include * Compatible build tools include
...@@ -52,13 +52,13 @@ To do this, in your project directory (`my_project`), create a file named ...@@ -52,13 +52,13 @@ To do this, in your project directory (`my_project`), create a file named
cmake_minimum_required(VERSION 3.14) cmake_minimum_required(VERSION 3.14)
project(my_project) project(my_project)
# GoogleTest requires at least C++11 # GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD 14)
include(FetchContent) include(FetchContent)
FetchContent_Declare( FetchContent_Declare(
googletest googletest
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
) )
# For Windows: Prevent overriding the parent project's compiler/linker settings # For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
...@@ -66,7 +66,7 @@ FetchContent_MakeAvailable(googletest) ...@@ -66,7 +66,7 @@ FetchContent_MakeAvailable(googletest)
``` ```
The above configuration declares a dependency on GoogleTest which is downloaded The above configuration declares a dependency on GoogleTest which is downloaded
from GitHub. In the above example, `609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is
the Git commit hash of the GoogleTest version to use; we recommend updating the the Git commit hash of the GoogleTest version to use; we recommend updating the
hash often to point to the latest version. hash often to point to the latest version.
...@@ -108,7 +108,7 @@ add_executable( ...@@ -108,7 +108,7 @@ add_executable(
) )
target_link_libraries( target_link_libraries(
hello_test hello_test
gtest_main GTest::gtest_main
) )
include(GoogleTest) include(GoogleTest)
......
...@@ -6,7 +6,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace. ...@@ -6,7 +6,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace.
## Returning a Value ## Returning a Value
| | | | Action | Description |
| :-------------------------------- | :-------------------------------------------- | | :-------------------------------- | :-------------------------------------------- |
| `Return()` | Return from a `void` mock function. | | `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. | | `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. |
...@@ -20,7 +20,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace. ...@@ -20,7 +20,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace.
## Side Effects ## Side Effects
| | | | Action | Description |
| :--------------------------------- | :-------------------------------------- | | :--------------------------------- | :-------------------------------------- |
| `Assign(&variable, value)` | Assign `value` to variable. | | `Assign(&variable, value)` | Assign `value` to variable. |
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | | `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
...@@ -38,9 +38,9 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace. ...@@ -38,9 +38,9 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace.
In the following, by "callable" we mean a free function, `std::function`, In the following, by "callable" we mean a free function, `std::function`,
functor, or lambda. functor, or lambda.
| | | | Action | Description |
| :---------------------------------- | :------------------------------------- | | :---------------------------------- | :------------------------------------- |
| `f` | Invoke f with the arguments passed to the mock function, where f is a callable. | | `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(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. | | `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(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. |
...@@ -86,7 +86,7 @@ value, and `foo` by reference. ...@@ -86,7 +86,7 @@ value, and `foo` by reference.
## Default Action ## Default Action
| Matcher | Description | | Action | Description |
| :------------ | :----------------------------------------------------- | | :------------ | :----------------------------------------------------- |
| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | | `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |
...@@ -96,7 +96,7 @@ composite action - trying to do so will result in a run-time error. ...@@ -96,7 +96,7 @@ composite action - trying to do so will result in a run-time error.
## Composite Actions ## Composite Actions
| | | | Action | Description |
| :----------------------------- | :------------------------------------------ | | :----------------------------- | :------------------------------------------ |
| `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. | | `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. | | `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. |
...@@ -106,7 +106,7 @@ composite action - trying to do so will result in a run-time error. ...@@ -106,7 +106,7 @@ composite action - trying to do so will result in a run-time error.
## Defining Actions ## Defining Actions
| | | | Macro | Description |
| :--------------------------------- | :-------------------------------------- | | :--------------------------------- | :-------------------------------------- |
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | | `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_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
......
...@@ -8,9 +8,13 @@ A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or ...@@ -8,9 +8,13 @@ A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | | `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. | | `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. |
{: .callout .note} {: .callout .warning}
**Note:** Although equality matching via `EXPECT_THAT(actual_value, **WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)`
expected_value)` is supported, prefer to make the comparison explicit via is supported, however note that implicit conversions can cause surprising
results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and
may pass unintentionally.
**BEST PRACTICE:** Prefer to make the comparison explicit via
`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, `EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value,
expected_value)`. expected_value)`.
...@@ -88,16 +92,17 @@ The `argument` can be either a C string or a C++ string object: ...@@ -88,16 +92,17 @@ The `argument` can be either a C string or a C++ string object:
| Matcher | Description | | Matcher | Description |
| :---------------------- | :------------------------------------------------- | | :---------------------- | :------------------------------------------------- |
| `ContainsRegex(string)` | `argument` matches the given regular expression. | | `ContainsRegex(string)` | `argument` matches the given regular expression. |
| `EndsWith(suffix)` | `argument` ends with string `suffix`. | | `EndsWith(suffix)` | `argument` ends with string `suffix`. |
| `HasSubstr(string)` | `argument` contains `string` as a sub-string. | | `HasSubstr(string)` | `argument` contains `string` as a sub-string. |
| `IsEmpty()` | `argument` is an empty 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. | | `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`. | | `StartsWith(prefix)` | `argument` starts with string `prefix`. |
| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | | `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. |
| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | | `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. |
| `StrEq(string)` | `argument` is equal to `string`. | | `StrEq(string)` | `argument` is equal to `string`. |
| `StrNe(string)` | `argument` is not equal to `string`. | | `StrNe(string)` | `argument` is not equal to `string`. |
| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. |
`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They `ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
use the regular expression syntax defined use the regular expression syntax defined
...@@ -116,6 +121,7 @@ messages, you can use: ...@@ -116,6 +121,7 @@ messages, you can use:
| `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. | | `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. | | `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. | | `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. |
| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which can be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains(e).Times(0)`. |
| `Each(e)` | `argument` is a container where *every* element 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. | | `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. | | `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. |
...@@ -146,7 +152,6 @@ messages, you can use: ...@@ -146,7 +152,6 @@ messages, you can use:
one might write: one might write:
```cpp ```cpp
using ::std::get;
MATCHER(FooEq, "") { MATCHER(FooEq, "") {
return std::get<0>(arg).Equals(std::get<1>(arg)); return std::get<0>(arg).Equals(std::get<1>(arg));
} }
...@@ -193,6 +198,7 @@ messages, you can use: ...@@ -193,6 +198,7 @@ messages, you can use:
| Matcher | Description | | Matcher | Description |
| :--------------- | :------------------------------------------------ | | :--------------- | :------------------------------------------------ |
| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | | `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. |
| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message.
## Pointer Matchers ## Pointer Matchers
...@@ -237,6 +243,7 @@ You can make a matcher from one or more other matchers: ...@@ -237,6 +243,7 @@ You can make a matcher from one or more other matchers:
| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | | `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. | | `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`. | | `Not(m)` | `argument` doesn't match matcher `m`. |
| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evaluates to true, else matches `m2`.|
## Adapters for Matchers ## Adapters for Matchers
...@@ -259,7 +266,7 @@ which must be a permanent callback. ...@@ -259,7 +266,7 @@ which must be a permanent callback.
## Defining Matchers ## Defining Matchers
| Matcher | Description | | Macro | Description |
| :----------------------------------- | :------------------------------------ | | :----------------------------------- | :------------------------------------ |
| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | | `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_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`. |
......
...@@ -248,7 +248,9 @@ EXPECT_CALL(my_mock, GetNumber()) ...@@ -248,7 +248,9 @@ EXPECT_CALL(my_mock, GetNumber())
.WillOnce(Return(3)); .WillOnce(Return(3));
``` ```
The `WillOnce` clause can be used any number of times on an expectation. The `WillOnce` clause can be used any number of times on an expectation. Unlike
`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most
once, so may be a move-only type and/or have an `&&`-qualified call operator.
#### WillRepeatedly {#EXPECT_CALL.WillRepeatedly} #### WillRepeatedly {#EXPECT_CALL.WillRepeatedly}
......
...@@ -109,7 +109,7 @@ namespace: ...@@ -109,7 +109,7 @@ namespace:
| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. | | `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. |
| `Bool()` | Yields sequence `{false, true}`. | | `Bool()` | Yields sequence `{false, true}`. |
| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. | | `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. |
| `ConvertGenerator<T>(g)` | Yields values generated by generator `g`, `static_cast` to `T`. |
The optional last argument *`name_generator`* is a function or functor that The optional last argument *`name_generator`* is a function or functor that
generates custom test name suffixes based on the test parameters. The function generates custom test name suffixes based on the test parameters. The function
must accept an argument of type must accept an argument of type
...@@ -518,8 +518,8 @@ Logs a property for the current test, test suite, or entire invocation of the ...@@ -518,8 +518,8 @@ Logs a property for the current test, test suite, or entire invocation of the
test program. Only the last value for a given key is logged. test program. Only the last value for a given key is logged.
The key must be a valid XML attribute name, and cannot conflict with the ones The key must be a valid XML attribute name, and cannot conflict with the ones
already used by GoogleTest (`name`, `status`, `time`, `classname`, `type_param`, already used by GoogleTest (`name`, `file`, `line`, `status`, `time`,
and `value_param`). `classname`, `type_param`, and `value_param`).
`RecordProperty` is `public static` so it can be called from utility functions `RecordProperty` is `public static` so it can be called from utility functions
that are not members of the test fixture. that are not members of the test fixture.
......
# Googletest Samples # Googletest Samples
If you're like us, you'd like to look at If you're like us, you'd like to look at
[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples) [googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples)
The sample directory has a number of well-commented samples showing how to use a The sample directory has a number of well-commented samples showing how to use a
variety of googletest features. variety of googletest features.
......
...@@ -36,13 +36,9 @@ endif() ...@@ -36,13 +36,9 @@ endif()
# as ${gmock_SOURCE_DIR} and to the root binary directory as # as ${gmock_SOURCE_DIR} and to the root binary directory as
# ${gmock_BINARY_DIR}. # ${gmock_BINARY_DIR}.
# Language "C" is required for find_package(Threads). # Language "C" is required for find_package(Threads).
if (CMAKE_VERSION VERSION_LESS 3.0) cmake_minimum_required(VERSION 3.5)
project(gmock CXX C) cmake_policy(SET CMP0048 NEW)
else() project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
cmake_policy(SET CMP0048 NEW)
project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
endif()
cmake_minimum_required(VERSION 2.8.12)
if (COMMAND set_up_hermetic_build) if (COMMAND set_up_hermetic_build)
set_up_hermetic_build() set_up_hermetic_build()
...@@ -109,11 +105,12 @@ endif() ...@@ -109,11 +105,12 @@ endif()
# to the targets for when we are part of a parent build (ie being pulled # to the targets for when we are part of a parent build (ie being pulled
# in via add_subdirectory() rather than being a standalone build). # in via add_subdirectory() rather than being a standalone build).
if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
string(REPLACE ";" "$<SEMICOLON>" dirs "${gmock_build_include_dirs}")
target_include_directories(gmock SYSTEM INTERFACE target_include_directories(gmock SYSTEM INTERFACE
"$<BUILD_INTERFACE:${gmock_build_include_dirs}>" "$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>") "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gmock_main SYSTEM INTERFACE target_include_directories(gmock_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${gmock_build_include_dirs}>" "$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>") "$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
endif() endif()
...@@ -154,7 +151,10 @@ if (gmock_build_tests) ...@@ -154,7 +151,10 @@ if (gmock_build_tests)
cxx_test(gmock_ex_test gmock_main) cxx_test(gmock_ex_test gmock_main)
cxx_test(gmock-function-mocker_test gmock_main) cxx_test(gmock-function-mocker_test gmock_main)
cxx_test(gmock-internal-utils_test gmock_main) cxx_test(gmock-internal-utils_test gmock_main)
cxx_test(gmock-matchers_test gmock_main) cxx_test(gmock-matchers-arithmetic_test gmock_main)
cxx_test(gmock-matchers-comparisons_test gmock_main)
cxx_test(gmock-matchers-containers_test gmock_main)
cxx_test(gmock-matchers-misc_test gmock_main)
cxx_test(gmock-more-actions_test gmock_main) cxx_test(gmock-more-actions_test gmock_main)
cxx_test(gmock-nice-strict_test gmock_main) cxx_test(gmock-nice-strict_test gmock_main)
cxx_test(gmock-port_test gmock_main) cxx_test(gmock-port_test gmock_main)
......
...@@ -35,10 +35,6 @@ Details and examples can be found here: ...@@ -35,10 +35,6 @@ Details and examples can be found here:
* [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html) * [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html)
* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.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 GoogleMock's license.
GoogleMock is a part of GoogleMock is a part of
[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a [GoogleTest C++ testing framework](http://github.com/google/googletest/) and a
subject to the same requirements. subject to the same requirements.
...@@ -27,21 +27,23 @@ ...@@ -27,21 +27,23 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements some commonly used cardinalities. More // This file implements some commonly used cardinalities. More
// cardinalities can be defined by the user implementing the // cardinalities can be defined by the user implementing the
// CardinalityInterface interface if necessary. // CardinalityInterface interface if necessary.
// GOOGLETEST_CM0002 DO NOT DELETE // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#include <limits.h> #include <limits.h>
#include <memory> #include <memory>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
...@@ -116,7 +118,7 @@ class GTEST_API_ Cardinality { ...@@ -116,7 +118,7 @@ class GTEST_API_ Cardinality {
// cardinality, i.e. exceed the maximum number of allowed calls. // cardinality, i.e. exceed the maximum number of allowed calls.
bool IsOverSaturatedByCallCount(int call_count) const { bool IsOverSaturatedByCallCount(int call_count) const {
return impl_->IsSaturatedByCallCount(call_count) && return impl_->IsSaturatedByCallCount(call_count) &&
!impl_->IsSatisfiedByCallCount(call_count); !impl_->IsSatisfiedByCallCount(call_count);
} }
// Describes self to an ostream // Describes self to an ostream
......
...@@ -31,10 +31,11 @@ ...@@ -31,10 +31,11 @@
// //
// This file implements MOCK_METHOD. // This file implements MOCK_METHOD.
// GOOGLETEST_CM0002 DO NOT DELETE // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
#include <type_traits> // IWYU pragma: keep #include <type_traits> // IWYU pragma: keep
#include <utility> // IWYU pragma: keep #include <utility> // IWYU pragma: keep
...@@ -64,6 +65,39 @@ struct ThisRefAdjuster { ...@@ -64,6 +65,39 @@ struct ThisRefAdjuster {
} }
}; };
constexpr bool PrefixOf(const char* a, const char* b) {
return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1));
}
template <int N, int M>
constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) {
return N <= M && internal::PrefixOf(prefix, str);
}
template <int N, int M>
constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) {
return N <= M && internal::PrefixOf(suffix, str + M - N);
}
template <int N, int M>
constexpr bool Equals(const char (&a)[N], const char (&b)[M]) {
return N == M && internal::PrefixOf(a, b);
}
template <int N>
constexpr bool ValidateSpec(const char (&spec)[N]) {
return internal::Equals("const", spec) ||
internal::Equals("override", spec) ||
internal::Equals("final", spec) ||
internal::Equals("noexcept", spec) ||
(internal::StartsWith("noexcept(", spec) &&
internal::EndsWith(")", spec)) ||
internal::Equals("ref(&)", spec) ||
internal::Equals("ref(&&)", spec) ||
(internal::StartsWith("Calltype(", spec) &&
internal::EndsWith(")", spec));
}
} // namespace internal } // namespace internal
// The style guide prohibits "using" statements in a namespace scope // The style guide prohibits "using" statements in a namespace scope
...@@ -74,8 +108,11 @@ struct ThisRefAdjuster { ...@@ -74,8 +108,11 @@ struct ThisRefAdjuster {
using internal::FunctionMocker; using internal::FunctionMocker;
} // namespace testing } // namespace testing
#define MOCK_METHOD(...) \ #define MOCK_METHOD(...) \
GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) GMOCK_INTERNAL_WARNING_PUSH() \
GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \
GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) \
GMOCK_INTERNAL_WARNING_POP()
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ #define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
...@@ -86,17 +123,18 @@ using internal::FunctionMocker; ...@@ -86,17 +123,18 @@ using internal::FunctionMocker;
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ #define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \
GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ #define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \
GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \
GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \
GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \
GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \
GMOCK_INTERNAL_GET_CALLTYPE(_Spec), GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \ GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec), \
GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \
(GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
...@@ -166,11 +204,11 @@ using internal::FunctionMocker; ...@@ -166,11 +204,11 @@ using internal::FunctionMocker;
GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
} \ } \
mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \ mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
GMOCK_MOCKER_(_N, _Constness, _MethodName) GMOCK_MOCKER_(_N, _Constness, _MethodName)
#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__
// Five Valid modifiers. // Valid modifiers.
#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ #define GMOCK_INTERNAL_HAS_CONST(_Tuple) \
GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple))
...@@ -189,6 +227,14 @@ using internal::FunctionMocker; ...@@ -189,6 +227,14 @@ using internal::FunctionMocker;
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \
_elem, ) _elem, )
#define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple)
#define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem) \
GMOCK_PP_IF( \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \
GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \ #define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple) GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)
...@@ -196,19 +242,25 @@ using internal::FunctionMocker; ...@@ -196,19 +242,25 @@ using internal::FunctionMocker;
GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \ GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
#define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \ #ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple) #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \
static_assert( \
#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)), \
static_assert( \ "Token \'" GMOCK_PP_STRINGIZE( \
(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ _elem) "\' cannot be recognized as a valid specification " \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ "modifier. Is a ',' missing?");
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ #else
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \ static_assert( \
GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \ (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \
GMOCK_PP_STRINGIZE( \ 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_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \
GMOCK_PP_STRINGIZE( \
_elem) " cannot be recognized as a valid specification modifier."); _elem) " cannot be recognized as a valid specification modifier.");
#endif // GMOCK_INTERNAL_STRICT_SPEC_ASSERT
// Modifiers implementation. // Modifiers implementation.
#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ #define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \
...@@ -238,26 +290,12 @@ using internal::FunctionMocker; ...@@ -238,26 +290,12 @@ using internal::FunctionMocker;
#define GMOCK_INTERNAL_UNPACK_ref(x) x #define GMOCK_INTERNAL_UNPACK_ref(x) x
#define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \ #define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \
GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem)
GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
(_elem)
// TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and
// GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows
// maybe they can be simplified somehow.
#define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \
GMOCK_INTERNAL_IS_CALLTYPE_I( \
GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
#define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg)
#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \ #define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype ,
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_IDENTITY _arg
#define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype #define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__
// Note: The use of `identity_t` here allows _Ret to represent return types that // Note: The use of `identity_t` here allows _Ret to represent return types that
// would normally need to be specified in a different way. For example, a method // would normally need to be specified in a different way. For example, a method
...@@ -476,4 +514,4 @@ using internal::FunctionMocker; ...@@ -476,4 +514,4 @@ using internal::FunctionMocker;
#define GMOCK_MOCKER_(arity, constness, Method) \ #define GMOCK_MOCKER_(arity, constness, Method) \
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements some matchers that depend on gmock-matchers.h. // This file implements some matchers that depend on gmock-matchers.h.
...@@ -35,11 +34,15 @@ ...@@ -35,11 +34,15 @@
// Note that tests are implemented in gmock-matchers_test.cc rather than // Note that tests are implemented in gmock-matchers_test.cc rather than
// gmock-more-matchers-test.cc. // gmock-more-matchers-test.cc.
// GOOGLETEST_CM0002 DO NOT DELETE // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#include <ostream>
#include <string>
#include "gmock/gmock-matchers.h" #include "gmock/gmock-matchers.h"
namespace testing { namespace testing {
...@@ -47,23 +50,51 @@ namespace testing { ...@@ -47,23 +50,51 @@ namespace testing {
// Silence C4100 (unreferenced formal // Silence C4100 (unreferenced formal
// parameter) for MSVC // parameter) for MSVC
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#if (_MSC_VER == 1900) #if (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value // and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14 // to bool 'true' or 'false') for MSVC 14
# pragma warning(disable:4800) #pragma warning(disable : 4800)
#endif #endif
#endif #endif
// Defines a matcher that matches an empty container. The container must namespace internal {
// support both size() and empty(), which all STL-like containers provide.
MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") { // Implements the polymorphic IsEmpty matcher, which
if (arg.empty()) { // can be used as a Matcher<T> as long as T is either a container that defines
return true; // empty() and size() (e.g. std::vector or std::string), or a C-style string.
class IsEmptyMatcher {
public:
// Matches anything that defines empty() and size().
template <typename MatcheeContainerType>
bool MatchAndExplain(const MatcheeContainerType& c,
MatchResultListener* listener) const {
if (c.empty()) {
return true;
}
*listener << "whose size is " << c.size();
return false;
}
// Matches C-style strings.
bool MatchAndExplain(const char* s, MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener);
} }
*result_listener << "whose size is " << arg.size();
return false; // Describes what this matcher matches.
void DescribeTo(std::ostream* os) const { *os << "is empty"; }
void DescribeNegationTo(std::ostream* os) const { *os << "isn't empty"; }
};
} // namespace internal
// Creates a polymorphic matcher that matches an empty container or C-style
// string. The container must support both size() and empty(), which all
// STL-like containers provide.
inline PolymorphicMatcher<internal::IsEmptyMatcher> IsEmpty() {
return MakePolymorphicMatcher(internal::IsEmptyMatcher());
} }
// Define a matcher that matches a value that evaluates in boolean // Define a matcher that matches a value that evaluates in boolean
...@@ -83,10 +114,9 @@ MATCHER(IsFalse, negation ? "is true" : "is false") { ...@@ -83,10 +114,9 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
} }
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
} // namespace testing } // namespace testing
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Implements class templates NiceMock, NaggyMock, and StrictMock. // Implements class templates NiceMock, NaggyMock, and StrictMock.
// //
// Given a mock class MockFoo that is created using Google Mock, // Given a mock class MockFoo that is created using Google Mock,
...@@ -58,11 +57,13 @@ ...@@ -58,11 +57,13 @@
// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
// supported. // supported.
// GOOGLETEST_CM0002 DO NOT DELETE // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
#include <cstdint>
#include <type_traits> #include <type_traits>
#include "gmock/gmock-spec-builders.h" #include "gmock/gmock-spec-builders.h"
...@@ -109,25 +110,37 @@ constexpr bool HasStrictnessModifier() { ...@@ -109,25 +110,37 @@ constexpr bool HasStrictnessModifier() {
template <typename Base> template <typename Base>
class NiceMockImpl { class NiceMockImpl {
public: public:
NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); } NiceMockImpl() {
::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this));
}
~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); } ~NiceMockImpl() {
::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
}
}; };
template <typename Base> template <typename Base>
class NaggyMockImpl { class NaggyMockImpl {
public: public:
NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); } NaggyMockImpl() {
::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this));
}
~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); } ~NaggyMockImpl() {
::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
}
}; };
template <typename Base> template <typename Base>
class StrictMockImpl { class StrictMockImpl {
public: public:
StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); } StrictMockImpl() {
::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this));
}
~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); } ~StrictMockImpl() {
::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
}
}; };
} // namespace internal } // namespace internal
...@@ -169,7 +182,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock ...@@ -169,7 +182,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
} }
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock); NiceMock(const NiceMock&) = delete;
NiceMock& operator=(const NiceMock&) = delete;
}; };
template <class MockClass> template <class MockClass>
...@@ -210,7 +224,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock ...@@ -210,7 +224,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
} }
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock); NaggyMock(const NaggyMock&) = delete;
NaggyMock& operator=(const NaggyMock&) = delete;
}; };
template <class MockClass> template <class MockClass>
...@@ -251,7 +266,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock ...@@ -251,7 +266,8 @@ class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
} }
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock); StrictMock(const StrictMock&) = delete;
StrictMock& operator=(const StrictMock&) = delete;
}; };
#undef GTEST_INTERNAL_EMPTY_BASE_CLASS #undef GTEST_INTERNAL_EMPTY_BASE_CLASS
......
...@@ -27,13 +27,10 @@ ...@@ -27,13 +27,10 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This is the main header file a user should include. // This is the main header file a user should include.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_
...@@ -64,14 +61,15 @@ ...@@ -64,14 +61,15 @@
#include "gmock/gmock-more-matchers.h" #include "gmock/gmock-more-matchers.h"
#include "gmock/gmock-nice-strict.h" #include "gmock/gmock-nice-strict.h"
#include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h"
namespace testing {
// Declares Google Mock flags that we want a user to use programmatically. // Declares Google Mock flags that we want a user to use programmatically.
GMOCK_DECLARE_bool_(catch_leaked_mocks); GMOCK_DECLARE_bool_(catch_leaked_mocks);
GMOCK_DECLARE_string_(verbose); GMOCK_DECLARE_string_(verbose);
GMOCK_DECLARE_int32_(default_mock_behavior); GMOCK_DECLARE_int32_(default_mock_behavior);
namespace testing {
// Initializes Google Mock. This must be called before running the // Initializes Google Mock. This must be called before running the
// tests. In particular, it parses the command line for the flags // tests. In particular, it parses the command line for the flags
// that Google Mock recognizes. Whenever a Google Mock flag is seen, // that Google Mock recognizes. Whenever a Google Mock flag is seen,
......
...@@ -14,3 +14,5 @@ The following macros can be defined: ...@@ -14,3 +14,5 @@ The following macros can be defined:
* `GMOCK_DEFINE_bool_(name, default_val, doc)` * `GMOCK_DEFINE_bool_(name, default_val, doc)`
* `GMOCK_DEFINE_int32_(name, default_val, doc)` * `GMOCK_DEFINE_int32_(name, default_val, doc)`
* `GMOCK_DEFINE_string_(name, default_val, doc)` * `GMOCK_DEFINE_string_(name, default_val, doc)`
* `GMOCK_FLAG_GET(flag_name)`
* `GMOCK_FLAG_SET(flag_name, value)`
// GOOGLETEST_CM0002 DO NOT DELETE // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_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_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
......
...@@ -26,10 +26,11 @@ ...@@ -26,10 +26,11 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Injection point for custom user configurations. See README for details // Injection point for custom user configurations. See README for details
//
// GOOGLETEST_CM0002 DO NOT DELETE // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_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_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
......
...@@ -26,12 +26,13 @@ ...@@ -26,12 +26,13 @@
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Injection point for custom user configurations. See README for details // Injection point for custom user configurations. See README for details
// //
// ** Custom implementation starts here ** // ** Custom implementation starts here **
// GOOGLETEST_CM0002 DO NOT DELETE // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_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_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Low-level types and utilities for porting Google Mock to various // Low-level types and utilities for porting Google Mock to various
// platforms. All macros ending with _ and symbols defined in an // platforms. All macros ending with _ and symbols defined in an
// internal namespace are subject to change without notice. Code // internal namespace are subject to change without notice. Code
...@@ -35,7 +34,8 @@ ...@@ -35,7 +34,8 @@
// end with _ are part of Google Mock's public API and can be used by // end with _ are part of Google Mock's public API and can be used by
// code outside Google Mock. // code outside Google Mock.
// GOOGLETEST_CM0002 DO NOT DELETE // IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
...@@ -53,35 +53,87 @@ ...@@ -53,35 +53,87 @@
// here, as Google Mock depends on Google Test. Only add a utility // here, as Google Mock depends on Google Test. Only add a utility
// here if it's truly specific to Google Mock. // here if it's truly specific to Google Mock.
#include "gtest/internal/gtest-port.h"
#include "gmock/internal/custom/gmock-port.h" #include "gmock/internal/custom/gmock-port.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_HAS_ABSL
#include "absl/flags/declare.h"
#include "absl/flags/flag.h"
#endif
// For MS Visual C++, check the compiler version. At least VS 2015 is // For MS Visual C++, check the compiler version. At least VS 2015 is
// required to compile Google Mock. // required to compile Google Mock.
#if defined(_MSC_VER) && _MSC_VER < 1900 #if defined(_MSC_VER) && _MSC_VER < 1900
# error "At least Visual C++ 2015 (14.0) is required to compile Google Mock." #error "At least Visual C++ 2015 (14.0) is required to compile Google Mock."
#endif #endif
// Macro for referencing flags. This is public as we want the user to // Macro for referencing flags. This is public as we want the user to
// use this syntax to reference Google Mock flags. // use this syntax to reference Google Mock flags.
#define GMOCK_FLAG_NAME_(name) gmock_##name
#define GMOCK_FLAG(name) FLAGS_gmock_##name #define GMOCK_FLAG(name) FLAGS_gmock_##name
#if !defined(GMOCK_DECLARE_bool_) // Pick a command line flags implementation.
#if GTEST_HAS_ABSL
// Macros for defining flags.
#define GMOCK_DEFINE_bool_(name, default_val, doc) \
ABSL_FLAG(bool, GMOCK_FLAG_NAME_(name), default_val, doc)
#define GMOCK_DEFINE_int32_(name, default_val, doc) \
ABSL_FLAG(int32_t, GMOCK_FLAG_NAME_(name), default_val, doc)
#define GMOCK_DEFINE_string_(name, default_val, doc) \
ABSL_FLAG(std::string, GMOCK_FLAG_NAME_(name), default_val, doc)
// Macros for declaring flags. // Macros for declaring flags.
# define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) #define GMOCK_DECLARE_bool_(name) \
# define GMOCK_DECLARE_int32_(name) extern GTEST_API_ int32_t GMOCK_FLAG(name) ABSL_DECLARE_FLAG(bool, GMOCK_FLAG_NAME_(name))
# define GMOCK_DECLARE_string_(name) \ #define GMOCK_DECLARE_int32_(name) \
extern GTEST_API_ ::std::string GMOCK_FLAG(name) ABSL_DECLARE_FLAG(int32_t, GMOCK_FLAG_NAME_(name))
#define GMOCK_DECLARE_string_(name) \
ABSL_DECLARE_FLAG(std::string, GMOCK_FLAG_NAME_(name))
#define GMOCK_FLAG_GET(name) ::absl::GetFlag(GMOCK_FLAG(name))
#define GMOCK_FLAG_SET(name, value) \
(void)(::absl::SetFlag(&GMOCK_FLAG(name), value))
#else // GTEST_HAS_ABSL
// Macros for defining flags. // Macros for defining flags.
# define GMOCK_DEFINE_bool_(name, default_val, doc) \ #define GMOCK_DEFINE_bool_(name, default_val, doc) \
GTEST_API_ bool GMOCK_FLAG(name) = (default_val) namespace testing { \
# define GMOCK_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ bool GMOCK_FLAG(name) = (default_val); \
GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val) } \
# define GMOCK_DEFINE_string_(name, default_val, doc) \ static_assert(true, "no-op to require trailing semicolon")
GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) #define GMOCK_DEFINE_int32_(name, default_val, doc) \
namespace testing { \
#endif // !defined(GMOCK_DECLARE_bool_) GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val); \
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DEFINE_string_(name, default_val, doc) \
namespace testing { \
GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val); \
} \
static_assert(true, "no-op to require trailing semicolon")
// Macros for declaring flags.
#define GMOCK_DECLARE_bool_(name) \
namespace testing { \
GTEST_API_ extern bool GMOCK_FLAG(name); \
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DECLARE_int32_(name) \
namespace testing { \
GTEST_API_ extern int32_t GMOCK_FLAG(name); \
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_DECLARE_string_(name) \
namespace testing { \
GTEST_API_ extern ::std::string GMOCK_FLAG(name); \
} \
static_assert(true, "no-op to require trailing semicolon")
#define GMOCK_FLAG_GET(name) ::testing::GMOCK_FLAG(name)
#define GMOCK_FLAG_SET(name, value) (void)(::testing::GMOCK_FLAG(name) = value)
#endif // GTEST_HAS_ABSL
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements cardinalities. // This file implements cardinalities.
...@@ -35,9 +34,11 @@ ...@@ -35,9 +34,11 @@
#include "gmock/gmock-cardinalities.h" #include "gmock/gmock-cardinalities.h"
#include <limits.h> #include <limits.h>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <sstream> #include <sstream>
#include <string> #include <string>
#include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-internal-utils.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
...@@ -49,8 +50,7 @@ namespace { ...@@ -49,8 +50,7 @@ namespace {
class BetweenCardinalityImpl : public CardinalityInterface { class BetweenCardinalityImpl : public CardinalityInterface {
public: public:
BetweenCardinalityImpl(int min, int max) BetweenCardinalityImpl(int min, int max)
: min_(min >= 0 ? min : 0), : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) {
max_(max >= min_ ? max : min_) {
std::stringstream ss; std::stringstream ss;
if (min < 0) { if (min < 0) {
ss << "The invocation lower bound must be >= 0, " ss << "The invocation lower bound must be >= 0, "
...@@ -62,8 +62,7 @@ class BetweenCardinalityImpl : public CardinalityInterface { ...@@ -62,8 +62,7 @@ class BetweenCardinalityImpl : public CardinalityInterface {
internal::Expect(false, __FILE__, __LINE__, ss.str()); internal::Expect(false, __FILE__, __LINE__, ss.str());
} else if (min > max) { } else if (min > max) {
ss << "The invocation upper bound (" << max ss << "The invocation upper bound (" << max
<< ") must be >= the invocation lower bound (" << min << ") must be >= the invocation lower bound (" << min << ").";
<< ").";
internal::Expect(false, __FILE__, __LINE__, ss.str()); internal::Expect(false, __FILE__, __LINE__, ss.str());
} }
} }
...@@ -87,7 +86,8 @@ class BetweenCardinalityImpl : public CardinalityInterface { ...@@ -87,7 +86,8 @@ class BetweenCardinalityImpl : public CardinalityInterface {
const int min_; const int min_;
const int max_; const int max_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl); BetweenCardinalityImpl(const BetweenCardinalityImpl&) = delete;
BetweenCardinalityImpl& operator=(const BetweenCardinalityImpl&) = delete;
}; };
// Formats "n times" in a human-friendly way. // Formats "n times" in a human-friendly way.
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file defines some utilities useful for implementing Google // This file defines some utilities useful for implementing Google
...@@ -37,8 +36,15 @@ ...@@ -37,8 +36,15 @@
#include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-internal-utils.h"
#include <ctype.h> #include <ctype.h>
#include <array>
#include <cctype>
#include <cstdint>
#include <cstring>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <string> #include <string>
#include <vector>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
...@@ -48,21 +54,22 @@ namespace internal { ...@@ -48,21 +54,22 @@ namespace internal {
// Joins a vector of strings as if they are fields of a tuple; returns // Joins a vector of strings as if they are fields of a tuple; returns
// the joined string. // the joined string.
GTEST_API_ std::string JoinAsTuple(const Strings& fields) { GTEST_API_ std::string JoinAsKeyValueTuple(
switch (fields.size()) { const std::vector<const char*>& names, const Strings& values) {
case 0: GTEST_CHECK_(names.size() == values.size());
return ""; if (values.empty()) {
case 1: return "";
return fields[0];
default:
std::string result = "(" + fields[0];
for (size_t i = 1; i < fields.size(); i++) {
result += ", ";
result += fields[i];
}
result += ")";
return result;
} }
const auto build_one = [&](const size_t i) {
return std::string(names[i]) + ": " + values[i];
};
std::string result = "(" + build_one(0);
for (size_t i = 1; i < values.size(); i++) {
result += ", ";
result += build_one(i);
}
result += ")";
return result;
} }
// Converts an identifier name to a space-separated list of lower-case // Converts an identifier name to a space-separated list of lower-case
...@@ -76,12 +83,11 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) { ...@@ -76,12 +83,11 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
// We don't care about the current locale as the input is // We don't care about the current locale as the input is
// guaranteed to be a valid C++ identifier name. // guaranteed to be a valid C++ identifier name.
const bool starts_new_word = IsUpper(*p) || const bool starts_new_word = IsUpper(*p) ||
(!IsAlpha(prev_char) && IsLower(*p)) || (!IsAlpha(prev_char) && IsLower(*p)) ||
(!IsDigit(prev_char) && IsDigit(*p)); (!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) { if (IsAlNum(*p)) {
if (starts_new_word && result != "") if (starts_new_word && result != "") result += ' ';
result += ' ';
result += ToLower(*p); result += ToLower(*p);
} }
} }
...@@ -95,12 +101,9 @@ class GoogleTestFailureReporter : public FailureReporterInterface { ...@@ -95,12 +101,9 @@ class GoogleTestFailureReporter : public FailureReporterInterface {
public: public:
void ReportFailure(FailureType type, const char* file, int line, void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) override { const std::string& message) override {
AssertHelper(type == kFatal ? AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
TestPartResult::kFatalFailure : : TestPartResult::kNonFatalFailure,
TestPartResult::kNonFatalFailure, file, line, message.c_str()) = Message();
file,
line,
message.c_str()) = Message();
if (type == kFatal) { if (type == kFatal) {
posix::Abort(); posix::Abort();
} }
...@@ -126,10 +129,10 @@ static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex); ...@@ -126,10 +129,10 @@ static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
// Returns true if and only if a log with the given severity is visible // Returns true if and only if a log with the given severity is visible
// according to the --gmock_verbose flag. // according to the --gmock_verbose flag.
GTEST_API_ bool LogIsVisible(LogSeverity severity) { GTEST_API_ bool LogIsVisible(LogSeverity severity) {
if (GMOCK_FLAG(verbose) == kInfoVerbosity) { if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) {
// Always show the log if --gmock_verbose=info. // Always show the log if --gmock_verbose=info.
return true; return true;
} else if (GMOCK_FLAG(verbose) == kErrorVerbosity) { } else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) {
// Always hide it if --gmock_verbose=error. // Always hide it if --gmock_verbose=error.
return false; return false;
} else { } else {
...@@ -148,8 +151,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) { ...@@ -148,8 +151,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) {
// conservative. // conservative.
GTEST_API_ void Log(LogSeverity severity, const std::string& message, GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int stack_frames_to_skip) { int stack_frames_to_skip) {
if (!LogIsVisible(severity)) if (!LogIsVisible(severity)) return;
return;
// Ensures that logs from different threads don't interleave. // Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex); MutexLock l(&g_log_mutex);
...@@ -178,8 +180,8 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message, ...@@ -178,8 +180,8 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
std::cout << "\n"; std::cout << "\n";
} }
std::cout << "Stack trace:\n" std::cout << "Stack trace:\n"
<< ::testing::internal::GetCurrentOsStackTraceExceptTop( << ::testing::internal::GetCurrentOsStackTraceExceptTop(
::testing::UnitTest::GetInstance(), actual_to_skip); actual_to_skip);
} }
std::cout << ::std::flush; std::cout << ::std::flush;
} }
...@@ -196,5 +198,54 @@ GTEST_API_ void IllegalDoDefault(const char* file, int line) { ...@@ -196,5 +198,54 @@ GTEST_API_ void IllegalDoDefault(const char* file, int line) {
"the variable in various places."); "the variable in various places.");
} }
constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
return *base64 == 0 ? static_cast<char>(65)
: *base64 == c
? carry
: UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1));
}
template <size_t... I>
constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,
const char* const base64) {
return {{UnBase64Impl(static_cast<char>(I), base64, 0)...}};
}
constexpr std::array<char, 256> UnBase64(const char* const base64) {
return UnBase64Impl(MakeIndexSequence<256>{}, base64);
}
static constexpr char kBase64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64);
bool Base64Unescape(const std::string& encoded, std::string* decoded) {
decoded->clear();
size_t encoded_len = encoded.size();
decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4));
int bit_pos = 0;
char dst = 0;
for (int src : encoded) {
if (std::isspace(src) || src == '=') {
continue;
}
char src_bin = kUnBase64[static_cast<size_t>(src)];
if (src_bin >= 64) {
decoded->clear();
return false;
}
if (bit_pos == 0) {
dst |= static_cast<char>(src_bin << 2);
bit_pos = 6;
} else {
dst |= static_cast<char>(src_bin >> (bit_pos - 2));
decoded->push_back(dst);
dst = static_cast<char>(src_bin << (10 - bit_pos));
bit_pos = (bit_pos + 6) % 8;
}
}
return true;
}
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements Matcher<const string&>, Matcher<string>, and // This file implements Matcher<const string&>, Matcher<string>, and
...@@ -36,9 +35,11 @@ ...@@ -36,9 +35,11 @@
#include "gmock/gmock-matchers.h" #include "gmock/gmock-matchers.h"
#include <string.h> #include <string.h>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <vector>
namespace testing { namespace testing {
namespace internal { namespace internal {
...@@ -48,11 +49,13 @@ namespace internal { ...@@ -48,11 +49,13 @@ namespace internal {
// 'negation' is false; otherwise returns the description of the // 'negation' is false; otherwise returns the description of the
// negation of the matcher. 'param_values' contains a list of strings // negation of the matcher. 'param_values' contains a list of strings
// that are the print-out of the matcher's parameters. // that are the print-out of the matcher's parameters.
GTEST_API_ std::string FormatMatcherDescription(bool negation, GTEST_API_ std::string FormatMatcherDescription(
const char* matcher_name, bool negation, const char* matcher_name,
const Strings& param_values) { const std::vector<const char*>& param_names, const Strings& param_values) {
std::string result = ConvertIdentifierNameToWords(matcher_name); std::string result = ConvertIdentifierNameToWords(matcher_name);
if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values); if (param_values.size() >= 1) {
result += " " + JoinAsKeyValueTuple(param_names, param_values);
}
return negation ? "not (" + result + ")" : result; return negation ? "not (" + result + ")" : result;
} }
...@@ -367,6 +370,23 @@ void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl( ...@@ -367,6 +370,23 @@ void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix( bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
const ::std::vector<std::string>& element_printouts, const ::std::vector<std::string>& element_printouts,
const MatchMatrix& matrix, MatchResultListener* listener) const { const MatchMatrix& matrix, MatchResultListener* listener) const {
if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {
return true;
}
if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
if (matrix.LhsSize() != matrix.RhsSize()) {
// The element count doesn't match. If the container is empty,
// there's no need to explain anything as Google Mock already
// prints the empty container. Otherwise we just need to show
// how many elements there actually are.
if (matrix.LhsSize() != 0 && listener->IsInterested()) {
*listener << "which has " << Elements(matrix.LhsSize());
}
return false;
}
}
bool result = true; bool result = true;
::std::vector<char> element_matched(matrix.LhsSize(), 0); ::std::vector<char> element_matched(matrix.LhsSize(), 0);
::std::vector<char> matcher_matched(matrix.RhsSize(), 0); ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
......
...@@ -27,17 +27,15 @@ ...@@ -27,17 +27,15 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
namespace testing { #include "gmock/internal/gmock-port.h"
GMOCK_DEFINE_bool_(catch_leaked_mocks, true, GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
"true if and only if Google Mock should report leaked " "true if and only if Google Mock should report leaked "
"mock objects as failures."); "mock objects as failures.");
GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity, GMOCK_DEFINE_string_(verbose, testing::internal::kWarningVerbosity,
"Controls how verbose Google Mock's output is." "Controls how verbose Google Mock's output is."
" Valid values:\n" " Valid values:\n"
" info - prints all messages.\n" " info - prints all messages.\n"
...@@ -51,6 +49,7 @@ GMOCK_DEFINE_int32_(default_mock_behavior, 1, ...@@ -51,6 +49,7 @@ GMOCK_DEFINE_int32_(default_mock_behavior, 1,
" 1 - by default, mocks act as NaggyMocks.\n" " 1 - by default, mocks act as NaggyMocks.\n"
" 2 - by default, mocks act as StrictMocks."); " 2 - by default, mocks act as StrictMocks.");
namespace testing {
namespace internal { namespace internal {
// Parses a string as a command line flag. The string should have the // Parses a string as a command line flag. The string should have the
...@@ -59,18 +58,18 @@ namespace internal { ...@@ -59,18 +58,18 @@ namespace internal {
// //
// Returns the value of the flag, or NULL if the parsing failed. // Returns the value of the flag, or NULL if the parsing failed.
static const char* ParseGoogleMockFlagValue(const char* str, static const char* ParseGoogleMockFlagValue(const char* str,
const char* flag, const char* flag_name,
bool def_optional) { bool def_optional) {
// str and flag must not be NULL. // str and flag must not be NULL.
if (str == nullptr || flag == nullptr) return nullptr; if (str == nullptr || flag_name == nullptr) return nullptr;
// The flag must start with "--gmock_". // The flag must start with "--gmock_".
const std::string flag_str = std::string("--gmock_") + flag; const std::string flag_name_str = std::string("--gmock_") + flag_name;
const size_t flag_len = flag_str.length(); const size_t flag_name_len = flag_name_str.length();
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; if (strncmp(str, flag_name_str.c_str(), flag_name_len) != 0) return nullptr;
// Skips the flag name. // Skips the flag name.
const char* flag_end = str + flag_len; const char* flag_end = str + flag_name_len;
// When def_optional is true, it's OK to not have a "=value" part. // When def_optional is true, it's OK to not have a "=value" part.
if (def_optional && (flag_end[0] == '\0')) { if (def_optional && (flag_end[0] == '\0')) {
...@@ -91,10 +90,10 @@ static const char* ParseGoogleMockFlagValue(const char* str, ...@@ -91,10 +90,10 @@ static const char* ParseGoogleMockFlagValue(const char* str,
// //
// On success, stores the value of the flag in *value, and returns // On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value. // true. On failure, returns false without changing *value.
static bool ParseGoogleMockBoolFlag(const char* str, const char* flag, static bool ParseGoogleMockFlag(const char* str, const char* flag_name,
bool* value) { bool* value) {
// Gets the value of the flag as a string. // Gets the value of the flag as a string.
const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true);
// Aborts if the parsing failed. // Aborts if the parsing failed.
if (value_str == nullptr) return false; if (value_str == nullptr) return false;
...@@ -110,10 +109,10 @@ static bool ParseGoogleMockBoolFlag(const char* str, const char* flag, ...@@ -110,10 +109,10 @@ static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
// On success, stores the value of the flag in *value, and returns // On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value. // true. On failure, returns false without changing *value.
template <typename String> template <typename String>
static bool ParseGoogleMockStringFlag(const char* str, const char* flag, static bool ParseGoogleMockFlag(const char* str, const char* flag_name,
String* value) { String* value) {
// Gets the value of the flag as a string. // Gets the value of the flag as a string.
const char* const value_str = ParseGoogleMockFlagValue(str, flag, false); const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, false);
// Aborts if the parsing failed. // Aborts if the parsing failed.
if (value_str == nullptr) return false; if (value_str == nullptr) return false;
...@@ -123,17 +122,17 @@ static bool ParseGoogleMockStringFlag(const char* str, const char* flag, ...@@ -123,17 +122,17 @@ static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
return true; return true;
} }
static bool ParseGoogleMockIntFlag(const char* str, const char* flag, static bool ParseGoogleMockFlag(const char* str, const char* flag_name,
int32_t* value) { int32_t* value) {
// Gets the value of the flag as a string. // Gets the value of the flag as a string.
const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true);
// Aborts if the parsing failed. // Aborts if the parsing failed.
if (value_str == nullptr) return false; if (value_str == nullptr) return false;
// Sets *value to the value of the flag. // Sets *value to the value of the flag.
return ParseInt32(Message() << "The value of flag --" << flag, return ParseInt32(Message() << "The value of flag --" << flag_name, value_str,
value_str, value); value);
} }
// The internal implementation of InitGoogleMock(). // The internal implementation of InitGoogleMock().
...@@ -152,11 +151,22 @@ void InitGoogleMockImpl(int* argc, CharType** argv) { ...@@ -152,11 +151,22 @@ void InitGoogleMockImpl(int* argc, CharType** argv) {
const char* const arg = arg_string.c_str(); const char* const arg = arg_string.c_str();
// Do we see a Google Mock flag? // Do we see a Google Mock flag?
if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks", bool found_gmock_flag = false;
&GMOCK_FLAG(catch_leaked_mocks)) ||
ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose)) || #define GMOCK_INTERNAL_PARSE_FLAG(flag_name) \
ParseGoogleMockIntFlag(arg, "default_mock_behavior", if (!found_gmock_flag) { \
&GMOCK_FLAG(default_mock_behavior))) { auto value = GMOCK_FLAG_GET(flag_name); \
if (ParseGoogleMockFlag(arg, #flag_name, &value)) { \
GMOCK_FLAG_SET(flag_name, value); \
found_gmock_flag = true; \
} \
}
GMOCK_INTERNAL_PARSE_FLAG(catch_leaked_mocks)
GMOCK_INTERNAL_PARSE_FLAG(verbose)
GMOCK_INTERNAL_PARSE_FLAG(default_mock_behavior)
if (found_gmock_flag) {
// Yes. Shift the remainder of the argv list left by one. Note // Yes. Shift the remainder of the argv list left by one. Note
// that argv has (*argc + 1) elements, the last one always being // that argv has (*argc + 1) elements, the last one always being
// NULL. The following loop moves the trailing NULL element as // NULL. The following loop moves the trailing NULL element as
......
...@@ -27,8 +27,8 @@ ...@@ -27,8 +27,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream> #include <iostream>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
...@@ -56,7 +56,7 @@ void loop() { RUN_ALL_TESTS(); } ...@@ -56,7 +56,7 @@ void loop() { RUN_ALL_TESTS(); }
// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library // https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library
// // NOLINT // // NOLINT
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
# include <tchar.h> // NOLINT #include <tchar.h> // NOLINT
GTEST_API_ int _tmain(int argc, TCHAR** argv) { GTEST_API_ int _tmain(int argc, TCHAR** argv) {
#else #else
......
...@@ -30,7 +30,6 @@ ...@@ -30,7 +30,6 @@
# #
# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock # Bazel Build for Google C++ Testing Framework(Google Test)-googlemock
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
load("@rules_python//python:defs.bzl", "py_library", "py_test") load("@rules_python//python:defs.bzl", "py_library", "py_test")
licenses(["notice"]) licenses(["notice"])
...@@ -39,8 +38,9 @@ licenses(["notice"]) ...@@ -39,8 +38,9 @@ licenses(["notice"])
cc_test( cc_test(
name = "gmock_all_test", name = "gmock_all_test",
size = "small", size = "small",
srcs = glob(include = ["gmock-*.cc"]), srcs = glob(include = ["gmock-*.cc"]) + ["gmock-matchers_test.h"],
linkopts = select({ linkopts = select({
"//:qnx": [],
"//:windows": [], "//:windows": [],
"//conditions:default": ["-pthread"], "//conditions:default": ["-pthread"],
}), }),
......
...@@ -27,14 +27,13 @@ ...@@ -27,14 +27,13 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the built-in cardinalities. // This file tests the built-in cardinalities.
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
namespace { namespace {
...@@ -55,13 +54,12 @@ class MockFoo { ...@@ -55,13 +54,12 @@ class MockFoo {
MOCK_METHOD0(Bar, int()); // NOLINT MOCK_METHOD0(Bar, int()); // NOLINT
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); MockFoo(const MockFoo&) = delete;
MockFoo& operator=(const MockFoo&) = delete;
}; };
// Tests that Cardinality objects can be default constructed. // Tests that Cardinality objects can be default constructed.
TEST(CardinalityTest, IsDefaultConstructable) { TEST(CardinalityTest, IsDefaultConstructable) { Cardinality c; }
Cardinality c;
}
// Tests that Cardinality objects are copyable. // Tests that Cardinality objects are copyable.
TEST(CardinalityTest, IsCopyable) { TEST(CardinalityTest, IsCopyable) {
...@@ -119,8 +117,7 @@ TEST(AnyNumber, Works) { ...@@ -119,8 +117,7 @@ TEST(AnyNumber, Works) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", ss.str());
ss.str());
} }
TEST(AnyNumberTest, HasCorrectBounds) { TEST(AnyNumberTest, HasCorrectBounds) {
...@@ -132,9 +129,11 @@ TEST(AnyNumberTest, HasCorrectBounds) { ...@@ -132,9 +129,11 @@ TEST(AnyNumberTest, HasCorrectBounds) {
// Tests AtLeast(n). // Tests AtLeast(n).
TEST(AtLeastTest, OnNegativeNumber) { TEST(AtLeastTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
AtLeast(-1); { // NOLINT
}, "The invocation lower bound must be >= 0"); AtLeast(-1);
},
"The invocation lower bound must be >= 0");
} }
TEST(AtLeastTest, OnZero) { TEST(AtLeastTest, OnZero) {
...@@ -147,8 +146,7 @@ TEST(AtLeastTest, OnZero) { ...@@ -147,8 +146,7 @@ TEST(AtLeastTest, OnZero) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", ss.str());
ss.str());
} }
TEST(AtLeastTest, OnPositiveNumber) { TEST(AtLeastTest, OnPositiveNumber) {
...@@ -164,18 +162,15 @@ TEST(AtLeastTest, OnPositiveNumber) { ...@@ -164,18 +162,15 @@ TEST(AtLeastTest, OnPositiveNumber) {
stringstream ss1; stringstream ss1;
AtLeast(1).DescribeTo(&ss1); AtLeast(1).DescribeTo(&ss1);
EXPECT_PRED_FORMAT2(IsSubstring, "at least once", EXPECT_PRED_FORMAT2(IsSubstring, "at least once", ss1.str());
ss1.str());
stringstream ss2; stringstream ss2;
c.DescribeTo(&ss2); c.DescribeTo(&ss2);
EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", ss2.str());
ss2.str());
stringstream ss3; stringstream ss3;
AtLeast(3).DescribeTo(&ss3); AtLeast(3).DescribeTo(&ss3);
EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", ss3.str());
ss3.str());
} }
TEST(AtLeastTest, HasCorrectBounds) { TEST(AtLeastTest, HasCorrectBounds) {
...@@ -187,9 +182,11 @@ TEST(AtLeastTest, HasCorrectBounds) { ...@@ -187,9 +182,11 @@ TEST(AtLeastTest, HasCorrectBounds) {
// Tests AtMost(n). // Tests AtMost(n).
TEST(AtMostTest, OnNegativeNumber) { TEST(AtMostTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
AtMost(-1); { // NOLINT
}, "The invocation upper bound must be >= 0"); AtMost(-1);
},
"The invocation upper bound must be >= 0");
} }
TEST(AtMostTest, OnZero) { TEST(AtMostTest, OnZero) {
...@@ -202,8 +199,7 @@ TEST(AtMostTest, OnZero) { ...@@ -202,8 +199,7 @@ TEST(AtMostTest, OnZero) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "never called", EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str());
ss.str());
} }
TEST(AtMostTest, OnPositiveNumber) { TEST(AtMostTest, OnPositiveNumber) {
...@@ -219,18 +215,15 @@ TEST(AtMostTest, OnPositiveNumber) { ...@@ -219,18 +215,15 @@ TEST(AtMostTest, OnPositiveNumber) {
stringstream ss1; stringstream ss1;
AtMost(1).DescribeTo(&ss1); AtMost(1).DescribeTo(&ss1);
EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", ss1.str());
ss1.str());
stringstream ss2; stringstream ss2;
c.DescribeTo(&ss2); c.DescribeTo(&ss2);
EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss2.str());
ss2.str());
stringstream ss3; stringstream ss3;
AtMost(3).DescribeTo(&ss3); AtMost(3).DescribeTo(&ss3);
EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", ss3.str());
ss3.str());
} }
TEST(AtMostTest, HasCorrectBounds) { TEST(AtMostTest, HasCorrectBounds) {
...@@ -242,22 +235,28 @@ TEST(AtMostTest, HasCorrectBounds) { ...@@ -242,22 +235,28 @@ TEST(AtMostTest, HasCorrectBounds) {
// Tests Between(m, n). // Tests Between(m, n).
TEST(BetweenTest, OnNegativeStart) { TEST(BetweenTest, OnNegativeStart) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Between(-1, 2); { // NOLINT
}, "The invocation lower bound must be >= 0, but is actually -1"); Between(-1, 2);
},
"The invocation lower bound must be >= 0, but is actually -1");
} }
TEST(BetweenTest, OnNegativeEnd) { TEST(BetweenTest, OnNegativeEnd) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Between(1, -2); { // NOLINT
}, "The invocation upper bound must be >= 0, but is actually -2"); Between(1, -2);
},
"The invocation upper bound must be >= 0, but is actually -2");
} }
TEST(BetweenTest, OnStartBiggerThanEnd) { TEST(BetweenTest, OnStartBiggerThanEnd) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Between(2, 1); { // NOLINT
}, "The invocation upper bound (1) must be >= " Between(2, 1);
"the invocation lower bound (2)"); },
"The invocation upper bound (1) must be >= "
"the invocation lower bound (2)");
} }
TEST(BetweenTest, OnZeroStartAndZeroEnd) { TEST(BetweenTest, OnZeroStartAndZeroEnd) {
...@@ -271,8 +270,7 @@ TEST(BetweenTest, OnZeroStartAndZeroEnd) { ...@@ -271,8 +270,7 @@ TEST(BetweenTest, OnZeroStartAndZeroEnd) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "never called", EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str());
ss.str());
} }
TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { TEST(BetweenTest, OnZeroStartAndNonZeroEnd) {
...@@ -289,8 +287,7 @@ TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { ...@@ -289,8 +287,7 @@ TEST(BetweenTest, OnZeroStartAndNonZeroEnd) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss.str());
ss.str());
} }
TEST(BetweenTest, OnSameStartAndEnd) { TEST(BetweenTest, OnSameStartAndEnd) {
...@@ -307,8 +304,7 @@ TEST(BetweenTest, OnSameStartAndEnd) { ...@@ -307,8 +304,7 @@ TEST(BetweenTest, OnSameStartAndEnd) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss.str());
ss.str());
} }
TEST(BetweenTest, OnDifferentStartAndEnd) { TEST(BetweenTest, OnDifferentStartAndEnd) {
...@@ -328,8 +324,7 @@ TEST(BetweenTest, OnDifferentStartAndEnd) { ...@@ -328,8 +324,7 @@ TEST(BetweenTest, OnDifferentStartAndEnd) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", ss.str());
ss.str());
} }
TEST(BetweenTest, HasCorrectBounds) { TEST(BetweenTest, HasCorrectBounds) {
...@@ -341,9 +336,11 @@ TEST(BetweenTest, HasCorrectBounds) { ...@@ -341,9 +336,11 @@ TEST(BetweenTest, HasCorrectBounds) {
// Tests Exactly(n). // Tests Exactly(n).
TEST(ExactlyTest, OnNegativeNumber) { TEST(ExactlyTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
Exactly(-1); { // NOLINT
}, "The invocation lower bound must be >= 0"); Exactly(-1);
},
"The invocation lower bound must be >= 0");
} }
TEST(ExactlyTest, OnZero) { TEST(ExactlyTest, OnZero) {
...@@ -356,8 +353,7 @@ TEST(ExactlyTest, OnZero) { ...@@ -356,8 +353,7 @@ TEST(ExactlyTest, OnZero) {
stringstream ss; stringstream ss;
c.DescribeTo(&ss); c.DescribeTo(&ss);
EXPECT_PRED_FORMAT2(IsSubstring, "never called", EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str());
ss.str());
} }
TEST(ExactlyTest, OnPositiveNumber) { TEST(ExactlyTest, OnPositiveNumber) {
...@@ -370,18 +366,15 @@ TEST(ExactlyTest, OnPositiveNumber) { ...@@ -370,18 +366,15 @@ TEST(ExactlyTest, OnPositiveNumber) {
stringstream ss1; stringstream ss1;
Exactly(1).DescribeTo(&ss1); Exactly(1).DescribeTo(&ss1);
EXPECT_PRED_FORMAT2(IsSubstring, "called once", EXPECT_PRED_FORMAT2(IsSubstring, "called once", ss1.str());
ss1.str());
stringstream ss2; stringstream ss2;
c.DescribeTo(&ss2); c.DescribeTo(&ss2);
EXPECT_PRED_FORMAT2(IsSubstring, "called twice", EXPECT_PRED_FORMAT2(IsSubstring, "called twice", ss2.str());
ss2.str());
stringstream ss3; stringstream ss3;
Exactly(3).DescribeTo(&ss3); Exactly(3).DescribeTo(&ss3);
EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss3.str());
ss3.str());
} }
TEST(ExactlyTest, HasCorrectBounds) { TEST(ExactlyTest, HasCorrectBounds) {
......
// 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 some commonly used argument matchers.
#ifndef GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_
#define GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_
#include <string.h>
#include <time.h>
#include <array>
#include <cstdint>
#include <deque>
#include <forward_list>
#include <functional>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "gmock/gmock-matchers.h"
#include "gmock/gmock-more-matchers.h"
#include "gmock/gmock.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
namespace testing {
namespace gmock_matchers_test {
using std::greater;
using std::less;
using std::list;
using std::make_pair;
using std::map;
using std::multimap;
using std::multiset;
using std::ostream;
using std::pair;
using std::set;
using std::stringstream;
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;
using testing::internal::IsReadableTypeName;
using testing::internal::MatchMatrix;
using testing::internal::PredicateFormatterFromMatcher;
using testing::internal::RE;
using testing::internal::StreamMatchResultListener;
using testing::internal::Strings;
// Helper for testing container-valued matchers in mock method context. It is
// important to test matchers in this context, since it requires additional type
// deduction beyond what EXPECT_THAT does, thus making it more restrictive.
struct ContainerHelper {
MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
};
// For testing ExplainMatchResultTo().
template <typename T>
struct GtestGreaterThanMatcher {
using is_gtest_matcher = void;
void DescribeTo(ostream* os) const { *os << "is > " << rhs; }
void DescribeNegationTo(ostream* os) const { *os << "is <= " << rhs; }
bool MatchAndExplain(T lhs, MatchResultListener* listener) const {
if (lhs > rhs) {
*listener << "which is " << (lhs - rhs) << " more than " << rhs;
} else if (lhs == rhs) {
*listener << "which is the same as " << rhs;
} else {
*listener << "which is " << (rhs - lhs) << " less than " << rhs;
}
return lhs > rhs;
}
T rhs;
};
template <typename T>
GtestGreaterThanMatcher<typename std::decay<T>::type> GtestGreaterThan(
T&& rhs) {
return {rhs};
}
// As the matcher above, but using the base class with virtual functions.
template <typename T>
class GreaterThanMatcher : public MatcherInterface<T> {
public:
explicit GreaterThanMatcher(T rhs) : impl_{rhs} {}
void DescribeTo(ostream* os) const override { impl_.DescribeTo(os); }
void DescribeNegationTo(ostream* os) const override {
impl_.DescribeNegationTo(os);
}
bool MatchAndExplain(T lhs, MatchResultListener* listener) const override {
return impl_.MatchAndExplain(lhs, listener);
}
private:
const GtestGreaterThanMatcher<T> impl_;
};
// Names and instantiates a new instance of GTestMatcherTestP.
#define INSTANTIATE_GTEST_MATCHER_TEST_P(TestSuite) \
using TestSuite##P = GTestMatcherTestP; \
INSTANTIATE_TEST_SUITE_P(MatcherInterface, TestSuite##P, Values(false)); \
INSTANTIATE_TEST_SUITE_P(GtestMatcher, TestSuite##P, Values(true))
class GTestMatcherTestP : public testing::TestWithParam<bool> {
public:
template <typename T>
Matcher<T> GreaterThan(T n) {
if (use_gtest_matcher_) {
return GtestGreaterThan(n);
} else {
return MakeMatcher(new GreaterThanMatcher<T>(n));
}
}
const bool use_gtest_matcher_ = GetParam();
};
// Returns the description of the given matcher.
template <typename T>
std::string Describe(const Matcher<T>& m) {
return DescribeMatcher<T>(m);
}
// Returns the description of the negation of the given matcher.
template <typename T>
std::string DescribeNegation(const Matcher<T>& m) {
return DescribeMatcher<T>(m, true);
}
// 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) {
StringMatchResultListener listener;
ExplainMatchResult(m, x, &listener);
return listener.str();
}
} // namespace gmock_matchers_test
} // namespace testing
#endif // GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_
...@@ -145,7 +145,7 @@ class Foo { ...@@ -145,7 +145,7 @@ class Foo {
std::string Binary(const std::string& str, char c) const { return str + c; } std::string Binary(const std::string& str, char c) const { return str + c; }
int Ternary(int x, bool y, char z) { return value_ + x + y*z; } int Ternary(int x, bool y, char z) { return value_ + x + y * z; }
int SumOf4(int a, int b, int c, int d) const { int SumOf4(int a, int b, int c, int d) const {
return a + b + c + d + value_; return a + b + c + d + value_;
...@@ -291,8 +291,7 @@ TEST(InvokeTest, FunctionWithUnusedParameters) { ...@@ -291,8 +291,7 @@ TEST(InvokeTest, FunctionWithUnusedParameters) {
std::make_tuple(10, 2, 5.6, std::string("hi")); std::make_tuple(10, 2, 5.6, std::string("hi"));
EXPECT_EQ(12, a1.Perform(dummy)); EXPECT_EQ(12, a1.Perform(dummy));
Action<int(int, int, bool, int*)> a2 = Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2);
Invoke(SumOfFirst2);
EXPECT_EQ( EXPECT_EQ(
23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr)))); 23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr))));
} }
...@@ -303,8 +302,7 @@ TEST(InvokeTest, MethodWithUnusedParameters) { ...@@ -303,8 +302,7 @@ TEST(InvokeTest, MethodWithUnusedParameters) {
Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2); Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2);
EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2))); EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2)));
Action<int(char, double, int, int)> a2 = Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2);
Invoke(&foo, &Foo::SumOfLast2);
EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3))); EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3)));
} }
...@@ -362,7 +360,8 @@ TEST(InvokeMethodTest, MethodThatTakes4Arguments) { ...@@ -362,7 +360,8 @@ TEST(InvokeMethodTest, MethodThatTakes4Arguments) {
// Tests using Invoke() with a 5-argument method. // Tests using Invoke() with a 5-argument method.
TEST(InvokeMethodTest, MethodThatTakes5Arguments) { TEST(InvokeMethodTest, MethodThatTakes5Arguments) {
Foo foo; Foo foo;
Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5); // NOLINT Action<int(int, int, int, int, int)> a =
Invoke(&foo, &Foo::SumOf5); // NOLINT
EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5)));
} }
...@@ -462,6 +461,12 @@ TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) { ...@@ -462,6 +461,12 @@ TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) {
EXPECT_EQ("seven", a.Perform(std::make_tuple(5, 6, std::string("seven"), 8))); EXPECT_EQ("seven", a.Perform(std::make_tuple(5, 6, std::string("seven"), 8)));
} }
TEST(ReturnArgActionTest, WorksForNonConstRefArg0) {
const Action<std::string&(std::string&)> a = ReturnArg<0>();
std::string s = "12345";
EXPECT_EQ(&s, &a.Perform(std::forward_as_tuple(s)));
}
TEST(SaveArgActionTest, WorksForSameType) { TEST(SaveArgActionTest, WorksForSameType) {
int result = 0; int result = 0;
const Action<void(int n)> a1 = SaveArg<0>(&result); const Action<void(int n)> a1 = SaveArg<0>(&result);
...@@ -517,15 +522,12 @@ TEST(SetArgRefereeActionTest, WorksWithExtraArguments) { ...@@ -517,15 +522,12 @@ TEST(SetArgRefereeActionTest, WorksWithExtraArguments) {
// the bool provided to the constructor to true when destroyed. // the bool provided to the constructor to true when destroyed.
class DeletionTester { class DeletionTester {
public: public:
explicit DeletionTester(bool* is_deleted) explicit DeletionTester(bool* is_deleted) : is_deleted_(is_deleted) {
: is_deleted_(is_deleted) {
// Make sure the bit is set to false. // Make sure the bit is set to false.
*is_deleted_ = false; *is_deleted_ = false;
} }
~DeletionTester() { ~DeletionTester() { *is_deleted_ = true; }
*is_deleted_ = true;
}
private: private:
bool* is_deleted_; bool* is_deleted_;
...@@ -534,7 +536,7 @@ class DeletionTester { ...@@ -534,7 +536,7 @@ class DeletionTester {
TEST(DeleteArgActionTest, OneArg) { TEST(DeleteArgActionTest, OneArg) {
bool is_deleted = false; bool is_deleted = false;
DeletionTester* t = new DeletionTester(&is_deleted); DeletionTester* t = new DeletionTester(&is_deleted);
const Action<void(DeletionTester*)> a1 = DeleteArg<0>(); // NOLINT const Action<void(DeletionTester*)> a1 = DeleteArg<0>(); // NOLINT
EXPECT_FALSE(is_deleted); EXPECT_FALSE(is_deleted);
a1.Perform(std::make_tuple(t)); a1.Perform(std::make_tuple(t));
EXPECT_TRUE(is_deleted); EXPECT_TRUE(is_deleted);
...@@ -543,8 +545,9 @@ TEST(DeleteArgActionTest, OneArg) { ...@@ -543,8 +545,9 @@ TEST(DeleteArgActionTest, OneArg) {
TEST(DeleteArgActionTest, TenArgs) { TEST(DeleteArgActionTest, TenArgs) {
bool is_deleted = false; bool is_deleted = false;
DeletionTester* t = new DeletionTester(&is_deleted); DeletionTester* t = new DeletionTester(&is_deleted);
const Action<void(bool, int, int, const char*, bool, const Action<void(bool, int, int, const char*, bool, int, int, int, int,
int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>(); DeletionTester*)>
a1 = DeleteArg<9>();
EXPECT_FALSE(is_deleted); EXPECT_FALSE(is_deleted);
a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t));
EXPECT_TRUE(is_deleted); EXPECT_TRUE(is_deleted);
...@@ -602,7 +605,7 @@ TEST(ThrowActionTest, Times0) { ...@@ -602,7 +605,7 @@ TEST(ThrowActionTest, Times0) {
// pointed to by the N-th (0-based) argument to values in range [first, last). // pointed to by the N-th (0-based) argument to values in range [first, last).
TEST(SetArrayArgumentTest, SetsTheNthArray) { TEST(SetArrayArgumentTest, SetsTheNthArray) {
using MyFunction = void(bool, int*, char*); using MyFunction = void(bool, int*, char*);
int numbers[] = { 1, 2, 3 }; int numbers[] = {1, 2, 3};
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3); Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3);
int n[4] = {}; int n[4] = {};
...@@ -638,7 +641,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) { ...@@ -638,7 +641,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArray) {
// Tests SetArrayArgument<N>(first, last) where first == last. // Tests SetArrayArgument<N>(first, last) where first == last.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
using MyFunction = void(bool, int*); using MyFunction = void(bool, int*);
int numbers[] = { 1, 2, 3 }; int numbers[] = {1, 2, 3};
Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers); Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers);
int n[4] = {}; int n[4] = {};
...@@ -654,10 +657,10 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { ...@@ -654,10 +657,10 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
// (but not equal) to the argument type. // (but not equal) to the argument type.
TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) { TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
using MyFunction = void(bool, int*); using MyFunction = void(bool, int*);
char chars[] = { 97, 98, 99 }; char chars[] = {97, 98, 99};
Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3); Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3);
int codes[4] = { 111, 222, 333, 444 }; int codes[4] = {111, 222, 333, 444};
int* pcodes = codes; int* pcodes = codes;
a.Perform(std::make_tuple(true, pcodes)); a.Perform(std::make_tuple(true, pcodes));
EXPECT_EQ(97, codes[0]); EXPECT_EQ(97, codes[0]);
......
...@@ -31,6 +31,7 @@ ...@@ -31,6 +31,7 @@
#include <string> #include <string>
#include <utility> #include <utility>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
...@@ -44,13 +45,13 @@ class Mock { ...@@ -44,13 +45,13 @@ class Mock {
MOCK_METHOD0(DoThis, void()); MOCK_METHOD0(DoThis, void());
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock); Mock(const Mock&) = delete;
Mock& operator=(const Mock&) = delete;
}; };
namespace testing { namespace testing {
namespace gmock_nice_strict_test { namespace gmock_nice_strict_test {
using testing::GMOCK_FLAG(verbose);
using testing::HasSubstr; using testing::HasSubstr;
using testing::NaggyMock; using testing::NaggyMock;
using testing::NiceMock; using testing::NiceMock;
...@@ -93,7 +94,8 @@ class MockFoo : public Foo { ...@@ -93,7 +94,8 @@ class MockFoo : public Foo {
MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible()); MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible());
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); MockFoo(const MockFoo&) = delete;
MockFoo& operator=(const MockFoo&) = delete;
}; };
class MockBar { class MockBar {
...@@ -103,7 +105,8 @@ class MockBar { ...@@ -103,7 +105,8 @@ class MockBar {
MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6, MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6,
const std::string& a7, const std::string& a8, bool a9, bool a10) { const std::string& a7, const std::string& a8, bool a9, bool a10) {
str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) +
static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F'); static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') +
(a10 ? 'T' : 'F');
} }
virtual ~MockBar() {} virtual ~MockBar() {}
...@@ -116,10 +119,10 @@ class MockBar { ...@@ -116,10 +119,10 @@ class MockBar {
private: private:
std::string str_; std::string str_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar); MockBar(const MockBar&) = delete;
MockBar& operator=(const MockBar&) = delete;
}; };
class MockBaz { class MockBaz {
public: public:
class MoveOnly { class MoveOnly {
...@@ -140,8 +143,8 @@ class MockBaz { ...@@ -140,8 +143,8 @@ class MockBaz {
// Tests that a raw mock generates warnings for uninteresting calls. // Tests that a raw mock generates warnings for uninteresting calls.
TEST(RawMockTest, WarningForUninterestingCall) { TEST(RawMockTest, WarningForUninterestingCall) {
const std::string saved_flag = GMOCK_FLAG(verbose); const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG(verbose) = "warning"; GMOCK_FLAG_SET(verbose, "warning");
MockFoo raw_foo; MockFoo raw_foo;
...@@ -151,26 +154,25 @@ TEST(RawMockTest, WarningForUninterestingCall) { ...@@ -151,26 +154,25 @@ TEST(RawMockTest, WarningForUninterestingCall) {
EXPECT_THAT(GetCapturedStdout(), EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call")); HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag; GMOCK_FLAG_SET(verbose, saved_flag);
} }
// Tests that a raw mock generates warnings for uninteresting calls // Tests that a raw mock generates warnings for uninteresting calls
// that delete the mock object. // that delete the mock object.
TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { TEST(RawMockTest, WarningForUninterestingCallAfterDeath) {
const std::string saved_flag = GMOCK_FLAG(verbose); const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG(verbose) = "warning"; GMOCK_FLAG_SET(verbose, "warning");
MockFoo* const raw_foo = new MockFoo; MockFoo* const raw_foo = new MockFoo;
ON_CALL(*raw_foo, DoThis()) ON_CALL(*raw_foo, DoThis()).WillByDefault(Invoke(raw_foo, &MockFoo::Delete));
.WillByDefault(Invoke(raw_foo, &MockFoo::Delete));
CaptureStdout(); CaptureStdout();
raw_foo->DoThis(); raw_foo->DoThis();
EXPECT_THAT(GetCapturedStdout(), EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call")); HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag; GMOCK_FLAG_SET(verbose, saved_flag);
} }
// Tests that a raw mock generates informational logs for // Tests that a raw mock generates informational logs for
...@@ -178,14 +180,14 @@ TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { ...@@ -178,14 +180,14 @@ TEST(RawMockTest, WarningForUninterestingCallAfterDeath) {
TEST(RawMockTest, InfoForUninterestingCall) { TEST(RawMockTest, InfoForUninterestingCall) {
MockFoo raw_foo; MockFoo raw_foo;
const std::string saved_flag = GMOCK_FLAG(verbose); const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG(verbose) = "info"; GMOCK_FLAG_SET(verbose, "info");
CaptureStdout(); CaptureStdout();
raw_foo.DoThis(); raw_foo.DoThis();
EXPECT_THAT(GetCapturedStdout(), EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call")); HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag; GMOCK_FLAG_SET(verbose, saved_flag);
} }
TEST(RawMockTest, IsNaggy_IsNice_IsStrict) { TEST(RawMockTest, IsNaggy_IsNice_IsStrict) {
...@@ -223,14 +225,14 @@ TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) { ...@@ -223,14 +225,14 @@ TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) {
TEST(NiceMockTest, InfoForUninterestingCall) { TEST(NiceMockTest, InfoForUninterestingCall) {
NiceMock<MockFoo> nice_foo; NiceMock<MockFoo> nice_foo;
const std::string saved_flag = GMOCK_FLAG(verbose); const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG(verbose) = "info"; GMOCK_FLAG_SET(verbose, "info");
CaptureStdout(); CaptureStdout();
nice_foo.DoThis(); nice_foo.DoThis();
EXPECT_THAT(GetCapturedStdout(), EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call")); HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag; GMOCK_FLAG_SET(verbose, saved_flag);
} }
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
...@@ -281,8 +283,8 @@ TEST(NiceMockTest, NonDefaultConstructor) { ...@@ -281,8 +283,8 @@ TEST(NiceMockTest, NonDefaultConstructor) {
// Tests that NiceMock works with a mock class that has a 10-ary // Tests that NiceMock works with a mock class that has a 10-ary
// non-default constructor. // non-default constructor.
TEST(NiceMockTest, NonDefaultConstructor10) { TEST(NiceMockTest, NonDefaultConstructor10) {
NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true,
"g", "h", true, false); false);
EXPECT_EQ("abcdefghTF", nice_bar.str()); EXPECT_EQ("abcdefghTF", nice_bar.str());
nice_bar.This(); nice_bar.This();
...@@ -326,8 +328,8 @@ TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) { ...@@ -326,8 +328,8 @@ TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) {
// Tests that a naggy mock generates warnings for uninteresting calls. // Tests that a naggy mock generates warnings for uninteresting calls.
TEST(NaggyMockTest, WarningForUninterestingCall) { TEST(NaggyMockTest, WarningForUninterestingCall) {
const std::string saved_flag = GMOCK_FLAG(verbose); const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG(verbose) = "warning"; GMOCK_FLAG_SET(verbose, "warning");
NaggyMock<MockFoo> naggy_foo; NaggyMock<MockFoo> naggy_foo;
...@@ -337,14 +339,14 @@ TEST(NaggyMockTest, WarningForUninterestingCall) { ...@@ -337,14 +339,14 @@ TEST(NaggyMockTest, WarningForUninterestingCall) {
EXPECT_THAT(GetCapturedStdout(), EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call")); HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag; GMOCK_FLAG_SET(verbose, saved_flag);
} }
// Tests that a naggy mock generates a warning for an uninteresting call // Tests that a naggy mock generates a warning for an uninteresting call
// that deletes the mock object. // that deletes the mock object.
TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) { TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) {
const std::string saved_flag = GMOCK_FLAG(verbose); const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG(verbose) = "warning"; GMOCK_FLAG_SET(verbose, "warning");
NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>; NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>;
...@@ -356,7 +358,7 @@ TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) { ...@@ -356,7 +358,7 @@ TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) {
EXPECT_THAT(GetCapturedStdout(), EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call")); HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag; GMOCK_FLAG_SET(verbose, saved_flag);
} }
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
...@@ -391,8 +393,8 @@ TEST(NaggyMockTest, NonDefaultConstructor) { ...@@ -391,8 +393,8 @@ TEST(NaggyMockTest, NonDefaultConstructor) {
// Tests that NaggyMock works with a mock class that has a 10-ary // Tests that NaggyMock works with a mock class that has a 10-ary
// non-default constructor. // non-default constructor.
TEST(NaggyMockTest, NonDefaultConstructor10) { TEST(NaggyMockTest, NonDefaultConstructor10) {
NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', "6", "7", true,
"6", "7", true, false); false);
EXPECT_EQ("01234567TF", naggy_bar.str()); EXPECT_EQ("01234567TF", naggy_bar.str());
naggy_bar.This(); naggy_bar.This();
...@@ -419,8 +421,8 @@ TEST(NaggyMockTest, AcceptsClassNamedMock) { ...@@ -419,8 +421,8 @@ TEST(NaggyMockTest, AcceptsClassNamedMock) {
} }
TEST(NaggyMockTest, IsNaggyInDestructor) { TEST(NaggyMockTest, IsNaggyInDestructor) {
const std::string saved_flag = GMOCK_FLAG(verbose); const std::string saved_flag = GMOCK_FLAG_GET(verbose);
GMOCK_FLAG(verbose) = "warning"; GMOCK_FLAG_SET(verbose, "warning");
CaptureStdout(); CaptureStdout();
{ {
...@@ -431,7 +433,7 @@ TEST(NaggyMockTest, IsNaggyInDestructor) { ...@@ -431,7 +433,7 @@ TEST(NaggyMockTest, IsNaggyInDestructor) {
EXPECT_THAT(GetCapturedStdout(), EXPECT_THAT(GetCapturedStdout(),
HasSubstr("Uninteresting mock function call")); HasSubstr("Uninteresting mock function call"));
GMOCK_FLAG(verbose) = saved_flag; GMOCK_FLAG_SET(verbose, saved_flag);
} }
TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) { TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) {
...@@ -491,8 +493,8 @@ TEST(StrictMockTest, NonDefaultConstructor) { ...@@ -491,8 +493,8 @@ TEST(StrictMockTest, NonDefaultConstructor) {
// Tests that StrictMock works with a mock class that has a 10-ary // Tests that StrictMock works with a mock class that has a 10-ary
// non-default constructor. // non-default constructor.
TEST(StrictMockTest, NonDefaultConstructor10) { TEST(StrictMockTest, NonDefaultConstructor10) {
StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true,
"g", "h", true, false); false);
EXPECT_EQ("abcdefghTF", strict_bar.str()); EXPECT_EQ("abcdefghTF", strict_bar.str());
EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true), EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true),
......
...@@ -27,12 +27,12 @@ ...@@ -27,12 +27,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the internal cross-platform support utilities. // This file tests the internal cross-platform support utilities.
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
// NOTE: if this file is left without tests for some reason, put a dummy // NOTE: if this file is left without tests for some reason, put a dummy
......
...@@ -30,11 +30,10 @@ ...@@ -30,11 +30,10 @@
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the internal preprocessor macro library. // This file tests the internal preprocessor macro library.
#include "gmock/internal/gmock-pp.h"
#include <string> #include <string>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gmock/internal/gmock-pp.h"
namespace testing { namespace testing {
namespace { namespace {
......
...@@ -38,7 +38,10 @@ ...@@ -38,7 +38,10 @@
#include "test/gmock-actions_test.cc" #include "test/gmock-actions_test.cc"
#include "test/gmock-cardinalities_test.cc" #include "test/gmock-cardinalities_test.cc"
#include "test/gmock-internal-utils_test.cc" #include "test/gmock-internal-utils_test.cc"
#include "test/gmock-matchers_test.cc" #include "test/gmock-matchers-arithmetic_test.cc"
#include "test/gmock-matchers-comparisons_test.cc"
#include "test/gmock-matchers-containers_test.cc"
#include "test/gmock-matchers-misc_test.cc"
#include "test/gmock-more-actions_test.cc" #include "test/gmock-more-actions_test.cc"
#include "test/gmock-nice-strict_test.cc" #include "test/gmock-nice-strict_test.cc"
#include "test/gmock-port_test.cc" #include "test/gmock-port_test.cc"
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests Google Mock's functionality that depends on exceptions. // Tests Google Mock's functionality that depends on exceptions.
#include "gmock/gmock.h" #include "gmock/gmock.h"
...@@ -75,6 +74,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { ...@@ -75,6 +74,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
} }
} }
} // unnamed namespace } // unnamed namespace
#endif #endif
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
"""Tests that leaked mock objects can be caught be Google Mock.""" """Tests that leaked mock objects can be caught be Google Mock."""
import gmock_test_utils from googlemock.test import gmock_test_utils
PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_') PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_')
TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*'] TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*']
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This program is for verifying that a leaked mock object can be // This program is for verifying that a leaked mock object can be
...@@ -52,7 +51,8 @@ class MockFoo : public FooInterface { ...@@ -52,7 +51,8 @@ class MockFoo : public FooInterface {
MOCK_METHOD0(DoThis, void()); MOCK_METHOD0(DoThis, void());
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); MockFoo(const MockFoo&) = delete;
MockFoo& operator=(const MockFoo&) = delete;
}; };
TEST(LeakTest, LeakedMockWithExpectCallCausesFailureWhenLeakCheckingIsEnabled) { TEST(LeakTest, LeakedMockWithExpectCallCausesFailureWhenLeakCheckingIsEnabled) {
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file is for verifying that various Google Mock constructs do not // This file is for verifying that various Google Mock constructs do not
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file is for verifying that various Google Mock constructs do not // This file is for verifying that various Google Mock constructs do not
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests that: // This file tests that:
...@@ -118,7 +117,7 @@ ...@@ -118,7 +117,7 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#if !GTEST_OS_WINDOWS_MOBILE #if !GTEST_OS_WINDOWS_MOBILE
# include <errno.h> #include <errno.h>
#endif #endif
#include <iostream> #include <iostream>
...@@ -200,14 +199,14 @@ class Interface { ...@@ -200,14 +199,14 @@ class Interface {
virtual char* StringFromString(char* str) = 0; virtual char* StringFromString(char* str) = 0;
virtual int IntFromString(char* str) = 0; virtual int IntFromString(char* str) = 0;
virtual int& IntRefFromString(char* str) = 0; virtual int& IntRefFromString(char* str) = 0;
virtual void VoidFromFunc(void(*func)(char* str)) = 0; virtual void VoidFromFunc(void (*func)(char* str)) = 0;
virtual void VoidFromIntRef(int& n) = 0; // NOLINT virtual void VoidFromIntRef(int& n) = 0; // NOLINT
virtual void VoidFromFloat(float n) = 0; virtual void VoidFromFloat(float n) = 0;
virtual void VoidFromDouble(double n) = 0; virtual void VoidFromDouble(double n) = 0;
virtual void VoidFromVector(const std::vector<int>& v) = 0; virtual void VoidFromVector(const std::vector<int>& v) = 0;
}; };
class Mock: public Interface { class Mock : public Interface {
public: public:
Mock() {} Mock() {}
...@@ -215,14 +214,15 @@ class Mock: public Interface { ...@@ -215,14 +214,15 @@ class Mock: public Interface {
MOCK_METHOD1(StringFromString, char*(char* str)); MOCK_METHOD1(StringFromString, char*(char* str));
MOCK_METHOD1(IntFromString, int(char* str)); MOCK_METHOD1(IntFromString, int(char* str));
MOCK_METHOD1(IntRefFromString, int&(char* str)); MOCK_METHOD1(IntRefFromString, int&(char* str));
MOCK_METHOD1(VoidFromFunc, void(void(*func)(char* str))); MOCK_METHOD1(VoidFromFunc, void(void (*func)(char* str)));
MOCK_METHOD1(VoidFromIntRef, void(int& n)); // NOLINT MOCK_METHOD1(VoidFromIntRef, void(int& n)); // NOLINT
MOCK_METHOD1(VoidFromFloat, void(float n)); MOCK_METHOD1(VoidFromFloat, void(float n));
MOCK_METHOD1(VoidFromDouble, void(double n)); MOCK_METHOD1(VoidFromDouble, void(double n));
MOCK_METHOD1(VoidFromVector, void(const std::vector<int>& v)); MOCK_METHOD1(VoidFromVector, void(const std::vector<int>& v));
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock); Mock(const Mock&) = delete;
Mock& operator=(const Mock&) = delete;
}; };
class InvokeHelper { class InvokeHelper {
...@@ -301,8 +301,8 @@ TEST(LinkTest, TestSetArrayArgument) { ...@@ -301,8 +301,8 @@ TEST(LinkTest, TestSetArrayArgument) {
char ch = 'x'; char ch = 'x';
char ch2 = 'y'; char ch2 = 'y';
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArrayArgument<0>(&ch2, EXPECT_CALL(mock, VoidFromString(_))
&ch2 + 1)); .WillOnce(SetArrayArgument<0>(&ch2, &ch2 + 1));
mock.VoidFromString(&ch); mock.VoidFromString(&ch);
} }
...@@ -339,8 +339,8 @@ TEST(LinkTest, TestInvokeWithoutArgs) { ...@@ -339,8 +339,8 @@ TEST(LinkTest, TestInvokeWithoutArgs) {
EXPECT_CALL(mock, VoidFromString(_)) EXPECT_CALL(mock, VoidFromString(_))
.WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid)) .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid))
.WillOnce(InvokeWithoutArgs(&test_invoke_helper, .WillOnce(
&InvokeHelper::VoidFromVoid)); InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid));
mock.VoidFromString(nullptr); mock.VoidFromString(nullptr);
mock.VoidFromString(nullptr); mock.VoidFromString(nullptr);
} }
...@@ -424,14 +424,14 @@ TEST(LinkTest, TestThrow) { ...@@ -424,14 +424,14 @@ TEST(LinkTest, TestThrow) {
// is expanded and macro expansion cannot contain #pragma. Therefore // is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here. // we suppress them here.
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#endif #endif
// Tests the linkage of actions created using ACTION macro. // Tests the linkage of actions created using ACTION macro.
namespace { namespace {
ACTION(Return1) { return 1; } ACTION(Return1) { return 1; }
} } // namespace
TEST(LinkTest, TestActionMacro) { TEST(LinkTest, TestActionMacro) {
Mock mock; Mock mock;
...@@ -443,7 +443,7 @@ TEST(LinkTest, TestActionMacro) { ...@@ -443,7 +443,7 @@ TEST(LinkTest, TestActionMacro) {
// Tests the linkage of actions created using ACTION_P macro. // Tests the linkage of actions created using ACTION_P macro.
namespace { namespace {
ACTION_P(ReturnArgument, ret_value) { return ret_value; } ACTION_P(ReturnArgument, ret_value) { return ret_value; }
} } // namespace
TEST(LinkTest, TestActionPMacro) { TEST(LinkTest, TestActionPMacro) {
Mock mock; Mock mock;
...@@ -457,10 +457,10 @@ namespace { ...@@ -457,10 +457,10 @@ namespace {
ACTION_P2(ReturnEqualsEitherOf, first, second) { ACTION_P2(ReturnEqualsEitherOf, first, second) {
return arg0 == first || arg0 == second; return arg0 == first || arg0 == second;
} }
} } // namespace
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
TEST(LinkTest, TestActionP2Macro) { TEST(LinkTest, TestActionP2Macro) {
...@@ -492,8 +492,7 @@ TEST(LinkTest, TestMatchersEq) { ...@@ -492,8 +492,7 @@ TEST(LinkTest, TestMatchersEq) {
const char* p = "x"; const char* p = "x";
ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return()); ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return());
ON_CALL(mock, VoidFromString(const_cast<char*>("y"))) ON_CALL(mock, VoidFromString(const_cast<char*>("y"))).WillByDefault(Return());
.WillByDefault(Return());
} }
// Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers. // Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers.
...@@ -592,7 +591,7 @@ TEST(LinkTest, TestMatcherElementsAre) { ...@@ -592,7 +591,7 @@ TEST(LinkTest, TestMatcherElementsAre) {
// Tests the linkage of the ElementsAreArray matcher. // Tests the linkage of the ElementsAreArray matcher.
TEST(LinkTest, TestMatcherElementsAreArray) { TEST(LinkTest, TestMatcherElementsAreArray) {
Mock mock; Mock mock;
char arr[] = { 'a', 'b' }; char arr[] = {'a', 'b'};
ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return()); ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return());
} }
......
...@@ -43,7 +43,7 @@ from io import open # pylint: disable=redefined-builtin, g-importing-member ...@@ -43,7 +43,7 @@ from io import open # pylint: disable=redefined-builtin, g-importing-member
import os import os
import re import re
import sys import sys
import gmock_test_utils from googlemock.test import gmock_test_utils
# The flag for generating the golden file # The flag for generating the golden file
...@@ -159,15 +159,18 @@ class GMockOutputTest(gmock_test_utils.TestCase): ...@@ -159,15 +159,18 @@ class GMockOutputTest(gmock_test_utils.TestCase):
golden_file = open(GOLDEN_PATH, 'rb') golden_file = open(GOLDEN_PATH, 'rb')
golden = golden_file.read().decode('utf-8') golden = golden_file.read().decode('utf-8')
golden_file.close() golden_file.close()
# On Windows the repository might have been checked out with \r\n line
# endings, so normalize it here.
golden = ToUnixLineEnding(golden)
# The normalized output should match the golden file. # The normalized output should match the golden file.
self.assertEquals(golden, output) self.assertEqual(golden, output)
# The raw output should contain 2 leaked mock object errors for # The raw output should contain 2 leaked mock object errors for
# test GMockOutputTest.CatchesLeakedMocks. # test GMockOutputTest.CatchesLeakedMocks.
self.assertEquals(['GMockOutputTest.CatchesLeakedMocks', self.assertEqual(['GMockOutputTest.CatchesLeakedMocks',
'GMockOutputTest.CatchesLeakedMocks'], 'GMockOutputTest.CatchesLeakedMocks'],
leaky_tests) leaky_tests)
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -27,21 +27,20 @@ ...@@ -27,21 +27,20 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests Google Mock's output in various scenarios. This ensures that // Tests Google Mock's output in various scenarios. This ensures that
// Google Mock's messages are readable and useful. // Google Mock's messages are readable and useful.
#include "gmock/gmock.h"
#include <stdio.h> #include <stdio.h>
#include <string> #include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
// Silence C4100 (unreferenced formal parameter) // Silence C4100 (unreferenced formal parameter)
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#endif #endif
using testing::_; using testing::_;
...@@ -63,7 +62,8 @@ class MockFoo { ...@@ -63,7 +62,8 @@ class MockFoo {
MOCK_METHOD2(Bar3, void(int x, int y)); MOCK_METHOD2(Bar3, void(int x, int y));
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); MockFoo(const MockFoo&) = delete;
MockFoo& operator=(const MockFoo&) = delete;
}; };
class GMockOutputTest : public testing::Test { class GMockOutputTest : public testing::Test {
...@@ -72,27 +72,25 @@ class GMockOutputTest : public testing::Test { ...@@ -72,27 +72,25 @@ class GMockOutputTest : public testing::Test {
}; };
TEST_F(GMockOutputTest, ExpectedCall) { TEST_F(GMockOutputTest, ExpectedCall) {
testing::GMOCK_FLAG(verbose) = "info"; GMOCK_FLAG_SET(verbose, "info");
EXPECT_CALL(foo_, Bar2(0, _)); EXPECT_CALL(foo_, Bar2(0, _));
foo_.Bar2(0, 0); // Expected call foo_.Bar2(0, 0); // Expected call
testing::GMOCK_FLAG(verbose) = "warning"; GMOCK_FLAG_SET(verbose, "warning");
} }
TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) { TEST_F(GMockOutputTest, ExpectedCallToVoidFunction) {
testing::GMOCK_FLAG(verbose) = "info"; GMOCK_FLAG_SET(verbose, "info");
EXPECT_CALL(foo_, Bar3(0, _)); EXPECT_CALL(foo_, Bar3(0, _));
foo_.Bar3(0, 0); // Expected call foo_.Bar3(0, 0); // Expected call
testing::GMOCK_FLAG(verbose) = "warning"; GMOCK_FLAG_SET(verbose, "warning");
} }
TEST_F(GMockOutputTest, ExplicitActionsRunOut) { TEST_F(GMockOutputTest, ExplicitActionsRunOut) {
EXPECT_CALL(foo_, Bar2(_, _)) EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));
.Times(2)
.WillOnce(Return(false));
foo_.Bar2(2, 2); foo_.Bar2(2, 2);
foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out.
} }
...@@ -134,8 +132,7 @@ TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) { ...@@ -134,8 +132,7 @@ TEST_F(GMockOutputTest, UninterestingCallToVoidFunction) {
} }
TEST_F(GMockOutputTest, RetiredExpectation) { TEST_F(GMockOutputTest, RetiredExpectation) {
EXPECT_CALL(foo_, Bar2(_, _)) EXPECT_CALL(foo_, Bar2(_, _)).RetiresOnSaturation();
.RetiresOnSaturation();
EXPECT_CALL(foo_, Bar2(0, 0)); EXPECT_CALL(foo_, Bar2(0, 0));
foo_.Bar2(1, 1); foo_.Bar2(1, 1);
...@@ -160,12 +157,9 @@ TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) { ...@@ -160,12 +157,9 @@ TEST_F(GMockOutputTest, UnsatisfiedPrerequisite) {
TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) { TEST_F(GMockOutputTest, UnsatisfiedPrerequisites) {
Sequence s1, s2; Sequence s1, s2;
EXPECT_CALL(foo_, Bar(_, 0, _)) EXPECT_CALL(foo_, Bar(_, 0, _)).InSequence(s1);
.InSequence(s1); EXPECT_CALL(foo_, Bar2(0, 0)).InSequence(s2);
EXPECT_CALL(foo_, Bar2(0, 0)) EXPECT_CALL(foo_, Bar2(1, _)).InSequence(s1, s2);
.InSequence(s2);
EXPECT_CALL(foo_, Bar2(1, _))
.InSequence(s1, s2);
foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites foo_.Bar2(1, 0); // Has two immediate unsatisfied pre-requisites
foo_.Bar("Hi", 0, 0); foo_.Bar("Hi", 0, 0);
...@@ -179,8 +173,7 @@ TEST_F(GMockOutputTest, UnsatisfiedWith) { ...@@ -179,8 +173,7 @@ TEST_F(GMockOutputTest, UnsatisfiedWith) {
TEST_F(GMockOutputTest, UnsatisfiedExpectation) { TEST_F(GMockOutputTest, UnsatisfiedExpectation) {
EXPECT_CALL(foo_, Bar(_, _, _)); EXPECT_CALL(foo_, Bar(_, _, _));
EXPECT_CALL(foo_, Bar2(0, _)) EXPECT_CALL(foo_, Bar2(0, _)).Times(2);
.Times(2);
foo_.Bar2(0, 1); foo_.Bar2(0, 1);
} }
...@@ -194,26 +187,22 @@ TEST_F(GMockOutputTest, MismatchArguments) { ...@@ -194,26 +187,22 @@ TEST_F(GMockOutputTest, MismatchArguments) {
} }
TEST_F(GMockOutputTest, MismatchWith) { TEST_F(GMockOutputTest, MismatchWith) {
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());
.With(Ge());
foo_.Bar2(2, 3); // Mismatch With() foo_.Bar2(2, 3); // Mismatch With()
foo_.Bar2(2, 1); foo_.Bar2(2, 1);
} }
TEST_F(GMockOutputTest, MismatchArgumentsAndWith) { TEST_F(GMockOutputTest, MismatchArgumentsAndWith) {
EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))) EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());
.With(Ge());
foo_.Bar2(1, 3); // Mismatch arguments and mismatch With() foo_.Bar2(1, 3); // Mismatch arguments and mismatch With()
foo_.Bar2(2, 1); foo_.Bar2(2, 1);
} }
TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _)) ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
.WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
EXPECT_CALL(foo_, Bar2(2, 2)); EXPECT_CALL(foo_, Bar2(2, 2));
foo_.Bar2(1, 0); // Unexpected call, takes default action #2. foo_.Bar2(1, 0); // Unexpected call, takes default action #2.
...@@ -222,10 +211,8 @@ TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) { ...@@ -222,10 +211,8 @@ TEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {
} }
TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _)) ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
.WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
EXPECT_CALL(foo_, Bar2(2, 2)); EXPECT_CALL(foo_, Bar2(2, 2));
EXPECT_CALL(foo_, Bar2(1, 1)); EXPECT_CALL(foo_, Bar2(1, 1));
...@@ -237,22 +224,17 @@ TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) { ...@@ -237,22 +224,17 @@ TEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {
} }
TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) { TEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _)) ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
.WillByDefault(Return(true)); // Default action #1 ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false)); // Default action #2
ON_CALL(foo_, Bar2(1, _))
.WillByDefault(Return(false)); // Default action #2
foo_.Bar2(2, 2); // Uninteresting call, takes default action #1. foo_.Bar2(2, 2); // Uninteresting call, takes default action #1.
foo_.Bar2(1, 1); // Uninteresting call, takes default action #2. foo_.Bar2(1, 1); // Uninteresting call, takes default action #2.
} }
TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) { TEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) {
ON_CALL(foo_, Bar2(_, _)) ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true)); // Default action #1
.WillByDefault(Return(true)); // Default action #1
EXPECT_CALL(foo_, Bar2(_, _)) EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));
.Times(2)
.WillOnce(Return(false));
foo_.Bar2(2, 2); foo_.Bar2(2, 2);
foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out. foo_.Bar2(1, 1); // Explicit actions in EXPECT_CALL run out.
} }
...@@ -293,17 +275,17 @@ void TestCatchesLeakedMocksInAdHocTests() { ...@@ -293,17 +275,17 @@ void TestCatchesLeakedMocksInAdHocTests() {
// foo is deliberately leaked. // foo is deliberately leaked.
} }
int main(int argc, char **argv) { int main(int argc, char** argv) {
testing::InitGoogleMock(&argc, argv); testing::InitGoogleMock(&argc, argv);
// Ensures that the tests pass no matter what value of // Ensures that the tests pass no matter what value of
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
testing::GMOCK_FLAG(catch_leaked_mocks) = true; GMOCK_FLAG_SET(catch_leaked_mocks, true);
testing::GMOCK_FLAG(verbose) = "warning"; GMOCK_FLAG_SET(verbose, "warning");
TestCatchesLeakedMocksInAdHocTests(); TestCatchesLeakedMocksInAdHocTests();
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
...@@ -75,14 +75,14 @@ GMOCK WARNING: ...@@ -75,14 +75,14 @@ GMOCK WARNING:
Uninteresting mock function call - returning default value. Uninteresting mock function call - returning default value.
Function call: Bar2(0, 1) Function call: Bar2(0, 1)
Returns: false Returns: false
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details. NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCall [ OK ] GMockOutputTest.UninterestingCall
[ RUN ] GMockOutputTest.UninterestingCallToVoidFunction [ RUN ] GMockOutputTest.UninterestingCallToVoidFunction
GMOCK WARNING: GMOCK WARNING:
Uninteresting mock function call - returning directly. Uninteresting mock function call - returning directly.
Function call: Bar3(0, 1) Function call: Bar3(0, 1)
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details. NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallToVoidFunction [ OK ] GMockOutputTest.UninterestingCallToVoidFunction
[ RUN ] GMockOutputTest.RetiredExpectation [ RUN ] GMockOutputTest.RetiredExpectation
unknown file: Failure unknown file: Failure
...@@ -266,14 +266,14 @@ Uninteresting mock function call - taking default action specified at: ...@@ -266,14 +266,14 @@ Uninteresting mock function call - taking default action specified at:
FILE:#: FILE:#:
Function call: Bar2(2, 2) Function call: Bar2(2, 2)
Returns: true Returns: true
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details. NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect for details.
GMOCK WARNING: GMOCK WARNING:
Uninteresting mock function call - taking default action specified at: Uninteresting mock function call - taking default action specified at:
FILE:#: FILE:#:
Function call: Bar2(1, 1) Function call: Bar2(1, 1)
Returns: false Returns: false
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details. NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md#knowing-when-to-expect for details.
[ OK ] GMockOutputTest.UninterestingCallWithDefaultAction [ OK ] GMockOutputTest.UninterestingCallWithDefaultAction
[ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction [ RUN ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction
...@@ -291,7 +291,7 @@ Stack trace: ...@@ -291,7 +291,7 @@ Stack trace:
[ RUN ] GMockOutputTest.PrintsMatcher [ RUN ] GMockOutputTest.PrintsMatcher
FILE:#: Failure FILE:#: Failure
Value of: (std::pair<int, bool>(42, true)) Value of: (std::pair<int, bool>(42, true))
Expected: is pair (is >= 48, true) Expected: is pair (first: is >= 48, second: true)
Actual: (42, true) (of type std::pair<int, bool>) Actual: (42, true) (of type std::pair<int, bool>)
[ FAILED ] GMockOutputTest.PrintsMatcher [ FAILED ] GMockOutputTest.PrintsMatcher
[ FAILED ] GMockOutputTest.UnexpectedCall [ FAILED ] GMockOutputTest.UnexpectedCall
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests that Google Mock constructs can be used in a large number of // Tests that Google Mock constructs can be used in a large number of
// threads concurrently. // threads concurrently.
...@@ -49,7 +48,7 @@ const int kRepeat = 50; ...@@ -49,7 +48,7 @@ const int kRepeat = 50;
class MockFoo { class MockFoo {
public: public:
MOCK_METHOD1(Bar, int(int n)); // NOLINT MOCK_METHOD1(Bar, int(int n)); // NOLINT
MOCK_METHOD2(Baz, char(const char* s1, const std::string& s2)); // NOLINT MOCK_METHOD2(Baz, char(const char* s1, const std::string& s2)); // NOLINT
}; };
...@@ -62,21 +61,16 @@ void JoinAndDelete(ThreadWithParam<T>* t) { ...@@ -62,21 +61,16 @@ void JoinAndDelete(ThreadWithParam<T>* t) {
struct Dummy {}; struct Dummy {};
// Tests that different mock objects can be used in their respective // Tests that different mock objects can be used in their respective
// threads. This should generate no Google Test failure. // threads. This should generate no Google Test failure.
void TestConcurrentMockObjects(Dummy /* dummy */) { void TestConcurrentMockObjects(Dummy /* dummy */) {
// Creates a mock and does some typical operations on it. // Creates a mock and does some typical operations on it.
MockFoo foo; MockFoo foo;
ON_CALL(foo, Bar(_)) ON_CALL(foo, Bar(_)).WillByDefault(Return(1));
.WillByDefault(Return(1)); ON_CALL(foo, Baz(_, _)).WillByDefault(Return('b'));
ON_CALL(foo, Baz(_, _)) ON_CALL(foo, Baz(_, "you")).WillByDefault(Return('a'));
.WillByDefault(Return('b'));
ON_CALL(foo, Baz(_, "you")) EXPECT_CALL(foo, Bar(0)).Times(AtMost(3));
.WillByDefault(Return('a'));
EXPECT_CALL(foo, Bar(0))
.Times(AtMost(3));
EXPECT_CALL(foo, Baz(_, _)); EXPECT_CALL(foo, Baz(_, _));
EXPECT_CALL(foo, Baz("hi", "you")) EXPECT_CALL(foo, Baz("hi", "you"))
.WillOnce(Return('z')) .WillOnce(Return('z'))
...@@ -119,22 +113,19 @@ void Helper1(Helper1Param param) { ...@@ -119,22 +113,19 @@ void Helper1(Helper1Param param) {
void TestConcurrentCallsOnSameObject(Dummy /* dummy */) { void TestConcurrentCallsOnSameObject(Dummy /* dummy */) {
MockFoo foo; MockFoo foo;
ON_CALL(foo, Bar(_)) ON_CALL(foo, Bar(_)).WillByDefault(Return(1));
.WillByDefault(Return(1)); EXPECT_CALL(foo, Baz(_, "b")).Times(kRepeat).WillRepeatedly(Return('a'));
EXPECT_CALL(foo, Baz(_, "b"))
.Times(kRepeat)
.WillRepeatedly(Return('a'));
EXPECT_CALL(foo, Baz(_, "c")); // Expected to be unsatisfied. EXPECT_CALL(foo, Baz(_, "c")); // Expected to be unsatisfied.
// This chunk of code should generate kRepeat failures about // This chunk of code should generate kRepeat failures about
// excessive calls, and 2*kRepeat failures about unexpected calls. // excessive calls, and 2*kRepeat failures about unexpected calls.
int count1 = 0; int count1 = 0;
const Helper1Param param = { &foo, &count1 }; const Helper1Param param = {&foo, &count1};
ThreadWithParam<Helper1Param>* const t = ThreadWithParam<Helper1Param>* const t =
new ThreadWithParam<Helper1Param>(Helper1, param, nullptr); new ThreadWithParam<Helper1Param>(Helper1, param, nullptr);
int count2 = 0; int count2 = 0;
const Helper1Param param2 = { &foo, &count2 }; const Helper1Param param2 = {&foo, &count2};
Helper1(param2); Helper1(param2);
JoinAndDelete(t); JoinAndDelete(t);
...@@ -162,22 +153,18 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) { ...@@ -162,22 +153,18 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(foo, Bar(0)); EXPECT_CALL(foo, Bar(0));
EXPECT_CALL(foo, Bar(1)) EXPECT_CALL(foo, Bar(1)).InSequence(s1, s2);
.InSequence(s1, s2);
} }
EXPECT_CALL(foo, Bar(2)) EXPECT_CALL(foo, Bar(2))
.Times(2*kRepeat) .Times(2 * kRepeat)
.InSequence(s1) .InSequence(s1)
.RetiresOnSaturation(); .RetiresOnSaturation();
EXPECT_CALL(foo, Bar(3)) EXPECT_CALL(foo, Bar(3)).Times(2 * kRepeat).InSequence(s2);
.Times(2*kRepeat)
.InSequence(s2);
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(foo, Bar(2)) EXPECT_CALL(foo, Bar(2)).InSequence(s1, s2);
.InSequence(s1, s2);
EXPECT_CALL(foo, Bar(4)); EXPECT_CALL(foo, Bar(4));
} }
...@@ -196,12 +183,12 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) { ...@@ -196,12 +183,12 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
// Tests using Google Mock constructs in many threads concurrently. // Tests using Google Mock constructs in many threads concurrently.
TEST(StressTest, CanUseGMockWithThreads) { TEST(StressTest, CanUseGMockWithThreads) {
void (*test_routines[])(Dummy dummy) = { void (*test_routines[])(Dummy dummy) = {
&TestConcurrentMockObjects, &TestConcurrentMockObjects,
&TestConcurrentCallsOnSameObject, &TestConcurrentCallsOnSameObject,
&TestPartiallyOrderedExpectationsWithThreads, &TestPartiallyOrderedExpectationsWithThreads,
}; };
const int kRoutines = sizeof(test_routines)/sizeof(test_routines[0]); const int kRoutines = sizeof(test_routines) / sizeof(test_routines[0]);
const int kCopiesOfEachRoutine = kMaxTestThreads / kRoutines; const int kCopiesOfEachRoutine = kMaxTestThreads / kRoutines;
const int kTestThreads = kCopiesOfEachRoutine * kRoutines; const int kTestThreads = kCopiesOfEachRoutine * kRoutines;
ThreadWithParam<Dummy>* threads[kTestThreads] = {}; ThreadWithParam<Dummy>* threads[kTestThreads] = {};
...@@ -220,7 +207,7 @@ TEST(StressTest, CanUseGMockWithThreads) { ...@@ -220,7 +207,7 @@ TEST(StressTest, CanUseGMockWithThreads) {
// Ensures that the correct number of failures have been reported. // Ensures that the correct number of failures have been reported.
const TestInfo* const info = UnitTest::GetInstance()->current_test_info(); const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
const TestResult& result = *info->result(); const TestResult& result = *info->result();
const int kExpectedFailures = (3*kRepeat + 1)*kCopiesOfEachRoutine; const int kExpectedFailures = (3 * kRepeat + 1) * kCopiesOfEachRoutine;
GTEST_CHECK_(kExpectedFailures == result.total_part_count()) GTEST_CHECK_(kExpectedFailures == result.total_part_count())
<< "Expected " << kExpectedFailures << " failures, but got " << "Expected " << kExpectedFailures << " failures, but got "
<< result.total_part_count(); << result.total_part_count();
...@@ -229,7 +216,7 @@ TEST(StressTest, CanUseGMockWithThreads) { ...@@ -229,7 +216,7 @@ TEST(StressTest, CanUseGMockWithThreads) {
} // namespace } // namespace
} // namespace testing } // namespace testing
int main(int argc, char **argv) { int main(int argc, char** argv) {
testing::InitGoogleMock(&argc, argv); testing::InitGoogleMock(&argc, argv);
const int exit_code = RUN_ALL_TESTS(); // Expected to fail. const int exit_code = RUN_ALL_TESTS(); // Expected to fail.
......
...@@ -27,7 +27,6 @@ ...@@ -27,7 +27,6 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests code in gmock.cc. // This file tests code in gmock.cc.
...@@ -35,13 +34,12 @@ ...@@ -35,13 +34,12 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include <string> #include <string>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/custom/gtest.h" #include "gtest/internal/custom/gtest.h"
#if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) #if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
using testing::GMOCK_FLAG(default_mock_behavior);
using testing::GMOCK_FLAG(verbose);
using testing::InitGoogleMock; using testing::InitGoogleMock;
// Verifies that calling InitGoogleMock() on argv results in new_argv, // Verifies that calling InitGoogleMock() on argv results in new_argv,
...@@ -49,7 +47,7 @@ using testing::InitGoogleMock; ...@@ -49,7 +47,7 @@ using testing::InitGoogleMock;
template <typename Char, int M, int N> template <typename Char, int M, int N>
void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
const ::std::string& expected_gmock_verbose) { const ::std::string& expected_gmock_verbose) {
const ::std::string old_verbose = GMOCK_FLAG(verbose); const ::std::string old_verbose = GMOCK_FLAG_GET(verbose);
int argc = M - 1; int argc = M - 1;
InitGoogleMock(&argc, const_cast<Char**>(argv)); InitGoogleMock(&argc, const_cast<Char**>(argv));
...@@ -59,8 +57,8 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], ...@@ -59,8 +57,8 @@ void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],
EXPECT_STREQ(new_argv[i], argv[i]); EXPECT_STREQ(new_argv[i], argv[i]);
} }
EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG(verbose).c_str()); EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG_GET(verbose));
GMOCK_FLAG(verbose) = old_verbose; // Restores the gmock_verbose flag. GMOCK_FLAG_SET(verbose, old_verbose); // Restores the gmock_verbose flag.
} }
TEST(InitGoogleMockTest, ParsesInvalidCommandLine) { TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
...@@ -68,7 +66,7 @@ TEST(InitGoogleMockTest, ParsesInvalidCommandLine) { ...@@ -68,7 +66,7 @@ TEST(InitGoogleMockTest, ParsesInvalidCommandLine) {
const char* new_argv[] = {nullptr}; const char* new_argv[] = {nullptr};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
} }
TEST(InitGoogleMockTest, ParsesEmptyCommandLine) { TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
...@@ -76,7 +74,7 @@ TEST(InitGoogleMockTest, ParsesEmptyCommandLine) { ...@@ -76,7 +74,7 @@ TEST(InitGoogleMockTest, ParsesEmptyCommandLine) {
const char* new_argv[] = {"foo.exe", nullptr}; const char* new_argv[] = {"foo.exe", nullptr};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
} }
TEST(InitGoogleMockTest, ParsesSingleFlag) { TEST(InitGoogleMockTest, ParsesSingleFlag) {
...@@ -88,16 +86,16 @@ TEST(InitGoogleMockTest, ParsesSingleFlag) { ...@@ -88,16 +86,16 @@ TEST(InitGoogleMockTest, ParsesSingleFlag) {
} }
TEST(InitGoogleMockTest, ParsesMultipleFlags) { TEST(InitGoogleMockTest, ParsesMultipleFlags) {
int old_default_behavior = GMOCK_FLAG(default_mock_behavior); int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior);
const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info",
L"--gmock_default_mock_behavior=2", nullptr}; L"--gmock_default_mock_behavior=2", nullptr};
const wchar_t* new_argv[] = {L"foo.exe", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr};
TestInitGoogleMock(argv, new_argv, "info"); TestInitGoogleMock(argv, new_argv, "info");
EXPECT_EQ(2, GMOCK_FLAG(default_mock_behavior)); EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior));
EXPECT_NE(2, old_default_behavior); EXPECT_NE(2, old_default_behavior);
GMOCK_FLAG(default_mock_behavior) = old_default_behavior; GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior);
} }
TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) { TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
...@@ -105,7 +103,7 @@ TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) { ...@@ -105,7 +103,7 @@ TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {
const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
} }
TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
...@@ -122,7 +120,7 @@ TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) { ...@@ -122,7 +120,7 @@ TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) {
const wchar_t* new_argv[] = {nullptr}; const wchar_t* new_argv[] = {nullptr};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
} }
TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) { TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
...@@ -130,7 +128,7 @@ TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) { ...@@ -130,7 +128,7 @@ TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {
const wchar_t* new_argv[] = {L"foo.exe", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
} }
TEST(WideInitGoogleMockTest, ParsesSingleFlag) { TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
...@@ -142,16 +140,16 @@ TEST(WideInitGoogleMockTest, ParsesSingleFlag) { ...@@ -142,16 +140,16 @@ TEST(WideInitGoogleMockTest, ParsesSingleFlag) {
} }
TEST(WideInitGoogleMockTest, ParsesMultipleFlags) { TEST(WideInitGoogleMockTest, ParsesMultipleFlags) {
int old_default_behavior = GMOCK_FLAG(default_mock_behavior); int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior);
const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info",
L"--gmock_default_mock_behavior=2", nullptr}; L"--gmock_default_mock_behavior=2", nullptr};
const wchar_t* new_argv[] = {L"foo.exe", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr};
TestInitGoogleMock(argv, new_argv, "info"); TestInitGoogleMock(argv, new_argv, "info");
EXPECT_EQ(2, GMOCK_FLAG(default_mock_behavior)); EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior));
EXPECT_NE(2, old_default_behavior); EXPECT_NE(2, old_default_behavior);
GMOCK_FLAG(default_mock_behavior) = old_default_behavior; GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior);
} }
TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) { TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
...@@ -159,7 +157,7 @@ TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) { ...@@ -159,7 +157,7 @@ TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {
const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr};
TestInitGoogleMock(argv, new_argv, GMOCK_FLAG(verbose)); TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));
} }
TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
...@@ -175,7 +173,7 @@ TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { ...@@ -175,7 +173,7 @@ TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {
// Makes sure Google Mock flags can be accessed in code. // Makes sure Google Mock flags can be accessed in code.
TEST(FlagTest, IsAccessibleInCode) { TEST(FlagTest, IsAccessibleInCode) {
bool dummy = testing::GMOCK_FLAG(catch_leaked_mocks) && bool dummy =
testing::GMOCK_FLAG(verbose) == ""; GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose) == "";
(void)dummy; // Avoids the "unused local variable" warning. (void)dummy; // Avoids the "unused local variable" warning.
} }
...@@ -30,21 +30,9 @@ ...@@ -30,21 +30,9 @@
"""Unit test utilities for Google C++ Mocking Framework.""" """Unit test utilities for Google C++ Mocking Framework."""
import os import os
import sys
# Determines path to gtest_test_utils and imports it.
SCRIPT_DIR = os.path.dirname(__file__) or '.'
# isdir resolves symbolic links.
gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../../googletest/test')
if os.path.isdir(gtest_tests_util_dir):
GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir
else:
GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../googletest/test')
sys.path.append(GTEST_TESTS_UTIL_DIR)
# pylint: disable=C6204 # pylint: disable=C6204
import gtest_test_utils from googletest.test import gtest_test_utils
def GetSourceDir(): def GetSourceDir():
......
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment