Merge branch 'main' into venik-unique-ptr

This commit is contained in:
Alexander Nikforov 2022-07-01 13:17:32 -07:00
commit 9cdc144792
25 changed files with 468 additions and 444 deletions

View file

@ -12,7 +12,7 @@ if (POLICY CMP0077)
endif (POLICY CMP0077)
project(googletest-distribution)
set(GOOGLETEST_VERSION 1.11.0)
set(GOOGLETEST_VERSION 1.12.1)
if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
set(CMAKE_CXX_EXTENSIONS OFF)

View file

@ -21,8 +21,8 @@ accept your pull requests.
## Are you a Googler?
If you are a Googler, please make an attempt to submit an internal change rather
than a GitHub Pull Request. If you are not able to submit an internal change a
If you are a Googler, please make an attempt to submit an internal contribution
rather than a GitHub Pull Request. If you are not able to submit internally, a
PR is acceptable as an alternative.
## Contributing A Patch

View file

@ -15,11 +15,14 @@ Our documentation is now live on GitHub Pages at
https://google.github.io/googletest/. We recommend browsing the documentation on
GitHub Pages rather than directly in the repository.
#### Release 1.11.0
#### Release 1.12.1
[Release 1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0)
[Release 1.12.1](https://github.com/google/googletest/releases/tag/release-1.12.1)
is now available.
The 1.12.x branch will be the last to support C++11. Future releases will
require at least C++14.
#### Coming Soon
* We are planning to take a dependency on
@ -56,7 +59,7 @@ More information about building GoogleTest can be found at
## Supported Platforms
GoogleTest requires a codebase and compiler compliant with the C++11 standard or
GoogleTest requires a codebase and compiler compliant with the C++14 standard or
newer.
The GoogleTest code is officially supported on the following platforms.

View file

@ -4,25 +4,25 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "com_google_absl",
sha256 = "f88c0030547281e8283ff183db61564ff08d3322a8c2e2de4c40e38c03c69aea",
strip_prefix = "abseil-cpp-c27ab06897f330267bed99061ed3e523e2606bf1",
urls = ["https://github.com/abseil/abseil-cpp/archive/c27ab06897f330267bed99061ed3e523e2606bf1.zip"], # 2022-04-18T19:51:27Z
sha256 = "1a1745b5ee81392f5ea4371a4ca41e55d446eeaee122903b2eaffbd8a3b67a2b",
strip_prefix = "abseil-cpp-01cc6567cff77738e416a7ddc17de2d435a780ce",
urls = ["https://github.com/abseil/abseil-cpp/archive/01cc6567cff77738e416a7ddc17de2d435a780ce.zip"], # 2022-06-21T19:28:27Z
)
# Note this must use a commit from the `abseil` branch of the RE2 project.
# https://github.com/google/re2/tree/abseil
http_archive(
name = "com_googlesource_code_re2",
sha256 = "906d0df8ff48f8d3a00a808827f009a840190f404559f649cb8e4d7143255ef9",
strip_prefix = "re2-a276a8c738735a0fe45a6ee590fe2df69bcf4502",
urls = ["https://github.com/google/re2/archive/a276a8c738735a0fe45a6ee590fe2df69bcf4502.zip"], # 2022-04-08
sha256 = "0a890c2aa0bb05b2ce906a15efb520d0f5ad4c7d37b8db959c43772802991887",
strip_prefix = "re2-a427f10b9fb4622dd6d8643032600aa1b50fbd12",
urls = ["https://github.com/google/re2/archive/a427f10b9fb4622dd6d8643032600aa1b50fbd12.zip"], # 2022-06-09
)
http_archive(
name = "rules_python",
sha256 = "98b3c592faea9636ac8444bfd9de7f3fb4c60590932d6e6ac5946e3f8dbd5ff6",
strip_prefix = "rules_python-ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2",
urls = ["https://github.com/bazelbuild/rules_python/archive/ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2.zip"], # 2021-05-17T00:24:16Z
sha256 = "0b460f17771258341528753b1679335b629d1d25e3af28eda47d009c103a6e15",
strip_prefix = "rules_python-aef17ad72919d184e5edb7abf61509eb78e57eda",
urls = ["https://github.com/bazelbuild/rules_python/archive/aef17ad72919d184e5edb7abf61509eb78e57eda.zip"], # 2022-06-21T23:44:47Z
)
http_archive(
@ -33,7 +33,7 @@ http_archive(
http_archive(
name = "platforms",
sha256 = "b601beaf841244de5c5a50d2b2eddd34839788000fa1be4260ce6603ca0d8eb7",
strip_prefix = "platforms-98939346da932eef0b54cf808622f5bb0928f00b",
urls = ["https://github.com/bazelbuild/platforms/archive/98939346da932eef0b54cf808622f5bb0928f00b.zip"],
sha256 = "a879ea428c6d56ab0ec18224f976515948822451473a80d06c2e50af0bbe5121",
strip_prefix = "platforms-da5541f26b7de1dc8e04c075c99df5351742a4a2",
urls = ["https://github.com/bazelbuild/platforms/archive/da5541f26b7de1dc8e04c075c99df5351742a4a2.zip"], # 2022-05-27
)

View file

@ -32,14 +32,14 @@
set -euox pipefail
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20220217"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20210617"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20220621"
if [[ -z ${GTEST_ROOT:-} ]]; then
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
fi
if [[ -z ${STD:-} ]]; then
STD="c++11 c++14 c++17 c++20"
STD="c++14 c++17 c++20"
fi
# Test the CMake build
@ -55,7 +55,7 @@ for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
${LINUX_LATEST_CONTAINER} \
/bin/bash -c "
cmake /src \
-DCMAKE_CXX_STANDARD=11 \
-DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
@ -72,12 +72,14 @@ time docker run \
--workdir="/src" \
--rm \
--env="CC=/usr/local/bin/gcc" \
--env="BAZEL_CXXOPTS=-std=c++14" \
${LINUX_GCC_FLOOR_CONTAINER} \
/usr/local/bin/bazel test ... \
--copt="-Wall" \
--copt="-Werror" \
--copt="-Wuninitialized" \
--copt="-Wno-error=pragmas" \
--distdir="/bazel-distdir" \
--keep_going \
--show_timestamps \
--test_output=errors

View file

@ -40,7 +40,7 @@ for cmake_off_on in OFF ON; do
BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)
cd ${BUILD_DIR}
time cmake ${GTEST_ROOT} \
-DCMAKE_CXX_STANDARD=11 \
-DCMAKE_CXX_STANDARD=14 \
-Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \
@ -53,7 +53,7 @@ done
# Test the Bazel build
# If we are running on Kokoro, check for a versioned Bazel binary.
KOKORO_GFILE_BAZEL_BIN="bazel-3.7.0-darwin-x86_64"
KOKORO_GFILE_BAZEL_BIN="bazel-5.1.1-darwin-x86_64"
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then
BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}"
chmod +x ${BAZEL_BIN}
@ -66,6 +66,7 @@ for absl in 0 1; do
${BAZEL_BIN} test ... \
--copt="-Wall" \
--copt="-Werror" \
--cxxopt="-std=c++14" \
--define="absl=${absl}" \
--keep_going \
--show_timestamps \

View file

@ -482,9 +482,11 @@ TEST_F(FooDeathTest, DoesThat) {
### Regular Expression Syntax
On POSIX systems (e.g. Linux, Cygwin, and Mac), 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
systems (Linux, Cygwin, Mac), googletest uses the
[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)
syntax. To learn about this 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_Regular_Expressions).
On Windows, googletest uses its own simple regular expression implementation. It
@ -1313,6 +1315,7 @@ First, define a fixture class template, as we did with typed tests:
```c++
template <typename T>
class FooTest : public testing::Test {
void DoSomethingInteresting();
...
};
```
@ -1330,6 +1333,9 @@ this as many times as you want:
TYPED_TEST_P(FooTest, DoesBlah) {
// Inside a test, refer to TypeParam to get the type parameter.
TypeParam n = 0;
// You will need to use `this` explicitly to refer to fixture members.
this->DoSomethingInteresting()
...
}

View file

@ -1,9 +1,9 @@
# Googletest FAQ
# GoogleTest FAQ
## Why should test suite names and test names not contain underscore?
{: .callout .note}
Note: Googletest reserves underscore (`_`) for special purpose keywords, such as
Note: GoogleTest reserves underscore (`_`) for special purpose keywords, such as
[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition
to the following rationale.
@ -50,15 +50,15 @@ Now, the two `TEST`s will both generate the same class
So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and
`TestName`. The rule is more constraining than necessary, but it's simple and
easy to remember. It also gives googletest some wiggle room in case its
easy to remember. It also gives GoogleTest some wiggle room in case its
implementation needs to change in the future.
If you violate the rule, there may not be immediate consequences, but your test
may (just may) break with a new compiler (or a new version of the compiler you
are using) or with a new version of googletest. Therefore it's best to follow
are using) or with a new version of GoogleTest. Therefore it's best to follow
the rule.
## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
First of all, you can use `nullptr` with each of these macros, e.g.
`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`,
@ -68,7 +68,7 @@ because `nullptr` does not have the type problems that `NULL` does.
Due to some peculiarity of C++, it requires some non-trivial template meta
programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
and `ASSERT_XX()` macros. Therefore we only do it where it's most needed
(otherwise we make the implementation of googletest harder to maintain and more
(otherwise we make the implementation of GoogleTest harder to maintain and more
error-prone than necessary).
Historically, the `EXPECT_EQ()` macro took the *expected* value as its first
@ -162,7 +162,7 @@ methods, the parent process will think the calls have never occurred. Therefore,
you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH`
macro.
## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug?
Actually, the bug is in `htonl()`.
@ -199,7 +199,7 @@ const int Foo::kBar; // No initializer here.
```
Otherwise your code is **invalid C++**, and may break in unexpected ways. In
particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will
generate an "undefined reference" linker error. The fact that "it used to work"
doesn't mean it's valid. It just means that you were lucky. :-)
@ -225,7 +225,7 @@ cases may want to use the same or slightly different fixtures. For example, you
may want to make sure that all of a GUI library's test suites don't leak
important system resources like fonts and brushes.
In googletest, you share a fixture among test suites by putting the shared logic
In GoogleTest, you share a fixture among test suites by putting the shared logic
in a base test fixture, then deriving from that base a separate fixture for each
test suite that wants to use this common logic. You then use `TEST_F()` to write
tests using each derived fixture.
@ -264,7 +264,7 @@ TEST_F(FooTest, Baz) { ... }
```
If necessary, you can continue to derive test fixtures from a derived fixture.
googletest has no limit on how deep the hierarchy can be.
GoogleTest has no limit on how deep the hierarchy can be.
For a complete example using derived test fixtures, see
[sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc).
@ -278,7 +278,7 @@ disabled by our build system. Please see more details
## My death test hangs (or seg-faults). How do I fix it?
In googletest, death tests are run in a child process and the way they work is
In GoogleTest, death tests are run in a child process and the way they work is
delicate. To write death tests you really need to understand how they work—see
the details at [Death Assertions](reference/assertions.md#death) in the
Assertions Reference.
@ -305,8 +305,8 @@ bullet - sorry!
## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
The first thing to remember is that googletest does **not** reuse the same test
fixture object across multiple tests. For each `TEST_F`, googletest will create
The first thing to remember is that GoogleTest does **not** reuse the same test
fixture object across multiple tests. For each `TEST_F`, GoogleTest will create
a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
call `TearDown()`, and then delete the test fixture object.
@ -345,11 +345,11 @@ You may still want to use `SetUp()/TearDown()` in the following cases:
that many standard libraries (like STL) may throw when exceptions are
enabled in the compiler. Therefore you should prefer `TearDown()` if you
want to write portable tests that work with or without exceptions.
* The googletest team is considering making the assertion macros throw on
* The GoogleTest team is considering making the assertion macros throw on
platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
client-side), which will eliminate the need for the user to propagate
failures from a subroutine to its caller. Therefore, you shouldn't use
googletest assertions in a destructor if your code could run on such a
GoogleTest assertions in a destructor if your code could run on such a
platform.
## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
@ -375,7 +375,7 @@ they write
This is **wrong and dangerous**. The testing services needs to see the return
value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
`main()` function ignores it, your test will be considered successful even if it
has a googletest assertion failure. Very bad.
has a GoogleTest assertion failure. Very bad.
We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
@ -440,14 +440,14 @@ TEST_F(BarTest, Abc) { ... }
TEST_F(BarTest, Def) { ... }
```
## googletest output is buried in a whole bunch of LOG messages. What do I do?
## GoogleTest output is buried in a whole bunch of LOG messages. What do I do?
The googletest output is meant to be a concise and human-friendly report. If
your test generates textual output itself, it will mix with the googletest
The GoogleTest output is meant to be a concise and human-friendly report. If
your test generates textual output itself, it will mix with the GoogleTest
output, making it hard to read. However, there is an easy solution to this
problem.
Since `LOG` messages go to stderr, we decided to let googletest output go to
Since `LOG` messages go to stderr, we decided to let GoogleTest output go to
stdout. This way, you can easily separate the two using redirection. For
example:
@ -520,7 +520,7 @@ TEST(MyDeathTest, CompoundStatement) {
## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
Googletest needs to be able to create objects of your test fixture class, so it
GoogleTest needs to be able to create objects of your test fixture class, so it
must have a default constructor. Normally the compiler will define one for you.
However, there are cases where you have to define your own:
@ -545,11 +545,11 @@ The new NPTL thread library doesn't suffer from this problem, as it doesn't
create a manager thread. However, if you don't control which machine your test
runs on, you shouldn't depend on this.
## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
## Why does GoogleTest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
googletest does not interleave tests from different test suites. That is, it
GoogleTest does not interleave tests from different test suites. That is, it
runs all tests in one test suite first, and then runs all tests in the next test
suite, and so on. googletest does this because it needs to set up a test suite
suite, and so on. GoogleTest does this because it needs to set up a test suite
before the first test in it is run, and tear it down afterwards. Splitting up
the test case would require multiple set-up and tear-down processes, which is
inefficient and makes the semantics unclean.
@ -588,11 +588,11 @@ TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
```
## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
makes it harder to search for real problems in the parent's log. Therefore,
googletest only prints them when the death test has failed.
GoogleTest only prints them when the death test has failed.
If you really need to see such LOG messages, a workaround is to temporarily
break the death test (e.g. by changing the regex pattern it is expected to
@ -611,7 +611,7 @@ needs to be defined in the *same* name space. See
## How do I suppress the memory leak messages on Windows?
Since the statically initialized googletest singleton requires allocations on
Since the statically initialized GoogleTest singleton requires allocations on
the heap, the Visual C++ memory leak detector will report memory leaks at the
end of the program run. The easiest way to avoid this is to use the
`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
@ -625,7 +625,7 @@ things accordingly, you are leaking test-only logic into production code and
there is no easy way to ensure that the test-only code paths aren't run by
mistake in production. Such cleverness also leads to
[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
advise against the practice, and googletest doesn't provide a way to do it.
advise against the practice, and GoogleTest doesn't provide a way to do it.
In general, the recommended way to cause the code to behave differently under
test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject
@ -672,7 +672,7 @@ TEST(CoolTest, DoSomething) {
```
However, the following code is **not allowed** and will produce a runtime error
from googletest because the test methods are using different test fixture
from GoogleTest because the test methods are using different test fixture
classes with the same test suite name.
```c++

View file

@ -392,8 +392,7 @@ Old macros and their new equivalents:
If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an
"uninteresting call", and the default action (which can be specified using
`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will
also by default cause gMock to print a warning. (In the future, we might remove
this warning by default.)
also by default cause gMock to print a warning.
However, sometimes you may want to ignore these uninteresting calls, and
sometimes you may want to treat them as errors. gMock lets you make the decision

View file

@ -9,7 +9,7 @@ we recommend this tutorial as a starting point.
To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++11.
* A compatible C++ compiler that supports at least C++14.
* [Bazel](https://bazel.build/), the preferred build system used by the
GoogleTest team.

View file

@ -10,7 +10,7 @@ this tutorial as a starting point. If your project uses Bazel, see the
To complete this tutorial, you'll need:
* A compatible operating system (e.g. Linux, macOS, Windows).
* A compatible C++ compiler that supports at least C++11.
* A compatible C++ compiler that supports at least C++14.
* [CMake](https://cmake.org/) and a compatible build tool for building the
project.
* Compatible build tools include
@ -52,8 +52,8 @@ To do this, in your project directory (`my_project`), create a file named
cmake_minimum_required(VERSION 3.14)
project(my_project)
# GoogleTest requires at least C++11
set(CMAKE_CXX_STANDARD 11)
# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)
include(FetchContent)
FetchContent_Declare(

View file

@ -8,9 +8,13 @@ A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. |
| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. |
{: .callout .note}
**Note:** Although equality matching via `EXPECT_THAT(actual_value,
expected_value)` is supported, prefer to make the comparison explicit via
{: .callout .warning}
**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)`
is supported, however note that implicit conversions can cause surprising
results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and
may pass unintentionally.
**BEST PRACTICE:** Prefer to make the comparison explicit via
`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value,
expected_value)`.

View file

@ -298,6 +298,53 @@ struct disjunction<P1, Ps...>
template <typename...>
using void_t = void;
// Detects whether an expression of type `From` can be implicitly converted to
// `To` according to [conv]. In C++17, [conv]/3 defines this as follows:
//
// An expression e can be implicitly converted to a type T if and only if
// the declaration T t=e; is well-formed, for some invented temporary
// variable t ([dcl.init]).
//
// [conv]/2 implies we can use function argument passing to detect whether this
// initialization is valid.
//
// Note that this is distinct from is_convertible, which requires this be valid:
//
// To test() {
// return declval<From>();
// }
//
// In particular, is_convertible doesn't give the correct answer when `To` and
// `From` are the same non-moveable type since `declval<From>` will be an rvalue
// reference, defeating the guaranteed copy elision that would otherwise make
// this function work.
//
// REQUIRES: `From` is not cv void.
template <typename From, typename To>
struct is_implicitly_convertible {
private:
// A function that accepts a parameter of type T. This can be called with type
// U successfully only if U is implicitly convertible to T.
template <typename T>
static void Accept(T);
// A function that creates a value of type T.
template <typename T>
static T Make();
// An overload be selected when implicit conversion from T to To is possible.
template <typename T, typename = decltype(Accept<To>(Make<T>()))>
static std::true_type TestImplicitConversion(int);
// A fallback overload selected in all other cases.
template <typename T>
static std::false_type TestImplicitConversion(...);
public:
using type = decltype(TestImplicitConversion<From>(0));
static constexpr bool value = type::value;
};
// Like std::invoke_result_t from C++17, but works only for objects with call
// operators (not e.g. member function pointers, which we don't need specific
// support for in OnceAction because std::function deals with them).
@ -313,9 +360,9 @@ struct is_callable_r_impl : std::false_type {};
template <typename R, typename F, typename... Args>
struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...>
: std::conditional<
std::is_same<R, void>::value, //
std::true_type, //
std::is_convertible<call_result_t<F, Args...>, R>>::type {};
std::is_void<R>::value, //
std::true_type, //
is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {};
// Like std::is_invocable_r from C++17, but works only for objects with call
// operators. See the note on call_result_t.

View file

@ -3235,6 +3235,11 @@ auto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
}
template <typename T>
auto UnpackStructImpl(const T& t, MakeIndexSequence<17>, char) {
const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q] = t;
return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q);
}
#endif // defined(__cpp_structured_bindings)
template <size_t I, typename T>

View file

@ -63,6 +63,7 @@
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_
#include <cstdint>
#include <type_traits>
#include "gmock/gmock-spec-builders.h"
@ -109,25 +110,37 @@ constexpr bool HasStrictnessModifier() {
template <typename Base>
class NiceMockImpl {
public:
NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(this); }
NiceMockImpl() {
::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this));
}
~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
~NiceMockImpl() {
::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
}
};
template <typename Base>
class NaggyMockImpl {
public:
NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(this); }
NaggyMockImpl() {
::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this));
}
~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
~NaggyMockImpl() {
::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
}
};
template <typename Base>
class StrictMockImpl {
public:
StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(this); }
StrictMockImpl() {
::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this));
}
~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(this); }
~StrictMockImpl() {
::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));
}
};
} // namespace internal

View file

@ -61,6 +61,7 @@
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
@ -132,9 +133,6 @@ class NaggyMockImpl;
// calls to ensure the integrity of the mock objects' states.
GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
// Untyped base class for ActionResultHolder<R>.
class UntypedActionResultHolderBase;
// Abstract base class of FunctionMocker. This is the
// type-agnostic part of the function mocker interface. Its pure
// virtual methods are implemented by FunctionMocker.
@ -157,20 +155,6 @@ class GTEST_API_ UntypedFunctionMockerBase {
// responsibility to guarantee the correctness of the arguments'
// types.
// Performs the default action with the given arguments and returns
// the action's result. The call description string will be used in
// the error message to describe the call in the case the default
// action fails.
// L = *
virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
void* untyped_args, const std::string& call_description) const = 0;
// Performs the given action with the given arguments and returns
// the action's result.
// L = *
virtual UntypedActionResultHolderBase* UntypedPerformAction(
const void* untyped_action, void* untyped_args) const = 0;
// Writes a message that the call is uninteresting (i.e. neither
// explicitly expected nor explicitly unexpected) to the given
// ostream.
@ -214,13 +198,6 @@ class GTEST_API_ UntypedFunctionMockerBase {
// SetOwnerAndName() has been called.
const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
// Returns the result of invoking this mock function with the given
// arguments. This function can be safely called from multiple
// threads concurrently. The caller is responsible for deleting the
// result.
UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
protected:
typedef std::vector<const void*> UntypedOnCallSpecs;
@ -428,22 +405,22 @@ class GTEST_API_ Mock {
// Tells Google Mock to allow uninteresting calls on the given mock
// object.
static void AllowUninterestingCalls(const void* mock_obj)
static void AllowUninterestingCalls(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Tells Google Mock to warn the user about uninteresting calls on
// the given mock object.
static void WarnUninterestingCalls(const void* mock_obj)
static void WarnUninterestingCalls(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Tells Google Mock to fail uninteresting calls on the given mock
// object.
static void FailUninterestingCalls(const void* mock_obj)
static void FailUninterestingCalls(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Tells Google Mock the given mock object is being destroyed and
// its entry in the call-reaction table should be removed.
static void UnregisterCallReaction(const void* mock_obj)
static void UnregisterCallReaction(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
// Returns the reaction Google Mock will have on uninteresting calls
@ -1368,99 +1345,27 @@ class ReferenceOrValueWrapper<T&> {
T* value_ptr_;
};
// C++ treats the void type specially. For example, you cannot define
// a void-typed variable or pass a void value to a function.
// ActionResultHolder<T> holds a value of type T, where T must be a
// copyable type or void (T doesn't need to be default-constructable).
// It hides the syntactic difference between void and other types, and
// is used to unify the code for invoking both void-returning and
// non-void-returning mock functions.
// Untyped base class for ActionResultHolder<T>.
class UntypedActionResultHolderBase {
public:
virtual ~UntypedActionResultHolderBase() {}
// Prints the held value as an action's result to os.
virtual void PrintAsActionResult(::std::ostream* os) const = 0;
};
// This generic definition is used when T is not void.
// Prints the held value as an action's result to os.
template <typename T>
class ActionResultHolder : public UntypedActionResultHolderBase {
void PrintAsActionResult(const T& result, std::ostream& os) {
os << "\n Returns: ";
// T may be a reference type, so we don't use UniversalPrint().
UniversalPrinter<T>::Print(result, &os);
}
// Reports an uninteresting call (whose description is in msg) in the
// manner specified by 'reaction'.
GTEST_API_ void ReportUninterestingCall(CallReaction reaction,
const std::string& msg);
// A generic RAII type that runs a user-provided function in its destructor.
class Cleanup final {
public:
// Returns the held value. Must not be called more than once.
T Unwrap() { return result_.Unwrap(); }
// Prints the held value as an action's result to os.
void PrintAsActionResult(::std::ostream* os) const override {
*os << "\n Returns: ";
// T may be a reference type, so we don't use UniversalPrint().
UniversalPrinter<T>::Print(result_.Peek(), os);
}
// Performs the given mock function's default action and returns the
// result in a new-ed ActionResultHolder.
template <typename F>
static ActionResultHolder* PerformDefaultAction(
const FunctionMocker<F>* func_mocker,
typename Function<F>::ArgumentTuple&& args,
const std::string& call_description) {
return new ActionResultHolder(Wrapper(
func_mocker->PerformDefaultAction(std::move(args), call_description)));
}
// Performs the given action and returns the result in a new-ed
// ActionResultHolder.
template <typename F>
static ActionResultHolder* PerformAction(
const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
return new ActionResultHolder(Wrapper(action.Perform(std::move(args))));
}
explicit Cleanup(std::function<void()> f) : f_(std::move(f)) {}
~Cleanup() { f_(); }
private:
typedef ReferenceOrValueWrapper<T> Wrapper;
explicit ActionResultHolder(Wrapper result) : result_(std::move(result)) {}
Wrapper result_;
ActionResultHolder(const ActionResultHolder&) = delete;
ActionResultHolder& operator=(const ActionResultHolder&) = delete;
};
// Specialization for T = void.
template <>
class ActionResultHolder<void> : public UntypedActionResultHolderBase {
public:
void Unwrap() {}
void PrintAsActionResult(::std::ostream* /* os */) const override {}
// Performs the given mock function's default action and returns ownership
// of an empty ActionResultHolder*.
template <typename F>
static ActionResultHolder* PerformDefaultAction(
const FunctionMocker<F>* func_mocker,
typename Function<F>::ArgumentTuple&& args,
const std::string& call_description) {
func_mocker->PerformDefaultAction(std::move(args), call_description);
return new ActionResultHolder;
}
// Performs the given action and returns ownership of an empty
// ActionResultHolder*.
template <typename F>
static ActionResultHolder* PerformAction(
const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
action.Perform(std::move(args));
return new ActionResultHolder;
}
private:
ActionResultHolder() {}
ActionResultHolder(const ActionResultHolder&) = delete;
ActionResultHolder& operator=(const ActionResultHolder&) = delete;
std::function<void()> f_;
};
template <typename F>
@ -1543,32 +1448,6 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
return DefaultValue<Result>::Get();
}
// Performs the default action with the given arguments and returns
// the action's result. The call description string will be used in
// the error message to describe the call in the case the default
// action fails. The caller is responsible for deleting the result.
// L = *
UntypedActionResultHolderBase* UntypedPerformDefaultAction(
void* untyped_args, // must point to an ArgumentTuple
const std::string& call_description) const override {
ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
return ResultHolder::PerformDefaultAction(this, std::move(*args),
call_description);
}
// Performs the given action with the given arguments and returns
// the action's result. The caller is responsible for deleting the
// result.
// L = *
UntypedActionResultHolderBase* UntypedPerformAction(
const void* untyped_action, void* untyped_args) const override {
// Make a copy of the action before performing it, in case the
// action deletes the mock object (and thus deletes itself).
const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
return ResultHolder::PerformAction(action, std::move(*args));
}
// Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
// clears the ON_CALL()s set on this mock function.
void ClearDefaultActionsLocked() override
@ -1600,10 +1479,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
// arguments. This function can be safely called from multiple
// threads concurrently.
Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
ArgumentTuple tuple(std::forward<Args>(args)...);
std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
this->UntypedInvokeWith(static_cast<void*>(&tuple))));
return holder->Unwrap();
return InvokeWith(ArgumentTuple(std::forward<Args>(args)...));
}
MockSpec<F> With(Matcher<Args>... m) {
@ -1614,8 +1490,6 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
template <typename Function>
friend class MockSpec;
typedef ActionResultHolder<Result> ResultHolder;
// Adds and returns a default action spec for this mock function.
OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,
const ArgumentMatcherTuple& m)
@ -1786,11 +1660,177 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
expectation->DescribeCallCountTo(why);
}
}
// Performs the given action (or the default if it's null) with the given
// arguments and returns the action's result.
// L = *
R PerformAction(const void* untyped_action, ArgumentTuple&& args,
const std::string& call_description) const {
if (untyped_action == nullptr) {
return PerformDefaultAction(std::move(args), call_description);
}
// Make a copy of the action before performing it, in case the
// action deletes the mock object (and thus deletes itself).
const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
return action.Perform(std::move(args));
}
// Is it possible to store an object of the supplied type in a local variable
// for the sake of printing it, then return it on to the caller?
template <typename T>
using can_print_result = internal::conjunction<
// void can't be stored as an object (and we also don't need to print it).
internal::negation<std::is_void<T>>,
// Non-moveable types can't be returned on to the user, so there's no way
// for us to intercept and print them.
std::is_move_constructible<T>>;
// Perform the supplied action, printing the result to os.
template <typename T = R,
typename std::enable_if<can_print_result<T>::value, int>::type = 0>
R PerformActionAndPrintResult(const void* const untyped_action,
ArgumentTuple&& args,
const std::string& call_description,
std::ostream& os) {
R result = PerformAction(untyped_action, std::move(args), call_description);
PrintAsActionResult(result, os);
return std::forward<R>(result);
}
// An overload for when it's not possible to print the result. In this case we
// simply perform the action.
template <typename T = R,
typename std::enable_if<
internal::negation<can_print_result<T>>::value, int>::type = 0>
R PerformActionAndPrintResult(const void* const untyped_action,
ArgumentTuple&& args,
const std::string& call_description,
std::ostream&) {
return PerformAction(untyped_action, std::move(args), call_description);
}
// Returns the result of invoking this mock function with the given
// arguments. This function can be safely called from multiple
// threads concurrently.
R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
}; // class FunctionMocker
// Reports an uninteresting call (whose description is in msg) in the
// manner specified by 'reaction'.
void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
// Calculates the result of invoking this mock function with the given
// arguments, prints it, and returns it.
template <typename R, typename... Args>
R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
// See the definition of untyped_expectations_ for why access to it
// is unprotected here.
if (untyped_expectations_.size() == 0) {
// No expectation is set on this mock method - we have an
// uninteresting call.
// We must get Google Mock's reaction on uninteresting calls
// made on this mock object BEFORE performing the action,
// because the action may DELETE the mock object and make the
// following expression meaningless.
const CallReaction reaction =
Mock::GetReactionOnUninterestingCalls(MockObject());
// True if and only if we need to print this call's arguments and return
// value. This definition must be kept in sync with
// the behavior of ReportUninterestingCall().
const bool need_to_report_uninteresting_call =
// If the user allows this uninteresting call, we print it
// only when they want informational messages.
reaction == kAllow ? LogIsVisible(kInfo) :
// If the user wants this to be a warning, we print
// it only when they want to see warnings.
reaction == kWarn
? LogIsVisible(kWarning)
:
// Otherwise, the user wants this to be an error, and we
// should always print detailed information in the error.
true;
if (!need_to_report_uninteresting_call) {
// Perform the action without printing the call information.
return this->PerformDefaultAction(
std::move(args), "Function call: " + std::string(Name()));
}
// Warns about the uninteresting call.
::std::stringstream ss;
this->UntypedDescribeUninterestingCall(&args, &ss);
// Perform the action, print the result, and then report the uninteresting
// call.
//
// 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.
const Cleanup report_uninteresting_call(
[&] { ReportUninterestingCall(reaction, ss.str()); });
return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
}
bool is_excessive = false;
::std::stringstream ss;
::std::stringstream why;
::std::stringstream loc;
const void* untyped_action = nullptr;
// The UntypedFindMatchingExpectation() function acquires and
// releases g_gmock_mutex.
const ExpectationBase* const untyped_expectation =
this->UntypedFindMatchingExpectation(&args, &untyped_action,
&is_excessive, &ss, &why);
const bool found = untyped_expectation != nullptr;
// True if and only if we need to print the call's arguments
// and return value.
// This definition must be kept in sync with the uses of Expect()
// and Log() in this function.
const bool need_to_report_call =
!found || is_excessive || LogIsVisible(kInfo);
if (!need_to_report_call) {
// Perform the action without printing the call information.
return PerformAction(untyped_action, std::move(args), "");
}
ss << " Function call: " << Name();
this->UntypedPrintArgs(&args, &ss);
// In case the action deletes a piece of the expectation, we
// generate the message beforehand.
if (found && !is_excessive) {
untyped_expectation->DescribeLocationTo(&loc);
}
// Perform the action, print the result, and then fail or log in whatever way
// is appropriate.
//
// 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.
const Cleanup handle_failures([&] {
ss << "\n" << why.str();
if (!found) {
// No expectation matches this call - reports a failure.
Expect(false, nullptr, -1, ss.str());
} else if (is_excessive) {
// We had an upper-bound violation and the failure message is in ss.
Expect(false, untyped_expectation->file(), untyped_expectation->line(),
ss.str());
} else {
// We had an expected call and the matching expectation is
// described in ss.
Log(kInfo, loc.str() + ss.str(), 2);
}
});
return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
ss);
}
} // namespace internal

View file

@ -41,6 +41,7 @@
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "gmock/gmock.h"
@ -369,136 +370,6 @@ const char* UntypedFunctionMockerBase::Name() const
return name;
}
// Calculates the result of invoking this mock function with the given
// arguments, prints it, and returns it. The caller is responsible
// for deleting the result.
UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
// See the definition of untyped_expectations_ for why access to it
// is unprotected here.
if (untyped_expectations_.size() == 0) {
// No expectation is set on this mock method - we have an
// uninteresting call.
// We must get Google Mock's reaction on uninteresting calls
// made on this mock object BEFORE performing the action,
// because the action may DELETE the mock object and make the
// following expression meaningless.
const CallReaction reaction =
Mock::GetReactionOnUninterestingCalls(MockObject());
// True if and only if we need to print this call's arguments and return
// value. This definition must be kept in sync with
// the behavior of ReportUninterestingCall().
const bool need_to_report_uninteresting_call =
// If the user allows this uninteresting call, we print it
// only when they want informational messages.
reaction == kAllow ? LogIsVisible(kInfo) :
// If the user wants this to be a warning, we print
// it only when they want to see warnings.
reaction == kWarn
? LogIsVisible(kWarning)
:
// Otherwise, the user wants this to be an error, and we
// should always print detailed information in the error.
true;
if (!need_to_report_uninteresting_call) {
// Perform the action without printing the call information.
return this->UntypedPerformDefaultAction(
untyped_args, "Function call: " + std::string(Name()));
}
// Warns about the uninteresting call.
::std::stringstream ss;
this->UntypedDescribeUninterestingCall(untyped_args, &ss);
// Calculates the function result.
UntypedActionResultHolderBase* const result =
this->UntypedPerformDefaultAction(untyped_args, ss.str());
// Prints the function result.
if (result != nullptr) result->PrintAsActionResult(&ss);
ReportUninterestingCall(reaction, ss.str());
return result;
}
bool is_excessive = false;
::std::stringstream ss;
::std::stringstream why;
::std::stringstream loc;
const void* untyped_action = nullptr;
// The UntypedFindMatchingExpectation() function acquires and
// releases g_gmock_mutex.
const ExpectationBase* const untyped_expectation =
this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
&is_excessive, &ss, &why);
const bool found = untyped_expectation != nullptr;
// True if and only if we need to print the call's arguments
// and return value.
// This definition must be kept in sync with the uses of Expect()
// and Log() in this function.
const bool need_to_report_call =
!found || is_excessive || LogIsVisible(kInfo);
if (!need_to_report_call) {
// Perform the action without printing the call information.
return untyped_action == nullptr
? this->UntypedPerformDefaultAction(untyped_args, "")
: this->UntypedPerformAction(untyped_action, untyped_args);
}
ss << " Function call: " << Name();
this->UntypedPrintArgs(untyped_args, &ss);
// In case the action deletes a piece of the expectation, we
// generate the message beforehand.
if (found && !is_excessive) {
untyped_expectation->DescribeLocationTo(&loc);
}
UntypedActionResultHolderBase* result = nullptr;
auto perform_action = [&] {
return untyped_action == nullptr
? this->UntypedPerformDefaultAction(untyped_args, ss.str())
: this->UntypedPerformAction(untyped_action, untyped_args);
};
auto handle_failures = [&] {
ss << "\n" << why.str();
if (!found) {
// No expectation matches this call - reports a failure.
Expect(false, nullptr, -1, ss.str());
} else if (is_excessive) {
// We had an upper-bound violation and the failure message is in ss.
Expect(false, untyped_expectation->file(), untyped_expectation->line(),
ss.str());
} else {
// We had an expected call and the matching expectation is
// described in ss.
Log(kInfo, loc.str() + ss.str(), 2);
}
};
#if GTEST_HAS_EXCEPTIONS
try {
result = perform_action();
} catch (...) {
handle_failures();
throw;
}
#else
result = perform_action();
#endif
if (result != nullptr) result->PrintAsActionResult(&ss);
handle_failures();
return result;
}
// Returns an Expectation object that references and co-owns exp,
// which must be an expectation on this mock function.
Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
@ -564,7 +435,7 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
return expectations_met;
}
CallReaction intToCallReaction(int mock_behavior) {
static CallReaction intToCallReaction(int mock_behavior) {
if (mock_behavior >= kAllow && mock_behavior <= kFail) {
return static_cast<internal::CallReaction>(mock_behavior);
}
@ -664,46 +535,50 @@ MockObjectRegistry g_mock_object_registry;
// Maps a mock object to the reaction Google Mock should have when an
// uninteresting method is called. Protected by g_gmock_mutex.
std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
std::unordered_map<uintptr_t, internal::CallReaction>&
UninterestingCallReactionMap() {
static auto* map = new std::unordered_map<uintptr_t, internal::CallReaction>;
return *map;
}
// Sets the reaction Google Mock should have when an uninteresting
// method of the given mock object is called.
void SetReactionOnUninterestingCalls(const void* mock_obj,
void SetReactionOnUninterestingCalls(uintptr_t mock_obj,
internal::CallReaction reaction)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex);
g_uninteresting_call_reaction[mock_obj] = reaction;
UninterestingCallReactionMap()[mock_obj] = reaction;
}
} // namespace
// Tells Google Mock to allow uninteresting calls on the given mock
// object.
void Mock::AllowUninterestingCalls(const void* mock_obj)
void Mock::AllowUninterestingCalls(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
}
// Tells Google Mock to warn the user about uninteresting calls on the
// given mock object.
void Mock::WarnUninterestingCalls(const void* mock_obj)
void Mock::WarnUninterestingCalls(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
}
// Tells Google Mock to fail uninteresting calls on the given mock
// object.
void Mock::FailUninterestingCalls(const void* mock_obj)
void Mock::FailUninterestingCalls(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
}
// Tells Google Mock the given mock object is being destroyed and its
// entry in the call-reaction table should be removed.
void Mock::UnregisterCallReaction(const void* mock_obj)
void Mock::UnregisterCallReaction(uintptr_t mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex);
g_uninteresting_call_reaction.erase(mock_obj);
UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj));
}
// Returns the reaction Google Mock will have on uninteresting calls
@ -711,10 +586,12 @@ void Mock::UnregisterCallReaction(const void* mock_obj)
internal::CallReaction Mock::GetReactionOnUninterestingCalls(
const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
internal::MutexLock l(&internal::g_gmock_mutex);
return (g_uninteresting_call_reaction.count(mock_obj) == 0)
return (UninterestingCallReactionMap().count(
reinterpret_cast<uintptr_t>(mock_obj)) == 0)
? internal::intToCallReaction(
GMOCK_FLAG_GET(default_mock_behavior))
: g_uninteresting_call_reaction[mock_obj];
: UninterestingCallReactionMap()[reinterpret_cast<uintptr_t>(
mock_obj)];
}
// Tells Google Mock to ignore mock_obj when checking for leaked mock

View file

@ -192,13 +192,15 @@ TEST(TypeTraits, IsInvocableRV) {
};
// The first overload is callable for const and non-const rvalues and lvalues.
// It can be used to obtain an int, void, or anything int is convertible too.
// It can be used to obtain an int, cv void, or anything int is convertible
// to.
static_assert(internal::is_callable_r<int, C>::value, "");
static_assert(internal::is_callable_r<int, C&>::value, "");
static_assert(internal::is_callable_r<int, const C>::value, "");
static_assert(internal::is_callable_r<int, const C&>::value, "");
static_assert(internal::is_callable_r<void, C>::value, "");
static_assert(internal::is_callable_r<const volatile void, C>::value, "");
static_assert(internal::is_callable_r<char, C>::value, "");
// It's possible to provide an int. If it's given to an lvalue, the result is
@ -217,6 +219,32 @@ TEST(TypeTraits, IsInvocableRV) {
static_assert(!internal::is_callable_r<void, C, std::string>::value, "");
static_assert(!internal::is_callable_r<void, C, int, int>::value, "");
// In C++17 and above, where it's guaranteed that functions can return
// non-moveable objects, everything should work fine for non-moveable rsult
// types too.
#if defined(__cplusplus) && __cplusplus >= 201703L
{
struct NonMoveable {
NonMoveable() = default;
NonMoveable(NonMoveable&&) = delete;
};
static_assert(!std::is_move_constructible_v<NonMoveable>);
struct Callable {
NonMoveable operator()() { return NonMoveable(); }
};
static_assert(internal::is_callable_r<NonMoveable, Callable>::value);
static_assert(internal::is_callable_r<void, Callable>::value);
static_assert(
internal::is_callable_r<const volatile void, Callable>::value);
static_assert(!internal::is_callable_r<int, Callable>::value);
static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);
}
#endif // C++17 and above
// Nothing should choke when we try to call other arguments besides directly
// callable objects, but they should not show up as callable.
static_assert(!internal::is_callable_r<void, int>::value, "");

View file

@ -37,6 +37,7 @@
#include <ostream> // NOLINT
#include <sstream>
#include <string>
#include <type_traits>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
@ -45,63 +46,19 @@
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace internal {
// Helper class for testing the Expectation class template.
class ExpectationTester {
public:
// Sets the call count of the given expectation to the given number.
void SetCallCount(int n, ExpectationBase* exp) { exp->call_count_ = n; }
};
} // namespace internal
} // namespace testing
namespace {
using testing::_;
using testing::AnyNumber;
using testing::AtLeast;
using testing::AtMost;
using testing::Between;
using testing::Cardinality;
using testing::CardinalityInterface;
using testing::Const;
using testing::ContainsRegex;
using testing::DoAll;
using testing::DoDefault;
using testing::Eq;
using testing::Expectation;
using testing::ExpectationSet;
using testing::Gt;
using testing::IgnoreResult;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::IsNotSubstring;
using testing::IsSubstring;
using testing::Lt;
using testing::Message;
using testing::Mock;
using testing::NaggyMock;
using testing::Ne;
using testing::Return;
using testing::SaveArg;
using testing::Sequence;
using testing::SetArgPointee;
using testing::internal::ExpectationTester;
using testing::internal::FormatFileLocation;
using testing::internal::kAllow;
using testing::internal::kErrorVerbosity;
using testing::internal::kFail;
using testing::internal::kInfoVerbosity;
using testing::internal::kWarn;
using testing::internal::kWarningVerbosity;
using ::testing::internal::FormatFileLocation;
using ::testing::internal::kAllow;
using ::testing::internal::kErrorVerbosity;
using ::testing::internal::kFail;
using ::testing::internal::kInfoVerbosity;
using ::testing::internal::kWarn;
using ::testing::internal::kWarningVerbosity;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::HasSubstr;
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
using ::testing::internal::CaptureStdout;
using ::testing::internal::GetCapturedStdout;
#endif
class Incomplete;
@ -846,6 +803,50 @@ TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
"to be called at least once");
}
#if defined(__cplusplus) && __cplusplus >= 201703L
// It should be possible to return a non-moveable type from a mock action in
// C++17 and above, where it's guaranteed that such a type can be initialized
// from a prvalue returned from a function.
TEST(ExpectCallTest, NonMoveableType) {
// Define a non-moveable result type.
struct Result {
explicit Result(int x_in) : x(x_in) {}
Result(Result&&) = delete;
int x;
};
static_assert(!std::is_move_constructible_v<Result>);
static_assert(!std::is_copy_constructible_v<Result>);
static_assert(!std::is_move_assignable_v<Result>);
static_assert(!std::is_copy_assignable_v<Result>);
// We should be able to use a callable that returns that result as both a
// OnceAction and an Action, whether the callable ignores arguments or not.
const auto return_17 = [] { return Result(17); };
static_cast<void>(OnceAction<Result()>{return_17});
static_cast<void>(Action<Result()>{return_17});
static_cast<void>(OnceAction<Result(int)>{return_17});
static_cast<void>(Action<Result(int)>{return_17});
// It should be possible to return the result end to end through an
// EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
MockFunction<Result()> mock;
EXPECT_CALL(mock, Call) //
.WillOnce(return_17) //
.WillRepeatedly(return_17);
EXPECT_EQ(17, mock.AsStdFunction()().x);
EXPECT_EQ(17, mock.AsStdFunction()().x);
EXPECT_EQ(17, mock.AsStdFunction()().x);
}
#endif // C++17 and above
// Tests that the n-th action is taken for the n-th matching
// invocation.
TEST(ExpectCallTest, NthMatchTakesNthAction) {
@ -2596,6 +2597,7 @@ TEST(ParameterlessExpectationsTest,
}
} // namespace
} // namespace testing
// Allows the user to define their own main and then invoke gmock_main
// from it. This might be necessary on some platforms which require

View file

@ -25,7 +25,7 @@ When building GoogleTest as a standalone project, the typical workflow starts
with
```
git clone https://github.com/google/googletest.git -b release-1.11.0
git clone https://github.com/google/googletest.git -b release-1.12.0
cd googletest # Main directory of the cloned repository.
mkdir build # Create a directory to hold the build output.
cd build
@ -94,7 +94,7 @@ include(FetchContent)
FetchContent_Declare(
googletest
# Specify the commit you depend on and update it regularly.
URL https://github.com/google/googletest/archive/e2239ee6043f73722e7aa812a459f54a28552929.zip
URL https://github.com/google/googletest/archive/5376968f6948923e2411081fd9372e71a59d8e77.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)

View file

@ -46,6 +46,9 @@
#include "gtest/gtest-message.h"
#include "gtest/internal/gtest-port.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
namespace testing {
// A class for indicating whether an assertion was successful. When
@ -229,4 +232,6 @@ GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
} // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_

View file

@ -185,14 +185,6 @@ GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
} // namespace edit_distance
// Calculate the diff between 'left' and 'right' and return it in unified diff
// format.
// If not null, stores in 'total_line_count' the total number of lines found
// in left + right.
GTEST_API_ std::string DiffStrings(const std::string& left,
const std::string& right,
size_t* total_line_count);
// Constructs and returns the message for an equality assertion
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
//

View file

@ -1200,6 +1200,9 @@ class GTEST_API_ AutoHandle {
// Nothing to do here.
#else
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
// Allows a controller thread to pause execution of newly created
// threads until notified. Instances of this class must be created
// and destroyed in the controller thread.
@ -1233,6 +1236,7 @@ class GTEST_API_ Notification {
std::condition_variable cv_;
bool notified_;
};
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
#endif // GTEST_HAS_NOTIFICATION_
// On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD
@ -1965,7 +1969,8 @@ inline int StrCaseCmp(const char* s1, const char* s2) {
}
inline char* StrDup(const char* src) { return strdup(src); }
#else // !__BORLANDC__
#if GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
inline int DoIsATTY(int /* fd */) { return 0; }
#else
inline int DoIsATTY(int fd) { return _isatty(fd); }

View file

@ -90,15 +90,6 @@
namespace testing {
namespace internal {
#if defined(_MSC_VER) || defined(__BORLANDC__)
// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
const int kStdOutFileno = 1;
const int kStdErrFileno = 2;
#else
const int kStdOutFileno = STDOUT_FILENO;
const int kStdErrFileno = STDERR_FILENO;
#endif // _MSC_VER
#if GTEST_OS_LINUX || GTEST_OS_GNU_HURD
namespace {
@ -1177,6 +1168,15 @@ static std::string GetCapturedStream(CapturedStream** captured_stream) {
return content;
}
#if defined(_MSC_VER) || defined(__BORLANDC__)
// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
const int kStdOutFileno = 1;
const int kStdErrFileno = 2;
#else
const int kStdOutFileno = STDOUT_FILENO;
const int kStdErrFileno = STDERR_FILENO;
#endif // defined(_MSC_VER) || defined(__BORLANDC__)
// Starts capturing stdout.
void CaptureStdout() {
CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);

View file

@ -3278,14 +3278,9 @@ static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \
GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)
const bool use_color = AlwaysFalse();
#else
static const bool in_color_mode =
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
const bool use_color = in_color_mode && (color != GTestColor::kDefault);
#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS
if (!use_color) {
vprintf(fmt, args);