diff --git a/.gitignore b/.gitignore index f08cb72a..fede02f6 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,10 @@ Win32-Release/ x64-Debug/ x64-Release/ +# VSCode files +.cache/ +cmake-variants.yaml + # Ignore autoconf / automake files Makefile.in aclocal.m4 diff --git a/CMakeLists.txt b/CMakeLists.txt index 6af41437..24d41c29 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,22 +1,10 @@ # Note: CMake support is community-based. The maintainers do not use CMake # internally. -cmake_minimum_required(VERSION 3.5) - -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) +cmake_minimum_required(VERSION 3.13) 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) set(CMAKE_CXX_EXTENSIONS OFF) @@ -27,7 +15,7 @@ enable_testing() include(CMakeDependentOption) include(GNUInstallDirs) -#Note that googlemock target already builds googletest +# Note that googlemock target already builds googletest. option(BUILD_GMOCK "Builds the googlemock subproject" ON) option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) option(GTEST_HAS_ABSL "Use Abseil and RE2. Requires Abseil and RE2 to be separately added to the build." OFF) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8bed14b2..ab5a47bf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,11 +47,11 @@ PR is acceptable as an alternative. ## The Google Test and Google Mock Communities The Google Test community exists primarily through the -[discussion group](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 -their own [discussion group](http://groups.google.com/group/googlemock). You are -definitely encouraged to contribute to the discussion and you can also help us -to keep the effectiveness of the group high by following and promoting the +their own [discussion group](https://groups.google.com/group/googlemock). You +are definitely encouraged to contribute to the discussion and you can also help +us to keep the effectiveness of the group high by following and promoting the guidelines listed here. ### Please Be Friendly diff --git a/README.md b/README.md index 10d1f86f..c1c14465 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ GoogleTest now follows the 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). 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 @@ -17,18 +17,18 @@ Our documentation is now live on GitHub Pages at https://google.github.io/googletest/. We recommend browsing the documentation on GitHub Pages rather than directly in the repository. -#### Release 1.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. -The 1.13.x branch requires at least C++14. +The 1.14.x branch requires at least C++14. #### Continuous Integration We use Google's internal systems for continuous integration. \ -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 +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 GoogleTest team. #### Coming Soon @@ -52,40 +52,39 @@ documentation. We recommend starting with the More information about building GoogleTest can be found at [googletest/README.md](googletest/README.md). -| Feature | Description | -| ---------------------------- | --------------------------------------------- | -| xUnit test framework | Googletest is based on the | -: : [xUnit](https\://en.wikipedia.org/wiki/XUnit) : -: : testing framework, a popular architecture for : -: : unit testing : -| Test discovery | Googletest automatically discovers and runs | -: : your tests, eliminating the need to manually : -: : register your tests : -| Rich set of assertions | Googletest provides a variety of assertions, | -: : such as equality, inequality, exceptions, and : -: : more, making it easy to test your code : -| User-defined assertions | You can define your own assertions with | -: : Googletest, making it simple to write tests : -: : that are specific to your code : -| Death tests | Googletest supports death tests, which verify | -: : that your code exits in a certain way, making : -: : it useful for testing error-handling code : -| Fatal and non-fatal failures | You can specify whether a test failure should | -: : be treated as fatal or non-fatal with : -: : Googletest, allowing tests to continue : -: : running even if a failure occurs : -| Value-parameterized tests | Googletest supports value-parameterized | -: : tests, which run multiple times with : -: : different input values, making it useful for : -: : testing functions that take different inputs : -| Type-parameterized tests | Googletest also supports type-parameterized | -: : tests, which run with different data types, : -: : making it useful for testing functions that : -: : work with different data types : -| Various options for running | Googletest provides many options for running | -: tests : tests, including running individual tests, : -: : running tests in a specific order, and : -: : running tests in parallel : +## Features + +* xUnit test framework: \ + Googletest is based on the [xUnit](https://en.wikipedia.org/wiki/XUnit) + testing framework, a popular architecture for unit testing +* Test discovery: \ + Googletest automatically discovers and runs your tests, eliminating the need + to manually register your tests +* Rich set of assertions: \ + Googletest provides a variety of assertions, such as equality, inequality, + exceptions, and more, making it easy to test your code +* User-defined assertions: \ + You can define your own assertions with Googletest, making it simple to + write tests that are specific to your code +* Death tests: \ + Googletest supports death tests, which verify that your code exits in a + certain way, making it useful for testing error-handling code +* Fatal and non-fatal failures: \ + You can specify whether a test failure should be treated as fatal or + non-fatal with Googletest, allowing tests to continue running even if a + failure occurs +* Value-parameterized tests: \ + Googletest supports value-parameterized tests, which run multiple times with + different input values, making it useful for testing functions that take + different inputs +* Type-parameterized tests: \ + Googletest also supports type-parameterized tests, which run with different + data types, making it useful for testing functions that work with different + data types +* Various options for running tests: \ + Googletest provides many options for running tests including running + individual tests, running tests in a specific order and running tests in + parallel ## Supported Platforms @@ -93,7 +92,7 @@ GoogleTest follows Google's [Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support). See [this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md) -for a list of currently supported versions compilers, platforms, and build +for a list of currently supported versions of compilers, platforms, and build tools. ## Who Is Using GoogleTest? @@ -101,12 +100,12 @@ tools. In addition to many internal projects at Google, GoogleTest is also used by the following notable projects: -* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser - and Chrome OS). -* The [LLVM](http://llvm.org/) compiler. +* The [Chromium projects](https://www.chromium.org/) (behind the Chrome + browser and Chrome OS). +* The [LLVM](https://llvm.org/) compiler. * [Protocol Buffers](https://github.com/google/protobuf), Google's data interchange format. -* The [OpenCV](http://opencv.org/) computer vision library. +* The [OpenCV](https://opencv.org/) computer vision library. ## Related Open Source Projects diff --git a/WORKSPACE b/WORKSPACE index 1c8ea24d..f819ffe6 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -6,22 +6,22 @@ googletest_deps() load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( - name = "rules_python", # 2023-01-10T22:00:51Z - sha256 = "5de54486a60ad8948dabe49605bb1c08053e04001a431ab3e96745b4d97a4419", - strip_prefix = "rules_python-70cce26432187a60b4e950118791385e6fb3c26f", - urls = ["https://github.com/bazelbuild/rules_python/archive/70cce26432187a60b4e950118791385e6fb3c26f.zip"], + name = "rules_python", # 2023-07-31T20:39:27Z + sha256 = "1250b59a33c591a1c4ba68c62e95fc88a84c334ec35a2e23f46cbc1b9a5a8b55", + strip_prefix = "rules_python-e355becc30275939d87116a4ec83dad4bb50d9e1", + urls = ["https://github.com/bazelbuild/rules_python/archive/e355becc30275939d87116a4ec83dad4bb50d9e1.zip"], ) http_archive( - name = "bazel_skylib", # 2022-11-16T18:29:32Z - sha256 = "a22290c26d29d3ecca286466f7f295ac6cbe32c0a9da3a91176a90e0725e3649", - strip_prefix = "bazel-skylib-5bfcb1a684550626ce138fe0fe8f5f702b3764c3", - urls = ["https://github.com/bazelbuild/bazel-skylib/archive/5bfcb1a684550626ce138fe0fe8f5f702b3764c3.zip"], + name = "bazel_skylib", # 2023-05-31T19:24:07Z + sha256 = "08c0386f45821ce246bbbf77503c973246ed6ee5c3463e41efc197fa9bc3a7f4", + strip_prefix = "bazel-skylib-288731ef9f7f688932bd50e704a91a45ec185f9b", + urls = ["https://github.com/bazelbuild/bazel-skylib/archive/288731ef9f7f688932bd50e704a91a45ec185f9b.zip"], ) http_archive( - name = "platforms", # 2022-11-09T19:18:22Z - sha256 = "b4a3b45dc4202e2b3e34e3bc49d2b5b37295fc23ea58d88fb9e01f3642ad9b55", - strip_prefix = "platforms-3fbc687756043fb58a407c2ea8c944bc2fe1d922", - urls = ["https://github.com/bazelbuild/platforms/archive/3fbc687756043fb58a407c2ea8c944bc2fe1d922.zip"], + name = "platforms", # 2023-07-28T19:44:27Z + sha256 = "40eb313613ff00a5c03eed20aba58890046f4d38dec7344f00bb9a8867853526", + strip_prefix = "platforms-4ad40ef271da8176d4fc0194d2089b8a76e19d7b", + urls = ["https://github.com/bazelbuild/platforms/archive/4ad40ef271da8176d4fc0194d2089b8a76e19d7b.zip"], ) diff --git a/ci/linux-presubmit.sh b/ci/linux-presubmit.sh index 6bac8878..a1caa272 100644 --- a/ci/linux-presubmit.sh +++ b/ci/linux-presubmit.sh @@ -31,7 +31,7 @@ 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" if [[ -z ${GTEST_ROOT:-} ]]; then diff --git a/docs/advanced.md b/docs/advanced.md index 3871db13..0e1f812b 100644 --- a/docs/advanced.md +++ b/docs/advanced.md @@ -508,9 +508,9 @@ TEST_F(FooDeathTest, DoesThat) { When built with Bazel and using Abseil, GoogleTest uses the [RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX systems (Linux, Cygwin, Mac), GoogleTest uses the -[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) +[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 -[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 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. 2. Outside your test fixture class (typically just below it), define those member variables, optionally giving them initial values. -3. In the same test fixture class, define a `static void SetUpTestSuite()` - function (remember not to spell it as **`SetupTestSuite`** with a small - `u`!) to set up the shared resources and a `static void TearDownTestSuite()` - function to tear them down. +3. In the same test fixture class, define a public member function `static void + SetUpTestSuite()` (remember not to spell it as **`SetupTestSuite`** with a + small `u`!) to set up the shared resources and a `static void + TearDownTestSuite()` function to tear them down. That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the *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 { - "$schema": "http://json-schema.org/schema#", + "$schema": "https://json-schema.org/schema#", "type": "object", "definitions": { "TestCase": { diff --git a/docs/faq.md b/docs/faq.md index 19280972..c7d10b50 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -3,7 +3,7 @@ ## Why should test suite names and test names not contain underscore? {: .callout .note} -Note: GoogleTest reserves underscore (`_`) for special purpose keywords, such as +Note: GoogleTest reserves underscore (`_`) for special-purpose keywords, such as [the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition to the following rationale. @@ -33,9 +33,9 @@ contains `_`? `TestSuiteName_Bar__Test`, which is invalid. So clearly `TestSuiteName` and `TestName` cannot start or end with `_` -(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't -followed by an upper-case letter. But that's getting complicated. So for -simplicity we just say that it cannot start with `_`.). +(Actually, `TestSuiteName` can start with `_`—as long as the `_` isn't followed +by an upper-case letter. But that's getting complicated. So for simplicity we +just say that it cannot start with `_`.). It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the middle. However, consider this: @@ -128,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 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` where it should be `message`), you -will now get run-time errors like: - -``` -... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto": -... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined. -``` - -If you see this, your `.proto` file is broken and needs to be fixed by making -the types fully qualified. The new definition of `ProtocolMessageEquals` and -`ProtocolMessageEquiv` just happen to reveal your bug. - ## My death test modifies some state, but the change seems lost after the death test finishes. Why? -Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the +Death tests (`EXPECT_DEATH`, etc.) are executed in a sub-process s.t. the expected crash won't kill the test program (i.e. the parent process). As a result, any in-memory side effects they incur are observable in their respective sub-processes, but not in the parent process. You can think of them as running @@ -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++ const int Foo::kBar; // No initializer here. ``` Otherwise your code is **invalid C++**, and may break in unexpected ways. In -particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will -generate an "undefined reference" linker error. The fact that "it used to work" -doesn't mean it's valid. It just means that you were lucky. :-) +particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc.) +will generate an "undefined reference" linker error. The fact that "it used to +work" doesn't mean it's valid. It just means that you were lucky. :-) If the declaration of the static data member is `constexpr` then it is implicitly an `inline` definition, and a separate definition in `foo.cc` is not @@ -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. When you need to write per-test set-up and tear-down logic, you have the choice -between using the test fixture constructor/destructor or `SetUp()/TearDown()`. +between using the test fixture constructor/destructor or `SetUp()`/`TearDown()`. The former is usually preferred, as it has the following benefits: * By initializing a member variable in the constructor, we have the option to @@ -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 platform. -## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? +## The compiler complains "no matching function to call" when I use `ASSERT_PRED*`. How do I fix it? See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions Reference. @@ -410,7 +389,7 @@ C++ is case-sensitive. Did you spell it as `Setup()`? Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and wonder why it's never called. -## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. +## I have several test suites which share the same test fixture logic; do I have to define a new test fixture class for each of them? This seems pretty tedious. You don't have to. Instead of @@ -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 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 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 with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. -## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do? +## But I don't like calling my entire test suite `*DeathTest` when it contains both death tests and non-death tests. What do I do? You don't have to, but if you like, you may split up the test suite into `FooTest` and `FooDeathTest`, where the names make it clear that they are @@ -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 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? @@ -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. 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 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. 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. The rule is **all test methods in the same test suite must use the same fixture -class.** This means that the following is **allowed** because both tests use the +class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`). ```c++ diff --git a/docs/gmock_cheat_sheet.md b/docs/gmock_cheat_sheet.md index 2fb0403e..ddafaaa2 100644 --- a/docs/gmock_cheat_sheet.md +++ b/docs/gmock_cheat_sheet.md @@ -20,7 +20,7 @@ class Foo { (note that `~Foo()` **must** be virtual) we can define its mock as ```cpp -#include "gmock/gmock.h" +#include class MockFoo : public Foo { public: diff --git a/docs/gmock_cook_book.md b/docs/gmock_cook_book.md index d57be58d..5e9b6647 100644 --- a/docs/gmock_cook_book.md +++ b/docs/gmock_cook_book.md @@ -697,9 +697,9 @@ TEST(AbcTest, Xyz) { EXPECT_CALL(foo, DoThat(_, _)); int n = 0; - EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. + EXPECT_EQ(foo.DoThis(5), '+'); // FakeFoo::DoThis() is invoked. foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. - EXPECT_EQ(2, n); + EXPECT_EQ(n, 2); } ``` @@ -1129,11 +1129,11 @@ using STL's `` header is just painful). For example, here's a predicate that's satisfied by any number that is >= 0, <= 100, and != 50: ```cpp -using testing::AllOf; -using testing::Ge; -using testing::Le; -using testing::Matches; -using testing::Ne; +using ::testing::AllOf; +using ::testing::Ge; +using ::testing::Le; +using ::testing::Matches; +using ::testing::Ne; ... Matches(AllOf(Ge(0), Le(100), Ne(50))) ``` @@ -1861,7 +1861,7 @@ error. So, what shall you do? Though you may be tempted, DO NOT use `std::ref()`: ```cpp -using testing::Return; +using ::testing::Return; class MockFoo : public Foo { public: @@ -1873,7 +1873,7 @@ class MockFoo : public Foo { EXPECT_CALL(foo, GetValue()) .WillRepeatedly(Return(std::ref(x))); // Wrong! 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: @@ -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*: ```cpp -using testing::ReturnPointee; +using ::testing::ReturnPointee; ... int x = 0; MockFoo foo; EXPECT_CALL(foo, GetValue()) .WillRepeatedly(ReturnPointee(&x)); // Note the & here. x = 42; - EXPECT_EQ(42, foo.GetValue()); // This will succeed now. + EXPECT_EQ(foo.GetValue(), 42); // This will succeed now. ``` ### Combining Actions @@ -1927,6 +1927,12 @@ class MockFoo : public Foo { action_n)); ``` +The return value of the last action **must** match the return type of the mocked +method. In the example above, `action_n` could be `Return(true)`, or a lambda +that returns a `bool`, but not `SaveArg`, which returns `void`. Otherwise the +signature of `DoAll` would not match the signature expected by `WillOnce`, which +is the signature of the mocked method, and it wouldn't compile. + ### Verifying Complex Arguments {#SaveArgVerify} If you want to verify that a method is called with a particular argument but the @@ -2264,7 +2270,7 @@ TEST_F(FooTest, Test) { EXPECT_CALL(foo, DoThis(2)) .WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5))); - EXPECT_EQ('+', foo.DoThis(2)); // Invokes SignOfSum(5, 2). + EXPECT_EQ(foo.DoThis(2), '+'); // Invokes SignOfSum(5, 2). } ``` @@ -2640,8 +2646,8 @@ action will exhibit different behaviors. Example: .WillRepeatedly(IncrementCounter(0)); foo.DoThis(); // Returns 1. foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 1 - Blah() uses a different - // counter than Bar()'s. + foo.DoThat(); // Returns 1 - DoThat() uses a different + // counter than DoThis()'s. ``` versus @@ -2771,11 +2777,13 @@ returns a null `unique_ptr`, that’s what you’ll get if you don’t specify a action: ```cpp +using ::testing::IsNull; +... // Use the default action. EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); // 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 @@ -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: ```cpp -#include "gmock/gmock.h" +#include -using testing::_; -using testing::HasSubstr; -using testing::Return; +using ::testing::_; +using ::testing::HasSubstr; +using ::testing::Return; class MockFoo { 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 function. So you can use a lambda: -``` +```cpp MockFunction mock; 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): -``` +```cpp struct MultiplyBy { template 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 supplied to the mock function: -``` +```cpp MockFunction mock; 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 once and is allowed to be a move-only type: -``` +```cpp // An action that contains move-only types and has an &&-qualified operator, // demanding in the type system that it be called at most once. This can be // used with WillOnce, but the compiler will reject it if handed to diff --git a/docs/gmock_for_dummies.md b/docs/gmock_for_dummies.md index b7264d35..9f24dcae 100644 --- a/docs/gmock_for_dummies.md +++ b/docs/gmock_for_dummies.md @@ -90,14 +90,14 @@ gMock is bundled with googletest. ## A Case for Mock Turtles Let's look at an example. Suppose you are developing a graphics program that -relies on a [LOGO](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 run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about -[Dependency Injection](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 the API in an interface (say, `Turtle`) and code to that interface: @@ -164,7 +164,7 @@ follow: After the process, you should have something like: ```cpp -#include "gmock/gmock.h" // Brings in gMock. +#include // Brings in gMock. class MockTurtle : public Turtle { public: @@ -224,8 +224,8 @@ Here's an example: ```cpp #include "path/to/mock-turtle.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" +#include +#include using ::testing::AtLeast; // #1 diff --git a/docs/pkgconfig.md b/docs/pkgconfig.md index 18a2546a..bf05d593 100644 --- a/docs/pkgconfig.md +++ b/docs/pkgconfig.md @@ -19,19 +19,15 @@ examples here we assume you want to compile the sample Using `pkg-config` in CMake is fairly easy: ```cmake -cmake_minimum_required(VERSION 3.0) - -cmake_policy(SET CMP0048 NEW) -project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX) - find_package(PkgConfig) pkg_search_module(GTEST REQUIRED gtest_main) -add_executable(testapp samples/sample3_unittest.cc) -target_link_libraries(testapp ${GTEST_LDFLAGS}) -target_compile_options(testapp PUBLIC ${GTEST_CFLAGS}) +add_executable(testapp) +target_sources(testapp PRIVATE samples/sample3_unittest.cc) +target_link_libraries(testapp PRIVATE ${GTEST_LDFLAGS}) +target_compile_options(testapp PRIVATE ${GTEST_CFLAGS}) -include(CTest) +enable_testing() add_test(first_and_only_test testapp) ``` diff --git a/docs/platforms.md b/docs/platforms.md index eba6ef80..d35a7be0 100644 --- a/docs/platforms.md +++ b/docs/platforms.md @@ -1,35 +1,8 @@ # Supported Platforms -GoogleTest requires a codebase and compiler compliant with the C++11 standard or -newer. - -The GoogleTest code is officially supported on the following platforms. -Operating systems or tools not listed below are community-supported. For -community-supported platforms, patches that do not complicate the code may be -considered. - -If you notice any problems on your platform, please file an issue on the -[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues). -Pull requests containing fixes are welcome! - -### Operating systems - -* Linux -* macOS -* Windows - -### Compilers - -* gcc 5.0+ -* clang 5.0+ -* MSVC 2015+ - -**macOS users:** Xcode 9.3+ provides clang 5.0+. - -### Build systems - -* [Bazel](https://bazel.build/) -* [CMake](https://cmake.org/) - -Bazel is the build system used by the team internally and in tests. CMake is -supported on a best-effort basis and by the community. +GoogleTest follows Google's +[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support). +See +[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md) +for a list of currently supported versions compilers, platforms, and build +tools. diff --git a/docs/primer.md b/docs/primer.md index 31d63160..8b98da2a 100644 --- a/docs/primer.md +++ b/docs/primer.md @@ -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 minutes to learn the basics and get started. So let's go! -## Beware of the nomenclature +## Beware of the Nomenclature {: .callout .note} *Note:* There might be some confusion arising from different definitions of the @@ -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 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 *[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: -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] -[istqb test case]: http://glossary.istqb.org/en/search/test%20case -[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite +[istqb test case]: https://glossary.istqb.org/en/search/test%20case +[istqb test suite]: https://glossary.istqb.org/en/search/test%20suite ## Basic Concepts @@ -210,7 +210,7 @@ objects for several different tests. To create a fixture: -1. Derive a class from `::testing::Test` . Start its body with `protected:`, as +1. Derive a class from `testing::Test` . Start its body with `protected:`, as we'll want to access fixture members from sub-classes. 2. Inside the class, declare any objects you plan to use. 3. If necessary, write a default constructor or `SetUp()` function to prepare @@ -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. ```c++ -class QueueTest : public ::testing::Test { +class QueueTest : public testing::Test { protected: void SetUp() override { // q0_ remains empty @@ -395,14 +395,14 @@ You can start from this boilerplate: ```c++ #include "this/package/foo.h" -#include "gtest/gtest.h" +#include namespace my { namespace project { namespace { // The fixture for testing class Foo. -class FooTest : public ::testing::Test { +class FooTest : public testing::Test { protected: // You can remove any or all of the following functions if their bodies would // be empty. @@ -450,14 +450,14 @@ TEST_F(FooTest, DoesXyz) { } // namespace my int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); + testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } ``` -The `::testing::InitGoogleTest()` function parses the command line for -GoogleTest flags, and removes all recognized flags. This allows the user to -control a test program's behavior via various flags, which we'll cover in the +The `testing::InitGoogleTest()` function parses the command line for GoogleTest +flags, and removes all recognized flags. This allows the user to control a test +program's behavior via various flags, which we'll cover in the [AdvancedGuide](advanced.md). You **must** call this function before calling `RUN_ALL_TESTS()`, or the flags won't be properly initialized. diff --git a/docs/reference/assertions.md b/docs/reference/assertions.md index 1cdff266..492ff5ef 100644 --- a/docs/reference/assertions.md +++ b/docs/reference/assertions.md @@ -1,7 +1,7 @@ # Assertions Reference 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 `. The majority of the macros listed below come as a pair with an `EXPECT_` variant and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal @@ -88,7 +88,7 @@ For example, the following code verifies that the string `value1` starts with 10: ```cpp -#include "gmock/gmock.h" +#include using ::testing::AllOf; using ::testing::Gt; diff --git a/docs/reference/mocking.md b/docs/reference/mocking.md index e414ffbd..ab37ebf3 100644 --- a/docs/reference/mocking.md +++ b/docs/reference/mocking.md @@ -1,8 +1,7 @@ # Mocking Reference This page lists the facilities provided by GoogleTest for creating and working -with mock objects. To use them, include the header -`gmock/gmock.h`. +with mock objects. To use them, add `#include `. ## Macros {#macros} diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 877dfa32..ead66b36 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -3,7 +3,7 @@ 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 `. ## Macros @@ -122,8 +122,8 @@ custom function can be used for more control: ```cpp INSTANTIATE_TEST_SUITE_P( MyInstantiation, MyTestSuite, - ::testing::Values(...), - [](const ::testing::TestParamInfo& info) { + testing::Values(...), + [](const testing::TestParamInfo& info) { // Can use info.param here to generate the test suffix std::string name = ... return name; @@ -148,7 +148,7 @@ type, for example: ```cpp template -class MyFixture : public ::testing::Test { +class MyFixture : public testing::Test { public: ... using List = std::list; @@ -324,7 +324,7 @@ Then the test code should look like: ```cpp 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} -`::testing::AssertionResult` +`testing::AssertionResult` 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} -`::testing::AssertionException` +`testing::AssertionException` Exception which can be thrown from [`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult). ### EmptyTestEventListener {#EmptyTestEventListener} -`::testing::EmptyTestEventListener` +`testing::EmptyTestEventListener` Provides an empty implementation of all methods in the [`TestEventListener`](#TestEventListener) interface, such that a subclass only @@ -416,7 +416,7 @@ needs to override the methods it cares about. ### Environment {#Environment} -`::testing::Environment` +`testing::Environment` Represents a global test environment. See [Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down). @@ -437,7 +437,7 @@ Override this to define how to tear down the environment. ### ScopedTrace {#ScopedTrace} -`::testing::ScopedTrace` +`testing::ScopedTrace` An instance of this class causes a trace to be included in every test failure message generated by code in the scope of the lifetime of the `ScopedTrace` @@ -453,7 +453,7 @@ ScopedTrace(const char* file, int line, const T& message) Example usage: ```cpp -::testing::ScopedTrace trace("file.cc", 123, "message"); +testing::ScopedTrace trace("file.cc", 123, "message"); ``` The resulting trace includes the given source file path and line number, and the @@ -464,7 +464,7 @@ See also [`SCOPED_TRACE`](#SCOPED_TRACE). ### Test {#Test} -`::testing::Test` +`testing::Test` The abstract class that all tests inherit from. `Test` is not copyable. @@ -552,7 +552,7 @@ after running each individual test. ### TestWithParam {#TestWithParam} -`::testing::TestWithParam` +`testing::TestWithParam` A convenience class which inherits from both [`Test`](#Test) and [`WithParamInterface`](#WithParamInterface). @@ -672,7 +672,7 @@ during execution of `SetUpTestSuite` and `TearDownTestSuite`. ### TestInfo {#TestInfo} -`::testing::TestInfo` +`testing::TestInfo` Stores information about a test. @@ -751,7 +751,7 @@ Returns the result of the test. See [`TestResult`](#TestResult). ### TestParamInfo {#TestParamInfo} -`::testing::TestParamInfo` +`testing::TestParamInfo` Describes a parameter to a value-parameterized test. The type `T` is the type of the parameter. @@ -761,7 +761,7 @@ and its integer index respectively. ### UnitTest {#UnitTest} -`::testing::UnitTest` +`testing::UnitTest` This class contains information about the test program. @@ -929,7 +929,7 @@ GoogleTest. See [`TestEventListeners`](#TestEventListeners). ### TestEventListener {#TestEventListener} -`::testing::TestEventListener` +`testing::TestEventListener` The interface for tracing execution of tests. The methods below are listed in the order the corresponding events are fired. @@ -1027,7 +1027,7 @@ Fired after all test activities have ended. ### TestEventListeners {#TestEventListeners} -`::testing::TestEventListeners` +`testing::TestEventListeners` 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} -`::testing::TestPartResult` +`testing::TestPartResult` A copyable object representing the result of a test part (i.e. an assertion or an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`). @@ -1154,7 +1154,7 @@ Returns true if and only if the test part failed. ### TestProperty {#TestProperty} -`::testing::TestProperty` +`testing::TestProperty` A copyable object representing a user-specified test property which can be output as a key/value string pair. @@ -1181,7 +1181,7 @@ Sets a new value, overriding the previous one. ### TestResult {#TestResult} -`::testing::TestResult` +`testing::TestResult` Contains information about the result of a single test. @@ -1262,20 +1262,20 @@ range, aborts the program. ### TimeInMillis {#TimeInMillis} -`::testing::TimeInMillis` +`testing::TimeInMillis` An integer type representing time in milliseconds. ### Types {#Types} -`::testing::Types` +`testing::Types` Represents a list of types for use in typed tests and type-parameterized tests. The template argument `T...` can be any number of types, for example: ``` -::testing::Types +testing::Types ``` See [Typed Tests](../advanced.md#typed-tests) and @@ -1284,7 +1284,7 @@ information. ### WithParamInterface {#WithParamInterface} -`::testing::WithParamInterface` +`testing::WithParamInterface` The pure interface class that all value-parameterized tests inherit from. @@ -1310,9 +1310,9 @@ tests. ### InitGoogleTest {#InitGoogleTest} -`void ::testing::InitGoogleTest(int* argc, char** argv)` \ -`void ::testing::InitGoogleTest(int* argc, wchar_t** argv)` \ -`void ::testing::InitGoogleTest()` +`void testing::InitGoogleTest(int* argc, char** argv)` \ +`void testing::InitGoogleTest(int* argc, wchar_t** argv)` \ +`void testing::InitGoogleTest()` Initializes GoogleTest. This must be called before calling [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line @@ -1329,7 +1329,7 @@ platforms where there is no `argc`/`argv`. ### AddGlobalTestEnvironment {#AddGlobalTestEnvironment} -`Environment* ::testing::AddGlobalTestEnvironment(Environment* env)` +`Environment* testing::AddGlobalTestEnvironment(Environment* env)` Adds a test environment to the test program. Must be called before [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See @@ -1342,7 +1342,7 @@ See also [`Environment`](#Environment). ```cpp template -TestInfo* ::testing::RegisterTest(const char* test_suite_name, const char* test_name, +TestInfo* testing::RegisterTest(const char* test_suite_name, const char* test_name, const char* type_param, const char* value_param, const char* file, int line, Factory factory) ``` @@ -1381,27 +1381,27 @@ an all-caps name. ### AssertionSuccess {#AssertionSuccess} -`AssertionResult ::testing::AssertionSuccess()` +`AssertionResult testing::AssertionSuccess()` Creates a successful assertion result. See [`AssertionResult`](#AssertionResult). ### AssertionFailure {#AssertionFailure} -`AssertionResult ::testing::AssertionFailure()` +`AssertionResult testing::AssertionFailure()` Creates a failed assertion result. Use the `<<` operator to store a failure message: ```cpp -::testing::AssertionFailure() << "My failure message"; +testing::AssertionFailure() << "My failure message"; ``` See [`AssertionResult`](#AssertionResult). ### StaticAssertTypeEq {#StaticAssertTypeEq} -`::testing::StaticAssertTypeEq()` +`testing::StaticAssertTypeEq()` Compile-time assertion for type equality. Compiles if and only if `T1` and `T2` 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} -`std::string ::testing::PrintToString(x)` +`std::string testing::PrintToString(x)` Prints any value `x` using GoogleTest's value printer. @@ -1420,7 +1420,7 @@ for more information. ### PrintToStringParamName {#PrintToStringParamName} -`std::string ::testing::PrintToStringParamName(TestParamInfo& info)` +`std::string testing::PrintToStringParamName(TestParamInfo& info)` A built-in parameterized test name generator which returns the result of [`PrintToString`](#PrintToString) called on `info.param`. Does not work when the diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt index 5c1f0daf..428bd9f8 100644 --- a/googlemock/CMakeLists.txt +++ b/googlemock/CMakeLists.txt @@ -5,7 +5,7 @@ # CMake build script for Google Mock. # # To run the tests for Google Mock itself on Linux, use 'make test' or -# ctest. You can select which tests to run using 'ctest -R regex'. +# ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. option(gmock_build_tests "Build all of Google Mock's own tests." OFF) @@ -36,8 +36,7 @@ endif() # as ${gmock_SOURCE_DIR} and to the root binary directory as # ${gmock_BINARY_DIR}. # Language "C" is required for find_package(Threads). -cmake_minimum_required(VERSION 3.5) -cmake_policy(SET CMP0048 NEW) +cmake_minimum_required(VERSION 3.13) project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) if (COMMAND set_up_hermetic_build) @@ -45,7 +44,7 @@ if (COMMAND set_up_hermetic_build) endif() # Instructs CMake to process Google Test's CMakeLists.txt and add its -# targets to the current scope. We are placing Google Test's binary +# targets to the current scope. We are placing Google Test's binary # directory in a subdirectory of our own as VC compilation may break # if they are the same (the default). add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}") @@ -61,9 +60,9 @@ else() endif() # Although Google Test's CMakeLists.txt calls this function, the -# changes there don't affect the current scope. Therefore we have to +# changes there don't affect the current scope. Therefore we have to # call it again here. -config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake +config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake # Adds Google Mock's and Google Test's header directories to the search path. 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. -# Google Mock libraries. We build them using more strict warnings than what +# Google Mock libraries. We build them using more strict warnings than what # are used for other targets, to ensure that Google Mock can be compiled by # a user aggressive about warnings. if (MSVC) @@ -101,22 +100,18 @@ else() target_link_libraries(gmock_main PUBLIC gmock) set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION}) 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 -# in via add_subdirectory() rather than being a standalone build). -if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") - string(REPLACE ";" "$" dirs "${gmock_build_include_dirs}") - target_include_directories(gmock SYSTEM INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") - target_include_directories(gmock_main SYSTEM INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") -endif() + +string(REPLACE ";" "$" dirs "${gmock_build_include_dirs}") +target_include_directories(gmock SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") +target_include_directories(gmock_main SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") ######################################################################## # -# Install rules +# Install rules. 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 # Google Mock itself. # -# The tests are not built by default. To build them, set the -# gmock_build_tests option to ON. You can do it by running ccmake +# The tests are not built by default. To build them, set the +# gmock_build_tests option to ON. You can do it by running ccmake # or specifying the -Dgmock_build_tests=ON flag when running cmake. if (gmock_build_tests) @@ -136,11 +131,7 @@ if (gmock_build_tests) enable_testing() if (MINGW OR CYGWIN) - if (CMAKE_VERSION VERSION_LESS "2.8.12") - add_compile_options("-Wa,-mbig-obj") - else() - add_definitions("-Wa,-mbig-obj") - endif() + add_compile_options("-Wa,-mbig-obj") endif() ############################################################ @@ -196,7 +187,7 @@ if (gmock_build_tests) cxx_shared_library(shared_gmock_main "${cxx_default}" "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) - # Tests that a binary can be built with Google Mock as a shared library. On + # Tests that a binary can be built with Google Mock as a shared library. On # some system configurations, it may not possible to run the binary without # knowing more details about the system configurations. We do not try to run # this binary. To get a more robust shared library coverage, configure with diff --git a/googlemock/README.md b/googlemock/README.md index 7da60655..e1103b16 100644 --- a/googlemock/README.md +++ b/googlemock/README.md @@ -8,8 +8,8 @@ derive better designs of your system and write better tests. It is inspired by: * [jMock](http://www.jmock.org/) -* [EasyMock](http://www.easymock.org/) -* [Hamcrest](http://code.google.com/p/hamcrest/) +* [EasyMock](https://easymock.org/) +* [Hamcrest](https://code.google.com/p/hamcrest/) It is designed with C++'s specifics in mind. @@ -36,5 +36,5 @@ Details and examples can be found here: * [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html) GoogleMock is a part of -[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a +[GoogleTest C++ testing framework](https://github.com/google/googletest/) and a subject to the same requirements. diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index bd9ba73e..f20258bc 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -175,9 +175,15 @@ struct BuiltInDefaultValueGetter { static T Get() { Assert(false, __FILE__, __LINE__, "Default action undefined for the function return type."); - return internal::Invalid(); +#if defined(__GNUC__) || defined(__clang__) + __builtin_unreachable(); +#elif defined(_MSC_VER) + __assume(0); +#else + return Invalid(); // The above statement will never be reached, but is required in // order for this function to compile. +#endif } }; diff --git a/googlemock/include/gmock/gmock-function-mocker.h b/googlemock/include/gmock/gmock-function-mocker.h index 1a1f126e..d2cb13cd 100644 --- a/googlemock/include/gmock/gmock-function-mocker.h +++ b/googlemock/include/gmock/gmock-function-mocker.h @@ -37,6 +37,7 @@ #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ +#include #include // IWYU pragma: keep #include // 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)); } -template +template constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { return N <= M && internal::PrefixOf(prefix, str); } -template +template constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { return N <= M && internal::PrefixOf(suffix, str + M - N); } -template +template constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { return N == M && internal::PrefixOf(a, b); } -template +template constexpr bool ValidateSpec(const char (&spec)[N]) { return internal::Equals("const", spec) || internal::Equals("override", spec) || diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 0f677137..8052c74a 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -1048,7 +1048,7 @@ class StartsWithMatcher { template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { - const StringType& s2(s); + const StringType s2(s); return s2.length() >= prefix_.length() && s2.substr(0, prefix_.length()) == prefix_; } @@ -1102,7 +1102,7 @@ class EndsWithMatcher { template bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { - const StringType& s2(s); + const StringType s2(s); return s2.length() >= suffix_.length() && s2.substr(s2.length() - suffix_.length()) == suffix_; } diff --git a/googlemock/include/gmock/gmock.h b/googlemock/include/gmock/gmock.h index 568c8c71..c78fb8ee 100644 --- a/googlemock/include/gmock/gmock.h +++ b/googlemock/include/gmock/gmock.h @@ -53,13 +53,14 @@ // // where all clauses are optional and WillOnce() can be repeated. -#include "gmock/gmock-actions.h" -#include "gmock/gmock-cardinalities.h" -#include "gmock/gmock-function-mocker.h" -#include "gmock/gmock-matchers.h" -#include "gmock/gmock-more-actions.h" -#include "gmock/gmock-more-matchers.h" -#include "gmock/gmock-nice-strict.h" +#include "gmock/gmock-actions.h" // IWYU pragma: export +#include "gmock/gmock-cardinalities.h" // IWYU pragma: export +#include "gmock/gmock-function-mocker.h" // IWYU pragma: export +#include "gmock/gmock-matchers.h" // IWYU pragma: export +#include "gmock/gmock-more-actions.h" // IWYU pragma: export +#include "gmock/gmock-more-matchers.h" // IWYU pragma: export +#include "gmock/gmock-nice-strict.h" // IWYU pragma: export +#include "gmock/gmock-spec-builders.h" // IWYU pragma: export #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc index 07bba4f0..81a5b7ea 100644 --- a/googlemock/src/gmock-matchers.cc +++ b/googlemock/src/gmock-matchers.cc @@ -120,7 +120,7 @@ GTEST_API_ std::string FormatMatcherDescription( // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method". // "Introduction to Algorithms (Second ed.)", pp. 651-664. // [2] "Ford-Fulkerson algorithm", Wikipedia, -// 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm' +// 'https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm' class MaxBipartiteMatchState { public: explicit MaxBipartiteMatchState(const MatchMatrix& graph) diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index fb37b53a..6b554127 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -32,7 +32,8 @@ #include "gmock/gmock.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 extern "C" { #endif diff --git a/googlemock/test/gmock-matchers-comparisons_test.cc b/googlemock/test/gmock-matchers-comparisons_test.cc index b2ce99e1..5b75b457 100644 --- a/googlemock/test/gmock-matchers-comparisons_test.cc +++ b/googlemock/test/gmock-matchers-comparisons_test.cc @@ -1769,6 +1769,15 @@ TEST(StartsWithTest, CanDescribeSelf) { EXPECT_EQ("starts with \"Hi\"", Describe(m)); } +TEST(StartsWithTest, WorksWithStringMatcherOnStringViewMatchee) { +#if GTEST_INTERNAL_HAS_STRING_VIEW + EXPECT_THAT(internal::StringView("talk to me goose"), + StartsWith(std::string("talk"))); +#else + GTEST_SKIP() << "Not applicable without internal::StringView."; +#endif // GTEST_INTERNAL_HAS_STRING_VIEW +} + // Tests EndsWith(s). TEST(EndsWithTest, MatchesStringWithGivenSuffix) { diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 221de2d2..aaf88d74 100644 --- a/googlemock/test/gmock-spec-builders_test.cc +++ b/googlemock/test/gmock-spec-builders_test.cc @@ -906,7 +906,7 @@ TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) { " - returning default value.")); } -TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) { +TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) { MockB b; std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1)); diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index 95bfa442..51a67c91 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -5,7 +5,7 @@ # CMake build script for Google Test. # # To run the tests for Google Test itself on Linux, use 'make test' or -# ctest. You can select which tests to run using 'ctest -R regex'. +# ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. # When other libraries are using a shared version of runtime libraries, @@ -35,7 +35,7 @@ endif() ######################################################################## # -# Project-wide settings +# Project-wide settings. # Name of the project. # @@ -44,21 +44,16 @@ endif() # ${gtest_BINARY_DIR}. # Language "C" is required for find_package(Threads). -# Project version: +# Project version. -cmake_minimum_required(VERSION 3.5) -cmake_policy(SET CMP0048 NEW) +cmake_minimum_required(VERSION 3.13) project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) -if (POLICY CMP0063) # Visibility - cmake_policy(SET CMP0063 NEW) -endif (POLICY CMP0063) - if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() -# These commands only run if this is the main project +# These commands only run if this is the main project. if(CMAKE_PROJECT_NAME STREQUAL "gtest" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to @@ -88,7 +83,7 @@ include(cmake/internal_utils.cmake) config_compiler_and_linker() # Defined in internal_utils.cmake. # Needed to set the namespace for both the export targets and the -# alias libraries +# alias libraries. set(cmake_package_name GTest CACHE INTERNAL "") # Create the CMake package file descriptors. @@ -100,12 +95,14 @@ if (INSTALL_GTEST) set(version_file "${generated_dir}/${cmake_package_name}ConfigVersion.cmake") write_basic_package_version_file(${version_file} VERSION ${GOOGLETEST_VERSION} COMPATIBILITY AnyNewerVersion) install(EXPORT ${targets_export_name} + COMPONENT "${PROJECT_NAME}" NAMESPACE ${cmake_package_name}:: DESTINATION ${cmake_files_install_dir}) set(config_file "${generated_dir}/${cmake_package_name}Config.cmake") configure_package_config_file("${gtest_SOURCE_DIR}/cmake/Config.cmake.in" "${config_file}" INSTALL_DESTINATION ${cmake_files_install_dir}) install(FILES ${version_file} ${config_file} + COMPONENT "${PROJECT_NAME}" DESTINATION ${cmake_files_install_dir}) endif() @@ -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. -# Google Test libraries. We build them using more strict warnings than what +# Google Test libraries. We build them using more strict warnings than what # are used for other targets, to ensure that gtest can be compiled by a user # aggressive about warnings. cxx_library(gtest "${cxx_strict}" src/gtest-all.cc) @@ -143,18 +140,13 @@ if(GTEST_HAS_ABSL) endif() cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc) set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION}) -# If the CMake version supports it, attach header directory information -# to the targets for when we are part of a parent build (ie being pulled -# in via add_subdirectory() rather than being a standalone build). -if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") - string(REPLACE ";" "$" dirs "${gtest_build_include_dirs}") - target_include_directories(gtest SYSTEM INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") - target_include_directories(gtest_main SYSTEM INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") -endif() +string(REPLACE ";" "$" dirs "${gtest_build_include_dirs}") +target_include_directories(gtest SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") +target_include_directories(gtest_main SYSTEM INTERFACE + "$" + "$/${CMAKE_INSTALL_INCLUDEDIR}>") if(CMAKE_SYSTEM_NAME MATCHES "QNX") target_link_libraries(gtest PUBLIC regex) endif() @@ -162,15 +154,15 @@ target_link_libraries(gtest_main PUBLIC gtest) ######################################################################## # -# Install rules +# Install rules. install_project(gtest gtest_main) ######################################################################## # # Samples on how to link user tests with gtest or gtest_main. # -# They are not built by default. To build them, set the -# gtest_build_samples option to ON. You can do it by running ccmake +# They are not built by default. To build them, set the +# gtest_build_samples option to ON. You can do it by running ccmake # or specifying the -Dgtest_build_samples=ON flag when running cmake. if (gtest_build_samples) @@ -193,8 +185,8 @@ endif() # You can skip this section if you aren't interested in testing # Google Test itself. # -# The tests are not built by default. To build them, set the -# gtest_build_tests option to ON. You can do it by running ccmake +# The tests are not built by default. To build them, set the +# gtest_build_tests option to ON. You can do it by running ccmake # or specifying the -Dgtest_build_tests=ON flag when running cmake. if (gtest_build_tests) @@ -276,7 +268,7 @@ if (gtest_build_tests) py_test(gtest_skip_environment_check_output_test) # Visual Studio .NET 2003 does not support STL with exceptions disabled. - if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003 + if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003 cxx_executable_with_flags( googletest-catch-exceptions-no-ex-test_ "${cxx_no_exception}" diff --git a/googletest/README.md b/googletest/README.md index 4cad12f7..44fd69b4 100644 --- a/googletest/README.md +++ b/googletest/README.md @@ -12,7 +12,7 @@ GoogleTest comes with a CMake build script ([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.). If you don't have CMake installed already, you can download it for free from -. +. CMake works by generating native makefiles or build projects that can be used in the compiler environment of your choice. You can either build GoogleTest as a @@ -25,7 +25,7 @@ When building GoogleTest as a standalone project, the typical workflow starts with ``` -git clone https://github.com/google/googletest.git -b v1.13.0 +git clone https://github.com/google/googletest.git -b v1.14.0 cd googletest # Main directory of the cloned repository. mkdir build # Create a directory to hold the build output. cd build @@ -124,10 +124,10 @@ match the project in which it is included. #### 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 -project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command along -with `set(CMAKE_CXX_STANDARD_REQUIRED ON). If this is not feasible, for example +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 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. @@ -145,7 +145,7 @@ We list the most frequently used macros below. For a complete list, see file ### Multi-threaded Tests GoogleTest is thread-safe where the pthread library is available. After -`#include "gtest/gtest.h"`, you can check the +`#include `, you can check the `GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is `#defined` to 1, no if it's undefined.). diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake index a3fb3cad..21887b2e 100644 --- a/googletest/cmake/internal_utils.cmake +++ b/googletest/cmake/internal_utils.cmake @@ -12,14 +12,6 @@ # Test and Google Mock's option() definitions, and thus must be # called *after* the options have been defined. -if (POLICY CMP0054) - cmake_policy(SET CMP0054 NEW) -endif (POLICY CMP0054) - -if (POLICY CMP0069) - cmake_policy(SET CMP0069 NEW) -endif (POLICY CMP0069) - # 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 @@ -37,7 +29,7 @@ macro(fix_default_compiler_settings_) CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt) # When Google Test is built as a shared library, it should also use - # shared runtime libraries. Otherwise, it may end up with multiple + # shared runtime libraries. Otherwise, it may end up with multiple # copies of runtime library data in different modules, resulting in # hard-to-find crashes. When it is built as a static library, it is # preferable to use CRT as static libraries, as we don't have to rely @@ -63,11 +55,11 @@ macro(fix_default_compiler_settings_) endmacro() # Defines the compiler/linker flags used to build Google Test and -# Google Mock. You can tweak these definitions to suit your need. A +# Google Mock. You can tweak these definitions to suit your need. A # variable's value is empty before it's explicitly assigned to. macro(config_compiler_and_linker) # Note: pthreads on MinGW is not supported, even if available - # instead, we use windows threading primitives + # instead, we use windows threading primitives. unset(GTEST_HAS_PTHREAD) if (NOT gtest_disable_pthreads AND NOT MINGW) # Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT. @@ -87,8 +79,8 @@ macro(config_compiler_and_linker) set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1") set(cxx_no_exception_flags "-EHs-c- -D_HAS_EXCEPTIONS=0") set(cxx_no_rtti_flags "-GR-") - # Suppress "unreachable code" warning - # http://stackoverflow.com/questions/3232669 explains the issue. + # Suppress "unreachable code" warning, + # https://stackoverflow.com/questions/3232669 explains the issue. set(cxx_base_flags "${cxx_base_flags} -wd4702") # Ensure MSVC treats source files as UTF-8 encoded. if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") @@ -118,7 +110,7 @@ macro(config_compiler_and_linker) set(cxx_exception_flags "-fexceptions") set(cxx_no_exception_flags "-fno-exceptions") # Until version 4.3.2, GCC doesn't define a macro to indicate - # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI + # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # explicitly. set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0") set(cxx_strict_flags @@ -135,7 +127,7 @@ macro(config_compiler_and_linker) set(cxx_exception_flags "-qeh") set(cxx_no_exception_flags "-qnoeh") # Until version 9.0, Visual Age doesn't define a macro to indicate - # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI + # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # explicitly. set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "HP") @@ -165,7 +157,7 @@ macro(config_compiler_and_linker) set(cxx_strict "${cxx_default} ${cxx_strict_flags}") endmacro() -# Defines the gtest & gtest_main libraries. User tests should link +# Defines the gtest & gtest_main libraries. User tests should link # with one of them. function(cxx_library_with_type name type cxx_flags) # type can be either STATIC or SHARED to denote a static or shared library. @@ -175,7 +167,7 @@ function(cxx_library_with_type name type cxx_flags) set_target_properties(${name} PROPERTIES COMPILE_FLAGS "${cxx_flags}") - # Set the output directory for build artifacts + # Set the output directory for build artifacts. set_target_properties(${name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" @@ -183,7 +175,7 @@ function(cxx_library_with_type name type cxx_flags) ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") - # make PDBs match library name + # Make PDBs match library name. get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX) set_target_properties(${name} PROPERTIES @@ -196,23 +188,14 @@ function(cxx_library_with_type name type cxx_flags) set_target_properties(${name} PROPERTIES COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1") - if (NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") - target_compile_definitions(${name} INTERFACE - $) - endif() + target_compile_definitions(${name} INTERFACE + $) endif() if (DEFINED GTEST_HAS_PTHREAD) - if ("${CMAKE_VERSION}" VERSION_LESS "3.1.0") - set(threads_spec ${CMAKE_THREAD_LIBS_INIT}) - else() - set(threads_spec Threads::Threads) - endif() - target_link_libraries(${name} PUBLIC ${threads_spec}) + target_link_libraries(${name} PUBLIC Threads::Threads) endif() - if (NOT "${CMAKE_VERSION}" VERSION_LESS "3.8") - target_compile_features(${name} PUBLIC cxx_std_14) - endif() + target_compile_features(${name} PUBLIC cxx_std_14) endfunction() ######################################################################## @@ -229,7 +212,7 @@ endfunction() # cxx_executable_with_flags(name cxx_flags libs srcs...) # -# creates a named C++ executable that depends on the given libraries and +# Creates a named C++ executable that depends on the given libraries and # is built from the given source files with the given compiler flags. function(cxx_executable_with_flags name cxx_flags libs) add_executable(${name} ${ARGN}) @@ -256,34 +239,19 @@ endfunction() # cxx_executable(name dir lib srcs...) # -# creates a named target that depends on the given libs and is built -# from the given source files. dir/name.cc is implicitly included in +# Creates a named target that depends on the given libs and is built +# from the given source files. dir/name.cc is implicitly included in # the source file list. function(cxx_executable name dir libs) cxx_executable_with_flags( ${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN}) endfunction() -# CMP0094 policy enables finding a Python executable in the LOCATION order, as -# 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() +find_package(Python3) # cxx_test_with_flags(name cxx_flags libs srcs...) # -# creates a named C++ test that depends on the given libs and is built +# Creates a named C++ test that depends on the given libs and is built # from the given source files with the given compiler flags. function(cxx_test_with_flags name cxx_flags libs) cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN}) @@ -292,8 +260,8 @@ endfunction() # cxx_test(name libs srcs...) # -# creates a named test target that depends on the given libs and is -# built from the given source files. Unlike cxx_test_with_flags, +# Creates a named test target that depends on the given libs and is +# built from the given source files. Unlike cxx_test_with_flags, # test/name.cc is already implicitly included in the source file list. function(cxx_test name libs) cxx_test_with_flags("${name}" "${cxx_default}" "${libs}" @@ -302,37 +270,25 @@ endfunction() # py_test(name) # -# creates a Python test with the given name whose main module is in -# test/name.py. It does nothing if Python is not installed. +# Creates a Python test with the given name whose main module is in +# test/name.py. It does nothing if Python is not installed. function(py_test name) - if (PYTHONINTERP_FOUND) - if ("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" VERSION_GREATER 3.1) - if (CMAKE_CONFIGURATION_TYPES) - # Multi-configuration build generators as for Visual Studio save - # output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug, - # Release etc.), so we have to provide it here. - add_test(NAME ${name} - COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py - --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$ ${ARGN}) - else (CMAKE_CONFIGURATION_TYPES) - # Single-configuration build generators like Makefile generators - # don't have subdirs below CMAKE_CURRENT_BINARY_DIR. - add_test(NAME ${name} - COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py - --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN}) - endif (CMAKE_CONFIGURATION_TYPES) - else() - # ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can - # directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known - # only at ctest runtime (by calling ctest -c ), 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) + if (NOT Python3_Interpreter_FOUND) + return() + endif() + + get_cmake_property(is_multi "GENERATOR_IS_MULTI_CONFIG") + set(build_dir "${CMAKE_CURRENT_BINARY_DIR}") + if (is_multi) + set(build_dir "${CMAKE_CURRENT_BINARY_DIR}/$") + endif() + + add_test(NAME ${name} + COMMAND Python3::Interpreter ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py + --build_dir=${build_dir} ${ARGN}) + + # Make the Python import path consistent between Bazel and CMake. + set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR}) endfunction() # install_project(targets...) @@ -341,21 +297,24 @@ endfunction() function(install_project) if(INSTALL_GTEST) install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/" + COMPONENT "${PROJECT_NAME}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") # Install the project targets. install(TARGETS ${ARGN} EXPORT ${targets_export_name} + COMPONENT "${PROJECT_NAME}" RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") - # Install PDBs + # Install PDBs. foreach(t ${ARGN}) get_target_property(t_pdb_name ${t} COMPILE_PDB_NAME) get_target_property(t_pdb_name_debug ${t} COMPILE_PDB_NAME_DEBUG) get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY) install(FILES "${t_pdb_output_directory}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$:${t_pdb_name_debug}>$<$>:${t_pdb_name}>.pdb" + COMPONENT "${PROJECT_NAME}" DESTINATION ${CMAKE_INSTALL_LIBDIR} OPTIONAL) endforeach() @@ -366,6 +325,7 @@ function(install_project) configure_file("${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in" "${configured_pc}" @ONLY) install(FILES "${configured_pc}" + COMPONENT "${PROJECT_NAME}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") endforeach() endif() diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index 4d4b152b..448ac6b7 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -56,6 +56,13 @@ #include "gtest/internal/gtest-port.h" +#ifdef GTEST_HAS_ABSL +#include + +#include "absl/strings/has_absl_stringify.h" +#include "absl/strings/str_cat.h" +#endif // GTEST_HAS_ABSL + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ /* class A needs to have dll-interface to be used by clients of class B */) @@ -111,8 +118,17 @@ class GTEST_API_ Message { *ss_ << str; } - // Streams a non-pointer value to this object. - template + // Streams a non-pointer value to this object. If building a version of + // GoogleTest with ABSL, this overload is only enabled if the value does not + // have an AbslStringify definition. + template < + typename T +#ifdef GTEST_HAS_ABSL + , + typename std::enable_if::value, // NOLINT + int>::type = 0 +#endif // GTEST_HAS_ABSL + > inline Message& operator<<(const T& val) { // Some libraries overload << for STL containers. These // overloads are defined in the global namespace instead of ::std. @@ -133,6 +149,21 @@ class GTEST_API_ Message { return *this; } +#ifdef GTEST_HAS_ABSL + // Streams a non-pointer value with an AbslStringify definition to this + // object. + template ::value, // NOLINT + int>::type = 0> + inline Message& operator<<(const T& val) { + // ::operator<< is needed here for a similar reason as with the non-Abseil + // version above + using ::operator<<; + *ss_ << absl::StrCat(val); + return *this; + } +#endif // GTEST_HAS_ABSL + // Streams a pointer value to this object. // // This function is an overload of the previous one. When you diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 539d99c4..1b12ef68 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -43,6 +43,9 @@ // 1. foo::PrintTo(const T&, ostream*) // 2. operator<<(ostream&, const T&) defined in either foo or the // global namespace. +// * Prefer AbslStringify(..) to operator<<(..), per https://abseil.io/tips/215. +// * Define foo::PrintTo(..) if the type already has AbslStringify(..), but an +// alternative presentation in test results is of interest. // // However if T is an STL-style container then it is printed element-wise // unless foo::PrintTo(const T&, ostream*) is defined. Note that @@ -112,9 +115,17 @@ #include #include +#ifdef GTEST_HAS_ABSL +#include "absl/strings/has_absl_stringify.h" +#include "absl/strings/str_cat.h" +#endif // GTEST_HAS_ABSL #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" +#if GTEST_INTERNAL_HAS_STD_SPAN +#include // NOLINT +#endif // GTEST_INTERNAL_HAS_STD_SPAN + namespace testing { // Definitions in the internal* namespaces are subject to change without notice. @@ -124,13 +135,32 @@ namespace internal { template void UniversalPrint(const T& value, ::std::ostream* os); +template +struct IsStdSpan { + static constexpr bool value = false; +}; + +#if GTEST_INTERNAL_HAS_STD_SPAN +template +struct IsStdSpan> { + static constexpr bool value = true; +}; +#endif // GTEST_INTERNAL_HAS_STD_SPAN + // Used to print an STL-style container when the user doesn't define // a PrintTo() for it. +// +// NOTE: Since std::span does not have const_iterator until C++23, it would +// fail IsContainerTest before C++23. However, IsContainerTest only uses +// the presence of const_iterator to avoid treating iterators as containers +// because of iterator::iterator. Which means std::span satisfies the *intended* +// condition of IsContainerTest. struct ContainerPrinter { template (0)) == sizeof(IsContainer)) && - !IsRecursiveContainer::value>::type> + ((sizeof(IsContainerTest(0)) == sizeof(IsContainer)) && + !IsRecursiveContainer::value) || + IsStdSpan::value>::type> static void PrintValue(const T& container, std::ostream* os) { const size_t kMaxCount = 32; // The maximum number of elements to print. *os << '{'; @@ -260,6 +290,17 @@ struct ConvertibleToStringViewPrinter { #endif }; +#ifdef GTEST_HAS_ABSL +struct ConvertibleToAbslStringifyPrinter { + template ::value>::type> // NOLINT + static void PrintValue(const T& value, ::std::ostream* os) { + *os << absl::StrCat(value); + } +}; +#endif // GTEST_HAS_ABSL + // Prints the given number of bytes in the given object to the given // ostream. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, @@ -298,8 +339,8 @@ struct FindFirstPrinter< // - Print containers (they have begin/end/etc). // - Print function pointers. // - Print object pointers. -// - Use the stream operator, if available. // - Print protocol buffers. +// - Use the stream operator, if available. // - Print types convertible to BiggestInt. // - Print types convertible to StringView, if available. // - 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< T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter, ProtobufPrinter, +#ifdef GTEST_HAS_ABSL + ConvertibleToAbslStringifyPrinter, +#endif // GTEST_HAS_ABSL internal_stream_operator_without_lexical_name_lookup::StreamPrinter, ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type; @@ -475,7 +519,7 @@ GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os); inline void PrintTo(char16_t c, ::std::ostream* os) { PrintTo(ImplicitCast_(c), os); } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t inline void PrintTo(char8_t c, ::std::ostream* os) { PrintTo(ImplicitCast_(c), os); } @@ -531,7 +575,7 @@ int AppropriateResolution(FloatType val) { } else if (val >= 0.0001) { mulfor6 = 1e9; } - if (static_cast(static_cast(val * mulfor6 + 0.5)) / + if (static_cast(static_cast(val * mulfor6 + 0.5)) / mulfor6 == val) return 6; @@ -546,7 +590,7 @@ int AppropriateResolution(FloatType val) { } else if (val >= 1e6) { // 1,000,000 to 9,999,999 divfor6 = 10; } - if (static_cast(static_cast(val / divfor6 + 0.5)) * + if (static_cast(static_cast(val / divfor6 + 0.5)) * divfor6 == val) 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) { PrintTo(ImplicitCast_(s), os); } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t // Overloads for u8 strings. GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os); inline void PrintTo(char8_t* s, ::std::ostream* os) { @@ -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, ::std::ostream* os); -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t // This overload prints a (const) char8_t array compactly. GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len, ::std::ostream* os); diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 84125034..a932e686 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -51,7 +51,6 @@ #include #include -#include #include #include #include @@ -1055,6 +1054,10 @@ class GTEST_API_ TestEventListeners { return default_xml_generator_; } + // Controls whether events will be forwarded by the repeater to the + // listeners in the list. + void SuppressEventForwarding(bool); + private: friend class TestSuite; friend class TestInfo; @@ -1084,7 +1087,6 @@ class GTEST_API_ TestEventListeners { // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool EventForwardingEnabled() const; - void SuppressEventForwarding(); // The actual list of listeners. internal::TestEventRepeater* repeater_; @@ -1571,12 +1573,12 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, } ::std::stringstream lhs_ss; - lhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << lhs_value; + lhs_ss.precision(std::numeric_limits::digits10 + 2); + lhs_ss << lhs_value; ::std::stringstream rhs_ss; - rhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << rhs_value; + rhs_ss.precision(std::numeric_limits::digits10 + 2); + rhs_ss << rhs_value; return EqFailure(lhs_expression, rhs_expression, StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss), @@ -2098,8 +2100,8 @@ class GTEST_API_ ScopedTrace { // Assuming that each thread maintains its own stack of traces. // Therefore, a SCOPED_TRACE() would (correctly) only affect the // assertions in its own thread. -#define SCOPED_TRACE(message) \ - ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \ +#define SCOPED_TRACE(message) \ + const ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \ __FILE__, __LINE__, (message)) // Compile-time assertion for type equality. diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 8e9c988b..61536d65 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -52,9 +52,7 @@ GTEST_DECLARE_string_(internal_run_death_test); namespace testing { namespace internal { -// Names of the flags (needed for parsing Google Test flags). -const char kDeathTestStyleFlag[] = "death_test_style"; -const char kDeathTestUseFork[] = "death_test_use_fork"; +// Name of the flag (needed for parsing Google Test flag). const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; #ifdef GTEST_HAS_DEATH_TEST diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 317894e7..4f077fcf 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -58,7 +58,6 @@ #include #include -#include #include #include #include @@ -79,7 +78,7 @@ // // will result in the token foo__LINE__, instead of foo followed by // 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_IMPL_(foo, bar) foo##bar @@ -170,7 +169,7 @@ namespace edit_distance { // All edits cost the same, with replace having lower priority than // add/remove. // Simple implementation of the Wagner-Fischer algorithm. -// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm +// See https://en.wikipedia.org/wiki/Wagner-Fischer_algorithm enum EditType { kMatch, kAdd, kRemove, kReplace }; GTEST_API_ std::vector CalculateOptimalEdits( const std::vector& left, const std::vector& right); @@ -237,7 +236,7 @@ GTEST_API_ std::string GetBoolAssertionFailureMessage( // For double, there are 11 exponent bits and 52 fraction bits. // // 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: // @@ -282,7 +281,7 @@ class FloatingPoint { // bits. Therefore, 4 should be enough for ordinary use. // // 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; // Constructs a FloatingPoint from a raw floating-point number. @@ -363,7 +362,7 @@ class FloatingPoint { // N - 1 (the biggest number representable using // 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. static Bits SignAndMagnitudeToBiased(const Bits& sam) { if (kSignBitMask & sam) { @@ -1497,19 +1496,20 @@ class NeverThrown { gtest_ar_, text, #actual, #expected) \ .c_str()) -#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \ - : fail("Expected: " #statement \ - " doesn't generate new fatal " \ - "failures in the current thread.\n" \ +#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + const ::testing::internal::HasNewFatalFailureHelper \ + gtest_fatal_failure_checker; \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ + } \ + } else /* NOLINT */ \ + GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \ + : fail("Expected: " #statement \ + " doesn't generate new fatal " \ + "failures in the current thread.\n" \ " Actual: it does.") // Expands to the name of the class that implements the given test. diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index 6a81c37f..b04f7020 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -584,7 +584,9 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { GTEST_CHECK_(IsValidParamName(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) << "Duplicate parameterized test name '" << param_name << "', in " diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h index 04064606..3162f2b1 100644 --- a/googletest/include/gtest/internal/gtest-port-arch.h +++ b/googletest/include/gtest/internal/gtest-port-arch.h @@ -113,6 +113,10 @@ #define GTEST_OS_XTENSA 1 #elif defined(__hexagon__) #define GTEST_OS_QURT 1 +#elif defined(CPU_QN9090) || defined(CPU_QN9090HN) +#define GTEST_OS_NXP_QN9090 1 +#elif defined(NRF52) +#define GTEST_OS_NRF52 1 #endif // __CYGWIN__ #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index d71110c0..d061a49b 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -208,6 +208,8 @@ // or // UniversalPrinter // specializations. Always defined to 0 or 1. +// GTEST_INTERNAL_HAS_STD_SPAN - for enabling UniversalPrinter +// specializations. Always defined to 0 or 1 // GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher or // Matcher // specializations. Always defined to 0 or 1. @@ -220,7 +222,6 @@ // GTEST_HAS_ALT_PATH_SEP_ - 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_DOWNCAST_ - Always defined to 0 or 1. // GTEST_HAS_NOTIFICATION_- Always defined to 0 or 1. // // Synchronization: @@ -280,6 +281,22 @@ #error C++ versions less than C++14 are not supported. #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()) +#include // C++20 and later +#elif (!defined(__has_include) || GTEST_INTERNAL_HAS_INCLUDE()) +#include // Pre-C++20 +#endif + #include // for isspace, etc #include // for ptrdiff_t #include @@ -313,10 +330,6 @@ #include "gtest/internal/custom/gtest-port.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_ #define GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ 0 #endif @@ -505,7 +518,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #if (!(defined(GTEST_OS_LINUX_ANDROID) || defined(GTEST_OS_CYGWIN) || \ defined(GTEST_OS_SOLARIS) || defined(GTEST_OS_HAIKU) || \ 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 #else #define GTEST_HAS_STD_WSTRING 0 @@ -613,7 +627,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Determines whether clone(2) is supported. // Usually it will only be available on Linux, excluding // 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 // 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_ #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) -#elif GTEST_CREATE_SHARED_LIBRARY +#elif defined(GTEST_CREATE_SHARED_LIBRARY) && GTEST_CREATE_SHARED_LIBRARY #define GTEST_API_ __declspec(dllexport) #endif #elif GTEST_HAVE_ATTRIBUTE_(visibility) @@ -924,9 +938,11 @@ using std::tuple_size; namespace internal { // 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. -class Secret; +class Secret { + Secret(const Secret&) = delete; +}; // A helper for suppressing warnings on constant condition. It just // returns 'condition'. @@ -1143,47 +1159,6 @@ inline To ImplicitCast_(To 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(foo)) HandleASubclass1Object(foo); -// if (dynamic_cast(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 // use like this: DownCast_(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_(to); - } - -#if GTEST_HAS_RTTI - // RTTI: debug mode only! - GTEST_CHECK_(f == nullptr || dynamic_cast(f) != nullptr); -#endif - return static_cast(f); -} - // Downcasts the pointer of type Base to Derived. // Derived must be a subclass of Base. The parameter MUST // 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. template Derived* CheckedDowncastToActualType(Base* base) { + static_assert(std::is_base_of::value, + "target type not derived from source type"); #if GTEST_HAS_RTTI - GTEST_CHECK_(typeid(*base) == typeid(Derived)); -#endif - -#if GTEST_HAS_DOWNCAST_ - return ::down_cast(base); -#elif GTEST_HAS_RTTI - return dynamic_cast(base); // NOLINT -#else - return static_cast(base); // Poor man's downcast. + GTEST_CHECK_(base == nullptr || dynamic_cast(base) != nullptr); #endif + return static_cast(base); } #if GTEST_HAS_STREAM_REDIRECTION @@ -1995,7 +1965,7 @@ inline bool IsUpper(char ch) { inline bool IsXDigit(char ch) { return isxdigit(static_cast(ch)) != 0; } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t inline bool IsXDigit(char8_t ch) { return isxdigit(static_cast(ch)) != 0; } @@ -2397,9 +2367,9 @@ using Any = ::absl::any; } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L && \ - (!defined(_MSC_VER) || GTEST_HAS_RTTI) +#if defined(__cpp_lib_any) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L && \ + (!defined(_MSC_VER) || GTEST_HAS_RTTI)) // Otherwise for C++17 and higher use std::any for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_ANY 1 @@ -2411,8 +2381,7 @@ using Any = ::std::any; } // namespace testing // The case where absl is configured NOT to alias std::any is not // supported. -#endif // __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L -#endif // __has_include +#endif // __cpp_lib_any #endif // GTEST_HAS_ABSL #ifndef GTEST_INTERNAL_HAS_ANY @@ -2432,8 +2401,8 @@ inline ::absl::nullopt_t Nullopt() { return ::absl::nullopt; } } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L +#if defined(__cpp_lib_optional) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L) // Otherwise for C++17 and higher use std::optional for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_OPTIONAL 1 @@ -2447,14 +2416,22 @@ inline ::std::nullopt_t Nullopt() { return ::std::nullopt; } } // namespace testing // The case where absl is configured NOT to alias std::optional is not // supported. -#endif // __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L -#endif // __has_include +#endif // __cpp_lib_optional #endif // GTEST_HAS_ABSL #ifndef GTEST_INTERNAL_HAS_OPTIONAL #define GTEST_INTERNAL_HAS_OPTIONAL 0 #endif +#if defined(__cpp_lib_span) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + 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 // Always use absl::string_view for Matcher<> specializations if googletest // is built with absl support. @@ -2466,8 +2443,9 @@ using StringView = ::absl::string_view; } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L +#if defined(__cpp_lib_string_view) || \ + (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L) // Otherwise for C++17 and higher use std::string_view for Matcher<> // specializations. #define GTEST_INTERNAL_HAS_STRING_VIEW 1 @@ -2479,9 +2457,7 @@ using StringView = ::std::string_view; } // namespace testing // The case where absl is configured NOT to alias std::string_view is not // supported. -#endif // __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= - // 201703L -#endif // __has_include +#endif // __cpp_lib_string_view #endif // GTEST_HAS_ABSL #ifndef GTEST_INTERNAL_HAS_STRING_VIEW @@ -2500,8 +2476,8 @@ using Variant = ::absl::variant; } // namespace internal } // namespace testing #else -#ifdef __has_include -#if __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L +#if defined(__cpp_lib_variant) || (GTEST_INTERNAL_HAS_INCLUDE() && \ + GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L) // Otherwise for C++17 and higher use std::variant for UniversalPrinter<> // specializations. #define GTEST_INTERNAL_HAS_VARIANT 1 @@ -2513,16 +2489,16 @@ using Variant = ::std::variant; } // namespace internal } // namespace testing // The case where absl is configured NOT to alias std::variant is not supported. -#endif // __has_include() && GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L -#endif // __has_include +#endif // __cpp_lib_variant #endif // GTEST_HAS_ABSL #ifndef GTEST_INTERNAL_HAS_VARIANT #define GTEST_INTERNAL_HAS_VARIANT 0 #endif -#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ - GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L +#if (defined(__cpp_constexpr) && !defined(__cpp_inline_variables)) || \ + (defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ + GTEST_INTERNAL_CPLUSPLUS_LANG < 201703L) #define GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL 1 #endif diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 4cf78e71..8417a300 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -783,7 +783,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { StreamableToString(static_cast(::GetCurrentProcessId())) + // size_t has the same width as pointers on both 32-bit and 64-bit // 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(write_handle)) + "|" + StreamableToString(reinterpret_cast(event_handle_.Get())); @@ -1128,7 +1128,7 @@ DeathTest::TestRole NoExecDeathTest::AssumeRole() { LogToStderr(); // Event forwarding to the listeners of event listener API mush be shut // down in death test subprocesses. - GetUnitTestImpl()->listeners()->SuppressEventForwarding(); + GetUnitTestImpl()->listeners()->SuppressEventForwarding(true); g_in_fast_death_test_child = true; return EXECUTE_TEST; } else { diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index 177588c1..fe9be924 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -102,7 +102,8 @@ FilePath FilePath::GetCurrentDir() { #if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \ defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_ESP8266) || \ 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 // something reasonable. return FilePath(kCurrentDirectoryString); @@ -335,7 +336,7 @@ bool FilePath::CreateDirectoriesRecursively() const { return false; } - if (pathname_.length() == 0 || pathname_ == kCurrentDirectoryString || this->DirectoryExists()) { + if (pathname_.empty() || pathname_ == kCurrentDirectoryString || this->DirectoryExists()) { return true; } @@ -356,7 +357,8 @@ bool FilePath::CreateFolder() const { #elif defined(GTEST_OS_WINDOWS) int result = _mkdir(pathname_.c_str()); #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 int result = 0; #else diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index 5ba557fe..4799a1e7 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -312,7 +312,7 @@ void ShuffleRange(internal::Random* random, int begin, int end, << begin << ", " << size << "]."; // 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--) { const int last_in_range = begin + range_width - 1; const int selected = @@ -387,10 +387,10 @@ class GTEST_API_ UnitTestOptions { #ifdef GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. - // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the - // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. + // Returns EXCEPTION_EXECUTE_HANDLER if given SEH exception was handled, or + // EXCEPTION_CONTINUE_SEARCH otherwise. // 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 // 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, internal::TearDownTestSuiteFunc tear_down_tc, TestInfo* test_info) { -#ifdef GTEST_HAS_DEATH_TEST +#if GTEST_HAS_FILE_SYSTEM // In order to support thread-safe death tests, we need to // remember the original working directory when the test program // 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()) << "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(), set_up_tc, tear_down_tc) diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index 2aaf2bcc..3bb7dd45 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -158,13 +158,13 @@ size_t GetThreadCount() { // we cannot detect it. size_t GetThreadCount() { int mib[] = { - CTL_KERN, - KERN_PROC, - KERN_PROC_PID, - getpid(), + CTL_KERN, + KERN_PROC, + KERN_PROC_PID, + getpid(), #ifdef GTEST_OS_NETBSD - sizeof(struct kinfo_proc), - 1, + sizeof(struct kinfo_proc), + 1, #endif }; 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) { 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 // full match. const size_t full_regex_len = strlen(regex) + 10; char* const full_pattern = new char[full_regex_len]; 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 // previous expression returns false. Otherwise partial_regex_ may // 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. if (is_valid_) { 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_) << "Regular expression \"" << regex @@ -1028,6 +1039,16 @@ GTEST_DISABLE_MSC_DEPRECATED_PUSH_() #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). class CapturedStream { public: @@ -1064,7 +1085,13 @@ class CapturedStream { // The location /data/local/tmp is directly accessible from native code. // '/sdcard' and other variants cannot be relied on, as they are not // 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) 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)); 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]); #else name_template = "/tmp/"; diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc index 2b470678..e3acecba 100644 --- a/googletest/src/gtest-printers.cc +++ b/googletest/src/gtest-printers.cc @@ -216,7 +216,7 @@ static const char* GetCharWidthPrefix(signed 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"; } #endif @@ -232,7 +232,7 @@ static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { return PrintAsStringLiteralTo(ToChar32(c), os); } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) { return PrintAsStringLiteralTo(ToChar32(c), os); } @@ -395,7 +395,7 @@ void UniversalPrintArray(const char* begin, size_t len, ostream* 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 // 'begin'. 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); } -#ifdef __cpp_char8_t +#ifdef __cpp_lib_char8_t void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); } #endif diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index fb7512c1..85d45b58 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -43,6 +43,7 @@ #include #include // NOLINT #include +#include // NOLINT: raise(3) is used on some platforms #include #include #include @@ -863,30 +864,39 @@ bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, } #if GTEST_HAS_SEH -// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the -// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. -// This function is useful as an __except condition. -int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { +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 message.GetString(); +} + +int UnitTestOptions::GTestProcessSEH(DWORD seh_code, const char* location) { // Google Test should handle a SEH exception if: // 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, // apparently). // // 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; - 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)) - should_handle = false; - else if (exception_code == EXCEPTION_BREAKPOINT) - should_handle = false; - else if (exception_code == kCxxExceptionCode) - should_handle = false; + internal::ReportFailureInUnknownLocation( + TestPartResult::kFatalFailure, + FormatSehExceptionMessage(seh_code, location) + + "\n" + "Stack trace:\n" + + ::testing::internal::GetCurrentOsStackTraceExceptTop(1)); - return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; + return EXCEPTION_EXECUTE_HANDLER; } #endif // GTEST_HAS_SEH @@ -2553,23 +2563,6 @@ bool Test::HasSameFixtureClass() { 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 { #if GTEST_HAS_EXCEPTIONS @@ -2611,16 +2604,8 @@ Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(), #if GTEST_HAS_SEH __try { return (object->*method)(); - } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT - GetExceptionCode())) { - // 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; + } __except (internal::UnitTestOptions::GTestProcessSEH( // NOLINT + GetExceptionCode(), location)) { return static_cast(0); } #else @@ -3019,7 +3004,8 @@ void TestSuite::Run() { internal::HandleExceptionsInMethodIfSupported( 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(); internal::Timer timer; @@ -3243,7 +3229,8 @@ static const char* GetAnsiColorCode(GTestColor color) { case GTestColor::kYellow: return "3"; default: - return nullptr; + assert(false); + return "9"; } } @@ -5155,8 +5142,8 @@ bool TestEventListeners::EventForwardingEnabled() const { return repeater_->forwarding_enabled(); } -void TestEventListeners::SuppressEventForwarding() { - repeater_->set_forwarding_enabled(false); +void TestEventListeners::SuppressEventForwarding(bool suppress) { + repeater_->set_forwarding_enabled(!suppress); } // class UnitTest @@ -5414,7 +5401,7 @@ void UnitTest::RecordProperty(const std::string& key, int UnitTest::Run() { #ifdef GTEST_HAS_DEATH_TEST 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 // 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. void UnitTestImpl::SuppressTestEventsIfInSubprocess() { if (internal_run_death_test_flag_ != nullptr) - listeners()->SuppressEventForwarding(); + listeners()->SuppressEventForwarding(true); } #endif // GTEST_HAS_DEATH_TEST @@ -5654,8 +5641,10 @@ void UnitTestImpl::ConfigureXmlOutput() { << output_format << "\" ignored."; } #else - GTEST_LOG_(ERROR) << "ERROR: alternative output formats require " - << "GTEST_HAS_FILE_SYSTEM to be enabled"; + if (!output_format.empty()) { + GTEST_LOG_(ERROR) << "ERROR: alternative output formats require " + << "GTEST_HAS_FILE_SYSTEM to be enabled"; + } #endif // GTEST_HAS_FILE_SYSTEM } diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index c2e3b3cc..8141caf4 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -31,7 +31,8 @@ #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. #ifdef GTEST_OS_ESP8266 diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 7754c130..1890b6ff 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -64,6 +64,7 @@ cc_test( "googletest-global-environment-unittest_.cc", "googletest-break-on-failure-unittest_.cc", "googletest-listener-test.cc", + "googletest-message-test.cc", "googletest-output-test_.cc", "googletest-list-tests-unittest_.cc", "googletest-shuffle-test_.cc", diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py index ee4dc9ae..180e18de 100755 --- a/googletest/test/googletest-catch-exceptions-test.py +++ b/googletest/test/googletest-catch-exceptions-test.py @@ -297,10 +297,10 @@ class CatchCxxExceptionsTest(gtest_test_utils.TestCase): def testUnhandledCxxExceptionsAbortTheProgram(self): # Filters out SEH exception tests on Windows. Unhandled SEH exceptions # 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. 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, ).output diff --git a/googletest/test/googletest-message-test.cc b/googletest/test/googletest-message-test.cc index 54e9d43c..bf1f094c 100644 --- a/googletest/test/googletest-message-test.cc +++ b/googletest/test/googletest-message-test.cc @@ -36,10 +36,26 @@ #include "gtest/gtest-message.h" #include "gtest/gtest.h" +#ifdef GTEST_HAS_ABSL +#include "absl/strings/str_format.h" +#endif // GTEST_HAS_ABSL + namespace { using ::testing::Message; +#ifdef GTEST_HAS_ABSL +struct AbslStringifiablePoint { + template + 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 default constructor. @@ -128,6 +144,13 @@ TEST(MessageTest, StreamsInt) { 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 // streamed to Message. TEST(MessageTest, StreamsBasicIoManip) { diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index 1f24fb79..6ddf822f 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -12,7 +12,7 @@ Expected equality of these values: 3 Stack trace: (omitted) -[==========] Running 89 tests from 42 test suites. +[==========] Running 90 tests from 43 test suites. [----------] Global test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -967,6 +967,15 @@ Stack trace: (omitted) googletest-output-test_.cc:#: Skipped [ 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 [ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 googletest-output-test_.cc:#: Failure @@ -1043,10 +1052,11 @@ Failed Expected fatal failure. Stack trace: (omitted) -[==========] 89 tests from 42 test suites ran. +[==========] 90 tests from 43 test suites ran. [ PASSED ] 31 tests. -[ SKIPPED ] 1 test, listed below: +[ SKIPPED ] 2 tests, listed below: [ SKIPPED ] TestSuiteThatFailsToSetUp.ShouldNotRun +[ SKIPPED ] TestSuiteThatSkipsInSetUp.ShouldNotRun [ FAILED ] 57 tests, listed below: [ FAILED ] NonfatalFailureTest.EscapesStringOperands [ FAILED ] NonfatalFailureTest.DiffForLongStrings diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index f1facf57..e3560c01 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -1007,6 +1007,12 @@ class TestSuiteThatFailsToSetUp : public testing::Test { }; 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 idea is to use Google Test to run all the tests we have defined (some diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 32a2a7b4..9f05a019 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -296,7 +296,7 @@ void* ThreadFunc(void* data) { TEST(GetThreadCountTest, ReturnsCorrectValue) { size_t starting_count; 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 // 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); ASSERT_EQ(0, pthread_attr_destroy(&attr)); ASSERT_EQ(0, status); - } - thread_count_after_create = GetThreadCount(); + thread_count_after_create = GetThreadCount(); + } void* dummy; ASSERT_EQ(0, pthread_join(thread_id, &dummy)); diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index f44f29a5..d5061bef 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -54,6 +54,15 @@ #include "gtest/gtest-printers.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 // NOLINT +#endif // GTEST_INTERNAL_HAS_STD_SPAN // Some user-defined types for testing the universal value printer. @@ -119,6 +128,19 @@ void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) { os << "StreamableInGlobal*"; } +#ifdef GTEST_HAS_ABSL +// A user-defined type with AbslStringify +struct Point { + template + 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 { // A user-defined unprintable type in a user namespace. @@ -317,6 +339,11 @@ TEST(PrintEnumTest, EnumWithPrintTo) { EXPECT_EQ("invalid", Print(static_cast(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. TEST(PrintClassTest, BiggestIntConvertible) { @@ -1157,6 +1184,17 @@ TEST(PrintStlContainerTest, Vector) { EXPECT_EQ("{ 1, 2 }", Print(v)); } +TEST(PrintStlContainerTest, StdSpan) { +#if GTEST_INTERNAL_HAS_STD_SPAN + int a[] = {3, 6, 5}; + std::span 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) { const int a[100] = {1, 2, 3}; const vector v(a, a + 100); @@ -1636,6 +1674,12 @@ TEST(PrintToStringTest, PrintReferenceToStreamableInGlobal) { 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) { // 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 diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py index 85a0c33c..38fc90ff 100755 --- a/googletest/test/gtest_help_test.py +++ b/googletest/test/gtest_help_test.py @@ -43,11 +43,22 @@ import sys 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_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' 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' 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. Returns: @@ -116,17 +127,14 @@ def RunWithFlag(flag): class GTestHelpTest(gtest_test_utils.TestCase): """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. 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) + exit_code, output = run_with_flag('--help') if HAS_ABSL_FLAGS: # The Abseil flags library prints the ProgramUsageMessage() with # --help and returns 1. @@ -136,7 +144,7 @@ class GTestHelpTest(gtest_test_utils.TestCase): 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) else: self.assertNotIn(STREAM_RESULT_TO_FLAG, output) @@ -146,53 +154,27 @@ class GTestHelpTest(gtest_test_utils.TestCase): else: self.assertNotIn(DEATH_TEST_STYLE_FLAG, output) - def TestUnknownFlagWithAbseil(self, flag): - """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): + def test_runs_tests_without_help_flag(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. - - 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.assertFalse(HELP_REGEX.search(output), output) - def testPrintsHelpWithFullFlag(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): + def test_runs_tests_with_gtest_internal_flag(self): """Verifies correct behavior when internal testing flag is specified. Verifies that the tests are run and no help message is printed when 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__': diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 77d968a7..67d776ed 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -67,11 +67,27 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { #include #include #include +#include #include #include "gtest/gtest-spi.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::value, int>> = 0> + operator T() const; // NOLINT(google-explicit-constructor) +}; +void operator<<(ConvertibleGlobalType&, int); +static_assert(sizeof(decltype(std::declval() + << 1)(*)()) > 0, + "error in operator<< overload resolution"); + namespace testing { namespace internal { @@ -173,7 +189,7 @@ class TestEventListenersAccessor { } static void SuppressEventForwarding(TestEventListeners* listeners) { - listeners->SuppressEventForwarding(); + listeners->SuppressEventForwarding(true); } }; @@ -4097,7 +4113,7 @@ TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { EXPECT_THROW(throw 1, 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_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), ""); EXPECT_ANY_THROW(throw 1); diff --git a/googletest_deps.bzl b/googletest_deps.bzl index 5e807d72..8f19cbed 100644 --- a/googletest_deps.bzl +++ b/googletest_deps.bzl @@ -7,16 +7,16 @@ def googletest_deps(): if not native.existing_rule("com_googlesource_code_re2"): http_archive( - name = "com_googlesource_code_re2", # 2023-06-01 - sha256 = "1726508efc93a50854c92e3f7ac66eb28f0e57652e413f11d7c1e28f97d997ba", - strip_prefix = "re2-03da4fc0857c285e3a26782f6bc8931c4c950df4", - urls = ["https://github.com/google/re2/archive/03da4fc0857c285e3a26782f6bc8931c4c950df4.zip"], + name = "com_googlesource_code_re2", # 2023-03-17T11:36:51Z + sha256 = "cb8b5312a65f2598954545a76e8bce913f35fbb3a21a5c88797a4448e9f9b9d9", + strip_prefix = "re2-578843a516fd1da7084ae46209a75f3613b6065e", + urls = ["https://github.com/google/re2/archive/578843a516fd1da7084ae46209a75f3613b6065e.zip"], ) if not native.existing_rule("com_google_absl"): http_archive( - name = "com_google_absl", # 2023-04-06T14:42:25Z - sha256 = "a50452f02402262f9a61a8eedda60f76dda6b9538d36b34b55bce9f74a4d5ef8", - strip_prefix = "abseil-cpp-e73b9139ee9b853a4bd7812531442c138da09084", - urls = ["https://github.com/abseil/abseil-cpp/archive/e73b9139ee9b853a4bd7812531442c138da09084.zip"], + name = "com_google_absl", # 2023-09-13T14:58:42Z + sha256 = "7766815ef6293dc7bca58fef59a96d7d3230874412dcd36dafb0e313ed1356f2", + strip_prefix = "abseil-cpp-9e1789ffea47fdeb3133aa42aa9592f3673fb6ed", + urls = ["https://github.com/abseil/abseil-cpp/archive/9e1789ffea47fdeb3133aa42aa9592f3673fb6ed.zip"], )