Compare commits

..

No commits in common. "main" and "v1.12.0" have entirely different histories.

174 changed files with 5886 additions and 10405 deletions

43
.github/ISSUE_TEMPLATE/00-bug_report.md vendored Normal file
View File

@ -0,0 +1,43 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'bug'
assignees: ''
---
**Describe the bug**
Include a clear and concise description of what the problem is, including what
you expected to happen, and what actually happened.
**Steps to reproduce the bug**
It's important that we are able to reproduce the problem that you are
experiencing. Please provide all code and relevant steps to reproduce the
problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links
to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the
problem are also helpful.
**Does the bug persist in the most recent commit?**
We recommend using the latest commit in the master branch in your projects.
**What operating system and version are you using?**
If you are using a Linux distribution please include the name and version of the
distribution as well.
**What compiler and version are you using?**
Please include the output of `gcc -v` or `clang -v`, or the equivalent for your
compiler.
**What build system are you using?**
Please include the output of `bazel --version` or `cmake --version`, or the
equivalent for your build system.
**Additional context**
Add any other context about the problem here.

View File

@ -1,53 +0,0 @@
name: Bug Report
description: Let us know that something does not work as expected.
title: "[Bug]: Please title this bug report"
body:
- type: textarea
id: what-happened
attributes:
label: Describe the issue
description: What happened, and what did you expect to happen?
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce the problem
description: It is important that we are able to reproduce the problem that you are experiencing. Please provide all code and relevant steps to reproduce the problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the problem are also helpful.
validations:
required: true
- type: textarea
id: version
attributes:
label: What version of GoogleTest are you using?
description: Please include the output of `git rev-parse HEAD` or the GoogleTest release version number that you are using.
validations:
required: true
- type: textarea
id: os
attributes:
label: What operating system and version are you using?
description: If you are using a Linux distribution please include the name and version of the distribution as well.
validations:
required: true
- type: textarea
id: compiler
attributes:
label: What compiler and version are you using?
description: Please include the output of `gcc -v` or `clang -v`, or the equivalent for your compiler.
validations:
required: true
- type: textarea
id: buildsystem
attributes:
label: What build system are you using?
description: Please include the output of `bazel --version` or `cmake --version`, or the equivalent for your build system.
validations:
required: true
- type: textarea
id: additional
attributes:
label: Additional context
description: Add any other context about the problem here.
validations:
required: false

View File

@ -0,0 +1,24 @@
---
name: Feature request
about: Propose a new feature
title: ''
labels: 'enhancement'
assignees: ''
---
**Does the feature exist in the most recent commit?**
We recommend using the latest commit from GitHub in your projects.
**Why do we need this feature?**
Ideally, explain why a combination of existing features cannot be used instead.
**Describe the proposal**
Include a detailed description of the feature, with usage examples.
**Is the feature specific to an operating system, compiler, or build system version?**
If it is, please specify which versions.

View File

@ -1,33 +0,0 @@
name: Feature request
description: Propose a new feature.
title: "[FR]: Please title this feature request"
labels: "enhancement"
body:
- type: textarea
id: version
attributes:
label: Does the feature exist in the most recent commit?
description: We recommend using the latest commit from GitHub in your projects.
validations:
required: true
- type: textarea
id: why
attributes:
label: Why do we need this feature?
description: Ideally, explain why a combination of existing features cannot be used instead.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Describe the proposal.
description: Include a detailed description of the feature, with usage examples.
validations:
required: true
- type: textarea
id: platform
attributes:
label: Is the feature specific to an operating system, compiler, or build system version?
description: If it is, please specify which versions.
validations:
required: true

View File

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

40
.github/workflows/gtest-ci.yml vendored Normal file
View File

@ -0,0 +1,40 @@
name: ci
on:
push:
pull_request:
jobs:
Linux:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Tests
run: bazel test --test_output=errors //...
MacOs:
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Tests
run: bazel test --test_output=errors //...
Windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Tests
run: bazel test --test_output=errors //...

5
.gitignore vendored
View File

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

View File

@ -30,8 +30,6 @@
#
# Bazel Build for Google C++ Testing Framework(Google Test)
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
@ -58,12 +56,6 @@ config_setting(
constraint_values = ["@platforms//os:openbsd"],
)
# NOTE: Fuchsia is not an officially supported platform.
config_setting(
name = "fuchsia",
constraint_values = ["@platforms//os:fuchsia"],
)
config_setting(
name = "msvc_compiler",
flag_values = {
@ -85,10 +77,6 @@ cc_library(
)
# Google Test including Google Mock
# For an actual test, use `gtest` and also `gtest_main` if you depend on gtest's
# main(). For a library, use `gtest_for_library` instead if the library can be
# testonly.
cc_library(
name = "gtest",
srcs = glob(
@ -144,41 +132,23 @@ cc_library(
}),
deps = select({
":has_absl": [
"@abseil-cpp//absl/container:flat_hash_set",
"@abseil-cpp//absl/debugging:failure_signal_handler",
"@abseil-cpp//absl/debugging:stacktrace",
"@abseil-cpp//absl/debugging:symbolize",
"@abseil-cpp//absl/flags:flag",
"@abseil-cpp//absl/flags:parse",
"@abseil-cpp//absl/flags:reflection",
"@abseil-cpp//absl/flags:usage",
"@abseil-cpp//absl/strings",
"@re2",
],
"//conditions:default": [],
}) + select({
# `gtest-death-test.cc` has `EXPECT_DEATH` that spawns a process,
# expects it to crash and inspects its logs with the given matcher,
# so that's why these libraries are needed.
# Otherwise, builds targeting Fuchsia would fail to compile.
":fuchsia": [
"@fuchsia_sdk//pkg/fdio",
"@fuchsia_sdk//pkg/zx",
"@com_google_absl//absl/debugging:failure_signal_handler",
"@com_google_absl//absl/debugging:stacktrace",
"@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/types:any",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:variant",
"@com_googlesource_code_re2//:re2",
],
"//conditions:default": [],
}),
)
# `gtest`, but testonly. See guidance on `gtest` for when to use this.
alias(
name = "gtest_for_library",
testonly = True,
actual = ":gtest",
)
# Implements main() for tests using gtest. Prefer to depend on `gtest` as well
# to ensure compliance with the layering_check Bazel feature where only the
# direct hdrs values are available.
cc_library(
name = "gtest_main",
srcs = ["googlemock/src/gmock_main.cc"],

View File

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

View File

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

View File

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

View File

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

111
README.md
View File

@ -2,28 +2,29 @@
### Announcements
#### Live at Head
GoogleTest now follows the
[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
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
Our documentation is now live on GitHub Pages at
https://google.github.io/googletest/. We recommend browsing the documentation on
GitHub Pages rather than directly in the repository.
#### Release 1.17.0
#### Release 1.11.0
[Release 1.17.0](https://github.com/google/googletest/releases/tag/v1.17.0) is
now available.
The 1.17.x branch
[requires at least C++17](https://opensource.google/documentation/policies/cplusplus-support#c_language_standard).
#### Continuous Integration
We use Google's internal systems for continuous integration.
[Release 1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0)
is now available.
#### Coming Soon
* We are planning to take a dependency on
[Abseil](https://github.com/abseil/abseil-cpp).
* More documentation improvements are planned.
## Welcome to **GoogleTest**, Google's C++ test framework!
@ -42,58 +43,64 @@ More information about building GoogleTest can be found at
## Features
* xUnit test framework: \
Googletest is based on the [xUnit](https://en.wikipedia.org/wiki/XUnit)
testing framework, a popular architecture for unit testing
* Test discovery: \
Googletest automatically discovers and runs your tests, eliminating the need
to manually register your tests
* Rich set of assertions: \
Googletest provides a variety of assertions, such as equality, inequality,
exceptions, and more, making it easy to test your code
* User-defined assertions: \
You can define your own assertions with Googletest, making it simple to
write tests that are specific to your code
* Death tests: \
Googletest supports death tests, which verify that your code exits in a
certain way, making it useful for testing error-handling code
* Fatal and non-fatal failures: \
You can specify whether a test failure should be treated as fatal or
non-fatal with Googletest, allowing tests to continue running even if a
failure occurs
* Value-parameterized tests: \
Googletest supports value-parameterized tests, which run multiple times with
different input values, making it useful for testing functions that take
different inputs
* Type-parameterized tests: \
Googletest also supports type-parameterized tests, which run with different
data types, making it useful for testing functions that work with different
data types
* Various options for running tests: \
Googletest provides many options for running tests including running
individual tests, running tests in a specific order and running tests in
parallel
* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework.
* Test discovery.
* A rich set of assertions.
* User-defined assertions.
* Death tests.
* Fatal and non-fatal failures.
* Value-parameterized tests.
* Type-parameterized tests.
* Various options for running the tests.
* XML test report generation.
## Supported Platforms
GoogleTest follows Google's
[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See
[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
for a list of currently supported versions of compilers, platforms, and build
tools.
GoogleTest requires a codebase and compiler compliant with the C++11 standard or
newer.
The GoogleTest code is officially supported on the following platforms.
Operating systems or tools not listed below are community-supported. For
community-supported platforms, patches that do not complicate the code may be
considered.
If you notice any problems on your platform, please file an issue on the
[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
Pull requests containing fixes are welcome!
### Operating Systems
* Linux
* macOS
* Windows
### Compilers
* gcc 5.0+
* clang 5.0+
* MSVC 2015+
**macOS users:** Xcode 9.3+ provides clang 5.0+.
### Build Systems
* [Bazel](https://bazel.build/)
* [CMake](https://cmake.org/)
**Note:** Bazel is the build system used by the team internally and in tests.
CMake is supported on a best-effort basis and by the community.
## Who Is Using GoogleTest?
In addition to many internal projects at Google, GoogleTest is also used by the
following notable projects:
* The [Chromium projects](https://www.chromium.org/) (behind the Chrome
browser and Chrome OS).
* The [LLVM](https://llvm.org/) compiler.
* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser
and Chrome OS).
* The [LLVM](http://llvm.org/) compiler.
* [Protocol Buffers](https://github.com/google/protobuf), Google's data
interchange format.
* The [OpenCV](https://opencv.org/) computer vision library.
* The [OpenCV](http://opencv.org/) computer vision library.
## Related Open Source Projects
@ -128,7 +135,7 @@ that generates stub code for GoogleTest.
## Contributing Changes
Please read
[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/main/CONTRIBUTING.md)
[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/master/CONTRIBUTING.md)
for details on how to contribute to this project.
Happy testing!

View File

@ -1,61 +1,39 @@
# Copyright 2024 Google Inc.
# All Rights Reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
workspace(name = "googletest")
load("//:googletest_deps.bzl", "googletest_deps")
googletest_deps()
workspace(name = "com_google_googletest")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rules_python",
sha256 = "2cc26bbd53854ceb76dd42a834b1002cd4ba7f8df35440cf03482e045affc244",
strip_prefix = "rules_python-1.3.0",
url = "https://github.com/bazelbuild/rules_python/releases/download/1.3.0/rules_python-1.3.0.tar.gz",
name = "com_google_absl",
sha256 = "1a1745b5ee81392f5ea4371a4ca41e55d446eeaee122903b2eaffbd8a3b67a2b",
strip_prefix = "abseil-cpp-01cc6567cff77738e416a7ddc17de2d435a780ce",
urls = ["https://github.com/abseil/abseil-cpp/archive/01cc6567cff77738e416a7ddc17de2d435a780ce.zip"], # 2022-06-21T19:28:27Z
)
# 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",
sha256 = "0a890c2aa0bb05b2ce906a15efb520d0f5ad4c7d37b8db959c43772802991887",
strip_prefix = "re2-a427f10b9fb4622dd6d8643032600aa1b50fbd12",
urls = ["https://github.com/google/re2/archive/a427f10b9fb4622dd6d8643032600aa1b50fbd12.zip"], # 2022-06-09
)
http_archive(
name = "rules_python",
sha256 = "0b460f17771258341528753b1679335b629d1d25e3af28eda47d009c103a6e15",
strip_prefix = "rules_python-aef17ad72919d184e5edb7abf61509eb78e57eda",
urls = ["https://github.com/bazelbuild/rules_python/archive/aef17ad72919d184e5edb7abf61509eb78e57eda.zip"], # 2022-06-21T23:44:47Z
)
http_archive(
name = "bazel_skylib",
urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz"],
sha256 = "f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728",
)
# https://github.com/bazelbuild/rules_python/releases/tag/1.1.0
load("@rules_python//python:repositories.bzl", "py_repositories")
py_repositories()
http_archive(
name = "platforms",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.11/platforms-0.0.11.tar.gz",
"https://github.com/bazelbuild/platforms/releases/download/0.0.11/platforms-0.0.11.tar.gz",
],
sha256 = "29742e87275809b5e598dc2f04d86960cc7a55b3067d97221c9abbc9926bff0f",
sha256 = "a879ea428c6d56ab0ec18224f976515948822451473a80d06c2e50af0bbe5121",
strip_prefix = "platforms-da5541f26b7de1dc8e04c075c99df5351742a4a2",
urls = ["https://github.com/bazelbuild/platforms/archive/da5541f26b7de1dc8e04c075c99df5351742a4a2.zip"], # 2022-05-27
)
load("@bazel_features//:deps.bzl", "bazel_features_deps")
bazel_features_deps()
load("@rules_cc//cc:extensions.bzl", "compatibility_proxy_repo")
compatibility_proxy_repo()

View File

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

View File

@ -31,67 +31,39 @@
set -euox pipefail
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20250430"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20250430"
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:20220621"
if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi
# Use Bazel Vendor mode to reduce reliance on external dependencies.
# See https://bazel.build/external/vendor and the Dockerfile for
# an explaination of how this works.
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" ]]; then
DOCKER_EXTRA_ARGS="--mount type=bind,source=${KOKORO_GFILE_DIR}/distdir,target=/distdir,readonly --env=BAZEL_VENDOR_ARCHIVE=/distdir/googletest_vendor.tar.gz ${DOCKER_EXTRA_ARGS:-}"
BAZEL_EXTRA_ARGS="--vendor_dir=/googletest_vendor ${BAZEL_EXTRA_ARGS:-}"
fi
if [[ -z ${STD:-} ]]; then
STD="c++17 c++20 c++23"
STD="c++11 c++14 c++17 c++20"
fi
# Test CMake + GCC
for cmake_off_on in OFF ON; do
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--tmpfs="/build:exec" \
--workdir="/build" \
--rm \
--env="CC=/usr/local/bin/gcc" \
--env=CXXFLAGS="-Werror -Wdeprecated" \
${LINUX_LATEST_CONTAINER} \
/bin/bash -c "
cmake /src \
-DCMAKE_CXX_STANDARD=17 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on} && \
make -j$(nproc) && \
ctest -j$(nproc) --output-on-failure"
done
# Test CMake + Clang
for cmake_off_on in OFF ON; do
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--tmpfs="/build:exec" \
--workdir="/build" \
--rm \
--env="CC=/opt/llvm/clang/bin/clang" \
--env=CXXFLAGS="-Werror -Wdeprecated --gcc-toolchain=/usr/local" \
${LINUX_LATEST_CONTAINER} \
/bin/bash -c "
cmake /src \
-DCMAKE_CXX_STANDARD=17 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on} && \
make -j$(nproc) && \
ctest -j$(nproc) --output-on-failure"
# Test the CMake build
for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
for cmake_off_on in OFF ON; do
time docker run \
--volume="${GTEST_ROOT}:/src:ro" \
--tmpfs="/build:exec" \
--workdir="/build" \
--rm \
--env="CC=${cc}" \
--env="CXX_FLAGS=\"-Werror -Wdeprecated\"" \
${LINUX_LATEST_CONTAINER} \
/bin/bash -c "
cmake /src \
-DCMAKE_CXX_STANDARD=11 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on} && \
make -j$(nproc) && \
ctest -j$(nproc) --output-on-failure"
done
done
# Do one test with an older version of GCC
@ -100,22 +72,16 @@ time docker run \
--workdir="/src" \
--rm \
--env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=c++17" \
${DOCKER_EXTRA_ARGS:-} \
${LINUX_GCC_FLOOR_CONTAINER} \
/bin/bash --login -c "
/usr/local/bin/bazel test ... \
--copt=\"-Wall\" \
--copt=\"-Werror\" \
--copt=\"-Wuninitialized\" \
--copt=\"-Wundef\" \
--copt=\"-Wno-error=pragmas\" \
--enable_bzlmod=false \
--features=external_include_paths \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wno-error=pragmas" \
--distdir="/bazel-distdir" \
--keep_going \
--show_timestamps \
--test_output=errors \
${BAZEL_EXTRA_ARGS:-}"
--test_output=errors
# Test GCC
for std in ${STD}; do
@ -126,21 +92,16 @@ for std in ${STD}; do
--rm \
--env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=${std}" \
${DOCKER_EXTRA_ARGS:-} \
${LINUX_LATEST_CONTAINER} \
/bin/bash --login -c "
/usr/local/bin/bazel test ... \
--copt=\"-Wall\" \
--copt=\"-Werror\" \
--copt=\"-Wuninitialized\" \
--copt=\"-Wundef\" \
--define=\"absl=${absl}\" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors \
${BAZEL_EXTRA_ARGS:-}"
/usr/local/bin/bazel test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--define="absl=${absl}" \
--distdir="/bazel-distdir" \
--keep_going \
--show_timestamps \
--test_output=errors
done
done
@ -153,22 +114,17 @@ for std in ${STD}; do
--rm \
--env="CC=/opt/llvm/clang/bin/clang" \
--env="BAZEL_CXXOPTS=-std=${std}" \
${DOCKER_EXTRA_ARGS:-} \
${LINUX_LATEST_CONTAINER} \
/bin/bash --login -c "
/usr/local/bin/bazel test ... \
--copt=\"--gcc-toolchain=/usr/local\" \
--copt=\"-Wall\" \
--copt=\"-Werror\" \
--copt=\"-Wuninitialized\" \
--copt=\"-Wundef\" \
--define=\"absl=${absl}\" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--linkopt=\"--gcc-toolchain=/usr/local\" \
--show_timestamps \
--test_output=errors \
${BAZEL_EXTRA_ARGS:-}"
/usr/local/bin/bazel test ... \
--copt="--gcc-toolchain=/usr/local" \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--define="absl=${absl}" \
--distdir="/bazel-distdir" \
--keep_going \
--linkopt="--gcc-toolchain=/usr/local" \
--show_timestamps \
--test_output=errors
done
done

View File

@ -31,9 +31,6 @@
set -euox pipefail
# Use Xcode 16.0
sudo xcode-select -s /Applications/Xcode_16.0.app/Contents/Developer
if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi
@ -43,20 +40,20 @@ for cmake_off_on in OFF ON; do
BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)
cd ${BUILD_DIR}
time cmake ${GTEST_ROOT} \
-DCMAKE_CXX_STANDARD=17 \
-DCMAKE_CXX_STANDARD=11 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
-Dcxx_no_exception=${cmake_off_on} \
-Dcxx_no_rtti=${cmake_off_on}
time make -j$(nproc)
time make
time ctest -j$(nproc) --output-on-failure
done
# Test the Bazel build
# If we are running on Kokoro, check for a versioned Bazel binary.
KOKORO_GFILE_BAZEL_BIN="bazel-8.2.1-darwin-x86_64"
KOKORO_GFILE_BAZEL_BIN="bazel-3.7.0-darwin-x86_64"
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then
BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}"
chmod +x ${BAZEL_BIN}
@ -64,24 +61,13 @@ else
BAZEL_BIN="bazel"
fi
# Use Bazel Vendor mode to reduce reliance on external dependencies.
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" ]]; then
tar -xf "${KOKORO_GFILE_DIR}/distdir/googletest_vendor.tar.gz" -C "${HOME}/"
BAZEL_EXTRA_ARGS="--vendor_dir=${HOME}/googletest_vendor ${BAZEL_EXTRA_ARGS:-}"
fi
cd ${GTEST_ROOT}
for absl in 0 1; do
${BAZEL_BIN} test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wundef" \
--cxxopt="-std=c++17" \
--define="absl=${absl}" \
--enable_bzlmod=true \
--features=external_include_paths \
--keep_going \
--show_timestamps \
--test_output=errors \
${BAZEL_EXTRA_ARGS:-}
--test_output=errors
done

View File

@ -1,85 +0,0 @@
SETLOCAL ENABLEDELAYEDEXPANSION
SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-8.2.1-windows-x86_64.exe
SET PATH=C:\Python34;%PATH%
SET BAZEL_PYTHON=C:\python34\python.exe
SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe
SET CMAKE_BIN="cmake.exe"
SET CTEST_BIN="ctest.exe"
SET CTEST_OUTPUT_ON_FAILURE=1
SET CMAKE_BUILD_PARALLEL_LEVEL=16
SET CTEST_PARALLEL_LEVEL=16
SET GTEST_ROOT=%~dp0\..
IF %errorlevel% neq 0 EXIT /B 1
:: ----------------------------------------------------------------------------
:: CMake
SET CMAKE_BUILD_PATH=cmake_msvc2022
MKDIR %CMAKE_BUILD_PATH%
CD %CMAKE_BUILD_PATH%
%CMAKE_BIN% %GTEST_ROOT% ^
-G "Visual Studio 17 2022" ^
-DCMAKE_CXX_STANDARD=17 ^
-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 %GTEST_ROOT%
RMDIR /S /Q %CMAKE_BUILD_PATH%
:: ----------------------------------------------------------------------------
:: Bazel
:: The default home directory on Kokoro is a long path which causes errors
:: because of Windows limitations on path length.
:: --output_user_root=C:\tmp causes Bazel to use a shorter path.
SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community
:: Use Bazel Vendor mode to reduce reliance on external dependencies.
IF EXIST "%KOKORO_GFILE_DIR%\distdir\googletest_vendor.tar.gz" (
tar --force-local -xf "%KOKORO_GFILE_DIR%\distdir\googletest_vendor.tar.gz" -C c:
SET VENDOR_FLAG=--vendor_dir=c:\googletest_vendor
) ELSE (
SET VENDOR_FLAG=
)
:: C++17
%BAZEL_EXE% ^
--output_user_root=C:\tmp ^
test ... ^
--compilation_mode=dbg ^
--copt=/std:c++17 ^
--copt=/WX ^
--enable_bzlmod=true ^
--keep_going ^
--test_output=errors ^
--test_tag_filters=-no_test_msvc2017 ^
%VENDOR_FLAG%
IF %errorlevel% neq 0 EXIT /B 1
:: C++20
%BAZEL_EXE% ^
--output_user_root=C:\tmp ^
test ... ^
--compilation_mode=dbg ^
--copt=/std:c++20 ^
--copt=/WX ^
--enable_bzlmod=true ^
--keep_going ^
--test_output=errors ^
--test_tag_filters=-no_test_msvc2017 ^
%VENDOR_FLAG%
IF %errorlevel% neq 0 EXIT /B 1

View File

@ -7,15 +7,15 @@
{% seo %}
<link rel="stylesheet" href="{{ "/assets/css/style.css?v=" | append: site.github.build_revision | relative_url }}">
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-9PTP6FW1M5"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-9PTP6FW1M5');
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-197576187-1', { 'storage': 'none' });
ga('set', 'referrer', document.referrer.split('?')[0]);
ga('set', 'location', window.location.href.split('?')[0]);
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
</head>
<body>
<div class="sidebar">
@ -48,7 +48,7 @@
<div class="footer">
GoogleTest &middot;
<a href="https://github.com/google/googletest">GitHub Repository</a> &middot;
<a href="https://github.com/google/googletest/blob/main/LICENSE">License</a> &middot;
<a href="https://github.com/google/googletest/blob/master/LICENSE">License</a> &middot;
<a href="https://policies.google.com/privacy">Privacy Policy</a>
</div>
</div>

View File

@ -1,9 +1,9 @@
# Advanced GoogleTest Topics
# Advanced googletest Topics
## Introduction
Now that you have read the [GoogleTest Primer](primer.md) and learned how to
write tests using GoogleTest, it's time to learn some new tricks. This document
Now that you have read the [googletest Primer](primer.md) and learned how to
write tests using googletest, it's time to learn some new tricks. This document
will show you more assertions as well as how to construct complex failure
messages, propagate fatal failures, reuse and speed up your test fixtures, and
use various flags with your tests.
@ -25,7 +25,7 @@ Reference.
### Predicate Assertions for Better Error Messages
Even though GoogleTest has a rich set of assertions, they can never be complete,
Even though googletest has a rich set of assertions, they can never be complete,
as it's impossible (nor a good idea) to anticipate all scenarios a user might
run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a
complex expression, for lack of a better macro. This has the problem of not
@ -35,7 +35,7 @@ failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this
is awkward especially when the expression has side-effects or is expensive to
evaluate.
GoogleTest gives you three different options to solve this problem:
googletest gives you three different options to solve this problem:
#### Using an Existing Boolean Function
@ -286,7 +286,7 @@ For example:
```c++
TEST(SkipTest, DoesSkip) {
GTEST_SKIP() << "Skipping single test";
FAIL(); // Won't fail; it won't be executed
EXPECT_EQ(0, 1); // Won't fail; it won't be executed
}
class SkipFixture : public ::testing::Test {
@ -298,15 +298,15 @@ class SkipFixture : public ::testing::Test {
// Tests for SkipFixture won't be executed.
TEST_F(SkipFixture, SkipsOneTest) {
FAIL(); // Won't fail; it won't be executed
EXPECT_EQ(5, 7); // Won't fail
}
```
As with assertion macros, you can stream a custom message into `GTEST_SKIP()`.
## Teaching GoogleTest How to Print Your Values
## Teaching googletest How to Print Your Values
When a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument
When a test assertion such as `EXPECT_EQ` fails, googletest prints the argument
values to help you debug. It does this using a user-extensible value printer.
This printer knows how to print built-in C++ types, native arrays, STL
@ -315,143 +315,73 @@ prints the raw bytes in the value and hopes that you the user can figure it out.
As mentioned earlier, the printer is *extensible*. That means you can teach it
to do a better job at printing your particular type than to dump the bytes. To
do that, define an `AbslStringify()` overload as a `friend` function template
for your type:
```cpp
namespace foo {
class Point { // We want GoogleTest to be able to print instances of this.
...
// Provide a friend overload.
template <typename Sink>
friend void AbslStringify(Sink& sink, const Point& point) {
absl::Format(&sink, "(%d, %d)", point.x, point.y);
}
int x;
int y;
};
// If you can't declare the function in the class it's important that the
// AbslStringify overload is defined in the SAME namespace that defines Point.
// C++'s look-up rules rely on that.
enum class EnumWithStringify { kMany = 0, kChoices = 1 };
template <typename Sink>
void AbslStringify(Sink& sink, EnumWithStringify e) {
absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices");
}
} // namespace foo
```
{: .callout .note}
Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its
string. For more information about supported operations on `AbslStringify()`'s
sink, see
[the `AbslStringify()` documentation](https://abseil.io/docs/cpp/guides/abslstringify).
`AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier
within its own format strings to perform type deduction. `Point` above could be
formatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`.
Sometimes, `AbslStringify()` might not be an option: your team may wish to print
types with extra debugging information for testing purposes only. If so, you can
instead define a `PrintTo()` function like this:
do that, define `<<` for your type:
```c++
#include <ostream>
namespace foo {
class Point {
...
friend void PrintTo(const Point& point, std::ostream* os) {
*os << "(" << point.x << "," << point.y << ")";
class Bar { // We want googletest to be able to print instances of this.
...
// Create a free inline friend function.
friend std::ostream& operator<<(std::ostream& os, const Bar& bar) {
return os << bar.DebugString(); // whatever needed to print bar to os
}
int x;
int y;
};
// If you can't declare the function in the class it's important that PrintTo()
// is defined in the SAME namespace that defines Point. C++'s look-up rules
// rely on that.
void PrintTo(const Point& point, std::ostream* os) {
*os << "(" << point.x << "," << point.y << ")";
// If you can't declare the function in the class it's important that the
// << operator is defined in the SAME namespace that defines Bar. C++'s look-up
// rules rely on that.
std::ostream& operator<<(std::ostream& os, const Bar& bar) {
return os << bar.DebugString(); // whatever needed to print bar to os
}
} // namespace foo
```
If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be
used by GoogleTest. This allows you to customize how the value appears in
GoogleTest's output without affecting code that relies on the behavior of
`AbslStringify()`.
Sometimes, this might not be an option: your team may consider it bad style to
have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that
doesn't do what you want (and you cannot change it). If so, you can instead
define a `PrintTo()` function like this:
If you have an existing `<<` operator and would like to define an
`AbslStringify()`, the latter will be used for GoogleTest printing.
```c++
#include <ostream>
If you want to print a value `x` using GoogleTest's value printer yourself, just
namespace foo {
class Bar {
...
friend void PrintTo(const Bar& bar, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os
}
};
// If you can't declare the function in the class it's important that PrintTo()
// is defined in the SAME namespace that defines Bar. C++'s look-up rules rely
// on that.
void PrintTo(const Bar& bar, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os
}
} // namespace foo
```
If you have defined both `<<` and `PrintTo()`, the latter will be used when
googletest is concerned. This allows you to customize how the value appears in
googletest's output without affecting code that relies on the behavior of its
`<<` operator.
If you want to print a value `x` using googletest's value printer yourself, just
call `::testing::PrintToString(x)`, which returns an `std::string`:
```c++
vector<pair<Point, int> > point_ints = GetPointIntVector();
vector<pair<Bar, int> > bar_ints = GetBarIntVector();
EXPECT_TRUE(IsCorrectPointIntVector(point_ints))
<< "point_ints = " << testing::PrintToString(point_ints);
EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
<< "bar_ints = " << testing::PrintToString(bar_ints);
```
For more details regarding `AbslStringify()` and its integration with other
libraries, see
[the documentation](https://abseil.io/docs/cpp/guides/abslstringify).
## Regular Expression Syntax
When built with Bazel and using Abseil, GoogleTest uses the
[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX
systems (Linux, Cygwin, Mac), GoogleTest uses the
[POSIX extended regular expression](https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
syntax. To learn about POSIX syntax, you may want to read this
[Wikipedia entry](https://en.wikipedia.org/wiki/Regular_expression#POSIX_extended).
On Windows, GoogleTest uses its own simple regular expression implementation. It
lacks many features. For example, we don't support union (`"x|y"`), grouping
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period
(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular
expressions.):
Expression | Meaning
---------- | --------------------------------------------------------------
`c` | matches any literal character `c`
`\\d` | matches any decimal digit
`\\D` | matches any character that's not a decimal digit
`\\f` | matches `\f`
`\\n` | matches `\n`
`\\r` | matches `\r`
`\\s` | matches any ASCII whitespace, including `\n`
`\\S` | matches any character that's not a whitespace
`\\t` | matches `\t`
`\\v` | matches `\v`
`\\w` | matches any letter, `_`, or decimal digit
`\\W` | matches any character that `\\w` doesn't match
`\\c` | matches any literal character `c`, which must be a punctuation
`.` | matches any single character except `\n`
`A?` | matches 0 or 1 occurrences of `A`
`A*` | matches 0 or many occurrences of `A`
`A+` | matches 1 or many occurrences of `A`
`^` | matches the beginning of a string (not that of each line)
`$` | matches the end of a string (not that of each line)
`xy` | matches `x` followed by `y`
To help you determine which capability is available on your system, GoogleTest
defines macros to govern which regular expression it is using. The macros are:
`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
tests to work in all cases, you can either `#if` on these macros or use the more
limited syntax only.
## Death Tests
In many applications, there are assertions that can cause application failure if
@ -463,7 +393,7 @@ corruption, security holes, or worse. Hence it is vitally important to test that
such assertion statements work as expected.
Since these precondition checks cause the processes to die, we call such tests
*death tests*. More generally, any test that checks that a program terminates
_death tests_. More generally, any test that checks that a program terminates
(except by throwing an exception) in an expected fashion is also a death test.
Note that if a piece of code throws an exception, we don't consider it "death"
@ -509,12 +439,6 @@ verifies that:
exit with exit code 0, and
* calling `KillProcess()` kills the process with signal `SIGKILL`.
{: .callout .warning}
Warning: If your death test contains mocks and is expecting a specific exit
code, then you must allow the mock objects to be leaked via `Mock::AllowLeak`.
This is because the mock leak detector will exit with its own error code if it
detects a leak.
The test function body may contain other assertions and statements as well, if
necessary.
@ -527,7 +451,7 @@ Note that a death test only cares about three things:
3. does the stderr output match `matcher`?
In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it
will **not** cause the death test to fail, as GoogleTest assertions don't abort
will **not** cause the death test to fail, as googletest assertions don't abort
the process.
### Death Test Naming
@ -556,6 +480,51 @@ TEST_F(FooDeathTest, DoesThat) {
}
```
### Regular Expression Syntax
When built with Bazel and using Abseil, googletest uses the
[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX
systems (Linux, Cygwin, Mac), googletest uses the
[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
syntax. To learn about POSIX syntax, you may want to read this
[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).
On Windows, googletest uses its own simple regular expression implementation. It
lacks many features. For example, we don't support union (`"x|y"`), grouping
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period
(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular
expressions.):
Expression | Meaning
---------- | --------------------------------------------------------------
`c` | matches any literal character `c`
`\\d` | matches any decimal digit
`\\D` | matches any character that's not a decimal digit
`\\f` | matches `\f`
`\\n` | matches `\n`
`\\r` | matches `\r`
`\\s` | matches any ASCII whitespace, including `\n`
`\\S` | matches any character that's not a whitespace
`\\t` | matches `\t`
`\\v` | matches `\v`
`\\w` | matches any letter, `_`, or decimal digit
`\\W` | matches any character that `\\w` doesn't match
`\\c` | matches any literal character `c`, which must be a punctuation
`.` | matches any single character except `\n`
`A?` | matches 0 or 1 occurrences of `A`
`A*` | matches 0 or many occurrences of `A`
`A+` | matches 1 or many occurrences of `A`
`^` | matches the beginning of a string (not that of each line)
`$` | matches the end of a string (not that of each line)
`xy` | matches `x` followed by `y`
To help you determine which capability is available on your system, googletest
defines macros to govern which regular expression it is using. The macros are:
`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death
tests to work in all cases, you can either `#if` on these macros or use the more
limited syntax only.
### How It Works
See [Death Assertions](reference/assertions.md#death) in the Assertions
@ -570,7 +539,7 @@ arrange that kind of environment. For example, statically-initialized modules
may start threads before main is ever reached. Once threads have been created,
it may be difficult or impossible to clean them up.
GoogleTest has three features intended to raise awareness of threading issues.
googletest has three features intended to raise awareness of threading issues.
1. A warning is emitted if multiple threads are running when a death test is
encountered.
@ -593,7 +562,7 @@ The automated testing framework does not set the style flag. You can choose a
particular style of death tests by setting the flag programmatically:
```c++
GTEST_FLAG_SET(death_test_style, "threadsafe");
GTEST_FLAG_SET(death_test_style, "threadsafe")
```
You can do this in `main()` to set the style for all death tests in the binary,
@ -623,7 +592,7 @@ TEST(MyDeathTest, TestTwo) {
The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If
it leaves the current function via a `return` statement or by throwing an
exception, the death test is considered to have failed. Some GoogleTest macros
exception, the death test is considered to have failed. Some googletest macros
may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid
them in `statement`.
@ -735,7 +704,7 @@ Some tips on using `SCOPED_TRACE`:
### Propagating Fatal Failures
A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that
when they fail they only abort the *current function*, not the entire test. For
when they fail they only abort the _current function_, not the entire test. For
example, the following test will segfault:
```c++
@ -757,7 +726,7 @@ TEST(FooTest, Bar) {
}
```
To alleviate this, GoogleTest provides three different solutions. You could use
To alleviate this, googletest provides three different solutions. You could use
either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
`HasFatalFailure()` function. They are described in the following two
subsections.
@ -791,7 +760,7 @@ in it, the test will continue after the subroutine returns. This may not be what
you want.
Often people want fatal failures to propagate like exceptions. For that
GoogleTest offers the following macros:
googletest offers the following macros:
Fatal assertion | Nonfatal assertion | Verifies
------------------------------------- | ------------------------------------- | --------
@ -883,7 +852,7 @@ will output XML like this:
> needs to be prefixed with `::testing::Test::` if used outside of the
> `TEST` body and the test fixture class.
> * *`key`* must be a valid XML attribute name, and cannot conflict with the
> ones already used by GoogleTest (`name`, `status`, `time`, `classname`,
> ones already used by googletest (`name`, `status`, `time`, `classname`,
> `type_param`, and `value_param`).
> * Calling `RecordProperty()` outside of the lifespan of a test is allowed.
> If it's called outside of a test but between a test suite's
@ -894,25 +863,25 @@ will output XML like this:
## Sharing Resources Between Tests in the Same Test Suite
GoogleTest creates a new test fixture object for each test in order to make
googletest creates a new test fixture object for each test in order to make
tests independent and easier to debug. However, sometimes tests use resources
that are expensive to set up, making the one-copy-per-test model prohibitively
expensive.
If the tests don't change the resource, there's no harm in their sharing a
single resource copy. So, in addition to per-test set-up/tear-down, GoogleTest
single resource copy. So, in addition to per-test set-up/tear-down, googletest
also supports per-test-suite set-up/tear-down. To use it:
1. In your test fixture class (say `FooTest` ), declare as `static` some member
variables to hold the shared resources.
2. Outside your test fixture class (typically just below it), define those
member variables, optionally giving them initial values.
3. In the same test fixture class, define a public member function `static void
SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a
small `u`!) to set up the shared resources and a `static void
TearDownTestSuite()` function to tear them down.
3. In the same test fixture class, define a `static void SetUpTestSuite()`
function (remember not to spell it as **`SetupTestSuite`** with a small
`u`!) to set up the shared resources and a `static void TearDownTestSuite()`
function to tear them down.
That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the
That's it! googletest automatically calls `SetUpTestSuite()` before running the
*first test* in the `FooTest` test suite (i.e. before creating the first
`FooTest` object), and calls `TearDownTestSuite()` after running the *last test*
in it (i.e. after deleting the last `FooTest` object). In between, the tests can
@ -927,8 +896,7 @@ Note that `SetUpTestSuite()` may be called multiple times for a test fixture
class that has derived classes, so you should not expect code in the function
body to be run only once. Also, derived classes still have access to shared
resources defined as static members, so careful consideration is needed when
managing shared resources to avoid memory leaks if shared resources are not
properly cleaned up in `TearDownTestSuite()`.
managing shared resources to avoid memory leaks.
Here's an example of per-test-suite set-up and tear-down:
@ -939,15 +907,10 @@ class FooTest : public testing::Test {
// Called before the first test in this test suite.
// Can be omitted if not needed.
static void SetUpTestSuite() {
shared_resource_ = new ...;
// If `shared_resource_` is **not deleted** in `TearDownTestSuite()`,
// reallocation should be prevented because `SetUpTestSuite()` may be called
// in subclasses of FooTest and lead to memory leak.
//
// if (shared_resource_ == nullptr) {
// shared_resource_ = new ...;
// }
// Avoid reallocating static objects if called in subclasses of FooTest.
if (shared_resource_ == nullptr) {
shared_resource_ = new ...;
}
}
// Per-test-suite tear-down.
@ -1005,34 +968,24 @@ class Environment : public ::testing::Environment {
};
```
Then, you register an instance of your environment class with GoogleTest by
Then, you register an instance of your environment class with googletest by
calling the `::testing::AddGlobalTestEnvironment()` function:
```c++
Environment* AddGlobalTestEnvironment(Environment* env);
```
Now, when `RUN_ALL_TESTS()` is invoked, it first calls the `SetUp()` method. The
tests are then executed, provided that none of the environments have reported
fatal failures and `GTEST_SKIP()` has not been invoked. Finally, `TearDown()` is
called.
Note that `SetUp()` and `TearDown()` are only invoked if there is at least one
test to be performed. Importantly, `TearDown()` is executed even if the test is
not run due to a fatal failure or `GTEST_SKIP()`.
Calling `SetUp()` and `TearDown()` for each iteration depends on the flag
`gtest_recreate_environments_when_repeating`. `SetUp()` and `TearDown()` are
called for each environment object when the object is recreated for each
iteration. However, if test environments are not recreated for each iteration,
`SetUp()` is called only on the first iteration, and `TearDown()` is called only
on the last iteration.
Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of
each environment object, then runs the tests if none of the environments
reported fatal failures and `GTEST_SKIP()` was not called. `RUN_ALL_TESTS()`
always calls `TearDown()` with each environment object, regardless of whether or
not the tests were run.
It's OK to register multiple environment objects. In this suite, their `SetUp()`
will be called in the order they are registered, and their `TearDown()` will be
called in the reverse order.
Note that GoogleTest takes ownership of the registered environment objects.
Note that googletest takes ownership of the registered environment objects.
Therefore **do not delete them** by yourself.
You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called,
@ -1084,7 +1037,7 @@ they must be declared **public** rather than **protected** in order to use
```c++
class FooTest :
public testing::TestWithParam<absl::string_view> {
public testing::TestWithParam<const char*> {
// You can implement all the usual fixture class members here.
// To access the test parameter, call GetParam() from class
// TestWithParam<T>.
@ -1095,7 +1048,7 @@ class BaseTest : public testing::Test {
...
};
class BarTest : public BaseTest,
public testing::WithParamInterface<absl::string_view> {
public testing::WithParamInterface<const char*> {
...
};
```
@ -1142,11 +1095,6 @@ instantiation of the test suite. The next argument is the name of the test
pattern, and the last is the
[parameter generator](reference/testing.md#param-generators).
The parameter generator expression is not evaluated until GoogleTest is
initialized (via `InitGoogleTest()`). Any prior initialization done in the
`main` function will be accessible from the parameter generator, for example,
the results of flag parsing.
You can instantiate a test pattern more than once, so to distinguish different
instances of the pattern, the instantiation name is added as a prefix to the
actual test suite name. Remember to pick unique prefixes for different
@ -1166,8 +1114,8 @@ with parameter values `"cat"` and `"dog"` using the
[`ValuesIn`](reference/testing.md#param-generators) parameter generator:
```c++
constexpr absl::string_view kPets[] = {"cat", "dog"};
INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets));
const char* pets[] = {"cat", "dog"};
INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets));
```
The tests from the instantiation above will have these names:
@ -1194,8 +1142,8 @@ GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);
You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples.
[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example"
[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
[sample7_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample7_unittest.cc "Parameterized Test example"
[sample8_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters"
### Creating Value-Parameterized Abstract Tests
@ -1346,7 +1294,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... }
You can see [sample6_unittest.cc] for a complete example.
[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example"
[sample6_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample6_unittest.cc "Typed Test example"
## Type-Parameterized Tests
@ -1450,19 +1398,17 @@ are two cases to consider:
To test them, we use the following special techniques:
* Both static functions and definitions/declarations in an unnamed namespace
are only visible within the same translation unit. To test them, move the
private code into the `foo::internal` namespace, where `foo` is the
namespace your project normally uses, and put the private declarations in a
`*-internal.h` file. Your production `.cc` files and your tests are allowed
to include this internal header, but your clients are not. This way, you can
fully test your internal implementation without leaking it to your clients.
are only visible within the same translation unit. To test them, you can
`#include` the entire `.cc` file being tested in your `*_test.cc` file.
(#including `.cc` files is not a good way to reuse code - you should not do
this in production code!)
{: .callout .note}
NOTE: It is also technically *possible* to `#include` the entire `.cc` file
being tested in your `*_test.cc` file to test static functions and
definitions/declarations in an unnamed namespace. However, this technique is
**not recommended** by this documentation and it is only presented here for the
sake of completeness.
However, a better approach is to move the private code into the
`foo::internal` namespace, where `foo` is the namespace your project
normally uses, and put the private declarations in a `*-internal.h` file.
Your production `.cc` files and your tests are allowed to include this
internal header, but your clients are not. This way, you can fully test your
internal implementation without leaking it to your clients.
* Private class members are only accessible from within the class or by
friends. To access a class' private members, you can declare your test
@ -1475,7 +1421,10 @@ sake of completeness.
Another way to test private members is to refactor them into an
implementation class, which is then declared in a `*-internal.h` file. Your
clients aren't allowed to include this header but your tests can.
clients aren't allowed to include this header but your tests can. Such is
called the
[Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/)
(Private Implementation) idiom.
Or, you can declare an individual test as a friend of your class by adding
this line in the class body:
@ -1541,12 +1490,12 @@ sake of completeness.
## "Catching" Failures
If you are building a testing utility on top of GoogleTest, you'll want to test
your utility. What framework would you use to test it? GoogleTest, of course.
If you are building a testing utility on top of googletest, you'll want to test
your utility. What framework would you use to test it? googletest, of course.
The challenge is to verify that your testing utility reports failures correctly.
In frameworks that report a failure by throwing an exception, you could catch
the exception and assert on it. But GoogleTest doesn't use exceptions, so how do
the exception and assert on it. But googletest doesn't use exceptions, so how do
we test that a piece of code generates an expected failure?
`"gtest/gtest-spi.h"` contains some constructs to do this.
@ -1689,9 +1638,9 @@ particular, you cannot find the test suite name in `SetUpTestSuite()`,
`TearDownTestSuite()` (where you know the test suite name implicitly), or
functions called from them.
## Extending GoogleTest by Handling Test Events
## Extending googletest by Handling Test Events
GoogleTest provides an **event listener API** to let you receive notifications
googletest provides an **event listener API** to let you receive notifications
about the progress of a test program and test failures. The events you can
listen to include the start and end of the test program, a test suite, or a test
method, among others. You may use this API to augment or replace the standard
@ -1752,7 +1701,7 @@ Here's an example:
### Using Event Listeners
To use the event listener you have defined, add an instance of it to the
GoogleTest event listener list (represented by class
googletest event listener list (represented by class
[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s"
at the end of the name) in your `main()` function, before calling
`RUN_ALL_TESTS()`:
@ -1763,7 +1712,7 @@ int main(int argc, char** argv) {
// Gets hold of the event listener list.
testing::TestEventListeners& listeners =
testing::UnitTest::GetInstance()->listeners();
// Adds a listener to the end. GoogleTest takes the ownership.
// Adds a listener to the end. googletest takes the ownership.
listeners.Append(new MinimalistPrinter);
return RUN_ALL_TESTS();
}
@ -1784,7 +1733,7 @@ You can do so by adding one line:
Now, sit back and enjoy a completely different output from your tests. For more
details, see [sample9_unittest.cc].
[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example"
[sample9_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample9_unittest.cc "Event listener example"
You may append more than one listener to the list. When an `On*Start()` or
`OnTestPartResult()` event is fired, the listeners will receive it in the order
@ -1811,17 +1760,17 @@ by the former.
See [sample10_unittest.cc] for an example of a failure-raising listener.
[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
[sample10_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample10_unittest.cc "Failure-raising listener example"
## Running Test Programs: Advanced Options
GoogleTest test programs are ordinary executables. Once built, you can run them
googletest test programs are ordinary executables. Once built, you can run them
directly and affect their behavior via the following environment variables
and/or command line flags. For the flags to work, your programs must call
`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
To see a list of supported flags and their usage, please run your test program
with the `--help` flag.
with the `--help` flag. You can also use `-h`, `-?`, or `/?` for short.
If an option is specified both by an environment variable and by a flag, the
latter takes precedence.
@ -1848,10 +1797,10 @@ corresponding environment variable for this flag.
#### Running a Subset of the Tests
By default, a GoogleTest program runs all tests the user has defined. Sometimes,
By default, a googletest program runs all tests the user has defined. Sometimes,
you want to run only a subset of the tests (e.g. for debugging or quickly
verifying a change). If you set the `GTEST_FILTER` environment variable or the
`--gtest_filter` flag to a filter string, GoogleTest will only run the tests
`--gtest_filter` flag to a filter string, googletest will only run the tests
whose full names (in the form of `TestSuiteName.TestName`) match the filter.
The format of a filter is a '`:`'-separated list of wildcard patterns (called
@ -1882,7 +1831,7 @@ For example:
#### Stop test execution upon first failure
By default, a GoogleTest program runs all tests the user has defined. In some
By default, a googletest program runs all tests the user has defined. In some
cases (e.g. iterative test development & execution) it may be desirable stop
test execution upon first failure (trading improved latency for completeness).
If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,
@ -1899,7 +1848,7 @@ If you need to disable all tests in a test suite, you can either add `DISABLED_`
to the front of the name of each test, or alternatively add it to the front of
the test suite name.
For example, the following tests won't be run by GoogleTest, even though they
For example, the following tests won't be run by googletest, even though they
will still be compiled:
```c++
@ -1914,7 +1863,7 @@ TEST_F(DISABLED_BarTest, DoesXyz) { ... }
{: .callout .note}
NOTE: This feature should only be used for temporary pain-relief. You still have
to fix the disabled tests at a later date. As a reminder, GoogleTest will print
to fix the disabled tests at a later date. As a reminder, googletest will print
a banner warning you if a test program contains any disabled tests.
{: .callout .tip}
@ -1930,35 +1879,6 @@ the `--gtest_also_run_disabled_tests` flag or set the
You can combine this with the `--gtest_filter` flag to further select which
disabled tests to run.
### Enforcing Having At Least One Test Case
A not uncommon programmer mistake is to write a test program that has no test
case linked in. This can happen, for example, when you put test case definitions
in a library and the library is not marked as "always link".
To catch such mistakes, run the test program with the
`--gtest_fail_if_no_test_linked` flag or set the `GTEST_FAIL_IF_NO_TEST_LINKED`
environment variable to a value other than `0`. Now the program will fail if no
test case is linked in.
Note that *any* test case linked in makes the program valid for the purpose of
this check. In particular, even a disabled test case suffices.
### Enforcing Running At Least One Test Case
In addition to enforcing that tests are defined in the binary with
`--gtest_fail_if_no_test_linked`, it is also possible to enforce that a test
case was actually executed to ensure that resources are not consumed by tests
that do nothing.
To catch such optimization opportunities, run the test program with the
`--gtest_fail_if_no_test_selected` flag or set the
`GTEST_FAIL_IF_NO_TEST_SELECTED` environment variable to a value other than `0`.
A test is considered selected if it begins to run, even if it is later skipped
via `GTEST_SKIP`. Thus, `DISABLED` tests do not count as selected and neither do
tests that are not matched by `--gtest_filter`.
### Repeating the Tests
Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it
@ -1988,12 +1908,8 @@ Repeat the tests whose name matches the filter 1000 times.
If your test program contains
[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be
repeated in each iteration as well, as the flakiness may be in it. To avoid
repeating global set-up/tear-down, specify
`--gtest_recreate_environments_when_repeating=false`{.nowrap}.
You can also specify the repeat count by setting the `GTEST_REPEAT` environment
variable.
repeated in each iteration as well, as the flakiness may be in it. You can also
specify the repeat count by setting the `GTEST_REPEAT` environment variable.
### Shuffling the Tests
@ -2001,16 +1917,16 @@ You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`
environment variable to `1`) to run the tests in a program in a random order.
This helps to reveal bad dependencies between tests.
By default, GoogleTest uses a random seed calculated from the current time.
By default, googletest uses a random seed calculated from the current time.
Therefore you'll get a different order every time. The console output includes
the random seed value, such that you can reproduce an order-related test failure
later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED`
flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an
integer in the range [0, 99999]. The seed value 0 is special: it tells
GoogleTest to do the default behavior of calculating the seed from the current
googletest to do the default behavior of calculating the seed from the current
time.
If you combine this with `--gtest_repeat=N`, GoogleTest will pick a different
If you combine this with `--gtest_repeat=N`, googletest will pick a different
random seed and re-shuffle the tests in each iteration.
### Distributing Test Functions to Multiple Machines
@ -2069,7 +1985,7 @@ shards, but here's one possible scenario:
#### Colored Terminal Output
GoogleTest can use colors in its terminal output to make it easier to spot the
googletest can use colors in its terminal output to make it easier to spot the
important information:
<pre>...
@ -2094,25 +2010,25 @@ important information:
You can set the `GTEST_COLOR` environment variable or the `--gtest_color`
command line flag to `yes`, `no`, or `auto` (the default) to enable colors,
disable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest
disable colors, or let googletest decide. When the value is `auto`, googletest
will use colors if and only if the output goes to a terminal and (on non-Windows
platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.
#### Suppressing test passes
By default, GoogleTest prints 1 line of output for each test, indicating if it
By default, googletest prints 1 line of output for each test, indicating if it
passed or failed. To show only test failures, run the test program with
`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.
#### Suppressing the Elapsed Time
By default, GoogleTest prints the time it takes to run each test. To disable
By default, googletest prints the time it takes to run each test. To disable
that, run the test program with the `--gtest_print_time=0` command line flag, or
set the GTEST_PRINT_TIME environment variable to `0`.
#### Suppressing UTF-8 Text Output
In case of assertion failures, GoogleTest prints expected and actual values of
In case of assertion failures, googletest prints expected and actual values of
type `string` both as hex-encoded strings as well as in readable UTF-8 text if
they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8
text because, for example, you don't have an UTF-8 compatible output medium, run
@ -2121,7 +2037,7 @@ environment variable to `0`.
#### Generating an XML Report
GoogleTest can emit a detailed XML report to a file in addition to its normal
googletest can emit a detailed XML report to a file in addition to its normal
textual output. The report contains the duration of each test, and thus can help
you identify slow tests.
@ -2132,15 +2048,15 @@ in which case the output can be found in the `test_detail.xml` file in the
current directory.
If you specify a directory (for example, `"xml:output/directory/"` on Linux or
`"xml:output\directory\"` on Windows), GoogleTest will create the XML file in
`"xml:output\directory\"` on Windows), googletest will create the XML file in
that directory, named after the test executable (e.g. `foo_test.xml` for test
program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left
over from a previous run), GoogleTest will pick a different name (e.g.
over from a previous run), googletest will pick a different name (e.g.
`foo_test_1.xml`) to avoid overwriting it.
The report is based on the `junitreport` Ant task. Since that format was
originally intended for Java, a little interpretation is required to make it
apply to GoogleTest tests, as shown here:
apply to googletest tests, as shown here:
```xml
<testsuites name="AllTests" ...>
@ -2155,8 +2071,8 @@ apply to GoogleTest tests, as shown here:
```
* The root `<testsuites>` element corresponds to the entire test program.
* `<testsuite>` elements correspond to GoogleTest test suites.
* `<testcase>` elements correspond to GoogleTest test functions.
* `<testsuite>` elements correspond to googletest test suites.
* `<testcase>` elements correspond to googletest test functions.
For instance, the following program
@ -2189,7 +2105,7 @@ could generate this report:
Things to note:
* The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how
many test functions the GoogleTest program or test suite contains, while the
many test functions the googletest program or test suite contains, while the
`failures` attribute tells how many of them failed.
* The `time` attribute expresses the duration of the test, test suite, or
@ -2201,12 +2117,12 @@ Things to note:
* The `file` and `line` attributes record the source file location, where the
test was defined.
* Each `<failure>` element corresponds to a single failed GoogleTest
* Each `<failure>` element corresponds to a single failed googletest
assertion.
#### Generating a JSON Report
GoogleTest can also emit a JSON report as an alternative format to XML. To
googletest can also emit a JSON report as an alternative format to XML. To
generate the JSON report, set the `GTEST_OUTPUT` environment variable or the
`--gtest_output` flag to the string `"json:path_to_output_file"`, which will
create the file at the given location. You can also just use the string
@ -2217,7 +2133,7 @@ The report format conforms to the following JSON Schema:
```json
{
"$schema": "https://json-schema.org/schema#",
"$schema": "http://json-schema.org/schema#",
"type": "object",
"definitions": {
"TestCase": {
@ -2418,7 +2334,7 @@ IMPORTANT: The exact format of the JSON document is subject to change.
#### Detecting Test Premature Exit
Google Test implements the *premature-exit-file* protocol for test runners to
Google Test implements the _premature-exit-file_ protocol for test runners to
catch any kind of unexpected exits of test programs. Upon start, Google Test
creates the file which will be automatically deleted after all work has been
finished. Then, the test runner can check if this file exists. In case the file
@ -2431,7 +2347,7 @@ variable has been set.
When running test programs under a debugger, it's very convenient if the
debugger can catch an assertion failure and automatically drop into interactive
mode. GoogleTest's *break-on-failure* mode supports this behavior.
mode. googletest's *break-on-failure* mode supports this behavior.
To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value
other than `0`. Alternatively, you can use the `--gtest_break_on_failure`
@ -2439,9 +2355,9 @@ command line flag.
#### Disabling Catching Test-Thrown Exceptions
GoogleTest can be used either with or without exceptions enabled. If a test
googletest can be used either with or without exceptions enabled. If a test
throws a C++ exception or (on Windows) a structured exception (SEH), by default
GoogleTest catches it, reports it as a test failure, and continues with the next
googletest catches it, reports it as a test failure, and continues with the next
test method. This maximizes the coverage of a test run. Also, on Windows an
uncaught exception will cause a pop-up window, so catching the exceptions allows
you to run the tests automatically.
@ -2479,4 +2395,4 @@ void __tsan_on_report() {
```
After compiling your project with one of the sanitizers enabled, if a particular
test triggers a sanitizer error, GoogleTest will report that it failed.
test triggers a sanitizer error, googletest will report that it failed.

View File

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

View File

@ -20,7 +20,7 @@ class Foo {
(note that `~Foo()` **must** be virtual) we can define its mock as
```cpp
#include <gmock/gmock.h>
#include "gmock/gmock.h"
class MockFoo : public Foo {
public:
@ -130,7 +130,7 @@ TEST(BarTest, DoesThis) {
## Setting Default Actions {#OnCall}
gMock has a **built-in default action** for any function that returns `void`,
`bool`, a numeric value, or a pointer. In C++11, it additionally returns
`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
the default-constructed value, if one exists for the given type.
To customize the default action for functions with return type `T`, 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
// creating a new Buzz every time.
DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
[] { return std::make_unique<Buzz>(AccessLevel::kInternal); });
[] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
// When this fires, the default action of MakeBuzz() will run, which
// will return a new Buzz object.

View File

@ -177,7 +177,7 @@ class StackInterface {
template <typename Elem>
class MockStack : public StackInterface<Elem> {
...
MOCK_METHOD(int, GetSize, (), (const, override));
MOCK_METHOD(int, GetSize, (), (override));
MOCK_METHOD(void, Push, (const Elem& x), (override));
};
```
@ -285,10 +285,6 @@ If you are concerned about the performance overhead incurred by virtual
functions, and profiling confirms your concern, you can combine this with the
recipe for [mocking non-virtual methods](#MockingNonVirtualMethods).
Alternatively, instead of introducing a new interface, you can rewrite your code
to accept a std::function instead of the free function, and then use
[MockFunction](#MockFunction) to mock the std::function.
### Old-Style `MOCK_METHODn` Macros
Before the generic `MOCK_METHOD` macro
@ -697,9 +693,9 @@ TEST(AbcTest, Xyz) {
EXPECT_CALL(foo, DoThat(_, _));
int n = 0;
EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked.
EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked.
foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked.
EXPECT_EQ(n, 2);
EXPECT_EQ(2, n);
}
```
@ -900,16 +896,15 @@ using ::testing::Not;
Matchers are function objects, and parametrized matchers can be composed just
like any other function. However because their types can be long and rarely
provide meaningful information, it can be easier to express them with template
parameters and `auto`. For example,
provide meaningful information, it can be easier to express them with C++14
generic lambdas to avoid specifying types. For example,
```cpp
using ::testing::Contains;
using ::testing::Property;
template <typename SubMatcher>
inline constexpr auto HasFoo(const SubMatcher& sub_matcher) {
return Property("foo", &MyClass::foo, Contains(sub_matcher));
inline constexpr auto HasFoo = [](const auto& f) {
return Property(&MyClass::foo, Contains(f));
};
...
EXPECT_THAT(x, HasFoo("blah"));
@ -937,8 +932,8 @@ casts a matcher `m` to type `Matcher<T>`. To ensure safety, gMock checks that
floating-point numbers), the conversion from `T` to `U` is not lossy (in
other words, any value representable by `T` can also be represented by `U`);
and
3. When `U` is a non-const reference, `T` must also be a reference (as the
underlying matcher may be interested in the address of the `U` value).
3. When `U` is a reference, `T` must also be a reference (as the underlying
matcher may be interested in the address of the `U` value).
The code won't compile if any of these conditions isn't met.
@ -1130,11 +1125,11 @@ using STL's `<functional>` header is just painful). For example, here's a
predicate that's satisfied by any number that is >= 0, <= 100, and != 50:
```cpp
using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
using ::testing::Matches;
using ::testing::Ne;
using testing::AllOf;
using testing::Ge;
using testing::Le;
using testing::Matches;
using testing::Ne;
...
Matches(AllOf(Ge(0), Le(100), Ne(50)))
```
@ -1163,7 +1158,7 @@ int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
```
Note that the predicate function / functor doesn't have to return `bool`. It
works as long as the return value can be used as the condition in the statement
works as long as the return value can be used as the condition in in statement
`if (condition) ...`.
### Matching Arguments that Are Not Copyable
@ -1350,7 +1345,7 @@ class BarPlusBazEqMatcher {
...
Foo foo;
EXPECT_THAT(foo, BarPlusBazEq(5))...;
EXPECT_CALL(foo, BarPlusBazEq(5))...;
```
### Matching Containers
@ -1429,12 +1424,11 @@ Use `Pair` when comparing maps or other associative containers.
{% raw %}
```cpp
using ::testing::UnorderedElementsAre;
using ::testing::Pair;
using testing::ElementsAre;
using testing::Pair;
...
absl::flat_hash_map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
EXPECT_THAT(m, UnorderedElementsAre(
Pair("a", 1), Pair("b", 2), Pair("c", 3)));
std::map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
EXPECT_THAT(m, ElementsAre(Pair("a", 1), Pair("b", 2), Pair("c", 3)));
```
{% endraw %}
@ -1451,8 +1445,8 @@ using ::testing::Pair;
* If the container is passed by pointer instead of by reference, just write
`Pointee(ElementsAre*(...))`.
* The order of elements *matters* for `ElementsAre*()`. If you are using it
with containers whose element order are undefined (such as a
`std::unordered_map`) you should use `UnorderedElementsAre`.
with containers whose element order are undefined (e.g. `hash_map`) you
should use `WhenSorted` around `ElementsAre`.
### Sharing Matchers
@ -1862,7 +1856,7 @@ error. So, what shall you do?
Though you may be tempted, DO NOT use `std::ref()`:
```cpp
using ::testing::Return;
using testing::Return;
class MockFoo : public Foo {
public:
@ -1874,7 +1868,7 @@ class MockFoo : public Foo {
EXPECT_CALL(foo, GetValue())
.WillRepeatedly(Return(std::ref(x))); // Wrong!
x = 42;
EXPECT_EQ(foo.GetValue(), 42);
EXPECT_EQ(42, foo.GetValue());
```
Unfortunately, it doesn't work here. The above code will fail with error:
@ -1896,20 +1890,20 @@ the expectation is set, and `Return(std::ref(x))` will always return 0.
returns the value pointed to by `pointer` at the time the action is *executed*:
```cpp
using ::testing::ReturnPointee;
using testing::ReturnPointee;
...
int x = 0;
MockFoo foo;
EXPECT_CALL(foo, GetValue())
.WillRepeatedly(ReturnPointee(&x)); // Note the & here.
x = 42;
EXPECT_EQ(foo.GetValue(), 42); // This will succeed now.
EXPECT_EQ(42, foo.GetValue()); // This will succeed now.
```
### Combining Actions
Want to do more than one thing when a function is called? That's fine. `DoAll()`
allows you to do a sequence of actions every time. Only the return value of the
allow you to do sequence of actions every time. Only the return value of the
last action in the sequence will be used.
```cpp
@ -1928,12 +1922,6 @@ class MockFoo : public Foo {
action_n));
```
The return value of the last action **must** match the return type of the mocked
method. In the example above, `action_n` could be `Return(true)`, or a lambda
that returns a `bool`, but not `SaveArg`, which returns `void`. Otherwise the
signature of `DoAll` would not match the signature expected by `WillOnce`, which
is the signature of the mocked method, and it wouldn't compile.
### Verifying Complex Arguments {#SaveArgVerify}
If you want to verify that a method is called with a particular argument but the
@ -2271,7 +2259,7 @@ TEST_F(FooTest, Test) {
EXPECT_CALL(foo, DoThis(2))
.WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5)));
EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2).
EXPECT_EQ('+', foo.DoThis(2)); // Invokes SignOfSum(5, 2).
}
```
@ -2647,8 +2635,8 @@ action will exhibit different behaviors. Example:
.WillRepeatedly(IncrementCounter(0));
foo.DoThis(); // Returns 1.
foo.DoThis(); // Returns 2.
foo.DoThat(); // Returns 1 - DoThat() uses a different
// counter than DoThis()'s.
foo.DoThat(); // Returns 1 - Blah() uses a different
// counter than Bar()'s.
```
versus
@ -2778,33 +2766,36 @@ returns a null `unique_ptr`, thats what youll get if you dont specify a
action:
```cpp
using ::testing::IsNull;
...
// Use the default action.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));
// Triggers the previous EXPECT_CALL.
EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull());
EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello"));
```
If you are not happy with the default action, you can tweak it as usual; see
[Setting Default Actions](#OnCall).
If you just need to return a move-only value, you can use it in combination with
`WillOnce`. For example:
If you just need to return a pre-defined move-only value, you can use the
`Return(ByMove(...))` action:
```cpp
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"))
.WillOnce(Return(std::make_unique<Buzz>(AccessLevel::kInternal)));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello"));
// When this fires, the unique_ptr<> specified by ByMove(...) will
// be returned.
EXPECT_CALL(mock_buzzer_, MakeBuzz("world"))
.WillOnce(Return(ByMove(MakeUnique<Buzz>(AccessLevel::kInternal))));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world"));
```
Quiz time! What do you think will happen if a `Return` action is performed more
than once (e.g. you write `... .WillRepeatedly(Return(std::move(...)));`)? Come
think of it, after the first time the action runs, the source value will be
consumed (since its a move-only value), so the next time around, theres no
value to move from -- youll get a run-time error that `Return(std::move(...))`
can only be run once.
Note that `ByMove()` is essential here - if you drop it, the code wont compile.
Quiz time! What do you think will happen if a `Return(ByMove(...))` action is
performed more than once (e.g. you write `...
.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time
the action runs, the source value will be consumed (since its a move-only
value), so the next time around, theres no value to move from -- youll get a
run-time error that `Return(ByMove(...))` can only be run once.
If you need your mock method to do more than just moving a pre-defined value,
remember that you can always use a lambda or a callable object, which can do
@ -2813,7 +2804,7 @@ pretty much anything you want:
```cpp
EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
.WillRepeatedly([](StringPiece text) {
return std::make_unique<Buzz>(AccessLevel::kInternal);
return MakeUnique<Buzz>(AccessLevel::kInternal);
});
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
@ -2821,7 +2812,7 @@ pretty much anything you want:
```
Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created
and returned. You cannot do this with `Return(std::make_unique<...>(...))`.
and returned. You cannot do this with `Return(ByMove(...))`.
That covers returning move-only values; but how do we work with methods
accepting move-only arguments? The answer is that they work normally, although
@ -2832,7 +2823,7 @@ can always use `Return`, or a [lambda or functor](#FunctionsAsActions):
using ::testing::Unused;
EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true));
EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal)),
EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal)),
0);
EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce(
@ -2876,7 +2867,7 @@ method:
// When one calls ShareBuzz() on the MockBuzzer like this, the call is
// forwarded to DoShareBuzz(), which is mocked. Therefore this statement
// will trigger the above EXPECT_CALL.
mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal), 0);
mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0);
```
### Making the Compilation Faster
@ -3201,11 +3192,11 @@ You can unlock this power by running your test with the `--gmock_verbose=info`
flag. For example, given the test program:
```cpp
#include <gmock/gmock.h>
#include "gmock/gmock.h"
using ::testing::_;
using ::testing::HasSubstr;
using ::testing::Return;
using testing::_;
using testing::HasSubstr;
using testing::Return;
class MockFoo {
public:
@ -3313,7 +3304,7 @@ For convenience, we allow the description string to be empty (`""`), in which
case gMock will use the sequence of words in the matcher name as the
description.
#### Basic Example
For example:
```cpp
MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
@ -3351,8 +3342,6 @@ If the above assertions fail, they will print something like:
where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are
automatically calculated from the matcher name `IsDivisibleBy7`.
#### Adding Custom Failure Messages
As you may have noticed, the auto-generated descriptions (especially those for
the negation) may not be so great. You can always override them with a `string`
expression of your own:
@ -3386,48 +3375,21 @@ With this definition, the above assertion will give a better message:
Actual: 27 (the remainder is 6)
```
#### Using EXPECT_ Statements in Matchers
You can also use `EXPECT_...` statements inside custom matcher definitions. In
many cases, this allows you to write your matcher more concisely while still
providing an informative error message. For example:
```cpp
MATCHER(IsDivisibleBy7, "") {
const auto remainder = arg % 7;
EXPECT_EQ(remainder, 0);
return true;
}
```
If you write a test that includes the line `EXPECT_THAT(27, IsDivisibleBy7());`,
you will get an error something like the following:
```shell
Expected equality of these values:
remainder
Which is: 6
0
```
#### `MatchAndExplain`
You should let `MatchAndExplain()` print *any additional information* that can
help a user understand the match result. Note that it should explain why the
match succeeds in case of a success (unless it's obvious) - this is useful when
the matcher is used inside `Not()`. There is no need to print the argument value
itself, as gMock already prints it for you.
#### Argument Types
The type of the value being matched (`arg_type`) is determined by the context in
which you use the matcher and is supplied to you by the compiler, so you don't
need to worry about declaring it (nor can you). This allows the matcher to be
polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where
the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the
`Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`,
`arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be
`unsigned long`; and so on.
{: .callout .note}
NOTE: The type of the value being matched (`arg_type`) is determined by the
context in which you use the matcher and is supplied to you by the compiler, so
you don't need to worry about declaring it (nor can you). This allows the
matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match
any type where the value of `(arg % 7) == 0` can be implicitly converted to a
`bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an
`int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will
be `unsigned long`; and so on.
### Writing New Parameterized Matchers Quickly
@ -3568,15 +3530,10 @@ just based on the number of parameters).
### Writing New Monomorphic Matchers
A matcher of type `testing::Matcher<T>` implements the matcher interface for `T`
and does two things: it tests whether a value of type `T` matches the matcher,
and can describe what kind of values it matches. The latter ability is used for
generating readable error messages when expectations are violated. Some matchers
can even explain why it matches or doesn't match a certain value, which can be
helpful when the reason isn't obvious.
Because a matcher of type `testing::Matcher<T>` for a particular type `T` can
only be used to match a value of type `T`, we call it "monomorphic."
A matcher of argument type `T` implements the matcher interface for `T` and does
two things: it tests whether a value of type `T` matches the matcher, and can
describe what kind of values it matches. The latter ability is used for
generating readable error messages when expectations are violated.
A matcher of `T` must declare a typedef like:
@ -3668,16 +3625,8 @@ instead of `std::ostream*`.
### Writing New Polymorphic Matchers
Unlike a monomorphic matcher, which can only be used to match a value of a
particular type, a *polymorphic* matcher is one that can be used to match values
of multiple types. For example, `Eq(5)` is a polymorhpic matcher as it can be
used to match an `int`, a `double`, a `float`, and so on. You should think of a
polymorphic matcher as a *matcher factory* as opposed to a
`testing::Matcher<SomeType>` - itself is not an actual matcher, but can be
implicitly converted to a `testing::Matcher<SomeType>` depending on the context.
Expanding what we learned above to polymorphic matchers is now as simple as
adding templates in the right place.
Expanding what we learned above to *polymorphic* matchers is now just as simple
as adding templates in the right place.
```cpp
@ -3803,26 +3752,6 @@ virtual.
Like in a monomorphic matcher, you may explain the match result by streaming
additional information to the `listener` argument in `MatchAndExplain()`.
### Implementing Composite Matchers {#CompositeMatchers}
Sometimes we want to define a matcher that takes other matchers as parameters.
For example, `DistanceFrom(target, m)` is a polymorphic matcher that takes a
matcher `m` as a parameter. It tests that the distance from `target` to the
value being matched satisfies sub-matcher `m`.
If you are implementing such a composite matcher, you'll need to generate the
description of the matcher based on the description(s) of its sub-matcher(s).
You can see the implementation of `DistanceFrom()` in
`googlemock/include/gmock/gmock-matchers.h` for an example. In particular, pay
attention to `DistanceFromMatcherImpl`. Notice that it stores the sub-matcher as
a `const Matcher<const Distance&> distance_matcher_` instead of a polymorphic
matcher - this allows it to call `distance_matcher_.DescribeTo(os)` to describe
the sub-matcher. If the sub-matcher is stored as a polymorphic matcher instead,
it would not be possible to get its description as in general polymorphic
matchers don't know how to describe themselves - they are matcher factories
instead of actual matchers; only after being converted to `Matcher<SomeType>`
can they be described.
### Writing New Cardinalities
A cardinality is used in `Times()` to tell gMock how many times you expect a
@ -3888,15 +3817,15 @@ If the built-in actions don't work for you, you can easily define your own one.
All you need is a call operator with a signature compatible with the mocked
function. So you can use a lambda:
```cpp
```
MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; });
EXPECT_EQ(mock.AsStdFunction()(2), 14);
EXPECT_EQ(14, mock.AsStdFunction()(2));
```
Or a struct with a call operator (even a templated one):
```cpp
```
struct MultiplyBy {
template <typename T>
T operator()(T arg) { return arg * multiplier; }
@ -3911,16 +3840,16 @@ struct MultiplyBy {
It's also fine for the callable to take no arguments, ignoring the arguments
supplied to the mock function:
```cpp
```
MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([] { return 17; });
EXPECT_EQ(mock.AsStdFunction()(0), 17);
EXPECT_EQ(17, mock.AsStdFunction()(0));
```
When used with `WillOnce`, the callable can assume it will be called at most
once and is allowed to be a move-only type:
```cpp
```
// An action that contains move-only types and has an &&-qualified operator,
// demanding in the type system that it be called at most once. This can be
// used with WillOnce, but the compiler will reject it if handed to
@ -4364,7 +4293,7 @@ particular type than to dump the bytes.
### Mock std::function {#MockFunction}
`std::function` is a general function type introduced in C++11. It is a
preferred way of passing callbacks to new interfaces. Functions are copyable,
preferred way of passing callbacks to new interfaces. Functions are copiable,
and are not usually passed around by pointer, which makes them tricky to mock.
But fear not - `MockFunction` can help you with that.

View File

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

View File

@ -19,15 +19,19 @@ examples here we assume you want to compile the sample
Using `pkg-config` in CMake is fairly easy:
```cmake
cmake_minimum_required(VERSION 3.0)
cmake_policy(SET CMP0048 NEW)
project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX)
find_package(PkgConfig)
pkg_search_module(GTEST REQUIRED gtest_main)
add_executable(testapp)
target_sources(testapp PRIVATE samples/sample3_unittest.cc)
target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS})
target_compile_options(testapp PRIVATE ${GTEST_CFLAGS})
add_executable(testapp samples/sample3_unittest.cc)
target_link_libraries(testapp ${GTEST_LDFLAGS})
target_compile_options(testapp PUBLIC ${GTEST_CFLAGS})
enable_testing()
include(CTest)
add_test(first_and_only_test testapp)
```

View File

@ -1,8 +1,35 @@
# Supported Platforms
GoogleTest follows Google's
[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See
[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
for a list of currently supported versions compilers, platforms, and build
tools.
GoogleTest requires a codebase and compiler compliant with the C++11 standard or
newer.
The GoogleTest code is officially supported on the following platforms.
Operating systems or tools not listed below are community-supported. For
community-supported platforms, patches that do not complicate the code may be
considered.
If you notice any problems on your platform, please file an issue on the
[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
Pull requests containing fixes are welcome!
### Operating systems
* Linux
* macOS
* Windows
### Compilers
* gcc 5.0+
* clang 5.0+
* MSVC 2015+
**macOS users:** Xcode 9.3+ provides clang 5.0+.
### Build systems
* [Bazel](https://bazel.build/)
* [CMake](https://cmake.org/)
Bazel is the build system used by the team internally and in tests. CMake is
supported on a best-effort basis and by the community.

View File

@ -1,84 +1,84 @@
# GoogleTest Primer
# Googletest Primer
## Introduction: Why GoogleTest?
## Introduction: Why googletest?
*GoogleTest* helps you write better C++ tests.
*googletest* helps you write better C++ tests.
GoogleTest is a testing framework developed by the Testing Technology team with
googletest is a testing framework developed by the Testing Technology team with
Google's specific requirements and constraints in mind. Whether you work on
Linux, Windows, or a Mac, if you write C++ code, GoogleTest can help you. And it
Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it
supports *any* kind of tests, not just unit tests.
So what makes a good test, and how does GoogleTest fit in? We believe:
So what makes a good test, and how does googletest fit in? We believe:
1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
that succeeds or fails as a result of other tests. GoogleTest isolates the
that succeeds or fails as a result of other tests. googletest isolates the
tests by running each of them on a different object. When a test fails,
GoogleTest allows you to run it in isolation for quick debugging.
googletest allows you to run it in isolation for quick debugging.
2. Tests should be well *organized* and reflect the structure of the tested
code. GoogleTest groups related tests into test suites that can share data
code. googletest groups related tests into test suites that can share data
and subroutines. This common pattern is easy to recognize and makes tests
easy to maintain. Such consistency is especially helpful when people switch
projects and start to work on a new code base.
3. Tests should be *portable* and *reusable*. Google has a lot of code that is
platform-neutral; its tests should also be platform-neutral. GoogleTest
platform-neutral; its tests should also be platform-neutral. googletest
works on different OSes, with different compilers, with or without
exceptions, so GoogleTest tests can work with a variety of configurations.
exceptions, so googletest tests can work with a variety of configurations.
4. When tests fail, they should provide as much *information* about the problem
as possible. GoogleTest doesn't stop at the first test failure. Instead, it
as possible. googletest doesn't stop at the first test failure. Instead, it
only stops the current test and continues with the next. You can also set up
tests that report non-fatal failures after which the current test continues.
Thus, you can detect and fix multiple bugs in a single run-edit-compile
cycle.
5. The testing framework should liberate test writers from housekeeping chores
and let them focus on the test *content*. GoogleTest automatically keeps
and let them focus on the test *content*. googletest automatically keeps
track of all tests defined, and doesn't require the user to enumerate them
in order to run them.
6. Tests should be *fast*. With GoogleTest, you can reuse shared resources
6. Tests should be *fast*. With googletest, you can reuse shared resources
across tests and pay for the set-up/tear-down only once, without making
tests depend on each other.
Since GoogleTest is based on the popular xUnit architecture, you'll feel right
Since googletest is based on the popular xUnit architecture, you'll feel right
at home if you've used JUnit or PyUnit before. If not, it will take you about 10
minutes to learn the basics and get started. So let's go!
## Beware of the Nomenclature
## Beware of the nomenclature
{: .callout .note}
*Note:* There might be some confusion arising from different definitions of the
terms *Test*, *Test Case* and *Test Suite*, so beware of misunderstanding these.
_Note:_ There might be some confusion arising from different definitions of the
terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
Historically, GoogleTest started to use the term *Test Case* for grouping
Historically, googletest started to use the term _Test Case_ for grouping
related tests, whereas current publications, including International Software
Testing Qualifications Board ([ISTQB](https://www.istqb.org/)) materials and
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
various textbooks on software quality, use the term
*[Test Suite][istqb test suite]* for this.
_[Test Suite][istqb test suite]_ for this.
The related term *Test*, as it is used in GoogleTest, corresponds to the term
*[Test Case][istqb test case]* of ISTQB and others.
The related term _Test_, as it is used in googletest, corresponds to the term
_[Test Case][istqb test case]_ of ISTQB and others.
The term *Test* is commonly of broad enough sense, including ISTQB's definition
of *Test Case*, so it's not much of a problem here. But the term *Test Case* as
The term _Test_ is commonly of broad enough sense, including ISTQB's definition
of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as
was used in Google Test is of contradictory sense and thus confusing.
GoogleTest recently started replacing the term *Test Case* with *Test Suite*.
googletest recently started replacing the term _Test Case_ with _Test Suite_.
The preferred API is *TestSuite*. The older TestCase API is being slowly
deprecated and refactored away.
So please be aware of the different definitions of the terms:
Meaning | GoogleTest Term | [ISTQB](https://www.istqb.org/) Term
Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
:----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
[istqb test case]: https://glossary.istqb.org/en_US/term/test-case
[istqb test suite]: https://glossary.istqb.org/en_US/term/test-suite
[istqb test case]: http://glossary.istqb.org/en/search/test%20case
[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite
## Basic Concepts
When using GoogleTest, you start by writing *assertions*, which are statements
When using googletest, you start by writing *assertions*, which are statements
that check whether a condition is true. An assertion's result can be *success*,
*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
current function; otherwise the program continues normally.
@ -98,11 +98,11 @@ assertion level and building up to tests and test suites.
## Assertions
GoogleTest assertions are macros that resemble function calls. You test a class
googletest assertions are macros that resemble function calls. You test a class
or function by making assertions about its behavior. When an assertion fails,
GoogleTest prints the assertion's source file and line number location, along
googletest prints the assertion's source file and line number location, along
with a failure message. You may also supply a custom failure message which will
be appended to GoogleTest's message.
be appended to googletest's message.
The assertions come in pairs that test the same thing but have different effects
on the current function. `ASSERT_*` versions generate fatal failures when they
@ -149,7 +149,7 @@ To create a test:
1. Use the `TEST()` macro to define and name a test function. These are
ordinary C++ functions that don't return a value.
2. In this function, along with any valid C++ statements you want to include,
use the various GoogleTest assertions to check values.
use the various googletest assertions to check values.
3. The test's result is determined by the assertions; if any assertion in the
test fails (either fatally or non-fatally), or if the test crashes, the
entire test fails. Otherwise, it succeeds.
@ -190,7 +190,7 @@ TEST(FactorialTest, HandlesPositiveInput) {
}
```
GoogleTest groups the test results by test suites, so logically related tests
googletest groups the test results by test suites, so logically related tests
should be in the same test suite; in other words, the first argument to their
`TEST()` should be the same. In the above example, we have two tests,
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
@ -210,7 +210,7 @@ objects for several different tests.
To create a fixture:
1. Derive a class from `testing::Test` . Start its body with `protected:`, as
1. Derive a class from `::testing::Test` . Start its body with `protected:`, as
we'll want to access fixture members from sub-classes.
2. Inside the class, declare any objects you plan to use.
3. If necessary, write a default constructor or `SetUp()` function to prepare
@ -227,14 +227,14 @@ When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
access objects and subroutines in the test fixture:
```c++
TEST_F(TestFixtureClassName, TestName) {
TEST_F(TestFixtureName, TestName) {
... test body ...
}
```
Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test
fixture class. (`_F` stands for "Fixture"). No test suite name is specified for
this macro.
Like `TEST()`, the first argument is the test suite name, but for `TEST_F()`
this must be the name of the test fixture class. You've probably guessed: `_F`
is for fixture.
Unfortunately, the C++ macro system does not allow us to create a single macro
that can handle both types of tests. Using the wrong macro causes a compiler
@ -244,12 +244,12 @@ Also, you must first define a test fixture class before using it in a
`TEST_F()`, or you'll get the compiler error "`virtual outside class
declaration`".
For each test defined with `TEST_F()`, GoogleTest will create a *fresh* test
For each test defined with `TEST_F()`, googletest will create a *fresh* test
fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean
up by calling `TearDown()`, and then delete the test fixture. Note that
different tests in the same test suite have different test fixture objects, and
GoogleTest always deletes a test fixture before it creates the next one.
GoogleTest does **not** reuse the same test fixture for multiple tests. Any
googletest always deletes a test fixture before it creates the next one.
googletest does **not** reuse the same test fixture for multiple tests. Any
changes one test makes to the fixture do not affect other tests.
As an example, let's write tests for a FIFO queue class named `Queue`, which has
@ -271,16 +271,15 @@ First, define a fixture class. By convention, you should give it the name
`FooTest` where `Foo` is the class being tested.
```c++
class QueueTest : public testing::Test {
class QueueTest : public ::testing::Test {
protected:
QueueTest() {
// q0_ remains empty
void SetUp() override {
q1_.Enqueue(1);
q2_.Enqueue(2);
q2_.Enqueue(3);
}
// ~QueueTest() override = default;
// void TearDown() override {}
Queue<int> q0_;
Queue<int> q1_;
@ -288,9 +287,8 @@ class QueueTest : public testing::Test {
};
```
In this case, we don't need to define a destructor or a `TearDown()` method,
because the implicit destructor generated by the compiler will perform all of
the necessary cleanup.
In this case, `TearDown()` is not needed since we don't have to clean up after
each test, other than what's already done by the destructor.
Now we'll write tests using `TEST_F()` and this fixture.
@ -326,17 +324,19 @@ would lead to a segfault when `n` is `NULL`.
When these tests run, the following happens:
1. GoogleTest constructs a `QueueTest` object (let's call it `t1`).
2. The first test (`IsEmptyInitially`) runs on `t1`.
3. `t1` is destructed.
4. The above steps are repeated on another `QueueTest` object, this time
1. googletest constructs a `QueueTest` object (let's call it `t1`).
2. `t1.SetUp()` initializes `t1`.
3. The first test (`IsEmptyInitially`) runs on `t1`.
4. `t1.TearDown()` cleans up after the test finishes.
5. `t1` is destructed.
6. The above steps are repeated on another `QueueTest` object, this time
running the `DequeueWorks` test.
**Availability**: Linux, Windows, Mac.
## Invoking the Tests
`TEST()` and `TEST_F()` implicitly register their tests with GoogleTest. So,
`TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
unlike with many other C++ testing frameworks, you don't have to re-list all
your defined tests in order to run them.
@ -347,7 +347,7 @@ test suites, or even different source files.
When invoked, the `RUN_ALL_TESTS()` macro:
* Saves the state of all GoogleTest flags.
* Saves the state of all googletest flags.
* Creates a test fixture object for the first test.
@ -359,7 +359,7 @@ When invoked, the `RUN_ALL_TESTS()` macro:
* Deletes the fixture.
* Restores the state of all GoogleTest flags.
* Restores the state of all googletest flags.
* Repeats the above steps for the next test, until all tests have run.
@ -373,14 +373,14 @@ If a fatal failure happens the subsequent steps will be skipped.
> return the value of `RUN_ALL_TESTS()`.
>
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
> once conflicts with some advanced GoogleTest features (e.g., thread-safe
> once conflicts with some advanced googletest features (e.g., thread-safe
> [death tests](advanced.md#death-tests)) and thus is not supported.
**Availability**: Linux, Windows, Mac.
## Writing the main() Function
Most users should *not* need to write their own `main` function and instead link
Most users should _not_ need to write their own `main` function and instead link
with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry
point. See the end of this section for details. The remainder of this section
should only apply when you need to do something custom before the tests run that
@ -394,14 +394,14 @@ You can start from this boilerplate:
```c++
#include "this/package/foo.h"
#include <gtest/gtest.h>
#include "gtest/gtest.h"
namespace my {
namespace project {
namespace {
// The fixture for testing class Foo.
class FooTest : public testing::Test {
class FooTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if their bodies would
// be empty.
@ -449,14 +449,14 @@ TEST_F(FooTest, DoesXyz) {
} // namespace my
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
```
The `testing::InitGoogleTest()` function parses the command line for GoogleTest
flags, and removes all recognized flags. This allows the user to control a test
program's behavior via various flags, which we'll cover in the
The `::testing::InitGoogleTest()` function parses the command line for
googletest flags, and removes all recognized flags. This allows the user to
control a test program's behavior via various flags, which we'll cover in the
[AdvancedGuide](advanced.md). You **must** call this function before calling
`RUN_ALL_TESTS()`, or the flags won't be properly initialized.
@ -475,7 +475,7 @@ NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
* Google Test is designed to be thread-safe. The implementation is thread-safe
on systems where the `pthreads` library is available. It is currently
*unsafe* to use Google Test assertions from two threads concurrently on
_unsafe_ to use Google Test assertions from two threads concurrently on
other systems (e.g. Windows). In most tests this is not an issue as usually
the assertions are done in the main thread. If you want to help, you can
volunteer to implement the necessary synchronization primitives in

View File

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

View File

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

View File

@ -24,8 +24,7 @@ provided by GoogleTest. All actions are defined in the `::testing` namespace.
| :--------------------------------- | :-------------------------------------- |
| `Assign(&variable, value)` | Assign `value` to variable. |
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer` by copy-assignment. |
| `SaveArgByMove<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer` by move-assignment. |
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
| `SetArgReferee<N>(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. |
| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. |
@ -48,8 +47,8 @@ functor, or lambda.
| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. |
| `InvokeArgument<N>(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. |
The return value of the invoked function (except `InvokeArgument`) is used as
the return value of the action.
The return value of the invoked function is used as the return value of the
action.
When defining a callable to be used with `Invoke*()`, you can declare any unused
parameters as `Unused`:

View File

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

View File

@ -42,14 +42,11 @@ Matcher | Description
| `Lt(value)` | `argument < value` |
| `Ne(value)` | `argument != value` |
| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. |
| `DistanceFrom(target, m)` | The distance between `argument` and `target` (computed by `abs(argument - target)`) matches `m`. |
| `DistanceFrom(target, get_distance, m)` | The distance between `argument` and `target` (computed by `get_distance(argument, target)`) matches `m`. |
| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. |
| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). |
| `NotNull()` | `argument` is a non-null pointer (raw or smart). |
| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)|
| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |
| `AnyWith<T>(m)` | `argument` is `any<>` that holds a value of type T with a value matching `m`. |
| `Ref(variable)` | `argument` is a reference to `variable`. |
| `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. |
@ -105,40 +102,13 @@ The `argument` can be either a C string or a C++ string object:
| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. |
| `StrEq(string)` | `argument` is equal to `string`. |
| `StrNe(string)` | `argument` is not equal to `string`. |
| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. The web-safe format from [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648#section-5) is supported. |
| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. |
`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
use the regular expression syntax defined
[here](../advanced.md#regular-expression-syntax). All of these matchers, except
`ContainsRegex()` and `MatchesRegex()` work for wide strings as well.
## Exception Matchers
| Matcher | Description |
| :---------------------------------------- | :------------------------------- |
| `Throws<E>()` | The `argument` is a callable object that, when called, throws an exception of the expected type `E`. |
| `Throws<E>(m)` | The `argument` is a callable object that, when called, throws an exception of type `E` that satisfies the matcher `m`. |
| `ThrowsMessage<E>(m)` | The `argument` is a callable object that, when called, throws an exception of type `E` with a message that satisfies the matcher `m`. |
Examples:
```cpp
auto argument = [] { throw std::runtime_error("error msg"); };
// Checks if the lambda throws a `std::runtime_error`.
EXPECT_THAT(argument, Throws<std::runtime_error>());
// Checks if the lambda throws a `std::runtime_error` with a specific message
// that matches "error msg".
EXPECT_THAT(argument,
Throws<std::runtime_error>(Property(&std::runtime_error::what,
Eq("error msg"))));
// Checks if the lambda throws a `std::runtime_error` with a message that
// contains "msg".
EXPECT_THAT(argument, ThrowsMessage<std::runtime_error>(HasSubstr("msg")));
```
## Container Matchers
Most STL-style containers support `==`, so you can use `Eq(expected_container)`
@ -201,11 +171,6 @@ messages, you can use:
| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. |
| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message.
{: .callout .warning}
Warning: Don't use `Property()` against member functions that you do not own,
because taking addresses of functions is fragile and generally not part of the
contract of the function.
**Notes:**
* You can use `FieldsAre()` to match any type that supports structured
@ -224,6 +189,10 @@ contract of the function.
EXPECT_THAT(s, FieldsAre(42, "aloha"));
```
* Don't use `Property()` against member functions that you do not own, because
taking addresses of functions is fragile and generally not part of the
contract of the function.
## Matching the Result of a Function, Functor, or Callback
| Matcher | Description |
@ -319,15 +288,3 @@ which must be a permanent callback.
return ExplainMatchResult(matcher, arg.nested().property(), result_listener);
}
```
5. You can use `DescribeMatcher<>` to describe another matcher. For example:
```cpp
MATCHER_P(XAndYThat, matcher,
"X that " + DescribeMatcher<int>(matcher, negation) +
(negation ? " or" : " and") + " Y that " +
DescribeMatcher<double>(matcher, negation)) {
return ExplainMatchResult(matcher, arg.x(), result_listener) &&
ExplainMatchResult(matcher, arg.y(), result_listener);
}
```

View File

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

View File

@ -3,7 +3,7 @@
<!--* toc_depth: 3 *-->
This page lists the facilities provided by GoogleTest for writing test programs.
To use them, add `#include <gtest/gtest.h>`.
To use them, include the header `gtest/gtest.h`.
## Macros
@ -94,8 +94,7 @@ Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with
The argument *`InstantiationName`* is a unique name for the instantiation of the
test suite, to distinguish between multiple instantiations. In test output, the
instantiation name is added as a prefix to the test suite name
*`TestSuiteName`*. If *`InstantiationName`* is empty
(`INSTANTIATE_TEST_SUITE_P(, ...)`), no prefix is added.
*`TestSuiteName`*.
The argument *`param_generator`* is one of the following GoogleTest-provided
functions that generate the test parameters, all defined in the `::testing`
@ -110,7 +109,6 @@ namespace:
| `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}`. |
| `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)` or `ConvertGenerator(g, func)` | Yields values generated by generator `g`, `static_cast` from `T`. (Note: `T` might not be what you expect. See [*Using ConvertGenerator*](#using-convertgenerator) below.) The second overload uses `func` to perform the conversion. |
The optional last argument *`name_generator`* is a function or functor that
generates custom test name suffixes based on the test parameters. The function
@ -123,8 +121,8 @@ custom function can be used for more control:
```cpp
INSTANTIATE_TEST_SUITE_P(
MyInstantiation, MyTestSuite,
testing::Values(...),
[](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
::testing::Values(...),
[](const ::testing::TestParamInfo<MyTestSuite::ParamType>& info) {
// Can use info.param here to generate the test suffix
std::string name = ...
return name;
@ -137,107 +135,9 @@ For more information, see
See also
[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST).
###### Using `ConvertGenerator`
The functions listed in the table above appear to return generators that create
values of the desired types, but this is not generally the case. Rather, they
typically return factory objects that convert to the the desired generators.
This affords some flexibility in allowing you to specify values of types that
are different from, yet implicitly convertible to, the actual parameter type
required by your fixture class.
For example, you can do the following with a fixture that requires an `int`
parameter:
```cpp
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
testing::Values(1, 1.2)); // Yes, Values() supports heterogeneous argument types.
```
It might seem obvious that `1.2` &mdash; a `double` &mdash; will be converted to
an `int` but in actuality it requires some template gymnastics involving the
indirection described in the previous paragraph.
What if your parameter type is not implicitly convertible from the generated
type but is *explicitly* convertible? There will be no automatic conversion, but
you can force it by applying `ConvertGenerator<T>`. The compiler can
automatically deduce the target type (your fixture's parameter type), but
because of the aforementioned indirection it cannot decide what the generated
type should be. You need to tell it, by providing the type `T` explicitly. Thus
`T` should not be your fixture's parameter type, but rather an intermediate type
that is supported by the factory object, and which can be `static_cast` to the
fixture's parameter type:
```cpp
// The fixture's parameter type.
class MyParam {
public:
// Explicit converting ctor.
explicit MyParam(const std::tuple<int, bool>& t);
...
};
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
ConvertGenerator<std::tuple<int, bool>>(Combine(Values(0.1, 1.2), Bool())));
```
In this example `Combine` supports the generation of `std::tuple<int, bool>>`
objects (even though the provided values for the first tuple element are
`double`s) and those `tuple`s get converted into `MyParam` objects by virtue of
the call to `ConvertGenerator`.
For parameter types that are not convertible from the generated types you can
provide a callable that does the conversion. The callable accepts an object of
the generated type and returns an object of the fixture's parameter type. The
generated type can often be deduced by the compiler from the callable's call
signature so you do not usually need specify it explicitly (but see a caveat
below).
```cpp
// The fixture's parameter type.
class MyParam {
public:
MyParam(int, bool);
...
};
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
ConvertGenerator(Combine(Values(1, 1.2), Bool()),
[](const std::tuple<int, bool>& t){
const auto [i, b] = t;
return MyParam(i, b);
}));
```
The callable may be anything that can be used to initialize a `std::function`
with the appropriate call signature. Note the callable's return object gets
`static_cast` to the fixture's parameter type, so it does not have to be of that
exact type, only convertible to it.
**Caveat:** Consider the following example.
```cpp
INSTANTIATE_TEST_SUITE_P(MyInstantiation, MyTestSuite,
ConvertGenerator(Values(std::string("s")), [](std::string_view s) { ... }));
```
The `string` argument gets copied into the factory object returned by `Values`.
Then, because the generated type deduced from the lambda is `string_view`, the
factory object spawns a generator that holds a `string_view` referencing that
`string`. Unfortunately, by the time this generator gets invoked, the factory
object is gone and the `string_view` is dangling.
To overcome this problem you can specify the generated type explicitly:
`ConvertGenerator<std::string>(Values(std::string("s")), [](std::string_view s)
{ ... })`. Alternatively, you can change the lambda's signature to take a
`std::string` or a `const std::string&` (the latter will not leave you with a
dangling reference because the type deduction strips off the reference and the
`const`).
### TYPED_TEST_SUITE {#TYPED_TEST_SUITE}
`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)`
`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`,`*`NameGenerator`*`)`
Defines a typed test suite based on the test fixture *`TestFixtureName`*. The
test suite name is *`TestFixtureName`*.
@ -247,7 +147,7 @@ type, for example:
```cpp
template <typename T>
class MyFixture : public testing::Test {
class MyFixture : public ::testing::Test {
public:
...
using List = std::list<T>;
@ -267,22 +167,6 @@ TYPED_TEST_SUITE(MyFixture, MyTypes);
The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE`
macro to parse correctly.
The optional third argument *`NameGenerator`* allows specifying a class that
exposes a templated static function `GetName(int)`. For example:
```cpp
class NameGenerator {
public:
template <typename T>
static std::string GetName(int) {
if constexpr (std::is_same_v<T, char>) return "char";
if constexpr (std::is_same_v<T, int>) return "int";
if constexpr (std::is_same_v<T, unsigned int>) return "unsignedInt";
}
};
TYPED_TEST_SUITE(MyFixture, MyTypes, NameGenerator);
```
See also [`TYPED_TEST`](#TYPED_TEST) and
[Typed Tests](../advanced.md#typed-tests) for more information.
@ -392,8 +276,7 @@ must be registered with
The argument *`InstantiationName`* is a unique name for the instantiation of the
test suite, to distinguish between multiple instantiations. In test output, the
instantiation name is added as a prefix to the test suite name
*`TestSuiteName`*. If *`InstantiationName`* is empty
(`INSTANTIATE_TYPED_TEST_SUITE_P(, ...)`), no prefix is added.
*`TestSuiteName`*.
The argument *`Types`* is a [`Types`](#Types) object representing the list of
types to run the tests on, for example:
@ -440,7 +323,7 @@ Then the test code should look like:
```cpp
namespace my_namespace {
class MyClassTest : public testing::Test {
class MyClassTest : public ::testing::Test {
...
};
@ -503,7 +386,7 @@ GoogleTest defines the following classes and types to help with writing tests.
### AssertionResult {#AssertionResult}
`testing::AssertionResult`
`::testing::AssertionResult`
A class for indicating whether an assertion was successful.
@ -517,14 +400,14 @@ To create an instance of this class, use one of the factory functions
### AssertionException {#AssertionException}
`testing::AssertionException`
`::testing::AssertionException`
Exception which can be thrown from
[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult).
### EmptyTestEventListener {#EmptyTestEventListener}
`testing::EmptyTestEventListener`
`::testing::EmptyTestEventListener`
Provides an empty implementation of all methods in the
[`TestEventListener`](#TestEventListener) interface, such that a subclass only
@ -532,7 +415,7 @@ needs to override the methods it cares about.
### Environment {#Environment}
`testing::Environment`
`::testing::Environment`
Represents a global test environment. See
[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down).
@ -553,7 +436,7 @@ Override this to define how to tear down the environment.
### ScopedTrace {#ScopedTrace}
`testing::ScopedTrace`
`::testing::ScopedTrace`
An instance of this class causes a trace to be included in every test failure
message generated by code in the scope of the lifetime of the `ScopedTrace`
@ -569,7 +452,7 @@ ScopedTrace(const char* file, int line, const T& message)
Example usage:
```cpp
testing::ScopedTrace trace("file.cc", 123, "message");
::testing::ScopedTrace trace("file.cc", 123, "message");
```
The resulting trace includes the given source file path and line number, and the
@ -580,7 +463,7 @@ See also [`SCOPED_TRACE`](#SCOPED_TRACE).
### Test {#Test}
`testing::Test`
`::testing::Test`
The abstract class that all tests inherit from. `Test` is not copyable.
@ -668,7 +551,7 @@ after running each individual test.
### TestWithParam {#TestWithParam}
`testing::TestWithParam<T>`
`::testing::TestWithParam<T>`
A convenience class which inherits from both [`Test`](#Test) and
[`WithParamInterface<T>`](#WithParamInterface).
@ -788,7 +671,7 @@ during execution of `SetUpTestSuite` and `TearDownTestSuite`.
### TestInfo {#TestInfo}
`testing::TestInfo`
`::testing::TestInfo`
Stores information about a test.
@ -867,7 +750,7 @@ Returns the result of the test. See [`TestResult`](#TestResult).
### TestParamInfo {#TestParamInfo}
`testing::TestParamInfo<T>`
`::testing::TestParamInfo<T>`
Describes a parameter to a value-parameterized test. The type `T` is the type of
the parameter.
@ -877,7 +760,7 @@ and its integer index respectively.
### UnitTest {#UnitTest}
`testing::UnitTest`
`::testing::UnitTest`
This class contains information about the test program.
@ -1045,7 +928,7 @@ GoogleTest. See [`TestEventListeners`](#TestEventListeners).
### TestEventListener {#TestEventListener}
`testing::TestEventListener`
`::testing::TestEventListener`
The interface for tracing execution of tests. The methods below are listed in
the order the corresponding events are fired.
@ -1143,7 +1026,7 @@ Fired after all test activities have ended.
### TestEventListeners {#TestEventListeners}
`testing::TestEventListeners`
`::testing::TestEventListeners`
Lets users add listeners to track events in GoogleTest.
@ -1188,7 +1071,7 @@ the caller and makes this function return `NULL` the next time.
### TestPartResult {#TestPartResult}
`testing::TestPartResult`
`::testing::TestPartResult`
A copyable object representing the result of a test part (i.e. an assertion or
an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`).
@ -1270,7 +1153,7 @@ Returns true if and only if the test part failed.
### TestProperty {#TestProperty}
`testing::TestProperty`
`::testing::TestProperty`
A copyable object representing a user-specified test property which can be
output as a key/value string pair.
@ -1297,7 +1180,7 @@ Sets a new value, overriding the previous one.
### TestResult {#TestResult}
`testing::TestResult`
`::testing::TestResult`
Contains information about the result of a single test.
@ -1378,20 +1261,20 @@ range, aborts the program.
### TimeInMillis {#TimeInMillis}
`testing::TimeInMillis`
`::testing::TimeInMillis`
An integer type representing time in milliseconds.
### Types {#Types}
`testing::Types<T...>`
`::testing::Types<T...>`
Represents a list of types for use in typed tests and type-parameterized tests.
The template argument `T...` can be any number of types, for example:
```
testing::Types<char, int, unsigned int>
::testing::Types<char, int, unsigned int>
```
See [Typed Tests](../advanced.md#typed-tests) and
@ -1400,7 +1283,7 @@ information.
### WithParamInterface {#WithParamInterface}
`testing::WithParamInterface<T>`
`::testing::WithParamInterface<T>`
The pure interface class that all value-parameterized tests inherit from.
@ -1426,16 +1309,14 @@ tests.
### InitGoogleTest {#InitGoogleTest}
`void testing::InitGoogleTest(int* argc, char** argv)` \
`void testing::InitGoogleTest(int* argc, wchar_t** argv)` \
`void testing::InitGoogleTest()`
`void ::testing::InitGoogleTest(int* argc, char** argv)` \
`void ::testing::InitGoogleTest(int* argc, wchar_t** argv)` \
`void ::testing::InitGoogleTest()`
Initializes GoogleTest. This must be called before calling
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line
for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it
is removed from `argv`, and `*argc` is decremented. Keep in mind that `argv`
must terminate with a `NULL` pointer (i.e. `argv[argc]` is `NULL`), which is
already the case with the default `argv` passed to `main`.
is removed from `argv`, and `*argc` is decremented.
No value is returned. Instead, the GoogleTest flag variables are updated.
@ -1447,7 +1328,7 @@ platforms where there is no `argc`/`argv`.
### AddGlobalTestEnvironment {#AddGlobalTestEnvironment}
`Environment* testing::AddGlobalTestEnvironment(Environment* env)`
`Environment* ::testing::AddGlobalTestEnvironment(Environment* env)`
Adds a test environment to the test program. Must be called before
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See
@ -1460,7 +1341,7 @@ See also [`Environment`](#Environment).
```cpp
template <typename Factory>
TestInfo* testing::RegisterTest(const char* test_suite_name, const char* test_name,
TestInfo* ::testing::RegisterTest(const char* test_suite_name, const char* test_name,
const char* type_param, const char* value_param,
const char* file, int line, Factory factory)
```
@ -1499,27 +1380,27 @@ an all-caps name.
### AssertionSuccess {#AssertionSuccess}
`AssertionResult testing::AssertionSuccess()`
`AssertionResult ::testing::AssertionSuccess()`
Creates a successful assertion result. See
[`AssertionResult`](#AssertionResult).
### AssertionFailure {#AssertionFailure}
`AssertionResult testing::AssertionFailure()`
`AssertionResult ::testing::AssertionFailure()`
Creates a failed assertion result. Use the `<<` operator to store a failure
message:
```cpp
testing::AssertionFailure() << "My failure message";
::testing::AssertionFailure() << "My failure message";
```
See [`AssertionResult`](#AssertionResult).
### StaticAssertTypeEq {#StaticAssertTypeEq}
`testing::StaticAssertTypeEq<T1, T2>()`
`::testing::StaticAssertTypeEq<T1, T2>()`
Compile-time assertion for type equality. Compiles if and only if `T1` and `T2`
are the same type. The value it returns is irrelevant.
@ -1528,7 +1409,7 @@ See [Type Assertions](../advanced.md#type-assertions) for more information.
### PrintToString {#PrintToString}
`std::string testing::PrintToString(x)`
`std::string ::testing::PrintToString(x)`
Prints any value `x` using GoogleTest's value printer.
@ -1538,7 +1419,7 @@ for more information.
### PrintToStringParamName {#PrintToStringParamName}
`std::string testing::PrintToStringParamName(TestParamInfo<T>& info)`
`std::string ::testing::PrintToStringParamName(TestParamInfo<T>& info)`
A built-in parameterized test name generator which returns the result of
[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the

View File

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

View File

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

View File

@ -5,7 +5,7 @@
# CMake build script for Google Mock.
#
# To run the tests for Google Mock itself on Linux, use 'make test' or
# ctest. You can select which tests to run using 'ctest -R regex'.
# ctest. You can select which tests to run using 'ctest -R regex'.
# For more options, run 'ctest --help'.
option(gmock_build_tests "Build all of Google Mock's own tests." OFF)
@ -36,7 +36,8 @@ endif()
# as ${gmock_SOURCE_DIR} and to the root binary directory as
# ${gmock_BINARY_DIR}.
# Language "C" is required for find_package(Threads).
cmake_minimum_required(VERSION 3.13)
cmake_minimum_required(VERSION 3.5)
cmake_policy(SET CMP0048 NEW)
project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
if (COMMAND set_up_hermetic_build)
@ -44,7 +45,7 @@ if (COMMAND set_up_hermetic_build)
endif()
# Instructs CMake to process Google Test's CMakeLists.txt and add its
# targets to the current scope. We are placing Google Test's binary
# targets to the current scope. We are placing Google Test's binary
# directory in a subdirectory of our own as VC compilation may break
# if they are the same (the default).
add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}")
@ -60,26 +61,25 @@ else()
endif()
# Although Google Test's CMakeLists.txt calls this function, the
# changes there don't affect the current scope. Therefore we have to
# changes there don't affect the current scope. Therefore we have to
# call it again here.
config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake
config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake
# Adds Google Mock's and Google Test's header directories to the search path.
# Get Google Test's include dirs from the target, gtest_SOURCE_DIR is broken
# when using fetch-content with the name "GTest".
get_target_property(gtest_include_dirs gtest INCLUDE_DIRECTORIES)
set(gmock_build_include_dirs
"${gmock_SOURCE_DIR}/include"
"${gmock_SOURCE_DIR}"
"${gtest_include_dirs}")
"${gtest_SOURCE_DIR}/include"
# This directory is needed to build directly from Google Test sources.
"${gtest_SOURCE_DIR}")
include_directories(${gmock_build_include_dirs})
########################################################################
#
# Defines the gmock & gmock_main libraries. User tests should link
# Defines the gmock & gmock_main libraries. User tests should link
# with one of them.
# Google Mock libraries. We build them using more strict warnings than what
# Google Mock libraries. We build them using more strict warnings than what
# are used for other targets, to ensure that Google Mock can be compiled by
# a user aggressive about warnings.
if (MSVC)
@ -101,18 +101,22 @@ else()
target_link_libraries(gmock_main PUBLIC gmock)
set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
endif()
string(REPLACE ";" "$<SEMICOLON>" dirs "${gmock_build_include_dirs}")
target_include_directories(gmock SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gmock_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
# If the CMake version supports it, attach header directory information
# to the targets for when we are part of a parent build (ie being pulled
# in via add_subdirectory() rather than being a standalone build).
if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
string(REPLACE ";" "$<SEMICOLON>" dirs "${gmock_build_include_dirs}")
target_include_directories(gmock SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gmock_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
endif()
########################################################################
#
# Install rules.
# Install rules
install_project(gmock gmock_main)
########################################################################
@ -122,8 +126,8 @@ install_project(gmock gmock_main)
# You can skip this section if you aren't interested in testing
# Google Mock itself.
#
# The tests are not built by default. To build them, set the
# gmock_build_tests option to ON. You can do it by running ccmake
# The tests are not built by default. To build them, set the
# gmock_build_tests option to ON. You can do it by running ccmake
# or specifying the -Dgmock_build_tests=ON flag when running cmake.
if (gmock_build_tests)
@ -132,7 +136,11 @@ if (gmock_build_tests)
enable_testing()
if (MINGW OR CYGWIN)
add_compile_options("-Wa,-mbig-obj")
if (CMAKE_VERSION VERSION_LESS "2.8.12")
add_compile_options("-Wa,-mbig-obj")
else()
add_definitions("-Wa,-mbig-obj")
endif()
endif()
############################################################
@ -188,7 +196,7 @@ if (gmock_build_tests)
cxx_shared_library(shared_gmock_main "${cxx_default}"
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
# Tests that a binary can be built with Google Mock as a shared library. On
# Tests that a binary can be built with Google Mock as a shared library. On
# some system configurations, it may not possible to run the binary without
# knowing more details about the system configurations. We do not try to run
# this binary. To get a more robust shared library coverage, configure with

View File

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

View File

@ -122,7 +122,7 @@
// MORE INFORMATION:
//
// To learn more about using these macros, please search for 'ACTION' on
// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md
// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*
@ -135,7 +135,6 @@
#endif
#include <algorithm>
#include <exception>
#include <functional>
#include <memory>
#include <string>
@ -147,7 +146,10 @@
#include "gmock/internal/gmock-port.h"
#include "gmock/internal/gmock-pp.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
namespace testing {
@ -176,15 +178,9 @@ struct BuiltInDefaultValueGetter<T, false> {
static T Get() {
Assert(false, __FILE__, __LINE__,
"Default action undefined for the function return type.");
#if defined(__GNUC__) || defined(__clang__)
__builtin_unreachable();
#elif defined(_MSC_VER)
__assume(0);
#else
return Invalid<T>();
return internal::Invalid<T>();
// The above statement will never be reached, but is required in
// order for this function to compile.
#endif
}
};
@ -196,7 +192,7 @@ struct BuiltInDefaultValueGetter<T, false> {
// other type T, the built-in default T value is undefined, and the
// function will abort the process.
template <typename T>
class [[nodiscard]] BuiltInDefaultValue {
class BuiltInDefaultValue {
public:
// This function returns true if and only if type T has a built-in default
// value.
@ -211,7 +207,7 @@ class [[nodiscard]] BuiltInDefaultValue {
// This partial specialization says that we use the same built-in
// default value for T and const T.
template <typename T>
class [[nodiscard]] BuiltInDefaultValue<const T> {
class BuiltInDefaultValue<const T> {
public:
static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
static T Get() { return BuiltInDefaultValue<T>::Get(); }
@ -220,7 +216,7 @@ class [[nodiscard]] BuiltInDefaultValue<const T> {
// This partial specialization defines the default values for pointer
// types.
template <typename T>
class [[nodiscard]] BuiltInDefaultValue<T*> {
class BuiltInDefaultValue<T*> {
public:
static bool Exists() { return true; }
static T* Get() { return nullptr; }
@ -383,7 +379,7 @@ typename std::add_const<T>::type& as_const(T& t) {
// Specialized for function types below.
template <typename F>
class [[nodiscard]] OnceAction;
class OnceAction;
// An action that can only be used once.
//
@ -421,7 +417,7 @@ class [[nodiscard]] OnceAction;
// A less-contrived example would be an action that returns an arbitrary type,
// whose &&-qualified call operator is capable of dealing with move-only types.
template <typename Result, typename... Args>
class [[nodiscard]] OnceAction<Result(Args...)> final {
class OnceAction<Result(Args...)> final {
private:
// True iff we can use the given callable type (or lvalue reference) directly
// via StdFunctionAdaptor.
@ -574,7 +570,7 @@ class [[nodiscard]] OnceAction<Result(Args...)> final {
// // Sets the default value for type T to be foo.
// DefaultValue<T>::Set(foo);
template <typename T>
class [[nodiscard]] DefaultValue {
class DefaultValue {
public:
// Sets the default value for type T; requires T to be
// copy-constructable and have a public destructor.
@ -618,7 +614,7 @@ class [[nodiscard]] DefaultValue {
private:
class ValueProducer {
public:
virtual ~ValueProducer() = default;
virtual ~ValueProducer() {}
virtual T Produce() = 0;
};
@ -651,7 +647,7 @@ class [[nodiscard]] DefaultValue {
// This partial specialization allows a user to set default values for
// reference types.
template <typename T>
class [[nodiscard]] DefaultValue<T&> {
class DefaultValue<T&> {
public:
// Sets the default value for type T&.
static void Set(T& x) { // NOLINT
@ -685,7 +681,7 @@ class [[nodiscard]] DefaultValue<T&> {
// This specialization allows DefaultValue<void>::Get() to
// compile.
template <>
class [[nodiscard]] DefaultValue<void> {
class DefaultValue<void> {
public:
static bool Exists() { return true; }
static void Get() {}
@ -701,13 +697,13 @@ T* DefaultValue<T&>::address_ = nullptr;
// Implement this interface to define an action for function type F.
template <typename F>
class [[nodiscard]] ActionInterface {
class ActionInterface {
public:
typedef typename internal::Function<F>::Result Result;
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
ActionInterface() = default;
virtual ~ActionInterface() = default;
ActionInterface() {}
virtual ~ActionInterface() {}
// Performs the action. This method is not const, as in general an
// action can have side effects and be stateful. For example, a
@ -721,7 +717,7 @@ class [[nodiscard]] ActionInterface {
};
template <typename F>
class [[nodiscard]] Action;
class Action;
// An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment)
// object that represents an action to be taken when a mock function of type
@ -730,7 +726,7 @@ class [[nodiscard]] Action;
// can view an object implementing ActionInterface<F> as a concrete action
// (including its current state), and an Action<F> object as a handle to it.
template <typename R, typename... Args>
class [[nodiscard]] Action<R(Args...)> {
class Action<R(Args...)> {
private:
using F = R(Args...);
@ -756,7 +752,7 @@ class [[nodiscard]] Action<R(Args...)> {
// Constructs a null Action. Needed for storing Action objects in
// STL containers.
Action() = default;
Action() {}
// Construct an Action from a specified callable.
// This cannot take std::function directly, because then Action would not be
@ -835,10 +831,6 @@ class [[nodiscard]] Action<R(Args...)> {
Result operator()(const InArgs&...) const {
return function_impl();
}
template <typename... InArgs>
Result operator()(const InArgs&...) {
return function_impl();
}
FunctionImpl function_impl;
};
@ -869,7 +861,7 @@ class [[nodiscard]] Action<R(Args...)> {
// the definition of Return(void) and SetArgumentPointee<N>(value) for
// complete examples.
template <typename Impl>
class [[nodiscard]] PolymorphicAction {
class PolymorphicAction {
public:
explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
@ -929,7 +921,7 @@ struct ByMoveWrapper {
// The general implementation of Return(R). Specializations follow below.
template <typename R>
class [[nodiscard]] ReturnAction final {
class ReturnAction final {
public:
explicit ReturnAction(R value) : value_(std::move(value)) {}
@ -1095,7 +1087,7 @@ class [[nodiscard]] ReturnAction final {
// the const call operator, checking at runtime that it isn't called more than
// once, since the user has declared their intent to do so by using ByMove.
template <typename T>
class [[nodiscard]] ReturnAction<ByMoveWrapper<T>> final {
class ReturnAction<ByMoveWrapper<T>> final {
public:
explicit ReturnAction(ByMoveWrapper<T> wrapper)
: state_(new State(std::move(wrapper.payload))) {}
@ -1122,7 +1114,7 @@ class [[nodiscard]] ReturnAction<ByMoveWrapper<T>> final {
};
// Implements the ReturnNull() action.
class [[nodiscard]] ReturnNullAction {
class ReturnNullAction {
public:
// Allows ReturnNull() to be used in any pointer-returning function. In C++11
// this is enforced by returning nullptr, and in non-C++11 by asserting a
@ -1134,7 +1126,7 @@ class [[nodiscard]] ReturnNullAction {
};
// Implements the Return() action.
class [[nodiscard]] ReturnVoidAction {
class ReturnVoidAction {
public:
// Allows Return() to be used in any void-returning function.
template <typename Result, typename ArgumentTuple>
@ -1147,7 +1139,7 @@ class [[nodiscard]] ReturnVoidAction {
// in any function that returns a reference to the type of x,
// regardless of the argument types.
template <typename T>
class [[nodiscard]] ReturnRefAction {
class ReturnRefAction {
public:
// Constructs a ReturnRefAction object from the reference to be returned.
explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
@ -1188,7 +1180,7 @@ class [[nodiscard]] ReturnRefAction {
// used in any function that returns a reference to the type of x,
// regardless of the argument types.
template <typename T>
class [[nodiscard]] ReturnRefOfCopyAction {
class ReturnRefOfCopyAction {
public:
// Constructs a ReturnRefOfCopyAction object from the reference to
// be returned.
@ -1229,7 +1221,7 @@ class [[nodiscard]] ReturnRefOfCopyAction {
// Implements the polymorphic ReturnRoundRobin(v) action, which can be
// used in any function that returns the element_type of v.
template <typename T>
class [[nodiscard]] ReturnRoundRobinAction {
class ReturnRoundRobinAction {
public:
explicit ReturnRoundRobinAction(std::vector<T> values) {
GTEST_CHECK_(!values.empty())
@ -1257,7 +1249,7 @@ class [[nodiscard]] ReturnRoundRobinAction {
};
// Implements the polymorphic DoDefault() action.
class [[nodiscard]] DoDefaultAction {
class DoDefaultAction {
public:
// This template type conversion operator allows DoDefault() to be
// used in any function.
@ -1270,7 +1262,7 @@ class [[nodiscard]] DoDefaultAction {
// Implements the Assign action to set a given pointer referent to a
// particular value.
template <typename T1, typename T2>
class [[nodiscard]] AssignAction {
class AssignAction {
public:
AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
@ -1284,12 +1276,12 @@ class [[nodiscard]] AssignAction {
const T2 value_;
};
#ifndef GTEST_OS_WINDOWS_MOBILE
#if !GTEST_OS_WINDOWS_MOBILE
// Implements the SetErrnoAndReturn action to simulate return from
// various system calls and libc functions.
template <typename T>
class [[nodiscard]] SetErrnoAndReturnAction {
class SetErrnoAndReturnAction {
public:
SetErrnoAndReturnAction(int errno_value, T result)
: errno_(errno_value), result_(result) {}
@ -1397,7 +1389,7 @@ class IgnoreResultAction {
void Perform(const ArgumentTuple& args) override {
// Performs the action and ignores its result.
(void)action_.Perform(args);
action_.Perform(args);
}
private:
@ -1428,19 +1420,17 @@ struct WithArgsAction {
// providing a call operator because even with a particular set of arguments
// they don't have a fixed return type.
template <
typename R, typename... Args,
typename std::enable_if<
std::is_convertible<InnerAction,
// Unfortunately we can't use the InnerSignature
// alias here; MSVC complains about the I
// parameter pack not being expanded (error C3520)
// despite it being expanded in the type alias.
// TupleElement is also an MSVC workaround.
// See its definition for details.
OnceAction<R(internal::TupleElement<
I, std::tuple<Args...>>...)>>::value,
int>::type = 0>
template <typename R, typename... Args,
typename std::enable_if<
std::is_convertible<
InnerAction,
// Unfortunately we can't use the InnerSignature alias here;
// MSVC complains about the I parameter pack not being
// expanded (error C3520) despite it being expanded in the
// type alias.
OnceAction<R(typename std::tuple_element<
I, std::tuple<Args...>>::type...)>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
struct OA {
OnceAction<InnerSignature<R, Args...>> inner_action;
@ -1455,43 +1445,17 @@ struct WithArgsAction {
return OA{std::move(inner_action)};
}
// As above, but in the case where we want to create a OnceAction from a const
// WithArgsAction. This is fine as long as the inner action doesn't need to
// move any of its state to create a OnceAction.
template <
typename R, typename... Args,
typename std::enable_if<
std::is_convertible<const InnerAction&,
OnceAction<R(internal::TupleElement<
I, std::tuple<Args...>>...)>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() const& { // NOLINT
struct OA {
OnceAction<InnerSignature<R, Args...>> inner_action;
R operator()(Args&&... args) && {
return std::move(inner_action)
.Call(std::get<I>(
std::forward_as_tuple(std::forward<Args>(args)...))...);
}
};
return OA{inner_action};
}
template <
typename R, typename... Args,
typename std::enable_if<
std::is_convertible<const InnerAction&,
// Unfortunately we can't use the InnerSignature
// alias here; MSVC complains about the I
// parameter pack not being expanded (error C3520)
// despite it being expanded in the type alias.
// TupleElement is also an MSVC workaround.
// See its definition for details.
Action<R(internal::TupleElement<
I, std::tuple<Args...>>...)>>::value,
int>::type = 0>
template <typename R, typename... Args,
typename std::enable_if<
std::is_convertible<
const InnerAction&,
// Unfortunately we can't use the InnerSignature alias here;
// MSVC complains about the I parameter pack not being
// expanded (error C3520) despite it being expanded in the
// type alias.
Action<R(typename std::tuple_element<
I, std::tuple<Args...>>::type...)>>::value,
int>::type = 0>
operator Action<R(Args...)>() const { // NOLINT
Action<InnerSignature<R, Args...>> converted(inner_action);
@ -1503,11 +1467,11 @@ struct WithArgsAction {
};
template <typename... Actions>
class [[nodiscard]] DoAllAction;
class DoAllAction;
// Base case: only a single action.
template <typename FinalAction>
class [[nodiscard]] DoAllAction<FinalAction> {
class DoAllAction<FinalAction> {
public:
struct UserConstructorTag {};
@ -1521,7 +1485,6 @@ class [[nodiscard]] DoAllAction<FinalAction> {
// providing a call operator because even with a particular set of arguments
// they don't have a fixed return type.
// We support conversion to OnceAction whenever the sub-action does.
template <typename R, typename... Args,
typename std::enable_if<
std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,
@ -1530,21 +1493,6 @@ class [[nodiscard]] DoAllAction<FinalAction> {
return std::move(final_action_);
}
// We also support conversion to OnceAction whenever the sub-action supports
// conversion to Action (since any Action can also be a OnceAction).
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<
negation<
std::is_convertible<FinalAction, OnceAction<R(Args...)>>>,
std::is_convertible<FinalAction, Action<R(Args...)>>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
return Action<R(Args...)>(std::move(final_action_));
}
// We support conversion to Action whenever the sub-action does.
template <
typename R, typename... Args,
typename std::enable_if<
@ -1561,7 +1509,7 @@ class [[nodiscard]] DoAllAction<FinalAction> {
// Recursive case: support N actions by calling the initial action and then
// calling through to the base class containing N-1 actions.
template <typename InitialAction, typename... OtherActions>
class [[nodiscard]] DoAllAction<InitialAction, OtherActions...>
class DoAllAction<InitialAction, OtherActions...>
: private DoAllAction<OtherActions...> {
private:
using Base = DoAllAction<OtherActions...>;
@ -1624,16 +1572,16 @@ class [[nodiscard]] DoAllAction<InitialAction, OtherActions...>
: Base({}, std::forward<U>(other_actions)...),
initial_action_(std::forward<T>(initial_action)) {}
// We support conversion to OnceAction whenever both the initial action and
// the rest support conversion to OnceAction.
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<std::is_convertible<
InitialAction,
OnceAction<void(InitialActionArgType<Args>...)>>,
std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
int>::type = 0>
template <typename R, typename... Args,
typename std::enable_if<
conjunction<
// Both the initial action and the rest must support
// conversion to OnceAction.
std::is_convertible<
InitialAction,
OnceAction<void(InitialActionArgType<Args>...)>>,
std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
// Return an action that first calls the initial action with arguments
// filtered through InitialActionArgType, then forwards arguments directly
@ -1656,34 +1604,12 @@ class [[nodiscard]] DoAllAction<InitialAction, OtherActions...>
};
}
// We also support conversion to OnceAction whenever the initial action
// supports conversion to Action (since any Action can also be a OnceAction).
//
// The remaining sub-actions must also be compatible, but we don't need to
// special case them because the base class deals with them.
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<
negation<std::is_convertible<
InitialAction,
OnceAction<void(InitialActionArgType<Args>...)>>>,
std::is_convertible<InitialAction,
Action<void(InitialActionArgType<Args>...)>>,
std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
int>::type = 0>
operator OnceAction<R(Args...)>() && { // NOLINT
return DoAll(
Action<void(InitialActionArgType<Args>...)>(std::move(initial_action_)),
std::move(static_cast<Base&>(*this)));
}
// We support conversion to Action whenever both the initial action and the
// rest support conversion to Action.
template <
typename R, typename... Args,
typename std::enable_if<
conjunction<
// Both the initial action and the rest must support conversion to
// Action.
std::is_convertible<const InitialAction&,
Action<void(InitialActionArgType<Args>...)>>,
std::is_convertible<const Base&, Action<R(Args...)>>>::value,
@ -1747,16 +1673,6 @@ struct SaveArgAction {
}
};
template <size_t k, typename Ptr>
struct SaveArgByMoveAction {
Ptr pointer;
template <typename... Args>
void operator()(Args&&... args) const {
*pointer = std::move(std::get<k>(std::tie(args...)));
}
};
template <size_t k, typename Ptr>
struct SaveArgPointeeAction {
Ptr pointer;
@ -1796,24 +1712,11 @@ struct SetArrayArgumentAction {
};
template <size_t k>
class [[nodiscard]] DeleteArgAction {
public:
struct DeleteArgAction {
template <typename... Args>
void operator()(const Args&... args) const {
DoDelete(std::get<k>(std::tie(args...)));
delete std::get<k>(std::tie(args...));
}
private:
template <typename T>
static void DoDelete(T* ptr) {
delete ptr;
}
template <typename T>
[[deprecated(
"DeleteArg<N> used for a non-pointer argument, it was likely migrated "
"to a smart pointer type. This action should be removed.")]]
static void DoDelete(T&) {}
};
template <typename Ptr>
@ -1836,13 +1739,6 @@ struct ThrowAction {
return [copy](Args...) -> R { throw copy; };
}
};
struct RethrowAction {
std::exception_ptr exception;
template <typename R, typename... Args>
operator Action<R(Args...)>() const { // NOLINT
return [ex = exception](Args...) -> R { std::rethrow_exception(ex); };
}
};
#endif // GTEST_HAS_EXCEPTIONS
} // namespace internal
@ -1879,13 +1775,6 @@ struct RethrowAction {
// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
typedef internal::IgnoredValue Unused;
// Deprecated single-argument DoAll.
template <typename Action>
GTEST_INTERNAL_DEPRECATE_AND_INLINE("Avoid using DoAll() for single actions")
typename std::decay<Action>::type DoAll(Action&& action) {
return std::forward<Action>(action);
}
// Creates an action that does actions a1, a2, ..., sequentially in
// each invocation. All but the last action will have a readonly view of the
// arguments.
@ -2036,7 +1925,7 @@ PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {
return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
}
#ifndef GTEST_OS_WINDOWS_MOBILE
#if !GTEST_OS_WINDOWS_MOBILE
// Creates an action that sets errno and returns the appropriate error.
template <typename T>
@ -2051,11 +1940,10 @@ PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(
// Various overloads for Invoke().
// Legacy function.
// Actions can now be implicitly constructed from callables. No need to create
// wrapper objects.
// This function exists for backwards compatibility.
template <typename FunctionImpl>
GTEST_INTERNAL_DEPRECATE_AND_INLINE(
"Actions can now be implicitly constructed from callables. No need to "
"create wrapper objects using Invoke().")
typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
return std::forward<FunctionImpl>(function_impl);
}
@ -2128,13 +2016,6 @@ internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
return {pointer};
}
// Action SaveArgByMove<k>(pointer) moves the k-th (0-based) argument of the
// mock function into *pointer.
template <size_t k, typename Ptr>
internal::SaveArgByMoveAction<k, Ptr> SaveArgByMove(Ptr pointer) {
return {pointer};
}
// Action SaveArgPointee<k>(pointer) saves the value pointed to
// by the k-th (0-based) argument of the mock function to *pointer.
template <size_t k, typename Ptr>
@ -2174,23 +2055,13 @@ internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
return {pointer};
}
#if GTEST_HAS_EXCEPTIONS
// Action Throw(exception) can be used in a mock function of any type
// to throw the given exception. Any copyable value can be thrown,
// except for std::exception_ptr, which is likely a mistake if
// thrown directly.
// to throw the given exception. Any copyable value can be thrown.
#if GTEST_HAS_EXCEPTIONS
template <typename T>
typename std::enable_if<
!std::is_base_of<std::exception_ptr, typename std::decay<T>::type>::value,
internal::ThrowAction<typename std::decay<T>::type>>::type
Throw(T&& exception) {
internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
return {std::forward<T>(exception)};
}
// Action Rethrow(exception_ptr) can be used in a mock function of any type
// to rethrow any exception_ptr. Note that the same object is thrown each time.
inline internal::RethrowAction Rethrow(std::exception_ptr exception) {
return {std::move(exception)};
}
#endif // GTEST_HAS_EXCEPTIONS
namespace internal {
@ -2239,13 +2110,13 @@ struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
R operator()(Args&&... arg) const {
static constexpr size_t kMaxArgs =
sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
return Apply(std::make_index_sequence<kMaxArgs>{},
std::make_index_sequence<10 - kMaxArgs>{},
return Apply(MakeIndexSequence<kMaxArgs>{},
MakeIndexSequence<10 - kMaxArgs>{},
args_type{std::forward<Args>(arg)...});
}
template <std::size_t... arg_id, std::size_t... excess_id>
R Apply(std::index_sequence<arg_id...>, std::index_sequence<excess_id...>,
R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
const args_type& args) const {
// Impl need not be specific to the signature of action being implemented;
// only the implementing function body needs to have all of the specific
@ -2278,9 +2149,9 @@ template <typename F, typename Impl>
}
#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
, [[maybe_unused]] const arg##i##_type& arg##i
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
[[maybe_unused]] const args_type& args GMOCK_PP_REPEAT( \
, const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
GMOCK_INTERNAL_ARG_UNUSED, , 10)
#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
@ -2345,8 +2216,8 @@ template <typename F, typename Impl>
std::shared_ptr<const gmock_Impl> impl_; \
}; \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
[[nodiscard]] inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)); \
inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
@ -2381,7 +2252,7 @@ template <typename F, typename Impl>
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
}; \
}; \
[[nodiscard]] inline name##Action name(); \
inline name##Action name() GTEST_MUST_USE_RESULT_; \
inline name##Action name() { return name##Action(); } \
template <typename function_type, typename return_type, typename args_type, \
GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
@ -2420,6 +2291,8 @@ template <typename F, typename Impl>
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_

View File

@ -63,9 +63,9 @@ namespace testing {
// management as Cardinality objects can now be copied like plain values.
// The implementation of a cardinality.
class [[nodiscard]] CardinalityInterface {
class CardinalityInterface {
public:
virtual ~CardinalityInterface() = default;
virtual ~CardinalityInterface() {}
// Conservative estimate on the lower/upper bound of the number of
// calls allowed.
@ -88,11 +88,11 @@ class [[nodiscard]] CardinalityInterface {
// object that specifies how many times a mock function is expected to
// be called. The implementation of Cardinality is just a std::shared_ptr
// to const CardinalityInterface. Don't inherit from Cardinality!
class GTEST_API_ [[nodiscard]] Cardinality {
class GTEST_API_ Cardinality {
public:
// Constructs a null cardinality. Needed for storing Cardinality
// objects in STL containers.
Cardinality() = default;
Cardinality() {}
// Constructs a Cardinality from its implementation.
explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -521,14 +521,14 @@
GMOCK_INTERNAL_DECL_##value_params) \
GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
= default; \
, : impl_(std::make_shared<gmock_Impl>( \
GMOCK_INTERNAL_LIST_##value_params)){}) \
, \
: impl_(std::make_shared<gmock_Impl>( \
GMOCK_INTERNAL_LIST_##value_params)){}) \
GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \
name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \
##value_params \
GMOCK_ACTION_CLASS_(name, value_params)(GMOCK_ACTION_CLASS_( \
name, value_params) &&) noexcept GMOCK_INTERNAL_DEFN_COPY_ \
##value_params template <typename F> \
##value_params GMOCK_ACTION_CLASS_(name, value_params)( \
GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept \
GMOCK_INTERNAL_DEFN_COPY_##value_params template <typename F> \
operator ::testing::Action<F>() const { \
return GMOCK_PP_IF( \
GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \
@ -550,10 +550,10 @@
}; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
[[nodiscard]] GMOCK_ACTION_CLASS_( \
GMOCK_ACTION_CLASS_( \
name, value_params)<GMOCK_INTERNAL_LIST_##template_params \
GMOCK_INTERNAL_LIST_TYPE_##value_params> \
name(GMOCK_INTERNAL_DECL_##value_params); \
name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \
template <GMOCK_INTERNAL_DECL_##template_params \
GMOCK_INTERNAL_DECL_TYPE_##value_params> \
inline GMOCK_ACTION_CLASS_( \
@ -582,7 +582,10 @@ namespace testing {
// the macro definition, as the warnings are generated when the macro
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
namespace internal {
@ -591,23 +594,21 @@ namespace internal {
// Overloads for other custom-callables are provided in the
// internal/custom/gmock-generated-actions.h header.
template <typename F, typename... Args>
auto InvokeArgument(F &&f,
Args... args) -> decltype(std::forward<F>(f)(args...)) {
return std::forward<F>(f)(args...);
auto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {
return f(args...);
}
template <std::size_t index, typename... Params>
struct InvokeArgumentAction {
template <typename... Args,
typename = typename std::enable_if<(index < sizeof...(Args))>::type>
auto operator()(Args &&...args) const
-> decltype(internal::InvokeArgument(
std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
std::declval<const Params &>()...)) {
internal::FlatTuple<Args &&...> args_tuple(FlatTupleConstructTag{},
std::forward<Args>(args)...);
return params.Apply([&](const Params &...unpacked_params) {
auto &&callable = std::move(args_tuple.template Get<index>());
auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument(
std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),
std::declval<const Params&>()...)) {
internal::FlatTuple<Args&&...> args_tuple(FlatTupleConstructTag{},
std::forward<Args>(args)...);
return params.Apply([&](const Params&... unpacked_params) {
auto&& callable = args_tuple.template Get<index>();
return internal::InvokeArgument(
std::forward<decltype(callable)>(callable), unpacked_params...);
});
@ -647,12 +648,14 @@ struct InvokeArgumentAction {
// later.
template <std::size_t index, typename... Params>
internal::InvokeArgumentAction<index, typename std::decay<Params>::type...>
InvokeArgument(Params &&...params) {
InvokeArgument(Params&&... params) {
return {internal::FlatTuple<typename std::decay<Params>::type...>(
internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};
}
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
} // namespace testing

View File

@ -40,58 +40,30 @@
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_
#include <ostream>
#include <string>
#include "gmock/gmock-matchers.h"
namespace testing {
// Silence C4100 (unreferenced formal
// parameter) for MSVC
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#if defined(_MSC_VER) && (_MSC_VER == 1900)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#if (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 14
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#pragma warning(disable : 4800)
#endif
#endif
namespace internal {
// Implements the polymorphic IsEmpty matcher, which
// can be used as a Matcher<T> as long as T is either a container that defines
// empty() and size() (e.g. std::vector or std::string), or a C-style string.
class [[nodiscard]] 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;
// Defines a matcher that matches an empty container. The container must
// support both size() and empty(), which all STL-like containers provide.
MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
if (arg.empty()) {
return true;
}
// Matches C-style strings.
bool MatchAndExplain(const char* s, MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener);
}
// Describes what this matcher matches.
void DescribeTo(std::ostream* os) const { *os << "is empty"; }
void DescribeNegationTo(std::ostream* os) const { *os << "isn't empty"; }
};
} // namespace internal
// Creates a polymorphic matcher that matches an empty container or C-style
// string. The container must support both size() and empty(), which all
// STL-like containers provide.
inline PolymorphicMatcher<internal::IsEmptyMatcher> IsEmpty() {
return MakePolymorphicMatcher(internal::IsEmptyMatcher());
*result_listener << "whose size is " << arg.size();
return false;
}
// Define a matcher that matches a value that evaluates in boolean
@ -110,10 +82,9 @@ MATCHER(IsFalse, negation ? "is true" : "is false") {
return !static_cast<bool>(arg);
}
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#ifdef _MSC_VER
#pragma warning(pop)
#endif
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
} // namespace testing

View File

@ -71,11 +71,11 @@
namespace testing {
template <class MockClass>
class [[nodiscard]] NiceMock;
class NiceMock;
template <class MockClass>
class [[nodiscard]] NaggyMock;
class NaggyMock;
template <class MockClass>
class [[nodiscard]] StrictMock;
class StrictMock;
namespace internal {
template <typename T>
@ -98,7 +98,7 @@ constexpr bool HasStrictnessModifier() {
// deregistration. This guarantees that MockClass's constructor and destructor
// run with the same level of strictness as its instance methods.
#if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) && \
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \
(defined(_MSC_VER) || defined(__clang__))
// We need to mark these classes with this declspec to ensure that
// the empty base class optimization is performed.
@ -108,7 +108,7 @@ constexpr bool HasStrictnessModifier() {
#endif
template <typename Base>
class [[nodiscard]] NiceMockImpl {
class NiceMockImpl {
public:
NiceMockImpl() {
::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this));
@ -120,7 +120,7 @@ class [[nodiscard]] NiceMockImpl {
};
template <typename Base>
class [[nodiscard]] NaggyMockImpl {
class NaggyMockImpl {
public:
NaggyMockImpl() {
::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this));
@ -132,7 +132,7 @@ class [[nodiscard]] NaggyMockImpl {
};
template <typename Base>
class [[nodiscard]] StrictMockImpl {
class StrictMockImpl {
public:
StrictMockImpl() {
::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this));
@ -146,7 +146,7 @@ class [[nodiscard]] StrictMockImpl {
} // namespace internal
template <class MockClass>
class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
: private internal::NiceMockImpl<MockClass>,
public MockClass {
public:
@ -187,7 +187,7 @@ class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock
};
template <class MockClass>
class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
: private internal::NaggyMockImpl<MockClass>,
public MockClass {
static_assert(!internal::HasStrictnessModifier<MockClass>(),
@ -229,7 +229,7 @@ class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock
};
template <class MockClass>
class [[nodiscard]] GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock
: private internal::StrictMockImpl<MockClass>,
public MockClass {
public:

View File

@ -65,7 +65,6 @@
#include <functional>
#include <map>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
@ -204,9 +203,6 @@ class GTEST_API_ UntypedFunctionMockerBase {
using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
struct UninterestingCallCleanupHandler;
struct FailureCleanupHandler;
// Returns an Expectation object that references and co-owns exp,
// which must be an expectation on this mock function.
Expectation GetHandleOf(ExpectationBase* exp);
@ -566,7 +562,7 @@ class ExpectationSet {
typedef Expectation::Set::value_type value_type;
// Constructs an empty set.
ExpectationSet() = default;
ExpectationSet() {}
// This single-argument ctor must not be explicit, in order to support the
// ExpectationSet es = EXPECT_CALL(...);
@ -660,7 +656,7 @@ class GTEST_API_ InSequence {
InSequence(const InSequence&) = delete;
InSequence& operator=(const InSequence&) = delete;
};
} GTEST_ATTRIBUTE_UNUSED_;
namespace internal {
@ -710,12 +706,6 @@ class GTEST_API_ ExpectationBase {
// describes it to the ostream.
virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
// Do not rely on this for correctness.
// This is only for making human-readable test output easier to understand.
void UntypedDescription(std::string description) {
description_ = std::move(description);
}
protected:
friend class ::testing::Expectation;
friend class UntypedFunctionMockerBase;
@ -782,10 +772,6 @@ class GTEST_API_ ExpectationBase {
retired_ = true;
}
// Returns a human-readable description of this expectation.
// Do not rely on this for correctness. It is only for human readability.
const std::string& GetDescription() const { return description_; }
// Returns true if and only if this expectation is satisfied.
bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
@ -845,7 +831,6 @@ class GTEST_API_ ExpectationBase {
const char* file_; // The file that contains the expectation.
int line_; // The line number of the expectation.
const std::string source_text_; // The EXPECT_CALL(...) source text.
std::string description_; // User-readable name for the expectation.
// True if and only if the cardinality is specified explicitly.
bool cardinality_specified_;
Cardinality cardinality_; // The cardinality of the expectation.
@ -868,7 +853,7 @@ class GTEST_API_ ExpectationBase {
Clause last_clause_;
mutable bool action_count_checked_; // Under mutex_.
mutable Mutex mutex_; // Protects action_count_checked_.
}; // class ExpectationBase
}; // class ExpectationBase
template <typename F>
class TypedExpectation;
@ -924,13 +909,6 @@ class TypedExpectation<R(Args...)> : public ExpectationBase {
return *this;
}
// Do not rely on this for correctness.
// This is only for making human-readable test output easier to understand.
TypedExpectation& Description(std::string name) {
ExpectationBase::UntypedDescription(std::move(name));
return *this;
}
// Implements the .Times() clause.
TypedExpectation& Times(const Cardinality& a_cardinality) {
ExpectationBase::UntypedTimes(a_cardinality);
@ -1221,15 +1199,10 @@ class TypedExpectation<R(Args...)> : public ExpectationBase {
::std::ostream* why)
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
g_gmock_mutex.AssertHeld();
const ::std::string& expectation_description = GetDescription();
if (IsSaturated()) {
// We have an excessive call.
IncrementCallCount();
*what << "Mock function ";
if (!expectation_description.empty()) {
*what << "\"" << expectation_description << "\" ";
}
*what << "called more times than expected - ";
*what << "Mock function called more times than expected - ";
mocker->DescribeDefaultActionTo(args, what);
DescribeCallCountTo(why);
@ -1244,11 +1217,7 @@ class TypedExpectation<R(Args...)> : public ExpectationBase {
}
// Must be done after IncrementCount()!
*what << "Mock function ";
if (!expectation_description.empty()) {
*what << "\"" << expectation_description << "\" ";
}
*what << "call matches " << source_text() << "...\n";
*what << "Mock function call matches " << source_text() << "...\n";
return &(GetCurrentAction(mocker, args));
}
@ -1292,10 +1261,10 @@ class MockSpec {
: function_mocker_(function_mocker), matchers_(matchers) {}
// Adds a new default action spec to the function mocker and returns
// the newly created spec. .WillByDefault() must be called on the returned
// object.
[[nodiscard]] internal::OnCallSpec<F>& InternalDefaultActionSetAt(
const char* file, int line, const char* obj, const char* call) {
// the newly created spec.
internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file,
int line, const char* obj,
const char* call) {
LogWithLocation(internal::kInfo, file, line,
std::string("ON_CALL(") + obj + ", " + call + ") invoked");
return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
@ -1399,41 +1368,6 @@ class Cleanup final {
std::function<void()> f_;
};
struct UntypedFunctionMockerBase::UninterestingCallCleanupHandler {
CallReaction reaction;
std::stringstream& ss;
~UninterestingCallCleanupHandler() {
ReportUninterestingCall(reaction, ss.str());
}
};
struct UntypedFunctionMockerBase::FailureCleanupHandler {
std::stringstream& ss;
std::stringstream& why;
std::stringstream& loc;
const ExpectationBase* untyped_expectation;
bool found;
bool is_excessive;
~FailureCleanupHandler() {
ss << "\n" << why.str();
if (!found) {
// No expectation matches this call - reports a failure.
Expect(false, nullptr, -1, ss.str());
} else if (is_excessive) {
// We had an upper-bound violation and the failure message is in ss.
Expect(false, untyped_expectation->file(), untyped_expectation->line(),
ss.str());
} else {
// We had an expected call and the matching expectation is
// described in ss.
Log(kInfo, loc.str() + ss.str(), 2);
}
}
};
template <typename F>
class FunctionMocker;
@ -1446,7 +1380,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
FunctionMocker() = default;
FunctionMocker() {}
// There is no generally useful and implementable semantics of
// copying a mock object, so copying a mock is usually a user error.
@ -1467,7 +1401,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
// function have been satisfied. If not, it will report Google Test
// non-fatal failures for the violations.
~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
VerifyAndClearExpectationsLocked();
Mock::UnregisterLocked(this);
ClearDefaultActionsLocked();
@ -1530,7 +1464,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
UntypedOnCallSpecs specs_to_delete;
untyped_on_call_specs_.swap(specs_to_delete);
g_gmock_mutex.unlock();
g_gmock_mutex.Unlock();
for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
it != specs_to_delete.end(); ++it) {
delete static_cast<const OnCallSpec<F>*>(*it);
@ -1538,7 +1472,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
// Lock the mutex again, since the caller expects it to be locked when we
// return.
g_gmock_mutex.lock();
g_gmock_mutex.Lock();
}
// Returns the result of invoking this mock function with the given
@ -1646,7 +1580,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
const ArgumentTuple& args =
*static_cast<const ArgumentTuple*>(untyped_args);
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
if (exp == nullptr) { // A match wasn't found.
this->FormatUnexpectedCallMessageLocked(args, what, why);
@ -1832,14 +1766,8 @@ R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
//
// We use RAII to do the latter in case R is void or a non-moveable type. In
// either case we can't assign it to a local variable.
//
// Note that std::bind() is essential here.
// We *don't* use any local callback types (like lambdas).
// Doing so slows down compilation dramatically because the *constructor* of
// std::function<T> is re-instantiated with different template
// parameters each time.
const UninterestingCallCleanupHandler report_uninteresting_call = {reaction,
ss};
const Cleanup report_uninteresting_call(
[&] { ReportUninterestingCall(reaction, ss.str()); });
return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
}
@ -1883,13 +1811,22 @@ R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
//
// We use RAII to do the latter in case R is void or a non-moveable type. In
// either case we can't assign it to a local variable.
//
// Note that we *don't* use any local callback types (like lambdas) here.
// Doing so slows down compilation dramatically because the *constructor* of
// std::function<T> is re-instantiated with different template
// parameters each time.
const FailureCleanupHandler handle_failures = {
ss, why, loc, untyped_expectation, found, is_excessive};
const Cleanup handle_failures([&] {
ss << "\n" << why.str();
if (!found) {
// No expectation matches this call - reports a failure.
Expect(false, nullptr, -1, ss.str());
} else if (is_excessive) {
// We had an upper-bound violation and the failure message is in ss.
Expect(false, untyped_expectation->file(), untyped_expectation->line(),
ss.str());
} else {
// We had an expected call and the matching expectation is
// described in ss.
Log(kInfo, loc.str() + ss.str(), 2);
}
});
return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
ss);

View File

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

View File

@ -44,7 +44,6 @@
#include <ostream> // NOLINT
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "gmock/internal/gmock-port.h"
@ -59,7 +58,11 @@ namespace internal {
// Silence MSVC C4100 (unreferenced formal parameter) and
// C4805('==': unsafe mix of type 'const int' and type 'const bool')
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4805)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4805)
#endif
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
@ -92,24 +95,6 @@ inline Element* GetRawPointer(Element* p) {
return p;
}
// Default definitions for all compilers.
// NOTE: If you implement support for other compilers, make sure to avoid
// unexpected overlaps.
// (e.g., Clang also processes #pragma GCC, and clang-cl also handles _MSC_VER.)
#define GMOCK_INTERNAL_WARNING_PUSH()
#define GMOCK_INTERNAL_WARNING_CLANG(Level, Name)
#define GMOCK_INTERNAL_WARNING_POP()
#if defined(__clang__)
#undef GMOCK_INTERNAL_WARNING_PUSH
#define GMOCK_INTERNAL_WARNING_PUSH() _Pragma("clang diagnostic push")
#undef GMOCK_INTERNAL_WARNING_CLANG
#define GMOCK_INTERNAL_WARNING_CLANG(Level, Warning) \
_Pragma(GMOCK_PP_INTERNAL_STRINGIZE(clang diagnostic Level Warning))
#undef GMOCK_INTERNAL_WARNING_POP
#define GMOCK_INTERNAL_WARNING_POP() _Pragma("clang diagnostic pop")
#endif
// MSVC treats wchar_t as a native type usually, but treats it as the
// same as unsigned short when the compiler option /Zc:wchar_t- is
// specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
@ -220,12 +205,12 @@ using LosslessArithmeticConvertible =
// This interface knows how to report a Google Mock failure (either
// non-fatal or fatal).
class [[nodiscard]] FailureReporterInterface {
class FailureReporterInterface {
public:
// The type of a failure (either non-fatal or fatal).
enum FailureType { kNonfatal, kFatal };
virtual ~FailureReporterInterface() = default;
virtual ~FailureReporterInterface() {}
// Reports a failure that occurred at the given source file location.
virtual void ReportFailure(FailureType type, const char* file, int line,
@ -296,19 +281,22 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
//
// ON_CALL(mock, Method({}, nullptr))...
//
class [[nodiscard]] WithoutMatchers {
class WithoutMatchers {
private:
WithoutMatchers() = default;
friend
#ifdef GTEST_OS_WINDOWS
GTEST_API_
#endif
WithoutMatchers GetWithoutMatchers();
WithoutMatchers() {}
friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
};
// Internal use only: access the singleton instance of WithoutMatchers.
GTEST_API_ WithoutMatchers GetWithoutMatchers();
// Disable MSVC warnings for infinite recursion, since in this case the
// recursion is unreachable.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4717)
#endif
// Invalid<T>() is usable as an expression of type T, but will terminate
// the program with an assertion failure if actually run. This is useful
// when a value of type T is needed for compilation, but the statement
@ -316,8 +304,7 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers();
// crashes).
template <typename T>
inline T Invalid() {
Assert(/*condition=*/false, /*file=*/"", /*line=*/-1,
"Internal error: attempt to return invalid value");
Assert(false, "", -1, "Internal error: attempt to return invalid value");
#if defined(__GNUC__) || defined(__clang__)
__builtin_unreachable();
#elif defined(_MSC_VER)
@ -327,6 +314,10 @@ inline T Invalid() {
#endif
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// Given a raw type (i.e. having no top-level reference or const
// modifier) RawContainer that's either an STL-style container or a
// native array, class StlContainerView<RawContainer> has the
@ -344,7 +335,7 @@ inline T Invalid() {
// This generic version is used when RawContainer itself is already an
// STL-style container.
template <class RawContainer>
class [[nodiscard]] StlContainerView {
class StlContainerView {
public:
typedef RawContainer type;
typedef const type& const_reference;
@ -359,7 +350,7 @@ class [[nodiscard]] StlContainerView {
// This specialization is used when RawContainer is a native array type.
template <typename Element, size_t N>
class [[nodiscard]] StlContainerView<Element[N]> {
class StlContainerView<Element[N]> {
public:
typedef typename std::remove_const<Element>::type RawElement;
typedef internal::NativeArray<RawElement> type;
@ -383,7 +374,7 @@ class [[nodiscard]] StlContainerView<Element[N]> {
// This specialization is used when RawContainer is a native array
// represented as a (pointer, size) tuple.
template <typename ElementPointer, typename Size>
class [[nodiscard]] StlContainerView< ::std::tuple<ElementPointer, Size> > {
class StlContainerView< ::std::tuple<ElementPointer, Size> > {
public:
typedef typename std::remove_const<
typename std::pointer_traits<ElementPointer>::element_type>::type
@ -425,7 +416,7 @@ struct RemoveConstFromKey<std::pair<const K, V> > {
GTEST_API_ void IllegalDoDefault(const char* file, int line);
template <typename F, typename Tuple, size_t... Idx>
auto ApplyImpl(F&& f, Tuple&& args, std::index_sequence<Idx...>)
auto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)
-> decltype(std::forward<F>(f)(
std::get<Idx>(std::forward<Tuple>(args))...)) {
return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
@ -433,13 +424,12 @@ auto ApplyImpl(F&& f, Tuple&& args, std::index_sequence<Idx...>)
// Apply the function to a tuple of arguments.
template <typename F, typename Tuple>
auto Apply(F&& f, Tuple&& args)
-> decltype(ApplyImpl(
std::forward<F>(f), std::forward<Tuple>(args),
std::make_index_sequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>())) {
auto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl(
std::forward<F>(f), std::forward<Tuple>(args),
MakeIndexSequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
std::make_index_sequence<std::tuple_size<
MakeIndexSequence<std::tuple_size<
typename std::remove_reference<Tuple>::type>::value>());
}
@ -471,16 +461,14 @@ struct Function<R(Args...)> {
using MakeResultIgnoredValue = IgnoredValue(Args...);
};
// Workaround for MSVC error C2039: 'type': is not a member of 'std'
// when std::tuple_element is used.
// See: https://github.com/google/googletest/issues/3931
// Can be replaced with std::tuple_element_t in C++14.
template <size_t I, typename T>
using TupleElement = typename std::tuple_element<I, T>::type;
template <typename R, typename... Args>
constexpr size_t Function<R(Args...)>::ArgumentCount;
bool Base64Unescape(const std::string& encoded, std::string* decoded);
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4805
#ifdef _MSC_VER
#pragma warning(pop)
#endif
} // namespace internal
} // namespace testing

View File

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

View File

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

View File

@ -41,10 +41,8 @@
#include <cctype>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <ostream> // NOLINT
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
@ -89,7 +87,7 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
(!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) {
if (starts_new_word && !result.empty()) result += ' ';
if (starts_new_word && result != "") result += ' ';
result += ToLower(*p);
}
}
@ -156,7 +154,7 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
if (!LogIsVisible(severity)) return;
// Ensures that logs from different threads don't interleave.
MutexLock l(g_log_mutex);
MutexLock l(&g_log_mutex);
if (severity == kWarning) {
// Prints a GMOCK WARNING marker to make the warnings easily searchable.
@ -183,7 +181,7 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message,
}
std::cout << "Stack trace:\n"
<< ::testing::internal::GetCurrentOsStackTraceExceptTop(
actual_to_skip);
::testing::UnitTest::GetInstance(), actual_to_skip);
}
std::cout << ::std::flush;
}
@ -200,26 +198,20 @@ GTEST_API_ void IllegalDoDefault(const char* file, int line) {
"the variable in various places.");
}
constexpr char UndoWebSafeEncoding(char c) {
return c == '-' ? '+' : c == '_' ? '/' : c;
}
constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
return *base64 == 0 ? static_cast<char>(65)
: *base64 == c
? carry
: UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1));
return *base64 == 0 ? static_cast<char>(65)
: *base64 == c ? carry
: UnBase64Impl(c, base64 + 1, carry + 1);
}
template <size_t... I>
constexpr std::array<char, 256> UnBase64Impl(std::index_sequence<I...>,
constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,
const char* const base64) {
return {
{UnBase64Impl(UndoWebSafeEncoding(static_cast<char>(I)), base64, 0)...}};
return {{UnBase64Impl(static_cast<char>(I), base64, 0)...}};
}
constexpr std::array<char, 256> UnBase64(const char* const base64) {
return UnBase64Impl(std::make_index_sequence<256>{}, base64);
return UnBase64Impl(MakeIndexSequence<256>{}, base64);
}
static constexpr char kBase64[] =

View File

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

View File

@ -40,7 +40,6 @@
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
@ -49,17 +48,17 @@
#include "gtest/gtest.h"
#include "gtest/internal/gtest-port.h"
#if defined(GTEST_OS_CYGWIN) || defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC)
#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
#include <unistd.h> // NOLINT
#endif
#ifdef GTEST_OS_QURT
#include <qurt_event.h>
#endif
// Silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#ifdef _MSC_VER
#if _MSC_VER == 1900
#pragma warning(push)
#pragma warning(disable : 4800)
#endif
#endif
namespace testing {
@ -96,7 +95,7 @@ ExpectationBase::ExpectationBase(const char* a_file, int a_line,
action_count_checked_(false) {}
// Destructs an ExpectationBase object.
ExpectationBase::~ExpectationBase() = default;
ExpectationBase::~ExpectationBase() {}
// Explicitly specifies the cardinality of this expectation. Used by
// the subclasses to implement the .Times() clause.
@ -212,7 +211,7 @@ void ExpectationBase::CheckActionCountIfNotDone() const
GTEST_LOCK_EXCLUDED_(mutex_) {
bool should_check = false;
{
MutexLock l(mutex_);
MutexLock l(&mutex_);
if (!action_count_checked_) {
action_count_checked_ = true;
should_check = true;
@ -293,12 +292,12 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
Log(kWarning,
msg +
"\nNOTE: You can safely ignore the above warning unless this "
"call should not happen. Do not suppress it by adding "
"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/"
"https://github.com/google/googletest/blob/master/docs/"
"gmock_cook_book.md#"
"knowing-when-to-expect-useoncall for details.\n",
"knowing-when-to-expect for details.\n",
stack_frames_to_skip);
break;
default: // FAIL
@ -309,7 +308,7 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
UntypedFunctionMockerBase::UntypedFunctionMockerBase()
: mock_obj_(nullptr), name_("") {}
UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;
UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
// Sets the mock object this mock method belongs to, and registers
// this information in the global mock registry. Will be called
@ -318,7 +317,7 @@ UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;
void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
{
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
mock_obj_ = mock_obj;
}
Mock::Register(mock_obj, this);
@ -332,7 +331,7 @@ void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
// We protect name_ under g_gmock_mutex in case this mock function
// is called from two threads concurrently.
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
mock_obj_ = mock_obj;
name_ = name;
}
@ -345,7 +344,7 @@ const void* UntypedFunctionMockerBase::MockObject() const
{
// We protect mock_obj_ under g_gmock_mutex in case this mock
// function is called from two threads concurrently.
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
Assert(mock_obj_ != nullptr, __FILE__, __LINE__,
"MockObject() must not be called before RegisterOwner() or "
"SetOwnerAndName() has been called.");
@ -362,7 +361,7 @@ const char* UntypedFunctionMockerBase::Name() const
{
// We protect name_ under g_gmock_mutex in case this mock
// function is called from two threads concurrently.
MutexLock l(g_gmock_mutex);
MutexLock l(&g_gmock_mutex);
Assert(name_ != nullptr, __FILE__, __LINE__,
"Name() must not be called before SetOwnerAndName() has "
"been called.");
@ -407,15 +406,8 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
} else if (!untyped_expectation->IsSatisfied()) {
expectations_met = false;
::std::stringstream ss;
const ::std::string& expectation_name =
untyped_expectation->GetDescription();
ss << "Actual function ";
if (!expectation_name.empty()) {
ss << "\"" << expectation_name << "\" ";
}
ss << "call count doesn't match " << untyped_expectation->source_text()
<< "...\n";
ss << "Actual function call count doesn't match "
<< untyped_expectation->source_text() << "...\n";
// No need to show the source file location of the expectation
// in the description, as the Expect() call that follows already
// takes care of it.
@ -436,14 +428,14 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
UntypedExpectations expectations_to_delete;
untyped_expectations_.swap(expectations_to_delete);
g_gmock_mutex.unlock();
g_gmock_mutex.Unlock();
expectations_to_delete.clear();
g_gmock_mutex.lock();
g_gmock_mutex.Lock();
return expectations_met;
}
static CallReaction intToCallReaction(int mock_behavior) {
CallReaction intToCallReaction(int mock_behavior) {
if (mock_behavior >= kAllow && mock_behavior <= kFail) {
return static_cast<internal::CallReaction>(mock_behavior);
}
@ -490,7 +482,6 @@ class MockObjectRegistry {
// failure, unless the user explicitly asked us to ignore it.
~MockObjectRegistry() {
if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return;
internal::MutexLock l(internal::g_gmock_mutex);
int leaked_count = 0;
for (StateMap::const_iterator it = states_.begin(); it != states_.end();
@ -505,7 +496,7 @@ class MockObjectRegistry {
std::cout << internal::FormatFileLocation(state.first_used_file,
state.first_used_line);
std::cout << " ERROR: this mock object";
if (!state.first_used_test.empty()) {
if (state.first_used_test != "") {
std::cout << " (used in test " << state.first_used_test_suite << "."
<< state.first_used_test << ")";
}
@ -528,12 +519,8 @@ class MockObjectRegistry {
// RUN_ALL_TESTS() has already returned when this destructor is
// called. Therefore we cannot use the normal Google Test
// failure reporting mechanism.
#ifdef GTEST_OS_QURT
qurt_exception_raise_fatal();
#else
_Exit(1); // We cannot call exit() as it is not reentrant and
_exit(1); // We cannot call exit() as it is not reentrant and
// may already have been called.
#endif
}
}
@ -559,7 +546,7 @@ UninterestingCallReactionMap() {
void SetReactionOnUninterestingCalls(uintptr_t mock_obj,
internal::CallReaction reaction)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
UninterestingCallReactionMap()[mock_obj] = reaction;
}
@ -590,7 +577,7 @@ void Mock::FailUninterestingCalls(uintptr_t mock_obj)
// entry in the call-reaction table should be removed.
void Mock::UnregisterCallReaction(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj));
}
@ -598,7 +585,7 @@ void Mock::UnregisterCallReaction(uintptr_t mock_obj)
// made on the given mock object.
internal::CallReaction Mock::GetReactionOnUninterestingCalls(
const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
return (UninterestingCallReactionMap().count(
reinterpret_cast<uintptr_t>(mock_obj)) == 0)
? internal::intToCallReaction(
@ -611,7 +598,7 @@ internal::CallReaction Mock::GetReactionOnUninterestingCalls(
// objects.
void Mock::AllowLeak(const void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
g_mock_object_registry.states()[mock_obj].leakable = true;
}
@ -620,7 +607,7 @@ void Mock::AllowLeak(const void* mock_obj)
// Test non-fatal failures and returns false.
bool Mock::VerifyAndClearExpectations(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
return VerifyAndClearExpectationsLocked(mock_obj);
}
@ -629,7 +616,7 @@ bool Mock::VerifyAndClearExpectations(void* mock_obj)
// verification was successful.
bool Mock::VerifyAndClear(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
ClearDefaultActionsLocked(mock_obj);
return VerifyAndClearExpectationsLocked(mock_obj);
}
@ -679,7 +666,7 @@ bool Mock::IsStrict(void* mock_obj)
void Mock::Register(const void* mock_obj,
internal::UntypedFunctionMockerBase* mocker)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
}
@ -689,7 +676,7 @@ void Mock::Register(const void* mock_obj,
void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
const char* file, int line)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(internal::g_gmock_mutex);
internal::MutexLock l(&internal::g_gmock_mutex);
MockObjectState& state = g_mock_object_registry.states()[mock_obj];
if (state.first_used_file == nullptr) {
state.first_used_file = file;
@ -747,13 +734,13 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj)
// needed by VerifyAndClearExpectationsLocked().
}
Expectation::Expectation() = default;
Expectation::Expectation() {}
Expectation::Expectation(
const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
: expectation_base_(an_expectation_base) {}
Expectation::~Expectation() = default;
Expectation::~Expectation() {}
// Adds an expectation to a sequence.
void Sequence::AddExpectation(const Expectation& expectation) const {
@ -787,6 +774,8 @@ InSequence::~InSequence() {
} // namespace testing
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#ifdef _MSC_VER
#if _MSC_VER == 1900
#pragma warning(pop)
#endif
#endif

View File

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

View File

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

View File

@ -30,7 +30,6 @@
#
# 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")
licenses(["notice"])

View File

@ -31,33 +31,33 @@
//
// This file tests the built-in actions.
// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
// length exceeded) for MSVC.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4503)
#if _MSC_VER == 1900
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15
#pragma warning(disable : 4800)
#endif
#endif
#include "gmock/gmock-actions.h"
#include <algorithm>
#include <functional>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#include "gtest/internal/gtest-port.h"
// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
// length exceeded) for MSVC.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
#if defined(_MSC_VER) && (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#endif
namespace testing {
namespace {
@ -188,7 +188,7 @@ TEST(TypeTraits, IsInvocableRV) {
struct C {
int operator()() const { return 0; }
void operator()(int) & {}
std::string operator()(int) && { return ""; }
std::string operator()(int) && { return ""; };
};
// The first overload is callable for const and non-const rvalues and lvalues.
@ -222,8 +222,7 @@ TEST(TypeTraits, IsInvocableRV) {
// In C++17 and above, where it's guaranteed that functions can return
// non-moveable objects, everything should work fine for non-moveable rsult
// types too.
// TODO(b/396121064) - Fix this test under MSVC
#ifndef _MSC_VER
#if defined(__cplusplus) && __cplusplus >= 201703L
{
struct NonMoveable {
NonMoveable() = default;
@ -244,7 +243,7 @@ TEST(TypeTraits, IsInvocableRV) {
static_assert(!internal::is_callable_r<int, Callable>::value);
static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);
}
#endif // _MSC_VER
#endif // C++17 and above
// Nothing should choke when we try to call other arguments besides directly
// callable objects, but they should not show up as callable.
@ -441,15 +440,15 @@ TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_EQ(0, DefaultValue<int>::Get());
EXPECT_DEATH_IF_SUPPORTED(
{ DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
"");
}
TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
DefaultValue<std::unique_ptr<int>>::SetFactory(
[] { return std::make_unique<int>(42); });
[] { return std::unique_ptr<int>(new int(42)); });
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
EXPECT_EQ(42, *i);
@ -467,7 +466,7 @@ TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
}
// Tests that DefaultValue<T&>::Exists is false initially.
// Tests that DefaultValue<T&>::Exists is false initiallly.
TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
EXPECT_FALSE(DefaultValue<int&>::Exists());
EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
@ -505,8 +504,8 @@ TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
EXPECT_DEATH_IF_SUPPORTED(
{ DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
"");
}
// Tests that ActionInterface can be implemented by defining the
@ -685,7 +684,7 @@ TEST(ReturnTest, SupportsReferenceLikeReturnType) {
// A reference wrapper for std::vector<int>, implicitly convertible from it.
struct Result {
const std::vector<int>* v;
Result(const std::vector<int>& vec) : v(&vec) {} // NOLINT
Result(const std::vector<int>& v) : v(&v) {} // NOLINT
};
// Set up an action for a mock function that returns the reference wrapper
@ -718,7 +717,7 @@ TEST(ReturnTest, PrefersConversionOperator) {
struct Out {
int x;
explicit Out(const int val) : x(val) {}
explicit Out(const int x) : x(x) {}
explicit Out(const In&) : x(0) {}
};
@ -808,7 +807,7 @@ TEST(ReturnTest, MoveOnlyResultType) {
"");
}
// Tests that Return(v) is covariant.
// Tests that Return(v) is covaraint.
struct Base {
bool operator==(const Base&) { return true; }
@ -987,7 +986,7 @@ TEST(ReturnRoundRobinTest, WorksForVector) {
class MockClass {
public:
MockClass() = default;
MockClass() {}
MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
MOCK_METHOD0(Foo, MyNonDefaultConstructible());
@ -1030,7 +1029,8 @@ void VoidFunc(bool /* flag */) {}
TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
MockClass mock;
EXPECT_CALL(mock, IntFunc(_)).WillRepeatedly(DoAll(VoidFunc, DoDefault()));
EXPECT_CALL(mock, IntFunc(_))
.WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));
// Ideally we should verify the error message as well. Sadly,
// EXPECT_DEATH() can only capture stderr, while Google Mock's
@ -1281,7 +1281,7 @@ int ReturnOne() {
TEST(IgnoreResultTest, MonomorphicAction) {
g_done = false;
Action<void()> a = IgnoreResult(&ReturnOne);
Action<void()> a = IgnoreResult(Invoke(ReturnOne));
a.Perform(std::make_tuple());
EXPECT_TRUE(g_done);
}
@ -1296,7 +1296,7 @@ MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
TEST(IgnoreResultTest, ActionReturningClass) {
g_done = false;
Action<void(int)> a =
IgnoreResult(&ReturnMyNonDefaultConstructible); // NOLINT
IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
a.Perform(std::make_tuple(2));
EXPECT_TRUE(g_done);
}
@ -1410,7 +1410,7 @@ TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {
void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
};
MockFunction<void(Obj&&)> mock;
MockFunction<void(Obj &&)> mock;
EXPECT_CALL(mock, Call)
.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
.WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
@ -1438,7 +1438,7 @@ TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {
void operator()(Obj&) && {}
};
MockFunction<void(Obj&&)> mock;
MockFunction<void(Obj &&)> mock;
EXPECT_CALL(mock, Call)
.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
@ -1476,50 +1476,9 @@ TEST(DoAll, SupportsTypeErasedActions) {
}
}
// A multi-action DoAll action should be convertible to a OnceAction, even when
// its component sub-actions are user-provided types that define only an Action
// conversion operator. If they supposed being called more than once then they
// also support being called at most once.
//
// Single-arg DoAll just returns its argument, so will prefer the Action<F>
// overload for WillOnce.
TEST(DoAll, ConvertibleToOnceActionWithUserProvidedActionConversion) {
// Final action.
struct CustomFinal final {
operator Action<int()>() { // NOLINT
return Return(17);
}
operator Action<int(int, char)>() { // NOLINT
return Return(19);
}
};
// Sub-actions.
struct CustomInitial final {
operator Action<void()>() { // NOLINT
return [] {};
}
operator Action<void(int, char)>() { // NOLINT
return [] {};
}
};
{
OnceAction<int()> action = DoAll(CustomInitial{}, CustomFinal{});
EXPECT_EQ(17, std::move(action).Call());
}
{
OnceAction<int(int, char)> action = DoAll(CustomInitial{}, CustomFinal{});
EXPECT_EQ(19, std::move(action).Call(0, 0));
}
}
// Tests using WithArgs and with an action that takes 1 argument.
TEST(WithArgsTest, OneArg) {
Action<bool(double x, int n)> a = WithArgs<1>(Unary);
Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT
EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));
EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));
}
@ -1527,7 +1486,7 @@ TEST(WithArgsTest, OneArg) {
// Tests using WithArgs with an action that takes 2 arguments.
TEST(WithArgsTest, TwoArgs) {
Action<const char*(const char* s, double x, short n)> a = // NOLINT
WithArgs<0, 2>(Binary);
WithArgs<0, 2>(Invoke(Binary));
const char s[] = "Hello";
EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
}
@ -1543,7 +1502,7 @@ struct ConcatAll {
// Tests using WithArgs with an action that takes 10 arguments.
TEST(WithArgsTest, TenArgs) {
Action<std::string(const char*, const char*, const char*, const char*)> a =
WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(ConcatAll{});
WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
EXPECT_EQ("0123210123",
a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
CharPtr("3"))));
@ -1568,21 +1527,21 @@ TEST(WithArgsTest, NonInvokeAction) {
// Tests using WithArgs to pass all original arguments in the original order.
TEST(WithArgsTest, Identity) {
Action<int(int x, char y, short z)> a = // NOLINT
WithArgs<0, 1, 2>(Ternary);
WithArgs<0, 1, 2>(Invoke(Ternary));
EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));
}
// Tests using WithArgs with repeated arguments.
TEST(WithArgsTest, RepeatedArguments) {
Action<int(bool, int m, int n)> a = // NOLINT
WithArgs<1, 1, 1, 1>(SumOf4);
WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));
}
// Tests using WithArgs with reversed argument order.
TEST(WithArgsTest, ReversedArgumentOrder) {
Action<const char*(short n, const char* input)> a = // NOLINT
WithArgs<1, 0>(Binary);
WithArgs<1, 0>(Invoke(Binary));
const char s[] = "Hello";
EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));
}
@ -1590,14 +1549,14 @@ TEST(WithArgsTest, ReversedArgumentOrder) {
// Tests using WithArgs with compatible, but not identical, argument types.
TEST(WithArgsTest, ArgsOfCompatibleTypes) {
Action<long(short x, char y, double z, char c)> a = // NOLINT
WithArgs<0, 1, 3>(Ternary);
WithArgs<0, 1, 3>(Invoke(Ternary));
EXPECT_EQ(123,
a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));
}
// Tests using WithArgs with an action that returns void.
TEST(WithArgsTest, VoidAction) {
Action<void(double x, char c, int n)> a = WithArgs<2, 1>(VoidBinary);
Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
g_done = false;
a.Perform(std::make_tuple(1.5, 'a', 3));
EXPECT_TRUE(g_done);
@ -1637,23 +1596,7 @@ TEST(WithArgsTest, RefQualifiedInnerAction) {
EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
}
// It should be fine to provide an lvalue WithArgsAction to WillOnce, even when
// the inner action only wants to convert to OnceAction.
TEST(WithArgsTest, ProvideAsLvalueToWillOnce) {
struct SomeAction {
operator OnceAction<int(int)>() const { // NOLINT
return [](const int arg) { return arg + 2; };
}
};
const auto wa = WithArg<1>(SomeAction{});
MockFunction<int(int, int)> mock;
EXPECT_CALL(mock, Call).WillOnce(wa);
EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
}
#ifndef GTEST_OS_WINDOWS_MOBILE
#if !GTEST_OS_WINDOWS_MOBILE
class SetErrnoAndReturnTest : public testing::Test {
protected:
@ -1812,7 +1755,9 @@ TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
delete c;
}
std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); }
std::unique_ptr<int> UniquePtrSource() {
return std::unique_ptr<int>(new int(19));
}
std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
std::vector<std::unique_ptr<int>> out;
@ -1822,7 +1767,7 @@ std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
MockClass mock;
std::unique_ptr<int> i = std::make_unique<int>(19);
std::unique_ptr<int> i(new int(19));
EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
EXPECT_CALL(mock, MakeVectorUnique())
.WillOnce(Return(ByMove(VectorUniquePtrSource())));
@ -1845,7 +1790,7 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
testing::MockFunction<void()> mock_function;
MockClass mock;
std::unique_ptr<int> i = std::make_unique<int>(19);
std::unique_ptr<int> i(new int(19));
EXPECT_CALL(mock_function, Call());
EXPECT_CALL(mock, MakeUnique())
.WillOnce(DoAll(InvokeWithoutArgs(&mock_function,
@ -1861,11 +1806,12 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
// Check default value
DefaultValue<std::unique_ptr<int>>::SetFactory(
[] { return std::make_unique<int>(42); });
[] { return std::unique_ptr<int>(new int(42)); });
EXPECT_EQ(42, *mock.MakeUnique());
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(UniquePtrSource);
EXPECT_CALL(mock, MakeVectorUnique()).WillRepeatedly(VectorUniquePtrSource);
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
EXPECT_CALL(mock, MakeVectorUnique())
.WillRepeatedly(Invoke(VectorUniquePtrSource));
std::unique_ptr<int> result1 = mock.MakeUnique();
EXPECT_EQ(19, *result1);
std::unique_ptr<int> result2 = mock.MakeUnique();
@ -1880,14 +1826,14 @@ TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
TEST(MockMethodTest, CanTakeMoveOnlyValue) {
MockClass mock;
auto make = [](int i) { return std::make_unique<int>(i); };
auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
return *i;
});
// DoAll() does not compile, since it would move from its arguments twice.
// EXPECT_CALL(mock, TakeUnique(_, _))
// .WillRepeatedly(DoAll([](std::unique_ptr<int> j) {})),
// .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
// Return(1)));
EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
.WillOnce(Return(-7))
@ -2111,7 +2057,9 @@ struct Double {
}
};
std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); }
std::unique_ptr<int> UniqueInt(int i) {
return std::unique_ptr<int>(new int(i));
}
TEST(FunctorActionTest, ActionFromFunction) {
Action<int(int, int&, int*)> a = &Add;
@ -2170,7 +2118,7 @@ TEST(FunctorActionTest, TypeConversion) {
EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
// Ensure creation of an empty action succeeds.
(void)Action<void(int)>(nullptr);
Action<void(int)>(nullptr);
}
TEST(FunctorActionTest, UnusedArguments) {
@ -2217,8 +2165,3 @@ TEST(ActionMacro, LargeArity) {
} // namespace
} // namespace testing
#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
#endif
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503

View File

@ -31,8 +31,6 @@
//
// This file tests the built-in cardinalities.
#include <ostream>
#include "gmock/gmock.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
@ -52,7 +50,7 @@ using testing::MakeCardinality;
class MockFoo {
public:
MockFoo() = default;
MockFoo() {}
MOCK_METHOD0(Bar, int()); // NOLINT
private:
@ -133,7 +131,7 @@ TEST(AnyNumberTest, HasCorrectBounds) {
TEST(AtLeastTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)AtLeast(-1);
AtLeast(-1);
},
"The invocation lower bound must be >= 0");
}
@ -186,7 +184,7 @@ TEST(AtLeastTest, HasCorrectBounds) {
TEST(AtMostTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)AtMost(-1);
AtMost(-1);
},
"The invocation upper bound must be >= 0");
}
@ -239,7 +237,7 @@ TEST(AtMostTest, HasCorrectBounds) {
TEST(BetweenTest, OnNegativeStart) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)Between(-1, 2);
Between(-1, 2);
},
"The invocation lower bound must be >= 0, but is actually -1");
}
@ -247,7 +245,7 @@ TEST(BetweenTest, OnNegativeStart) {
TEST(BetweenTest, OnNegativeEnd) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)Between(1, -2);
Between(1, -2);
},
"The invocation upper bound must be >= 0, but is actually -2");
}
@ -255,7 +253,7 @@ TEST(BetweenTest, OnNegativeEnd) {
TEST(BetweenTest, OnStartBiggerThanEnd) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)Between(2, 1);
Between(2, 1);
},
"The invocation upper bound (1) must be >= "
"the invocation lower bound (2)");
@ -340,7 +338,7 @@ TEST(BetweenTest, HasCorrectBounds) {
TEST(ExactlyTest, OnNegativeNumber) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
(void)Exactly(-1);
Exactly(-1);
},
"The invocation lower bound must be >= 0");
}

View File

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

View File

@ -40,7 +40,6 @@
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
@ -57,7 +56,7 @@
#include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION_
#ifdef GTEST_OS_CYGWIN
#if GTEST_OS_CYGWIN
#include <sys/types.h> // For ssize_t. NOLINT
#endif
@ -168,7 +167,7 @@ TEST(KindOfTest, Integer) {
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT
#if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || defined(GTEST_OS_CYGWIN)
#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN
// ssize_t is not defined on Windows and possibly some other OSes.
EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT
#endif
@ -545,7 +544,7 @@ TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {
void OnCallLogger() {
DummyMock mock;
(void)ON_CALL(mock, TestMethod());
ON_CALL(mock, TestMethod());
}
// Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
@ -568,7 +567,7 @@ TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {
void OnCallAnyArgumentLogger() {
DummyMock mock;
(void)ON_CALL(mock, TestMethodArg(_));
ON_CALL(mock, TestMethodArg(_));
}
// Verifies that ON_CALL prints provided _ argument.

View File

@ -31,19 +31,15 @@
//
// This file tests some commonly used argument matchers.
#include <cmath>
#include <limits>
#include <memory>
#include <ostream>
#include <string>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing {
namespace gmock_matchers_test {
@ -399,188 +395,6 @@ TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
EXPECT_EQ("are an almost-equal pair", Describe(m));
}
// Tests that DistanceFrom() can describe itself properly.
TEST(DistanceFrom, CanDescribeSelf) {
Matcher<double> m = DistanceFrom(1.5, Lt(0.1));
EXPECT_EQ(Describe(m), "is < 0.1 away from 1.5");
m = DistanceFrom(2.5, Gt(0.2));
EXPECT_EQ(Describe(m), "is > 0.2 away from 2.5");
}
// Tests that DistanceFrom() can explain match failure.
TEST(DistanceFrom, CanExplainMatchFailure) {
Matcher<double> m = DistanceFrom(1.5, Lt(0.1));
EXPECT_EQ(Explain(m, 2.0), "which is 0.5 away from 1.5");
}
// Tests that DistanceFrom() matches a double that is within the given range of
// the given value.
TEST(DistanceFrom, MatchesDoubleWithinRange) {
const Matcher<double> m = DistanceFrom(0.5, Le(0.1));
EXPECT_TRUE(m.Matches(0.45));
EXPECT_TRUE(m.Matches(0.5));
EXPECT_TRUE(m.Matches(0.55));
EXPECT_FALSE(m.Matches(0.39));
EXPECT_FALSE(m.Matches(0.61));
}
// Tests that DistanceFrom() matches a double reference that is within the given
// range of the given value.
TEST(DistanceFrom, MatchesDoubleRefWithinRange) {
const Matcher<const double&> m = DistanceFrom(0.5, Le(0.1));
EXPECT_TRUE(m.Matches(0.45));
EXPECT_TRUE(m.Matches(0.5));
EXPECT_TRUE(m.Matches(0.55));
EXPECT_FALSE(m.Matches(0.39));
EXPECT_FALSE(m.Matches(0.61));
}
// Tests that DistanceFrom() can be implicitly converted to a matcher depending
// on the type of the argument.
TEST(DistanceFrom, CanBeImplicitlyConvertedToMatcher) {
EXPECT_THAT(0.58, DistanceFrom(0.5, Le(0.1)));
EXPECT_THAT(0.2, Not(DistanceFrom(0.5, Le(0.1))));
EXPECT_THAT(0.58f, DistanceFrom(0.5f, Le(0.1f)));
EXPECT_THAT(0.7f, Not(DistanceFrom(0.5f, Le(0.1f))));
}
// Tests that DistanceFrom() can be used on compatible types (i.e. not
// everything has to be of the same type).
TEST(DistanceFrom, CanBeUsedOnCompatibleTypes) {
EXPECT_THAT(0.58, DistanceFrom(0.5, Le(0.1f)));
EXPECT_THAT(0.2, Not(DistanceFrom(0.5, Le(0.1f))));
EXPECT_THAT(0.58, DistanceFrom(0.5f, Le(0.1)));
EXPECT_THAT(0.2, Not(DistanceFrom(0.5f, Le(0.1))));
EXPECT_THAT(0.58, DistanceFrom(0.5f, Le(0.1f)));
EXPECT_THAT(0.2, Not(DistanceFrom(0.5f, Le(0.1f))));
EXPECT_THAT(0.58f, DistanceFrom(0.5, Le(0.1)));
EXPECT_THAT(0.2f, Not(DistanceFrom(0.5, Le(0.1))));
EXPECT_THAT(0.58f, DistanceFrom(0.5, Le(0.1f)));
EXPECT_THAT(0.2f, Not(DistanceFrom(0.5, Le(0.1f))));
EXPECT_THAT(0.58f, DistanceFrom(0.5f, Le(0.1)));
EXPECT_THAT(0.2f, Not(DistanceFrom(0.5f, Le(0.1))));
}
// A 2-dimensional point. For testing using DistanceFrom() with a custom type
// that doesn't have a built-in distance function.
class Point {
public:
Point(double x, double y) : x_(x), y_(y) {}
double x() const { return x_; }
double y() const { return y_; }
private:
double x_;
double y_;
};
// Returns the distance between two points.
double PointDistance(const Point& lhs, const Point& rhs) {
return std::sqrt(std::pow(lhs.x() - rhs.x(), 2) +
std::pow(lhs.y() - rhs.y(), 2));
}
// Tests that DistanceFrom() can be used on a type with a custom distance
// function.
TEST(DistanceFrom, CanBeUsedOnTypeWithCustomDistanceFunction) {
const Matcher<Point> m =
DistanceFrom(Point(0.5, 0.5), PointDistance, Le(0.1));
EXPECT_THAT(Point(0.45, 0.45), m);
EXPECT_THAT(Point(0.2, 0.45), Not(m));
}
// A wrapper around a double value. For testing using DistanceFrom() with a
// custom type that has neither a built-in distance function nor a built-in
// distance comparator.
class Double {
public:
explicit Double(double value) : value_(value) {}
Double(const Double& other) = default;
double value() const { return value_; }
// Defines how to print a Double value. We don't use the AbslStringify API
// because googletest doesn't require absl yet.
friend void PrintTo(const Double& value, std::ostream* os) {
*os << "Double(" << value.value() << ")";
}
private:
double value_;
};
// Returns the distance between two Double values.
Double DoubleDistance(Double lhs, Double rhs) {
return Double(std::abs(lhs.value() - rhs.value()));
}
MATCHER_P(DoubleLe, rhs, (negation ? "is > " : "is <= ") + PrintToString(rhs)) {
return arg.value() <= rhs.value();
}
// Tests that DistanceFrom() can describe itself properly for a type with a
// custom printer.
TEST(DistanceFrom, CanDescribeWithCustomPrinter) {
const Matcher<Double> m =
DistanceFrom(Double(0.5), DoubleDistance, DoubleLe(Double(0.1)));
EXPECT_EQ(Describe(m), "is <= Double(0.1) away from Double(0.5)");
EXPECT_EQ(DescribeNegation(m), "is > Double(0.1) away from Double(0.5)");
}
// Tests that DistanceFrom() can be used with a custom distance function and
// comparator.
TEST(DistanceFrom, CanCustomizeDistanceAndComparator) {
const Matcher<Double> m =
DistanceFrom(Double(0.5), DoubleDistance, DoubleLe(Double(0.1)));
EXPECT_TRUE(m.Matches(Double(0.45)));
EXPECT_TRUE(m.Matches(Double(0.5)));
EXPECT_FALSE(m.Matches(Double(0.39)));
EXPECT_FALSE(m.Matches(Double(0.61)));
}
// For testing using DistanceFrom() with a type that supports both - and abs.
class Float {
public:
explicit Float(float value) : value_(value) {}
Float(const Float& other) = default;
float value() const { return value_; }
private:
float value_ = 0.0f;
};
// Returns the difference between two Float values. This must be defined in the
// same namespace as Float.
Float operator-(const Float& lhs, const Float& rhs) {
return Float(lhs.value() - rhs.value());
}
// Returns the absolute value of a Float value. This must be defined in the
// same namespace as Float.
Float abs(Float value) { return Float(std::abs(value.value())); }
// Returns true if and only if the first Float value is less than the second
// Float value. This must be defined in the same namespace as Float.
bool operator<(const Float& lhs, const Float& rhs) {
return lhs.value() < rhs.value();
}
// Tests that DistanceFrom() can be used with a type that supports both - and
// abs.
TEST(DistanceFrom, CanBeUsedWithTypeThatSupportsBothMinusAndAbs) {
const Matcher<Float> m = DistanceFrom(Float(0.5f), Lt(Float(0.1f)));
EXPECT_TRUE(m.Matches(Float(0.45f)));
EXPECT_TRUE(m.Matches(Float(0.55f)));
EXPECT_FALSE(m.Matches(Float(0.39f)));
EXPECT_FALSE(m.Matches(Float(0.61f)));
}
// Tests that Not(m) matches any value that doesn't match m.
TEST(NotTest, NegatesMatcher) {
Matcher<int> m;
@ -720,6 +534,7 @@ TEST(AllOfTest, CanDescribeNegation) {
m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
Ne(10), Ne(11));
AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
AllOfMatches(11, m);
}
@ -743,9 +558,10 @@ TEST_P(AllOfTestP, ExplainsResult) {
Matcher<int> m;
// Successful match. Both matchers need to explain. The second
// matcher doesn't give an explanation, so the matcher description is used.
// matcher doesn't give an explanation, so only the first matcher's
// explanation is printed.
m = AllOf(GreaterThan(10), Lt(30));
EXPECT_EQ("which is 15 more than 10, and is < 30", Explain(m, 25));
EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
// Successful match. Both matchers need to explain.
m = AllOf(GreaterThan(10), GreaterThan(20));
@ -755,9 +571,8 @@ TEST_P(AllOfTestP, ExplainsResult) {
// Successful match. All matchers need to explain. The second
// matcher doesn't given an explanation.
m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
EXPECT_EQ(
"which is 15 more than 10, and is < 30, and which is 5 more than 20",
Explain(m, 25));
EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
Explain(m, 25));
// Successful match. All matchers need to explain.
m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
@ -769,14 +584,13 @@ TEST_P(AllOfTestP, ExplainsResult) {
// Failed match. The first matcher, which failed, needs to
// explain.
m = AllOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
Explain(m, 5));
EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
// Failed match. The second matcher, which failed, needs to
// explain. Since it doesn't given an explanation, the matcher text is
// explain. Since it doesn't given an explanation, nothing is
// printed.
m = AllOf(GreaterThan(10), Lt(30));
EXPECT_EQ("which doesn't match (is < 30)", Explain(m, 40));
EXPECT_EQ("", Explain(m, 40));
// Failed match. The second matcher, which failed, needs to
// explain.
@ -959,43 +773,45 @@ TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
TEST_P(AnyOfTestP, ExplainsResult) {
Matcher<int> m;
// Failed match. The second matcher have no explanation (description is used).
// Failed match. Both matchers need to explain. The second
// matcher doesn't give an explanation, so only the first matcher's
// explanation is printed.
m = AnyOf(GreaterThan(10), Lt(0));
EXPECT_EQ("which is 5 less than 10, and isn't < 0", Explain(m, 5));
EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
// Failed match. Both matchers have explanations.
// Failed match. Both matchers need to explain.
m = AnyOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
Explain(m, 5));
// Failed match. The middle matcher have no explanation.
// Failed match. All matchers need to explain. The second
// matcher doesn't given an explanation.
m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
EXPECT_EQ(
"which is 5 less than 10, and isn't > 20, and which is 25 less than 30",
Explain(m, 5));
EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
Explain(m, 5));
// Failed match. All three matchers have explanations.
// Failed match. All matchers need to explain.
m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
EXPECT_EQ(
"which is 5 less than 10, and which is 15 less than 20, "
"and which is 25 less than 30",
Explain(m, 5));
// Successful match. The first macher succeeded and has explanation.
// Successful match. The first matcher, which succeeded, needs to
// explain.
m = AnyOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
// Successful match. The second matcher succeeded and has explanation.
// Successful match. The second matcher, which succeeded, needs to
// explain. Since it doesn't given an explanation, nothing is
// printed.
m = AnyOf(GreaterThan(10), Lt(30));
EXPECT_EQ("", Explain(m, 0));
// Successful match. The second matcher, which succeeded, needs to
// explain.
m = AnyOf(GreaterThan(30), GreaterThan(20));
EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
// Successful match. The first matcher succeeded and has no explanation.
m = AnyOf(Gt(10), Lt(20));
EXPECT_EQ("which matches (is > 10)", Explain(m, 15));
// Successful match. The second matcher succeeded and has no explanation.
m = AnyOf(Gt(30), Gt(20));
EXPECT_EQ("which matches (is > 20)", Explain(m, 25));
}
// The following predicate function and predicate functor are for
@ -1138,7 +954,7 @@ TEST(AllArgsTest, WorksForNonTuple) {
class AllArgsHelper {
public:
AllArgsHelper() = default;
AllArgsHelper() {}
MOCK_METHOD2(Helper, int(char x, int y));
@ -1159,7 +975,7 @@ TEST(AllArgsTest, WorksInWithClause) {
class OptionalMatchersHelper {
public:
OptionalMatchersHelper() = default;
OptionalMatchersHelper() {}
MOCK_METHOD0(NoArgs, int());
@ -1221,7 +1037,7 @@ class FloatingPointTest : public testing::Test {
Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
further_from_infinity_(
Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
max_(std::numeric_limits<RawType>::max()),
max_(Floating::Max()),
nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {}
@ -1625,7 +1441,7 @@ TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
}
TEST(NotTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, Pointee(Eq(3)));
EXPECT_THAT(p, Not(Pointee(Eq(2))));
}
@ -1681,13 +1497,13 @@ TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
} // namespace adl_test
TEST(AllOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
}
TEST(AnyOfTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
}
@ -1696,4 +1512,6 @@ TEST(AnyOfTest, WorksOnMoveOnlyType) {
} // namespace gmock_matchers_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif

View File

@ -31,20 +31,15 @@
//
// This file tests some commonly used argument matchers.
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing {
namespace gmock_matchers_test {
@ -412,27 +407,9 @@ class IntValue {
int value_;
};
// For testing casting matchers between compatible types. This is similar to
// IntValue, but takes a non-const reference to the value, showing MatcherCast
// works with such types (and doesn't, for example, use a const ref internally).
class MutableIntView {
public:
// An int& can be statically (although not implicitly) cast to a
// MutableIntView.
explicit MutableIntView(int& a_value) : value_(a_value) {}
int& value() const { return value_; }
private:
int& value_;
};
// For testing casting matchers between compatible types.
bool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; }
// For testing casting matchers between compatible types.
bool IsPositiveMutableIntView(MutableIntView foo) { return foo.value() > 0; }
// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
// can be statically converted to U.
TEST(MatcherCastTest, FromCompatibleType) {
@ -448,34 +425,14 @@ TEST(MatcherCastTest, FromCompatibleType) {
// predicate.
EXPECT_TRUE(m4.Matches(1));
EXPECT_FALSE(m4.Matches(0));
Matcher<MutableIntView> m5 = Truly(IsPositiveMutableIntView);
Matcher<int> m6 = MatcherCast<int>(m5);
// In the following, the arguments 1 and 0 are statically converted to
// MutableIntView objects, and then tested by the IsPositiveMutableIntView()
// predicate.
EXPECT_TRUE(m6.Matches(1));
EXPECT_FALSE(m6.Matches(0));
}
// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest, FromConstReferenceToNonReference) {
int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<const int&> m1 = Eq(0);
Matcher<int> m2 = MatcherCast<int>(m1);
int n1 = 0;
EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
}
// Tests that MatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest, FromConstReferenceToReference) {
int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<int&> m2 = MatcherCast<int&>(m1);
int n1 = 0;
EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
}
// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
@ -484,12 +441,6 @@ TEST(MatcherCastTest, FromReferenceToNonReference) {
Matcher<int> m2 = MatcherCast<int>(m1);
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
// Of course, reference identity isn't preserved since a copy is required.
int n = 0;
Matcher<int&> m3 = Ref(n);
Matcher<int> m4 = MatcherCast<int>(m3);
EXPECT_FALSE(m4.Matches(n));
}
// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
@ -622,48 +573,21 @@ struct IntReferenceWrapper {
const int* value;
};
// Compared the contained values
bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
return *a.value == *b.value;
return a.value == b.value;
}
TEST(MatcherCastTest, ValueIsCopied) {
{
// When an IntReferenceWrapper is passed.
int n = 42;
Matcher<IntReferenceWrapper> m =
MatcherCast<IntReferenceWrapper>(IntReferenceWrapper(n));
{
int value = 42;
EXPECT_TRUE(m.Matches(value));
value = 10;
EXPECT_FALSE(m.Matches(value));
// This changes the stored reference.
n = 10;
EXPECT_TRUE(m.Matches(value));
}
}
{
// When an int is passed.
int n = 42;
Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
{
int value = 42;
EXPECT_TRUE(m.Matches(value));
value = 10;
EXPECT_FALSE(m.Matches(value));
// This does not change the stored int.
n = 10;
EXPECT_FALSE(m.Matches(value));
}
}
TEST(MatcherCastTest, ValueIsNotCopied) {
int n = 42;
Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
// Verify that the matcher holds a reference to n, not to its temporary copy.
EXPECT_TRUE(m.Matches(n));
}
class Base {
public:
virtual ~Base() = default;
Base() = default;
virtual ~Base() {}
Base() {}
private:
Base(const Base&) = delete;
@ -721,16 +645,6 @@ TEST(SafeMatcherCastTest, FromBaseClass) {
EXPECT_FALSE(m4.Matches(d2));
}
// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest, FromConstReferenceToNonReference) {
int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<int> m2 = SafeMatcherCast<int>(m1);
int n1 = 0;
EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
}
// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
int n = 0;
@ -948,7 +862,7 @@ struct Type {
};
TEST(TypedEqTest, HasSpecifiedType) {
// Verifies that the type of TypedEq<T>(v) is Matcher<T>.
// Verfies that the type of TypedEq<T>(v) is Matcher<T>.
Type<Matcher<int>>::IsTypeOf(TypedEq<int>(5));
Type<Matcher<double>>::IsTypeOf(TypedEq<double>(5));
}
@ -1069,30 +983,6 @@ TEST(ComparisonBaseTest, WorksWithMoveOnly) {
helper.Call(MoveOnly(1));
}
TEST(IsEmptyTest, MatchesContainer) {
const Matcher<std::vector<int>> m = IsEmpty();
std::vector<int> a = {};
std::vector<int> b = {1};
EXPECT_TRUE(m.Matches(a));
EXPECT_FALSE(m.Matches(b));
}
TEST(IsEmptyTest, MatchesStdString) {
const Matcher<std::string> m = IsEmpty();
std::string a = "z";
std::string b = "";
EXPECT_FALSE(m.Matches(a));
EXPECT_TRUE(m.Matches(b));
}
TEST(IsEmptyTest, MatchesCString) {
const Matcher<const char*> m = IsEmpty();
const char a[] = "";
const char b[] = "x";
EXPECT_TRUE(m.Matches(a));
EXPECT_FALSE(m.Matches(b));
}
// Tests that IsNull() matches any NULL pointer of any type.
TEST(IsNullTest, MatchesNullPointer) {
Matcher<int*> m1 = IsNull();
@ -1614,7 +1504,7 @@ TEST(PairTest, MatchesCorrectly) {
EXPECT_THAT(p, Pair(25, "foo"));
EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
// 'first' doesn't match, but 'second' matches.
// 'first' doesnt' match, but 'second' matches.
EXPECT_THAT(p, Not(Pair(42, "foo")));
EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
@ -1629,7 +1519,7 @@ TEST(PairTest, MatchesCorrectly) {
TEST(PairTest, WorksWithMoveOnly) {
pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
p.second = std::make_unique<int>(7);
p.second.reset(new int(7));
EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
}
@ -1794,21 +1684,6 @@ TEST(FieldsAreTest, StructuredBindings) {
};
EXPECT_THAT(MyVarType16{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType17 {
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q;
};
EXPECT_THAT(MyVarType17{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType18 {
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r;
};
EXPECT_THAT(MyVarType18{},
FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
struct MyVarType19 {
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s;
};
EXPECT_THAT(MyVarType19{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0));
}
#endif
@ -1852,15 +1727,6 @@ TEST(StartsWithTest, CanDescribeSelf) {
EXPECT_EQ("starts with \"Hi\"", Describe(m));
}
TEST(StartsWithTest, WorksWithStringMatcherOnStringViewMatchee) {
#if GTEST_INTERNAL_HAS_STRING_VIEW
EXPECT_THAT(internal::StringView("talk to me goose"),
StartsWith(std::string("talk")));
#else
GTEST_SKIP() << "Not applicable without internal::StringView.";
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
// Tests EndsWith(s).
TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
@ -1898,13 +1764,11 @@ TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {
EXPECT_FALSE(m1.Matches("invalid base64"));
EXPECT_FALSE(m1.Matches("aGVsbG8gd29ybGQ=")); // hello world
EXPECT_TRUE(m1.Matches("aGVsbG8gd29ybGQh")); // hello world!
EXPECT_TRUE(m1.Matches("+/-_IQ")); // \xfb\xff\xbf!
const Matcher<const std::string&> m2 = WhenBase64Unescaped(EndsWith("!"));
EXPECT_FALSE(m2.Matches("invalid base64"));
EXPECT_FALSE(m2.Matches("aGVsbG8gd29ybGQ=")); // hello world
EXPECT_TRUE(m2.Matches("aGVsbG8gd29ybGQh")); // hello world!
EXPECT_TRUE(m2.Matches("+/-_IQ")); // \xfb\xff\xbf!
#if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<const internal::StringView&> m3 =
@ -1912,7 +1776,6 @@ TEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {
EXPECT_FALSE(m3.Matches("invalid base64"));
EXPECT_FALSE(m3.Matches("aGVsbG8gd29ybGQ=")); // hello world
EXPECT_TRUE(m3.Matches("aGVsbG8gd29ybGQh")); // hello world!
EXPECT_TRUE(m3.Matches("+/-_IQ")); // \xfb\xff\xbf!
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
@ -2389,19 +2252,22 @@ PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
return MakePolymorphicMatcher(DivisibleByImpl(n));
}
// Tests that when AllOf() fails, all failing matchers are asked to explain why.
// Tests that when AllOf() fails, only the first failing matcher is
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_False_False) {
const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
EXPECT_EQ("which is 1 modulo 4, and which is 2 modulo 3", Explain(m, 5));
EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
}
// Tests that when AllOf() fails, all failing matchers are asked to explain why.
// Tests that when AllOf() fails, only the first failing matcher is
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_False_True) {
const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
}
// Tests that when AllOf() fails, all failing matchers are asked to explain why.
// Tests that when AllOf() fails, only the first failing matcher is
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_True_False) {
const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
@ -2414,79 +2280,9 @@ TEST(ExplainMatchResultTest, AllOf_True_True) {
EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
}
// Tests that when AllOf() succeeds, but matchers have no explanation,
// the matcher description is used.
TEST(ExplainMatchResultTest, AllOf_True_True_2) {
const Matcher<int> m = AllOf(Ge(2), Le(3));
EXPECT_EQ("is >= 2, and is <= 3", Explain(m, 2));
}
// A matcher that records whether the listener was interested.
template <typename T>
class CountingMatcher : public MatcherInterface<T> {
public:
explicit CountingMatcher(const Matcher<T>& base_matcher,
std::vector<bool>* listener_interested)
: base_matcher_(base_matcher),
listener_interested_(listener_interested) {}
bool MatchAndExplain(T x, MatchResultListener* listener) const override {
listener_interested_->push_back(listener->IsInterested());
return base_matcher_.MatchAndExplain(x, listener);
}
void DescribeTo(ostream* os) const override { base_matcher_.DescribeTo(os); }
private:
Matcher<T> base_matcher_;
std::vector<bool>* listener_interested_;
};
TEST(AllOfTest, DoesNotFormatChildMatchersWhenNotInterested) {
std::vector<bool> listener_interested;
Matcher<int> matcher =
MakeMatcher(new CountingMatcher<int>(Eq(1), &listener_interested));
EXPECT_TRUE(matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
Matcher<int> all_of_matcher = AllOf(matcher, matcher);
EXPECT_TRUE(all_of_matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false, false));
listener_interested.clear();
EXPECT_FALSE(all_of_matcher.Matches(0));
EXPECT_THAT(listener_interested, ElementsAre(false));
}
TEST(AnyOfTest, DoesNotFormatChildMatchersWhenNotInterested) {
std::vector<bool> listener_interested;
Matcher<int> matcher =
MakeMatcher(new CountingMatcher<int>(Eq(1), &listener_interested));
EXPECT_TRUE(matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
Matcher<int> any_of_matcher = AnyOf(matcher, matcher);
EXPECT_TRUE(any_of_matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
EXPECT_FALSE(any_of_matcher.Matches(0));
EXPECT_THAT(listener_interested, ElementsAre(false, false));
}
TEST(OptionalTest, DoesNotFormatChildMatcherWhenNotInterested) {
std::vector<bool> listener_interested;
Matcher<int> matcher =
MakeMatcher(new CountingMatcher<int>(Eq(1), &listener_interested));
EXPECT_TRUE(matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
Matcher<std::optional<int>> optional_matcher = Optional(matcher);
EXPECT_FALSE(optional_matcher.Matches(std::nullopt));
EXPECT_THAT(listener_interested, ElementsAre());
EXPECT_TRUE(optional_matcher.Matches(1));
EXPECT_THAT(listener_interested, ElementsAre(false));
listener_interested.clear();
EXPECT_FALSE(matcher.Matches(0));
EXPECT_THAT(listener_interested, ElementsAre(false));
EXPECT_EQ("", Explain(m, 2));
}
INSTANTIATE_GTEST_MATCHER_TEST_P(ExplainmatcherResultTest);
@ -2517,4 +2313,6 @@ TEST(PolymorphicMatcherTest, CanAccessImpl) {
} // namespace gmock_matchers_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif

View File

@ -31,26 +31,15 @@
//
// This file tests some commonly used argument matchers.
#include <algorithm>
#include <array>
#include <cstddef>
#include <deque>
#include <forward_list>
#include <iterator>
#include <list>
#include <memory>
#include <ostream>
#include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing {
namespace gmock_matchers_test {
@ -217,7 +206,7 @@ TEST(PointeeTest, ReferenceToNonConstRawPointer) {
TEST(PointeeTest, SmartPointer) {
const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));
std::unique_ptr<int> n = std::make_unique<int>(1);
std::unique_ptr<int> n(new int(1));
EXPECT_TRUE(m.Matches(n));
}
@ -254,7 +243,7 @@ TEST(PointerTest, RawPointerToConst) {
}
TEST(PointerTest, SmartPointer) {
std::unique_ptr<int> n = std::make_unique<int>(10);
std::unique_ptr<int> n(new int(10));
int* raw_n = n.get();
const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));
@ -1047,8 +1036,8 @@ TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
// a NULL function pointer.
TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
EXPECT_DEATH_IF_SUPPORTED(
(void)ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
Eq(std::string("foo"))),
ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
Eq(std::string("foo"))),
"NULL function pointer is passed into ResultOf\\(\\)\\.");
}
@ -1193,8 +1182,8 @@ TEST(SizeIsTest, WorksWithMinimalistCustomType) {
TEST(SizeIsTest, CanDescribeSelf) {
Matcher<vector<int>> m = SizeIs(2);
EXPECT_EQ("has a size that is equal to 2", Describe(m));
EXPECT_EQ("has a size that isn't equal to 2", DescribeNegation(m));
EXPECT_EQ("size is equal to 2", Describe(m));
EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
}
TEST(SizeIsTest, ExplainsResult) {
@ -1205,16 +1194,13 @@ TEST(SizeIsTest, ExplainsResult) {
vector<int> container;
EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
EXPECT_EQ("whose size 0 matches", Explain(m2, container));
EXPECT_EQ("whose size 0 matches, which matches (is equal to 0)",
Explain(m3, container));
EXPECT_EQ("whose size 0 matches", Explain(m3, container));
EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
container.push_back(0);
container.push_back(0);
EXPECT_EQ("whose size 2 matches", Explain(m1, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
EXPECT_EQ(
"whose size 2 doesn't match, isn't equal to 0, and isn't equal to 3",
Explain(m3, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
EXPECT_EQ("whose size 2 matches", Explain(m4, container));
}
@ -1272,11 +1258,10 @@ TEST(WhenSortedByTest, CanDescribeSelf) {
TEST(WhenSortedByTest, ExplainsMatchResult) {
const int a[] = {2, 1};
EXPECT_EQ(
Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a),
"which is { 1, 2 } when sorted, whose element #0 (1) isn't equal to 2");
EXPECT_EQ(Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a),
"which is { 1, 2 } when sorted");
EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
EXPECT_EQ("which is { 1, 2 } when sorted",
Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
}
// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
@ -1480,10 +1465,8 @@ TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
Explain(m1, container));
EXPECT_EQ("whose distance between begin() and end() 0 matches",
Explain(m2, container));
EXPECT_EQ(
"whose distance between begin() and end() 0 matches, which matches (is "
"equal to 0)",
Explain(m3, container));
EXPECT_EQ("whose distance between begin() and end() 0 matches",
Explain(m3, container));
EXPECT_EQ(
"whose distance between begin() and end() 0 doesn't match, which is 1 "
"less than 1",
@ -1494,10 +1477,8 @@ TEST_P(BeginEndDistanceIsTestP, ExplainsResult) {
Explain(m1, container));
EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
Explain(m2, container));
EXPECT_EQ(
"whose distance between begin() and end() 2 doesn't match, isn't equal "
"to 0, and isn't equal to 3",
Explain(m3, container));
EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
Explain(m3, container));
EXPECT_EQ(
"whose distance between begin() and end() 2 matches, which is 1 more "
"than 1",
@ -1777,295 +1758,6 @@ TEST(IsSubsetOfTest, WorksWithMoveOnly) {
helper.Call(MakeUniquePtrs({2}));
}
// A container whose iterator returns a temporary. This can iterate over the
// characters in a string.
class CharString {
public:
using value_type = char;
class const_iterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = char;
using difference_type = std::ptrdiff_t;
using pointer = const char*;
using reference = const char&;
// Create an iterator that points to the given character.
explicit const_iterator(const char* ptr) : ptr_(ptr) {}
// Returns the current character. IMPORTANT: this must return a temporary,
// not a reference, to test that ElementsAre() works with containers whose
// iterators return temporaries.
char operator*() const { return *ptr_; }
// Advances to the next character.
const_iterator& operator++() {
++ptr_;
return *this;
}
// Compares two iterators.
bool operator==(const const_iterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const const_iterator& other) const {
return ptr_ != other.ptr_;
}
private:
const char* ptr_ = nullptr;
};
// Creates a CharString that contains the given string.
explicit CharString(const std::string& s) : s_(s) {}
// Returns an iterator pointing to the first character in the string.
const_iterator begin() const { return const_iterator(s_.c_str()); }
// Returns an iterator pointing past the last character in the string.
const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }
private:
std::string s_;
};
// Tests using ElementsAre() with a container whose iterator returns a
// temporary.
TEST(ElementsAreTest, WorksWithContainerThatReturnsTempInIterator) {
CharString s("abc");
EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));
EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));
}
// Tests using ElementsAreArray() with a container whose iterator returns a
// temporary.
TEST(ElementsAreArrayTest, WorksWithContainerThatReturnsTempInIterator) {
CharString s("abc");
EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));
EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));
}
// A container whose iterator returns a temporary and is not copy-assignable.
// This simulates the behavior of the proxy object returned by absl::StrSplit().
class CharString2 {
public:
using value_type = char;
class const_iterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = char;
using difference_type = std::ptrdiff_t;
using pointer = const char*;
using reference = const char&;
// Make const_iterator copy-constructible but not copy-assignable,
// simulating the behavior of the proxy object returned by absl::StrSplit().
const_iterator(const const_iterator&) = default;
const_iterator& operator=(const const_iterator&) = delete;
// Create an iterator that points to the given character.
explicit const_iterator(const char* ptr) : ptr_(ptr) {}
// Returns the current character. IMPORTANT: this must return a temporary,
// not a reference, to test that ElementsAre() works with containers whose
// iterators return temporaries.
char operator*() const { return *ptr_; }
// Advances to the next character.
const_iterator& operator++() {
++ptr_;
return *this;
}
// Compares two iterators.
bool operator==(const const_iterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const const_iterator& other) const {
return ptr_ != other.ptr_;
}
private:
const char* ptr_ = nullptr;
};
// Creates a CharString that contains the given string.
explicit CharString2(const std::string& s) : s_(s) {}
// Returns an iterator pointing to the first character in the string.
const_iterator begin() const { return const_iterator(s_.c_str()); }
// Returns an iterator pointing past the last character in the string.
const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }
private:
std::string s_;
};
// Tests using ElementsAre() with a container whose iterator returns a
// temporary and is not copy-assignable.
TEST(ElementsAreTest, WorksWithContainerThatReturnsTempInUnassignableIterator) {
CharString2 s("abc");
EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));
EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));
}
// Tests using ElementsAreArray() with a container whose iterator returns a
// temporary and is not copy-assignable.
TEST(ElementsAreArrayTest,
WorksWithContainerThatReturnsTempInUnassignableIterator) {
CharString2 s("abc");
EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));
EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));
}
// A container whose iterator returns a temporary and is neither
// copy-constructible nor copy-assignable.
class CharString3 {
public:
using value_type = char;
class const_iterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = char;
using difference_type = std::ptrdiff_t;
using pointer = const char*;
using reference = const char&;
// Make const_iterator neither copy-constructible nor copy-assignable.
const_iterator(const const_iterator&) = delete;
const_iterator& operator=(const const_iterator&) = delete;
// Create an iterator that points to the given character.
explicit const_iterator(const char* ptr) : ptr_(ptr) {}
// Returns the current character. IMPORTANT: this must return a temporary,
// not a reference, to test that ElementsAre() works with containers whose
// iterators return temporaries.
char operator*() const { return *ptr_; }
// Advances to the next character.
const_iterator& operator++() {
++ptr_;
return *this;
}
// Compares two iterators.
bool operator==(const const_iterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const const_iterator& other) const {
return ptr_ != other.ptr_;
}
private:
const char* ptr_ = nullptr;
};
// Creates a CharString that contains the given string.
explicit CharString3(const std::string& s) : s_(s) {}
// Returns an iterator pointing to the first character in the string.
const_iterator begin() const { return const_iterator(s_.c_str()); }
// Returns an iterator pointing past the last character in the string.
const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }
private:
std::string s_;
};
// Tests using ElementsAre() with a container whose iterator returns a
// temporary and is neither copy-constructible nor copy-assignable.
TEST(ElementsAreTest, WorksWithContainerThatReturnsTempInUncopyableIterator) {
CharString3 s("abc");
EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));
EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));
}
// Tests using ElementsAreArray() with a container whose iterator returns a
// temporary and is neither copy-constructible nor copy-assignable.
TEST(ElementsAreArrayTest,
WorksWithContainerThatReturnsTempInUncopyableIterator) {
CharString3 s("abc");
EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));
EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));
}
// A container whose iterator returns a temporary, is neither
// copy-constructible nor copy-assignable, and has no member types.
class CharString4 {
public:
using value_type = char;
class const_iterator {
public:
// Do not define difference_type, etc.
// Make const_iterator neither copy-constructible nor copy-assignable.
const_iterator(const const_iterator&) = delete;
const_iterator& operator=(const const_iterator&) = delete;
// Create an iterator that points to the given character.
explicit const_iterator(const char* ptr) : ptr_(ptr) {}
// Returns the current character. IMPORTANT: this must return a temporary,
// not a reference, to test that ElementsAre() works with containers whose
// iterators return temporaries.
char operator*() const { return *ptr_; }
// Advances to the next character.
const_iterator& operator++() {
++ptr_;
return *this;
}
// Compares two iterators.
bool operator==(const const_iterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const const_iterator& other) const {
return ptr_ != other.ptr_;
}
private:
const char* ptr_ = nullptr;
};
// Creates a CharString that contains the given string.
explicit CharString4(const std::string& s) : s_(s) {}
// Returns an iterator pointing to the first character in the string.
const_iterator begin() const { return const_iterator(s_.c_str()); }
// Returns an iterator pointing past the last character in the string.
const_iterator end() const { return const_iterator(s_.c_str() + s_.size()); }
private:
std::string s_;
};
// Tests using ElementsAre() with a container whose iterator returns a
// temporary, is neither copy-constructible nor copy-assignable, and has no
// member types.
TEST(ElementsAreTest, WorksWithContainerWithIteratorWithNoMemberTypes) {
CharString4 s("abc");
EXPECT_THAT(s, ElementsAre('a', 'b', 'c'));
EXPECT_THAT(s, Not(ElementsAre('a', 'b', 'd')));
}
// Tests using ElementsAreArray() with a container whose iterator returns a
// temporary, is neither copy-constructible nor copy-assignable, and has no
// member types.
TEST(ElementsAreArrayTest, WorksWithContainerWithIteratorWithNoMemberTypes) {
CharString4 s("abc");
EXPECT_THAT(s, ElementsAreArray({'a', 'b', 'c'}));
EXPECT_THAT(s, Not(ElementsAreArray({'a', 'b', 'd'})));
}
// Tests using ElementsAre() and ElementsAreArray() with stream-like
// "containers".
@ -2134,8 +1826,8 @@ TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
}
TEST(UnorderedElementsAreArrayTest, VectorBool) {
const bool a[] = {false, true, false, true, true};
const bool b[] = {true, false, true, true, false};
const bool a[] = {0, 1, 0, 1, 1};
const bool b[] = {1, 0, 1, 1, 0};
std::vector<bool> expected(std::begin(a), std::end(a));
std::vector<bool> actual(std::begin(b), std::end(b));
StringMatchResultListener listener;
@ -2312,14 +2004,7 @@ TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
StringMatchResultListener listener;
EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
<< listener.str();
EXPECT_THAT(listener.str(),
Eq("which has 1 element\n"
"where the following matchers don't match any elements:\n"
"matcher #0: is equal to 1,\n"
"matcher #1: is equal to 2,\n"
"matcher #2: is equal to 3\n"
"and where the following elements don't match any matchers:\n"
"element #0: 4"));
EXPECT_THAT(listener.str(), Eq("which has 1 element"));
}
TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
@ -2327,11 +2012,7 @@ TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
StringMatchResultListener listener;
EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))
<< listener.str();
EXPECT_THAT(listener.str(),
Eq("where the following matchers don't match any elements:\n"
"matcher #0: is equal to 1,\n"
"matcher #1: is equal to 2,\n"
"matcher #2: is equal to 3"));
EXPECT_THAT(listener.str(), Eq(""));
}
TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
@ -2446,7 +2127,7 @@ TEST_P(EachTestP, ExplainsMatchResultCorrectly) {
Matcher<set<int>> m = Each(2);
EXPECT_EQ("", Explain(m, a));
Matcher<const int (&)[1]> n = Each(1); // NOLINT
Matcher<const int(&)[1]> n = Each(1); // NOLINT
const int b[1] = {1};
EXPECT_EQ("", Explain(n, b));
@ -2581,7 +2262,7 @@ TEST(PointwiseTest, MakesCopyOfRhs) {
rhs.push_back(4);
int lhs[] = {1, 2};
const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs);
EXPECT_THAT(lhs, m);
// Changing rhs now shouldn't affect m, which made a copy of rhs.
@ -2709,7 +2390,7 @@ TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
rhs.push_back(4);
int lhs[] = {2, 1};
const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
EXPECT_THAT(lhs, m);
// Changing rhs now shouldn't affect m, which made a copy of rhs.
@ -2747,7 +2428,7 @@ TEST(UnorderedPointwiseTest, RejectsWrongSize) {
const double lhs[2] = {1, 2};
const int rhs[1] = {0};
EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
EXPECT_EQ("which has 2 elements\n",
EXPECT_EQ("which has 2 elements",
Explain(UnorderedPointwise(Gt(), rhs), lhs));
const int rhs2[3] = {0, 1, 2};
@ -2796,7 +2477,7 @@ TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
}
TEST(PointeeTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, Pointee(Eq(3)));
EXPECT_THAT(p, Not(Pointee(Eq(2))));
}
@ -2960,11 +2641,11 @@ TEST_P(ElementsAreTestP, CanExplainMismatchRightSize) {
vector<int> v;
v.push_back(2);
v.push_back(1);
EXPECT_EQ(Explain(m, v), "whose element #0 (2) isn't equal to 1");
EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
v[0] = 1;
EXPECT_EQ(Explain(m, v),
"whose element #1 (1) is <= 5, which is 4 less than 5");
EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
Explain(m, v));
}
TEST(ElementsAreTest, MatchesOneElementVector) {
@ -3097,7 +2778,7 @@ TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
class NativeArrayPassedAsPointerAndSize {
public:
NativeArrayPassedAsPointerAndSize() = default;
NativeArrayPassedAsPointerAndSize() {}
MOCK_METHOD(void, Helper, (int* array, int size));
@ -3364,7 +3045,7 @@ TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
TEST_P(ContainsTestP, ExplainsMatchResultCorrectly) {
const int a[2] = {1, 2};
Matcher<const int (&)[2]> m = Contains(2);
Matcher<const int(&)[2]> m = Contains(2);
EXPECT_EQ("whose element #1 matches", Explain(m, a));
m = Contains(3);
@ -3443,4 +3124,6 @@ TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
} // namespace gmock_matchers_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif

View File

@ -31,22 +31,15 @@
//
// This file tests some commonly used argument matchers.
#include <array>
#include <cstdint>
#include <memory>
#include <ostream>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "test/gmock-matchers_test.h"
#include "gtest/gtest.h"
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
// possible loss of data and C4100, unreferenced local parameter
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244 4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4100)
#endif
#include "test/gmock-matchers_test.h"
namespace testing {
namespace gmock_matchers_test {
@ -79,7 +72,7 @@ TEST(AddressTest, Const) {
}
TEST(AddressTest, MatcherDoesntCopy) {
std::unique_ptr<int> n = std::make_unique<int>(1);
std::unique_ptr<int> n(new int(1));
const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));
EXPECT_TRUE(m.Matches(n));
@ -202,14 +195,14 @@ TEST(IsTrueTest, IsTrueIsFalse) {
EXPECT_THAT(nullptr, Not(IsTrue()));
EXPECT_THAT(nullptr, IsFalse());
std::unique_ptr<int> null_unique;
std::unique_ptr<int> nonnull_unique = std::make_unique<int>(0);
std::unique_ptr<int> nonnull_unique(new int(0));
EXPECT_THAT(null_unique, Not(IsTrue()));
EXPECT_THAT(null_unique, IsFalse());
EXPECT_THAT(nonnull_unique, IsTrue());
EXPECT_THAT(nonnull_unique, Not(IsFalse()));
}
#ifdef GTEST_HAS_TYPED_TEST
#if GTEST_HAS_TYPED_TEST
// Tests ContainerEq with different container types, and
// different element types.
@ -675,8 +668,6 @@ TEST_P(MatcherTupleTestP, ExplainsMatchFailure) {
// explanation.
}
#if GTEST_HAS_TYPED_TEST
// Sample optional type implementation with minimal requirements for use with
// Optional matcher.
template <typename T>
@ -694,94 +685,38 @@ class SampleOptional {
bool has_value_;
};
// Sample optional type implementation with alternative minimal requirements for
// use with Optional matcher. In particular, while it doesn't have a bool
// conversion operator, it does have a has_value() method.
template <typename T>
class SampleOptionalWithoutBoolConversion {
public:
using value_type = T;
explicit SampleOptionalWithoutBoolConversion(T value)
: value_(std::move(value)), has_value_(true) {}
SampleOptionalWithoutBoolConversion() : value_(), has_value_(false) {}
bool has_value() const { return has_value_; }
const T& operator*() const { return value_; }
private:
T value_;
bool has_value_;
};
template <typename T>
class OptionalTest : public testing::Test {};
using OptionalTestTypes =
testing::Types<SampleOptional<int>,
SampleOptionalWithoutBoolConversion<int>>;
TYPED_TEST_SUITE(OptionalTest, OptionalTestTypes);
TYPED_TEST(OptionalTest, DescribesSelf) {
const Matcher<TypeParam> m = Optional(Eq(1));
TEST(OptionalTest, DescribesSelf) {
const Matcher<SampleOptional<int>> m = Optional(Eq(1));
EXPECT_EQ("value is equal to 1", Describe(m));
}
TYPED_TEST(OptionalTest, ExplainsSelf) {
const Matcher<TypeParam> m = Optional(Eq(1));
EXPECT_EQ("whose value 1 matches", Explain(m, TypeParam(1)));
EXPECT_EQ("whose value 2 doesn't match", Explain(m, TypeParam(2)));
TEST(OptionalTest, ExplainsSelf) {
const Matcher<SampleOptional<int>> m = Optional(Eq(1));
EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
}
TYPED_TEST(OptionalTest, MatchesNonEmptyOptional) {
const Matcher<TypeParam> m1 = Optional(1);
const Matcher<TypeParam> m2 = Optional(Eq(2));
const Matcher<TypeParam> m3 = Optional(Lt(3));
TypeParam opt(1);
TEST(OptionalTest, MatchesNonEmptyOptional) {
const Matcher<SampleOptional<int>> m1 = Optional(1);
const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
SampleOptional<int> opt(1);
EXPECT_TRUE(m1.Matches(opt));
EXPECT_FALSE(m2.Matches(opt));
EXPECT_TRUE(m3.Matches(opt));
}
TYPED_TEST(OptionalTest, DoesNotMatchNullopt) {
const Matcher<TypeParam> m = Optional(1);
TypeParam empty;
TEST(OptionalTest, DoesNotMatchNullopt) {
const Matcher<SampleOptional<int>> m = Optional(1);
SampleOptional<int> empty;
EXPECT_FALSE(m.Matches(empty));
}
TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersTakingReferences) {
const Matcher<const int&> eq1 = Eq(1);
const Matcher<const int&> eq2 = Eq(2);
TypeParam opt(1);
EXPECT_THAT(opt, Optional(eq1));
EXPECT_THAT(opt, Optional(Not(eq2)));
EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2))));
TEST(OptionalTest, WorksWithMoveOnly) {
Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
}
TYPED_TEST(OptionalTest, ComposesWithMonomorphicMatchersRequiringConversion) {
const Matcher<int64_t> eq1 = Eq(1);
const Matcher<int64_t> eq2 = Eq(2);
TypeParam opt(1);
EXPECT_THAT(opt, Optional(eq1));
EXPECT_THAT(opt, Optional(Not(eq2)));
EXPECT_THAT(opt, Optional(AllOf(eq1, Not(eq2))));
}
template <typename T>
class MoveOnlyOptionalTest : public testing::Test {};
using MoveOnlyOptionalTestTypes =
testing::Types<SampleOptional<std::unique_ptr<int>>,
SampleOptionalWithoutBoolConversion<std::unique_ptr<int>>>;
TYPED_TEST_SUITE(MoveOnlyOptionalTest, MoveOnlyOptionalTestTypes);
TYPED_TEST(MoveOnlyOptionalTest, WorksWithMoveOnly) {
Matcher<TypeParam> m = Optional(Eq(nullptr));
EXPECT_TRUE(m.Matches(TypeParam(nullptr)));
}
#endif // GTEST_HAS_TYPED_TEST
class SampleVariantIntString {
public:
SampleVariantIntString(int i) : i_(i), has_int_(true) {}
@ -928,7 +863,7 @@ TEST(ArgsTest, AcceptsOneTemplateArg) {
}
TEST(ArgsTest, AcceptsTwoTemplateArgs) {
const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<0, 1>(Lt())));
EXPECT_THAT(t, (Args<1, 2>(Lt())));
@ -936,13 +871,13 @@ TEST(ArgsTest, AcceptsTwoTemplateArgs) {
}
TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<0, 0>(Eq())));
EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
}
TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
const std::tuple<short, int, long> t(short{4}, 5, 6L); // NOLINT
const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
EXPECT_THAT(t, (Args<2, 0>(Gt())));
EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
}
@ -957,7 +892,7 @@ TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
}
TEST(ArgsTest, CanBeNested) {
const std::tuple<short, int, long, int> t(short{4}, 5, 6L, 6); // NOLINT
const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
}
@ -1626,7 +1561,7 @@ TEST(AnyOfArrayTest, Matchers) {
}
TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {
// AnyOfArray and AllOfArray use the same underlying template-template,
// AnyOfArray and AllOfArry use the same underlying template-template,
// thus it is sufficient to test one here.
const std::vector<int> v0{};
const std::vector<int> v1{1};
@ -1635,10 +1570,10 @@ TEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {
const Matcher<int> m1 = AnyOfArray(v1);
const Matcher<int> m2 = AnyOfArray(v2);
EXPECT_EQ("", Explain(m0, 0));
EXPECT_EQ("which matches (is equal to 1)", Explain(m1, 1));
EXPECT_EQ("isn't equal to 1", Explain(m1, 2));
EXPECT_EQ("which matches (is equal to 3)", Explain(m2, 3));
EXPECT_EQ("isn't equal to 2, and isn't equal to 3", Explain(m2, 4));
EXPECT_EQ("", Explain(m1, 1));
EXPECT_EQ("", Explain(m1, 2));
EXPECT_EQ("", Explain(m2, 3));
EXPECT_EQ("", Explain(m2, 4));
EXPECT_EQ("()", Describe(m0));
EXPECT_EQ("(is equal to 1)", Describe(m1));
EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
@ -1665,7 +1600,7 @@ MATCHER(IsNotNull, "") { return arg != nullptr; }
// Verifies that a matcher defined using MATCHER() can work on
// move-only types.
TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, IsNotNull());
EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
}
@ -1675,25 +1610,11 @@ MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
// Verifies that a matcher defined using MATCHER_P*() can work on
// move-only types.
TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
std::unique_ptr<int> p = std::make_unique<int>(3);
std::unique_ptr<int> p(new int(3));
EXPECT_THAT(p, UniquePointee(3));
EXPECT_THAT(p, Not(UniquePointee(2)));
}
MATCHER(EnsureNoUnusedButMarkedUnusedWarning, "") { return (arg % 2) == 0; }
TEST(MockMethodMockFunctionTest, EnsureNoUnusedButMarkedUnusedWarning) {
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic error "-Wused-but-marked-unused"
#endif
// https://github.com/google/googletest/issues/4055
EXPECT_THAT(0, EnsureNoUnusedButMarkedUnusedWarning());
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}
#if GTEST_HAS_EXCEPTIONS
// std::function<void()> is used below for compatibility with older copies of
@ -1857,8 +1778,8 @@ TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
{
Matcher<uint64_t> inner = Eq(10);
Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
EXPECT_TRUE(matcher.Matches([]() { throw (uint32_t)10; }));
EXPECT_FALSE(matcher.Matches([]() { throw (uint32_t)11; }));
EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
}
}
@ -1879,4 +1800,6 @@ TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
} // namespace gmock_matchers_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4244 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif

View File

@ -148,9 +148,9 @@ class GreaterThanMatcher : public MatcherInterface<T> {
};
// 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)); \
#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> {

View File

@ -31,23 +31,22 @@
//
// This file tests the built-in actions in gmock-actions.h.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4577)
#endif
#include "gmock/gmock-more-actions.h"
#include <algorithm>
#include <functional>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4577)
namespace testing {
namespace gmock_more_actions_test {
@ -59,7 +58,6 @@ using testing::Invoke;
using testing::ReturnArg;
using testing::ReturnPointee;
using testing::SaveArg;
using testing::SaveArgByMove;
using testing::SaveArgPointee;
using testing::SetArgReferee;
using testing::Unused;
@ -86,16 +84,6 @@ struct UnaryFunctor {
int operator()(bool x) { return x ? 1 : -1; }
};
struct UnaryMoveOnlyFunctor : UnaryFunctor {
UnaryMoveOnlyFunctor() = default;
UnaryMoveOnlyFunctor(const UnaryMoveOnlyFunctor&) = delete;
UnaryMoveOnlyFunctor(UnaryMoveOnlyFunctor&&) = default;
};
struct OneShotUnaryFunctor {
int operator()(bool x) && { return x ? 1 : -1; }
};
const char* Binary(const char* input, short n) { return input + n; } // NOLINT
int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
@ -202,45 +190,45 @@ class Foo {
// Tests using Invoke() with a nullary function.
TEST(InvokeTest, Nullary) {
Action<int()> a = &Nullary;
Action<int()> a = Invoke(Nullary); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple()));
}
// Tests using Invoke() with a unary function.
TEST(InvokeTest, Unary) {
Action<bool(int)> a = &Unary;
Action<bool(int)> a = Invoke(Unary); // NOLINT
EXPECT_FALSE(a.Perform(std::make_tuple(1)));
EXPECT_TRUE(a.Perform(std::make_tuple(-1)));
}
// Tests using Invoke() with a binary function.
TEST(InvokeTest, Binary) {
Action<const char*(const char*, short)> a = &Binary; // NOLINT
Action<const char*(const char*, short)> a = Invoke(Binary); // NOLINT
const char* p = "Hello";
EXPECT_EQ(p + 2, a.Perform(std::make_tuple(p, Short(2))));
}
// Tests using Invoke() with a ternary function.
TEST(InvokeTest, Ternary) {
Action<int(int, char, short)> a = &Ternary; // NOLINT
Action<int(int, char, short)> a = Invoke(Ternary); // NOLINT
EXPECT_EQ(6, a.Perform(std::make_tuple(1, '\2', Short(3))));
}
// Tests using Invoke() with a 4-argument function.
TEST(InvokeTest, FunctionThatTakes4Arguments) {
Action<int(int, int, int, int)> a = &SumOf4;
Action<int(int, int, int, int)> a = Invoke(SumOf4); // NOLINT
EXPECT_EQ(1234, a.Perform(std::make_tuple(1000, 200, 30, 4)));
}
// Tests using Invoke() with a 5-argument function.
TEST(InvokeTest, FunctionThatTakes5Arguments) {
Action<int(int, int, int, int, int)> a = &SumOf5;
Action<int(int, int, int, int, int)> a = Invoke(SumOf5); // NOLINT
EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5)));
}
// Tests using Invoke() with a 6-argument function.
TEST(InvokeTest, FunctionThatTakes6Arguments) {
Action<int(int, int, int, int, int, int)> a = &SumOf6;
Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6); // NOLINT
EXPECT_EQ(123456,
a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6)));
}
@ -253,7 +241,7 @@ inline const char* CharPtr(const char* s) { return s; }
TEST(InvokeTest, FunctionThatTakes7Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*)>
a = &Concat7;
a = Invoke(Concat7);
EXPECT_EQ("1234567",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
@ -264,7 +252,7 @@ TEST(InvokeTest, FunctionThatTakes7Arguments) {
TEST(InvokeTest, FunctionThatTakes8Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*)>
a = &Concat8;
a = Invoke(Concat8);
EXPECT_EQ("12345678",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
@ -276,7 +264,7 @@ TEST(InvokeTest, FunctionThatTakes9Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*,
const char*)>
a = &Concat9;
a = Invoke(Concat9);
EXPECT_EQ("123456789", a.Perform(std::make_tuple(
CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
@ -288,7 +276,7 @@ TEST(InvokeTest, FunctionThatTakes10Arguments) {
Action<std::string(const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*,
const char*, const char*)>
a = &Concat10;
a = Invoke(Concat10);
EXPECT_EQ("1234567890",
a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
CharPtr("4"), CharPtr("5"), CharPtr("6"),
@ -298,12 +286,12 @@ TEST(InvokeTest, FunctionThatTakes10Arguments) {
// Tests using Invoke() with functions with parameters declared as Unused.
TEST(InvokeTest, FunctionWithUnusedParameters) {
Action<int(int, int, double, const std::string&)> a1 = &SumOfFirst2;
Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2);
std::tuple<int, int, double, std::string> dummy =
std::make_tuple(10, 2, 5.6, std::string("hi"));
EXPECT_EQ(12, a1.Perform(dummy));
Action<int(int, int, bool, int*)> a2 = &SumOfFirst2;
Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2);
EXPECT_EQ(
23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr))));
}
@ -320,13 +308,13 @@ TEST(InvokeTest, MethodWithUnusedParameters) {
// Tests using Invoke() with a functor.
TEST(InvokeTest, Functor) {
Action<long(long, int)> a = plus<long>(); // NOLINT
Action<long(long, int)> a = Invoke(plus<long>()); // NOLINT
EXPECT_EQ(3L, a.Perform(std::make_tuple(1, 2)));
}
// Tests using Invoke(f) as an action of a compatible type.
TEST(InvokeTest, FunctionWithCompatibleType) {
Action<long(int, short, char, bool)> a = &SumOf4; // NOLINT
Action<long(int, short, char, bool)> a = Invoke(SumOf4); // NOLINT
EXPECT_EQ(4321, a.Perform(std::make_tuple(4000, Short(300), Char(20), true)));
}
@ -447,13 +435,13 @@ TEST(InvokeMethodTest, MethodWithCompatibleType) {
// Tests using WithoutArgs with an action that takes no argument.
TEST(WithoutArgsTest, NoArg) {
Action<int(int n)> a = WithoutArgs(&Nullary); // NOLINT
Action<int(int n)> a = WithoutArgs(Invoke(Nullary)); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
}
// Tests using WithArg with an action that takes 1 argument.
TEST(WithArgTest, OneArg) {
Action<bool(double x, int n)> b = WithArg<1>(&Unary); // NOLINT
Action<bool(double x, int n)> b = WithArg<1>(Invoke(Unary)); // NOLINT
EXPECT_TRUE(b.Perform(std::make_tuple(1.5, -1)));
EXPECT_FALSE(b.Perform(std::make_tuple(1.5, 1)));
}
@ -493,34 +481,6 @@ TEST(SaveArgActionTest, WorksForCompatibleType) {
EXPECT_EQ('a', result);
}
struct MoveOnly {
explicit MoveOnly(int v) : i(v) {}
MoveOnly(MoveOnly&& o) {
i = o.i;
o.i = -1;
}
MoveOnly& operator=(MoveOnly&& o) {
i = o.i;
o.i = -1;
return *this;
}
int i;
};
TEST(SaveArgByMoveActionTest, WorksForSameType) {
MoveOnly result{0};
const Action<void(MoveOnly v)> a1 = SaveArgByMove<0>(&result);
a1.Perform(std::make_tuple(MoveOnly{5}));
EXPECT_EQ(5, result.i);
}
TEST(SaveArgByMoveActionTest, WorksForCompatibleType) {
MoveOnly result{0};
const Action<void(bool, MoveOnly)> a1 = SaveArgByMove<1>(&result);
a1.Perform(std::make_tuple(true, MoveOnly{7}));
EXPECT_EQ(7, result.i);
}
TEST(SaveArgPointeeActionTest, WorksForSameType) {
int result = 0;
const int value = 5;
@ -716,7 +676,7 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) {
Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end());
std::string s;
a.Perform(std::make_tuple(true, std::back_inserter(s)));
a.Perform(std::make_tuple(true, back_inserter(s)));
EXPECT_EQ(letters, s);
}
@ -737,24 +697,12 @@ TEST(InvokeArgumentTest, Function0) {
EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary)));
}
// Tests using InvokeArgument with a unary functor.
// Tests using InvokeArgument with a unary function.
TEST(InvokeArgumentTest, Functor1) {
Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor())));
}
// Tests using InvokeArgument with a unary move-only functor.
TEST(InvokeArgumentTest, Functor1MoveOnly) {
Action<int(UnaryMoveOnlyFunctor)> a = InvokeArgument<0>(true); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryMoveOnlyFunctor())));
}
// Tests using InvokeArgument with a one-shot unary functor.
TEST(InvokeArgumentTest, OneShotFunctor1) {
Action<int(OneShotUnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT
EXPECT_EQ(1, a.Perform(std::make_tuple(OneShotUnaryFunctor())));
}
// Tests using InvokeArgument with a 5-ary function.
TEST(InvokeArgumentTest, Function5) {
Action<int(int (*)(int, int, int, int, int))> a = // NOLINT
@ -785,34 +733,34 @@ TEST(InvokeArgumentTest, Functor6) {
// Tests using InvokeArgument with a 7-ary function.
TEST(InvokeArgumentTest, Function7) {
Action<std::string(std::string (*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*))>
Action<std::string(std::string(*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*))>
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7)));
}
// Tests using InvokeArgument with a 8-ary function.
TEST(InvokeArgumentTest, Function8) {
Action<std::string(std::string (*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*, const char*))>
Action<std::string(std::string(*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*, const char*))>
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8)));
}
// Tests using InvokeArgument with a 9-ary function.
TEST(InvokeArgumentTest, Function9) {
Action<std::string(std::string (*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*, const char*, const char*))>
Action<std::string(std::string(*)(const char*, const char*, const char*,
const char*, const char*, const char*,
const char*, const char*, const char*))>
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9)));
}
// Tests using InvokeArgument with a 10-ary function.
TEST(InvokeArgumentTest, Function10) {
Action<std::string(std::string (*)(
Action<std::string(std::string(*)(
const char*, const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*, const char*))>
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
@ -857,22 +805,6 @@ TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {
EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));
}
TEST(InvokeArgumentTest, MoveOnlyType) {
struct Marker {};
struct {
// Method takes a unique_ptr (to a type we don't care about), and an
// invocable type.
MOCK_METHOD(bool, MockMethod,
(std::unique_ptr<Marker>, std::function<int()>), ());
} mock;
ON_CALL(mock, MockMethod(_, _)).WillByDefault(InvokeArgument<1>());
// This compiles, but is a little opaque as a workaround:
ON_CALL(mock, MockMethod(_, _))
.WillByDefault(WithArg<1>(InvokeArgument<0>()));
}
// Tests DoAll(a1, a2).
TEST(DoAllTest, TwoActions) {
int n = 0;
@ -1050,7 +982,11 @@ TEST(DoAllTest, ImplicitlyConvertsActionArguments) {
// is expanded and macro expansion cannot contain #pragma. Therefore
// we suppress them here.
// Also suppress C4503 decorated name length exceeded, name was truncated
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4503)
#endif
// Tests the ACTION*() macro family.
// Tests that ACTION() can define an action that doesn't reference the
@ -1612,6 +1548,3 @@ TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {
} // namespace gmock_more_actions_test
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4577

View File

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

View File

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

View File

@ -98,7 +98,7 @@ class NonDefaultConstructible {
class MockA {
public:
MockA() = default;
MockA() {}
MOCK_METHOD1(DoA, void(int n));
MOCK_METHOD1(ReturnResult, Result(int n));
@ -113,7 +113,7 @@ class MockA {
class MockB {
public:
MockB() = default;
MockB() {}
MOCK_CONST_METHOD0(DoB, int()); // NOLINT
MOCK_METHOD1(DoB, int(int n)); // NOLINT
@ -125,7 +125,7 @@ class MockB {
class ReferenceHoldingMock {
public:
ReferenceHoldingMock() = default;
ReferenceHoldingMock() {}
MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
@ -143,12 +143,12 @@ class ReferenceHoldingMock {
class CC {
public:
virtual ~CC() = default;
virtual ~CC() {}
virtual int Method() = 0;
};
class MockCC : public CC {
public:
MockCC() = default;
MockCC() {}
MOCK_METHOD0(Method, int());
@ -160,7 +160,7 @@ class MockCC : public CC {
// Tests that a method with expanded name compiles.
TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
MockCC cc;
(void)ON_CALL(cc, Method());
ON_CALL(cc, Method());
}
// Tests that the method with expanded name not only compiles but runs
@ -193,7 +193,7 @@ TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
MockA a;
MockA* pa = &a;
(void)ON_CALL(*pa++, DoA(_));
ON_CALL(*pa++, DoA(_));
EXPECT_EQ(&a + 1, pa);
}
@ -201,7 +201,7 @@ TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
MockA a;
int n = 0;
(void)ON_CALL(a, DoA(n++));
ON_CALL(a, DoA(n++));
EXPECT_EQ(1, n);
}
@ -232,7 +232,7 @@ TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
EXPECT_DEATH_IF_SUPPORTED(
{
(void)ON_CALL(a, DoA(5));
ON_CALL(a, DoA(5));
a.DoA(5);
},
"");
@ -739,12 +739,11 @@ TEST(ExpectCallTest, CatchesTooFewCalls) {
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
MockB b;
EXPECT_CALL(b, DoB(5)).Description("DoB Method").Times(AtLeast(2));
EXPECT_CALL(b, DoB(5)).Times(AtLeast(2));
b.DoB(5);
},
"Actual function \"DoB Method\" call count "
"doesn't match EXPECT_CALL(b, DoB(5))...\n"
"Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
" Expected: to be called at least twice\n"
" Actual: called once - unsatisfied and active");
}
@ -804,39 +803,39 @@ TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
"to be called at least once");
}
// TODO(b/396121064) - Fix this test under MSVC
#ifndef _MSC_VER
#if defined(__cplusplus) && __cplusplus >= 201703L
// It should be possible to return a non-moveable type from a mock action in
// C++17 and above, where it's guaranteed that such a type can be initialized
// from a prvalue returned from a function.
TEST(ExpectCallTest, NonMoveableType) {
// Define a non-moveable result type.
struct NonMoveableStruct {
explicit NonMoveableStruct(int x_in) : x(x_in) {}
NonMoveableStruct(NonMoveableStruct&&) = delete;
struct Result {
explicit Result(int x_in) : x(x_in) {}
Result(Result&&) = delete;
int x;
};
static_assert(!std::is_move_constructible_v<NonMoveableStruct>);
static_assert(!std::is_copy_constructible_v<NonMoveableStruct>);
static_assert(!std::is_move_constructible_v<Result>);
static_assert(!std::is_copy_constructible_v<Result>);
static_assert(!std::is_move_assignable_v<NonMoveableStruct>);
static_assert(!std::is_copy_assignable_v<NonMoveableStruct>);
static_assert(!std::is_move_assignable_v<Result>);
static_assert(!std::is_copy_assignable_v<Result>);
// We should be able to use a callable that returns that result as both a
// OnceAction and an Action, whether the callable ignores arguments or not.
const auto return_17 = [] { return NonMoveableStruct(17); };
const auto return_17 = [] { return Result(17); };
static_cast<void>(OnceAction<NonMoveableStruct()>{return_17});
static_cast<void>(Action<NonMoveableStruct()>{return_17});
static_cast<void>(OnceAction<Result()>{return_17});
static_cast<void>(Action<Result()>{return_17});
static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17});
static_cast<void>(Action<NonMoveableStruct(int)>{return_17});
static_cast<void>(OnceAction<Result(int)>{return_17});
static_cast<void>(Action<Result(int)>{return_17});
// It should be possible to return the result end to end through an
// EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
MockFunction<NonMoveableStruct()> mock;
MockFunction<Result()> mock;
EXPECT_CALL(mock, Call) //
.WillOnce(return_17) //
.WillRepeatedly(return_17);
@ -846,7 +845,7 @@ TEST(ExpectCallTest, NonMoveableType) {
EXPECT_EQ(17, mock.AsStdFunction()().x);
}
#endif // _MSC_VER
#endif // C++17 and above
// Tests that the n-th action is taken for the n-th matching
// invocation.
@ -905,7 +904,7 @@ TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
" - returning default value."));
}
TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) {
TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
MockB b;
std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
@ -1065,7 +1064,7 @@ TEST(UnexpectedCallTest, UnmatchedArguments) {
// Tests that Google Mock explains that an expectation with
// unsatisfied pre-requisites doesn't match the call.
TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
Sequence s1, s2;
MockB b;
EXPECT_CALL(b, DoB(1)).InSequence(s1);
@ -1088,7 +1087,16 @@ TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
// Verifies that the failure message contains the two unsatisfied
// pre-requisites but not the satisfied one.
#ifdef GTEST_USES_POSIX_RE
#if GTEST_USES_PCRE
EXPECT_THAT(
r.message(),
ContainsRegex(
// PCRE has trouble using (.|\n) to match any character, but
// supports the (?s) prefix for using . to match any character.
"(?s)the following immediate pre-requisites are not satisfied:\n"
".*: pre-requisite #0\n"
".*: pre-requisite #1"));
#elif GTEST_USES_POSIX_RE
EXPECT_THAT(r.message(),
ContainsRegex(
// POSIX RE doesn't understand the (?s) prefix, but has no
@ -1103,7 +1111,7 @@ TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
"the following immediate pre-requisites are not satisfied:"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
#endif // GTEST_USES_POSIX_RE
#endif // GTEST_USES_PCRE
b.DoB(1);
b.DoB(3);
@ -1140,11 +1148,10 @@ TEST(ExcessiveCallTest, DoesDefaultAction) {
// When there is no ON_CALL(), the default value for the return type
// should be returned.
MockB b;
EXPECT_CALL(b, DoB(0)).Description("DoB Method").Times(0);
EXPECT_CALL(b, DoB(0)).Times(0);
int n = -1;
EXPECT_NONFATAL_FAILURE(
n = b.DoB(0),
"Mock function \"DoB Method\" called more times than expected");
EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
"Mock function called more times than expected");
EXPECT_EQ(0, n);
}
@ -1152,11 +1159,10 @@ TEST(ExcessiveCallTest, DoesDefaultAction) {
// the failure message contains the argument values.
TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
MockA a;
EXPECT_CALL(a, DoA(_)).Description("DoA Method").Times(0);
EXPECT_CALL(a, DoA(_)).Times(0);
EXPECT_NONFATAL_FAILURE(
a.DoA(9),
"Mock function \"DoA Method\" called more times than expected - "
"returning directly.\n"
"Mock function called more times than expected - returning directly.\n"
" Function call: DoA(9)\n"
" Expected: to be never called\n"
" Actual: called once - over-saturated and active");
@ -1770,11 +1776,16 @@ TEST(DeletingMockEarlyTest, Success2) {
// Suppresses warning on unreferenced formal parameter in MSVC with
// -W4.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
ACTION_P(Delete, ptr) { delete ptr; }
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
MockA* const a = new MockA;
@ -1881,7 +1892,7 @@ struct Unprintable {
class MockC {
public:
MockC() = default;
MockC() {}
MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
const Printable& x, Unprintable y));
@ -2045,12 +2056,12 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
NaggyMock<MockA> a;
const std::string note =
"NOTE: You can safely ignore the above warning unless this "
"call should not happen. Do not suppress it by adding "
"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/"
"https://github.com/google/googletest/blob/master/docs/"
"gmock_cook_book.md#"
"knowing-when-to-expect-useoncall for details.";
"knowing-when-to-expect for details.";
// A void-returning function.
CaptureStdout();
@ -2121,7 +2132,7 @@ void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
class LogTestHelper {
public:
LogTestHelper() = default;
LogTestHelper() {}
MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
@ -2588,7 +2599,14 @@ TEST(ParameterlessExpectationsTest,
} // namespace
} // namespace testing
// Allows the user to define their own main and then invoke gmock_main
// from it. This might be necessary on some platforms which require
// specific setup and teardown.
#if GMOCK_RENAME_MAIN
int gmock_main(int argc, char** argv) {
#else
int main(int argc, char** argv) {
#endif // GMOCK_RENAME_MAIN
testing::InitGoogleMock(&argc, argv);
// Ensures that the tests pass no matter what value of
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.

View File

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

View File

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

View File

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

View File

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

View File

@ -39,7 +39,7 @@ gmock_output_test.py
"""
from io import open # pylint: disable=redefined-builtin, g-importing-member
from io import open # pylint: disable=redefined-builtin, g-importing-member
import os
import re
import sys
@ -159,22 +159,15 @@ class GMockOutputTest(gmock_test_utils.TestCase):
golden_file = open(GOLDEN_PATH, 'rb')
golden = golden_file.read().decode('utf-8')
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.
self.assertEqual(golden, output)
# The raw output should contain 2 leaked mock object errors for
# test GMockOutputTest.CatchesLeakedMocks.
self.assertEqual(
[
'GMockOutputTest.CatchesLeakedMocks',
'GMockOutputTest.CatchesLeakedMocks',
],
leaky_tests,
)
self.assertEqual(['GMockOutputTest.CatchesLeakedMocks',
'GMockOutputTest.CatchesLeakedMocks'],
leaky_tests)
if __name__ == '__main__':

View File

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

View File

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

View File

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

View File

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

View File

@ -5,7 +5,7 @@
# CMake build script for Google Test.
#
# To run the tests for Google Test itself on Linux, use 'make test' or
# ctest. You can select which tests to run using 'ctest -R regex'.
# ctest. You can select which tests to run using 'ctest -R regex'.
# For more options, run 'ctest --help'.
# When other libraries are using a shared version of runtime libraries,
@ -35,7 +35,7 @@ endif()
########################################################################
#
# Project-wide settings.
# Project-wide settings
# Name of the project.
#
@ -44,16 +44,21 @@ endif()
# ${gtest_BINARY_DIR}.
# Language "C" is required for find_package(Threads).
# Project version.
# Project version:
cmake_minimum_required(VERSION 3.13)
cmake_minimum_required(VERSION 3.5)
cmake_policy(SET CMP0048 NEW)
project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
if (POLICY CMP0063) # Visibility
cmake_policy(SET CMP0063 NEW)
endif (POLICY CMP0063)
if (COMMAND set_up_hermetic_build)
set_up_hermetic_build()
endif()
# These commands only run if this is the main project.
# These commands only run if this is the main project
if(CMAKE_PROJECT_NAME STREQUAL "gtest" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution")
# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to
@ -83,7 +88,7 @@ include(cmake/internal_utils.cmake)
config_compiler_and_linker() # Defined in internal_utils.cmake.
# Needed to set the namespace for both the export targets and the
# alias libraries.
# alias libraries
set(cmake_package_name GTest CACHE INTERNAL "")
# Create the CMake package file descriptors.
@ -95,14 +100,12 @@ if (INSTALL_GTEST)
set(version_file "${generated_dir}/${cmake_package_name}ConfigVersion.cmake")
write_basic_package_version_file(${version_file} VERSION ${GOOGLETEST_VERSION} COMPATIBILITY AnyNewerVersion)
install(EXPORT ${targets_export_name}
COMPONENT "${PROJECT_NAME}"
NAMESPACE ${cmake_package_name}::
DESTINATION ${cmake_files_install_dir})
set(config_file "${generated_dir}/${cmake_package_name}Config.cmake")
configure_package_config_file("${gtest_SOURCE_DIR}/cmake/Config.cmake.in"
"${config_file}" INSTALL_DESTINATION ${cmake_files_install_dir})
install(FILES ${version_file} ${config_file}
COMPONENT "${PROJECT_NAME}"
DESTINATION ${cmake_files_install_dir})
endif()
@ -114,52 +117,44 @@ include_directories(${gtest_build_include_dirs})
########################################################################
#
# Defines the gtest & gtest_main libraries. User tests should link
# Defines the gtest & gtest_main libraries. User tests should link
# with one of them.
# Google Test libraries. We build them using more strict warnings than what
# Google Test libraries. We build them using more strict warnings than what
# are used for other targets, to ensure that gtest can be compiled by a user
# aggressive about warnings.
cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
set_target_properties(gtest PROPERTIES VERSION ${GOOGLETEST_VERSION})
if(GTEST_HAS_ABSL)
target_compile_definitions(gtest PUBLIC GTEST_HAS_ABSL=1)
target_link_libraries(gtest PUBLIC
absl::failure_signal_handler
absl::stacktrace
absl::symbolize
absl::flags_parse
absl::flags_reflection
absl::flags_usage
absl::strings
re2::re2
)
endif()
cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
string(REPLACE ";" "$<SEMICOLON>" dirs "${gtest_build_include_dirs}")
target_include_directories(gtest SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gtest_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
if(CMAKE_SYSTEM_NAME MATCHES "QNX" AND CMAKE_SYSTEM_VERSION VERSION_GREATER_EQUAL 7.1)
# If the CMake version supports it, attach header directory information
# to the targets for when we are part of a parent build (ie being pulled
# in via add_subdirectory() rather than being a standalone build).
if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
string(REPLACE ";" "$<SEMICOLON>" dirs "${gtest_build_include_dirs}")
target_include_directories(gtest SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
target_include_directories(gtest_main SYSTEM INTERFACE
"$<BUILD_INTERFACE:${dirs}>"
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
endif()
if(CMAKE_SYSTEM_NAME MATCHES "QNX")
target_link_libraries(gtest PUBLIC regex)
endif()
target_link_libraries(gtest_main PUBLIC gtest)
########################################################################
#
# Install rules.
# Install rules
install_project(gtest gtest_main)
########################################################################
#
# Samples on how to link user tests with gtest or gtest_main.
#
# They are not built by default. To build them, set the
# gtest_build_samples option to ON. You can do it by running ccmake
# They are not built by default. To build them, set the
# gtest_build_samples option to ON. You can do it by running ccmake
# or specifying the -Dgtest_build_samples=ON flag when running cmake.
if (gtest_build_samples)
@ -182,8 +177,8 @@ endif()
# You can skip this section if you aren't interested in testing
# Google Test itself.
#
# The tests are not built by default. To build them, set the
# gtest_build_tests option to ON. You can do it by running ccmake
# The tests are not built by default. To build them, set the
# gtest_build_tests option to ON. You can do it by running ccmake
# or specifying the -Dgtest_build_tests=ON flag when running cmake.
if (gtest_build_tests)
@ -265,7 +260,7 @@ if (gtest_build_tests)
py_test(gtest_skip_environment_check_output_test)
# Visual Studio .NET 2003 does not support STL with exceptions disabled.
if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003
if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003
cxx_executable_with_flags(
googletest-catch-exceptions-no-ex-test_
"${cxx_no_exception}"

View File

@ -9,10 +9,10 @@ depends on which build system you use, and is usually straightforward.
### Build with CMake
GoogleTest comes with a CMake build script
([CMakeLists.txt](https://github.com/google/googletest/blob/main/CMakeLists.txt))
([CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt))
that can be used on a wide range of platforms ("C" stands for cross-platform.).
If you don't have CMake installed already, you can download it for free from
<https://cmake.org/>.
<http://www.cmake.org/>.
CMake works by generating native makefiles or build projects that can be used in
the compiler environment of your choice. You can either build GoogleTest as a
@ -25,7 +25,7 @@ When building GoogleTest as a standalone project, the typical workflow starts
with
```
git clone https://github.com/google/googletest.git -b v1.17.0
git clone https://github.com/google/googletest.git -b release-1.11.0
cd googletest # Main directory of the cloned repository.
mkdir build # Create a directory to hold the build output.
cd build
@ -94,7 +94,7 @@ include(FetchContent)
FetchContent_Declare(
googletest
# Specify the commit you depend on and update it regularly.
URL https://github.com/google/googletest/archive/5376968f6948923e2411081fd9372e71a59d8e77.zip
URL https://github.com/google/googletest/archive/e2239ee6043f73722e7aa812a459f54a28552929.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
@ -124,12 +124,12 @@ match the project in which it is included.
#### C++ Standard Version
An environment that supports C++17 is required in order to successfully build
An environment that supports C++11 is required in order to successfully build
GoogleTest. One way to ensure this is to specify the standard in the top-level
project, for example by using the `set(CMAKE_CXX_STANDARD 17)` command along
with `set(CMAKE_CXX_STANDARD_REQUIRED ON)`. If this is not feasible, for example
in a C project using GoogleTest for validation, then it can be specified by
adding it to the options for cmake via the`-DCMAKE_CXX_FLAGS` option.
project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command. If this
is not feasible, for example in a C project using GoogleTest for validation,
then it can be specified by adding it to the options for cmake via the
`DCMAKE_CXX_FLAGS` option.
### Tweaking GoogleTest
@ -140,27 +140,23 @@ command line. Generally, these macros are named like `GTEST_XYZ` and you define
them to either 1 or 0 to enable or disable a certain feature.
We list the most frequently used macros below. For a complete list, see file
[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/main/googletest/include/gtest/internal/gtest-port.h).
[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-port.h).
### Multi-threaded Tests
GoogleTest is thread-safe where the pthread library is available. After
`#include <gtest/gtest.h>`, you can check the `GTEST_IS_THREADSAFE` macro to see
whether this is the case (yes if the macro is `#defined` to 1, no if it's
undefined.).
`#include "gtest/gtest.h"`, you can check the
`GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is
`#defined` to 1, no if it's undefined.).
If GoogleTest doesn't correctly detect whether pthread is available in your
environment, you can force it with
```
-DGTEST_HAS_PTHREAD=1
```
-DGTEST_HAS_PTHREAD=1
or
```
-DGTEST_HAS_PTHREAD=0
```
-DGTEST_HAS_PTHREAD=0
When GoogleTest uses pthread, you may need to add flags to your compiler and/or
linker to select the pthread library, or you'll get link errors. If you use the
@ -176,27 +172,23 @@ as a DLL on Windows) if you prefer.
To compile *gtest* as a shared library, add
```
-DGTEST_CREATE_SHARED_LIBRARY=1
```
-DGTEST_CREATE_SHARED_LIBRARY=1
to the compiler flags. You'll also need to tell the linker to produce a shared
library instead - consult your linker's manual for how to do it.
To compile your *tests* that use the gtest shared library, add
```
-DGTEST_LINKED_AS_SHARED_LIBRARY=1
```
-DGTEST_LINKED_AS_SHARED_LIBRARY=1
to the compiler flags.
Note: while the above steps aren't technically necessary today when using some
compilers (e.g. GCC), they may become necessary in the future, if we decide to
improve the speed of loading the library (see
<https://gcc.gnu.org/wiki/Visibility> for details). Therefore you are
recommended to always add the above flags when using GoogleTest as a shared
library. Otherwise a future release of GoogleTest may break your build script.
<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended
to always add the above flags when using GoogleTest as a shared library.
Otherwise a future release of GoogleTest may break your build script.
### Avoiding Macro Name Clashes
@ -208,9 +200,7 @@ rename its macro to avoid the conflict.
Specifically, if both GoogleTest and some other code define macro FOO, you can
add
```
-DGTEST_DONT_DEFINE_FOO=1
```
-DGTEST_DONT_DEFINE_FOO=1
to the compiler flags to tell GoogleTest to change the macro's name from `FOO`
to `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`,
@ -218,14 +208,10 @@ to `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`,
`EXPECT_FALSE`, `EXPECT_TRUE`, `FAIL`, `SUCCEED`, `TEST`, or `TEST_F`. For
example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
```
GTEST_TEST(SomeTest, DoesThis) { ... }
```
GTEST_TEST(SomeTest, DoesThis) { ... }
instead of
```
TEST(SomeTest, DoesThis) { ... }
```
TEST(SomeTest, DoesThis) { ... }
in order to define a test.

View File

@ -4,10 +4,6 @@ if (@GTEST_HAS_PTHREAD@)
set(THREADS_PREFER_PTHREAD_FLAG @THREADS_PREFER_PTHREAD_FLAG@)
find_dependency(Threads)
endif()
if (@GTEST_HAS_ABSL@)
find_dependency(absl)
find_dependency(re2)
endif()
include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake")
check_required_components("@project_name@")

View File

@ -12,14 +12,17 @@
# Test and Google Mock's option() definitions, and thus must be
# called *after* the options have been defined.
if (POLICY CMP0054)
cmake_policy(SET CMP0054 NEW)
endif (POLICY CMP0054)
# Tweaks CMake's default compiler/linker settings to suit Google Test's needs.
#
# This must be a macro(), as inside a function string() can only
# update variables in the function scope.
macro(fix_default_compiler_settings_)
if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC|Clang")
# For MSVC and Clang, CMake sets certain flags to defaults we want to
# override.
if (MSVC)
# For MSVC, CMake sets certain flags to defaults we want to override.
# This replacement code is taken from sample in the CMake Wiki at
# https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace.
foreach (flag_var
@ -29,17 +32,13 @@ macro(fix_default_compiler_settings_)
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt)
# When Google Test is built as a shared library, it should also use
# shared runtime libraries. Otherwise, it may end up with multiple
# shared runtime libraries. Otherwise, it may end up with multiple
# copies of runtime library data in different modules, resulting in
# hard-to-find crashes. When it is built as a static library, it is
# preferable to use CRT as static libraries, as we don't have to rely
# on CRT DLLs being available. CMake always defaults to using shared
# CRT libraries, so we override that default here.
string(REPLACE "/MD" "-MT" ${flag_var} "${${flag_var}}")
# When using Ninja with Clang, static builds pass -D_DLL on Windows.
# This is incorrect and should not happen, so we fix that here.
string(REPLACE "-D_DLL" "" ${flag_var} "${${flag_var}}")
endif()
# We prefer more strict warning checking for building Google Test.
@ -55,11 +54,11 @@ macro(fix_default_compiler_settings_)
endmacro()
# Defines the compiler/linker flags used to build Google Test and
# Google Mock. You can tweak these definitions to suit your need. A
# Google Mock. You can tweak these definitions to suit your need. A
# variable's value is empty before it's explicitly assigned to.
macro(config_compiler_and_linker)
# Note: pthreads on MinGW is not supported, even if available
# instead, we use windows threading primitives.
# instead, we use windows threading primitives
unset(GTEST_HAS_PTHREAD)
if (NOT gtest_disable_pthreads AND NOT MINGW)
# Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT.
@ -79,38 +78,26 @@ macro(config_compiler_and_linker)
set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1")
set(cxx_no_exception_flags "-EHs-c- -D_HAS_EXCEPTIONS=0")
set(cxx_no_rtti_flags "-GR-")
# Suppress "unreachable code" warning,
# https://stackoverflow.com/questions/3232669 explains the issue.
# Suppress "unreachable code" warning
# http://stackoverflow.com/questions/3232669 explains the issue.
set(cxx_base_flags "${cxx_base_flags} -wd4702")
# Ensure MSVC treats source files as UTF-8 encoded.
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
set(cxx_base_flags "${cxx_base_flags} -utf-8")
endif()
if (CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
set(cxx_base_flags "${cxx_base_flags} /fp:precise -Wno-inconsistent-missing-override -Wno-microsoft-exception-spec -Wno-unused-function -Wno-unused-but-set-variable")
endif()
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR
CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
set(cxx_base_flags "-Wall -Wshadow -Wconversion -Wundef")
set(cxx_base_flags "${cxx_base_flags} -utf-8")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(cxx_base_flags "-Wall -Wshadow -Wconversion")
set(cxx_exception_flags "-fexceptions")
set(cxx_no_exception_flags "-fno-exceptions")
set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Winline -Wredundant-decls")
set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Wchar-subscripts -Winline -Wredundant-decls")
set(cxx_no_rtti_flags "-fno-rtti")
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(cxx_strict_flags "${cxx_strict_flags} -Wchar-subscripts")
endif()
if (CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
set(cxx_base_flags "${cxx_base_flags} -Wno-implicit-float-size-conversion -ffp-model=precise")
endif()
elseif (CMAKE_COMPILER_IS_GNUCXX)
set(cxx_base_flags "-Wall -Wshadow -Wundef")
set(cxx_base_flags "-Wall -Wshadow")
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0)
set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else")
endif()
set(cxx_exception_flags "-fexceptions")
set(cxx_no_exception_flags "-fno-exceptions")
# Until version 4.3.2, GCC doesn't define a macro to indicate
# whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI
# whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI
# explicitly.
set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0")
set(cxx_strict_flags
@ -127,7 +114,7 @@ macro(config_compiler_and_linker)
set(cxx_exception_flags "-qeh")
set(cxx_no_exception_flags "-qnoeh")
# Until version 9.0, Visual Age doesn't define a macro to indicate
# whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI
# whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI
# explicitly.
set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "HP")
@ -157,7 +144,7 @@ macro(config_compiler_and_linker)
set(cxx_strict "${cxx_default} ${cxx_strict_flags}")
endmacro()
# Defines the gtest & gtest_main libraries. User tests should link
# Defines the gtest & gtest_main libraries. User tests should link
# with one of them.
function(cxx_library_with_type name type cxx_flags)
# type can be either STATIC or SHARED to denote a static or shared library.
@ -167,15 +154,14 @@ function(cxx_library_with_type name type cxx_flags)
set_target_properties(${name}
PROPERTIES
COMPILE_FLAGS "${cxx_flags}")
# Set the output directory for build artifacts.
# Set the output directory for build artifacts
set_target_properties(${name}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")
# Make PDBs match library name.
PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
# make PDBs match library name
get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX)
set_target_properties(${name}
PROPERTIES
@ -188,14 +174,23 @@ function(cxx_library_with_type name type cxx_flags)
set_target_properties(${name}
PROPERTIES
COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1")
target_compile_definitions(${name} INTERFACE
$<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
if (NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
target_compile_definitions(${name} INTERFACE
$<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
endif()
endif()
if (DEFINED GTEST_HAS_PTHREAD)
target_link_libraries(${name} PUBLIC Threads::Threads)
if ("${CMAKE_VERSION}" VERSION_LESS "3.1.0")
set(threads_spec ${CMAKE_THREAD_LIBS_INIT})
else()
set(threads_spec Threads::Threads)
endif()
target_link_libraries(${name} PUBLIC ${threads_spec})
endif()
target_compile_features(${name} PUBLIC cxx_std_17)
if (NOT "${CMAKE_VERSION}" VERSION_LESS "3.8")
target_compile_features(${name} PUBLIC cxx_std_11)
endif()
endfunction()
########################################################################
@ -212,7 +207,7 @@ endfunction()
# cxx_executable_with_flags(name cxx_flags libs srcs...)
#
# Creates a named C++ executable that depends on the given libraries and
# creates a named C++ executable that depends on the given libraries and
# is built from the given source files with the given compiler flags.
function(cxx_executable_with_flags name cxx_flags libs)
add_executable(${name} ${ARGN})
@ -239,21 +234,26 @@ endfunction()
# cxx_executable(name dir lib srcs...)
#
# Creates a named target that depends on the given libs and is built
# from the given source files. dir/name.cc is implicitly included in
# creates a named target that depends on the given libs and is built
# from the given source files. dir/name.cc is implicitly included in
# the source file list.
function(cxx_executable name dir libs)
cxx_executable_with_flags(
${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN})
endfunction()
if(gtest_build_tests)
find_package(Python3)
# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
if ("${CMAKE_VERSION}" VERSION_LESS "3.12.0")
find_package(PythonInterp)
else()
find_package(Python COMPONENTS Interpreter)
set(PYTHONINTERP_FOUND ${Python_Interpreter_FOUND})
set(PYTHON_EXECUTABLE ${Python_EXECUTABLE})
endif()
# cxx_test_with_flags(name cxx_flags libs srcs...)
#
# Creates a named C++ test that depends on the given libs and is built
# creates a named C++ test that depends on the given libs and is built
# from the given source files with the given compiler flags.
function(cxx_test_with_flags name cxx_flags libs)
cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN})
@ -262,8 +262,8 @@ endfunction()
# cxx_test(name libs srcs...)
#
# Creates a named test target that depends on the given libs and is
# built from the given source files. Unlike cxx_test_with_flags,
# creates a named test target that depends on the given libs and is
# built from the given source files. Unlike cxx_test_with_flags,
# test/name.cc is already implicitly included in the source file list.
function(cxx_test name libs)
cxx_test_with_flags("${name}" "${cxx_default}" "${libs}"
@ -272,25 +272,37 @@ endfunction()
# py_test(name)
#
# Creates a Python test with the given name whose main module is in
# test/name.py. It does nothing if Python is not installed.
# creates a Python test with the given name whose main module is in
# test/name.py. It does nothing if Python is not installed.
function(py_test name)
if (NOT Python3_Interpreter_FOUND)
return()
endif()
get_cmake_property(is_multi "GENERATOR_IS_MULTI_CONFIG")
set(build_dir "${CMAKE_CURRENT_BINARY_DIR}")
if (is_multi)
set(build_dir "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>")
endif()
add_test(NAME ${name}
COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${build_dir} ${ARGN})
# Make the Python import path consistent between Bazel and CMake.
set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})
if (PYTHONINTERP_FOUND)
if ("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" VERSION_GREATER 3.1)
if (CMAKE_CONFIGURATION_TYPES)
# Multi-configuration build generators as for Visual Studio save
# output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug,
# Release etc.), so we have to provide it here.
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
else (CMAKE_CONFIGURATION_TYPES)
# Single-configuration build generators like Makefile generators
# don't have subdirs below CMAKE_CURRENT_BINARY_DIR.
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
endif (CMAKE_CONFIGURATION_TYPES)
else()
# ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can
# directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
# only at ctest runtime (by calling ctest -c <Configuration>), so
# we have to escape $ to delay variable substitution here.
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
endif()
# Make the Python import path consistent between Bazel and CMake.
set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})
endif(PYTHONINTERP_FOUND)
endfunction()
# install_project(targets...)
@ -299,24 +311,21 @@ endfunction()
function(install_project)
if(INSTALL_GTEST)
install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/"
COMPONENT "${PROJECT_NAME}"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
# Install the project targets.
install(TARGETS ${ARGN}
EXPORT ${targets_export_name}
COMPONENT "${PROJECT_NAME}"
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")
if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
# Install PDBs.
# Install PDBs
foreach(t ${ARGN})
get_target_property(t_pdb_name ${t} COMPILE_PDB_NAME)
get_target_property(t_pdb_name_debug ${t} COMPILE_PDB_NAME_DEBUG)
get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY)
install(FILES
"${t_pdb_output_directory}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$<CONFIG:Debug>:${t_pdb_name_debug}>$<$<NOT:$<CONFIG:Debug>>:${t_pdb_name}>.pdb"
COMPONENT "${PROJECT_NAME}"
DESTINATION ${CMAKE_INSTALL_LIBDIR}
OPTIONAL)
endforeach()
@ -327,7 +336,6 @@ function(install_project)
configure_file("${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in"
"${configured_pc}" @ONLY)
install(FILES "${configured_pc}"
COMPONENT "${PROJECT_NAME}"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
endforeach()
endif()

View File

@ -130,14 +130,7 @@ namespace testing {
// Expected: Foo() is even
// Actual: it's 5
//
// Returned AssertionResult objects may not be ignored.
// Note: Disabled for SWIG as it doesn't parse attributes correctly.
#if !defined(SWIG)
class [[nodiscard]] AssertionResult;
#endif // !SWIG
class GTEST_API_ [[nodiscard]] AssertionResult {
class GTEST_API_ AssertionResult {
public:
// Copy constructor.
// Used in EXPECT_TRUE/FALSE(assertion_result).
@ -188,7 +181,7 @@ class GTEST_API_ [[nodiscard]] AssertionResult {
// assertion's expectation). When nothing has been streamed into the
// object, returns an empty string.
const char* message() const {
return message_ != nullptr ? message_->c_str() : "";
return message_.get() != nullptr ? message_->c_str() : "";
}
// Deprecated; please use message() instead.
const char* failure_message() const { return message(); }
@ -211,7 +204,7 @@ class GTEST_API_ [[nodiscard]] AssertionResult {
private:
// Appends the contents of message to message_.
void AppendMessage(const Message& a_message) {
if (message_ == nullptr) message_ = ::std::make_unique<::std::string>();
if (message_.get() == nullptr) message_.reset(new ::std::string);
message_->append(a_message.GetString().c_str());
}

View File

@ -51,7 +51,7 @@ GTEST_DECLARE_string_(death_test_style);
namespace testing {
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
namespace internal {
@ -192,7 +192,7 @@ GTEST_API_ bool InDeathTestChild();
// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
// Tests that an exit code describes a normal exit with a given exit code.
class GTEST_API_ [[nodiscard]] ExitedWithCode {
class GTEST_API_ ExitedWithCode {
public:
explicit ExitedWithCode(int exit_code);
ExitedWithCode(const ExitedWithCode&) = default;
@ -203,10 +203,10 @@ class GTEST_API_ [[nodiscard]] ExitedWithCode {
const int exit_code_;
};
#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)
#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
// Tests that an exit code describes an exit due to termination by a
// given signal.
class GTEST_API_ [[nodiscard]] KilledBySignal {
class GTEST_API_ KilledBySignal {
public:
explicit KilledBySignal(int signum);
bool operator()(int exit_status) const;
@ -293,8 +293,8 @@ class GTEST_API_ [[nodiscard]] KilledBySignal {
// statement is compiled but not executed, to ensure that
// EXPECT_DEATH_IF_SUPPORTED compiles with a certain
// parameter if and only if EXPECT_DEATH compiles with it.
// regex_or_matcher - A regex that a macro such as EXPECT_DEATH would use
// to test the output of statement. This parameter has to be
// regex - A regex that a macro such as EXPECT_DEATH would use to test
// the output of statement. This parameter has to be
// compiled but not evaluated by this macro, to ensure that
// this macro only accepts expressions that a macro such as
// EXPECT_DEATH would accept.
@ -311,13 +311,13 @@ class GTEST_API_ [[nodiscard]] KilledBySignal {
// statement unconditionally returns or throws. The Message constructor at
// the end allows the syntax of streaming additional messages into the
// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex_or_matcher, terminator) \
#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \
<< "Statement '" #statement "' cannot be verified."; \
} else if (::testing::internal::AlwaysFalse()) { \
(void)::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
::testing::internal::RE::PartialMatch(".*", (regex)); \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
terminator; \
} else \
@ -328,7 +328,7 @@ class GTEST_API_ [[nodiscard]] KilledBySignal {
// death tests are supported; otherwise they just issue a warning. This is
// useful when you are combining death test assertions with normal test
// assertions in one test.
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEATH(statement, regex)
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \

View File

@ -40,7 +40,6 @@
#define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
#include <atomic>
#include <functional>
#include <memory>
#include <ostream>
#include <string>
@ -67,15 +66,15 @@ namespace testing {
// To implement a matcher Foo for type T, define:
// 1. a class FooMatcherMatcher that implements the matcher interface:
// using is_gtest_matcher = void;
// bool MatchAndExplain(const T&, std::ostream*) const;
// bool MatchAndExplain(const T&, std::ostream*);
// (MatchResultListener* can also be used instead of std::ostream*)
// void DescribeTo(std::ostream*) const;
// void DescribeNegationTo(std::ostream*) const;
// void DescribeTo(std::ostream*);
// void DescribeNegationTo(std::ostream*);
//
// 2. a factory function that creates a Matcher<T> object from a
// FooMatcherMatcher.
class [[nodiscard]] MatchResultListener {
class MatchResultListener {
public:
// Creates a listener object with the given underlying ostream. The
// listener does not own the ostream, and does not dereference it
@ -107,13 +106,13 @@ class [[nodiscard]] MatchResultListener {
MatchResultListener& operator=(const MatchResultListener&) = delete;
};
inline MatchResultListener::~MatchResultListener() = default;
inline MatchResultListener::~MatchResultListener() {}
// An instance of a subclass of this knows how to describe itself as a
// matcher.
class GTEST_API_ [[nodiscard]] MatcherDescriberInterface {
class GTEST_API_ MatcherDescriberInterface {
public:
virtual ~MatcherDescriberInterface() = default;
virtual ~MatcherDescriberInterface() {}
// Describes this matcher to an ostream. The function should print
// a verb phrase that describes the property a value matching this
@ -137,7 +136,7 @@ class GTEST_API_ [[nodiscard]] MatcherDescriberInterface {
// The implementation of a matcher.
template <typename T>
class [[nodiscard]] MatcherInterface : public MatcherDescriberInterface {
class MatcherInterface : public MatcherDescriberInterface {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener' if necessary (see the next paragraph), in
@ -179,8 +178,45 @@ class [[nodiscard]] MatcherInterface : public MatcherDescriberInterface {
namespace internal {
struct AnyEq {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a == b;
}
};
struct AnyNe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a != b;
}
};
struct AnyLt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a < b;
}
};
struct AnyGt {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a > b;
}
};
struct AnyLe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a <= b;
}
};
struct AnyGe {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
return a >= b;
}
};
// A match result listener that ignores the explanation.
class [[nodiscard]] DummyMatchResultListener : public MatchResultListener {
class DummyMatchResultListener : public MatchResultListener {
public:
DummyMatchResultListener() : MatchResultListener(nullptr) {}
@ -192,7 +228,7 @@ class [[nodiscard]] DummyMatchResultListener : public MatchResultListener {
// A match result listener that forwards the explanation to a given
// ostream. The difference between this and MatchResultListener is
// that the former is concrete.
class [[nodiscard]] StreamMatchResultListener : public MatchResultListener {
class StreamMatchResultListener : public MatchResultListener {
public:
explicit StreamMatchResultListener(::std::ostream* os)
: MatchResultListener(os) {}
@ -225,7 +261,7 @@ struct SharedPayload : SharedPayloadBase {
// from it. We put functionalities common to all Matcher<T>
// specializations here to avoid code duplication.
template <typename T>
class [[nodiscard]] MatcherBase : private MatcherDescriberInterface {
class MatcherBase : private MatcherDescriberInterface {
public:
// Returns true if and only if the matcher matches x; also explains the
// match result to 'listener'.
@ -296,12 +332,12 @@ class [[nodiscard]] MatcherBase : private MatcherDescriberInterface {
return *this;
}
MatcherBase(MatcherBase&& other) noexcept
MatcherBase(MatcherBase&& other)
: vtable_(other.vtable_), buffer_(other.buffer_) {
other.vtable_ = nullptr;
}
MatcherBase& operator=(MatcherBase&& other) noexcept {
MatcherBase& operator=(MatcherBase&& other) {
if (this == &other) return *this;
Destroy();
vtable_ = other.vtable_;
@ -460,7 +496,7 @@ class [[nodiscard]] MatcherBase : private MatcherDescriberInterface {
// implementation of Matcher<T> is just a std::shared_ptr to const
// MatcherInterface<T>. Don't inherit from Matcher!
template <typename T>
class [[nodiscard]] Matcher : public internal::MatcherBase<T> {
class Matcher : public internal::MatcherBase<T> {
public:
// Constructs a null matcher. Needed for storing Matcher objects in STL
// containers. A default-constructed matcher is not yet initialized. You
@ -491,10 +527,10 @@ class [[nodiscard]] Matcher : public internal::MatcherBase<T> {
// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
// matcher is expected.
template <>
class GTEST_API_ [[nodiscard]]
Matcher<const std::string&> : public internal::MatcherBase<const std::string&> {
class GTEST_API_ Matcher<const std::string&>
: public internal::MatcherBase<const std::string&> {
public:
Matcher() = default;
Matcher() {}
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<const std::string&>(impl) {}
@ -513,10 +549,10 @@ Matcher<const std::string&> : public internal::MatcherBase<const std::string&> {
};
template <>
class GTEST_API_ [[nodiscard]]
Matcher<std::string> : public internal::MatcherBase<std::string> {
class GTEST_API_ Matcher<std::string>
: public internal::MatcherBase<std::string> {
public:
Matcher() = default;
Matcher() {}
explicit Matcher(const MatcherInterface<const std::string&>* impl)
: internal::MatcherBase<std::string>(impl) {}
@ -541,10 +577,10 @@ Matcher<std::string> : public internal::MatcherBase<std::string> {
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
// matcher is expected.
template <>
class GTEST_API_ [[nodiscard]] Matcher<const internal::StringView&>
class GTEST_API_ Matcher<const internal::StringView&>
: public internal::MatcherBase<const internal::StringView&> {
public:
Matcher() = default;
Matcher() {}
explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
: internal::MatcherBase<const internal::StringView&>(impl) {}
@ -567,10 +603,10 @@ class GTEST_API_ [[nodiscard]] Matcher<const internal::StringView&>
};
template <>
class GTEST_API_ [[nodiscard]] Matcher<internal::StringView>
class GTEST_API_ Matcher<internal::StringView>
: public internal::MatcherBase<internal::StringView> {
public:
Matcher() = default;
Matcher() {}
explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
: internal::MatcherBase<internal::StringView>(impl) {}
@ -614,7 +650,7 @@ std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
//
// See the definition of NotNull() for a complete example.
template <class Impl>
class [[nodiscard]] PolymorphicMatcher {
class PolymorphicMatcher {
public:
explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
@ -689,7 +725,7 @@ namespace internal {
// The following template definition assumes that the Rhs parameter is
// a "bare" type (i.e. neither 'const T' nor 'T&').
template <typename D, typename Rhs, typename Op>
class [[nodiscard]] ComparisonBase {
class ComparisonBase {
public:
explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
@ -722,89 +758,54 @@ class [[nodiscard]] ComparisonBase {
};
template <typename Rhs>
class [[nodiscard]] EqMatcher
: public ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>> {
class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
public:
explicit EqMatcher(const Rhs& rhs)
: ComparisonBase<EqMatcher<Rhs>, Rhs, std::equal_to<>>(rhs) {}
: ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) {}
static const char* Desc() { return "is equal to"; }
static const char* NegatedDesc() { return "isn't equal to"; }
};
template <typename Rhs>
class [[nodiscard]] NeMatcher
: public ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>> {
class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
public:
explicit NeMatcher(const Rhs& rhs)
: ComparisonBase<NeMatcher<Rhs>, Rhs, std::not_equal_to<>>(rhs) {}
: ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) {}
static const char* Desc() { return "isn't equal to"; }
static const char* NegatedDesc() { return "is equal to"; }
};
template <typename Rhs>
class [[nodiscard]] LtMatcher
: public ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>> {
class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
public:
explicit LtMatcher(const Rhs& rhs)
: ComparisonBase<LtMatcher<Rhs>, Rhs, std::less<>>(rhs) {}
: ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) {}
static const char* Desc() { return "is <"; }
static const char* NegatedDesc() { return "isn't <"; }
};
template <typename Rhs>
class [[nodiscard]] GtMatcher
: public ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>> {
class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
public:
explicit GtMatcher(const Rhs& rhs)
: ComparisonBase<GtMatcher<Rhs>, Rhs, std::greater<>>(rhs) {}
: ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) {}
static const char* Desc() { return "is >"; }
static const char* NegatedDesc() { return "isn't >"; }
};
template <typename Rhs>
class [[nodiscard]] LeMatcher
: public ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>> {
class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
public:
explicit LeMatcher(const Rhs& rhs)
: ComparisonBase<LeMatcher<Rhs>, Rhs, std::less_equal<>>(rhs) {}
: ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) {}
static const char* Desc() { return "is <="; }
static const char* NegatedDesc() { return "isn't <="; }
};
template <typename Rhs>
class [[nodiscard]] GeMatcher
: public ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>> {
class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
public:
explicit GeMatcher(const Rhs& rhs)
: ComparisonBase<GeMatcher<Rhs>, Rhs, std::greater_equal<>>(rhs) {}
: ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) {}
static const char* Desc() { return "is >="; }
static const char* NegatedDesc() { return "isn't >="; }
};
// Same as `EqMatcher<Rhs>`, except that the `rhs` is stored as `StoredRhs` and
// must be implicitly convertible to `Rhs`.
template <typename Rhs, typename StoredRhs>
class [[nodiscard]] ImplicitCastEqMatcher {
public:
explicit ImplicitCastEqMatcher(const StoredRhs& rhs) : stored_rhs_(rhs) {}
using is_gtest_matcher = void;
template <typename Lhs>
bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
return lhs == rhs();
}
void DescribeTo(std::ostream* os) const {
*os << "is equal to ";
UniversalPrint(rhs(), os);
}
void DescribeNegationTo(std::ostream* os) const {
*os << "isn't equal to ";
UniversalPrint(rhs(), os);
}
private:
Rhs rhs() const { return ImplicitCast_<Rhs>(stored_rhs_); }
StoredRhs stored_rhs_;
};
template <typename T, typename = typename std::enable_if<
std::is_constructible<std::string, T>::value>::type>
using StringLike = T;
@ -812,7 +813,7 @@ using StringLike = T;
// Implements polymorphic matchers MatchesRegex(regex) and
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
// T can be converted to a string.
class [[nodiscard]] MatchesRegexMatcher {
class MatchesRegexMatcher {
public:
MatchesRegexMatcher(const RE* regex, bool full_match)
: regex_(regex), full_match_(full_match) {}
@ -841,7 +842,7 @@ class [[nodiscard]] MatchesRegexMatcher {
template <class MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const {
const std::string s2(s);
const std::string& s2(s);
return full_match_ ? RE::FullMatch(s2, *regex_)
: RE::PartialMatch(s2, *regex_);
}

View File

@ -50,19 +50,10 @@
#include <limits>
#include <memory>
#include <ostream>
#include <sstream>
#include <string>
#include "gtest/internal/gtest-port.h"
#ifdef GTEST_HAS_ABSL
#include <type_traits>
#include "absl/strings/has_absl_stringify.h"
#include "absl/strings/str_cat.h"
#endif // GTEST_HAS_ABSL
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@ -118,17 +109,8 @@ class GTEST_API_ Message {
*ss_ << str;
}
// Streams a non-pointer value to this object. If building a version of
// GoogleTest with ABSL, this overload is only enabled if the value does not
// have an AbslStringify definition.
template <
typename T
#ifdef GTEST_HAS_ABSL
,
typename std::enable_if<!absl::HasAbslStringify<T>::value, // NOLINT
int>::type = 0
#endif // GTEST_HAS_ABSL
>
// Streams a non-pointer value to this object.
template <typename T>
inline Message& operator<<(const T& val) {
// Some libraries overload << for STL containers. These
// overloads are defined in the global namespace instead of ::std.
@ -149,21 +131,6 @@ class GTEST_API_ Message {
return *this;
}
#ifdef GTEST_HAS_ABSL
// Streams a non-pointer value with an AbslStringify definition to this
// object.
template <typename T,
typename std::enable_if<absl::HasAbslStringify<T>::value, // NOLINT
int>::type = 0>
inline Message& operator<<(const T& val) {
// ::operator<< is needed here for a similar reason as with the non-Abseil
// version above
using ::operator<<;
*ss_ << absl::StrCat(val);
return *this;
}
#endif // GTEST_HAS_ABSL
// Streams a pointer value to this object.
//
// This function is an overload of the previous one. When you

View File

@ -174,12 +174,11 @@ TEST_P(DerivedTest, DoesBlah) {
#endif // 0
#include <functional>
#include <iterator>
#include <utility>
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-param-util.h" // IWYU pragma: export
#include "gtest/internal/gtest-param-util.h"
#include "gtest/internal/gtest-port.h"
namespace testing {
@ -408,106 +407,9 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
return internal::CartesianProductHolder<Generator...>(g...);
}
// ConvertGenerator() wraps a parameter generator in order to cast each produced
// value through a known type before supplying it to the test suite
//
// Synopsis:
// ConvertGenerator<T>(gen)
// - returns a generator producing the same elements as generated by gen, but
// each T-typed element is static_cast to a type deduced from the interface
// that accepts this generator, and then returned
//
// It is useful when using the Combine() function to get the generated
// parameters in a custom type instead of std::tuple
//
// Example:
//
// This will instantiate tests in test suite AnimalTest each one with
// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
// tuple("dog", BLACK), and tuple("dog", WHITE):
//
// enum Color { BLACK, GRAY, WHITE };
// struct ParamType {
// using TupleT = std::tuple<const char*, Color>;
// std::string animal;
// Color color;
// ParamType(TupleT t) : animal(std::get<0>(t)), color(std::get<1>(t)) {}
// };
// class AnimalTest
// : public testing::TestWithParam<ParamType> {...};
//
// TEST_P(AnimalTest, AnimalLooksNice) {...}
//
// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,
// ConvertGenerator<ParamType::TupleT>(
// Combine(Values("cat", "dog"),
// Values(BLACK, WHITE))));
//
template <typename RequestedT>
internal::ParamConverterGenerator<RequestedT> ConvertGenerator(
internal::ParamGenerator<RequestedT> gen) {
return internal::ParamConverterGenerator<RequestedT>(std::move(gen));
}
// As above, but takes a callable as a second argument. The callable converts
// the generated parameter to the test fixture's parameter type. This allows you
// to use a parameter type that does not have a converting constructor from the
// generated type.
//
// Example:
//
// This will instantiate tests in test suite AnimalTest each one with
// the parameter values tuple("cat", BLACK), tuple("cat", WHITE),
// tuple("dog", BLACK), and tuple("dog", WHITE):
//
// enum Color { BLACK, GRAY, WHITE };
// struct ParamType {
// std::string animal;
// Color color;
// };
// class AnimalTest
// : public testing::TestWithParam<ParamType> {...};
//
// TEST_P(AnimalTest, AnimalLooksNice) {...}
//
// INSTANTIATE_TEST_SUITE_P(
// AnimalVariations, AnimalTest,
// ConvertGenerator(Combine(Values("cat", "dog"), Values(BLACK, WHITE)),
// [](std::tuple<std::string, Color> t) {
// return ParamType{.animal = std::get<0>(t),
// .color = std::get<1>(t)};
// }));
//
template <typename T, int&... ExplicitArgumentBarrier, typename Gen,
typename Func,
typename StdFunction = decltype(std::function(std::declval<Func>()))>
internal::ParamConverterGenerator<T, StdFunction> ConvertGenerator(Gen&& gen,
Func&& f) {
return internal::ParamConverterGenerator<T, StdFunction>(
std::forward<Gen>(gen), std::forward<Func>(f));
}
// As above, but infers the T from the supplied std::function instead of
// having the caller specify it.
template <int&... ExplicitArgumentBarrier, typename Gen, typename Func,
typename StdFunction = decltype(std::function(std::declval<Func>()))>
auto ConvertGenerator(Gen&& gen, Func&& f) {
constexpr bool is_single_arg_std_function =
internal::IsSingleArgStdFunction<StdFunction>::value;
if constexpr (is_single_arg_std_function) {
return ConvertGenerator<
typename internal::FuncSingleParamType<StdFunction>::type>(
std::forward<Gen>(gen), std::forward<Func>(f));
} else {
static_assert(is_single_arg_std_function,
"The call signature must contain a single argument.");
}
}
#define TEST_P(test_suite_name, test_name) \
class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
: public test_suite_name, \
private ::testing::internal::GTestNonCopyable { \
: public test_suite_name { \
public: \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
void TestBody() override; \
@ -526,7 +428,12 @@ auto ConvertGenerator(Gen&& gen, Func&& f) {
::testing::internal::CodeLocation(__FILE__, __LINE__)); \
return 0; \
} \
[[maybe_unused]] static int gtest_registering_dummy_; \
static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
(const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete; \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \
const GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name) &) = delete; /* NOLINT */ \
}; \
int GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)::gtest_registering_dummy_ = \
@ -550,38 +457,39 @@ auto ConvertGenerator(Gen&& gen, Func&& f) {
#define GTEST_GET_FIRST_(first, ...) first
#define GTEST_GET_SECOND_(first, second, ...) second
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
gtest_##prefix##test_suite_name##_EvalGenerator_() { \
return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
} \
static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
if (::testing::internal::AlwaysFalse()) { \
::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))); \
auto t = std::make_tuple(__VA_ARGS__); \
static_assert(std::tuple_size<decltype(t)>::value <= 2, \
"Too Many Args!"); \
} \
return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))))(info); \
} \
[[maybe_unused]] static int gtest_##prefix##test_suite_name##_dummy_ = \
::testing::UnitTest::GetInstance() \
->parameterized_test_registry() \
.GetTestSuitePatternHolder<test_suite_name>( \
GTEST_STRINGIFY_(test_suite_name), \
::testing::internal::CodeLocation(__FILE__, __LINE__)) \
->AddTestSuiteInstantiation( \
GTEST_STRINGIFY_(prefix), \
&gtest_##prefix##test_suite_name##_EvalGenerator_, \
&gtest_##prefix##test_suite_name##_EvalGenerateName_, __FILE__, \
__LINE__)
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \
static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
gtest_##prefix##test_suite_name##_EvalGenerator_() { \
return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
} \
static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \
const ::testing::TestParamInfo<test_suite_name::ParamType>& info) { \
if (::testing::internal::AlwaysFalse()) { \
::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))); \
auto t = std::make_tuple(__VA_ARGS__); \
static_assert(std::tuple_size<decltype(t)>::value <= 2, \
"Too Many Args!"); \
} \
return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \
__VA_ARGS__, \
::testing::internal::DefaultParamName<test_suite_name::ParamType>, \
DUMMY_PARAM_))))(info); \
} \
static int gtest_##prefix##test_suite_name##_dummy_ \
GTEST_ATTRIBUTE_UNUSED_ = \
::testing::UnitTest::GetInstance() \
->parameterized_test_registry() \
.GetTestSuitePatternHolder<test_suite_name>( \
GTEST_STRINGIFY_(test_suite_name), \
::testing::internal::CodeLocation(__FILE__, __LINE__)) \
->AddTestSuiteInstantiation( \
GTEST_STRINGIFY_(prefix), \
&gtest_##prefix##test_suite_name##_EvalGenerator_, \
&gtest_##prefix##test_suite_name##_EvalGenerateName_, \
__FILE__, __LINE__)
// Allow Marking a Parameterized test class as not needing to be instantiated.
#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \

View File

@ -43,9 +43,6 @@
// 1. foo::PrintTo(const T&, ostream*)
// 2. operator<<(ostream&, const T&) defined in either foo or the
// global namespace.
// * Prefer AbslStringify(..) to operator<<(..), per https://abseil.io/tips/215.
// * Define foo::PrintTo(..) if the type already has AbslStringify(..), but an
// alternative presentation in test results is of interest.
//
// However if T is an STL-style container then it is printed element-wise
// unless foo::PrintTo(const T&, ostream*) is defined. Note that
@ -104,36 +101,19 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#include <any>
#include <functional>
#include <memory>
#include <optional>
#include <ostream> // NOLINT
#include <sstream>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <variant>
#include <vector>
#ifdef GTEST_HAS_ABSL
#include "absl/strings/has_absl_stringify.h"
#include "absl/strings/str_cat.h"
#endif // GTEST_HAS_ABSL
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
#if GTEST_INTERNAL_HAS_STD_SPAN
#include <span> // NOLINT
#endif // GTEST_INTERNAL_HAS_STD_SPAN
#if GTEST_INTERNAL_HAS_COMPARE_LIB
#include <compare> // NOLINT
#endif // GTEST_INTERNAL_HAS_COMPARE_LIB
namespace testing {
// Definitions in the internal* namespaces are subject to change without notice.
@ -143,32 +123,13 @@ namespace internal {
template <typename T>
void UniversalPrint(const T& value, ::std::ostream* os);
template <typename T>
struct IsStdSpan {
static constexpr bool value = false;
};
#if GTEST_INTERNAL_HAS_STD_SPAN
template <typename E>
struct IsStdSpan<std::span<E>> {
static constexpr bool value = true;
};
#endif // GTEST_INTERNAL_HAS_STD_SPAN
// Used to print an STL-style container when the user doesn't define
// a PrintTo() for it.
//
// NOTE: Since std::span does not have const_iterator until C++23, it would
// fail IsContainerTest before C++23. However, IsContainerTest only uses
// the presence of const_iterator to avoid treating iterators as containers
// because of iterator::iterator. Which means std::span satisfies the *intended*
// condition of IsContainerTest.
struct ContainerPrinter {
template <typename T,
typename = typename std::enable_if<
((sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
!IsRecursiveContainer<T>::value) ||
IsStdSpan<T>::value>::type>
(sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
!IsRecursiveContainer<T>::value>::type>
static void PrintValue(const T& container, std::ostream* os) {
const size_t kMaxCount = 32; // The maximum number of elements to print.
*os << '{';
@ -244,13 +205,12 @@ struct StreamPrinter {
// Don't accept member pointers here. We'd print them via implicit
// conversion to bool, which isn't useful.
typename = typename std::enable_if<
!std::is_member_pointer<T>::value>::type>
// Only accept types for which we can find a streaming operator via
// ADL (possibly involving implicit conversions).
// (Use SFINAE via return type, because it seems GCC < 12 doesn't handle name
// lookup properly when we do it in the template parameter list.)
static auto PrintValue(const T& value, ::std::ostream* os)
-> decltype((void)(*os << value)) {
!std::is_member_pointer<T>::value>::type,
// Only accept types for which we can find a streaming operator via
// ADL (possibly involving implicit conversions).
typename = decltype(std::declval<std::ostream&>()
<< std::declval<const T&>())>
static void PrintValue(const T& value, ::std::ostream* os) {
// Call streaming operator found by ADL, possibly with implicit conversions
// of the arguments.
*os << value;
@ -298,17 +258,6 @@ struct ConvertibleToStringViewPrinter {
#endif
};
#ifdef GTEST_HAS_ABSL
struct ConvertibleToAbslStringifyPrinter {
template <typename T,
typename = typename std::enable_if<
absl::HasAbslStringify<T>::value>::type> // NOLINT
static void PrintValue(const T& value, ::std::ostream* os) {
*os << absl::StrCat(value);
}
};
#endif // GTEST_HAS_ABSL
// Prints the given number of bytes in the given object to the given
// ostream.
GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
@ -347,8 +296,8 @@ struct FindFirstPrinter<
// - Print containers (they have begin/end/etc).
// - Print function pointers.
// - Print object pointers.
// - Print protocol buffers.
// - Use the stream operator, if available.
// - Print protocol buffers.
// - Print types convertible to BiggestInt.
// - Print types convertible to StringView, if available.
// - Fallback to printing the raw bytes of the object.
@ -356,13 +305,9 @@ template <typename T>
void PrintWithFallback(const T& value, ::std::ostream* os) {
using Printer = typename FindFirstPrinter<
T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
ProtobufPrinter,
#ifdef GTEST_HAS_ABSL
ConvertibleToAbslStringifyPrinter,
#endif // GTEST_HAS_ABSL
internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter,
RawBytesPrinter, FallbackPrinter>::type;
ProtobufPrinter, ConvertibleToIntegerPrinter,
ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
Printer::PrintValue(value, os);
}
@ -382,7 +327,7 @@ void PrintWithFallback(const T& value, ::std::ostream* os) {
// The default case.
template <typename ToPrint, typename OtherOperand>
class [[nodiscard]] FormatForComparison {
class FormatForComparison {
public:
static ::std::string Format(const ToPrint& value) {
return ::testing::PrintToString(value);
@ -391,7 +336,7 @@ class [[nodiscard]] FormatForComparison {
// Array.
template <typename ToPrint, size_t N, typename OtherOperand>
class [[nodiscard]] FormatForComparison<ToPrint[N], OtherOperand> {
class FormatForComparison<ToPrint[N], OtherOperand> {
public:
static ::std::string Format(const ToPrint* value) {
return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
@ -439,7 +384,7 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
#endif
@ -477,7 +422,7 @@ std::string FormatForComparisonFailureMessage(const T1& value,
// function template), as we need to partially specialize it for
// reference types, which cannot be done with function templates.
template <typename T>
class [[nodiscard]] UniversalPrinter;
class UniversalPrinter;
// Prints the given value using the << operator if it has one;
// otherwise prints the bytes in it. This is what
@ -525,15 +470,11 @@ GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
inline void PrintTo(char16_t c, ::std::ostream* os) {
// TODO(b/418738869): Incorrect for values not representing valid codepoints.
// Also see https://github.com/google/googletest/issues/4762.
PrintTo(static_cast<char32_t>(c), os);
PrintTo(ImplicitCast_<char32_t>(c), os);
}
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
inline void PrintTo(char8_t c, ::std::ostream* os) {
// TODO(b/418738869): Incorrect for values not representing valid codepoints.
// Also see https://github.com/google/googletest/issues/4762.
PrintTo(static_cast<char32_t>(c), os);
PrintTo(ImplicitCast_<char32_t>(c), os);
}
#endif
@ -543,101 +484,6 @@ GTEST_API_ void PrintTo(__uint128_t v, ::std::ostream* os);
GTEST_API_ void PrintTo(__int128_t v, ::std::ostream* os);
#endif // __SIZEOF_INT128__
// The default resolution used to print floating-point values uses only
// 6 digits, which can be confusing if a test compares two values whose
// difference lies in the 7th digit. So we'd like to print out numbers
// in full precision.
// However if the value is something simple like 1.1, full will print a
// long string like 1.100000001 due to floating-point numbers not using
// a base of 10. This routiune returns an appropriate resolution for a
// given floating-point number, that is, 6 if it will be accurate, or a
// max_digits10 value (full precision) if it won't, for values between
// 0.0001 and one million.
// It does this by computing what those digits would be (by multiplying
// by an appropriate power of 10), then dividing by that power again to
// see if gets the original value back.
// A similar algorithm applies for values larger than one million; note
// that for those values, we must divide to get a six-digit number, and
// then multiply to possibly get the original value again.
template <typename FloatType>
int AppropriateResolution(FloatType val) {
int full = std::numeric_limits<FloatType>::max_digits10;
if (val < 0) val = -val;
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
#endif
if (val < 1000000) {
FloatType mulfor6 = 1e10;
// Without these static casts, the template instantiation for float would
// fail to compile when -Wdouble-promotion is enabled, as the arithmetic and
// comparison logic would promote floats to doubles.
if (val >= static_cast<FloatType>(100000.0)) { // 100,000 to 999,999
mulfor6 = 1.0;
} else if (val >= static_cast<FloatType>(10000.0)) {
mulfor6 = 1e1;
} else if (val >= static_cast<FloatType>(1000.0)) {
mulfor6 = 1e2;
} else if (val >= static_cast<FloatType>(100.0)) {
mulfor6 = 1e3;
} else if (val >= static_cast<FloatType>(10.0)) {
mulfor6 = 1e4;
} else if (val >= static_cast<FloatType>(1.0)) {
mulfor6 = 1e5;
} else if (val >= static_cast<FloatType>(0.1)) {
mulfor6 = 1e6;
} else if (val >= static_cast<FloatType>(0.01)) {
mulfor6 = 1e7;
} else if (val >= static_cast<FloatType>(0.001)) {
mulfor6 = 1e8;
} else if (val >= static_cast<FloatType>(0.0001)) {
mulfor6 = 1e9;
}
if (static_cast<FloatType>(static_cast<int32_t>(
val * mulfor6 + (static_cast<FloatType>(0.5)))) /
mulfor6 ==
val)
return 6;
} else if (val < static_cast<FloatType>(1e10)) {
FloatType divfor6 = static_cast<FloatType>(1.0);
if (val >= static_cast<FloatType>(1e9)) { // 1,000,000,000 to 9,999,999,999
divfor6 = 10000;
} else if (val >=
static_cast<FloatType>(1e8)) { // 100,000,000 to 999,999,999
divfor6 = 1000;
} else if (val >=
static_cast<FloatType>(1e7)) { // 10,000,000 to 99,999,999
divfor6 = 100;
} else if (val >= static_cast<FloatType>(1e6)) { // 1,000,000 to 9,999,999
divfor6 = 10;
}
if (static_cast<FloatType>(static_cast<int32_t>(
val / divfor6 + (static_cast<FloatType>(0.5)))) *
divfor6 ==
val)
return 6;
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
return full;
}
inline void PrintTo(float f, ::std::ostream* os) {
auto old_precision = os->precision();
os->precision(AppropriateResolution(f));
*os << f;
os->precision(old_precision);
}
inline void PrintTo(double d, ::std::ostream* os) {
auto old_precision = os->precision();
os->precision(AppropriateResolution(d));
*os << d;
os->precision(old_precision);
}
// Overloads for C strings.
GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
inline void PrintTo(char* s, ::std::ostream* os) {
@ -658,7 +504,7 @@ inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
inline void PrintTo(unsigned char* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const void*>(s), os);
}
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
// Overloads for u8 strings.
GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
inline void PrintTo(char8_t* s, ::std::ostream* os) {
@ -703,63 +549,44 @@ void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
}
}
// Overloads for ::std::string and ::std::string_view
GTEST_API_ void PrintStringTo(::std::string_view s, ::std::ostream* os);
// Overloads for ::std::string.
GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os);
inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
PrintStringTo(s, os);
}
inline void PrintTo(::std::string_view s, ::std::ostream* os) {
PrintStringTo(s, os);
}
// Overloads for ::std::u8string and ::std::u8string_view
#ifdef __cpp_lib_char8_t
GTEST_API_ void PrintU8StringTo(::std::u8string_view s, ::std::ostream* os);
// Overloads for ::std::u8string
#ifdef __cpp_char8_t
GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
PrintU8StringTo(s, os);
}
inline void PrintTo(::std::u8string_view s, ::std::ostream* os) {
PrintU8StringTo(s, os);
}
#endif
// Overloads for ::std::u16string and ::std::u16string_view
GTEST_API_ void PrintU16StringTo(::std::u16string_view s, ::std::ostream* os);
// Overloads for ::std::u16string
GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
PrintU16StringTo(s, os);
}
inline void PrintTo(::std::u16string_view s, ::std::ostream* os) {
PrintU16StringTo(s, os);
}
// Overloads for ::std::u32string and ::std::u32string_view
GTEST_API_ void PrintU32StringTo(::std::u32string_view s, ::std::ostream* os);
// Overloads for ::std::u32string
GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
PrintU32StringTo(s, os);
}
inline void PrintTo(::std::u32string_view s, ::std::ostream* os) {
PrintU32StringTo(s, os);
}
// Overloads for ::std::wstring and ::std::wstring_view
// Overloads for ::std::wstring.
#if GTEST_HAS_STD_WSTRING
GTEST_API_ void PrintWideStringTo(::std::wstring_view s, ::std::ostream* os);
GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os);
inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
PrintWideStringTo(s, os);
}
inline void PrintTo(::std::wstring_view s, ::std::ostream* os) {
PrintWideStringTo(s, os);
}
#endif // GTEST_HAS_STD_WSTRING
#if GTEST_INTERNAL_HAS_STRING_VIEW
// Overload for internal::StringView. Needed for build configurations where
// internal::StringView is an alias for absl::string_view, but absl::string_view
// is a distinct type from std::string_view.
template <int&... ExplicitArgumentBarrier, typename T = internal::StringView,
std::enable_if_t<!std::is_same_v<T, ::std::string_view>, int> = 0>
// Overload for internal::StringView.
inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
PrintStringTo(sp, os);
PrintTo(::std::string(sp), os);
}
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
@ -813,41 +640,6 @@ void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
(PrintSmartPointer<T>)(ptr, os, 0);
}
#if GTEST_INTERNAL_HAS_COMPARE_LIB
template <typename T>
void PrintOrderingHelper(T ordering, std::ostream* os) {
if (ordering == T::less) {
*os << "(less)";
} else if (ordering == T::greater) {
*os << "(greater)";
} else if (ordering == T::equivalent) {
*os << "(equivalent)";
} else {
*os << "(unknown ordering)";
}
}
inline void PrintTo(std::strong_ordering ordering, std::ostream* os) {
if (ordering == std::strong_ordering::equal) {
*os << "(equal)";
} else {
PrintOrderingHelper(ordering, os);
}
}
inline void PrintTo(std::partial_ordering ordering, std::ostream* os) {
if (ordering == std::partial_ordering::unordered) {
*os << "(unordered)";
} else {
PrintOrderingHelper(ordering, os);
}
}
inline void PrintTo(std::weak_ordering ordering, std::ostream* os) {
PrintOrderingHelper(ordering, os);
}
#endif
// Helper function for printing a tuple. T must be instantiated with
// a tuple type.
template <typename T>
@ -889,7 +681,7 @@ void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
// Implements printing a non-reference type T by letting the compiler
// pick the right overload of PrintTo() for T.
template <typename T>
class [[nodiscard]] UniversalPrinter {
class UniversalPrinter {
public:
// MSVC warns about adding const to a function type, so we want to
// disable the warning.
@ -915,13 +707,16 @@ class [[nodiscard]] UniversalPrinter {
// Remove any const-qualifiers before passing a type to UniversalPrinter.
template <typename T>
class [[nodiscard]] UniversalPrinter<const T> : public UniversalPrinter<T> {};
class UniversalPrinter<const T> : public UniversalPrinter<T> {};
#if GTEST_INTERNAL_HAS_ANY
// Printer for std::any / absl::any
// Printer for std::any
template <>
class [[nodiscard]] UniversalPrinter<std::any> {
class UniversalPrinter<Any> {
public:
static void Print(const std::any& value, ::std::ostream* os) {
static void Print(const Any& value, ::std::ostream* os) {
if (value.has_value()) {
*os << "value of type " << GetTypeName(value);
} else {
@ -930,7 +725,7 @@ class [[nodiscard]] UniversalPrinter<std::any> {
}
private:
static std::string GetTypeName(const std::any& value) {
static std::string GetTypeName(const Any& value) {
#if GTEST_HAS_RTTI
return internal::GetTypeName(value.type());
#else
@ -940,11 +735,16 @@ class [[nodiscard]] UniversalPrinter<std::any> {
}
};
// Printer for std::optional
#endif // GTEST_INTERNAL_HAS_ANY
#if GTEST_INTERNAL_HAS_OPTIONAL
// Printer for std::optional / absl::optional
template <typename T>
class [[nodiscard]] UniversalPrinter<std::optional<T>> {
class UniversalPrinter<Optional<T>> {
public:
static void Print(const std::optional<T>& value, ::std::ostream* os) {
static void Print(const Optional<T>& value, ::std::ostream* os) {
*os << '(';
if (!value) {
*os << "nullopt";
@ -956,18 +756,29 @@ class [[nodiscard]] UniversalPrinter<std::optional<T>> {
};
template <>
class [[nodiscard]] UniversalPrinter<std::nullopt_t> {
class UniversalPrinter<decltype(Nullopt())> {
public:
static void Print(std::nullopt_t, ::std::ostream* os) { *os << "(nullopt)"; }
static void Print(decltype(Nullopt()), ::std::ostream* os) {
*os << "(nullopt)";
}
};
// Printer for std::variant
#endif // GTEST_INTERNAL_HAS_OPTIONAL
#if GTEST_INTERNAL_HAS_VARIANT
// Printer for std::variant / absl::variant
template <typename... T>
class [[nodiscard]] UniversalPrinter<std::variant<T...>> {
class UniversalPrinter<Variant<T...>> {
public:
static void Print(const std::variant<T...>& value, ::std::ostream* os) {
static void Print(const Variant<T...>& value, ::std::ostream* os) {
*os << '(';
#if GTEST_HAS_ABSL
absl::visit(Visitor{os, value.index()}, value);
#else
std::visit(Visitor{os, value.index()}, value);
#endif // GTEST_HAS_ABSL
*os << ')';
}
@ -984,6 +795,8 @@ class [[nodiscard]] UniversalPrinter<std::variant<T...>> {
};
};
#endif // GTEST_INTERNAL_HAS_VARIANT
// UniversalPrintArray(begin, len, os) prints an array of 'len'
// elements, starting at address 'begin'.
template <typename T>
@ -1011,7 +824,7 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,
::std::ostream* os);
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
// This overload prints a (const) char8_t array compactly.
GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
::std::ostream* os);
@ -1031,7 +844,7 @@ GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,
// Implements printing an array type T[N].
template <typename T, size_t N>
class [[nodiscard]] UniversalPrinter<T[N]> {
class UniversalPrinter<T[N]> {
public:
// Prints the given array, omitting some elements when there are too
// many.
@ -1042,7 +855,7 @@ class [[nodiscard]] UniversalPrinter<T[N]> {
// Implements printing a reference type T&.
template <typename T>
class [[nodiscard]] UniversalPrinter<T&> {
class UniversalPrinter<T&> {
public:
// MSVC warns about adding const to a function type, so we want to
// disable the warning.
@ -1065,35 +878,28 @@ class [[nodiscard]] UniversalPrinter<T&> {
// NUL-terminated string (but not the pointer) is printed.
template <typename T>
class [[nodiscard]] UniversalTersePrinter {
class UniversalTersePrinter {
public:
static void Print(const T& value, ::std::ostream* os) {
UniversalPrint(value, os);
}
};
template <typename T>
class [[nodiscard]] UniversalTersePrinter<T&> {
class UniversalTersePrinter<T&> {
public:
static void Print(const T& value, ::std::ostream* os) {
UniversalPrint(value, os);
}
};
template <typename T>
class [[nodiscard]] UniversalTersePrinter<std::reference_wrapper<T>> {
public:
static void Print(std::reference_wrapper<T> value, ::std::ostream* os) {
UniversalTersePrinter<T>::Print(value.get(), os);
}
};
template <typename T, size_t N>
class [[nodiscard]] UniversalTersePrinter<T[N]> {
class UniversalTersePrinter<T[N]> {
public:
static void Print(const T (&value)[N], ::std::ostream* os) {
UniversalPrinter<T[N]>::Print(value, os);
}
};
template <>
class [[nodiscard]] UniversalTersePrinter<const char*> {
class UniversalTersePrinter<const char*> {
public:
static void Print(const char* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1104,12 +910,12 @@ class [[nodiscard]] UniversalTersePrinter<const char*> {
}
};
template <>
class [[nodiscard]]
UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {};
class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
};
#ifdef __cpp_lib_char8_t
#ifdef __cpp_char8_t
template <>
class [[nodiscard]] UniversalTersePrinter<const char8_t*> {
class UniversalTersePrinter<const char8_t*> {
public:
static void Print(const char8_t* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1120,12 +926,12 @@ class [[nodiscard]] UniversalTersePrinter<const char8_t*> {
}
};
template <>
class [[nodiscard]] UniversalTersePrinter<char8_t*>
class UniversalTersePrinter<char8_t*>
: public UniversalTersePrinter<const char8_t*> {};
#endif
template <>
class [[nodiscard]] UniversalTersePrinter<const char16_t*> {
class UniversalTersePrinter<const char16_t*> {
public:
static void Print(const char16_t* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1136,11 +942,11 @@ class [[nodiscard]] UniversalTersePrinter<const char16_t*> {
}
};
template <>
class [[nodiscard]] UniversalTersePrinter<char16_t*>
class UniversalTersePrinter<char16_t*>
: public UniversalTersePrinter<const char16_t*> {};
template <>
class [[nodiscard]] UniversalTersePrinter<const char32_t*> {
class UniversalTersePrinter<const char32_t*> {
public:
static void Print(const char32_t* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1151,12 +957,12 @@ class [[nodiscard]] UniversalTersePrinter<const char32_t*> {
}
};
template <>
class [[nodiscard]] UniversalTersePrinter<char32_t*>
class UniversalTersePrinter<char32_t*>
: public UniversalTersePrinter<const char32_t*> {};
#if GTEST_HAS_STD_WSTRING
template <>
class [[nodiscard]] UniversalTersePrinter<const wchar_t*> {
class UniversalTersePrinter<const wchar_t*> {
public:
static void Print(const wchar_t* str, ::std::ostream* os) {
if (str == nullptr) {
@ -1169,7 +975,7 @@ class [[nodiscard]] UniversalTersePrinter<const wchar_t*> {
#endif
template <>
class [[nodiscard]] UniversalTersePrinter<wchar_t*> {
class UniversalTersePrinter<wchar_t*> {
public:
static void Print(wchar_t* str, ::std::ostream* os) {
UniversalTersePrinter<const wchar_t*>::Print(str, os);

View File

@ -33,8 +33,6 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
#define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
#include <string>
#include "gtest/gtest.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
@ -51,7 +49,7 @@ namespace testing {
// generated in the same thread that created this object or it can intercept
// all generated failures. The scope of this mock object can be controlled with
// the second argument to the two arguments constructor.
class GTEST_API_ [[nodiscard]] ScopedFakeTestPartResultReporter
class GTEST_API_ ScopedFakeTestPartResultReporter
: public TestPartResultReporterInterface {
public:
// The two possible mocking modes of this object.
@ -100,7 +98,7 @@ namespace internal {
// TestPartResultArray contains exactly one failure that has the given
// type and contains the given substring. If that's not the case, a
// non-fatal failure will be generated.
class GTEST_API_ [[nodiscard]] SingleFailureChecker {
class GTEST_API_ SingleFailureChecker {
public:
// The constructor remembers the arguments.
SingleFailureChecker(const TestPartResultArray* results,

View File

@ -35,8 +35,6 @@
#define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
#include <iosfwd>
#include <ostream>
#include <string>
#include <vector>
#include "gtest/internal/gtest-internal.h"
@ -51,7 +49,7 @@ namespace testing {
// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).
//
// Don't inherit from TestPartResult as its destructor is not virtual.
class GTEST_API_ [[nodiscard]] TestPartResult {
class GTEST_API_ TestPartResult {
public:
// The possible outcomes of a test part (i.e. an assertion or an
// explicit SUCCEED(), FAIL(), or ADD_FAILURE()).
@ -131,9 +129,9 @@ std::ostream& operator<<(std::ostream& os, const TestPartResult& result);
//
// Don't inherit from TestPartResultArray as its destructor is not
// virtual.
class GTEST_API_ [[nodiscard]] TestPartResultArray {
class GTEST_API_ TestPartResultArray {
public:
TestPartResultArray() = default;
TestPartResultArray() {}
// Appends the given TestPartResult to the array.
void Append(const TestPartResult& result);
@ -152,9 +150,9 @@ class GTEST_API_ [[nodiscard]] TestPartResultArray {
};
// This interface knows how to report a test part result.
class GTEST_API_ [[nodiscard]] TestPartResultReporterInterface {
class GTEST_API_ TestPartResultReporterInterface {
public:
virtual ~TestPartResultReporterInterface() = default;
virtual ~TestPartResultReporterInterface() {}
virtual void ReportTestPartResult(const TestPartResult& result) = 0;
};
@ -167,7 +165,7 @@ namespace internal {
// reported, it only delegates the reporting to the former result reporter.
// The original result reporter is restored in the destructor.
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
class GTEST_API_ [[nodiscard]] HasNewFatalFailureHelper
class GTEST_API_ HasNewFatalFailureHelper
: public TestPartResultReporterInterface {
public:
HasNewFatalFailureHelper();

View File

@ -45,18 +45,18 @@
// First, define a fixture class template. It should be parameterized
// by a type. Remember to derive it from testing::Test.
template <typename T>
class [[nodiscard]] FooTest : public testing::Test {
class FooTest : public testing::Test {
public:
...
using List = ::std::list<T>;
typedef std::list<T> List;
static T shared_;
T value_;
};
// Next, associate a list of types with the test suite, which will be
// repeated for each type in the list. The using-declaration is necessary for
// repeated for each type in the list. The typedef is necessary for
// the macro to parse correctly.
using MyTypes = ::testing::Types<char, int, unsigned int>;
typedef testing::Types<char, int, unsigned int> MyTypes;
TYPED_TEST_SUITE(FooTest, MyTypes);
// If the type list contains only one type, you can write that type
@ -123,7 +123,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... }
// First, define a fixture class template. It should be parameterized
// by a type. Remember to derive it from testing::Test.
template <typename T>
class [[nodiscard]] FooTest : public testing::Test {
class FooTest : public testing::Test {
...
};
@ -157,7 +157,7 @@ REGISTER_TYPED_TEST_SUITE_P(FooTest,
// argument to the INSTANTIATE_* macro is a prefix that will be added
// to the actual test suite name. Remember to pick unique prefixes for
// different instances.
using MyTypes = ::testing::Types<char, int, unsigned int>;
typedef testing::Types<char, int, unsigned int> MyTypes;
INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
// If the type list contains only one type, you can write that type
@ -205,8 +205,8 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
typedef gtest_TypeParam_ TypeParam; \
void TestBody() override; \
}; \
[[maybe_unused]] static bool gtest_##CaseName##_##TestName##_registered_ = \
::testing::internal::TypeParameterizedTest< \
static bool gtest_##CaseName##_##TestName##_registered_ \
GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
CaseName, \
::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
TestName)>, \
@ -267,31 +267,31 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
TYPED_TEST_SUITE_P
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#define TYPED_TEST_P(SuiteName, TestName) \
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
template <typename gtest_TypeParam_> \
class TestName : public SuiteName<gtest_TypeParam_> { \
private: \
typedef SuiteName<gtest_TypeParam_> TestFixture; \
typedef gtest_TypeParam_ TypeParam; \
void TestBody() override; \
}; \
[[maybe_unused]] static bool gtest_##TestName##_defined_ = \
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
__FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
GTEST_STRINGIFY_(TestName)); \
} \
template <typename gtest_TypeParam_> \
void GTEST_SUITE_NAMESPACE_( \
#define TYPED_TEST_P(SuiteName, TestName) \
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
template <typename gtest_TypeParam_> \
class TestName : public SuiteName<gtest_TypeParam_> { \
private: \
typedef SuiteName<gtest_TypeParam_> TestFixture; \
typedef gtest_TypeParam_ TypeParam; \
void TestBody() override; \
}; \
static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
__FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
GTEST_STRINGIFY_(TestName)); \
} \
template <typename gtest_TypeParam_> \
void GTEST_SUITE_NAMESPACE_( \
SuiteName)::TestName<gtest_TypeParam_>::TestBody()
// Note: this won't work correctly if the trailing arguments are macros.
#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
} \
[[maybe_unused]] static const char* const GTEST_REGISTERED_TEST_NAMES_( \
SuiteName) = \
static const char* const GTEST_REGISTERED_TEST_NAMES_( \
SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
@ -306,7 +306,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
"test-suit-prefix must not be empty"); \
[[maybe_unused]] static bool gtest_##Prefix##_##SuiteName = \
static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
::testing::internal::TypeParameterizedTestSuite< \
SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
::testing::internal::GenerateTypeList<Types>::type>:: \

View File

@ -50,26 +50,22 @@
#define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <vector>
#include "gtest/gtest-assertion-result.h" // IWYU pragma: export
#include "gtest/gtest-death-test.h" // IWYU pragma: export
#include "gtest/gtest-matchers.h" // IWYU pragma: export
#include "gtest/gtest-message.h" // IWYU pragma: export
#include "gtest/gtest-param-test.h" // IWYU pragma: export
#include "gtest/gtest-printers.h" // IWYU pragma: export
#include "gtest/gtest-test-part.h" // IWYU pragma: export
#include "gtest/gtest-typed-test.h" // IWYU pragma: export
#include "gtest/gtest_pred_impl.h" // IWYU pragma: export
#include "gtest/gtest_prod.h" // IWYU pragma: export
#include "gtest/gtest-assertion-result.h"
#include "gtest/gtest-death-test.h"
#include "gtest/gtest-matchers.h"
#include "gtest/gtest-message.h"
#include "gtest/gtest-param-test.h"
#include "gtest/gtest-printers.h"
#include "gtest/gtest-test-part.h"
#include "gtest/gtest-typed-test.h"
#include "gtest/gtest_pred_impl.h"
#include "gtest/gtest_prod.h"
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h"
@ -165,7 +161,11 @@ namespace testing {
// Silence C4100 (unreferenced formal parameter) and 4805
// unsafe mix of type 'const int' and type 'const bool'
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4805 4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4805)
#pragma warning(disable : 4100)
#endif
// The upper limit for valid stack trace depths.
const int kMaxStackTraceDepth = 100;
@ -190,31 +190,20 @@ void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message);
std::set<std::string>* GetIgnoredParameterizedTestSuites();
// A base class that prevents subclasses from being copyable.
// We do this instead of using '= delete' so as to avoid triggering warnings
// inside user code regarding any of our declarations.
class [[nodiscard]] GTestNonCopyable {
public:
GTestNonCopyable() = default;
GTestNonCopyable(const GTestNonCopyable&) = delete;
GTestNonCopyable& operator=(const GTestNonCopyable&) = delete;
~GTestNonCopyable() = default;
};
} // namespace internal
// The friend relationship of some of these classes is cyclic.
// If we don't forward declare them the compiler might confuse the classes
// in friendship clauses with same named classes on the scope.
class [[nodiscard]] Test;
class [[nodiscard]] TestSuite;
class Test;
class TestSuite;
// Old API is still available but deprecated
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
using TestCase = TestSuite;
#endif
class [[nodiscard]] TestInfo;
class [[nodiscard]] UnitTest;
class TestInfo;
class UnitTest;
// The abstract class that all tests inherit from.
//
@ -239,7 +228,7 @@ class [[nodiscard]] UnitTest;
// TEST_F(FooTest, Baz) { ... }
//
// Test is not copyable.
class GTEST_API_ [[nodiscard]] Test {
class GTEST_API_ Test {
public:
friend class TestInfo;
@ -296,13 +285,7 @@ class GTEST_API_ [[nodiscard]] Test {
// SetUp/TearDown method of Environment objects registered with Google
// Test) will be output as attributes of the <testsuites> element.
static void RecordProperty(const std::string& key, const std::string& value);
// We do not define a custom serialization except for values that can be
// converted to int64_t, but other values could be logged in this way.
template <typename T, std::enable_if_t<std::is_convertible<T, int64_t>::value,
bool> = true>
static void RecordProperty(const std::string& key, const T& value) {
RecordProperty(key, (Message() << value).GetString());
}
static void RecordProperty(const std::string& key, int value);
protected:
// Creates a Test object.
@ -366,7 +349,7 @@ typedef internal::TimeInMillis TimeInMillis;
// output as a key/value string pair.
//
// Don't inherit from TestProperty as its destructor is not virtual.
class [[nodiscard]] TestProperty {
class TestProperty {
public:
// C'tor. TestProperty does NOT have a default constructor.
// Always use this constructor (with parameters) to create a
@ -396,7 +379,7 @@ class [[nodiscard]] TestProperty {
// the Test.
//
// TestResult is not copyable.
class GTEST_API_ [[nodiscard]] TestResult {
class GTEST_API_ TestResult {
public:
// Creates an empty TestResult.
TestResult();
@ -530,7 +513,7 @@ class GTEST_API_ [[nodiscard]] TestResult {
// The constructor of TestInfo registers itself with the UnitTest
// singleton such that the RUN_ALL_TESTS() macro knows which tests to
// run.
class GTEST_API_ [[nodiscard]] TestInfo {
class GTEST_API_ TestInfo {
public:
// Destructs a TestInfo object. This function is not virtual, so
// don't inherit from TestInfo.
@ -550,14 +533,14 @@ class GTEST_API_ [[nodiscard]] TestInfo {
// Returns the name of the parameter type, or NULL if this is not a typed
// or a type-parameterized test.
const char* type_param() const {
if (type_param_ != nullptr) return type_param_->c_str();
if (type_param_.get() != nullptr) return type_param_->c_str();
return nullptr;
}
// Returns the text representation of the value parameter, or NULL if this
// is not a value-parameterized test.
const char* value_param() const {
if (value_param_ != nullptr) return value_param_->c_str();
if (value_param_.get() != nullptr) return value_param_->c_str();
return nullptr;
}
@ -599,7 +582,7 @@ class GTEST_API_ [[nodiscard]] TestInfo {
const TestResult* result() const { return &result_; }
private:
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
friend class internal::DefaultDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST
friend class Test;
@ -607,7 +590,7 @@ class GTEST_API_ [[nodiscard]] TestInfo {
friend class internal::UnitTestImpl;
friend class internal::StreamingListenerTest;
friend TestInfo* internal::MakeAndRegisterTestInfo(
std::string test_suite_name, const char* name, const char* type_param,
const char* test_suite_name, const char* name, const char* type_param,
const char* value_param, internal::CodeLocation code_location,
internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc,
@ -615,7 +598,7 @@ class GTEST_API_ [[nodiscard]] TestInfo {
// Constructs a TestInfo object. The newly constructed instance assumes
// ownership of the factory object.
TestInfo(std::string test_suite_name, std::string name,
TestInfo(const std::string& test_suite_name, const std::string& name,
const char* a_type_param, // NULL if not a type-parameterized test
const char* a_value_param, // NULL if not a value-parameterized test
internal::CodeLocation a_code_location,
@ -669,7 +652,7 @@ class GTEST_API_ [[nodiscard]] TestInfo {
// A test suite, which consists of a vector of TestInfos.
//
// TestSuite is not copyable.
class GTEST_API_ [[nodiscard]] TestSuite {
class GTEST_API_ TestSuite {
public:
// Creates a TestSuite with the given name.
//
@ -683,7 +666,7 @@ class GTEST_API_ [[nodiscard]] TestSuite {
// this is not a type-parameterized test.
// set_up_tc: pointer to the function that sets up the test suite
// tear_down_tc: pointer to the function that tears down the test suite
TestSuite(const std::string& name, const char* a_type_param,
TestSuite(const char* name, const char* a_type_param,
internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc);
@ -696,7 +679,7 @@ class GTEST_API_ [[nodiscard]] TestSuite {
// Returns the name of the parameter type, or NULL if this is not a
// type-parameterized test suite.
const char* type_param() const {
if (type_param_ != nullptr) return type_param_->c_str();
if (type_param_.get() != nullptr) return type_param_->c_str();
return nullptr;
}
@ -890,10 +873,10 @@ class GTEST_API_ [[nodiscard]] TestSuite {
// available.
// 2. You cannot use ASSERT_* directly in a constructor or
// destructor.
class [[nodiscard]] Environment {
class Environment {
public:
// The d'tor is virtual as we need to subclass Environment.
virtual ~Environment() = default;
virtual ~Environment() {}
// Override this to define how to set up the environment.
virtual void SetUp() {}
@ -911,7 +894,7 @@ class [[nodiscard]] Environment {
#if GTEST_HAS_EXCEPTIONS
// Exception which can be thrown from TestEventListener::OnTestPartResult.
class GTEST_API_ [[nodiscard]] AssertionException
class GTEST_API_ AssertionException
: public internal::GoogleTestFailureException {
public:
explicit AssertionException(const TestPartResult& result)
@ -922,9 +905,9 @@ class GTEST_API_ [[nodiscard]] AssertionException
// The interface for tracing execution of tests. The methods are organized in
// the order the corresponding events are fired.
class [[nodiscard]] TestEventListener {
class TestEventListener {
public:
virtual ~TestEventListener() = default;
virtual ~TestEventListener() {}
// Fired before any test activity starts.
virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
@ -989,7 +972,7 @@ class [[nodiscard]] TestEventListener {
// the methods they override will not be caught during the build. For
// comments about each method please see the definition of TestEventListener
// above.
class [[nodiscard]] EmptyTestEventListener : public TestEventListener {
class EmptyTestEventListener : public TestEventListener {
public:
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
void OnTestIterationStart(const UnitTest& /*unit_test*/,
@ -1019,7 +1002,7 @@ class [[nodiscard]] EmptyTestEventListener : public TestEventListener {
};
// TestEventListeners lets users add listeners to track events in Google Test.
class GTEST_API_ [[nodiscard]] TestEventListeners {
class GTEST_API_ TestEventListeners {
public:
TestEventListeners();
~TestEventListeners();
@ -1054,10 +1037,6 @@ class GTEST_API_ [[nodiscard]] TestEventListeners {
return default_xml_generator_;
}
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
void SuppressEventForwarding(bool);
private:
friend class TestSuite;
friend class TestInfo;
@ -1087,6 +1066,7 @@ class GTEST_API_ [[nodiscard]] TestEventListeners {
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
bool EventForwardingEnabled() const;
void SuppressEventForwarding();
// The actual list of listeners.
internal::TestEventRepeater* repeater_;
@ -1110,7 +1090,7 @@ class GTEST_API_ [[nodiscard]] TestEventListeners {
//
// This class is thread-safe as long as the methods are called
// according to their specification.
class GTEST_API_ [[nodiscard]] UnitTest {
class GTEST_API_ UnitTest {
public:
// Gets the singleton UnitTest object. The first time this method
// is called, a UnitTest object is constructed and returned.
@ -1123,7 +1103,7 @@ class GTEST_API_ [[nodiscard]] UnitTest {
// This method can only be called from the main thread.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
[[nodiscard]] int Run();
int Run() GTEST_MUST_USE_RESULT_;
// Returns the working directory when the first TEST() or TEST_F()
// was executed. The UnitTest object owns the string.
@ -1262,20 +1242,6 @@ class GTEST_API_ [[nodiscard]] UnitTest {
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
TestSuite* GetMutableTestSuite(int i);
// Invokes OsStackTrackGetterInterface::UponLeavingGTest. UponLeavingGTest()
// should be called immediately before Google Test calls user code. It saves
// some information about the current stack that CurrentStackTrace() will use
// to find and hide Google Test stack frames.
void UponLeavingGTest();
// Sets the TestSuite object for the test that's currently running.
void set_current_test_suite(TestSuite* a_current_test_suite)
GTEST_LOCK_EXCLUDED_(mutex_);
// Sets the TestInfo object for the test that's currently running.
void set_current_test_info(TestInfo* a_current_test_info)
GTEST_LOCK_EXCLUDED_(mutex_);
// Accessors for the implementation object.
internal::UnitTestImpl* impl() { return impl_; }
const internal::UnitTestImpl* impl() const { return impl_; }
@ -1284,8 +1250,6 @@ class GTEST_API_ [[nodiscard]] UnitTest {
// members of UnitTest.
friend class ScopedTrace;
friend class Test;
friend class TestInfo;
friend class TestSuite;
friend class internal::AssertHelper;
friend class internal::StreamingListenerTest;
friend class internal::UnitTestRecordPropertyTestHelper;
@ -1398,7 +1362,7 @@ AssertionResult CmpHelperEQ(const char* lhs_expression,
return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
}
class [[nodiscard]] EqHelper {
class EqHelper {
public:
// This templatized version is for the general case.
template <
@ -1589,12 +1553,12 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
}
::std::stringstream lhs_ss;
lhs_ss.precision(std::numeric_limits<RawType>::digits10 + 2);
lhs_ss << lhs_value;
lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< lhs_value;
::std::stringstream rhs_ss;
rhs_ss.precision(std::numeric_limits<RawType>::digits10 + 2);
rhs_ss << rhs_value;
rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< rhs_value;
return EqFailure(lhs_expression, rhs_expression,
StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss),
@ -1610,11 +1574,9 @@ GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
double val1, double val2,
double abs_error);
using GoogleTest_NotSupported_OnFunctionReturningNonVoid = void;
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// A class that enables one to stream messages to assertion macros
class GTEST_API_ [[nodiscard]] AssertHelper {
class GTEST_API_ AssertHelper {
public:
// Constructor.
AssertHelper(TestPartResult::Type type, const char* file, int line,
@ -1623,8 +1585,7 @@ class GTEST_API_ [[nodiscard]] AssertHelper {
// Message assignment is a semantic trick to enable assertion
// streaming; see the GTEST_MESSAGE_ macro below.
GoogleTest_NotSupported_OnFunctionReturningNonVoid operator=(
const Message& message) const;
void operator=(const Message& message) const;
private:
// We put our data in a struct so that the size of the AssertHelper class can
@ -1664,7 +1625,7 @@ class GTEST_API_ [[nodiscard]] AssertHelper {
// the GetParam() method.
//
// Use it with one of the parameter generator defining functions, like Range(),
// Values(), ValuesIn(), Bool(), Combine(), and ConvertGenerator<T>().
// Values(), ValuesIn(), Bool(), and Combine().
//
// class FooTest : public ::testing::TestWithParam<int> {
// protected:
@ -1689,14 +1650,14 @@ class GTEST_API_ [[nodiscard]] AssertHelper {
// INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
template <typename T>
class [[nodiscard]] WithParamInterface {
class WithParamInterface {
public:
typedef T ParamType;
virtual ~WithParamInterface() = default;
virtual ~WithParamInterface() {}
// The current parameter value. Is also available in the test fixture's
// constructor.
[[nodiscard]] static const ParamType& GetParam() {
static const ParamType& GetParam() {
GTEST_CHECK_(parameter_ != nullptr)
<< "GetParam() can only be called inside a value-parameterized test "
<< "-- did you intend to write TEST_P instead of TEST_F?";
@ -1723,8 +1684,7 @@ const T* WithParamInterface<T>::parameter_ = nullptr;
// WithParamInterface, and can just inherit from ::testing::TestWithParam.
template <typename T>
class [[nodiscard]] TestWithParam : public Test,
public WithParamInterface<T> {};
class TestWithParam : public Test, public WithParamInterface<T> {};
// Macros for indicating success/failure in test code.
@ -1763,15 +1723,14 @@ class [[nodiscard]] TestWithParam : public Test,
#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
// Like GTEST_FAIL(), but at the given source file location.
#define GTEST_FAIL_AT(file, line) \
return GTEST_MESSAGE_AT_(file, line, "Failed", \
::testing::TestPartResult::kFatalFailure)
#define GTEST_FAIL_AT(file, line) \
GTEST_MESSAGE_AT_(file, line, "Failed", \
::testing::TestPartResult::kFatalFailure)
// Define this macro to 1 to omit the definition of FAIL(), which is a
// generic name and clashes with some other libraries.
#if !(defined(GTEST_DONT_DEFINE_FAIL) && GTEST_DONT_DEFINE_FAIL)
#if !GTEST_DONT_DEFINE_FAIL
#define FAIL() GTEST_FAIL()
#define FAIL_AT(file, line) GTEST_FAIL_AT(file, line)
#endif
// Generates a success with a generic message.
@ -1779,7 +1738,7 @@ class [[nodiscard]] TestWithParam : public Test,
// Define this macro to 1 to omit the definition of SUCCEED(), which
// is a generic name and clashes with some other libraries.
#if !(defined(GTEST_DONT_DEFINE_SUCCEED) && GTEST_DONT_DEFINE_SUCCEED)
#if !GTEST_DONT_DEFINE_SUCCEED
#define SUCCEED() GTEST_SUCCEED()
#endif
@ -1823,19 +1782,19 @@ class [[nodiscard]] TestWithParam : public Test,
// Define these macros to 1 to omit the definition of the corresponding
// EXPECT or ASSERT, which clashes with some users' own code.
#if !(defined(GTEST_DONT_DEFINE_EXPECT_TRUE) && GTEST_DONT_DEFINE_EXPECT_TRUE)
#if !GTEST_DONT_DEFINE_EXPECT_TRUE
#define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
#endif
#if !(defined(GTEST_DONT_DEFINE_EXPECT_FALSE) && GTEST_DONT_DEFINE_EXPECT_FALSE)
#if !GTEST_DONT_DEFINE_EXPECT_FALSE
#define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_TRUE) && GTEST_DONT_DEFINE_ASSERT_TRUE)
#if !GTEST_DONT_DEFINE_ASSERT_TRUE
#define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_FALSE) && GTEST_DONT_DEFINE_ASSERT_FALSE)
#if !GTEST_DONT_DEFINE_ASSERT_FALSE
#define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
#endif
@ -1914,27 +1873,27 @@ class [[nodiscard]] TestWithParam : public Test,
// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
// ASSERT_XY(), which clashes with some users' own code.
#if !(defined(GTEST_DONT_DEFINE_ASSERT_EQ) && GTEST_DONT_DEFINE_ASSERT_EQ)
#if !GTEST_DONT_DEFINE_ASSERT_EQ
#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_NE) && GTEST_DONT_DEFINE_ASSERT_NE)
#if !GTEST_DONT_DEFINE_ASSERT_NE
#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_LE) && GTEST_DONT_DEFINE_ASSERT_LE)
#if !GTEST_DONT_DEFINE_ASSERT_LE
#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_LT) && GTEST_DONT_DEFINE_ASSERT_LT)
#if !GTEST_DONT_DEFINE_ASSERT_LT
#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_GE) && GTEST_DONT_DEFINE_ASSERT_GE)
#if !GTEST_DONT_DEFINE_ASSERT_GE
#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
#endif
#if !(defined(GTEST_DONT_DEFINE_ASSERT_GT) && GTEST_DONT_DEFINE_ASSERT_GT)
#if !GTEST_DONT_DEFINE_ASSERT_GT
#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
#endif
@ -2022,7 +1981,7 @@ GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
double val1, double val2);
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// Macros that test for HRESULT failure and success, these are only useful
// on Windows, and rely on Windows SDK macros and APIs to compile.
@ -2072,7 +2031,7 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
// Example:
// testing::ScopedTrace trace("file.cc", 123, "message");
//
class GTEST_API_ [[nodiscard]] ScopedTrace {
class GTEST_API_ ScopedTrace {
public:
// The c'tor pushes the given source file location and message onto
// a trace stack maintained by Google Test.
@ -2104,7 +2063,9 @@ class GTEST_API_ [[nodiscard]] ScopedTrace {
ScopedTrace(const ScopedTrace&) = delete;
ScopedTrace& operator=(const ScopedTrace&) = delete;
};
} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
// c'tor and d'tor. Therefore it doesn't
// need to be used otherwise.
// Causes a trace (including the source file path, the current line
// number, and the given message) to be included in every test failure
@ -2121,8 +2082,8 @@ class GTEST_API_ [[nodiscard]] ScopedTrace {
// Assuming that each thread maintains its own stack of traces.
// Therefore, a SCOPED_TRACE() would (correctly) only affect the
// assertions in its own thread.
#define SCOPED_TRACE(message) \
const ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \
#define SCOPED_TRACE(message) \
::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \
__FILE__, __LINE__, (message))
// Compile-time assertion for type equality.
@ -2192,7 +2153,7 @@ constexpr bool StaticAssertTypeEq() noexcept {
// Define this macro to 1 to omit the definition of TEST(), which
// is a generic name and clashes with some other libraries.
#if !(defined(GTEST_DONT_DEFINE_TEST) && GTEST_DONT_DEFINE_TEST)
#if !GTEST_DONT_DEFINE_TEST
#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
#endif
@ -2224,22 +2185,17 @@ constexpr bool StaticAssertTypeEq() noexcept {
#define GTEST_TEST_F(test_fixture, test_name) \
GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>())
#if !(defined(GTEST_DONT_DEFINE_TEST_F) && GTEST_DONT_DEFINE_TEST_F)
#if !GTEST_DONT_DEFINE_TEST_F
#define TEST_F(test_fixture, test_name) GTEST_TEST_F(test_fixture, test_name)
#endif
// Returns a path to a temporary directory, which should be writable. It is
// implementation-dependent whether or not the path is terminated by the
// directory-separator character.
// Returns a path to temporary directory.
// Tries to determine an appropriate directory for the platform.
GTEST_API_ std::string TempDir();
// Returns a path to a directory that contains ancillary data files that might
// be used by tests. It is implementation dependent whether or not the path is
// terminated by the directory-separator character. The directory and the files
// in it should be considered read-only.
GTEST_API_ std::string SrcDir();
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4805 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// Dynamically registers a test with the framework.
//
@ -2328,12 +2284,11 @@ TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
// tests are successful, or 1 otherwise.
//
// RUN_ALL_TESTS() should be invoked after the command line has been
// parsed by InitGoogleTest(). RUN_ALL_TESTS will tear down and delete any
// installed environments and should only be called once per binary.
// parsed by InitGoogleTest().
//
// This function was formerly a macro; thus, it is in the global
// namespace and has an all-caps name.
[[nodiscard]] int RUN_ALL_TESTS();
int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); }

View File

@ -42,43 +42,21 @@
#include <stdio.h>
#include <memory>
#include <string>
#include "gtest/gtest-matchers.h"
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h"
GTEST_DECLARE_string_(internal_run_death_test);
namespace testing {
namespace internal {
// Name of the flag (needed for parsing Google Test flag).
// Names of the flags (needed for parsing Google Test flags).
const char kDeathTestStyleFlag[] = "death_test_style";
const char kDeathTestUseFork[] = "death_test_use_fork";
const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
// and interpreted as a regex (rather than an Eq matcher) for legacy
// compatibility.
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
::testing::internal::RE regex) {
return ContainsRegex(regex.pattern());
}
inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
return ContainsRegex(regex);
}
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
const ::std::string& regex) {
return ContainsRegex(regex);
}
// If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
// used directly.
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
Matcher<const ::std::string&> matcher) {
return matcher;
}
#ifdef GTEST_HAS_DEATH_TEST
#if GTEST_HAS_DEATH_TEST
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
@ -94,9 +72,9 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
//
// exit status: The integer exit information in the format specified
// by wait(2)
// exit code: The integer code passed to exit(3), _Exit(2), or
// exit code: The integer code passed to exit(3), _exit(2), or
// returned from main()
class GTEST_API_ [[nodiscard]] DeathTest {
class GTEST_API_ DeathTest {
public:
// Create returns false if there was an error determining the
// appropriate action to take for the current death test; for example,
@ -109,7 +87,7 @@ class GTEST_API_ [[nodiscard]] DeathTest {
static bool Create(const char* statement, Matcher<const std::string&> matcher,
const char* file, int line, DeathTest** test);
DeathTest();
virtual ~DeathTest() = default;
virtual ~DeathTest() {}
// A helper class that aborts a death test when it's deleted.
class ReturnSentinel {
@ -121,7 +99,7 @@ class GTEST_API_ [[nodiscard]] DeathTest {
DeathTest* const test_;
ReturnSentinel(const ReturnSentinel&) = delete;
ReturnSentinel& operator=(const ReturnSentinel&) = delete;
};
} GTEST_ATTRIBUTE_UNUSED_;
// An enumeration of possible roles that may be taken when a death
// test is encountered. EXECUTE means that the death test logic should
@ -172,16 +150,16 @@ class GTEST_API_ [[nodiscard]] DeathTest {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// Factory interface for death tests. May be mocked out for testing.
class [[nodiscard]] DeathTestFactory {
class DeathTestFactory {
public:
virtual ~DeathTestFactory() = default;
virtual ~DeathTestFactory() {}
virtual bool Create(const char* statement,
Matcher<const std::string&> matcher, const char* file,
int line, DeathTest** test) = 0;
};
// A concrete DeathTestFactory implementation for normal use.
class [[nodiscard]] DefaultDeathTestFactory : public DeathTestFactory {
class DefaultDeathTestFactory : public DeathTestFactory {
public:
bool Create(const char* statement, Matcher<const std::string&> matcher,
const char* file, int line, DeathTest** test) override;
@ -191,6 +169,28 @@ class [[nodiscard]] DefaultDeathTestFactory : public DeathTestFactory {
// by a signal, or exited normally with a nonzero exit code.
GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
// and interpreted as a regex (rather than an Eq matcher) for legacy
// compatibility.
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
::testing::internal::RE regex) {
return ContainsRegex(regex.pattern());
}
inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
return ContainsRegex(regex);
}
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
const ::std::string& regex) {
return ContainsRegex(regex);
}
// If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
// used directly.
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
Matcher<const ::std::string&> matcher) {
return matcher;
}
// Traps C++ exceptions escaping statement and reports them as test
// failures. Note that trapping SEH exceptions is not implemented here.
#if GTEST_HAS_EXCEPTIONS
@ -237,7 +237,7 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
} \
break; \
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
const ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
gtest_dt); \
GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
@ -256,19 +256,19 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
// must accept a streamed message even though the message is never printed.
// The regex object is not evaluated, but it is used to prevent "unused"
// warnings and to avoid an expression that doesn't compile in debug mode.
#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} else if (!::testing::internal::AlwaysTrue()) { \
(void)::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
} else \
#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
} else if (!::testing::internal::AlwaysTrue()) { \
::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
} else \
::testing::Message()
// A class representing the parsed contents of the
// --gtest_internal_run_death_test flag, as it existed when
// RUN_ALL_TESTS was called.
class [[nodiscard]] InternalRunDeathTestFlag {
class InternalRunDeathTestFlag {
public:
InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index,
int a_write_fd)

View File

@ -42,17 +42,11 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
#include <string>
#include <utility>
#include "gtest/internal/gtest-port.h"
#include "gtest/internal/gtest-string.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
#if GTEST_HAS_FILE_SYSTEM
namespace testing {
namespace internal {
@ -67,13 +61,12 @@ namespace internal {
// Names are NOT checked for syntax correctness -- no checking for illegal
// characters, malformed paths, etc.
class GTEST_API_ [[nodiscard]] FilePath {
class GTEST_API_ FilePath {
public:
FilePath() : pathname_("") {}
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {}
FilePath(FilePath&& rhs) noexcept : pathname_(std::move(rhs.pathname_)) {}
explicit FilePath(std::string pathname) : pathname_(std::move(pathname)) {
explicit FilePath(const std::string& pathname) : pathname_(pathname) {
Normalize();
}
@ -81,10 +74,6 @@ class GTEST_API_ [[nodiscard]] FilePath {
Set(rhs);
return *this;
}
FilePath& operator=(FilePath&& rhs) noexcept {
pathname_ = std::move(rhs.pathname_);
return *this;
}
void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; }
@ -210,16 +199,6 @@ class GTEST_API_ [[nodiscard]] FilePath {
// separators. Returns NULL if no path separator was found.
const char* FindLastPathSeparator() const;
// Returns the length of the path root, including the directory separator at
// the end of the prefix. Returns zero by definition if the path is relative.
// Examples:
// - [Windows] "..\Sibling" => 0
// - [Windows] "\Windows" => 1
// - [Windows] "C:/Windows\Notepad.exe" => 3
// - [Windows] "\\Host\Share\C$/Windows" => 13
// - [UNIX] "/bin" => 1
size_t CalculateRootLength() const;
std::string pathname_;
}; // class FilePath
@ -228,6 +207,4 @@ class GTEST_API_ [[nodiscard]] FilePath {
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GTEST_HAS_FILE_SYSTEM
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_

View File

@ -41,7 +41,7 @@
#include "gtest/internal/gtest-port.h"
#ifdef GTEST_OS_LINUX
#if GTEST_OS_LINUX
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
@ -57,13 +57,12 @@
#include <string.h>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <limits>
#include <map>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "gtest/gtest-message.h"
@ -78,7 +77,7 @@
//
// will result in the token foo__LINE__, instead of foo followed by
// the current line number. For more details, see
// https://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar
@ -95,7 +94,7 @@
#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
namespace proto2 {
class [[nodiscard]] MessageLite;
class MessageLite;
}
namespace testing {
@ -115,15 +114,15 @@ template <typename T>
namespace internal {
struct TraceInfo; // Information about a trace point.
class [[nodiscard]] TestInfoImpl; // Opaque implementation of TestInfo
class [[nodiscard]] UnitTestImpl; // Opaque implementation of UnitTest
class TestInfoImpl; // Opaque implementation of TestInfo
class UnitTestImpl; // Opaque implementation of UnitTest
// The text used in failure messages to indicate the start of the
// stack trace.
GTEST_API_ extern const char kStackTraceMarker[];
// An IgnoredValue object can be implicitly constructed from ANY value.
class [[nodiscard]] IgnoredValue {
class IgnoredValue {
struct Sink {};
public:
@ -155,8 +154,7 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(
// errors presumably detectable only at run time. Since
// std::runtime_error inherits from std::exception, many testing
// frameworks know how to extract and print the message inside it.
class GTEST_API_ [[nodiscard]] GoogleTestFailureException
: public ::std::runtime_error {
class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
public:
explicit GoogleTestFailureException(const TestPartResult& failure);
};
@ -170,7 +168,7 @@ namespace edit_distance {
// All edits cost the same, with replace having lower priority than
// add/remove.
// Simple implementation of the Wagner-Fischer algorithm.
// See https://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
enum EditType { kMatch, kAdd, kRemove, kReplace };
GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
const std::vector<size_t>& left, const std::vector<size_t>& right);
@ -237,13 +235,13 @@ GTEST_API_ std::string GetBoolAssertionFailureMessage(
// For double, there are 11 exponent bits and 52 fraction bits.
//
// More details can be found at
// https://en.wikipedia.org/wiki/IEEE_floating-point_standard.
// http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
//
// Template parameter:
//
// RawType: the raw floating-point type (either float or double)
template <typename RawType>
class [[nodiscard]] FloatingPoint {
class FloatingPoint {
public:
// Defines the unsigned integer type that has the same size as the
// floating point number.
@ -282,7 +280,7 @@ class [[nodiscard]] FloatingPoint {
// bits. Therefore, 4 should be enough for ordinary use.
//
// See the following article for more details on ULP:
// https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
// http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
static const uint32_t kMaxUlps = 4;
// Constructs a FloatingPoint from a raw floating-point number.
@ -291,35 +289,38 @@ class [[nodiscard]] FloatingPoint {
// around may change its bits, although the new value is guaranteed
// to be also a NAN. Therefore, don't expect this constructor to
// preserve the bits in x when x is a NAN.
explicit FloatingPoint(RawType x) { memcpy(&bits_, &x, sizeof(x)); }
explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
// Static methods
// Reinterprets a bit pattern as a floating-point number.
//
// This function is needed to test the AlmostEquals() method.
static RawType ReinterpretBits(Bits bits) {
RawType fp;
memcpy(&fp, &bits, sizeof(fp));
return fp;
static RawType ReinterpretBits(const Bits bits) {
FloatingPoint fp(0);
fp.u_.bits_ = bits;
return fp.u_.value_;
}
// Returns the floating-point number that represent positive infinity.
static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }
// Returns the maximum representable finite floating-point number.
static RawType Max();
// Non-static methods
// Returns the bits that represents this number.
const Bits& bits() const { return bits_; }
const Bits& bits() const { return u_.bits_; }
// Returns the exponent bits of this number.
Bits exponent_bits() const { return kExponentBitMask & bits_; }
Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
// Returns the fraction bits of this number.
Bits fraction_bits() const { return kFractionBitMask & bits_; }
Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
// Returns the sign bit of this number.
Bits sign_bit() const { return kSignBitMask & bits_; }
Bits sign_bit() const { return kSignBitMask & u_.bits_; }
// Returns true if and only if this is NAN (not a number).
bool is_nan() const {
@ -333,16 +334,23 @@ class [[nodiscard]] FloatingPoint {
//
// - returns false if either number is (or both are) NAN.
// - treats really large numbers as almost equal to infinity.
// - thinks +0.0 and -0.0 are 0 ULP's apart.
// - thinks +0.0 and -0.0 are 0 DLP's apart.
bool AlmostEquals(const FloatingPoint& rhs) const {
// The IEEE standard says that any comparison operation involving
// a NAN must return false.
if (is_nan() || rhs.is_nan()) return false;
return DistanceBetweenSignAndMagnitudeNumbers(bits_, rhs.bits_) <= kMaxUlps;
return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <=
kMaxUlps;
}
private:
// The data type used to store the actual floating-point number.
union FloatingPointUnion {
RawType value_; // The raw floating-point number.
Bits bits_; // The bits that represent the number.
};
// Converts an integer from the sign-and-magnitude representation to
// the biased representation. More precisely, let N be 2 to the
// power of (kBitCount - 1), an integer x is represented by the
@ -356,9 +364,9 @@ class [[nodiscard]] FloatingPoint {
// N - 1 (the biggest number representable using
// sign-and-magnitude) is represented by 2N - 1.
//
// Read https://en.wikipedia.org/wiki/Signed_number_representations
// Read http://en.wikipedia.org/wiki/Signed_number_representations
// for more details on signed number representations.
static Bits SignAndMagnitudeToBiased(Bits sam) {
static Bits SignAndMagnitudeToBiased(const Bits& sam) {
if (kSignBitMask & sam) {
// sam represents a negative number.
return ~sam + 1;
@ -370,15 +378,27 @@ class [[nodiscard]] FloatingPoint {
// Given two numbers in the sign-and-magnitude representation,
// returns the distance between them as an unsigned number.
static Bits DistanceBetweenSignAndMagnitudeNumbers(Bits sam1, Bits sam2) {
static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits& sam1,
const Bits& sam2) {
const Bits biased1 = SignAndMagnitudeToBiased(sam1);
const Bits biased2 = SignAndMagnitudeToBiased(sam2);
return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
}
Bits bits_; // The bits that represent the number.
FloatingPointUnion u_;
};
// We cannot use std::numeric_limits<T>::max() as it clashes with the max()
// macro defined by <windows.h>.
template <>
inline float FloatingPoint<float>::Max() {
return FLT_MAX;
}
template <>
inline double FloatingPoint<double>::Max() {
return DBL_MAX;
}
// Typedefs the instances of the FloatingPoint template class that we
// care to use.
typedef FloatingPoint<float> Float;
@ -393,7 +413,7 @@ typedef FloatingPoint<double> Double;
typedef const void* TypeId;
template <typename T>
class [[nodiscard]] TypeIdHelper {
class TypeIdHelper {
public:
// dummy_ must not have a const type. Otherwise an overly eager
// compiler (e.g. MSVC 7.1 & 8.0) may try to merge
@ -425,9 +445,9 @@ GTEST_API_ TypeId GetTestTypeId();
// Defines the abstract factory interface that creates instances
// of a Test object.
class [[nodiscard]] TestFactoryBase {
class TestFactoryBase {
public:
virtual ~TestFactoryBase() = default;
virtual ~TestFactoryBase() {}
// Creates a test instance to run. The instance is both created and destroyed
// within TestInfoImpl::Run()
@ -441,15 +461,15 @@ class [[nodiscard]] TestFactoryBase {
TestFactoryBase& operator=(const TestFactoryBase&) = delete;
};
// This class provides implementation of TestFactoryBase interface.
// This class provides implementation of TeastFactoryBase interface.
// It is used in TEST and TEST_F macros.
template <class TestClass>
class [[nodiscard]] TestFactoryImpl : public TestFactoryBase {
class TestFactoryImpl : public TestFactoryBase {
public:
Test* CreateTest() override { return new TestClass; }
};
#ifdef GTEST_OS_WINDOWS
#if GTEST_OS_WINDOWS
// Predicate-formatters for implementing the HRESULT checking macros
// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
@ -467,8 +487,8 @@ using SetUpTestSuiteFunc = void (*)();
using TearDownTestSuiteFunc = void (*)();
struct CodeLocation {
CodeLocation(std::string a_file, int a_line)
: file(std::move(a_file)), line(a_line) {}
CodeLocation(const std::string& a_file, int a_line)
: file(a_file), line(a_line) {}
std::string file;
int line;
@ -548,7 +568,7 @@ struct SuiteApiResolver : T {
// type_param: the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test.
// value_param: text representation of the test's value parameter,
// or NULL if this is not a value-parameterized test.
// or NULL if this is not a type-parameterized test.
// code_location: code location where the test is defined
// fixture_class_id: ID of the test fixture class
// set_up_tc: pointer to the function that sets up the test suite
@ -557,7 +577,7 @@ struct SuiteApiResolver : T {
// The newly created TestInfo instance will assume
// ownership of the factory object.
GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
std::string test_suite_name, const char* name, const char* type_param,
const char* test_suite_name, const char* name, const char* type_param,
const char* value_param, CodeLocation code_location,
TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
@ -571,7 +591,7 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
// State of the definition of a type-parameterized test suite.
class GTEST_API_ [[nodiscard]] TypedTestSuitePState {
class GTEST_API_ TypedTestSuitePState {
public:
TypedTestSuitePState() : registered_(false) {}
@ -588,7 +608,8 @@ class GTEST_API_ [[nodiscard]] TypedTestSuitePState {
fflush(stderr);
posix::Abort();
}
registered_tests_.emplace(test_name, CodeLocation(file, line));
registered_tests_.insert(
::std::make_pair(test_name, CodeLocation(file, line)));
return true;
}
@ -610,7 +631,7 @@ class GTEST_API_ [[nodiscard]] TypedTestSuitePState {
const char* registered_tests);
private:
typedef ::std::map<std::string, CodeLocation, std::less<>> RegisteredTestsMap;
typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
bool registered_;
RegisteredTestsMap registered_tests_;
@ -686,13 +707,13 @@ std::vector<std::string> GenerateNames() {
// Implementation note: The GTEST_TEMPLATE_ macro declares a template
// template parameter. It's defined in gtest-type-util.h.
template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
class [[nodiscard]] TypeParameterizedTest {
class TypeParameterizedTest {
public:
// 'index' is the index of the test in the type list 'Types'
// specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
// Types). Valid values for 'index' are [0, N - 1] where N is the
// length of Types.
static bool Register(const char* prefix, CodeLocation code_location,
static bool Register(const char* prefix, const CodeLocation& code_location,
const char* case_name, const char* test_names, int index,
const std::vector<std::string>& type_names =
GenerateNames<DefaultNameGenerator, Types>()) {
@ -704,7 +725,8 @@ class [[nodiscard]] TypeParameterizedTest {
// list.
MakeAndRegisterTestInfo(
(std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
"/" + type_names[static_cast<size_t>(index)]),
"/" + type_names[static_cast<size_t>(index)])
.c_str(),
StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
GetTypeName<Type>().c_str(),
nullptr, // No value parameter.
@ -716,17 +738,21 @@ class [[nodiscard]] TypeParameterizedTest {
new TestFactoryImpl<TestClass>);
// Next, recurses (at compile time) with the tail of the type list.
return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail>::
Register(prefix, std::move(code_location), case_name, test_names,
index + 1, type_names);
return TypeParameterizedTest<Fixture, TestSel,
typename Types::Tail>::Register(prefix,
code_location,
case_name,
test_names,
index + 1,
type_names);
}
};
// The base case for the compile time recursion.
template <GTEST_TEMPLATE_ Fixture, class TestSel>
class [[nodiscard]] TypeParameterizedTest<Fixture, TestSel, internal::None> {
class TypeParameterizedTest<Fixture, TestSel, internal::None> {
public:
static bool Register(const char* /*prefix*/, CodeLocation,
static bool Register(const char* /*prefix*/, const CodeLocation&,
const char* /*case_name*/, const char* /*test_names*/,
int /*index*/,
const std::vector<std::string>& =
@ -745,7 +771,7 @@ GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
// Test. The return value is insignificant - we just need to return
// something such that we can call this function in a namespace scope.
template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
class [[nodiscard]] TypeParameterizedTestSuite {
class TypeParameterizedTestSuite {
public:
static bool Register(const char* prefix, CodeLocation code_location,
const TypedTestSuitePState* state, const char* case_name,
@ -773,8 +799,7 @@ class [[nodiscard]] TypeParameterizedTestSuite {
// Next, recurses (at compile time) with the tail of the test list.
return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
Types>::Register(prefix,
std::move(code_location),
Types>::Register(prefix, code_location,
state, case_name,
SkipComma(test_names),
type_names);
@ -783,7 +808,7 @@ class [[nodiscard]] TypeParameterizedTestSuite {
// The base case for the compile time recursion.
template <GTEST_TEMPLATE_ Fixture, typename Types>
class [[nodiscard]] TypeParameterizedTestSuite<Fixture, internal::None, Types> {
class TypeParameterizedTestSuite<Fixture, internal::None, Types> {
public:
static bool Register(const char* /*prefix*/, const CodeLocation&,
const TypedTestSuitePState* /*state*/,
@ -804,7 +829,8 @@ class [[nodiscard]] TypeParameterizedTestSuite<Fixture, internal::None, Types> {
// For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(int skip_count);
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest* unit_test,
int skip_count);
// Helpers for suppressing warnings on unreachable code or constant
// condition.
@ -839,7 +865,7 @@ struct TrueWithString {
// doesn't use global state (and therefore can't interfere with user
// code). Unlike rand_r(), it's portable. An LCG isn't very random,
// but it's good enough for our purposes.
class GTEST_API_ [[nodiscard]] Random {
class GTEST_API_ Random {
public:
static const uint32_t kMaxRange = 1u << 31;
@ -865,7 +891,7 @@ class GTEST_API_ [[nodiscard]] Random {
// that's true if and only if T has methods DebugString() and ShortDebugString()
// that return std::string.
template <typename T>
class [[nodiscard]] HasDebugStringAndShortDebugString {
class HasDebugStringAndShortDebugString {
private:
template <typename C>
static auto CheckDebugString(C*) -> typename std::is_same<
@ -887,6 +913,9 @@ class [[nodiscard]] HasDebugStringAndShortDebugString {
HasDebugStringType::value && HasShortDebugStringType::value;
};
template <typename T>
constexpr bool HasDebugStringAndShortDebugString<T>::value;
// When the compiler sees expression IsContainerTest<C>(0), if C is an
// STL-style container class, the first overload of IsContainerTest
// will be viable (since both C::iterator* and C::const_iterator* are
@ -1065,7 +1094,7 @@ struct RelationToSourceCopy {};
// this requirement. Element can be an array type itself (hence
// multi-dimensional arrays are supported).
template <typename Element>
class [[nodiscard]] NativeArray {
class NativeArray {
public:
// STL-style container typedefs.
typedef Element value_type;
@ -1125,6 +1154,40 @@ class [[nodiscard]] NativeArray {
void (NativeArray::*clone_)(const Element*, size_t);
};
// Backport of std::index_sequence.
template <size_t... Is>
struct IndexSequence {
using type = IndexSequence;
};
// Double the IndexSequence, and one if plus_one is true.
template <bool plus_one, typename T, size_t sizeofT>
struct DoubleSequence;
template <size_t... I, size_t sizeofT>
struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
};
template <size_t... I, size_t sizeofT>
struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
using type = IndexSequence<I..., (sizeofT + I)...>;
};
// Backport of std::make_index_sequence.
// It uses O(ln(N)) instantiation depth.
template <size_t N>
struct MakeIndexSequenceImpl
: DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,
N / 2>::type {};
template <>
struct MakeIndexSequenceImpl<0> : IndexSequence<> {};
template <size_t N>
using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;
template <typename... T>
using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;
template <size_t>
struct Ignore {
Ignore(...); // NOLINT
@ -1133,7 +1196,7 @@ struct Ignore {
template <typename>
struct ElemFromListImpl;
template <size_t... I>
struct ElemFromListImpl<std::index_sequence<I...>> {
struct ElemFromListImpl<IndexSequence<I...>> {
// We make Ignore a template to solve a problem with MSVC.
// A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
// MSVC doesn't understand how to deal with that pack expansion.
@ -1144,14 +1207,15 @@ struct ElemFromListImpl<std::index_sequence<I...>> {
template <size_t N, typename... T>
struct ElemFromList {
using type = decltype(ElemFromListImpl<std::make_index_sequence<N>>::Apply(
static_cast<T (*)()>(nullptr)...));
using type =
decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(
static_cast<T (*)()>(nullptr)...));
};
struct FlatTupleConstructTag {};
template <typename... T>
class [[nodiscard]] FlatTuple;
class FlatTuple;
template <typename Derived, size_t I>
struct FlatTupleElemBase;
@ -1170,9 +1234,9 @@ template <typename Derived, typename Idx>
struct FlatTupleBase;
template <size_t... Idx, typename... T>
struct FlatTupleBase<FlatTuple<T...>, std::index_sequence<Idx...>>
struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
: FlatTupleElemBase<FlatTuple<T...>, Idx>... {
using Indices = std::index_sequence<Idx...>;
using Indices = IndexSequence<Idx...>;
FlatTupleBase() = default;
template <typename... Args>
explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)
@ -1207,15 +1271,14 @@ struct FlatTupleBase<FlatTuple<T...>, std::index_sequence<Idx...>>
// implementations.
// FlatTuple and ElemFromList are not recursive and have a fixed depth
// regardless of T...
// std::make_index_sequence, on the other hand, it is recursive but with an
// MakeIndexSequence, on the other hand, it is recursive but with an
// instantiation depth of O(ln(N)).
template <typename... T>
class [[nodiscard]] FlatTuple
class FlatTuple
: private FlatTupleBase<FlatTuple<T...>,
std::make_index_sequence<sizeof...(T)>> {
using Indices =
typename FlatTupleBase<FlatTuple<T...>,
std::make_index_sequence<sizeof...(T)>>::Indices;
typename MakeIndexSequence<sizeof...(T)>::type> {
using Indices = typename FlatTupleBase<
FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;
public:
FlatTuple() = default;
@ -1229,40 +1292,30 @@ class [[nodiscard]] FlatTuple
// Utility functions to be called with static_assert to induce deprecation
// warnings.
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"INSTANTIATE_TEST_CASE_P is deprecated, please use "
"INSTANTIATE_TEST_SUITE_P")]]
constexpr bool InstantiateTestCase_P_IsDeprecated() {
return true;
}
"INSTANTIATE_TEST_SUITE_P")
constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"TYPED_TEST_CASE_P is deprecated, please use "
"TYPED_TEST_SUITE_P")]]
constexpr bool TypedTestCase_P_IsDeprecated() {
return true;
}
"TYPED_TEST_SUITE_P")
constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"TYPED_TEST_CASE is deprecated, please use "
"TYPED_TEST_SUITE")]]
constexpr bool TypedTestCaseIsDeprecated() {
return true;
}
"TYPED_TEST_SUITE")
constexpr bool TypedTestCaseIsDeprecated() { return true; }
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
"REGISTER_TYPED_TEST_SUITE_P")]]
constexpr bool RegisterTypedTestCase_P_IsDeprecated() {
return true;
}
"REGISTER_TYPED_TEST_SUITE_P")
constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
[[deprecated(
GTEST_INTERNAL_DEPRECATED(
"INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
"INSTANTIATE_TYPED_TEST_SUITE_P")]]
constexpr bool InstantiateTypedTestCase_P_IsDeprecated() {
return true;
}
"INSTANTIATE_TYPED_TEST_SUITE_P")
constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
} // namespace internal
} // namespace testing
@ -1318,7 +1371,7 @@ struct tuple_size<testing::internal::FlatTuple<Ts...>>
namespace testing {
namespace internal {
class [[nodiscard]] NeverThrown {
class NeverThrown {
public:
const char* what() const noexcept {
return "this exception should never be thrown";
@ -1455,20 +1508,19 @@ class [[nodiscard]] NeverThrown {
gtest_ar_, text, #actual, #expected) \
.c_str())
#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
const ::testing::internal::HasNewFatalFailureHelper \
gtest_fatal_failure_checker; \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
} \
} else /* NOLINT */ \
GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \
: fail("Expected: " #statement \
" doesn't generate new fatal " \
"failures in the current thread.\n" \
#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \
::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
} \
} else \
GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \
: fail("Expected: " #statement \
" doesn't generate new fatal " \
"failures in the current thread.\n" \
" Actual: it does.")
// Expands to the name of the class that implements the given test.
@ -1499,7 +1551,7 @@ class [[nodiscard]] NeverThrown {
\
private: \
void TestBody() override; \
[[maybe_unused]] static ::testing::TestInfo* const test_info_; \
static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
}; \
\
::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \

View File

@ -39,16 +39,11 @@
#include <ctype.h>
#include <cassert>
#include <functional>
#include <iterator>
#include <map>
#include <memory>
#include <ostream>
#include <set>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
@ -87,19 +82,19 @@ namespace internal {
// TEST_P macro is used to define two tests with the same name
// but in different namespaces.
GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,
const CodeLocation& code_location);
CodeLocation code_location);
template <typename>
class [[nodiscard]] ParamGeneratorInterface;
class ParamGeneratorInterface;
template <typename>
class [[nodiscard]] ParamGenerator;
class ParamGenerator;
// Interface for iterating over elements provided by an implementation
// of ParamGeneratorInterface<T>.
template <typename T>
class [[nodiscard]] ParamIteratorInterface {
class ParamIteratorInterface {
public:
virtual ~ParamIteratorInterface() = default;
virtual ~ParamIteratorInterface() {}
// A pointer to the base generator instance.
// Used only for the purposes of iterator comparison
// to make sure that two iterators belong to the same generator.
@ -127,7 +122,7 @@ class [[nodiscard]] ParamIteratorInterface {
// ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
// and implements the const forward iterator concept.
template <typename T>
class [[nodiscard]] ParamIterator {
class ParamIterator {
public:
typedef T value_type;
typedef const T& reference;
@ -169,11 +164,11 @@ class [[nodiscard]] ParamIterator {
// ParamGeneratorInterface<T> is the binary interface to access generators
// defined in other translation units.
template <typename T>
class [[nodiscard]] ParamGeneratorInterface {
class ParamGeneratorInterface {
public:
typedef T ParamType;
virtual ~ParamGeneratorInterface() = default;
virtual ~ParamGeneratorInterface() {}
// Generator interface definition
virtual ParamIteratorInterface<T>* Begin() const = 0;
@ -186,7 +181,7 @@ class [[nodiscard]] ParamGeneratorInterface {
// ParamGeneratorInterface<T> instance is shared among all copies
// of the original object. This is possible because that instance is immutable.
template <typename T>
class [[nodiscard]] ParamGenerator {
class ParamGenerator {
public:
typedef ParamIterator<T> iterator;
@ -210,14 +205,14 @@ class [[nodiscard]] ParamGenerator {
// operator<().
// This class is used in the Range() function.
template <typename T, typename IncrementT>
class [[nodiscard]] RangeGenerator : public ParamGeneratorInterface<T> {
class RangeGenerator : public ParamGeneratorInterface<T> {
public:
RangeGenerator(T begin, T end, IncrementT step)
: begin_(begin),
end_(end),
step_(step),
end_index_(CalculateEndIndex(begin, end, step)) {}
~RangeGenerator() override = default;
~RangeGenerator() override {}
ParamIteratorInterface<T>* Begin() const override {
return new Iterator(this, begin_, 0, step_);
@ -232,7 +227,7 @@ class [[nodiscard]] RangeGenerator : public ParamGeneratorInterface<T> {
Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
IncrementT step)
: base_(base), value_(value), index_(index), step_(step) {}
~Iterator() override = default;
~Iterator() override {}
const ParamGeneratorInterface<T>* BaseGenerator() const override {
return base_;
@ -296,13 +291,12 @@ class [[nodiscard]] RangeGenerator : public ParamGeneratorInterface<T> {
// since the source can be located on the stack, and the generator
// is likely to persist beyond that stack frame.
template <typename T>
class [[nodiscard]] ValuesInIteratorRangeGenerator
: public ParamGeneratorInterface<T> {
class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
public:
template <typename ForwardIterator>
ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
: container_(begin, end) {}
~ValuesInIteratorRangeGenerator() override = default;
~ValuesInIteratorRangeGenerator() override {}
ParamIteratorInterface<T>* Begin() const override {
return new Iterator(this, container_.begin());
@ -319,7 +313,7 @@ class [[nodiscard]] ValuesInIteratorRangeGenerator
Iterator(const ParamGeneratorInterface<T>* base,
typename ContainerType::const_iterator iterator)
: base_(base), iterator_(iterator) {}
~Iterator() override = default;
~Iterator() override {}
const ParamGeneratorInterface<T>* BaseGenerator() const override {
return base_;
@ -382,7 +376,9 @@ class [[nodiscard]] ValuesInIteratorRangeGenerator
// integer test parameter index.
template <class ParamType>
std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
return std::to_string(info.index);
Message name_stream;
name_stream << info.index;
return name_stream.GetString();
}
template <typename T = int>
@ -397,7 +393,7 @@ void TestNotEmpty(const T&) {}
// Stores a parameter value and later creates tests parameterized with that
// value.
template <class TestClass>
class [[nodiscard]] ParameterizedTestFactory : public TestFactoryBase {
class ParameterizedTestFactory : public TestFactoryBase {
public:
typedef typename TestClass::ParamType ParamType;
explicit ParameterizedTestFactory(ParamType parameter)
@ -419,9 +415,9 @@ class [[nodiscard]] ParameterizedTestFactory : public TestFactoryBase {
// TestMetaFactoryBase is a base class for meta-factories that create
// test factories for passing into MakeAndRegisterTestInfo function.
template <class ParamType>
class [[nodiscard]] TestMetaFactoryBase {
class TestMetaFactoryBase {
public:
virtual ~TestMetaFactoryBase() = default;
virtual ~TestMetaFactoryBase() {}
virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
};
@ -435,12 +431,12 @@ class [[nodiscard]] TestMetaFactoryBase {
// it for each Test/Parameter value combination. Thus it needs meta factory
// creator class.
template <class TestSuite>
class [[nodiscard]] TestMetaFactory
class TestMetaFactory
: public TestMetaFactoryBase<typename TestSuite::ParamType> {
public:
using ParamType = typename TestSuite::ParamType;
TestMetaFactory() = default;
TestMetaFactory() {}
TestFactoryBase* CreateTestFactory(ParamType parameter) override {
return new ParameterizedTestFactory<TestSuite>(parameter);
@ -461,9 +457,9 @@ class [[nodiscard]] TestMetaFactory
// in RegisterTests method. The ParameterizeTestSuiteRegistry class holds
// a collection of pointers to the ParameterizedTestSuiteInfo objects
// and calls RegisterTests() on each of them when asked.
class [[nodiscard]] ParameterizedTestSuiteInfoBase {
class ParameterizedTestSuiteInfoBase {
public:
virtual ~ParameterizedTestSuiteInfoBase() = default;
virtual ~ParameterizedTestSuiteInfoBase() {}
// Base part of test suite name for display purposes.
virtual const std::string& GetTestSuiteName() const = 0;
@ -504,8 +500,7 @@ GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
// test suite. It registers tests with all values generated by all
// generators when asked.
template <class TestSuite>
class [[nodiscard]] ParameterizedTestSuiteInfo
: public ParameterizedTestSuiteInfoBase {
class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
public:
// ParamType and GeneratorCreationFunc are private types but are required
// for declarations of public methods AddTestPattern() and
@ -515,10 +510,9 @@ class [[nodiscard]] ParameterizedTestSuiteInfo
typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);
explicit ParameterizedTestSuiteInfo(std::string name,
explicit ParameterizedTestSuiteInfo(const char* name,
CodeLocation code_location)
: test_suite_name_(std::move(name)),
code_location_(std::move(code_location)) {}
: test_suite_name_(name), code_location_(code_location) {}
// Test suite base name for display purposes.
const std::string& GetTestSuiteName() const override {
@ -532,20 +526,20 @@ class [[nodiscard]] ParameterizedTestSuiteInfo
// prefix). test_base_name is the name of an individual test without
// parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
// test suite base name and DoBar is test base name.
void AddTestPattern(const char*, const char* test_base_name,
void AddTestPattern(const char* test_suite_name, const char* test_base_name,
TestMetaFactoryBase<ParamType>* meta_factory,
CodeLocation code_location) {
tests_.emplace_back(
new TestInfo(test_base_name, meta_factory, std::move(code_location)));
tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(
test_suite_name, test_base_name, meta_factory, code_location)));
}
// INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information
// about a generator.
int AddTestSuiteInstantiation(std::string instantiation_name,
int AddTestSuiteInstantiation(const std::string& instantiation_name,
GeneratorCreationFunc* func,
ParamNameGeneratorFunc* name_func,
const char* file, int line) {
instantiations_.emplace_back(std::move(instantiation_name), func, name_func,
file, line);
instantiations_.push_back(
InstantiationInfo(instantiation_name, func, name_func, file, line));
return 0; // Return value used only to run this method in namespace scope.
}
// UnitTest class invokes this method to register tests in this test suite
@ -556,61 +550,60 @@ class [[nodiscard]] ParameterizedTestSuiteInfo
void RegisterTests() override {
bool generated_instantiations = false;
std::string test_suite_name;
std::string test_name;
for (const std::shared_ptr<TestInfo>& test_info : tests_) {
for (const InstantiationInfo& instantiation : instantiations_) {
const std::string& instantiation_name = instantiation.name;
ParamGenerator<ParamType> generator((*instantiation.generator)());
ParamNameGeneratorFunc* name_func = instantiation.name_func;
const char* file = instantiation.file;
int line = instantiation.line;
for (typename TestInfoContainer::iterator test_it = tests_.begin();
test_it != tests_.end(); ++test_it) {
std::shared_ptr<TestInfo> test_info = *test_it;
for (typename InstantiationContainer::iterator gen_it =
instantiations_.begin();
gen_it != instantiations_.end(); ++gen_it) {
const std::string& instantiation_name = gen_it->name;
ParamGenerator<ParamType> generator((*gen_it->generator)());
ParamNameGeneratorFunc* name_func = gen_it->name_func;
const char* file = gen_it->file;
int line = gen_it->line;
std::string test_suite_name;
if (!instantiation_name.empty())
test_suite_name = instantiation_name + "/";
else
test_suite_name.clear();
test_suite_name += test_suite_name_;
test_suite_name += test_info->test_suite_base_name;
size_t i = 0;
std::set<std::string> test_param_names;
for (const auto& param : generator) {
for (typename ParamGenerator<ParamType>::iterator param_it =
generator.begin();
param_it != generator.end(); ++param_it, ++i) {
generated_instantiations = true;
test_name.clear();
Message test_name_stream;
std::string param_name =
name_func(TestParamInfo<ParamType>(param, i));
name_func(TestParamInfo<ParamType>(*param_it, i));
GTEST_CHECK_(IsValidParamName(param_name))
<< "Parameterized test name '" << param_name
<< "' is invalid (contains spaces, dashes, or any "
"non-alphanumeric characters other than underscores), in "
<< file << " line " << line << "" << std::endl;
<< "' is invalid, in " << file << " line " << line << std::endl;
GTEST_CHECK_(test_param_names.count(param_name) == 0)
<< "Duplicate parameterized test name '" << param_name << "', in "
<< file << " line " << line << std::endl;
test_param_names.insert(param_name);
if (!test_info->test_base_name.empty()) {
test_name.append(test_info->test_base_name).append("/");
test_name_stream << test_info->test_base_name << "/";
}
test_name += param_name;
test_param_names.insert(std::move(param_name));
test_name_stream << param_name;
MakeAndRegisterTestInfo(
test_suite_name, test_name.c_str(),
test_suite_name.c_str(), test_name_stream.GetString().c_str(),
nullptr, // No type parameter.
PrintToString(param).c_str(), test_info->code_location,
PrintToString(*param_it).c_str(), test_info->code_location,
GetTestSuiteTypeId(),
SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),
SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),
test_info->test_meta_factory->CreateTestFactory(param));
++i;
} // for param
} // for instantiation
} // for test_info
test_info->test_meta_factory->CreateTestFactory(*param_it));
} // for param_it
} // for gen_it
} // for test_it
if (!generated_instantiations) {
// There are no generaotrs, or they all generate nothing ...
@ -623,13 +616,15 @@ class [[nodiscard]] ParameterizedTestSuiteInfo
// LocalTestInfo structure keeps information about a single test registered
// with TEST_P macro.
struct TestInfo {
TestInfo(const char* a_test_base_name,
TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,
TestMetaFactoryBase<ParamType>* a_test_meta_factory,
CodeLocation a_code_location)
: test_base_name(a_test_base_name),
: test_suite_base_name(a_test_suite_base_name),
test_base_name(a_test_base_name),
test_meta_factory(a_test_meta_factory),
code_location(std::move(a_code_location)) {}
code_location(a_code_location) {}
const std::string test_suite_base_name;
const std::string test_base_name;
const std::unique_ptr<TestMetaFactoryBase<ParamType>> test_meta_factory;
const CodeLocation code_location;
@ -639,10 +634,11 @@ class [[nodiscard]] ParameterizedTestSuiteInfo
// <Instantiation name, Sequence generator creation function,
// Name generator function, Source file, Source line>
struct InstantiationInfo {
InstantiationInfo(std::string name_in, GeneratorCreationFunc* generator_in,
InstantiationInfo(const std::string& name_in,
GeneratorCreationFunc* generator_in,
ParamNameGeneratorFunc* name_func_in, const char* file_in,
int line_in)
: name(std::move(name_in)),
: name(name_in),
generator(generator_in),
name_func(name_func_in),
file(file_in),
@ -690,9 +686,9 @@ using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;
// ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P
// and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding
// ParameterizedTestSuiteInfo descriptors.
class [[nodiscard]] ParameterizedTestSuiteRegistry {
class ParameterizedTestSuiteRegistry {
public:
ParameterizedTestSuiteRegistry() = default;
ParameterizedTestSuiteRegistry() {}
~ParameterizedTestSuiteRegistry() {
for (auto& test_suite_info : test_suite_infos_) {
delete test_suite_info;
@ -703,32 +699,29 @@ class [[nodiscard]] ParameterizedTestSuiteRegistry {
// tests and instantiations of a particular test suite.
template <class TestSuite>
ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(
std::string test_suite_name, CodeLocation code_location) {
const char* test_suite_name, CodeLocation code_location) {
ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;
auto item_it = suite_name_to_info_index_.find(test_suite_name);
if (item_it != suite_name_to_info_index_.end()) {
auto* test_suite_info = test_suite_infos_[item_it->second];
if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
// Complain about incorrect usage of Google Test facilities
// and terminate the program since we cannot guaranty correct
// test suite setup and tear-down in this case.
ReportInvalidTestSuiteType(test_suite_name.c_str(), code_location);
posix::Abort();
} else {
// At this point we are sure that the object we found is of the same
// type we are looking for, so we downcast it to that type
// without further checks.
typed_test_info =
CheckedDowncastToActualType<ParameterizedTestSuiteInfo<TestSuite>>(
test_suite_info);
for (auto& test_suite_info : test_suite_infos_) {
if (test_suite_info->GetTestSuiteName() == test_suite_name) {
if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {
// Complain about incorrect usage of Google Test facilities
// and terminate the program since we cannot guaranty correct
// test suite setup and tear-down in this case.
ReportInvalidTestSuiteType(test_suite_name, code_location);
posix::Abort();
} else {
// At this point we are sure that the object we found is of the same
// type we are looking for, so we downcast it to that type
// without further checks.
typed_test_info = CheckedDowncastToActualType<
ParameterizedTestSuiteInfo<TestSuite>>(test_suite_info);
}
break;
}
}
if (typed_test_info == nullptr) {
typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(
test_suite_name, std::move(code_location));
suite_name_to_info_index_.emplace(std::move(test_suite_name),
test_suite_infos_.size());
test_suite_name, code_location);
test_suite_infos_.push_back(typed_test_info);
}
return typed_test_info;
@ -742,9 +735,8 @@ class [[nodiscard]] ParameterizedTestSuiteRegistry {
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
template <class TestCase>
ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
std::string test_case_name, CodeLocation code_location) {
return GetTestSuitePatternHolder<TestCase>(std::move(test_case_name),
std::move(code_location));
const char* test_case_name, CodeLocation code_location) {
return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);
}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
@ -753,7 +745,6 @@ class [[nodiscard]] ParameterizedTestSuiteRegistry {
using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;
TestSuiteInfoContainer test_suite_infos_;
::std::unordered_map<std::string, size_t> suite_name_to_info_index_;
ParameterizedTestSuiteRegistry(const ParameterizedTestSuiteRegistry&) =
delete;
@ -764,7 +755,7 @@ class [[nodiscard]] ParameterizedTestSuiteRegistry {
// Keep track of what type-parameterized test suite are defined and
// where as well as which are intatiated. This allows susequently
// identifying suits that are defined but never used.
class [[nodiscard]] TypeParameterizedTestSuiteRegistry {
class TypeParameterizedTestSuiteRegistry {
public:
// Add a suite definition
void RegisterTestSuite(const char* test_suite_name,
@ -780,7 +771,7 @@ class [[nodiscard]] TypeParameterizedTestSuiteRegistry {
private:
struct TypeParameterizedTestSuiteInfo {
explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
: code_location(std::move(c)), instantiated(false) {}
: code_location(c), instantiated(false) {}
CodeLocation code_location;
bool instantiated;
@ -800,38 +791,43 @@ internal::ParamGenerator<typename Container::value_type> ValuesIn(
namespace internal {
// Used in the Values() function to provide polymorphic capabilities.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4100)
#endif
template <typename... Ts>
class [[nodiscard]] ValueArray {
class ValueArray {
public:
explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}
template <typename T>
operator ParamGenerator<T>() const { // NOLINT
return ValuesIn(MakeVector<T>(std::make_index_sequence<sizeof...(Ts)>()));
return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));
}
private:
template <typename T, size_t... I>
std::vector<T> MakeVector(std::index_sequence<I...>) const {
std::vector<T> MakeVector(IndexSequence<I...>) const {
return std::vector<T>{static_cast<T>(v_.template Get<I>())...};
}
FlatTuple<Ts...> v_;
};
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
#ifdef _MSC_VER
#pragma warning(pop)
#endif
template <typename... T>
class [[nodiscard]] CartesianProductGenerator
class CartesianProductGenerator
: public ParamGeneratorInterface<::std::tuple<T...>> {
public:
typedef ::std::tuple<T...> ParamType;
CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)
: generators_(g) {}
~CartesianProductGenerator() override = default;
~CartesianProductGenerator() override {}
ParamIteratorInterface<ParamType>* Begin() const override {
return new Iterator(this, generators_, false);
@ -844,7 +840,7 @@ class [[nodiscard]] CartesianProductGenerator
template <class I>
class IteratorImpl;
template <size_t... I>
class IteratorImpl<std::index_sequence<I...>>
class IteratorImpl<IndexSequence<I...>>
: public ParamIteratorInterface<ParamType> {
public:
IteratorImpl(const ParamGeneratorInterface<ParamType>* base,
@ -856,7 +852,7 @@ class [[nodiscard]] CartesianProductGenerator
current_(is_end ? end_ : begin_) {
ComputeCurrentValue();
}
~IteratorImpl() override = default;
~IteratorImpl() override {}
const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {
return base_;
@ -935,13 +931,13 @@ class [[nodiscard]] CartesianProductGenerator
std::shared_ptr<ParamType> current_value_;
};
using Iterator = IteratorImpl<std::make_index_sequence<sizeof...(T)>>;
using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;
std::tuple<ParamGenerator<T>...> generators_;
};
template <class... Gen>
class [[nodiscard]] CartesianProductHolder {
class CartesianProductHolder {
public:
CartesianProductHolder(const Gen&... g) : generators_(g...) {}
template <typename... T>
@ -954,113 +950,6 @@ class [[nodiscard]] CartesianProductHolder {
std::tuple<Gen...> generators_;
};
template <typename From, typename To, typename Func>
class [[nodiscard]] ParamGeneratorConverter
: public ParamGeneratorInterface<To> {
public:
ParamGeneratorConverter(ParamGenerator<From> gen, Func converter) // NOLINT
: generator_(std::move(gen)), converter_(std::move(converter)) {}
ParamIteratorInterface<To>* Begin() const override {
return new Iterator(this, generator_.begin(), generator_.end());
}
ParamIteratorInterface<To>* End() const override {
return new Iterator(this, generator_.end(), generator_.end());
}
// Returns the std::function wrapping the user-supplied converter callable. It
// is used by the iterator (see class Iterator below) to convert the object
// (of type FROM) returned by the ParamGenerator to an object of a type that
// can be static_cast to type TO.
const Func& TypeConverter() const { return converter_; }
private:
class Iterator : public ParamIteratorInterface<To> {
public:
Iterator(const ParamGeneratorConverter* base, ParamIterator<From> it,
ParamIterator<From> end)
: base_(base), it_(it), end_(end) {
if (it_ != end_)
value_ =
std::make_shared<To>(static_cast<To>(base->TypeConverter()(*it_)));
}
~Iterator() override = default;
const ParamGeneratorInterface<To>* BaseGenerator() const override {
return base_;
}
void Advance() override {
++it_;
if (it_ != end_)
value_ =
std::make_shared<To>(static_cast<To>(base_->TypeConverter()(*it_)));
}
ParamIteratorInterface<To>* Clone() const override {
return new Iterator(*this);
}
const To* Current() const override { return value_.get(); }
bool Equals(const ParamIteratorInterface<To>& other) const override {
// Having the same base generator guarantees that the other
// iterator is of the same type and we can downcast.
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
<< "The program attempted to compare iterators "
<< "from different generators." << std::endl;
const ParamIterator<From> other_it =
CheckedDowncastToActualType<const Iterator>(&other)->it_;
return it_ == other_it;
}
private:
Iterator(const Iterator& other) = default;
const ParamGeneratorConverter* const base_;
ParamIterator<From> it_;
ParamIterator<From> end_;
std::shared_ptr<To> value_;
}; // class ParamGeneratorConverter::Iterator
ParamGenerator<From> generator_;
Func converter_;
}; // class ParamGeneratorConverter
template <class GeneratedT,
typename StdFunction =
std::function<const GeneratedT&(const GeneratedT&)>>
class [[nodiscard]] ParamConverterGenerator {
public:
ParamConverterGenerator(ParamGenerator<GeneratedT> g) // NOLINT
: generator_(std::move(g)), converter_(Identity) {}
ParamConverterGenerator(ParamGenerator<GeneratedT> g, StdFunction converter)
: generator_(std::move(g)), converter_(std::move(converter)) {}
template <typename T>
operator ParamGenerator<T>() const { // NOLINT
return ParamGenerator<T>(
new ParamGeneratorConverter<GeneratedT, T, StdFunction>(generator_,
converter_));
}
private:
static const GeneratedT& Identity(const GeneratedT& v) { return v; }
ParamGenerator<GeneratedT> generator_;
StdFunction converter_;
};
// Template to determine the param type of a single-param std::function.
template <typename T>
struct FuncSingleParamType;
template <typename R, typename P>
struct FuncSingleParamType<std::function<R(P)>> {
using type = std::remove_cv_t<std::remove_reference_t<P>>;
};
template <typename T>
struct IsSingleArgStdFunction : public std::false_type {};
template <typename R, typename P>
struct IsSingleArgStdFunction<std::function<R(P)>> : public std::true_type {};
} // namespace internal
} // namespace testing

View File

@ -56,8 +56,6 @@
#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
#define GTEST_OS_WINDOWS_PHONE 1
#define GTEST_OS_WINDOWS_TV_TITLE 1
#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_GAMES)
#define GTEST_OS_WINDOWS_GAMES 1
#else
// WINAPI_FAMILY defined but no known partition matched.
// Default to desktop.
@ -113,12 +111,6 @@
#define GTEST_OS_ESP32 1
#elif defined(__XTENSA__)
#define GTEST_OS_XTENSA 1
#elif defined(__hexagon__)
#define GTEST_OS_QURT 1
#elif defined(CPU_QN9090) || defined(CPU_QN9090HN)
#define GTEST_OS_NXP_QN9090 1
#elif defined(NRF52)
#define GTEST_OS_NRF52 1
#endif // __CYGWIN__
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_

File diff suppressed because it is too large Load Diff

View File

@ -51,7 +51,6 @@
#include <string.h>
#include <cstdint>
#include <sstream>
#include <string>
#include "gtest/internal/gtest-port.h"
@ -60,7 +59,7 @@ namespace testing {
namespace internal {
// String - an abstract class holding static string utilities.
class GTEST_API_ [[nodiscard]] String {
class GTEST_API_ String {
public:
// Static utility methods
@ -73,7 +72,7 @@ class GTEST_API_ [[nodiscard]] String {
// memory using malloc().
static const char* CloneCString(const char* c_str);
#ifdef GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE
// Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
// able to pass strings to Win32 APIs on CE we need to convert them
// to 'Unicode', UTF-16.
@ -166,7 +165,7 @@ class GTEST_API_ [[nodiscard]] String {
private:
String(); // Not meant to be instantiated.
}; // class String
}; // class String
// Gets the content of the stringstream's buffer as an std::string. Each '\0'
// character in the buffer is replaced with "\\0".

View File

@ -37,10 +37,6 @@
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
#include <string>
#include <type_traits>
#include <typeinfo>
#include "gtest/internal/gtest-port.h"
// #ifdef __GNUC__ is too general here. It is possible to use gcc without using
@ -67,22 +63,6 @@ inline std::string CanonicalizeForStdLibVersioning(std::string s) {
s.erase(strlen("std"), end - strlen("std"));
}
}
// Strip redundant spaces in typename to match MSVC
// For example, std::pair<int, bool> -> std::pair<int,bool>
static const char to_search[] = ", ";
const char replace_char = ',';
size_t pos = 0;
while (true) {
// Get the next occurrence from the current position
pos = s.find(to_search, pos);
if (pos == std::string::npos) {
break;
}
// Replace this occurrence of substring
s.replace(pos, strlen(to_search), 1, replace_char);
++pos;
}
return s;
}
@ -101,20 +81,6 @@ inline std::string GetTypeName(const std::type_info& type) {
const std::string name_str(status == 0 ? readable_name : name);
free(readable_name);
return CanonicalizeForStdLibVersioning(name_str);
#elif defined(_MSC_VER)
// Strip struct and class due to differences between
// MSVC and other compilers. std::pair<int,bool> is printed as
// "struct std::pair<int,bool>" when using MSVC vs "std::pair<int, bool>" with
// other compilers.
std::string s = name;
// Only strip the leading "struct " and "class ", so uses rfind == 0 to
// ensure that
if (s.rfind("struct ", 0) == 0) {
s = s.substr(strlen("struct "));
} else if (s.rfind("class ", 0) == 0) {
s = s.substr(strlen("class "));
}
return s;
#else
return name;
#endif // GTEST_HAS_CXXABI_H_ || __HP_aCC

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