Unverified Commit 76bce79a authored by Andy Soffer's avatar Andy Soffer Committed by GitHub
Browse files

Merge branch 'main' into fixes_std_pair_diff

parents 6f1c4b3d f345b2ca
...@@ -10,21 +10,21 @@ body: ...@@ -10,21 +10,21 @@ body:
description: We recommend using the latest commit from GitHub in your projects. description: We recommend using the latest commit from GitHub in your projects.
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: why id: why
attributes: attributes:
label: Why do we need this feature? label: Why do we need this feature?
description: Ideally, explain why a combination of existing features cannot be used instead. description: Ideally, explain why a combination of existing features cannot be used instead.
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: proposal id: proposal
attributes: attributes:
label: Describe the proposal. label: Describe the proposal.
description: Include a detailed description of the feature, with usage examples. description: Include a detailed description of the feature, with usage examples.
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: platform id: platform
attributes: attributes:
label: Is the feature specific to an operating system, compiler, or build system version? label: Is the feature specific to an operating system, compiler, or build system version?
......
workspace(name = "com_google_googletest") workspace(name = "com_google_googletest")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("//:googletest_deps.bzl", "googletest_deps")
googletest_deps()
http_archive(
name = "com_google_absl", # 2023-01-10T21:08:25Z
sha256 = "f9a4e749f42c386a32a90fddf0e2913ed408d10c42f7f33ccf4c59ac4f0d1d05",
strip_prefix = "abseil-cpp-52835439ca90d86b27bf8cd1708296e95604d724",
urls = ["https://github.com/abseil/abseil-cpp/archive/52835439ca90d86b27bf8cd1708296e95604d724.zip"],
)
# Note this must use a commit from the `abseil` branch of the RE2 project. load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# https://github.com/google/re2/tree/abseil
http_archive(
name = "com_googlesource_code_re2", # 2022-12-21T14:29:10Z
sha256 = "b9ce3a51beebb38534d11d40f8928d40509b9e18a735f6a4a97ad3d014c87cb5",
strip_prefix = "re2-d0b1f8f2ecc2ea74956c7608b6f915175314ff0e",
urls = ["https://github.com/google/re2/archive/d0b1f8f2ecc2ea74956c7608b6f915175314ff0e.zip"],
)
http_archive( http_archive(
name = "rules_python", # 2023-01-10T22:00:51Z name = "rules_python", # 2023-01-10T22:00:51Z
......
...@@ -31,8 +31,8 @@ ...@@ -31,8 +31,8 @@
set -euox pipefail set -euox pipefail
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20220217" readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20230217"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20220621" readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20230120"
if [[ -z ${GTEST_ROOT:-} ]]; then if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)" GTEST_ROOT="$(realpath $(dirname ${0})/..)"
...@@ -78,6 +78,7 @@ time docker run \ ...@@ -78,6 +78,7 @@ time docker run \
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wuninitialized" \ --copt="-Wuninitialized" \
--copt="-Wundef" \
--copt="-Wno-error=pragmas" \ --copt="-Wno-error=pragmas" \
--distdir="/bazel-distdir" \ --distdir="/bazel-distdir" \
--features=external_include_paths \ --features=external_include_paths \
...@@ -99,6 +100,7 @@ for std in ${STD}; do ...@@ -99,6 +100,7 @@ for std in ${STD}; do
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wuninitialized" \ --copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \ --define="absl=${absl}" \
--distdir="/bazel-distdir" \ --distdir="/bazel-distdir" \
--features=external_include_paths \ --features=external_include_paths \
...@@ -123,6 +125,7 @@ for std in ${STD}; do ...@@ -123,6 +125,7 @@ for std in ${STD}; do
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wuninitialized" \ --copt="-Wuninitialized" \
--copt="-Wundef" \
--define="absl=${absl}" \ --define="absl=${absl}" \
--distdir="/bazel-distdir" \ --distdir="/bazel-distdir" \
--features=external_include_paths \ --features=external_include_paths \
......
...@@ -66,6 +66,7 @@ for absl in 0 1; do ...@@ -66,6 +66,7 @@ for absl in 0 1; do
${BAZEL_BIN} test ... \ ${BAZEL_BIN} test ... \
--copt="-Wall" \ --copt="-Wall" \
--copt="-Werror" \ --copt="-Werror" \
--copt="-Wundef" \
--cxxopt="-std=c++14" \ --cxxopt="-std=c++14" \
--define="absl=${absl}" \ --define="absl=${absl}" \
--features=external_include_paths \ --features=external_include_paths \
......
...@@ -2,12 +2,14 @@ SETLOCAL ENABLEDELAYEDEXPANSION ...@@ -2,12 +2,14 @@ SETLOCAL ENABLEDELAYEDEXPANSION
SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-5.1.1-windows-x86_64.exe SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-5.1.1-windows-x86_64.exe
SET PATH=C:\Python37;%PATH% SET PATH=C:\Python34;%PATH%
SET BAZEL_PYTHON=C:\python37\python.exe SET BAZEL_PYTHON=C:\python34\python.exe
SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe
SET CMAKE_BIN="C:\Program Files\CMake\bin\cmake.exe" SET CMAKE_BIN="cmake.exe"
SET CTEST_BIN="C:\Program Files\CMake\bin\ctest.exe" SET CTEST_BIN="ctest.exe"
SET CTEST_OUTPUT_ON_FAILURE=1 SET CTEST_OUTPUT_ON_FAILURE=1
SET CMAKE_BUILD_PARALLEL_LEVEL=16
SET CTEST_PARALLEL_LEVEL=16
IF EXIST git\googletest ( IF EXIST git\googletest (
CD git\googletest CD git\googletest
...@@ -18,12 +20,12 @@ IF EXIST git\googletest ( ...@@ -18,12 +20,12 @@ IF EXIST git\googletest (
IF %errorlevel% neq 0 EXIT /B 1 IF %errorlevel% neq 0 EXIT /B 1
:: ---------------------------------------------------------------------------- :: ----------------------------------------------------------------------------
:: CMake Visual Studio 15 2017 Win64 :: CMake
MKDIR cmake_msvc2017 MKDIR cmake_msvc2022
CD cmake_msvc2017 CD cmake_msvc2022
%CMAKE_BIN% .. ^ %CMAKE_BIN% .. ^
-G "Visual Studio 15 2017 Win64" ^ -G "Visual Studio 17 2022" ^
-DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^ -DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^
-DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^ -DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^
-DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^ -DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^
...@@ -39,12 +41,12 @@ IF %errorlevel% neq 0 EXIT /B 1 ...@@ -39,12 +41,12 @@ IF %errorlevel% neq 0 EXIT /B 1
IF %errorlevel% neq 0 EXIT /B 1 IF %errorlevel% neq 0 EXIT /B 1
CD .. CD ..
RMDIR /S /Q cmake_msvc2017 RMDIR /S /Q cmake_msvc2022
:: ---------------------------------------------------------------------------- :: ----------------------------------------------------------------------------
:: Bazel Visual Studio 15 2017 Win64 :: Bazel
SET BAZEL_VC=C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community
%BAZEL_EXE% test ... ^ %BAZEL_EXE% test ... ^
--compilation_mode=dbg ^ --compilation_mode=dbg ^
--copt=/std:c++14 ^ --copt=/std:c++14 ^
......
# Advanced googletest Topics # Advanced GoogleTest Topics
## Introduction ## Introduction
Now that you have read the [googletest Primer](primer.md) and learned how to 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 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 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 messages, propagate fatal failures, reuse and speed up your test fixtures, and
use various flags with your tests. use various flags with your tests.
...@@ -25,7 +25,7 @@ Reference. ...@@ -25,7 +25,7 @@ Reference.
### Predicate Assertions for Better Error Messages ### 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 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 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 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 ...@@ -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 is awkward especially when the expression has side-effects or is expensive to
evaluate. 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 #### Using an Existing Boolean Function
...@@ -304,9 +304,9 @@ TEST_F(SkipFixture, SkipsOneTest) { ...@@ -304,9 +304,9 @@ TEST_F(SkipFixture, SkipsOneTest) {
As with assertion macros, you can stream a custom message into `GTEST_SKIP()`. 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. 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 This printer knows how to print built-in C++ types, native arrays, STL
...@@ -315,73 +315,96 @@ prints the raw bytes in the value and hopes that you the user can figure it out. ...@@ -315,73 +315,96 @@ 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 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 to do a better job at printing your particular type than to dump the bytes. To
do that, define `<<` for your type: do that, define an `AbslStringify()` overload as a `friend` function template
for your type:
```c++
#include <ostream>
```cpp
namespace foo { namespace foo {
class Bar { // We want googletest to be able to print instances of this. class Point { // We want GoogleTest to be able to print instances of this.
... ...
// Create a free inline friend function. // Provide a friend overload.
friend std::ostream& operator<<(std::ostream& os, const Bar& bar) { template <typename Sink>
return os << bar.DebugString(); // whatever needed to print bar to os 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 // 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 // AbslStringify overload is defined in the SAME namespace that defines Point.
// rules rely on that. // C++'s look-up rules rely on that.
std::ostream& operator<<(std::ostream& os, const Bar& bar) { enum class EnumWithStringify { kMany = 0, kChoices = 1 };
return os << bar.DebugString(); // whatever needed to print bar to os
template <typename Sink>
void AbslStringify(Sink& sink, EnumWithStringify e) {
absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices");
} }
} // namespace foo } // namespace foo
``` ```
Sometimes, this might not be an option: your team may consider it bad style to {: .callout .note}
have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its
doesn't do what you want (and you cannot change it). If so, you can instead string. For more information about supported operations on `AbslStringify()`'s
define a `PrintTo()` function like this: sink, see go/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:
```c++ ```c++
#include <ostream> #include <ostream>
namespace foo { namespace foo {
class Bar { class Point {
... ...
friend void PrintTo(const Bar& bar, std::ostream* os) { friend void PrintTo(const Point& point, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os *os << "(" << point.x << "," << point.y << ")";
} }
int x;
int y;
}; };
// If you can't declare the function in the class it's important that PrintTo() // 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 // is defined in the SAME namespace that defines Point. C++'s look-up rules
// on that. // rely on that.
void PrintTo(const Bar& bar, std::ostream* os) { void PrintTo(const Point& point, std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os *os << "(" << point.x << "," << point.y << ")";
} }
} // namespace foo } // namespace foo
``` ```
If you have defined both `<<` and `PrintTo()`, the latter will be used when If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be
googletest is concerned. This allows you to customize how the value appears in 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 its GoogleTest's output without affecting code that relies on the behavior of
`<<` operator. `AbslStringify()`.
If you have an existing `<<` operator and would like to define an
`AbslStringify()`, the latter will be used for GoogleTest printing.
If you want to print a value `x` using googletest's value printer yourself, just If you want to print a value `x` using GoogleTest's value printer yourself, just
call `::testing::PrintToString(x)`, which returns an `std::string`: call `::testing::PrintToString(x)`, which returns an `std::string`:
```c++ ```c++
vector<pair<Bar, int> > bar_ints = GetBarIntVector(); vector<pair<Point, int> > point_ints = GetPointIntVector();
EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) EXPECT_TRUE(IsCorrectPointIntVector(point_ints))
<< "bar_ints = " << testing::PrintToString(bar_ints); << "point_ints = " << testing::PrintToString(point_ints);
``` ```
For more details regarding `AbslStringify()` and its integration with other
libraries, see go/abslstringify.
## Death Tests ## Death Tests
In many applications, there are assertions that can cause application failure if In many applications, there are assertions that can cause application failure if
...@@ -451,7 +474,7 @@ Note that a death test only cares about three things: ...@@ -451,7 +474,7 @@ Note that a death test only cares about three things:
3. does the stderr output match `matcher`? 3. does the stderr output match `matcher`?
In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it 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. the process.
### Death Test Naming ### Death Test Naming
...@@ -482,14 +505,14 @@ TEST_F(FooDeathTest, DoesThat) { ...@@ -482,14 +505,14 @@ TEST_F(FooDeathTest, DoesThat) {
### Regular Expression Syntax ### Regular Expression Syntax
When built with Bazel and using Abseil, googletest uses the When built with Bazel and using Abseil, GoogleTest uses the
[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX [RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX
systems (Linux, Cygwin, Mac), googletest uses the systems (Linux, Cygwin, Mac), GoogleTest uses the
[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) [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 syntax. To learn about POSIX syntax, you may want to read this
[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended). [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended).
On Windows, googletest uses its own simple regular expression implementation. It On Windows, GoogleTest uses its own simple regular expression implementation. It
lacks many features. For example, we don't support union (`"x|y"`), grouping lacks many features. For example, we don't support union (`"x|y"`), grouping
(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among (`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among
others. Below is what we do support (`A` denotes a literal character, period others. Below is what we do support (`A` denotes a literal character, period
...@@ -519,7 +542,7 @@ Expression | Meaning ...@@ -519,7 +542,7 @@ Expression | Meaning
`$` | matches the end 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` `xy` | matches `x` followed by `y`
To help you determine which capability is available on your system, googletest 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: 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 `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 tests to work in all cases, you can either `#if` on these macros or use the more
...@@ -539,7 +562,7 @@ arrange that kind of environment. For example, statically-initialized modules ...@@ -539,7 +562,7 @@ arrange that kind of environment. For example, statically-initialized modules
may start threads before main is ever reached. Once threads have been created, may start threads before main is ever reached. Once threads have been created,
it may be difficult or impossible to clean them up. 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 1. A warning is emitted if multiple threads are running when a death test is
encountered. encountered.
...@@ -562,7 +585,7 @@ The automated testing framework does not set the style flag. You can choose a ...@@ -562,7 +585,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: particular style of death tests by setting the flag programmatically:
```c++ ```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, You can do this in `main()` to set the style for all death tests in the binary,
...@@ -592,7 +615,7 @@ TEST(MyDeathTest, TestTwo) { ...@@ -592,7 +615,7 @@ TEST(MyDeathTest, TestTwo) {
The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If 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 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 may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid
them in `statement`. them in `statement`.
...@@ -726,7 +749,7 @@ TEST(FooTest, Bar) { ...@@ -726,7 +749,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 either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the
`HasFatalFailure()` function. They are described in the following two `HasFatalFailure()` function. They are described in the following two
subsections. subsections.
...@@ -760,7 +783,7 @@ in it, the test will continue after the subroutine returns. This may not be what ...@@ -760,7 +783,7 @@ in it, the test will continue after the subroutine returns. This may not be what
you want. you want.
Often people want fatal failures to propagate like exceptions. For that 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 Fatal assertion | Nonfatal assertion | Verifies
------------------------------------- | ------------------------------------- | -------- ------------------------------------- | ------------------------------------- | --------
...@@ -852,7 +875,7 @@ will output XML like this: ...@@ -852,7 +875,7 @@ will output XML like this:
> needs to be prefixed with `::testing::Test::` if used outside of the > needs to be prefixed with `::testing::Test::` if used outside of the
> `TEST` body and the test fixture class. > `TEST` body and the test fixture class.
> * *`key`* must be a valid XML attribute name, and cannot conflict with the > * *`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`). > `type_param`, and `value_param`).
> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. > * 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 > If it's called outside of a test but between a test suite's
...@@ -863,13 +886,13 @@ will output XML like this: ...@@ -863,13 +886,13 @@ will output XML like this:
## Sharing Resources Between Tests in the Same Test Suite ## 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 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 that are expensive to set up, making the one-copy-per-test model prohibitively
expensive. expensive.
If the tests don't change the resource, there's no harm in their sharing a 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: 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 1. In your test fixture class (say `FooTest` ), declare as `static` some member
...@@ -881,7 +904,7 @@ also supports per-test-suite set-up/tear-down. To use it: ...@@ -881,7 +904,7 @@ also supports per-test-suite set-up/tear-down. To use it:
`u`!) to set up the shared resources and a `static void TearDownTestSuite()` `u`!) to set up the shared resources and a `static void TearDownTestSuite()`
function to tear them down. 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 *first test* in the `FooTest` test suite (i.e. before creating the first
`FooTest` object), and calls `TearDownTestSuite()` after running the *last test* `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 in it (i.e. after deleting the last `FooTest` object). In between, the tests can
...@@ -974,7 +997,7 @@ class Environment : public ::testing::Environment { ...@@ -974,7 +997,7 @@ 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: calling the `::testing::AddGlobalTestEnvironment()` function:
```c++ ```c++
...@@ -991,7 +1014,7 @@ It's OK to register multiple environment objects. In this suite, their `SetUp()` ...@@ -991,7 +1014,7 @@ 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 will be called in the order they are registered, and their `TearDown()` will be
called in the reverse order. 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. Therefore **do not delete them** by yourself.
You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called,
...@@ -1043,7 +1066,7 @@ they must be declared **public** rather than **protected** in order to use ...@@ -1043,7 +1066,7 @@ they must be declared **public** rather than **protected** in order to use
```c++ ```c++
class FooTest : class FooTest :
public testing::TestWithParam<const char*> { public testing::TestWithParam<absl::string_view> {
// You can implement all the usual fixture class members here. // You can implement all the usual fixture class members here.
// To access the test parameter, call GetParam() from class // To access the test parameter, call GetParam() from class
// TestWithParam<T>. // TestWithParam<T>.
...@@ -1054,7 +1077,7 @@ class BaseTest : public testing::Test { ...@@ -1054,7 +1077,7 @@ class BaseTest : public testing::Test {
... ...
}; };
class BarTest : public BaseTest, class BarTest : public BaseTest,
public testing::WithParamInterface<const char*> { public testing::WithParamInterface<absl::string_view> {
... ...
}; };
``` ```
...@@ -1125,8 +1148,8 @@ with parameter values `"cat"` and `"dog"` using the ...@@ -1125,8 +1148,8 @@ with parameter values `"cat"` and `"dog"` using the
[`ValuesIn`](reference/testing.md#param-generators) parameter generator: [`ValuesIn`](reference/testing.md#param-generators) parameter generator:
```c++ ```c++
const char* pets[] = {"cat", "dog"}; constexpr absl::string_view kPets[] = {"cat", "dog"};
INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets)); INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets));
``` ```
The tests from the instantiation above will have these names: The tests from the instantiation above will have these names:
...@@ -1501,12 +1524,12 @@ To test them, we use the following special techniques: ...@@ -1501,12 +1524,12 @@ To test them, we use the following special techniques:
## "Catching" Failures ## "Catching" Failures
If you are building a testing utility on top of googletest, you'll want to test 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. 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. 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 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? we test that a piece of code generates an expected failure?
`"gtest/gtest-spi.h"` contains some constructs to do this. `"gtest/gtest-spi.h"` contains some constructs to do this.
...@@ -1649,9 +1672,9 @@ particular, you cannot find the test suite name in `SetUpTestSuite()`, ...@@ -1649,9 +1672,9 @@ particular, you cannot find the test suite name in `SetUpTestSuite()`,
`TearDownTestSuite()` (where you know the test suite name implicitly), or `TearDownTestSuite()` (where you know the test suite name implicitly), or
functions called from them. 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 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 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 method, among others. You may use this API to augment or replace the standard
...@@ -1712,7 +1735,7 @@ Here's an example: ...@@ -1712,7 +1735,7 @@ Here's an example:
### Using Event Listeners ### Using Event Listeners
To use the event listener you have defined, add an instance of it to the 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" [`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s"
at the end of the name) in your `main()` function, before calling at the end of the name) in your `main()` function, before calling
`RUN_ALL_TESTS()`: `RUN_ALL_TESTS()`:
...@@ -1723,7 +1746,7 @@ int main(int argc, char** argv) { ...@@ -1723,7 +1746,7 @@ int main(int argc, char** argv) {
// Gets hold of the event listener list. // Gets hold of the event listener list.
testing::TestEventListeners& listeners = testing::TestEventListeners& listeners =
testing::UnitTest::GetInstance()->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); listeners.Append(new MinimalistPrinter);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
...@@ -1775,7 +1798,7 @@ See [sample10_unittest.cc] for an example of a failure-raising listener. ...@@ -1775,7 +1798,7 @@ See [sample10_unittest.cc] for an example of a failure-raising listener.
## Running Test Programs: Advanced Options ## 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 directly and affect their behavior via the following environment variables
and/or command line flags. For the flags to work, your programs must call and/or command line flags. For the flags to work, your programs must call
`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. `::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.
...@@ -1808,10 +1831,10 @@ corresponding environment variable for this flag. ...@@ -1808,10 +1831,10 @@ corresponding environment variable for this flag.
#### Running a Subset of the Tests #### 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 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 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. 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 The format of a filter is a '`:`'-separated list of wildcard patterns (called
...@@ -1842,7 +1865,7 @@ For example: ...@@ -1842,7 +1865,7 @@ For example:
#### Stop test execution upon first failure #### 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 cases (e.g. iterative test development & execution) it may be desirable stop
test execution upon first failure (trading improved latency for completeness). test execution upon first failure (trading improved latency for completeness).
If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set, If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,
...@@ -1859,7 +1882,7 @@ If you need to disable all tests in a test suite, you can either add `DISABLED_` ...@@ -1859,7 +1882,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 to the front of the name of each test, or alternatively add it to the front of
the test suite name. 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: will still be compiled:
```c++ ```c++
...@@ -1874,7 +1897,7 @@ TEST_F(DISABLED_BarTest, DoesXyz) { ... } ...@@ -1874,7 +1897,7 @@ TEST_F(DISABLED_BarTest, DoesXyz) { ... }
{: .callout .note} {: .callout .note}
NOTE: This feature should only be used for temporary pain-relief. You still have 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. a banner warning you if a test program contains any disabled tests.
{: .callout .tip} {: .callout .tip}
...@@ -1932,16 +1955,16 @@ You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` ...@@ -1932,16 +1955,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. environment variable to `1`) to run the tests in a program in a random order.
This helps to reveal bad dependencies between tests. 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 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 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` 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 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 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. 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. random seed and re-shuffle the tests in each iteration.
### Distributing Test Functions to Multiple Machines ### Distributing Test Functions to Multiple Machines
...@@ -2000,7 +2023,7 @@ shards, but here's one possible scenario: ...@@ -2000,7 +2023,7 @@ shards, but here's one possible scenario:
#### Colored Terminal Output #### 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: important information:
<pre>... <pre>...
...@@ -2025,25 +2048,25 @@ important information: ...@@ -2025,25 +2048,25 @@ important information:
You can set the `GTEST_COLOR` environment variable or the `--gtest_color` 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, 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 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`. platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.
#### Suppressing test passes #### 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 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`. `--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.
#### Suppressing the Elapsed Time #### 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 that, run the test program with the `--gtest_print_time=0` command line flag, or
set the GTEST_PRINT_TIME environment variable to `0`. set the GTEST_PRINT_TIME environment variable to `0`.
#### Suppressing UTF-8 Text Output #### 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 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 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 text because, for example, you don't have an UTF-8 compatible output medium, run
...@@ -2052,7 +2075,7 @@ environment variable to `0`. ...@@ -2052,7 +2075,7 @@ environment variable to `0`.
#### Generating an XML Report #### 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 textual output. The report contains the duration of each test, and thus can help
you identify slow tests. you identify slow tests.
...@@ -2063,15 +2086,15 @@ in which case the output can be found in the `test_detail.xml` file in the ...@@ -2063,15 +2086,15 @@ in which case the output can be found in the `test_detail.xml` file in the
current directory. current directory.
If you specify a directory (for example, `"xml:output/directory/"` on Linux or 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 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 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. `foo_test_1.xml`) to avoid overwriting it.
The report is based on the `junitreport` Ant task. Since that format was 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 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 ```xml
<testsuites name="AllTests" ...> <testsuites name="AllTests" ...>
...@@ -2086,8 +2109,8 @@ apply to googletest tests, as shown here: ...@@ -2086,8 +2109,8 @@ apply to googletest tests, as shown here:
``` ```
* The root `<testsuites>` element corresponds to the entire test program. * The root `<testsuites>` element corresponds to the entire test program.
* `<testsuite>` elements correspond to googletest test suites. * `<testsuite>` elements correspond to GoogleTest test suites.
* `<testcase>` elements correspond to googletest test functions. * `<testcase>` elements correspond to GoogleTest test functions.
For instance, the following program For instance, the following program
...@@ -2120,7 +2143,7 @@ could generate this report: ...@@ -2120,7 +2143,7 @@ could generate this report:
Things to note: Things to note:
* The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how * 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. `failures` attribute tells how many of them failed.
* The `time` attribute expresses the duration of the test, test suite, or * The `time` attribute expresses the duration of the test, test suite, or
...@@ -2132,12 +2155,12 @@ Things to note: ...@@ -2132,12 +2155,12 @@ Things to note:
* The `file` and `line` attributes record the source file location, where the * The `file` and `line` attributes record the source file location, where the
test was defined. test was defined.
* Each `<failure>` element corresponds to a single failed googletest * Each `<failure>` element corresponds to a single failed GoogleTest
assertion. assertion.
#### Generating a JSON Report #### 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 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 `--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 create the file at the given location. You can also just use the string
...@@ -2362,7 +2385,7 @@ variable has been set. ...@@ -2362,7 +2385,7 @@ variable has been set.
When running test programs under a debugger, it's very convenient if the When running test programs under a debugger, it's very convenient if the
debugger can catch an assertion failure and automatically drop into interactive 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 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` other than `0`. Alternatively, you can use the `--gtest_break_on_failure`
...@@ -2370,9 +2393,9 @@ command line flag. ...@@ -2370,9 +2393,9 @@ command line flag.
#### Disabling Catching Test-Thrown Exceptions #### 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 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 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 uncaught exception will cause a pop-up window, so catching the exceptions allows
you to run the tests automatically. you to run the tests automatically.
...@@ -2410,4 +2433,4 @@ void __tsan_on_report() { ...@@ -2410,4 +2433,4 @@ void __tsan_on_report() {
``` ```
After compiling your project with one of the sanitizers enabled, if a particular 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.
...@@ -2781,26 +2781,21 @@ action: ...@@ -2781,26 +2781,21 @@ action:
If you are not happy with the default action, you can tweak it as usual; see If you are not happy with the default action, you can tweak it as usual; see
[Setting Default Actions](#OnCall). [Setting Default Actions](#OnCall).
If you just need to return a pre-defined move-only value, you can use the If you just need to return a move-only value, you can use it in combination with
`Return(ByMove(...))` action: `WillOnce`. For example:
```cpp ```cpp
// When this fires, the unique_ptr<> specified by ByMove(...) will EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"))
// be returned. .WillOnce(Return(std::make_unique<Buzz>(AccessLevel::kInternal)));
EXPECT_CALL(mock_buzzer_, MakeBuzz("world")) EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("hello"));
.WillOnce(Return(ByMove(std::make_unique<Buzz>(AccessLevel::kInternal))));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world"));
``` ```
Note that `ByMove()` is essential here - if you drop it, the code won’t compile. 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
Quiz time! What do you think will happen if a `Return(ByMove(...))` action is think of it, after the first time the action runs, the source value will be
performed more than once (e.g. you write `... consumed (since it’s a move-only value), so the next time around, there’s no
.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time value to move from -- you’ll get a run-time error that `Return(std::move(...))`
the action runs, the source value will be consumed (since it’s a move-only can only be run once.
value), so the next time around, there’s no value to move from -- you’ll 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, 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 remember that you can always use a lambda or a callable object, which can do
...@@ -2817,7 +2812,7 @@ pretty much anything you want: ...@@ -2817,7 +2812,7 @@ pretty much anything you want:
``` ```
Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created
and returned. You cannot do this with `Return(ByMove(...))`. and returned. You cannot do this with `Return(std::make_unique<...>(...))`.
That covers returning move-only values; but how do we work with methods 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 accepting move-only arguments? The answer is that they work normally, although
...@@ -4298,7 +4293,7 @@ particular type than to dump the bytes. ...@@ -4298,7 +4293,7 @@ particular type than to dump the bytes.
### Mock std::function {#MockFunction} ### Mock std::function {#MockFunction}
`std::function` is a general function type introduced in C++11. It is a `std::function` is a general function type introduced in C++11. It is a
preferred way of passing callbacks to new interfaces. Functions are copiable, preferred way of passing callbacks to new interfaces. Functions are copyable,
and are not usually passed around by pointer, which makes them tricky to mock. and are not usually passed around by pointer, which makes them tricky to mock.
But fear not - `MockFunction` can help you with that. But fear not - `MockFunction` can help you with that.
......
# 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 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. 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 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, 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 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 and subroutines. This common pattern is easy to recognize and makes tests
easy to maintain. Such consistency is especially helpful when people switch easy to maintain. Such consistency is especially helpful when people switch
projects and start to work on a new code base. 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 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 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 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 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. 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 Thus, you can detect and fix multiple bugs in a single run-edit-compile
cycle. cycle.
5. The testing framework should liberate test writers from housekeeping chores 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 track of all tests defined, and doesn't require the user to enumerate them
in order to run 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 across tests and pay for the set-up/tear-down only once, without making
tests depend on each other. 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 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! minutes to learn the basics and get started. So let's go!
## Beware of the nomenclature ## Beware of the nomenclature
{: .callout .note} {: .callout .note}
_Note:_ There might be some confusion arising from different definitions of the *Note:* There might be some confusion arising from different definitions of the
terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these. 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 related tests, whereas current publications, including International Software
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
various textbooks on software quality, use the term 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 The related term *Test*, as it is used in GoogleTest, corresponds to the term
_[Test Case][istqb test case]_ of ISTQB and others. *[Test Case][istqb test case]* of ISTQB and others.
The term _Test_ is commonly of broad enough sense, including ISTQB's definition 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 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. 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 The preferred API is *TestSuite*. The older TestCase API is being slowly
deprecated and refactored away. deprecated and refactored away.
So please be aware of the different definitions of the terms: So please be aware of the different definitions of the terms:
Meaning | googletest Term | [ISTQB](http://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] Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
...@@ -78,7 +78,7 @@ Exercise a particular program path with specific input values and verify the res ...@@ -78,7 +78,7 @@ Exercise a particular program path with specific input values and verify the res
## Basic Concepts ## 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*, 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 *nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
current function; otherwise the program continues normally. current function; otherwise the program continues normally.
...@@ -98,11 +98,11 @@ assertion level and building up to tests and test suites. ...@@ -98,11 +98,11 @@ assertion level and building up to tests and test suites.
## Assertions ## 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, 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 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 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 on the current function. `ASSERT_*` versions generate fatal failures when they
...@@ -149,7 +149,7 @@ To create a test: ...@@ -149,7 +149,7 @@ To create a test:
1. Use the `TEST()` macro to define and name a test function. These are 1. Use the `TEST()` macro to define and name a test function. These are
ordinary C++ functions that don't return a value. ordinary C++ functions that don't return a value.
2. In this function, along with any valid C++ statements you want to include, 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 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 test fails (either fatally or non-fatally), or if the test crashes, the
entire test fails. Otherwise, it succeeds. entire test fails. Otherwise, it succeeds.
...@@ -190,7 +190,7 @@ TEST(FactorialTest, HandlesPositiveInput) { ...@@ -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 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, `TEST()` should be the same. In the above example, we have two tests,
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test `HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
...@@ -227,14 +227,14 @@ When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to ...@@ -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: access objects and subroutines in the test fixture:
```c++ ```c++
TEST_F(TestFixtureName, TestName) { TEST_F(TestFixtureClassName, TestName) {
... test body ... ... test body ...
} }
``` ```
Like `TEST()`, the first argument is the test suite name, but for `TEST_F()` Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test
this must be the name of the test fixture class. You've probably guessed: `_F` fixture class. (`_F` stands for "Fixture"). No test suite name is specified for
is for fixture. this macro.
Unfortunately, the C++ macro system does not allow us to create a single macro 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 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 ...@@ -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 `TEST_F()`, or you'll get the compiler error "`virtual outside class
declaration`". declaration`".
For each test defined with `TEST_F()`, googletest will create a *fresh* test For each test defined with `TEST_F()`, GoogleTest will create a *fresh* test
fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean
up by calling `TearDown()`, and then delete the test fixture. Note that up by calling `TearDown()`, and then delete the test fixture. Note that
different tests in the same test suite have different test fixture objects, and different tests in the same test suite have different test fixture objects, and
googletest always deletes a test fixture before it creates the next one. GoogleTest always deletes a test fixture before it creates the next one.
googletest does **not** reuse the same test fixture for multiple tests. Any GoogleTest does **not** reuse the same test fixture for multiple tests. Any
changes one test makes to the fixture do not affect other tests. 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 As an example, let's write tests for a FIFO queue class named `Queue`, which has
...@@ -325,7 +325,7 @@ would lead to a segfault when `n` is `NULL`. ...@@ -325,7 +325,7 @@ would lead to a segfault when `n` is `NULL`.
When these tests run, the following happens: When these tests run, the following happens:
1. googletest constructs a `QueueTest` object (let's call it `t1`). 1. GoogleTest constructs a `QueueTest` object (let's call it `t1`).
2. `t1.SetUp()` initializes `t1`. 2. `t1.SetUp()` initializes `t1`.
3. The first test (`IsEmptyInitially`) runs on `t1`. 3. The first test (`IsEmptyInitially`) runs on `t1`.
4. `t1.TearDown()` cleans up after the test finishes. 4. `t1.TearDown()` cleans up after the test finishes.
...@@ -337,7 +337,7 @@ When these tests run, the following happens: ...@@ -337,7 +337,7 @@ When these tests run, the following happens:
## Invoking the Tests ## 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 unlike with many other C++ testing frameworks, you don't have to re-list all
your defined tests in order to run them. your defined tests in order to run them.
...@@ -348,7 +348,7 @@ test suites, or even different source files. ...@@ -348,7 +348,7 @@ test suites, or even different source files.
When invoked, the `RUN_ALL_TESTS()` macro: 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. * Creates a test fixture object for the first test.
...@@ -360,7 +360,7 @@ When invoked, the `RUN_ALL_TESTS()` macro: ...@@ -360,7 +360,7 @@ When invoked, the `RUN_ALL_TESTS()` macro:
* Deletes the fixture. * 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. * Repeats the above steps for the next test, until all tests have run.
...@@ -374,14 +374,14 @@ If a fatal failure happens the subsequent steps will be skipped. ...@@ -374,14 +374,14 @@ If a fatal failure happens the subsequent steps will be skipped.
> return the value of `RUN_ALL_TESTS()`. > return the value of `RUN_ALL_TESTS()`.
> >
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than > 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. > [death tests](advanced.md#death-tests)) and thus is not supported.
**Availability**: Linux, Windows, Mac. **Availability**: Linux, Windows, Mac.
## Writing the main() Function ## 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 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 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 should only apply when you need to do something custom before the tests run that
...@@ -456,7 +456,7 @@ int main(int argc, char **argv) { ...@@ -456,7 +456,7 @@ int main(int argc, char **argv) {
``` ```
The `::testing::InitGoogleTest()` function parses the command line for The `::testing::InitGoogleTest()` function parses the command line for
googletest flags, and removes all recognized flags. This allows the user to GoogleTest flags, and removes all recognized flags. This allows the user to
control a test program's behavior via various flags, which we'll cover in the 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 [AdvancedGuide](advanced.md). You **must** call this function before calling
`RUN_ALL_TESTS()`, or the flags won't be properly initialized. `RUN_ALL_TESTS()`, or the flags won't be properly initialized.
...@@ -476,7 +476,7 @@ NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. ...@@ -476,7 +476,7 @@ NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
* Google Test is designed to be thread-safe. The implementation is thread-safe * Google Test is designed to be thread-safe. The implementation is thread-safe
on systems where the `pthreads` library is available. It is currently 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 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 the assertions are done in the main thread. If you want to help, you can
volunteer to implement the necessary synchronization primitives in volunteer to implement the necessary synchronization primitives in
......
...@@ -515,7 +515,7 @@ Verifies that *`expression`* is a success `HRESULT`. ...@@ -515,7 +515,7 @@ Verifies that *`expression`* is a success `HRESULT`.
### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED} ### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED}
`EXPECT_HRESULT_FAILED(`*`expression`*`)` \ `EXPECT_HRESULT_FAILED(`*`expression`*`)` \
`EXPECT_HRESULT_FAILED(`*`expression`*`)` `ASSERT_HRESULT_FAILED(`*`expression`*`)`
Verifies that *`expression`* is a failure `HRESULT`. Verifies that *`expression`* is a failure `HRESULT`.
......
...@@ -110,6 +110,7 @@ namespace: ...@@ -110,6 +110,7 @@ namespace:
| `Bool()` | Yields sequence `{false, true}`. | | `Bool()` | Yields sequence `{false, true}`. |
| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. | | `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. |
| `ConvertGenerator<T>(g)` | Yields values generated by generator `g`, `static_cast` to `T`. | | `ConvertGenerator<T>(g)` | Yields values generated by generator `g`, `static_cast` to `T`. |
The optional last argument *`name_generator`* is a function or functor that The optional last argument *`name_generator`* is a function or functor that
generates custom test name suffixes based on the test parameters. The function generates custom test name suffixes based on the test parameters. The function
must accept an argument of type must accept an argument of type
......
...@@ -611,7 +611,7 @@ class DefaultValue { ...@@ -611,7 +611,7 @@ class DefaultValue {
private: private:
class ValueProducer { class ValueProducer {
public: public:
virtual ~ValueProducer() {} virtual ~ValueProducer() = default;
virtual T Produce() = 0; virtual T Produce() = 0;
}; };
...@@ -699,8 +699,8 @@ class ActionInterface { ...@@ -699,8 +699,8 @@ class ActionInterface {
typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::Result Result;
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
ActionInterface() {} ActionInterface() = default;
virtual ~ActionInterface() {} virtual ~ActionInterface() = default;
// Performs the action. This method is not const, as in general an // Performs the action. This method is not const, as in general an
// action can have side effects and be stateful. For example, a // action can have side effects and be stateful. For example, a
...@@ -749,7 +749,7 @@ class Action<R(Args...)> { ...@@ -749,7 +749,7 @@ class Action<R(Args...)> {
// Constructs a null Action. Needed for storing Action objects in // Constructs a null Action. Needed for storing Action objects in
// STL containers. // STL containers.
Action() {} Action() = default;
// Construct an Action from a specified callable. // Construct an Action from a specified callable.
// This cannot take std::function directly, because then Action would not be // This cannot take std::function directly, because then Action would not be
...@@ -1273,7 +1273,7 @@ class AssignAction { ...@@ -1273,7 +1273,7 @@ class AssignAction {
const T2 value_; const T2 value_;
}; };
#if !GTEST_OS_WINDOWS_MOBILE #ifndef GTEST_OS_WINDOWS_MOBILE
// Implements the SetErrnoAndReturn action to simulate return from // Implements the SetErrnoAndReturn action to simulate return from
// various system calls and libc functions. // various system calls and libc functions.
...@@ -1926,7 +1926,7 @@ PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) { ...@@ -1926,7 +1926,7 @@ PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {
return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
} }
#if !GTEST_OS_WINDOWS_MOBILE #ifndef GTEST_OS_WINDOWS_MOBILE
// Creates an action that sets errno and returns the appropriate error. // Creates an action that sets errno and returns the appropriate error.
template <typename T> template <typename T>
......
...@@ -65,7 +65,7 @@ namespace testing { ...@@ -65,7 +65,7 @@ namespace testing {
// The implementation of a cardinality. // The implementation of a cardinality.
class CardinalityInterface { class CardinalityInterface {
public: public:
virtual ~CardinalityInterface() {} virtual ~CardinalityInterface() = default;
// Conservative estimate on the lower/upper bound of the number of // Conservative estimate on the lower/upper bound of the number of
// calls allowed. // calls allowed.
...@@ -92,7 +92,7 @@ class GTEST_API_ Cardinality { ...@@ -92,7 +92,7 @@ class GTEST_API_ Cardinality {
public: public:
// Constructs a null cardinality. Needed for storing Cardinality // Constructs a null cardinality. Needed for storing Cardinality
// objects in STL containers. // objects in STL containers.
Cardinality() {} Cardinality() = default;
// Constructs a Cardinality from its implementation. // Constructs a Cardinality from its implementation.
explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
......
...@@ -257,6 +257,8 @@ ...@@ -257,6 +257,8 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <exception>
#include <functional>
#include <initializer_list> #include <initializer_list>
#include <ios> #include <ios>
#include <iterator> #include <iterator>
...@@ -562,7 +564,7 @@ namespace internal { ...@@ -562,7 +564,7 @@ namespace internal {
// If the explanation is not empty, prints it to the ostream. // If the explanation is not empty, prints it to the ostream.
inline void PrintIfNotEmpty(const std::string& explanation, inline void PrintIfNotEmpty(const std::string& explanation,
::std::ostream* os) { ::std::ostream* os) {
if (explanation != "" && os != nullptr) { if (!explanation.empty() && os != nullptr) {
*os << ", " << explanation; *os << ", " << explanation;
} }
} }
...@@ -1199,27 +1201,27 @@ class PairMatchBase { ...@@ -1199,27 +1201,27 @@ class PairMatchBase {
}; };
}; };
class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> { class Eq2Matcher : public PairMatchBase<Eq2Matcher, std::equal_to<>> {
public: public:
static const char* Desc() { return "an equal pair"; } static const char* Desc() { return "an equal pair"; }
}; };
class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> { class Ne2Matcher : public PairMatchBase<Ne2Matcher, std::not_equal_to<>> {
public: public:
static const char* Desc() { return "an unequal pair"; } static const char* Desc() { return "an unequal pair"; }
}; };
class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> { class Lt2Matcher : public PairMatchBase<Lt2Matcher, std::less<>> {
public: public:
static const char* Desc() { return "a pair where the first < the second"; } static const char* Desc() { return "a pair where the first < the second"; }
}; };
class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> { class Gt2Matcher : public PairMatchBase<Gt2Matcher, std::greater<>> {
public: public:
static const char* Desc() { return "a pair where the first > the second"; } static const char* Desc() { return "a pair where the first > the second"; }
}; };
class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> { class Le2Matcher : public PairMatchBase<Le2Matcher, std::less_equal<>> {
public: public:
static const char* Desc() { return "a pair where the first <= the second"; } static const char* Desc() { return "a pair where the first <= the second"; }
}; };
class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> { class Ge2Matcher : public PairMatchBase<Ge2Matcher, std::greater_equal<>> {
public: public:
static const char* Desc() { return "a pair where the first >= the second"; } static const char* Desc() { return "a pair where the first >= the second"; }
}; };
...@@ -1473,6 +1475,7 @@ class SomeOfArrayMatcher { ...@@ -1473,6 +1475,7 @@ class SomeOfArrayMatcher {
operator Matcher<U>() const { // NOLINT operator Matcher<U>() const { // NOLINT
using RawU = typename std::decay<U>::type; using RawU = typename std::decay<U>::type;
std::vector<Matcher<RawU>> matchers; std::vector<Matcher<RawU>> matchers;
matchers.reserve(matchers_.size());
for (const auto& matcher : matchers_) { for (const auto& matcher : matchers_) {
matchers.push_back(MatcherCast<RawU>(matcher)); matchers.push_back(MatcherCast<RawU>(matcher));
} }
...@@ -2964,7 +2967,7 @@ class KeyMatcherImpl : public MatcherInterface<PairType> { ...@@ -2964,7 +2967,7 @@ class KeyMatcherImpl : public MatcherInterface<PairType> {
const bool match = inner_matcher_.MatchAndExplain( const bool match = inner_matcher_.MatchAndExplain(
pair_getters::First(key_value, Rank0()), &inner_listener); pair_getters::First(key_value, Rank0()), &inner_listener);
const std::string explanation = inner_listener.str(); const std::string explanation = inner_listener.str();
if (explanation != "") { if (!explanation.empty()) {
*listener << "whose first field is a value " << explanation; *listener << "whose first field is a value " << explanation;
} }
return match; return match;
...@@ -3111,12 +3114,12 @@ class PairMatcherImpl : public MatcherInterface<PairType> { ...@@ -3111,12 +3114,12 @@ class PairMatcherImpl : public MatcherInterface<PairType> {
const std::string& second_explanation, const std::string& second_explanation,
MatchResultListener* listener) const { MatchResultListener* listener) const {
*listener << "whose both fields match"; *listener << "whose both fields match";
if (first_explanation != "") { if (!first_explanation.empty()) {
*listener << ", where the first field is a value " << first_explanation; *listener << ", where the first field is a value " << first_explanation;
} }
if (second_explanation != "") { if (!second_explanation.empty()) {
*listener << ", "; *listener << ", ";
if (first_explanation != "") { if (!first_explanation.empty()) {
*listener << "and "; *listener << "and ";
} else { } else {
*listener << "where "; *listener << "where ";
...@@ -5542,7 +5545,8 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage( ...@@ -5542,7 +5545,8 @@ PolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(
\ \
private: \ private: \
::std::string FormatDescription(bool negation) const { \ ::std::string FormatDescription(bool negation) const { \
::std::string gmock_description = (description); \ ::std::string gmock_description; \
gmock_description = (description); \
if (!gmock_description.empty()) { \ if (!gmock_description.empty()) { \
return gmock_description; \ return gmock_description; \
} \ } \
......
...@@ -98,7 +98,7 @@ constexpr bool HasStrictnessModifier() { ...@@ -98,7 +98,7 @@ constexpr bool HasStrictnessModifier() {
// deregistration. This guarantees that MockClass's constructor and destructor // deregistration. This guarantees that MockClass's constructor and destructor
// run with the same level of strictness as its instance methods. // run with the same level of strictness as its instance methods.
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \ #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) && \
(defined(_MSC_VER) || defined(__clang__)) (defined(_MSC_VER) || defined(__clang__))
// We need to mark these classes with this declspec to ensure that // We need to mark these classes with this declspec to ensure that
// the empty base class optimization is performed. // the empty base class optimization is performed.
......
...@@ -204,6 +204,9 @@ class GTEST_API_ UntypedFunctionMockerBase { ...@@ -204,6 +204,9 @@ class GTEST_API_ UntypedFunctionMockerBase {
using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>; using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
struct UninterestingCallCleanupHandler;
struct FailureCleanupHandler;
// Returns an Expectation object that references and co-owns exp, // Returns an Expectation object that references and co-owns exp,
// which must be an expectation on this mock function. // which must be an expectation on this mock function.
Expectation GetHandleOf(ExpectationBase* exp); Expectation GetHandleOf(ExpectationBase* exp);
...@@ -563,7 +566,7 @@ class ExpectationSet { ...@@ -563,7 +566,7 @@ class ExpectationSet {
typedef Expectation::Set::value_type value_type; typedef Expectation::Set::value_type value_type;
// Constructs an empty set. // Constructs an empty set.
ExpectationSet() {} ExpectationSet() = default;
// This single-argument ctor must not be explicit, in order to support the // This single-argument ctor must not be explicit, in order to support the
// ExpectationSet es = EXPECT_CALL(...); // ExpectationSet es = EXPECT_CALL(...);
...@@ -1396,6 +1399,41 @@ class Cleanup final { ...@@ -1396,6 +1399,41 @@ class Cleanup final {
std::function<void()> f_; 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> template <typename F>
class FunctionMocker; class FunctionMocker;
...@@ -1408,7 +1446,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { ...@@ -1408,7 +1446,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
using ArgumentTuple = std::tuple<Args...>; using ArgumentTuple = std::tuple<Args...>;
using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>; using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
FunctionMocker() {} FunctionMocker() = default;
// There is no generally useful and implementable semantics of // There is no generally useful and implementable semantics of
// copying a mock object, so copying a mock is usually a user error. // copying a mock object, so copying a mock is usually a user error.
...@@ -1794,8 +1832,15 @@ R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args) ...@@ -1794,8 +1832,15 @@ 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 // 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. // either case we can't assign it to a local variable.
const Cleanup report_uninteresting_call( //
[&] { ReportUninterestingCall(reaction, ss.str()); }); // 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
};
return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss); return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
} }
...@@ -1839,22 +1884,14 @@ R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args) ...@@ -1839,22 +1884,14 @@ 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 // 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. // either case we can't assign it to a local variable.
const Cleanup handle_failures([&] { //
ss << "\n" << why.str(); // Note that we *don't* use any local callback types (like lambdas) here.
// Doing so slows down compilation dramatically because the *constructor* of
if (!found) { // std::function<T> is re-instantiated with different template
// No expectation matches this call - reports a failure. // parameters each time.
Expect(false, nullptr, -1, ss.str()); const FailureCleanupHandler handle_failures = {
} else if (is_excessive) { ss, why, loc, untyped_expectation, found, 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(), return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
ss); ss);
......
...@@ -224,7 +224,7 @@ class FailureReporterInterface { ...@@ -224,7 +224,7 @@ class FailureReporterInterface {
// The type of a failure (either non-fatal or fatal). // The type of a failure (either non-fatal or fatal).
enum FailureType { kNonfatal, kFatal }; enum FailureType { kNonfatal, kFatal };
virtual ~FailureReporterInterface() {} virtual ~FailureReporterInterface() = default;
// Reports a failure that occurred at the given source file location. // Reports a failure that occurred at the given source file location.
virtual void ReportFailure(FailureType type, const char* file, int line, virtual void ReportFailure(FailureType type, const char* file, int line,
...@@ -311,7 +311,8 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers(); ...@@ -311,7 +311,8 @@ GTEST_API_ WithoutMatchers GetWithoutMatchers();
// crashes). // crashes).
template <typename T> template <typename T>
inline T Invalid() { inline T Invalid() {
Assert(false, "", -1, "Internal error: attempt to return invalid value"); Assert(/*condition=*/false, /*file=*/"", /*line=*/-1,
"Internal error: attempt to return invalid value");
#if defined(__GNUC__) || defined(__clang__) #if defined(__GNUC__) || defined(__clang__)
__builtin_unreachable(); __builtin_unreachable();
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
...@@ -464,8 +465,10 @@ struct Function<R(Args...)> { ...@@ -464,8 +465,10 @@ struct Function<R(Args...)> {
using MakeResultIgnoredValue = IgnoredValue(Args...); using MakeResultIgnoredValue = IgnoredValue(Args...);
}; };
#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
template <typename R, typename... Args> template <typename R, typename... Args>
constexpr size_t Function<R(Args...)>::ArgumentCount; constexpr size_t Function<R(Args...)>::ArgumentCount;
#endif
// Workaround for MSVC error C2039: 'type': is not a member of 'std' // Workaround for MSVC error C2039: 'type': is not a member of 'std'
// when std::tuple_element is used. // when std::tuple_element is used.
......
...@@ -41,6 +41,7 @@ ...@@ -41,6 +41,7 @@
#include <cctype> #include <cctype>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
#include <iostream>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <string> #include <string>
#include <vector> #include <vector>
...@@ -87,7 +88,7 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) { ...@@ -87,7 +88,7 @@ GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
(!IsDigit(prev_char) && IsDigit(*p)); (!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) { if (IsAlNum(*p)) {
if (starts_new_word && result != "") result += ' '; if (starts_new_word && !result.empty()) result += ' ';
result += ToLower(*p); result += ToLower(*p);
} }
} }
......
...@@ -53,7 +53,7 @@ GTEST_API_ std::string FormatMatcherDescription( ...@@ -53,7 +53,7 @@ GTEST_API_ std::string FormatMatcherDescription(
bool negation, const char* matcher_name, bool negation, const char* matcher_name,
const std::vector<const char*>& param_names, const Strings& param_values) { const std::vector<const char*>& param_names, const Strings& param_values) {
std::string result = ConvertIdentifierNameToWords(matcher_name); std::string result = ConvertIdentifierNameToWords(matcher_name);
if (param_values.size() >= 1) { if (!param_values.empty()) {
result += " " + JoinAsKeyValueTuple(param_names, param_values); result += " " + JoinAsKeyValueTuple(param_names, param_values);
} }
return negation ? "not (" + result + ")" : result; return negation ? "not (" + result + ")" : result;
......
...@@ -40,6 +40,7 @@ ...@@ -40,6 +40,7 @@
#include <map> #include <map>
#include <memory> #include <memory>
#include <set> #include <set>
#include <sstream>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
...@@ -48,10 +49,10 @@ ...@@ -48,10 +49,10 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC #if defined(GTEST_OS_CYGWIN) || defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC)
#include <unistd.h> // NOLINT #include <unistd.h> // NOLINT
#endif #endif
#if GTEST_OS_QURT #ifdef GTEST_OS_QURT
#include <qurt_event.h> #include <qurt_event.h>
#endif #endif
...@@ -95,7 +96,7 @@ ExpectationBase::ExpectationBase(const char* a_file, int a_line, ...@@ -95,7 +96,7 @@ ExpectationBase::ExpectationBase(const char* a_file, int a_line,
action_count_checked_(false) {} action_count_checked_(false) {}
// Destructs an ExpectationBase object. // Destructs an ExpectationBase object.
ExpectationBase::~ExpectationBase() {} ExpectationBase::~ExpectationBase() = default;
// Explicitly specifies the cardinality of this expectation. Used by // Explicitly specifies the cardinality of this expectation. Used by
// the subclasses to implement the .Times() clause. // the subclasses to implement the .Times() clause.
...@@ -297,7 +298,7 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) { ...@@ -297,7 +298,7 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
"See " "See "
"https://github.com/google/googletest/blob/main/docs/" "https://github.com/google/googletest/blob/main/docs/"
"gmock_cook_book.md#" "gmock_cook_book.md#"
"knowing-when-to-expect for details.\n", "knowing-when-to-expect-useoncall for details.\n",
stack_frames_to_skip); stack_frames_to_skip);
break; break;
default: // FAIL default: // FAIL
...@@ -308,7 +309,7 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) { ...@@ -308,7 +309,7 @@ void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
UntypedFunctionMockerBase::UntypedFunctionMockerBase() UntypedFunctionMockerBase::UntypedFunctionMockerBase()
: mock_obj_(nullptr), name_("") {} : mock_obj_(nullptr), name_("") {}
UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;
// Sets the mock object this mock method belongs to, and registers // Sets the mock object this mock method belongs to, and registers
// this information in the global mock registry. Will be called // this information in the global mock registry. Will be called
...@@ -503,7 +504,7 @@ class MockObjectRegistry { ...@@ -503,7 +504,7 @@ class MockObjectRegistry {
std::cout << internal::FormatFileLocation(state.first_used_file, std::cout << internal::FormatFileLocation(state.first_used_file,
state.first_used_line); state.first_used_line);
std::cout << " ERROR: this mock object"; std::cout << " ERROR: this mock object";
if (state.first_used_test != "") { if (!state.first_used_test.empty()) {
std::cout << " (used in test " << state.first_used_test_suite << "." std::cout << " (used in test " << state.first_used_test_suite << "."
<< state.first_used_test << ")"; << state.first_used_test << ")";
} }
...@@ -526,7 +527,7 @@ class MockObjectRegistry { ...@@ -526,7 +527,7 @@ class MockObjectRegistry {
// RUN_ALL_TESTS() has already returned when this destructor is // RUN_ALL_TESTS() has already returned when this destructor is
// called. Therefore we cannot use the normal Google Test // called. Therefore we cannot use the normal Google Test
// failure reporting mechanism. // failure reporting mechanism.
#if GTEST_OS_QURT #ifdef GTEST_OS_QURT
qurt_exception_raise_fatal(); qurt_exception_raise_fatal();
#else #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
...@@ -745,13 +746,13 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj) ...@@ -745,13 +746,13 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj)
// needed by VerifyAndClearExpectationsLocked(). // needed by VerifyAndClearExpectationsLocked().
} }
Expectation::Expectation() {} Expectation::Expectation() = default;
Expectation::Expectation( Expectation::Expectation(
const std::shared_ptr<internal::ExpectationBase>& an_expectation_base) const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
: expectation_base_(an_expectation_base) {} : expectation_base_(an_expectation_base) {}
Expectation::~Expectation() {} Expectation::~Expectation() = default;
// Adds an expectation to a sequence. // Adds an expectation to a sequence.
void Sequence::AddExpectation(const Expectation& expectation) const { void Sequence::AddExpectation(const Expectation& expectation) const {
......
...@@ -29,6 +29,8 @@ ...@@ -29,6 +29,8 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include <string>
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
GMOCK_DEFINE_bool_(catch_leaked_mocks, true, GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment