Merge branch 'main' into patch-1

This commit is contained in:
Joakim Plate 2023-11-14 10:14:51 +01:00 committed by GitHub
commit 269d3b9909
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
55 changed files with 741 additions and 676 deletions

4
.gitignore vendored
View File

@ -24,6 +24,10 @@ Win32-Release/
x64-Debug/ x64-Debug/
x64-Release/ x64-Release/
# VSCode files
.cache/
cmake-variants.yaml
# Ignore autoconf / automake files # Ignore autoconf / automake files
Makefile.in Makefile.in
aclocal.m4 aclocal.m4

View File

@ -1,22 +1,10 @@
# Note: CMake support is community-based. The maintainers do not use CMake # Note: CMake support is community-based. The maintainers do not use CMake
# internally. # internally.
cmake_minimum_required(VERSION 3.5) cmake_minimum_required(VERSION 3.13)
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
endif (POLICY CMP0048)
if (POLICY CMP0069)
cmake_policy(SET CMP0069 NEW)
endif (POLICY CMP0069)
if (POLICY CMP0077)
cmake_policy(SET CMP0077 NEW)
endif (POLICY CMP0077)
project(googletest-distribution) project(googletest-distribution)
set(GOOGLETEST_VERSION 1.13.0) set(GOOGLETEST_VERSION 1.14.0)
if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_EXTENSIONS OFF)
@ -27,7 +15,7 @@ enable_testing()
include(CMakeDependentOption) include(CMakeDependentOption)
include(GNUInstallDirs) include(GNUInstallDirs)
#Note that googlemock target already builds googletest # Note that googlemock target already builds googletest.
option(BUILD_GMOCK "Builds the googlemock subproject" ON) option(BUILD_GMOCK "Builds the googlemock subproject" ON)
option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON)
option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF) option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF)

View File

@ -47,11 +47,11 @@ PR is acceptable as an alternative.
## The Google Test and Google Mock Communities ## The Google Test and Google Mock Communities
The Google Test community exists primarily through the The Google Test community exists primarily through the
[discussion group](http://groups.google.com/group/googletestframework) and the [discussion group](https://groups.google.com/group/googletestframework) and the
GitHub repository. Likewise, the Google Mock community exists primarily through GitHub repository. Likewise, the Google Mock community exists primarily through
their own [discussion group](http://groups.google.com/group/googlemock). You are their own [discussion group](https://groups.google.com/group/googlemock). You
definitely encouraged to contribute to the discussion and you can also help us are definitely encouraged to contribute to the discussion and you can also help
to keep the effectiveness of the group high by following and promoting the us to keep the effectiveness of the group high by following and promoting the
guidelines listed here. guidelines listed here.
### Please Be Friendly ### Please Be Friendly

View File

@ -9,7 +9,7 @@ GoogleTest now follows the
We recommend We recommend
[updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it). [updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it).
We do publish occasional semantic versions, tagged with We do publish occasional semantic versions, tagged with
`v${major}.${minor}.${patch}` (e.g. `v1.13.0`). `v${major}.${minor}.${patch}` (e.g. `v1.14.0`).
#### Documentation Updates #### Documentation Updates
@ -17,18 +17,18 @@ Our documentation is now live on GitHub Pages at
https://google.github.io/googletest/. We recommend browsing the documentation on https://google.github.io/googletest/. We recommend browsing the documentation on
GitHub Pages rather than directly in the repository. GitHub Pages rather than directly in the repository.
#### Release 1.13.0 #### Release 1.14.0
[Release 1.13.0](https://github.com/google/googletest/releases/tag/v1.13.0) is [Release 1.14.0](https://github.com/google/googletest/releases/tag/v1.14.0) is
now available. now available.
The 1.13.x branch requires at least C++14. The 1.14.x branch requires at least C++14.
#### Continuous Integration #### Continuous Integration
We use Google's internal systems for continuous integration. \ We use Google's internal systems for continuous integration. \
GitHub Actions were added for the convenience of open source contributors. They GitHub Actions were added for the convenience of open-source contributors. They
are exclusively maintained by the open source community and not used by the are exclusively maintained by the open-source community and not used by the
GoogleTest team. GoogleTest team.
#### Coming Soon #### Coming Soon
@ -52,40 +52,39 @@ documentation. We recommend starting with the
More information about building GoogleTest can be found at More information about building GoogleTest can be found at
[googletest/README.md](googletest/README.md). [googletest/README.md](googletest/README.md).
| Feature | Description | ## Features
| ---------------------------- | --------------------------------------------- |
| xUnit test framework | Googletest is based on the | * xUnit test framework: \
: : [xUnit](https\://en.wikipedia.org/wiki/XUnit) : Googletest is based on the [xUnit](https://en.wikipedia.org/wiki/XUnit)
: : testing framework, a popular architecture for : testing framework, a popular architecture for unit testing
: : unit testing : * Test discovery: \
| Test discovery | Googletest automatically discovers and runs | Googletest automatically discovers and runs your tests, eliminating the need
: : your tests, eliminating the need to manually : to manually register your tests
: : register your tests : * Rich set of assertions: \
| Rich set of assertions | Googletest provides a variety of assertions, | Googletest provides a variety of assertions, such as equality, inequality,
: : such as equality, inequality, exceptions, and : exceptions, and more, making it easy to test your code
: : more, making it easy to test your code : * User-defined assertions: \
| User-defined assertions | You can define your own assertions with | You can define your own assertions with Googletest, making it simple to
: : Googletest, making it simple to write tests : write tests that are specific to your code
: : that are specific to your code : * Death tests: \
| Death tests | Googletest supports death tests, which verify | Googletest supports death tests, which verify that your code exits in a
: : that your code exits in a certain way, making : certain way, making it useful for testing error-handling code
: : it useful for testing error-handling code : * Fatal and non-fatal failures: \
| Fatal and non-fatal failures | You can specify whether a test failure should | You can specify whether a test failure should be treated as fatal or
: : be treated as fatal or non-fatal with : non-fatal with Googletest, allowing tests to continue running even if a
: : Googletest, allowing tests to continue : failure occurs
: : running even if a failure occurs : * Value-parameterized tests: \
| Value-parameterized tests | Googletest supports value-parameterized | Googletest supports value-parameterized tests, which run multiple times with
: : tests, which run multiple times with : different input values, making it useful for testing functions that take
: : different input values, making it useful for : different inputs
: : testing functions that take different inputs : * Type-parameterized tests: \
| Type-parameterized tests | Googletest also supports type-parameterized | Googletest also supports type-parameterized tests, which run with different
: : tests, which run with different data types, : data types, making it useful for testing functions that work with different
: : making it useful for testing functions that : data types
: : work with different data types : * Various options for running tests: \
| Various options for running | Googletest provides many options for running | Googletest provides many options for running tests including running
: tests : tests, including running individual tests, : individual tests, running tests in a specific order and running tests in
: : running tests in a specific order, and : parallel
: : running tests in parallel :
## Supported Platforms ## Supported Platforms
@ -93,7 +92,7 @@ GoogleTest follows Google's
[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support). [Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support).
See See
[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md) [this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
for a list of currently supported versions compilers, platforms, and build for a list of currently supported versions of compilers, platforms, and build
tools. tools.
## Who Is Using GoogleTest? ## Who Is Using GoogleTest?
@ -101,12 +100,12 @@ tools.
In addition to many internal projects at Google, GoogleTest is also used by the In addition to many internal projects at Google, GoogleTest is also used by the
following notable projects: following notable projects:
* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser * The [Chromium projects](https://www.chromium.org/) (behind the Chrome
and Chrome OS). browser and Chrome OS).
* The [LLVM](http://llvm.org/) compiler. * The [LLVM](https://llvm.org/) compiler.
* [Protocol Buffers](https://github.com/google/protobuf), Google's data * [Protocol Buffers](https://github.com/google/protobuf), Google's data
interchange format. interchange format.
* The [OpenCV](http://opencv.org/) computer vision library. * The [OpenCV](https://opencv.org/) computer vision library.
## Related Open Source Projects ## Related Open Source Projects

View File

@ -6,22 +6,22 @@ googletest_deps()
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive( http_archive(
name = "rules_python", # 2023-01-10T22:00:51Z name = "rules_python", # 2023-07-31T20:39:27Z
sha256 = "5de54486a60ad8948dabe49605bb1c08053e04001a431ab3e96745b4d97a4419", sha256 = "1250b59a33c591a1c4ba68c62e95fc88a84c334ec35a2e23f46cbc1b9a5a8b55",
strip_prefix = "rules_python-70cce26432187a60b4e950118791385e6fb3c26f", strip_prefix = "rules_python-e355becc30275939d87116a4ec83dad4bb50d9e1",
urls = ["https://github.com/bazelbuild/rules_python/archive/70cce26432187a60b4e950118791385e6fb3c26f.zip"], urls = ["https://github.com/bazelbuild/rules_python/archive/e355becc30275939d87116a4ec83dad4bb50d9e1.zip"],
) )
http_archive( http_archive(
name = "bazel_skylib", # 2022-11-16T18:29:32Z name = "bazel_skylib", # 2023-05-31T19:24:07Z
sha256 = "a22290c26d29d3ecca286466f7f295ac6cbe32c0a9da3a91176a90e0725e3649", sha256 = "08c0386f45821ce246bbbf77503c973246ed6ee5c3463e41efc197fa9bc3a7f4",
strip_prefix = "bazel-skylib-5bfcb1a684550626ce138fe0fe8f5f702b3764c3", strip_prefix = "bazel-skylib-288731ef9f7f688932bd50e704a91a45ec185f9b",
urls = ["https://github.com/bazelbuild/bazel-skylib/archive/5bfcb1a684550626ce138fe0fe8f5f702b3764c3.zip"], urls = ["https://github.com/bazelbuild/bazel-skylib/archive/288731ef9f7f688932bd50e704a91a45ec185f9b.zip"],
) )
http_archive( http_archive(
name = "platforms", # 2022-11-09T19:18:22Z name = "platforms", # 2023-07-28T19:44:27Z
sha256 = "b4a3b45dc4202e2b3e34e3bc49d2b5b37295fc23ea58d88fb9e01f3642ad9b55", sha256 = "40eb313613ff00a5c03eed20aba58890046f4d38dec7344f00bb9a8867853526",
strip_prefix = "platforms-3fbc687756043fb58a407c2ea8c944bc2fe1d922", strip_prefix = "platforms-4ad40ef271da8176d4fc0194d2089b8a76e19d7b",
urls = ["https://github.com/bazelbuild/platforms/archive/3fbc687756043fb58a407c2ea8c944bc2fe1d922.zip"], urls = ["https://github.com/bazelbuild/platforms/archive/4ad40ef271da8176d4fc0194d2089b8a76e19d7b.zip"],
) )

View File

@ -31,7 +31,7 @@
set -euox pipefail set -euox pipefail
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20230217" readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20230816"
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20230120" 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

View File

@ -508,9 +508,9 @@ TEST_F(FooDeathTest, DoesThat) {
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](https://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](https://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
@ -899,10 +899,10 @@ also supports per-test-suite set-up/tear-down. To use it:
variables to hold the shared resources. variables to hold the shared resources.
2. Outside your test fixture class (typically just below it), define those 2. Outside your test fixture class (typically just below it), define those
member variables, optionally giving them initial values. member variables, optionally giving them initial values.
3. In the same test fixture class, define a `static void SetUpTestSuite()` 3. In the same test fixture class, define a public member function `static void
function (remember not to spell it as **`SetupTestSuite`** with a small SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a
`u`!) to set up the shared resources and a `static void TearDownTestSuite()` small `u`!) to set up the shared resources and a `static void
function to tear them down. TearDownTestSuite()` function to tear them down.
That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the
*first test* in the `FooTest` test suite (i.e. before creating the first *first test* in the `FooTest` test suite (i.e. before creating the first
@ -2171,7 +2171,7 @@ The report format conforms to the following JSON Schema:
```json ```json
{ {
"$schema": "http://json-schema.org/schema#", "$schema": "https://json-schema.org/schema#",
"type": "object", "type": "object",
"definitions": { "definitions": {
"TestCase": { "TestCase": {

View File

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

View File

@ -20,7 +20,7 @@ class Foo {
(note that `~Foo()` **must** be virtual) we can define its mock as (note that `~Foo()` **must** be virtual) we can define its mock as
```cpp ```cpp
#include "gmock/gmock.h" #include <gmock/gmock.h>
class MockFoo : public Foo { class MockFoo : public Foo {
public: public:

View File

@ -697,9 +697,9 @@ TEST(AbcTest, Xyz) {
EXPECT_CALL(foo, DoThat(_, _)); EXPECT_CALL(foo, DoThat(_, _));
int n = 0; int n = 0;
EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked.
foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked.
EXPECT_EQ(2, n); EXPECT_EQ(n, 2);
} }
``` ```
@ -1129,11 +1129,11 @@ using STL's `<functional>` header is just painful). For example, here's a
predicate that's satisfied by any number that is >= 0, <= 100, and != 50: predicate that's satisfied by any number that is >= 0, <= 100, and != 50:
```cpp ```cpp
using testing::AllOf; using ::testing::AllOf;
using testing::Ge; using ::testing::Ge;
using testing::Le; using ::testing::Le;
using testing::Matches; using ::testing::Matches;
using testing::Ne; using ::testing::Ne;
... ...
Matches(AllOf(Ge(0), Le(100), Ne(50))) Matches(AllOf(Ge(0), Le(100), Ne(50)))
``` ```
@ -1861,7 +1861,7 @@ error. So, what shall you do?
Though you may be tempted, DO NOT use `std::ref()`: Though you may be tempted, DO NOT use `std::ref()`:
```cpp ```cpp
using testing::Return; using ::testing::Return;
class MockFoo : public Foo { class MockFoo : public Foo {
public: public:
@ -1873,7 +1873,7 @@ class MockFoo : public Foo {
EXPECT_CALL(foo, GetValue()) EXPECT_CALL(foo, GetValue())
.WillRepeatedly(Return(std::ref(x))); // Wrong! .WillRepeatedly(Return(std::ref(x))); // Wrong!
x = 42; x = 42;
EXPECT_EQ(42, foo.GetValue()); EXPECT_EQ(foo.GetValue(), 42);
``` ```
Unfortunately, it doesn't work here. The above code will fail with error: Unfortunately, it doesn't work here. The above code will fail with error:
@ -1895,14 +1895,14 @@ the expectation is set, and `Return(std::ref(x))` will always return 0.
returns the value pointed to by `pointer` at the time the action is *executed*: returns the value pointed to by `pointer` at the time the action is *executed*:
```cpp ```cpp
using testing::ReturnPointee; using ::testing::ReturnPointee;
... ...
int x = 0; int x = 0;
MockFoo foo; MockFoo foo;
EXPECT_CALL(foo, GetValue()) EXPECT_CALL(foo, GetValue())
.WillRepeatedly(ReturnPointee(&x)); // Note the & here. .WillRepeatedly(ReturnPointee(&x)); // Note the & here.
x = 42; x = 42;
EXPECT_EQ(42, foo.GetValue()); // This will succeed now. EXPECT_EQ(foo.GetValue(), 42); // This will succeed now.
``` ```
### Combining Actions ### Combining Actions
@ -1927,6 +1927,12 @@ class MockFoo : public Foo {
action_n)); action_n));
``` ```
The return value of the last action **must** match the return type of the mocked
method. In the example above, `action_n` could be `Return(true)`, or a lambda
that returns a `bool`, but not `SaveArg`, which returns `void`. Otherwise the
signature of `DoAll` would not match the signature expected by `WillOnce`, which
is the signature of the mocked method, and it wouldn't compile.
### Verifying Complex Arguments {#SaveArgVerify} ### Verifying Complex Arguments {#SaveArgVerify}
If you want to verify that a method is called with a particular argument but the If you want to verify that a method is called with a particular argument but the
@ -2264,7 +2270,7 @@ TEST_F(FooTest, Test) {
EXPECT_CALL(foo, DoThis(2)) EXPECT_CALL(foo, DoThis(2))
.WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5))); .WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5)));
EXPECT_EQ('+', foo.DoThis(2)); // Invokes SignOfSum(5, 2). EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2).
} }
``` ```
@ -2640,8 +2646,8 @@ action will exhibit different behaviors. Example:
.WillRepeatedly(IncrementCounter(0)); .WillRepeatedly(IncrementCounter(0));
foo.DoThis(); // Returns 1. foo.DoThis(); // Returns 1.
foo.DoThis(); // Returns 2. foo.DoThis(); // Returns 2.
foo.DoThat(); // Returns 1 - Blah() uses a different foo.DoThat(); // Returns 1 - DoThat() uses a different
// counter than Bar()'s. // counter than DoThis()'s.
``` ```
versus versus
@ -2771,11 +2777,13 @@ returns a null `unique_ptr`, thats what youll get if you dont specify a
action: action:
```cpp ```cpp
using ::testing::IsNull;
...
// Use the default action. // Use the default action.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));
// Triggers the previous EXPECT_CALL. // Triggers the previous EXPECT_CALL.
EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello")); EXPECT_THAT(mock_buzzer_.MakeBuzz("hello"), IsNull());
``` ```
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
@ -3192,11 +3200,11 @@ You can unlock this power by running your test with the `--gmock_verbose=info`
flag. For example, given the test program: flag. For example, given the test program:
```cpp ```cpp
#include "gmock/gmock.h" #include <gmock/gmock.h>
using testing::_; using ::testing::_;
using testing::HasSubstr; using ::testing::HasSubstr;
using testing::Return; using ::testing::Return;
class MockFoo { class MockFoo {
public: public:
@ -3817,15 +3825,15 @@ If the built-in actions don't work for you, you can easily define your own one.
All you need is a call operator with a signature compatible with the mocked All you need is a call operator with a signature compatible with the mocked
function. So you can use a lambda: function. So you can use a lambda:
``` ```cpp
MockFunction<int(int)> mock; MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; });
EXPECT_EQ(14, mock.AsStdFunction()(2)); EXPECT_EQ(mock.AsStdFunction()(2), 14);
``` ```
Or a struct with a call operator (even a templated one): Or a struct with a call operator (even a templated one):
``` ```cpp
struct MultiplyBy { struct MultiplyBy {
template <typename T> template <typename T>
T operator()(T arg) { return arg * multiplier; } T operator()(T arg) { return arg * multiplier; }
@ -3840,16 +3848,16 @@ struct MultiplyBy {
It's also fine for the callable to take no arguments, ignoring the arguments It's also fine for the callable to take no arguments, ignoring the arguments
supplied to the mock function: supplied to the mock function:
``` ```cpp
MockFunction<int(int)> mock; MockFunction<int(int)> mock;
EXPECT_CALL(mock, Call).WillOnce([] { return 17; }); EXPECT_CALL(mock, Call).WillOnce([] { return 17; });
EXPECT_EQ(17, mock.AsStdFunction()(0)); EXPECT_EQ(mock.AsStdFunction()(0), 17);
``` ```
When used with `WillOnce`, the callable can assume it will be called at most When used with `WillOnce`, the callable can assume it will be called at most
once and is allowed to be a move-only type: once and is allowed to be a move-only type:
``` ```cpp
// An action that contains move-only types and has an &&-qualified operator, // An action that contains move-only types and has an &&-qualified operator,
// demanding in the type system that it be called at most once. This can be // demanding in the type system that it be called at most once. This can be
// used with WillOnce, but the compiler will reject it if handed to // used with WillOnce, but the compiler will reject it if handed to

View File

@ -90,14 +90,14 @@ gMock is bundled with googletest.
## A Case for Mock Turtles ## A Case for Mock Turtles
Let's look at an example. Suppose you are developing a graphics program that Let's look at an example. Suppose you are developing a graphics program that
relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like relies on a [LOGO](https://en.wikipedia.org/wiki/Logo_programming_language)-like
API for drawing. How would you test that it does the right thing? Well, you can API for drawing. How would you test that it does the right thing? Well, you can
run it and compare the screen with a golden screen snapshot, but let's admit it: run it and compare the screen with a golden screen snapshot, but let's admit it:
tests like this are expensive to run and fragile (What if you just upgraded to a tests like this are expensive to run and fragile (What if you just upgraded to a
shiny new graphics card that has better anti-aliasing? Suddenly you have to shiny new graphics card that has better anti-aliasing? Suddenly you have to
update all your golden images.). It would be too painful if all your tests are update all your golden images.). It would be too painful if all your tests are
like this. Fortunately, you learned about like this. Fortunately, you learned about
[Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) and know the right thing
to do: instead of having your application talk to the system API directly, wrap to do: instead of having your application talk to the system API directly, wrap
the API in an interface (say, `Turtle`) and code to that interface: the API in an interface (say, `Turtle`) and code to that interface:
@ -164,7 +164,7 @@ follow:
After the process, you should have something like: After the process, you should have something like:
```cpp ```cpp
#include "gmock/gmock.h" // Brings in gMock. #include <gmock/gmock.h> // Brings in gMock.
class MockTurtle : public Turtle { class MockTurtle : public Turtle {
public: public:
@ -224,8 +224,8 @@ Here's an example:
```cpp ```cpp
#include "path/to/mock-turtle.h" #include "path/to/mock-turtle.h"
#include "gmock/gmock.h" #include <gmock/gmock.h>
#include "gtest/gtest.h" #include <gtest/gtest.h>
using ::testing::AtLeast; // #1 using ::testing::AtLeast; // #1

View File

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

View File

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

View File

@ -42,7 +42,7 @@ 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
@ -50,7 +50,7 @@ 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](https://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.
@ -68,13 +68,13 @@ 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](https://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]
[istqb test case]: http://glossary.istqb.org/en/search/test%20case [istqb test case]: https://glossary.istqb.org/en/search/test%20case
[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite [istqb test suite]: https://glossary.istqb.org/en/search/test%20suite
## Basic Concepts ## Basic Concepts
@ -210,7 +210,7 @@ objects for several different tests.
To create a fixture: To create a fixture:
1. Derive a class from `::testing::Test` . Start its body with `protected:`, as 1. Derive a class from `testing::Test` . Start its body with `protected:`, as
we'll want to access fixture members from sub-classes. we'll want to access fixture members from sub-classes.
2. Inside the class, declare any objects you plan to use. 2. Inside the class, declare any objects you plan to use.
3. If necessary, write a default constructor or `SetUp()` function to prepare 3. If necessary, write a default constructor or `SetUp()` function to prepare
@ -271,7 +271,7 @@ First, define a fixture class. By convention, you should give it the name
`FooTest` where `Foo` is the class being tested. `FooTest` where `Foo` is the class being tested.
```c++ ```c++
class QueueTest : public ::testing::Test { class QueueTest : public testing::Test {
protected: protected:
void SetUp() override { void SetUp() override {
// q0_ remains empty // q0_ remains empty
@ -395,14 +395,14 @@ You can start from this boilerplate:
```c++ ```c++
#include "this/package/foo.h" #include "this/package/foo.h"
#include "gtest/gtest.h" #include <gtest/gtest.h>
namespace my { namespace my {
namespace project { namespace project {
namespace { namespace {
// The fixture for testing class Foo. // The fixture for testing class Foo.
class FooTest : public ::testing::Test { class FooTest : public testing::Test {
protected: protected:
// You can remove any or all of the following functions if their bodies would // You can remove any or all of the following functions if their bodies would
// be empty. // be empty.
@ -450,14 +450,14 @@ TEST_F(FooTest, DoesXyz) {
} // namespace my } // namespace my
int main(int argc, char **argv) { int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
``` ```
The `::testing::InitGoogleTest()` function parses the command line for The `testing::InitGoogleTest()` function parses the command line for GoogleTest
GoogleTest flags, and removes all recognized flags. This allows the user to flags, and removes all recognized flags. This allows the user to control a test
control a test program's behavior via various flags, which we'll cover in the 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.

View File

@ -1,7 +1,7 @@
# Assertions Reference # Assertions Reference
This page lists the assertion macros provided by GoogleTest for verifying code This page lists the assertion macros provided by GoogleTest for verifying code
behavior. To use them, include the header `gtest/gtest.h`. behavior. To use them, add `#include <gtest/gtest.h>`.
The majority of the macros listed below come as a pair with an `EXPECT_` variant The majority of the macros listed below come as a pair with an `EXPECT_` variant
and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal
@ -88,7 +88,7 @@ For example, the following code verifies that the string `value1` starts with
10: 10:
```cpp ```cpp
#include "gmock/gmock.h" #include <gmock/gmock.h>
using ::testing::AllOf; using ::testing::AllOf;
using ::testing::Gt; using ::testing::Gt;

View File

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

View File

@ -3,7 +3,7 @@
<!--* toc_depth: 3 *--> <!--* toc_depth: 3 *-->
This page lists the facilities provided by GoogleTest for writing test programs. This page lists the facilities provided by GoogleTest for writing test programs.
To use them, include the header `gtest/gtest.h`. To use them, add `#include <gtest/gtest.h>`.
## Macros ## Macros
@ -122,8 +122,8 @@ custom function can be used for more control:
```cpp ```cpp
INSTANTIATE_TEST_SUITE_P( INSTANTIATE_TEST_SUITE_P(
MyInstantiation, MyTestSuite, MyInstantiation, MyTestSuite,
::testing::Values(...), testing::Values(...),
[](const ::testing::TestParamInfo<MyTestSuite::ParamType>& info) { [](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {
// Can use info.param here to generate the test suffix // Can use info.param here to generate the test suffix
std::string name = ... std::string name = ...
return name; return name;
@ -148,7 +148,7 @@ type, for example:
```cpp ```cpp
template <typename T> template <typename T>
class MyFixture : public ::testing::Test { class MyFixture : public testing::Test {
public: public:
... ...
using List = std::list<T>; using List = std::list<T>;
@ -324,7 +324,7 @@ Then the test code should look like:
```cpp ```cpp
namespace my_namespace { namespace my_namespace {
class MyClassTest : public ::testing::Test { class MyClassTest : public testing::Test {
... ...
}; };
@ -387,7 +387,7 @@ GoogleTest defines the following classes and types to help with writing tests.
### AssertionResult {#AssertionResult} ### AssertionResult {#AssertionResult}
`::testing::AssertionResult` `testing::AssertionResult`
A class for indicating whether an assertion was successful. A class for indicating whether an assertion was successful.
@ -401,14 +401,14 @@ To create an instance of this class, use one of the factory functions
### AssertionException {#AssertionException} ### AssertionException {#AssertionException}
`::testing::AssertionException` `testing::AssertionException`
Exception which can be thrown from Exception which can be thrown from
[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult). [`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult).
### EmptyTestEventListener {#EmptyTestEventListener} ### EmptyTestEventListener {#EmptyTestEventListener}
`::testing::EmptyTestEventListener` `testing::EmptyTestEventListener`
Provides an empty implementation of all methods in the Provides an empty implementation of all methods in the
[`TestEventListener`](#TestEventListener) interface, such that a subclass only [`TestEventListener`](#TestEventListener) interface, such that a subclass only
@ -416,7 +416,7 @@ needs to override the methods it cares about.
### Environment {#Environment} ### Environment {#Environment}
`::testing::Environment` `testing::Environment`
Represents a global test environment. See Represents a global test environment. See
[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down). [Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down).
@ -437,7 +437,7 @@ Override this to define how to tear down the environment.
### ScopedTrace {#ScopedTrace} ### ScopedTrace {#ScopedTrace}
`::testing::ScopedTrace` `testing::ScopedTrace`
An instance of this class causes a trace to be included in every test failure An instance of this class causes a trace to be included in every test failure
message generated by code in the scope of the lifetime of the `ScopedTrace` message generated by code in the scope of the lifetime of the `ScopedTrace`
@ -453,7 +453,7 @@ ScopedTrace(const char* file, int line, const T& message)
Example usage: Example usage:
```cpp ```cpp
::testing::ScopedTrace trace("file.cc", 123, "message"); testing::ScopedTrace trace("file.cc", 123, "message");
``` ```
The resulting trace includes the given source file path and line number, and the The resulting trace includes the given source file path and line number, and the
@ -464,7 +464,7 @@ See also [`SCOPED_TRACE`](#SCOPED_TRACE).
### Test {#Test} ### Test {#Test}
`::testing::Test` `testing::Test`
The abstract class that all tests inherit from. `Test` is not copyable. The abstract class that all tests inherit from. `Test` is not copyable.
@ -552,7 +552,7 @@ after running each individual test.
### TestWithParam {#TestWithParam} ### TestWithParam {#TestWithParam}
`::testing::TestWithParam<T>` `testing::TestWithParam<T>`
A convenience class which inherits from both [`Test`](#Test) and A convenience class which inherits from both [`Test`](#Test) and
[`WithParamInterface<T>`](#WithParamInterface). [`WithParamInterface<T>`](#WithParamInterface).
@ -672,7 +672,7 @@ during execution of `SetUpTestSuite` and `TearDownTestSuite`.
### TestInfo {#TestInfo} ### TestInfo {#TestInfo}
`::testing::TestInfo` `testing::TestInfo`
Stores information about a test. Stores information about a test.
@ -751,7 +751,7 @@ Returns the result of the test. See [`TestResult`](#TestResult).
### TestParamInfo {#TestParamInfo} ### TestParamInfo {#TestParamInfo}
`::testing::TestParamInfo<T>` `testing::TestParamInfo<T>`
Describes a parameter to a value-parameterized test. The type `T` is the type of Describes a parameter to a value-parameterized test. The type `T` is the type of
the parameter. the parameter.
@ -761,7 +761,7 @@ and its integer index respectively.
### UnitTest {#UnitTest} ### UnitTest {#UnitTest}
`::testing::UnitTest` `testing::UnitTest`
This class contains information about the test program. This class contains information about the test program.
@ -929,7 +929,7 @@ GoogleTest. See [`TestEventListeners`](#TestEventListeners).
### TestEventListener {#TestEventListener} ### TestEventListener {#TestEventListener}
`::testing::TestEventListener` `testing::TestEventListener`
The interface for tracing execution of tests. The methods below are listed in The interface for tracing execution of tests. The methods below are listed in
the order the corresponding events are fired. the order the corresponding events are fired.
@ -1027,7 +1027,7 @@ Fired after all test activities have ended.
### TestEventListeners {#TestEventListeners} ### TestEventListeners {#TestEventListeners}
`::testing::TestEventListeners` `testing::TestEventListeners`
Lets users add listeners to track events in GoogleTest. Lets users add listeners to track events in GoogleTest.
@ -1072,7 +1072,7 @@ the caller and makes this function return `NULL` the next time.
### TestPartResult {#TestPartResult} ### TestPartResult {#TestPartResult}
`::testing::TestPartResult` `testing::TestPartResult`
A copyable object representing the result of a test part (i.e. an assertion or A copyable object representing the result of a test part (i.e. an assertion or
an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`). an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`).
@ -1154,7 +1154,7 @@ Returns true if and only if the test part failed.
### TestProperty {#TestProperty} ### TestProperty {#TestProperty}
`::testing::TestProperty` `testing::TestProperty`
A copyable object representing a user-specified test property which can be A copyable object representing a user-specified test property which can be
output as a key/value string pair. output as a key/value string pair.
@ -1181,7 +1181,7 @@ Sets a new value, overriding the previous one.
### TestResult {#TestResult} ### TestResult {#TestResult}
`::testing::TestResult` `testing::TestResult`
Contains information about the result of a single test. Contains information about the result of a single test.
@ -1262,20 +1262,20 @@ range, aborts the program.
### TimeInMillis {#TimeInMillis} ### TimeInMillis {#TimeInMillis}
`::testing::TimeInMillis` `testing::TimeInMillis`
An integer type representing time in milliseconds. An integer type representing time in milliseconds.
### Types {#Types} ### Types {#Types}
`::testing::Types<T...>` `testing::Types<T...>`
Represents a list of types for use in typed tests and type-parameterized tests. Represents a list of types for use in typed tests and type-parameterized tests.
The template argument `T...` can be any number of types, for example: The template argument `T...` can be any number of types, for example:
``` ```
::testing::Types<char, int, unsigned int> testing::Types<char, int, unsigned int>
``` ```
See [Typed Tests](../advanced.md#typed-tests) and See [Typed Tests](../advanced.md#typed-tests) and
@ -1284,7 +1284,7 @@ information.
### WithParamInterface {#WithParamInterface} ### WithParamInterface {#WithParamInterface}
`::testing::WithParamInterface<T>` `testing::WithParamInterface<T>`
The pure interface class that all value-parameterized tests inherit from. The pure interface class that all value-parameterized tests inherit from.
@ -1310,9 +1310,9 @@ tests.
### InitGoogleTest {#InitGoogleTest} ### InitGoogleTest {#InitGoogleTest}
`void ::testing::InitGoogleTest(int* argc, char** argv)` \ `void testing::InitGoogleTest(int* argc, char** argv)` \
`void ::testing::InitGoogleTest(int* argc, wchar_t** argv)` \ `void testing::InitGoogleTest(int* argc, wchar_t** argv)` \
`void ::testing::InitGoogleTest()` `void testing::InitGoogleTest()`
Initializes GoogleTest. This must be called before calling Initializes GoogleTest. This must be called before calling
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line
@ -1329,7 +1329,7 @@ platforms where there is no `argc`/`argv`.
### AddGlobalTestEnvironment {#AddGlobalTestEnvironment} ### AddGlobalTestEnvironment {#AddGlobalTestEnvironment}
`Environment* ::testing::AddGlobalTestEnvironment(Environment* env)` `Environment* testing::AddGlobalTestEnvironment(Environment* env)`
Adds a test environment to the test program. Must be called before Adds a test environment to the test program. Must be called before
[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See
@ -1342,7 +1342,7 @@ See also [`Environment`](#Environment).
```cpp ```cpp
template <typename Factory> template <typename Factory>
TestInfo* ::testing::RegisterTest(const char* test_suite_name, const char* test_name, TestInfo* testing::RegisterTest(const char* test_suite_name, const char* test_name,
const char* type_param, const char* value_param, const char* type_param, const char* value_param,
const char* file, int line, Factory factory) const char* file, int line, Factory factory)
``` ```
@ -1381,27 +1381,27 @@ an all-caps name.
### AssertionSuccess {#AssertionSuccess} ### AssertionSuccess {#AssertionSuccess}
`AssertionResult ::testing::AssertionSuccess()` `AssertionResult testing::AssertionSuccess()`
Creates a successful assertion result. See Creates a successful assertion result. See
[`AssertionResult`](#AssertionResult). [`AssertionResult`](#AssertionResult).
### AssertionFailure {#AssertionFailure} ### AssertionFailure {#AssertionFailure}
`AssertionResult ::testing::AssertionFailure()` `AssertionResult testing::AssertionFailure()`
Creates a failed assertion result. Use the `<<` operator to store a failure Creates a failed assertion result. Use the `<<` operator to store a failure
message: message:
```cpp ```cpp
::testing::AssertionFailure() << "My failure message"; testing::AssertionFailure() << "My failure message";
``` ```
See [`AssertionResult`](#AssertionResult). See [`AssertionResult`](#AssertionResult).
### StaticAssertTypeEq {#StaticAssertTypeEq} ### StaticAssertTypeEq {#StaticAssertTypeEq}
`::testing::StaticAssertTypeEq<T1, T2>()` `testing::StaticAssertTypeEq<T1, T2>()`
Compile-time assertion for type equality. Compiles if and only if `T1` and `T2` Compile-time assertion for type equality. Compiles if and only if `T1` and `T2`
are the same type. The value it returns is irrelevant. are the same type. The value it returns is irrelevant.
@ -1410,7 +1410,7 @@ See [Type Assertions](../advanced.md#type-assertions) for more information.
### PrintToString {#PrintToString} ### PrintToString {#PrintToString}
`std::string ::testing::PrintToString(x)` `std::string testing::PrintToString(x)`
Prints any value `x` using GoogleTest's value printer. Prints any value `x` using GoogleTest's value printer.
@ -1420,7 +1420,7 @@ for more information.
### PrintToStringParamName {#PrintToStringParamName} ### PrintToStringParamName {#PrintToStringParamName}
`std::string ::testing::PrintToStringParamName(TestParamInfo<T>& info)` `std::string testing::PrintToStringParamName(TestParamInfo<T>& info)`
A built-in parameterized test name generator which returns the result of A built-in parameterized test name generator which returns the result of
[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the [`PrintToString`](#PrintToString) called on `info.param`. Does not work when the

View File

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

View File

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

View File

@ -175,9 +175,15 @@ struct BuiltInDefaultValueGetter<T, false> {
static T Get() { static T Get() {
Assert(false, __FILE__, __LINE__, Assert(false, __FILE__, __LINE__,
"Default action undefined for the function return type."); "Default action undefined for the function return type.");
return internal::Invalid<T>(); #if defined(__GNUC__) || defined(__clang__)
__builtin_unreachable();
#elif defined(_MSC_VER)
__assume(0);
#else
return Invalid<T>();
// The above statement will never be reached, but is required in // The above statement will never be reached, but is required in
// order for this function to compile. // order for this function to compile.
#endif
} }
}; };

View File

@ -37,6 +37,7 @@
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_
#include <cstddef>
#include <type_traits> // IWYU pragma: keep #include <type_traits> // IWYU pragma: keep
#include <utility> // IWYU pragma: keep #include <utility> // IWYU pragma: keep
@ -69,22 +70,22 @@ constexpr bool PrefixOf(const char* a, const char* b) {
return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1));
} }
template <int N, int M> template <size_t N, size_t M>
constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) {
return N <= M && internal::PrefixOf(prefix, str); return N <= M && internal::PrefixOf(prefix, str);
} }
template <int N, int M> template <size_t N, size_t M>
constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) {
return N <= M && internal::PrefixOf(suffix, str + M - N); return N <= M && internal::PrefixOf(suffix, str + M - N);
} }
template <int N, int M> template <size_t N, size_t M>
constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { constexpr bool Equals(const char (&a)[N], const char (&b)[M]) {
return N == M && internal::PrefixOf(a, b); return N == M && internal::PrefixOf(a, b);
} }
template <int N> template <size_t N>
constexpr bool ValidateSpec(const char (&spec)[N]) { constexpr bool ValidateSpec(const char (&spec)[N]) {
return internal::Equals("const", spec) || return internal::Equals("const", spec) ||
internal::Equals("override", spec) || internal::Equals("override", spec) ||

View File

@ -1048,7 +1048,7 @@ class StartsWithMatcher {
template <typename MatcheeStringType> template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s, bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const { MatchResultListener* /* listener */) const {
const StringType& s2(s); const StringType s2(s);
return s2.length() >= prefix_.length() && return s2.length() >= prefix_.length() &&
s2.substr(0, prefix_.length()) == prefix_; s2.substr(0, prefix_.length()) == prefix_;
} }
@ -1102,7 +1102,7 @@ class EndsWithMatcher {
template <typename MatcheeStringType> template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s, bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const { MatchResultListener* /* listener */) const {
const StringType& s2(s); const StringType s2(s);
return s2.length() >= suffix_.length() && return s2.length() >= suffix_.length() &&
s2.substr(s2.length() - suffix_.length()) == suffix_; s2.substr(s2.length() - suffix_.length()) == suffix_;
} }

View File

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

View File

@ -120,7 +120,7 @@ GTEST_API_ std::string FormatMatcherDescription(
// [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method". // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
// "Introduction to Algorithms (Second ed.)", pp. 651-664. // "Introduction to Algorithms (Second ed.)", pp. 651-664.
// [2] "Ford-Fulkerson algorithm", Wikipedia, // [2] "Ford-Fulkerson algorithm", Wikipedia,
// 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm' // 'https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
class MaxBipartiteMatchState { class MaxBipartiteMatchState {
public: public:
explicit MaxBipartiteMatchState(const MatchMatrix& graph) explicit MaxBipartiteMatchState(const MatchMatrix& graph)

View File

@ -32,7 +32,8 @@
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) #if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) || \
(defined(GTEST_OS_NRF52) && defined(ARDUINO))
#ifdef GTEST_OS_ESP8266 #ifdef GTEST_OS_ESP8266
extern "C" { extern "C" {
#endif #endif

View File

@ -1769,6 +1769,15 @@ TEST(StartsWithTest, CanDescribeSelf) {
EXPECT_EQ("starts with \"Hi\"", Describe(m)); EXPECT_EQ("starts with \"Hi\"", Describe(m));
} }
TEST(StartsWithTest, WorksWithStringMatcherOnStringViewMatchee) {
#if GTEST_INTERNAL_HAS_STRING_VIEW
EXPECT_THAT(internal::StringView("talk to me goose"),
StartsWith(std::string("talk")));
#else
GTEST_SKIP() << "Not applicable without internal::StringView.";
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
}
// Tests EndsWith(s). // Tests EndsWith(s).
TEST(EndsWithTest, MatchesStringWithGivenSuffix) { TEST(EndsWithTest, MatchesStringWithGivenSuffix) {

View File

@ -906,7 +906,7 @@ TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
" - returning default value.")); " - returning default value."));
} }
TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) { TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) {
MockB b; MockB b;
std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1)); EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));

View File

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

View File

@ -12,7 +12,7 @@ GoogleTest comes with a CMake build script
([CMakeLists.txt](https://github.com/google/googletest/blob/main/CMakeLists.txt)) ([CMakeLists.txt](https://github.com/google/googletest/blob/main/CMakeLists.txt))
that can be used on a wide range of platforms ("C" stands for cross-platform.). that can be used on a wide range of platforms ("C" stands for cross-platform.).
If you don't have CMake installed already, you can download it for free from If you don't have CMake installed already, you can download it for free from
<http://www.cmake.org/>. <https://cmake.org/>.
CMake works by generating native makefiles or build projects that can be used in CMake works by generating native makefiles or build projects that can be used in
the compiler environment of your choice. You can either build GoogleTest as a the compiler environment of your choice. You can either build GoogleTest as a
@ -25,7 +25,7 @@ When building GoogleTest as a standalone project, the typical workflow starts
with with
``` ```
git clone https://github.com/google/googletest.git -b v1.13.0 git clone https://github.com/google/googletest.git -b v1.14.0
cd googletest # Main directory of the cloned repository. cd googletest # Main directory of the cloned repository.
mkdir build # Create a directory to hold the build output. mkdir build # Create a directory to hold the build output.
cd build cd build
@ -124,10 +124,10 @@ match the project in which it is included.
#### C++ Standard Version #### C++ Standard Version
An environment that supports C++11 is required in order to successfully build An environment that supports C++14 is required in order to successfully build
GoogleTest. One way to ensure this is to specify the standard in the top-level GoogleTest. One way to ensure this is to specify the standard in the top-level
project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command along project, for example by using the `set(CMAKE_CXX_STANDARD 14)` command along
with `set(CMAKE_CXX_STANDARD_REQUIRED ON). If this is not feasible, for example with `set(CMAKE_CXX_STANDARD_REQUIRED ON)`. If this is not feasible, for example
in a C project using GoogleTest for validation, then it can be specified by in a C project using GoogleTest for validation, then it can be specified by
adding it to the options for cmake via the`-DCMAKE_CXX_FLAGS` option. adding it to the options for cmake via the`-DCMAKE_CXX_FLAGS` option.
@ -145,7 +145,7 @@ We list the most frequently used macros below. For a complete list, see file
### Multi-threaded Tests ### Multi-threaded Tests
GoogleTest is thread-safe where the pthread library is available. After GoogleTest is thread-safe where the pthread library is available. After
`#include "gtest/gtest.h"`, you can check the `#include <gtest/gtest.h>`, you can check the
`GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is `GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is
`#defined` to 1, no if it's undefined.). `#defined` to 1, no if it's undefined.).

View File

@ -12,14 +12,6 @@
# Test and Google Mock's option() definitions, and thus must be # Test and Google Mock's option() definitions, and thus must be
# called *after* the options have been defined. # called *after* the options have been defined.
if (POLICY CMP0054)
cmake_policy(SET CMP0054 NEW)
endif (POLICY CMP0054)
if (POLICY CMP0069)
cmake_policy(SET CMP0069 NEW)
endif (POLICY CMP0069)
# Tweaks CMake's default compiler/linker settings to suit Google Test's needs. # Tweaks CMake's default compiler/linker settings to suit Google Test's needs.
# #
# This must be a macro(), as inside a function string() can only # This must be a macro(), as inside a function string() can only
@ -37,7 +29,7 @@ macro(fix_default_compiler_settings_)
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt) if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt)
# When Google Test is built as a shared library, it should also use # When Google Test is built as a shared library, it should also use
# shared runtime libraries. Otherwise, it may end up with multiple # shared runtime libraries. Otherwise, it may end up with multiple
# copies of runtime library data in different modules, resulting in # copies of runtime library data in different modules, resulting in
# hard-to-find crashes. When it is built as a static library, it is # hard-to-find crashes. When it is built as a static library, it is
# preferable to use CRT as static libraries, as we don't have to rely # preferable to use CRT as static libraries, as we don't have to rely
@ -63,11 +55,11 @@ macro(fix_default_compiler_settings_)
endmacro() endmacro()
# Defines the compiler/linker flags used to build Google Test and # Defines the compiler/linker flags used to build Google Test and
# Google Mock. You can tweak these definitions to suit your need. A # Google Mock. You can tweak these definitions to suit your need. A
# variable's value is empty before it's explicitly assigned to. # variable's value is empty before it's explicitly assigned to.
macro(config_compiler_and_linker) macro(config_compiler_and_linker)
# Note: pthreads on MinGW is not supported, even if available # Note: pthreads on MinGW is not supported, even if available
# instead, we use windows threading primitives # instead, we use windows threading primitives.
unset(GTEST_HAS_PTHREAD) unset(GTEST_HAS_PTHREAD)
if (NOT gtest_disable_pthreads AND NOT MINGW) if (NOT gtest_disable_pthreads AND NOT MINGW)
# Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT. # Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT.
@ -87,8 +79,8 @@ macro(config_compiler_and_linker)
set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1") set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1")
set(cxx_no_exception_flags "-EHs-c- -D_HAS_EXCEPTIONS=0") set(cxx_no_exception_flags "-EHs-c- -D_HAS_EXCEPTIONS=0")
set(cxx_no_rtti_flags "-GR-") set(cxx_no_rtti_flags "-GR-")
# Suppress "unreachable code" warning # Suppress "unreachable code" warning,
# http://stackoverflow.com/questions/3232669 explains the issue. # https://stackoverflow.com/questions/3232669 explains the issue.
set(cxx_base_flags "${cxx_base_flags} -wd4702") set(cxx_base_flags "${cxx_base_flags} -wd4702")
# Ensure MSVC treats source files as UTF-8 encoded. # Ensure MSVC treats source files as UTF-8 encoded.
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
@ -118,7 +110,7 @@ macro(config_compiler_and_linker)
set(cxx_exception_flags "-fexceptions") set(cxx_exception_flags "-fexceptions")
set(cxx_no_exception_flags "-fno-exceptions") set(cxx_no_exception_flags "-fno-exceptions")
# Until version 4.3.2, GCC doesn't define a macro to indicate # Until version 4.3.2, GCC doesn't define a macro to indicate
# whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI
# explicitly. # explicitly.
set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0") set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0")
set(cxx_strict_flags set(cxx_strict_flags
@ -135,7 +127,7 @@ macro(config_compiler_and_linker)
set(cxx_exception_flags "-qeh") set(cxx_exception_flags "-qeh")
set(cxx_no_exception_flags "-qnoeh") set(cxx_no_exception_flags "-qnoeh")
# Until version 9.0, Visual Age doesn't define a macro to indicate # Until version 9.0, Visual Age doesn't define a macro to indicate
# whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI
# explicitly. # explicitly.
set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0") set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "HP") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "HP")
@ -165,7 +157,7 @@ macro(config_compiler_and_linker)
set(cxx_strict "${cxx_default} ${cxx_strict_flags}") set(cxx_strict "${cxx_default} ${cxx_strict_flags}")
endmacro() endmacro()
# Defines the gtest & gtest_main libraries. User tests should link # Defines the gtest & gtest_main libraries. User tests should link
# with one of them. # with one of them.
function(cxx_library_with_type name type cxx_flags) function(cxx_library_with_type name type cxx_flags)
# type can be either STATIC or SHARED to denote a static or shared library. # type can be either STATIC or SHARED to denote a static or shared library.
@ -175,7 +167,7 @@ function(cxx_library_with_type name type cxx_flags)
set_target_properties(${name} set_target_properties(${name}
PROPERTIES PROPERTIES
COMPILE_FLAGS "${cxx_flags}") COMPILE_FLAGS "${cxx_flags}")
# Set the output directory for build artifacts # Set the output directory for build artifacts.
set_target_properties(${name} set_target_properties(${name}
PROPERTIES PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
@ -183,7 +175,7 @@ function(cxx_library_with_type name type cxx_flags)
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")
# make PDBs match library name # Make PDBs match library name.
get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX) get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX)
set_target_properties(${name} set_target_properties(${name}
PROPERTIES PROPERTIES
@ -196,23 +188,14 @@ function(cxx_library_with_type name type cxx_flags)
set_target_properties(${name} set_target_properties(${name}
PROPERTIES PROPERTIES
COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1") COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1")
if (NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") target_compile_definitions(${name} INTERFACE
target_compile_definitions(${name} INTERFACE $<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
$<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
endif()
endif() endif()
if (DEFINED GTEST_HAS_PTHREAD) if (DEFINED GTEST_HAS_PTHREAD)
if ("${CMAKE_VERSION}" VERSION_LESS "3.1.0") target_link_libraries(${name} PUBLIC Threads::Threads)
set(threads_spec ${CMAKE_THREAD_LIBS_INIT})
else()
set(threads_spec Threads::Threads)
endif()
target_link_libraries(${name} PUBLIC ${threads_spec})
endif() endif()
if (NOT "${CMAKE_VERSION}" VERSION_LESS "3.8") target_compile_features(${name} PUBLIC cxx_std_14)
target_compile_features(${name} PUBLIC cxx_std_14)
endif()
endfunction() endfunction()
######################################################################## ########################################################################
@ -229,7 +212,7 @@ endfunction()
# cxx_executable_with_flags(name cxx_flags libs srcs...) # cxx_executable_with_flags(name cxx_flags libs srcs...)
# #
# creates a named C++ executable that depends on the given libraries and # Creates a named C++ executable that depends on the given libraries and
# is built from the given source files with the given compiler flags. # is built from the given source files with the given compiler flags.
function(cxx_executable_with_flags name cxx_flags libs) function(cxx_executable_with_flags name cxx_flags libs)
add_executable(${name} ${ARGN}) add_executable(${name} ${ARGN})
@ -256,34 +239,19 @@ endfunction()
# cxx_executable(name dir lib srcs...) # cxx_executable(name dir lib srcs...)
# #
# creates a named target that depends on the given libs and is built # Creates a named target that depends on the given libs and is built
# from the given source files. dir/name.cc is implicitly included in # from the given source files. dir/name.cc is implicitly included in
# the source file list. # the source file list.
function(cxx_executable name dir libs) function(cxx_executable name dir libs)
cxx_executable_with_flags( cxx_executable_with_flags(
${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN}) ${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN})
endfunction() endfunction()
# CMP0094 policy enables finding a Python executable in the LOCATION order, as find_package(Python3)
# specified by the PATH environment variable.
if (POLICY CMP0094)
cmake_policy(SET CMP0094 NEW)
endif()
# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
if ("${CMAKE_VERSION}" VERSION_LESS "3.12.0")
find_package(PythonInterp)
set(PYTHONINTERP_FOUND ${PYTHONINTERP_FOUND} CACHE INTERNAL "")
set(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE} CACHE INTERNAL "")
else()
find_package(Python COMPONENTS Interpreter)
set(PYTHONINTERP_FOUND ${Python_Interpreter_FOUND} CACHE INTERNAL "")
set(PYTHON_EXECUTABLE ${Python_EXECUTABLE} CACHE INTERNAL "")
endif()
# cxx_test_with_flags(name cxx_flags libs srcs...) # cxx_test_with_flags(name cxx_flags libs srcs...)
# #
# creates a named C++ test that depends on the given libs and is built # Creates a named C++ test that depends on the given libs and is built
# from the given source files with the given compiler flags. # from the given source files with the given compiler flags.
function(cxx_test_with_flags name cxx_flags libs) function(cxx_test_with_flags name cxx_flags libs)
cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN}) cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN})
@ -292,8 +260,8 @@ endfunction()
# cxx_test(name libs srcs...) # cxx_test(name libs srcs...)
# #
# creates a named test target that depends on the given libs and is # Creates a named test target that depends on the given libs and is
# built from the given source files. Unlike cxx_test_with_flags, # built from the given source files. Unlike cxx_test_with_flags,
# test/name.cc is already implicitly included in the source file list. # test/name.cc is already implicitly included in the source file list.
function(cxx_test name libs) function(cxx_test name libs)
cxx_test_with_flags("${name}" "${cxx_default}" "${libs}" cxx_test_with_flags("${name}" "${cxx_default}" "${libs}"
@ -302,37 +270,25 @@ endfunction()
# py_test(name) # py_test(name)
# #
# creates a Python test with the given name whose main module is in # Creates a Python test with the given name whose main module is in
# test/name.py. It does nothing if Python is not installed. # test/name.py. It does nothing if Python is not installed.
function(py_test name) function(py_test name)
if (PYTHONINTERP_FOUND) if (NOT Python3_Interpreter_FOUND)
if ("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" VERSION_GREATER 3.1) return()
if (CMAKE_CONFIGURATION_TYPES) endif()
# Multi-configuration build generators as for Visual Studio save
# output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug, get_cmake_property(is_multi "GENERATOR_IS_MULTI_CONFIG")
# Release etc.), so we have to provide it here. set(build_dir "${CMAKE_CURRENT_BINARY_DIR}")
add_test(NAME ${name} if (is_multi)
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py set(build_dir "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>")
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN}) endif()
else (CMAKE_CONFIGURATION_TYPES)
# Single-configuration build generators like Makefile generators add_test(NAME ${name}
# don't have subdirs below CMAKE_CURRENT_BINARY_DIR. COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
add_test(NAME ${name} --build_dir=${build_dir} ${ARGN})
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN}) # Make the Python import path consistent between Bazel and CMake.
endif (CMAKE_CONFIGURATION_TYPES) set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})
else()
# ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can
# directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
# only at ctest runtime (by calling ctest -c <Configuration>), so
# we have to escape $ to delay variable substitution here.
add_test(NAME ${name}
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
endif()
# Make the Python import path consistent between Bazel and CMake.
set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})
endif(PYTHONINTERP_FOUND)
endfunction() endfunction()
# install_project(targets...) # install_project(targets...)
@ -341,21 +297,24 @@ endfunction()
function(install_project) function(install_project)
if(INSTALL_GTEST) if(INSTALL_GTEST)
install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/" install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/"
COMPONENT "${PROJECT_NAME}"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
# Install the project targets. # Install the project targets.
install(TARGETS ${ARGN} install(TARGETS ${ARGN}
EXPORT ${targets_export_name} EXPORT ${targets_export_name}
COMPONENT "${PROJECT_NAME}"
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")
if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
# Install PDBs # Install PDBs.
foreach(t ${ARGN}) foreach(t ${ARGN})
get_target_property(t_pdb_name ${t} COMPILE_PDB_NAME) get_target_property(t_pdb_name ${t} COMPILE_PDB_NAME)
get_target_property(t_pdb_name_debug ${t} COMPILE_PDB_NAME_DEBUG) get_target_property(t_pdb_name_debug ${t} COMPILE_PDB_NAME_DEBUG)
get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY) get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY)
install(FILES install(FILES
"${t_pdb_output_directory}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$<CONFIG:Debug>:${t_pdb_name_debug}>$<$<NOT:$<CONFIG:Debug>>:${t_pdb_name}>.pdb" "${t_pdb_output_directory}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$<CONFIG:Debug>:${t_pdb_name_debug}>$<$<NOT:$<CONFIG:Debug>>:${t_pdb_name}>.pdb"
COMPONENT "${PROJECT_NAME}"
DESTINATION ${CMAKE_INSTALL_LIBDIR} DESTINATION ${CMAKE_INSTALL_LIBDIR}
OPTIONAL) OPTIONAL)
endforeach() endforeach()
@ -366,6 +325,7 @@ function(install_project)
configure_file("${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in" configure_file("${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in"
"${configured_pc}" @ONLY) "${configured_pc}" @ONLY)
install(FILES "${configured_pc}" install(FILES "${configured_pc}"
COMPONENT "${PROJECT_NAME}"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
endforeach() endforeach()
endif() endif()

View File

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

View File

@ -43,6 +43,9 @@
// 1. foo::PrintTo(const T&, ostream*) // 1. foo::PrintTo(const T&, ostream*)
// 2. operator<<(ostream&, const T&) defined in either foo or the // 2. operator<<(ostream&, const T&) defined in either foo or the
// global namespace. // global namespace.
// * Prefer AbslStringify(..) to operator<<(..), per https://abseil.io/tips/215.
// * Define foo::PrintTo(..) if the type already has AbslStringify(..), but an
// alternative presentation in test results is of interest.
// //
// However if T is an STL-style container then it is printed element-wise // However if T is an STL-style container then it is printed element-wise
// unless foo::PrintTo(const T&, ostream*) is defined. Note that // unless foo::PrintTo(const T&, ostream*) is defined. Note that
@ -112,9 +115,17 @@
#include <utility> #include <utility>
#include <vector> #include <vector>
#ifdef GTEST_HAS_ABSL
#include "absl/strings/has_absl_stringify.h"
#include "absl/strings/str_cat.h"
#endif // GTEST_HAS_ABSL
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#if GTEST_INTERNAL_HAS_STD_SPAN
#include <span> // NOLINT
#endif // GTEST_INTERNAL_HAS_STD_SPAN
namespace testing { namespace testing {
// Definitions in the internal* namespaces are subject to change without notice. // Definitions in the internal* namespaces are subject to change without notice.
@ -124,13 +135,32 @@ namespace internal {
template <typename T> template <typename T>
void UniversalPrint(const T& value, ::std::ostream* os); void UniversalPrint(const T& value, ::std::ostream* os);
template <typename T>
struct IsStdSpan {
static constexpr bool value = false;
};
#if GTEST_INTERNAL_HAS_STD_SPAN
template <typename E>
struct IsStdSpan<std::span<E>> {
static constexpr bool value = true;
};
#endif // GTEST_INTERNAL_HAS_STD_SPAN
// Used to print an STL-style container when the user doesn't define // Used to print an STL-style container when the user doesn't define
// a PrintTo() for it. // a PrintTo() for it.
//
// NOTE: Since std::span does not have const_iterator until C++23, it would
// fail IsContainerTest before C++23. However, IsContainerTest only uses
// the presence of const_iterator to avoid treating iterators as containers
// because of iterator::iterator. Which means std::span satisfies the *intended*
// condition of IsContainerTest.
struct ContainerPrinter { struct ContainerPrinter {
template <typename T, template <typename T,
typename = typename std::enable_if< typename = typename std::enable_if<
(sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) && ((sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
!IsRecursiveContainer<T>::value>::type> !IsRecursiveContainer<T>::value) ||
IsStdSpan<T>::value>::type>
static void PrintValue(const T& container, std::ostream* os) { static void PrintValue(const T& container, std::ostream* os) {
const size_t kMaxCount = 32; // The maximum number of elements to print. const size_t kMaxCount = 32; // The maximum number of elements to print.
*os << '{'; *os << '{';
@ -260,6 +290,17 @@ struct ConvertibleToStringViewPrinter {
#endif #endif
}; };
#ifdef GTEST_HAS_ABSL
struct ConvertibleToAbslStringifyPrinter {
template <typename T,
typename = typename std::enable_if<
absl::HasAbslStringify<T>::value>::type> // NOLINT
static void PrintValue(const T& value, ::std::ostream* os) {
*os << absl::StrCat(value);
}
};
#endif // GTEST_HAS_ABSL
// Prints the given number of bytes in the given object to the given // Prints the given number of bytes in the given object to the given
// ostream. // ostream.
GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
@ -298,8 +339,8 @@ struct FindFirstPrinter<
// - Print containers (they have begin/end/etc). // - Print containers (they have begin/end/etc).
// - Print function pointers. // - Print function pointers.
// - Print object pointers. // - Print object pointers.
// - Use the stream operator, if available.
// - Print protocol buffers. // - Print protocol buffers.
// - Use the stream operator, if available.
// - Print types convertible to BiggestInt. // - Print types convertible to BiggestInt.
// - Print types convertible to StringView, if available. // - Print types convertible to StringView, if available.
// - Fallback to printing the raw bytes of the object. // - Fallback to printing the raw bytes of the object.
@ -308,6 +349,9 @@ void PrintWithFallback(const T& value, ::std::ostream* os) {
using Printer = typename FindFirstPrinter< using Printer = typename FindFirstPrinter<
T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter, T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
ProtobufPrinter, ProtobufPrinter,
#ifdef GTEST_HAS_ABSL
ConvertibleToAbslStringifyPrinter,
#endif // GTEST_HAS_ABSL
internal_stream_operator_without_lexical_name_lookup::StreamPrinter, internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter, ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter,
RawBytesPrinter, FallbackPrinter>::type; RawBytesPrinter, FallbackPrinter>::type;
@ -475,7 +519,7 @@ GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
inline void PrintTo(char16_t c, ::std::ostream* os) { inline void PrintTo(char16_t c, ::std::ostream* os) {
PrintTo(ImplicitCast_<char32_t>(c), os); PrintTo(ImplicitCast_<char32_t>(c), os);
} }
#ifdef __cpp_char8_t #ifdef __cpp_lib_char8_t
inline void PrintTo(char8_t c, ::std::ostream* os) { inline void PrintTo(char8_t c, ::std::ostream* os) {
PrintTo(ImplicitCast_<char32_t>(c), os); PrintTo(ImplicitCast_<char32_t>(c), os);
} }
@ -531,7 +575,7 @@ int AppropriateResolution(FloatType val) {
} else if (val >= 0.0001) { } else if (val >= 0.0001) {
mulfor6 = 1e9; mulfor6 = 1e9;
} }
if (static_cast<float>(static_cast<int32_t>(val * mulfor6 + 0.5)) / if (static_cast<FloatType>(static_cast<int32_t>(val * mulfor6 + 0.5)) /
mulfor6 == mulfor6 ==
val) val)
return 6; return 6;
@ -546,7 +590,7 @@ int AppropriateResolution(FloatType val) {
} else if (val >= 1e6) { // 1,000,000 to 9,999,999 } else if (val >= 1e6) { // 1,000,000 to 9,999,999
divfor6 = 10; divfor6 = 10;
} }
if (static_cast<float>(static_cast<int32_t>(val / divfor6 + 0.5)) * if (static_cast<FloatType>(static_cast<int32_t>(val / divfor6 + 0.5)) *
divfor6 == divfor6 ==
val) val)
return 6; return 6;
@ -588,7 +632,7 @@ inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
inline void PrintTo(unsigned char* s, ::std::ostream* os) { inline void PrintTo(unsigned char* s, ::std::ostream* os) {
PrintTo(ImplicitCast_<const void*>(s), os); PrintTo(ImplicitCast_<const void*>(s), os);
} }
#ifdef __cpp_char8_t #ifdef __cpp_lib_char8_t
// Overloads for u8 strings. // Overloads for u8 strings.
GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os); GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
inline void PrintTo(char8_t* s, ::std::ostream* os) { inline void PrintTo(char8_t* s, ::std::ostream* os) {
@ -908,7 +952,7 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
GTEST_API_ void UniversalPrintArray(const char* begin, size_t len, GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,
::std::ostream* os); ::std::ostream* os);
#ifdef __cpp_char8_t #ifdef __cpp_lib_char8_t
// This overload prints a (const) char8_t array compactly. // This overload prints a (const) char8_t array compactly.
GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len, GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
::std::ostream* os); ::std::ostream* os);

View File

@ -51,7 +51,6 @@
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <iomanip>
#include <limits> #include <limits>
#include <memory> #include <memory>
#include <ostream> #include <ostream>
@ -1055,6 +1054,10 @@ class GTEST_API_ TestEventListeners {
return default_xml_generator_; return default_xml_generator_;
} }
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
void SuppressEventForwarding(bool);
private: private:
friend class TestSuite; friend class TestSuite;
friend class TestInfo; friend class TestInfo;
@ -1084,7 +1087,6 @@ class GTEST_API_ TestEventListeners {
// Controls whether events will be forwarded by the repeater to the // Controls whether events will be forwarded by the repeater to the
// listeners in the list. // listeners in the list.
bool EventForwardingEnabled() const; bool EventForwardingEnabled() const;
void SuppressEventForwarding();
// The actual list of listeners. // The actual list of listeners.
internal::TestEventRepeater* repeater_; internal::TestEventRepeater* repeater_;
@ -1571,12 +1573,12 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
} }
::std::stringstream lhs_ss; ::std::stringstream lhs_ss;
lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) lhs_ss.precision(std::numeric_limits<RawType>::digits10 + 2);
<< lhs_value; lhs_ss << lhs_value;
::std::stringstream rhs_ss; ::std::stringstream rhs_ss;
rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) rhs_ss.precision(std::numeric_limits<RawType>::digits10 + 2);
<< rhs_value; rhs_ss << rhs_value;
return EqFailure(lhs_expression, rhs_expression, return EqFailure(lhs_expression, rhs_expression,
StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss), StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss),
@ -2098,8 +2100,8 @@ class GTEST_API_ ScopedTrace {
// Assuming that each thread maintains its own stack of traces. // Assuming that each thread maintains its own stack of traces.
// Therefore, a SCOPED_TRACE() would (correctly) only affect the // Therefore, a SCOPED_TRACE() would (correctly) only affect the
// assertions in its own thread. // assertions in its own thread.
#define SCOPED_TRACE(message) \ #define SCOPED_TRACE(message) \
::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \ const ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \
__FILE__, __LINE__, (message)) __FILE__, __LINE__, (message))
// Compile-time assertion for type equality. // Compile-time assertion for type equality.

View File

@ -52,9 +52,7 @@ GTEST_DECLARE_string_(internal_run_death_test);
namespace testing { namespace testing {
namespace internal { namespace internal {
// Names of the flags (needed for parsing Google Test flags). // Name of the flag (needed for parsing Google Test flag).
const char kDeathTestStyleFlag[] = "death_test_style";
const char kDeathTestUseFork[] = "death_test_use_fork";
const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
#ifdef GTEST_HAS_DEATH_TEST #ifdef GTEST_HAS_DEATH_TEST

View File

@ -58,7 +58,6 @@
#include <cstdint> #include <cstdint>
#include <functional> #include <functional>
#include <iomanip>
#include <limits> #include <limits>
#include <map> #include <map>
#include <set> #include <set>
@ -79,7 +78,7 @@
// //
// will result in the token foo__LINE__, instead of foo followed by // will result in the token foo__LINE__, instead of foo followed by
// the current line number. For more details, see // the current line number. For more details, see
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 // https://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar
@ -170,7 +169,7 @@ namespace edit_distance {
// All edits cost the same, with replace having lower priority than // All edits cost the same, with replace having lower priority than
// add/remove. // add/remove.
// Simple implementation of the Wagner-Fischer algorithm. // Simple implementation of the Wagner-Fischer algorithm.
// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm // See https://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
enum EditType { kMatch, kAdd, kRemove, kReplace }; enum EditType { kMatch, kAdd, kRemove, kReplace };
GTEST_API_ std::vector<EditType> CalculateOptimalEdits( GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
const std::vector<size_t>& left, const std::vector<size_t>& right); const std::vector<size_t>& left, const std::vector<size_t>& right);
@ -237,7 +236,7 @@ GTEST_API_ std::string GetBoolAssertionFailureMessage(
// For double, there are 11 exponent bits and 52 fraction bits. // For double, there are 11 exponent bits and 52 fraction bits.
// //
// More details can be found at // More details can be found at
// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. // https://en.wikipedia.org/wiki/IEEE_floating-point_standard.
// //
// Template parameter: // Template parameter:
// //
@ -282,7 +281,7 @@ class FloatingPoint {
// bits. Therefore, 4 should be enough for ordinary use. // bits. Therefore, 4 should be enough for ordinary use.
// //
// See the following article for more details on ULP: // See the following article for more details on ULP:
// http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ // https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
static const uint32_t kMaxUlps = 4; static const uint32_t kMaxUlps = 4;
// Constructs a FloatingPoint from a raw floating-point number. // Constructs a FloatingPoint from a raw floating-point number.
@ -363,7 +362,7 @@ class FloatingPoint {
// N - 1 (the biggest number representable using // N - 1 (the biggest number representable using
// sign-and-magnitude) is represented by 2N - 1. // sign-and-magnitude) is represented by 2N - 1.
// //
// Read http://en.wikipedia.org/wiki/Signed_number_representations // Read https://en.wikipedia.org/wiki/Signed_number_representations
// for more details on signed number representations. // for more details on signed number representations.
static Bits SignAndMagnitudeToBiased(const Bits& sam) { static Bits SignAndMagnitudeToBiased(const Bits& sam) {
if (kSignBitMask & sam) { if (kSignBitMask & sam) {
@ -1497,19 +1496,20 @@ class NeverThrown {
gtest_ar_, text, #actual, #expected) \ gtest_ar_, text, #actual, #expected) \
.c_str()) .c_str())
#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
if (::testing::internal::AlwaysTrue()) { \ if (::testing::internal::AlwaysTrue()) { \
::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ const ::testing::internal::HasNewFatalFailureHelper \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ gtest_fatal_failure_checker; \
if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
} \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
} else \ } \
GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \ } else /* NOLINT */ \
: fail("Expected: " #statement \ GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \
" doesn't generate new fatal " \ : fail("Expected: " #statement \
"failures in the current thread.\n" \ " doesn't generate new fatal " \
"failures in the current thread.\n" \
" Actual: it does.") " Actual: it does.")
// Expands to the name of the class that implements the given test. // Expands to the name of the class that implements the given test.

View File

@ -584,7 +584,9 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
GTEST_CHECK_(IsValidParamName(param_name)) GTEST_CHECK_(IsValidParamName(param_name))
<< "Parameterized test name '" << param_name << "Parameterized test name '" << param_name
<< "' is invalid, in " << file << " line " << line << std::endl; << "' is invalid (contains spaces, dashes, or any "
"non-alphanumeric characters other than underscores), in "
<< file << " line " << line << "" << std::endl;
GTEST_CHECK_(test_param_names.count(param_name) == 0) GTEST_CHECK_(test_param_names.count(param_name) == 0)
<< "Duplicate parameterized test name '" << param_name << "', in " << "Duplicate parameterized test name '" << param_name << "', in "

View File

@ -113,6 +113,10 @@
#define GTEST_OS_XTENSA 1 #define GTEST_OS_XTENSA 1
#elif defined(__hexagon__) #elif defined(__hexagon__)
#define GTEST_OS_QURT 1 #define GTEST_OS_QURT 1
#elif defined(CPU_QN9090) || defined(CPU_QN9090HN)
#define GTEST_OS_NXP_QN9090 1
#elif defined(NRF52)
#define GTEST_OS_NRF52 1
#endif // __CYGWIN__ #endif // __CYGWIN__
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_

View File

@ -208,6 +208,8 @@
// or // or
// UniversalPrinter<absl::optional> // UniversalPrinter<absl::optional>
// specializations. Always defined to 0 or 1. // specializations. Always defined to 0 or 1.
// GTEST_INTERNAL_HAS_STD_SPAN - for enabling UniversalPrinter<std::span>
// specializations. Always defined to 0 or 1
// GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
// Matcher<absl::string_view> // Matcher<absl::string_view>
// specializations. Always defined to 0 or 1. // specializations. Always defined to 0 or 1.
@ -220,7 +222,6 @@
// GTEST_HAS_ALT_PATH_SEP_ - Always defined to 0 or 1. // GTEST_HAS_ALT_PATH_SEP_ - Always defined to 0 or 1.
// GTEST_WIDE_STRING_USES_UTF16_ - Always defined to 0 or 1. // GTEST_WIDE_STRING_USES_UTF16_ - Always defined to 0 or 1.
// GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Always defined to 0 or 1. // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Always defined to 0 or 1.
// GTEST_HAS_DOWNCAST_ - Always defined to 0 or 1.
// GTEST_HAS_NOTIFICATION_- Always defined to 0 or 1. // GTEST_HAS_NOTIFICATION_- Always defined to 0 or 1.
// //
// Synchronization: // Synchronization:
@ -280,6 +281,22 @@
#error C++ versions less than C++14 are not supported. #error C++ versions less than C++14 are not supported.
#endif #endif
// MSVC >= 19.11 (VS 2017 Update 3) supports __has_include.
#ifdef __has_include
#define GTEST_INTERNAL_HAS_INCLUDE __has_include
#else
#define GTEST_INTERNAL_HAS_INCLUDE(...) 0
#endif
// Detect C++ feature test macros as gracefully as possible.
// MSVC >= 19.15, Clang >= 3.4.1, and GCC >= 4.1.2 support feature test macros.
#if GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L && \
(!defined(__has_include) || GTEST_INTERNAL_HAS_INCLUDE(<version>))
#include <version> // C++20 and later
#elif (!defined(__has_include) || GTEST_INTERNAL_HAS_INCLUDE(<ciso646>))
#include <ciso646> // Pre-C++20
#endif
#include <ctype.h> // for isspace, etc #include <ctype.h> // for isspace, etc
#include <stddef.h> // for ptrdiff_t #include <stddef.h> // for ptrdiff_t
#include <stdio.h> #include <stdio.h>
@ -313,10 +330,6 @@
#include "gtest/internal/custom/gtest-port.h" #include "gtest/internal/custom/gtest-port.h"
#include "gtest/internal/gtest-port-arch.h" #include "gtest/internal/gtest-port-arch.h"
#ifndef GTEST_HAS_DOWNCAST_
#define GTEST_HAS_DOWNCAST_ 0
#endif
#ifndef GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ #ifndef GTEST_HAS_MUTEX_AND_THREAD_LOCAL_
#define GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ 0 #define GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ 0
#endif #endif
@ -505,7 +518,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#if (!(defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_CYGWIN) || \ #if (!(defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_CYGWIN) || \
defined(GTEST_OS_SOLARIS) || defined(GTEST_OS_HAIKU) || \ defined(GTEST_OS_SOLARIS) || defined(GTEST_OS_HAIKU) || \
defined(GTEST_OS_ESP32) || defined(GTEST_OS_ESP8266) || \ defined(GTEST_OS_ESP32) || defined(GTEST_OS_ESP8266) || \
defined(GTEST_OS_XTENSA) || defined(GTEST_OS_QURT))) defined(GTEST_OS_XTENSA) || defined(GTEST_OS_QURT) || \
defined(GTEST_OS_NXP_QN9090) || defined(GTEST_OS_NRF52)))
#define GTEST_HAS_STD_WSTRING 1 #define GTEST_HAS_STD_WSTRING 1
#else #else
#define GTEST_HAS_STD_WSTRING 0 #define GTEST_HAS_STD_WSTRING 0
@ -613,7 +627,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
// Determines whether clone(2) is supported. // Determines whether clone(2) is supported.
// Usually it will only be available on Linux, excluding // Usually it will only be available on Linux, excluding
// Linux on the Itanium architecture. // Linux on the Itanium architecture.
// Also see http://linux.die.net/man/2/clone. // Also see https://linux.die.net/man/2/clone.
#ifndef GTEST_HAS_CLONE #ifndef GTEST_HAS_CLONE
// The user didn't tell us, so we need to figure it out. // The user didn't tell us, so we need to figure it out.
@ -831,9 +845,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#ifndef GTEST_API_ #ifndef GTEST_API_
#ifdef _MSC_VER #ifdef _MSC_VER
#if GTEST_LINKED_AS_SHARED_LIBRARY #if defined(GTEST_LINKED_AS_SHARED_LIBRARY) && GTEST_LINKED_AS_SHARED_LIBRARY
#define GTEST_API_ __declspec(dllimport) #define GTEST_API_ __declspec(dllimport)
#elif GTEST_CREATE_SHARED_LIBRARY #elif defined(GTEST_CREATE_SHARED_LIBRARY) && GTEST_CREATE_SHARED_LIBRARY
#define GTEST_API_ __declspec(dllexport) #define GTEST_API_ __declspec(dllexport)
#endif #endif
#elif GTEST_HAVE_ATTRIBUTE_(visibility) #elif GTEST_HAVE_ATTRIBUTE_(visibility)
@ -924,9 +938,11 @@ using std::tuple_size;
namespace internal { namespace internal {
// A secret type that Google Test users don't know about. It has no // A secret type that Google Test users don't know about. It has no
// definition on purpose. Therefore it's impossible to create a // accessible constructors on purpose. Therefore it's impossible to create a
// Secret object, which is what we want. // Secret object, which is what we want.
class Secret; class Secret {
Secret(const Secret&) = delete;
};
// A helper for suppressing warnings on constant condition. It just // A helper for suppressing warnings on constant condition. It just
// returns 'condition'. // returns 'condition'.
@ -1143,47 +1159,6 @@ inline To ImplicitCast_(To x) {
return x; return x;
} }
// When you upcast (that is, cast a pointer from type Foo to type
// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts
// always succeed. When you downcast (that is, cast a pointer from
// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
// how do you know the pointer is really of type SubclassOfFoo? It
// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
// when you downcast, you should use this macro. In debug mode, we
// use dynamic_cast<> to double-check the downcast is legal (we die
// if it's not). In normal mode, we do the efficient static_cast<>
// instead. Thus, it's important to test in debug mode to make sure
// the cast is legal!
// This is the only place in the code we should use dynamic_cast<>.
// In particular, you SHOULDN'T be using dynamic_cast<> in order to
// do RTTI (eg code like this:
// if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
// if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
// You should design the code some other way not to need this.
//
// This relatively ugly name is intentional. It prevents clashes with
// similar functions users may have (e.g., down_cast). The internal
// namespace alone is not enough because the function can be found by ADL.
template <typename To, typename From> // use like this: DownCast_<T*>(foo);
inline To DownCast_(From* f) { // so we only accept pointers
// Ensures that To is a sub-type of From *. This test is here only
// for compile-time type checking, and has no overhead in an
// optimized build at run-time, as it will be optimized away
// completely.
GTEST_INTENTIONAL_CONST_COND_PUSH_()
if (false) {
GTEST_INTENTIONAL_CONST_COND_POP_()
const To to = nullptr;
::testing::internal::ImplicitCast_<From*>(to);
}
#if GTEST_HAS_RTTI
// RTTI: debug mode only!
GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
#endif
return static_cast<To>(f);
}
// Downcasts the pointer of type Base to Derived. // Downcasts the pointer of type Base to Derived.
// Derived must be a subclass of Base. The parameter MUST // Derived must be a subclass of Base. The parameter MUST
// point to a class of type Derived, not any subclass of it. // point to a class of type Derived, not any subclass of it.
@ -1191,17 +1166,12 @@ inline To DownCast_(From* f) { // so we only accept pointers
// check to enforce this. // check to enforce this.
template <class Derived, class Base> template <class Derived, class Base>
Derived* CheckedDowncastToActualType(Base* base) { Derived* CheckedDowncastToActualType(Base* base) {
static_assert(std::is_base_of<Base, Derived>::value,
"target type not derived from source type");
#if GTEST_HAS_RTTI #if GTEST_HAS_RTTI
GTEST_CHECK_(typeid(*base) == typeid(Derived)); GTEST_CHECK_(base == nullptr || dynamic_cast<Derived*>(base) != nullptr);
#endif
#if GTEST_HAS_DOWNCAST_
return ::down_cast<Derived*>(base);
#elif GTEST_HAS_RTTI
return dynamic_cast<Derived*>(base); // NOLINT
#else
return static_cast<Derived*>(base); // Poor man's downcast.
#endif #endif
return static_cast<Derived*>(base);
} }
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
@ -1995,7 +1965,7 @@ inline bool IsUpper(char ch) {
inline bool IsXDigit(char ch) { inline bool IsXDigit(char ch) {
return isxdigit(static_cast<unsigned char>(ch)) != 0; return isxdigit(static_cast<unsigned char>(ch)) != 0;
} }
#ifdef __cpp_char8_t #ifdef __cpp_lib_char8_t
inline bool IsXDigit(char8_t ch) { inline bool IsXDigit(char8_t ch) {
return isxdigit(static_cast<unsigned char>(ch)) != 0; return isxdigit(static_cast<unsigned char>(ch)) != 0;
} }
@ -2397,9 +2367,9 @@ using Any = ::absl::any;
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
#else #else
#ifdef __has_include #if defined(__cpp_lib_any) || (GTEST_INTERNAL_HAS_INCLUDE(<any>) && \
#if __has_include(<any>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L && \ GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L && \
(!defined(_MSC_VER) || GTEST_HAS_RTTI) (!defined(_MSC_VER) || GTEST_HAS_RTTI))
// Otherwise for C++17 and higher use std::any for UniversalPrinter<> // Otherwise for C++17 and higher use std::any for UniversalPrinter<>
// specializations. // specializations.
#define GTEST_INTERNAL_HAS_ANY 1 #define GTEST_INTERNAL_HAS_ANY 1
@ -2411,8 +2381,7 @@ using Any = ::std::any;
} // namespace testing } // namespace testing
// The case where absl is configured NOT to alias std::any is not // The case where absl is configured NOT to alias std::any is not
// supported. // supported.
#endif // __has_include(<any>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L #endif // __cpp_lib_any
#endif // __has_include
#endif // GTEST_HAS_ABSL #endif // GTEST_HAS_ABSL
#ifndef GTEST_INTERNAL_HAS_ANY #ifndef GTEST_INTERNAL_HAS_ANY
@ -2432,8 +2401,8 @@ inline ::absl::nullopt_t Nullopt() { return ::absl::nullopt; }
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
#else #else
#ifdef __has_include #if defined(__cpp_lib_optional) || (GTEST_INTERNAL_HAS_INCLUDE(<optional>) && \
#if __has_include(<optional>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L)
// Otherwise for C++17 and higher use std::optional for UniversalPrinter<> // Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
// specializations. // specializations.
#define GTEST_INTERNAL_HAS_OPTIONAL 1 #define GTEST_INTERNAL_HAS_OPTIONAL 1
@ -2447,14 +2416,22 @@ inline ::std::nullopt_t Nullopt() { return ::std::nullopt; }
} // namespace testing } // namespace testing
// The case where absl is configured NOT to alias std::optional is not // The case where absl is configured NOT to alias std::optional is not
// supported. // supported.
#endif // __has_include(<optional>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L #endif // __cpp_lib_optional
#endif // __has_include
#endif // GTEST_HAS_ABSL #endif // GTEST_HAS_ABSL
#ifndef GTEST_INTERNAL_HAS_OPTIONAL #ifndef GTEST_INTERNAL_HAS_OPTIONAL
#define GTEST_INTERNAL_HAS_OPTIONAL 0 #define GTEST_INTERNAL_HAS_OPTIONAL 0
#endif #endif
#if defined(__cpp_lib_span) || (GTEST_INTERNAL_HAS_INCLUDE(<span>) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 202002L)
#define GTEST_INTERNAL_HAS_STD_SPAN 1
#endif // __cpp_lib_span
#ifndef GTEST_INTERNAL_HAS_STD_SPAN
#define GTEST_INTERNAL_HAS_STD_SPAN 0
#endif
#ifdef GTEST_HAS_ABSL #ifdef GTEST_HAS_ABSL
// Always use absl::string_view for Matcher<> specializations if googletest // Always use absl::string_view for Matcher<> specializations if googletest
// is built with absl support. // is built with absl support.
@ -2466,8 +2443,9 @@ using StringView = ::absl::string_view;
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
#else #else
#ifdef __has_include #if defined(__cpp_lib_string_view) || \
#if __has_include(<string_view>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L (GTEST_INTERNAL_HAS_INCLUDE(<string_view>) && \
GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L)
// Otherwise for C++17 and higher use std::string_view for Matcher<> // Otherwise for C++17 and higher use std::string_view for Matcher<>
// specializations. // specializations.
#define GTEST_INTERNAL_HAS_STRING_VIEW 1 #define GTEST_INTERNAL_HAS_STRING_VIEW 1
@ -2479,9 +2457,7 @@ using StringView = ::std::string_view;
} // namespace testing } // namespace testing
// The case where absl is configured NOT to alias std::string_view is not // The case where absl is configured NOT to alias std::string_view is not
// supported. // supported.
#endif // __has_include(<string_view>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= #endif // __cpp_lib_string_view
// 201703L
#endif // __has_include
#endif // GTEST_HAS_ABSL #endif // GTEST_HAS_ABSL
#ifndef GTEST_INTERNAL_HAS_STRING_VIEW #ifndef GTEST_INTERNAL_HAS_STRING_VIEW
@ -2500,8 +2476,8 @@ using Variant = ::absl::variant<T...>;
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
#else #else
#ifdef __has_include #if defined(__cpp_lib_variant) || (GTEST_INTERNAL_HAS_INCLUDE(<variant>) && \
#if __has_include(<variant>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L)
// Otherwise for C++17 and higher use std::variant for UniversalPrinter<> // Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
// specializations. // specializations.
#define GTEST_INTERNAL_HAS_VARIANT 1 #define GTEST_INTERNAL_HAS_VARIANT 1
@ -2513,16 +2489,16 @@ using Variant = ::std::variant<T...>;
} // namespace internal } // namespace internal
} // namespace testing } // namespace testing
// The case where absl is configured NOT to alias std::variant is not supported. // The case where absl is configured NOT to alias std::variant is not supported.
#endif // __has_include(<variant>) && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L #endif // __cpp_lib_variant
#endif // __has_include
#endif // GTEST_HAS_ABSL #endif // GTEST_HAS_ABSL
#ifndef GTEST_INTERNAL_HAS_VARIANT #ifndef GTEST_INTERNAL_HAS_VARIANT
#define GTEST_INTERNAL_HAS_VARIANT 0 #define GTEST_INTERNAL_HAS_VARIANT 0
#endif #endif
#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ #if (defined(__cpp_constexpr) && !defined(__cpp_inline_variables)) || \
GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L (defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L)
#define GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL 1 #define GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL 1
#endif #endif

View File

@ -783,7 +783,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) + StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
// size_t has the same width as pointers on both 32-bit and 64-bit // size_t has the same width as pointers on both 32-bit and 64-bit
// Windows platforms. // Windows platforms.
// See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. // See https://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
"|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" + "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" +
StreamableToString(reinterpret_cast<size_t>(event_handle_.Get())); StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
@ -1128,7 +1128,7 @@ DeathTest::TestRole NoExecDeathTest::AssumeRole() {
LogToStderr(); LogToStderr();
// Event forwarding to the listeners of event listener API mush be shut // Event forwarding to the listeners of event listener API mush be shut
// down in death test subprocesses. // down in death test subprocesses.
GetUnitTestImpl()->listeners()->SuppressEventForwarding(); GetUnitTestImpl()->listeners()->SuppressEventForwarding(true);
g_in_fast_death_test_child = true; g_in_fast_death_test_child = true;
return EXECUTE_TEST; return EXECUTE_TEST;
} else { } else {

View File

@ -102,7 +102,8 @@ FilePath FilePath::GetCurrentDir() {
#if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \ #if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \
defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \ defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \
defined(GTEST_OS_ESP32) || defined(GTEST_OS_XTENSA) || \ defined(GTEST_OS_ESP32) || defined(GTEST_OS_XTENSA) || \
defined(GTEST_OS_QURT) defined(GTEST_OS_QURT) || defined(GTEST_OS_NXP_QN9090) || \
defined(GTEST_OS_NRF52)
// These platforms do not have a current directory, so we just return // These platforms do not have a current directory, so we just return
// something reasonable. // something reasonable.
return FilePath(kCurrentDirectoryString); return FilePath(kCurrentDirectoryString);
@ -335,7 +336,7 @@ bool FilePath::CreateDirectoriesRecursively() const {
return false; return false;
} }
if (pathname_.length() == 0 || pathname_ == kCurrentDirectoryString || this->DirectoryExists()) { if (pathname_.empty() || pathname_ == kCurrentDirectoryString || this->DirectoryExists()) {
return true; return true;
} }
@ -356,7 +357,8 @@ bool FilePath::CreateFolder() const {
#elif defined(GTEST_OS_WINDOWS) #elif defined(GTEST_OS_WINDOWS)
int result = _mkdir(pathname_.c_str()); int result = _mkdir(pathname_.c_str());
#elif defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \ #elif defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \
defined(GTEST_OS_QURT) defined(GTEST_OS_QURT) || defined(GTEST_OS_NXP_QN9090) || \
defined(GTEST_OS_NRF52)
// do nothing // do nothing
int result = 0; int result = 0;
#else #else

View File

@ -312,7 +312,7 @@ void ShuffleRange(internal::Random* random, int begin, int end,
<< begin << ", " << size << "]."; << begin << ", " << size << "].";
// Fisher-Yates shuffle, from // Fisher-Yates shuffle, from
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle // https://en.wikipedia.org/wiki/Fisher-Yates_shuffle
for (int range_width = end - begin; range_width >= 2; range_width--) { for (int range_width = end - begin; range_width >= 2; range_width--) {
const int last_in_range = begin + range_width - 1; const int last_in_range = begin + range_width - 1;
const int selected = const int selected =
@ -387,10 +387,10 @@ class GTEST_API_ UnitTestOptions {
#ifdef GTEST_OS_WINDOWS #ifdef GTEST_OS_WINDOWS
// Function for supporting the gtest_catch_exception flag. // Function for supporting the gtest_catch_exception flag.
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // Returns EXCEPTION_EXECUTE_HANDLER if given SEH exception was handled, or
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // EXCEPTION_CONTINUE_SEARCH otherwise.
// This function is useful as an __except condition. // This function is useful as an __except condition.
static int GTestShouldProcessSEH(DWORD exception_code); static int GTestProcessSEH(DWORD seh_code, const char* location);
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
// Returns true if "name" matches the ':' separated list of glob-style // Returns true if "name" matches the ':' separated list of glob-style
@ -672,7 +672,7 @@ class GTEST_API_ UnitTestImpl {
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc, internal::TearDownTestSuiteFunc tear_down_tc,
TestInfo* test_info) { TestInfo* test_info) {
#ifdef GTEST_HAS_DEATH_TEST #if GTEST_HAS_FILE_SYSTEM
// In order to support thread-safe death tests, we need to // In order to support thread-safe death tests, we need to
// remember the original working directory when the test program // remember the original working directory when the test program
// was first invoked. We cannot do this in RUN_ALL_TESTS(), as // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
@ -685,7 +685,7 @@ class GTEST_API_ UnitTestImpl {
GTEST_CHECK_(!original_working_dir_.IsEmpty()) GTEST_CHECK_(!original_working_dir_.IsEmpty())
<< "Failed to get the current working directory."; << "Failed to get the current working directory.";
} }
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_FILE_SYSTEM
GetTestSuite(test_info->test_suite_name(), test_info->type_param(), GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
set_up_tc, tear_down_tc) set_up_tc, tear_down_tc)

View File

@ -158,13 +158,13 @@ size_t GetThreadCount() {
// we cannot detect it. // we cannot detect it.
size_t GetThreadCount() { size_t GetThreadCount() {
int mib[] = { int mib[] = {
CTL_KERN, CTL_KERN,
KERN_PROC, KERN_PROC,
KERN_PROC_PID, KERN_PROC_PID,
getpid(), getpid(),
#ifdef GTEST_OS_NETBSD #ifdef GTEST_OS_NETBSD
sizeof(struct kinfo_proc), sizeof(struct kinfo_proc),
1, 1,
#endif #endif
}; };
u_int miblen = sizeof(mib) / sizeof(mib[0]); u_int miblen = sizeof(mib) / sizeof(mib[0]);
@ -697,13 +697,24 @@ bool RE::PartialMatch(const char* str, const RE& re) {
void RE::Init(const char* regex) { void RE::Init(const char* regex) {
pattern_ = regex; pattern_ = regex;
// NetBSD (and Android, which takes its regex implemntation from NetBSD) does
// not include the GNU regex extensions (such as Perl style character classes
// like \w) in REG_EXTENDED. REG_EXTENDED is only specified to include the
// [[:alpha:]] style character classes. Enable REG_GNU wherever it is defined
// so users can use those extensions.
#if defined(REG_GNU)
constexpr int reg_flags = REG_EXTENDED | REG_GNU;
#else
constexpr int reg_flags = REG_EXTENDED;
#endif
// Reserves enough bytes to hold the regular expression used for a // Reserves enough bytes to hold the regular expression used for a
// full match. // full match.
const size_t full_regex_len = strlen(regex) + 10; const size_t full_regex_len = strlen(regex) + 10;
char* const full_pattern = new char[full_regex_len]; char* const full_pattern = new char[full_regex_len];
snprintf(full_pattern, full_regex_len, "^(%s)$", regex); snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; is_valid_ = regcomp(&full_regex_, full_pattern, reg_flags) == 0;
// We want to call regcomp(&partial_regex_, ...) even if the // We want to call regcomp(&partial_regex_, ...) even if the
// previous expression returns false. Otherwise partial_regex_ may // previous expression returns false. Otherwise partial_regex_ may
// not be properly initialized can may cause trouble when it's // not be properly initialized can may cause trouble when it's
@ -714,7 +725,7 @@ void RE::Init(const char* regex) {
// regex. We change it to an equivalent form "()" to be safe. // regex. We change it to an equivalent form "()" to be safe.
if (is_valid_) { if (is_valid_) {
const char* const partial_regex = (*regex == '\0') ? "()" : regex; const char* const partial_regex = (*regex == '\0') ? "()" : regex;
is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; is_valid_ = regcomp(&partial_regex_, partial_regex, reg_flags) == 0;
} }
EXPECT_TRUE(is_valid_) EXPECT_TRUE(is_valid_)
<< "Regular expression \"" << regex << "Regular expression \"" << regex
@ -1028,6 +1039,16 @@ GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
namespace {
#if defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_IOS)
bool EndsWithPathSeparator(const std::string& path) {
return !path.empty() && path.back() == GTEST_PATH_SEP_[0];
}
#endif
} // namespace
// Object that captures an output stream (stdout/stderr). // Object that captures an output stream (stdout/stderr).
class CapturedStream { class CapturedStream {
public: public:
@ -1064,7 +1085,13 @@ class CapturedStream {
// The location /data/local/tmp is directly accessible from native code. // The location /data/local/tmp is directly accessible from native code.
// '/sdcard' and other variants cannot be relied on, as they are not // '/sdcard' and other variants cannot be relied on, as they are not
// guaranteed to be mounted, or may have a delay in mounting. // guaranteed to be mounted, or may have a delay in mounting.
name_template = "/data/local/tmp/"; //
// However, prefer using the TMPDIR environment variable if set, as newer
// devices may have /data/local/tmp read-only.
name_template = TempDir();
if (!EndsWithPathSeparator(name_template))
name_template.push_back(GTEST_PATH_SEP_[0]);
#elif defined(GTEST_OS_IOS) #elif defined(GTEST_OS_IOS)
char user_temp_dir[PATH_MAX + 1]; char user_temp_dir[PATH_MAX + 1];
@ -1084,7 +1111,7 @@ class CapturedStream {
::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir, sizeof(user_temp_dir)); ::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir, sizeof(user_temp_dir));
name_template = user_temp_dir; name_template = user_temp_dir;
if (name_template.back() != GTEST_PATH_SEP_[0]) if (!EndsWithPathSeparator(name_template))
name_template.push_back(GTEST_PATH_SEP_[0]); name_template.push_back(GTEST_PATH_SEP_[0]);
#else #else
name_template = "/tmp/"; name_template = "/tmp/";

View File

@ -216,7 +216,7 @@ static const char* GetCharWidthPrefix(signed char) { return ""; }
static const char* GetCharWidthPrefix(unsigned char) { return ""; } static const char* GetCharWidthPrefix(unsigned char) { return ""; }
#ifdef __cpp_char8_t #ifdef __cpp_lib_char8_t
static const char* GetCharWidthPrefix(char8_t) { return "u8"; } static const char* GetCharWidthPrefix(char8_t) { return "u8"; }
#endif #endif
@ -232,7 +232,7 @@ static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
return PrintAsStringLiteralTo(ToChar32(c), os); return PrintAsStringLiteralTo(ToChar32(c), os);
} }
#ifdef __cpp_char8_t #ifdef __cpp_lib_char8_t
static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) { static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
return PrintAsStringLiteralTo(ToChar32(c), os); return PrintAsStringLiteralTo(ToChar32(c), os);
} }
@ -395,7 +395,7 @@ void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os); UniversalPrintCharArray(begin, len, os);
} }
#ifdef __cpp_char8_t #ifdef __cpp_lib_char8_t
// Prints a (const) char8_t array of 'len' elements, starting at address // Prints a (const) char8_t array of 'len' elements, starting at address
// 'begin'. // 'begin'.
void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) { void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
@ -438,7 +438,7 @@ void PrintCStringTo(const Char* s, ostream* os) {
void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); } void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
#ifdef __cpp_char8_t #ifdef __cpp_lib_char8_t
void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); } void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
#endif #endif

View File

@ -43,6 +43,7 @@
#include <algorithm> #include <algorithm>
#include <chrono> // NOLINT #include <chrono> // NOLINT
#include <cmath> #include <cmath>
#include <csignal> // NOLINT: raise(3) is used on some platforms
#include <cstdint> #include <cstdint>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
@ -863,30 +864,39 @@ bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,
} }
#if GTEST_HAS_SEH #if GTEST_HAS_SEH
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the static std::string FormatSehExceptionMessage(DWORD exception_code,
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. const char* location) {
// This function is useful as an __except condition. Message message;
int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { message << "SEH exception with code 0x" << std::setbase(16) << exception_code
<< std::setbase(10) << " thrown in " << location << ".";
return message.GetString();
}
int UnitTestOptions::GTestProcessSEH(DWORD seh_code, const char* location) {
// Google Test should handle a SEH exception if: // Google Test should handle a SEH exception if:
// 1. the user wants it to, AND // 1. the user wants it to, AND
// 2. this is not a breakpoint exception, AND // 2. this is not a breakpoint exception or stack overflow, AND
// 3. this is not a C++ exception (VC++ implements them via SEH, // 3. this is not a C++ exception (VC++ implements them via SEH,
// apparently). // apparently).
// //
// SEH exception code for C++ exceptions. // SEH exception code for C++ exceptions.
// (see http://support.microsoft.com/kb/185294 for more information). // (see https://support.microsoft.com/kb/185294 for more information).
const DWORD kCxxExceptionCode = 0xe06d7363; const DWORD kCxxExceptionCode = 0xe06d7363;
bool should_handle = true; if (!GTEST_FLAG_GET(catch_exceptions) || seh_code == kCxxExceptionCode ||
seh_code == EXCEPTION_BREAKPOINT ||
seh_code == EXCEPTION_STACK_OVERFLOW) {
return EXCEPTION_CONTINUE_SEARCH; // Don't handle these exceptions
}
if (!GTEST_FLAG_GET(catch_exceptions)) internal::ReportFailureInUnknownLocation(
should_handle = false; TestPartResult::kFatalFailure,
else if (exception_code == EXCEPTION_BREAKPOINT) FormatSehExceptionMessage(seh_code, location) +
should_handle = false; "\n"
else if (exception_code == kCxxExceptionCode) "Stack trace:\n" +
should_handle = false; ::testing::internal::GetCurrentOsStackTraceExceptTop(1));
return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; return EXCEPTION_EXECUTE_HANDLER;
} }
#endif // GTEST_HAS_SEH #endif // GTEST_HAS_SEH
@ -2553,23 +2563,6 @@ bool Test::HasSameFixtureClass() {
return true; return true;
} }
#if GTEST_HAS_SEH
// Adds an "exception thrown" fatal failure to the current test. This
// function returns its result via an output parameter pointer because VC++
// prohibits creation of objects with destructors on stack in functions
// using __try (see error C2712).
static std::string* FormatSehExceptionMessage(DWORD exception_code,
const char* location) {
Message message;
message << "SEH exception with code 0x" << std::setbase(16) << exception_code
<< std::setbase(10) << " thrown in " << location << ".";
return new std::string(message.GetString());
}
#endif // GTEST_HAS_SEH
namespace internal { namespace internal {
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
@ -2611,16 +2604,8 @@ Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
#if GTEST_HAS_SEH #if GTEST_HAS_SEH
__try { __try {
return (object->*method)(); return (object->*method)();
} __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT } __except (internal::UnitTestOptions::GTestProcessSEH( // NOLINT
GetExceptionCode())) { GetExceptionCode(), location)) {
// We create the exception message on the heap because VC++ prohibits
// creation of objects with destructors on stack in functions using __try
// (see error C2712).
std::string* exception_message =
FormatSehExceptionMessage(GetExceptionCode(), location);
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
*exception_message);
delete exception_message;
return static_cast<Result>(0); return static_cast<Result>(0);
} }
#else #else
@ -3019,7 +3004,8 @@ void TestSuite::Run() {
internal::HandleExceptionsInMethodIfSupported( internal::HandleExceptionsInMethodIfSupported(
this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()"); this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()");
const bool skip_all = ad_hoc_test_result().Failed(); const bool skip_all =
ad_hoc_test_result().Failed() || ad_hoc_test_result().Skipped();
start_timestamp_ = internal::GetTimeInMillis(); start_timestamp_ = internal::GetTimeInMillis();
internal::Timer timer; internal::Timer timer;
@ -3243,7 +3229,8 @@ static const char* GetAnsiColorCode(GTestColor color) {
case GTestColor::kYellow: case GTestColor::kYellow:
return "3"; return "3";
default: default:
return nullptr; assert(false);
return "9";
} }
} }
@ -5155,8 +5142,8 @@ bool TestEventListeners::EventForwardingEnabled() const {
return repeater_->forwarding_enabled(); return repeater_->forwarding_enabled();
} }
void TestEventListeners::SuppressEventForwarding() { void TestEventListeners::SuppressEventForwarding(bool suppress) {
repeater_->set_forwarding_enabled(false); repeater_->set_forwarding_enabled(!suppress);
} }
// class UnitTest // class UnitTest
@ -5414,7 +5401,7 @@ void UnitTest::RecordProperty(const std::string& key,
int UnitTest::Run() { int UnitTest::Run() {
#ifdef GTEST_HAS_DEATH_TEST #ifdef GTEST_HAS_DEATH_TEST
const bool in_death_test_child_process = const bool in_death_test_child_process =
GTEST_FLAG_GET(internal_run_death_test).length() > 0; !GTEST_FLAG_GET(internal_run_death_test).empty();
// Google Test implements this protocol for catching that a test // Google Test implements this protocol for catching that a test
// program exits before returning control to Google Test: // program exits before returning control to Google Test:
@ -5634,7 +5621,7 @@ void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
// subprocess. Must not be called before InitGoogleTest. // subprocess. Must not be called before InitGoogleTest.
void UnitTestImpl::SuppressTestEventsIfInSubprocess() { void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
if (internal_run_death_test_flag_ != nullptr) if (internal_run_death_test_flag_ != nullptr)
listeners()->SuppressEventForwarding(); listeners()->SuppressEventForwarding(true);
} }
#endif // GTEST_HAS_DEATH_TEST #endif // GTEST_HAS_DEATH_TEST
@ -5654,8 +5641,10 @@ void UnitTestImpl::ConfigureXmlOutput() {
<< output_format << "\" ignored."; << output_format << "\" ignored.";
} }
#else #else
GTEST_LOG_(ERROR) << "ERROR: alternative output formats require " if (!output_format.empty()) {
<< "GTEST_HAS_FILE_SYSTEM to be enabled"; GTEST_LOG_(ERROR) << "ERROR: alternative output formats require "
<< "GTEST_HAS_FILE_SYSTEM to be enabled";
}
#endif // GTEST_HAS_FILE_SYSTEM #endif // GTEST_HAS_FILE_SYSTEM
} }

View File

@ -31,7 +31,8 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) #if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) || \
(defined(GTEST_OS_NRF52) && defined(ARDUINO))
// Arduino-like platforms: program entry points are setup/loop instead of main. // Arduino-like platforms: program entry points are setup/loop instead of main.
#ifdef GTEST_OS_ESP8266 #ifdef GTEST_OS_ESP8266

View File

@ -64,6 +64,7 @@ cc_test(
"googletest-global-environment-unittest_.cc", "googletest-global-environment-unittest_.cc",
"googletest-break-on-failure-unittest_.cc", "googletest-break-on-failure-unittest_.cc",
"googletest-listener-test.cc", "googletest-listener-test.cc",
"googletest-message-test.cc",
"googletest-output-test_.cc", "googletest-output-test_.cc",
"googletest-list-tests-unittest_.cc", "googletest-list-tests-unittest_.cc",
"googletest-shuffle-test_.cc", "googletest-shuffle-test_.cc",

View File

@ -297,10 +297,10 @@ class CatchCxxExceptionsTest(gtest_test_utils.TestCase):
def testUnhandledCxxExceptionsAbortTheProgram(self): def testUnhandledCxxExceptionsAbortTheProgram(self):
# Filters out SEH exception tests on Windows. Unhandled SEH exceptions # Filters out SEH exception tests on Windows. Unhandled SEH exceptions
# cause tests to show pop-up windows there. # cause tests to show pop-up windows there.
FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*' filter_out_seh_tests_flag = FILTER_FLAG + '=-*Seh*'
# By default, Google Test doesn't catch the exceptions. # By default, Google Test doesn't catch the exceptions.
uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess( uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess(
[EX_EXE_PATH, NO_CATCH_EXCEPTIONS_FLAG, FITLER_OUT_SEH_TESTS_FLAG], [EX_EXE_PATH, NO_CATCH_EXCEPTIONS_FLAG, filter_out_seh_tests_flag],
env=environ, env=environ,
).output ).output

View File

@ -36,10 +36,26 @@
#include "gtest/gtest-message.h" #include "gtest/gtest-message.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#ifdef GTEST_HAS_ABSL
#include "absl/strings/str_format.h"
#endif // GTEST_HAS_ABSL
namespace { namespace {
using ::testing::Message; using ::testing::Message;
#ifdef GTEST_HAS_ABSL
struct AbslStringifiablePoint {
template <typename Sink>
friend void AbslStringify(Sink& sink, const AbslStringifiablePoint& p) {
absl::Format(&sink, "(%d, %d)", p.x, p.y);
}
int x;
int y;
};
#endif // GTEST_HAS_ABSL
// Tests the testing::Message class // Tests the testing::Message class
// Tests the default constructor. // Tests the default constructor.
@ -128,6 +144,13 @@ TEST(MessageTest, StreamsInt) {
EXPECT_EQ("123", (Message() << 123).GetString()); EXPECT_EQ("123", (Message() << 123).GetString());
} }
#ifdef GTEST_HAS_ABSL
// Tests streaming a type with an AbslStringify definition.
TEST(MessageTest, StreamsAbslStringify) {
EXPECT_EQ("(1, 2)", (Message() << AbslStringifiablePoint{1, 2}).GetString());
}
#endif // GTEST_HAS_ABSL
// Tests that basic IO manipulators (endl, ends, and flush) can be // Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to Message. // streamed to Message.
TEST(MessageTest, StreamsBasicIoManip) { TEST(MessageTest, StreamsBasicIoManip) {

View File

@ -12,7 +12,7 @@ Expected equality of these values:
3 3
Stack trace: (omitted) Stack trace: (omitted)
[==========] Running 89 tests from 42 test suites. [==========] Running 90 tests from 43 test suites.
[----------] Global test environment set-up. [----------] Global test environment set-up.
FooEnvironment::SetUp() called. FooEnvironment::SetUp() called.
BarEnvironment::SetUp() called. BarEnvironment::SetUp() called.
@ -967,6 +967,15 @@ Stack trace: (omitted)
googletest-output-test_.cc:#: Skipped googletest-output-test_.cc:#: Skipped
[ SKIPPED ] TestSuiteThatFailsToSetUp.ShouldNotRun [ SKIPPED ] TestSuiteThatFailsToSetUp.ShouldNotRun
[----------] 1 test from TestSuiteThatSkipsInSetUp
googletest-output-test_.cc:#: Skipped
Skip entire test suite
Stack trace: (omitted)
[ RUN ] TestSuiteThatSkipsInSetUp.ShouldNotRun
googletest-output-test_.cc:#: Skipped
[ SKIPPED ] TestSuiteThatSkipsInSetUp.ShouldNotRun
[----------] 1 test from PrintingFailingParams/FailingParamTest [----------] 1 test from PrintingFailingParams/FailingParamTest
[ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 [ RUN ] PrintingFailingParams/FailingParamTest.Fails/0
googletest-output-test_.cc:#: Failure googletest-output-test_.cc:#: Failure
@ -1043,10 +1052,11 @@ Failed
Expected fatal failure. Expected fatal failure.
Stack trace: (omitted) Stack trace: (omitted)
[==========] 89 tests from 42 test suites ran. [==========] 90 tests from 43 test suites ran.
[ PASSED ] 31 tests. [ PASSED ] 31 tests.
[ SKIPPED ] 1 test, listed below: [ SKIPPED ] 2 tests, listed below:
[ SKIPPED ] TestSuiteThatFailsToSetUp.ShouldNotRun [ SKIPPED ] TestSuiteThatFailsToSetUp.ShouldNotRun
[ SKIPPED ] TestSuiteThatSkipsInSetUp.ShouldNotRun
[ FAILED ] 57 tests, listed below: [ FAILED ] 57 tests, listed below:
[ FAILED ] NonfatalFailureTest.EscapesStringOperands [ FAILED ] NonfatalFailureTest.EscapesStringOperands
[ FAILED ] NonfatalFailureTest.DiffForLongStrings [ FAILED ] NonfatalFailureTest.DiffForLongStrings

View File

@ -1007,6 +1007,12 @@ class TestSuiteThatFailsToSetUp : public testing::Test {
}; };
TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); } TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); }
class TestSuiteThatSkipsInSetUp : public testing::Test {
public:
static void SetUpTestSuite() { GTEST_SKIP() << "Skip entire test suite"; }
};
TEST_F(TestSuiteThatSkipsInSetUp, ShouldNotRun) { std::abort(); }
// The main function. // The main function.
// //
// The idea is to use Google Test to run all the tests we have defined (some // The idea is to use Google Test to run all the tests we have defined (some

View File

@ -296,7 +296,7 @@ void* ThreadFunc(void* data) {
TEST(GetThreadCountTest, ReturnsCorrectValue) { TEST(GetThreadCountTest, ReturnsCorrectValue) {
size_t starting_count; size_t starting_count;
size_t thread_count_after_create; size_t thread_count_after_create;
size_t thread_count_after_join; size_t thread_count_after_join = 0;
// We can't guarantee that no other thread was created or destroyed between // We can't guarantee that no other thread was created or destroyed between
// any two calls to GetThreadCount(). We make multiple attempts, hoping that // any two calls to GetThreadCount(). We make multiple attempts, hoping that
@ -316,9 +316,9 @@ TEST(GetThreadCountTest, ReturnsCorrectValue) {
const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
ASSERT_EQ(0, pthread_attr_destroy(&attr)); ASSERT_EQ(0, pthread_attr_destroy(&attr));
ASSERT_EQ(0, status); ASSERT_EQ(0, status);
}
thread_count_after_create = GetThreadCount(); thread_count_after_create = GetThreadCount();
}
void* dummy; void* dummy;
ASSERT_EQ(0, pthread_join(thread_id, &dummy)); ASSERT_EQ(0, pthread_join(thread_id, &dummy));

View File

@ -54,6 +54,15 @@
#include "gtest/gtest-printers.h" #include "gtest/gtest-printers.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-port.h"
#ifdef GTEST_HAS_ABSL
#include "absl/strings/str_format.h"
#endif
#if GTEST_INTERNAL_HAS_STD_SPAN
#include <span> // NOLINT
#endif // GTEST_INTERNAL_HAS_STD_SPAN
// Some user-defined types for testing the universal value printer. // Some user-defined types for testing the universal value printer.
@ -119,6 +128,19 @@ void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
os << "StreamableInGlobal*"; os << "StreamableInGlobal*";
} }
#ifdef GTEST_HAS_ABSL
// A user-defined type with AbslStringify
struct Point {
template <typename Sink>
friend void AbslStringify(Sink& sink, const Point& p) {
absl::Format(&sink, "(%d, %d)", p.x, p.y);
}
int x = 10;
int y = 20;
};
#endif
namespace foo { namespace foo {
// A user-defined unprintable type in a user namespace. // A user-defined unprintable type in a user namespace.
@ -317,6 +339,11 @@ TEST(PrintEnumTest, EnumWithPrintTo) {
EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0))); EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
} }
#ifdef GTEST_HAS_ABSL
// Tests printing a class that defines AbslStringify
TEST(PrintClassTest, AbslStringify) { EXPECT_EQ("(10, 20)", Print(Point())); }
#endif
// Tests printing a class implicitly convertible to BiggestInt. // Tests printing a class implicitly convertible to BiggestInt.
TEST(PrintClassTest, BiggestIntConvertible) { TEST(PrintClassTest, BiggestIntConvertible) {
@ -1157,6 +1184,17 @@ TEST(PrintStlContainerTest, Vector) {
EXPECT_EQ("{ 1, 2 }", Print(v)); EXPECT_EQ("{ 1, 2 }", Print(v));
} }
TEST(PrintStlContainerTest, StdSpan) {
#if GTEST_INTERNAL_HAS_STD_SPAN
int a[] = {3, 6, 5};
std::span<int> s = a;
EXPECT_EQ("{ 3, 6, 5 }", Print(s));
#else
GTEST_SKIP() << "Does not have std::span.";
#endif // GTEST_INTERNAL_HAS_STD_SPAN
}
TEST(PrintStlContainerTest, LongSequence) { TEST(PrintStlContainerTest, LongSequence) {
const int a[100] = {1, 2, 3}; const int a[100] = {1, 2, 3};
const vector<int> v(a, a + 100); const vector<int> v(a, a + 100);
@ -1636,6 +1674,12 @@ TEST(PrintToStringTest, PrintReferenceToStreamableInGlobal) {
EXPECT_STREQ("StreamableInGlobal", PrintToString(r).c_str()); EXPECT_STREQ("StreamableInGlobal", PrintToString(r).c_str());
} }
#ifdef GTEST_HAS_ABSL
TEST(PrintToStringTest, AbslStringify) {
EXPECT_PRINT_TO_STRING_(Point(), "(10, 20)");
}
#endif
TEST(IsValidUTF8Test, IllFormedUTF8) { TEST(IsValidUTF8Test, IllFormedUTF8) {
// The following test strings are ill-formed UTF-8 and are printed // The following test strings are ill-formed UTF-8 and are printed
// as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is

View File

@ -43,11 +43,22 @@ import sys
from googletest.test import gtest_test_utils from googletest.test import gtest_test_utils
FREEBSD = ('FreeBSD', 'GNU/kFreeBSD')
NETBSD = ('NetBSD',)
OPENBSD = ('OpenBSD',)
def is_bsd_based_os() -> bool:
"""Determine whether or not the OS is BSD-based."""
if os.name != 'posix':
return False
return os.uname()[0] in (FREEBSD + NETBSD + OPENBSD)
IS_DARWIN = os.name == 'posix' and os.uname()[0] == 'Darwin' IS_DARWIN = os.name == 'posix' and os.uname()[0] == 'Darwin'
IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'
IS_GNUHURD = os.name == 'posix' and os.uname()[0] == 'GNU' IS_GNUHURD = os.name == 'posix' and os.uname()[0] == 'GNU'
IS_GNUKFREEBSD = os.name == 'posix' and os.uname()[0] == 'GNU/kFreeBSD'
IS_OPENBSD = os.name == 'posix' and os.uname()[0] == 'OpenBSD'
IS_WINDOWS = os.name == 'nt' IS_WINDOWS = os.name == 'nt'
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_') PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_')
@ -96,7 +107,7 @@ HELP_REGEX = re.compile(
) )
def RunWithFlag(flag): def run_with_flag(flag):
"""Runs gtest_help_test_ with the given flag. """Runs gtest_help_test_ with the given flag.
Returns: Returns:
@ -116,17 +127,14 @@ def RunWithFlag(flag):
class GTestHelpTest(gtest_test_utils.TestCase): class GTestHelpTest(gtest_test_utils.TestCase):
"""Tests the --help flag and its equivalent forms.""" """Tests the --help flag and its equivalent forms."""
def TestHelpFlag(self, flag): def test_prints_help_with_full_flag(self):
"""Verifies correct behavior when help flag is specified. """Verifies correct behavior when help flag is specified.
The right message must be printed and the tests must The right message must be printed and the tests must
skipped when the given flag is specified. skipped when the given flag is specified.
Args:
flag: A flag to pass to the binary or None.
""" """
exit_code, output = RunWithFlag(flag) exit_code, output = run_with_flag('--help')
if HAS_ABSL_FLAGS: if HAS_ABSL_FLAGS:
# The Abseil flags library prints the ProgramUsageMessage() with # The Abseil flags library prints the ProgramUsageMessage() with
# --help and returns 1. # --help and returns 1.
@ -136,7 +144,7 @@ class GTestHelpTest(gtest_test_utils.TestCase):
self.assertTrue(HELP_REGEX.search(output), output) self.assertTrue(HELP_REGEX.search(output), output)
if IS_DARWIN or IS_LINUX or IS_GNUHURD or IS_GNUKFREEBSD or IS_OPENBSD: if IS_DARWIN or IS_LINUX or IS_GNUHURD or is_bsd_based_os():
self.assertIn(STREAM_RESULT_TO_FLAG, output) self.assertIn(STREAM_RESULT_TO_FLAG, output)
else: else:
self.assertNotIn(STREAM_RESULT_TO_FLAG, output) self.assertNotIn(STREAM_RESULT_TO_FLAG, output)
@ -146,53 +154,27 @@ class GTestHelpTest(gtest_test_utils.TestCase):
else: else:
self.assertNotIn(DEATH_TEST_STYLE_FLAG, output) self.assertNotIn(DEATH_TEST_STYLE_FLAG, output)
def TestUnknownFlagWithAbseil(self, flag): def test_runs_tests_without_help_flag(self):
"""Verifies correct behavior when an unknown flag is specified.
The right message must be printed and the tests must
skipped when the given flag is specified.
Args:
flag: A flag to pass to the binary or None.
"""
exit_code, output = RunWithFlag(flag)
self.assertEqual(1, exit_code)
self.assertIn('ERROR: Unknown command line flag', output)
def TestNonHelpFlag(self, flag):
"""Verifies correct behavior when no help flag is specified. """Verifies correct behavior when no help flag is specified.
Verifies that when no help flag is specified, the tests are run Verifies that when no help flag is specified, the tests are run
and the help message is not printed. and the help message is not printed.
Args:
flag: A flag to pass to the binary or None.
""" """
exit_code, output = RunWithFlag(flag) exit_code, output = run_with_flag(None)
self.assertNotEqual(exit_code, 0) self.assertNotEqual(exit_code, 0)
self.assertFalse(HELP_REGEX.search(output), output) self.assertFalse(HELP_REGEX.search(output), output)
def testPrintsHelpWithFullFlag(self): def test_runs_tests_with_gtest_internal_flag(self):
self.TestHelpFlag('--help')
def testRunsTestsWithoutHelpFlag(self):
"""Verifies correct behavior when no help flag is specified.
Verifies that when no help flag is specified, the tests are run
and the help message is not printed.
"""
self.TestNonHelpFlag(None)
def testRunsTestsWithGtestInternalFlag(self):
"""Verifies correct behavior when internal testing flag is specified. """Verifies correct behavior when internal testing flag is specified.
Verifies that the tests are run and no help message is printed when Verifies that the tests are run and no help message is printed when
a flag starting with Google Test prefix and 'internal_' is supplied. a flag starting with Google Test prefix and 'internal_' is supplied.
""" """
self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING) exit_code, output = run_with_flag(INTERNAL_FLAG_FOR_TESTING)
self.assertNotEqual(exit_code, 0)
self.assertFalse(HELP_REGEX.search(output), output)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -67,11 +67,27 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include <unordered_set> #include <unordered_set>
#include <utility>
#include <vector> #include <vector>
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "src/gtest-internal-inl.h" #include "src/gtest-internal-inl.h"
struct ConvertibleGlobalType {
// The inner enable_if is to ensure invoking is_constructible doesn't fail.
// The outer enable_if is to ensure the overload resolution doesn't encounter
// an ambiguity.
template <
class T,
std::enable_if_t<
false, std::enable_if_t<std::is_constructible<T>::value, int>> = 0>
operator T() const; // NOLINT(google-explicit-constructor)
};
void operator<<(ConvertibleGlobalType&, int);
static_assert(sizeof(decltype(std::declval<ConvertibleGlobalType&>()
<< 1)(*)()) > 0,
"error in operator<< overload resolution");
namespace testing { namespace testing {
namespace internal { namespace internal {
@ -173,7 +189,7 @@ class TestEventListenersAccessor {
} }
static void SuppressEventForwarding(TestEventListeners* listeners) { static void SuppressEventForwarding(TestEventListeners* listeners) {
listeners->SuppressEventForwarding(); listeners->SuppressEventForwarding(true);
} }
}; };
@ -4097,7 +4113,7 @@ TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
EXPECT_THROW(throw 1, int); EXPECT_THROW(throw 1, int);
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), ""); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), ""); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw n, const char*), "");
EXPECT_NO_THROW(n++); EXPECT_NO_THROW(n++);
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), ""); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
EXPECT_ANY_THROW(throw 1); EXPECT_ANY_THROW(throw 1);

View File

@ -7,16 +7,16 @@ def googletest_deps():
if not native.existing_rule("com_googlesource_code_re2"): if not native.existing_rule("com_googlesource_code_re2"):
http_archive( http_archive(
name = "com_googlesource_code_re2", # 2023-06-01 name = "com_googlesource_code_re2", # 2023-03-17T11:36:51Z
sha256 = "1726508efc93a50854c92e3f7ac66eb28f0e57652e413f11d7c1e28f97d997ba", sha256 = "cb8b5312a65f2598954545a76e8bce913f35fbb3a21a5c88797a4448e9f9b9d9",
strip_prefix = "re2-03da4fc0857c285e3a26782f6bc8931c4c950df4", strip_prefix = "re2-578843a516fd1da7084ae46209a75f3613b6065e",
urls = ["https://github.com/google/re2/archive/03da4fc0857c285e3a26782f6bc8931c4c950df4.zip"], urls = ["https://github.com/google/re2/archive/578843a516fd1da7084ae46209a75f3613b6065e.zip"],
) )
if not native.existing_rule("com_google_absl"): if not native.existing_rule("com_google_absl"):
http_archive( http_archive(
name = "com_google_absl", # 2023-04-06T14:42:25Z name = "com_google_absl", # 2023-09-13T14:58:42Z
sha256 = "a50452f02402262f9a61a8eedda60f76dda6b9538d36b34b55bce9f74a4d5ef8", sha256 = "7766815ef6293dc7bca58fef59a96d7d3230874412dcd36dafb0e313ed1356f2",
strip_prefix = "abseil-cpp-e73b9139ee9b853a4bd7812531442c138da09084", strip_prefix = "abseil-cpp-9e1789ffea47fdeb3133aa42aa9592f3673fb6ed",
urls = ["https://github.com/abseil/abseil-cpp/archive/e73b9139ee9b853a4bd7812531442c138da09084.zip"], urls = ["https://github.com/abseil/abseil-cpp/archive/9e1789ffea47fdeb3133aa42aa9592f3673fb6ed.zip"],
) )