diff options
58 files changed, 846 insertions, 836 deletions
diff --git a/.travis.yml b/.travis.yml index 56f7d7c1..04b51dde 100644 --- a/.travis.yml +++ b/.travis.yml @@ -66,7 +66,7 @@ addons: packages: - ccache - gcc@4.9 - - llvm@3.9 + - llvm@4 update: true notifications: diff --git a/CMakeLists.txt b/CMakeLists.txt index 3fae2f96..f11bbb52 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ if (POLICY CMP0048) endif (POLICY CMP0048) project(googletest-distribution) -set(GOOGLETEST_VERSION 1.9.0) +set(GOOGLETEST_VERSION 1.10.0) if (CMAKE_VERSION VERSION_LESS "3.1") add_definitions(-std=c++11) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7e8b4799..30c8d890 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -90,32 +90,40 @@ and their own tests from a git checkout, which has further requirements: * [Python](https://www.python.org/) v2.3 or newer (for running some of the tests and re-generating certain source files from templates) * [CMake](https://cmake.org/) v2.6.4 or newer -* [GNU Build System](https://en.wikipedia.org/wiki/GNU_Build_System) including - automake (>= 1.9), autoconf (>= 2.59), and libtool / libtoolize. -## Developing Google Test +## Developing Google Test and Google Mock -This section discusses how to make your own changes to Google Test. +This section discusses how to make your own changes to the Google Test project. -### Testing Google Test Itself +### Testing Google Test and Google Mock Themselves To make sure your changes work as intended and don't break existing -functionality, you'll want to compile and run Google Test's own tests. For that -you can use CMake: +functionality, you'll want to compile and run Google Test and GoogleMock's own +tests. For that you can use CMake: mkdir mybuild cd mybuild - cmake -Dgtest_build_tests=ON ${GTEST_DIR} + cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR} + +To choose between building only Google Test or Google Mock, you may modify your +cmake command to be one of each + + cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests + cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests Make sure you have Python installed, as some of Google Test's tests are written in Python. If the cmake command complains about not being able to find Python (`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it explicitly where your Python executable can be found: - cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR} + cmake -DPYTHON_EXECUTABLE=path/to/python ... + +Next, you can build Google Test and / or Google Mock and all desired tests. On +\*nix, this is usually done by + + make -Next, you can build Google Test and all of its own tests. On \*nix, this is -usually done by 'make'. To run the tests, do +To run the tests, do make test @@ -132,27 +140,3 @@ You don't need to worry about regenerating the source files unless you need to modify them. You would then modify the corresponding `.pump` files and run the '[pump.py](googletest/scripts/pump.py)' generator script. See the [Pump Manual](googletest/docs/pump_manual.md). - -## Developing Google Mock - -This section discusses how to make your own changes to Google Mock. - -#### Testing Google Mock Itself - -To make sure your changes work as intended and don't break existing -functionality, you'll want to compile and run Google Test's own tests. For that -you'll need Autotools. First, make sure you have followed the instructions above -to configure Google Mock. Then, create a build output directory and enter it. -Next, - - ${GMOCK_DIR}/configure # try --help for more info - -Once you have successfully configured Google Mock, the build steps are standard -for GNU-style OSS packages. - - make # Standard makefile following GNU conventions - make check # Builds and runs all tests - all should pass. - -Note that when building your project against Google Mock, you are building -against Google Test as well. There is no need to configure Google Test -separately. @@ -5,24 +5,19 @@ [](https://travis-ci.org/google/googletest) [](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master) -### Future Plans +### Announcements: -#### 1.8.x Release: +#### Release 1.10.x -[the 1.8.x](https://github.com/google/googletest/releases/tag/release-1.8.1) is -the last release that works with pre-C++11 compilers. The 1.8.x will not accept -any requests for any new features and any bugfix requests will only be accepted -if proven "critical" +[Release 1.10.x](https://github.com/google/googletest/releases/tag/release-1.10.0) +is now available. -#### Post 1.8.x: +#### Coming Soon -On-going work to improve/cleanup/pay technical debt. When this work is completed -there will be a 1.9.x tagged release - -#### Post 1.9.x - -Post 1.9.x googletest will follow -[Abseil Live at Head philosophy](https://abseil.io/about/philosophy) +* Post 1.10.x googletest will follow + [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) +* We are also planning to take a dependency on + [Abseil](https://github.com/abseil/abseil-cpp). ## Welcome to **Google Test**, Google's C++ test framework! @@ -107,6 +102,9 @@ runs tests from your binary in parallel to provide significant speed-up. is a VS Code extension allowing to view Google Tests in a tree view, and run/debug your tests. +[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser +that generates stub code for Google Test. + ## Requirements Google Test is designed to have fairly minimal requirements to build and use diff --git a/ci/install-osx.sh b/ci/install-osx.sh index f2baebd2..cc475082 100755 --- a/ci/install-osx.sh +++ b/ci/install-osx.sh @@ -37,4 +37,4 @@ if [ "${TRAVIS_OS_NAME}" != "osx" ]; then fi brew update -brew install ccache gcc@4.9 llvm@3.9 +brew install ccache gcc@4.9 diff --git a/googlemock/cmake/gmock.pc.in b/googlemock/cmake/gmock.pc.in index 08e04547..2ef0fbca 100644 --- a/googlemock/cmake/gmock.pc.in +++ b/googlemock/cmake/gmock.pc.in @@ -1,6 +1,5 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: gmock Description: GoogleMock (without main() function) diff --git a/googlemock/cmake/gmock_main.pc.in b/googlemock/cmake/gmock_main.pc.in index b22fe614..04658fe2 100644 --- a/googlemock/cmake/gmock_main.pc.in +++ b/googlemock/cmake/gmock_main.pc.in @@ -1,6 +1,5 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: gmock_main Description: GoogleMock (with main() function) diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md index 239a4c6d..850963af 100644 --- a/googlemock/docs/cheat_sheet.md +++ b/googlemock/docs/cheat_sheet.md @@ -202,6 +202,15 @@ EXPECT_CALL(mock-object, method (matchers)?) .RetiresOnSaturation(); ? ``` +For each item above, `?` means it can be used at most once, while `*` means it +can be used any number of times. + +In order to pass, `EXPECT_CALL` must be used before the calls are actually made. + +The `(matchers)` is a comma-separated list of matchers that correspond to each +of the arguments of `method`, and sets the expectation only for calls of +`method` that matches all of the matchers. + If `(matchers)` is omitted, the expectation is the same as if the matchers were set to anything matchers (for example, `(_, _, _, _)` for a four-arg method). @@ -221,17 +230,19 @@ and the default action will be taken each time. <!-- GOOGLETEST_CM0020 DO NOT DELETE --> A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or -`EXPECT_CALL()`, or use it to validate a value directly: +`EXPECT_CALL()`, or use it to validate a value directly using two macros: <!-- mdformat off(github rendering does not support multiline tables) --> -| Matcher | Description | +| Macro | Description | | :----------------------------------- | :------------------------------------ | | `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | | `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | <!-- mdformat on --> -Built-in matchers (where `argument` is the function argument) are divided into -several categories: +Built-in matchers (where `argument` is the function argument, e.g. +`actual_value` in the example above, or when used in the context of +`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are +divided into several categories: #### Wildcard @@ -251,6 +262,8 @@ Matcher | Description | `Le(value)` | `argument <= value` | | `Lt(value)` | `argument < value` | | `Ne(value)` | `argument != value` | +| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. | +| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | | `IsNull()` | `argument` is a `NULL` pointer (raw or smart). | | `NotNull()` | `argument` is a non-null pointer (raw or smart). | | `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. | @@ -333,10 +346,8 @@ messages, you can use: | `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. | | `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | | `IsEmpty()` | `argument` is an empty container (`container.empty()`). | -| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. | | `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. | | `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | -| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | | `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | | `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | | `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. | @@ -731,12 +742,12 @@ you can do it earlier: using ::testing::Mock; ... // Verifies and removes the expectations on mock_obj; -// returns true if successful. +// returns true if and only if successful. Mock::VerifyAndClearExpectations(&mock_obj); ... // Verifies and removes the expectations on mock_obj; // also removes the default actions set by ON_CALL(); -// returns true if successful. +// returns true if and only if successful. Mock::VerifyAndClear(&mock_obj); ``` diff --git a/googlemock/docs/cook_book.md b/googlemock/docs/cook_book.md index 28f7ba1d..ea55ab35 100644 --- a/googlemock/docs/cook_book.md +++ b/googlemock/docs/cook_book.md @@ -1,4 +1,4 @@ -## gMock Cookbook +# gMock Cookbook <!-- GOOGLETEST_CM0012 DO NOT DELETE --> @@ -10,7 +10,7 @@ recommended to write `using ::testing::Foo;` once in your file before using the name `Foo` defined by gMock. We omit such `using` statements in this section for brevity, but you should do it in your own code. -### Creating Mock Classes +## Creating Mock Classes Mock classes are defined as normal classes, using the `MOCK_METHOD` macro to generate mocked methods. The macro gets 3 or 4 parameters: @@ -36,7 +36,7 @@ generated method: * **`Calltype(...)`** - Sets the call type for the method (e.g. to `STDMETHODCALLTYPE`), useful in Windows. -#### Dealing with unprotected commas +### Dealing with unprotected commas Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent `MOCK_METHOD` from parsing its arguments correctly: @@ -74,7 +74,7 @@ class MockFoo { }; ``` -#### Mocking Private or Protected Methods +### Mocking Private or Protected Methods You must always put a mock method definition (`MOCK_METHOD`) in a `public:` section of the mock class, regardless of the method being mocked being `public`, @@ -108,7 +108,7 @@ class MockFoo : public Foo { }; ``` -#### Mocking Overloaded Methods +### Mocking Overloaded Methods You can mock overloaded functions as usual. No special attention is required: @@ -152,7 +152,7 @@ class MockFoo : public Foo { }; ``` -#### Mocking Class Templates +### Mocking Class Templates You can mock class templates just like any class. @@ -175,7 +175,7 @@ class MockStack : public StackInterface<Elem> { }; ``` -#### Mocking Non-virtual Methods {#MockingNonVirtualMethods} +### Mocking Non-virtual Methods {#MockingNonVirtualMethods} gMock can mock non-virtual functions to be used in Hi-perf dependency injection.<!-- GOOGLETEST_CM0017 DO NOT DELETE --> @@ -243,7 +243,7 @@ tests. ... exercise reader ... ``` -#### Mocking Free Functions +### Mocking Free Functions It's possible to use gMock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract @@ -279,7 +279,7 @@ If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can combine this with the recipe for [mocking non-virtual methods](#MockingNonVirtualMethods). -#### Old-Style `MOCK_METHODn` Macros +### Old-Style `MOCK_METHODn` Macros Before the generic `MOCK_METHOD` macro was introduced, mocks where created using a family of macros collectively called `MOCK_METHODn`. These macros are still @@ -337,7 +337,7 @@ Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, </table> -#### The Nice, the Strict, and the Naggy {#NiceStrictNaggy} +### The Nice, the Strict, and the Naggy {#NiceStrictNaggy} If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an "uninteresting call", and the default action (which can be specified using @@ -444,7 +444,7 @@ nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort. -#### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces} +### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces} Sometimes a method has a long list of arguments that is mostly uninteresting. For example: @@ -516,7 +516,7 @@ ON_CALL(factory, DoMakeTurtle) .WillByDefault(MakeMockTurtle()); ``` -#### Alternative to Mocking Concrete Classes +### Alternative to Mocking Concrete Classes Often you may find yourself using classes that don't implement interfaces. In order to test your code that uses such a class (let's call it `Concrete`), you @@ -578,7 +578,7 @@ I'd like to assure you that the Java community has been practicing this for a long time and it's a proven effective technique applicable in a wide variety of situations. :-) -#### Delegating Calls to a Fake {#DelegatingToFake} +### Delegating Calls to a Fake {#DelegatingToFake} Some times you have a non-trivial fake implementation of an interface. For example: @@ -696,7 +696,7 @@ Instead, you can define a `FileOps` interface and an `IOOps` interface and split `System`'s functionalities into the two. Then you can mock `IOOps` without mocking `FileOps`. -#### Delegating Calls to a Real Object +### Delegating Calls to a Real Object When using testing doubles (mocks, fakes, stubs, and etc), sometimes their behaviors will differ from those of the real objects. This difference could be @@ -747,7 +747,7 @@ arguments, in the right order, called the right number of times, etc), and a real object will answer the calls (so the behavior will be the same as in production). This gives you the best of both worlds. -#### Delegating Calls to a Parent Class +### Delegating Calls to a Parent Class Ideally, you should code to interfaces, whose methods are all pure virtual. In reality, sometimes you do need to mock a virtual method that is not pure (i.e, @@ -815,9 +815,9 @@ or tell the mock object that you don't want to mock `Concrete()`: `MockFoo::Concrete()` will be called (and cause an infinite recursion) since `Foo::Concrete()` is virtual. That's just how C++ works.) -### Using Matchers +## Using Matchers -#### Matching Argument Values Exactly +### Matching Argument Values Exactly You can specify exactly which arguments a mock method is expecting: @@ -829,7 +829,7 @@ using ::testing::Return; EXPECT_CALL(foo, DoThat("Hello", bar)); ``` -#### Using Simple Matchers +### Using Simple Matchers You can use matchers to match arguments that have a certain property: @@ -850,7 +850,7 @@ A frequently used matcher is `_`, which matches anything: ``` <!-- GOOGLETEST_CM0022 DO NOT DELETE --> -#### Combining Matchers {#CombiningMatchers} +### Combining Matchers {#CombiningMatchers} You can build complex matchers from existing ones using `AllOf()`, `AllOfArray()`, `AnyOf()`, `AnyOfArray()` and `Not()`: @@ -871,7 +871,7 @@ using ::testing::Not; NULL)); ``` -#### Casting Matchers {#SafeMatcherCast} +### Casting Matchers {#SafeMatcherCast} gMock matchers are statically typed, meaning that the compiler can catch your mistake if you use a matcher of the wrong type (for example, if you use `Eq(5)` @@ -926,7 +926,7 @@ can `static_cast` type `T` to type `U`. always safe as it could throw away information, for example), so be careful not to misuse/abuse it. -#### Selecting Between Overloaded Functions {#SelectOverload} +### Selecting Between Overloaded Functions {#SelectOverload} If you expect an overloaded function to be called, the compiler may need some help on which overloaded version it is. @@ -983,7 +983,7 @@ TEST(PrinterTest, Print) { } ``` -#### Performing Different Actions Based on the Arguments +### Performing Different Actions Based on the Arguments When a mock method is called, the *last* matching expectation that's still active will be selected (think "newer overrides older"). So, you can make a @@ -1005,7 +1005,7 @@ using ::testing::Return; Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will be returned; otherwise `'b'` will be returned. -#### Matching Multiple Arguments as a Whole +### Matching Multiple Arguments as a Whole Sometimes it's not enough to match the arguments individually. For example, we may want to say that the first argument must be less than the second argument. @@ -1057,7 +1057,7 @@ Note that if you want to pass the arguments to a predicate of your own (e.g. take a `::std::tuple` as its argument; gMock will pass the `n` selected arguments as *one* single tuple to the predicate. -#### Using Matchers as Predicates +### Using Matchers as Predicates Have you noticed that a matcher is just a fancy predicate that also knows how to describe itself? Many existing algorithms take predicates as arguments (e.g. @@ -1095,7 +1095,7 @@ using testing::Ne; Matches(AllOf(Ge(0), Le(100), Ne(50))) ``` -#### Using Matchers in googletest Assertions +### Using Matchers in googletest Assertions Since matchers are basically predicates that also know how to describe themselves, there is a way to take advantage of them in googletest assertions. @@ -1143,7 +1143,7 @@ Expected: starts with "Hello" **Credit:** The idea of `(ASSERT|EXPECT)_THAT` was borrowed from Joe Walnes' Hamcrest project, which adds `assertThat()` to JUnit. -#### Using Predicates as Matchers +### Using Predicates as Matchers gMock provides a [built-in set](#MatcherList) of matchers. In case you find them lacking, you can use an arbitrary unary predicate function or functor as a @@ -1165,7 +1165,7 @@ works as long as the return value can be used as the condition in in statement <!-- GOOGLETEST_CM0023 DO NOT DELETE --> -#### Matching Arguments that Are Not Copyable +### Matching Arguments that Are Not Copyable When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of `bar`. When `Foo()` is called later, gMock compares the argument to `Foo()` with @@ -1195,7 +1195,7 @@ using ::testing::Lt; Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the result is undefined. -#### Validating a Member of an Object +### Validating a Member of an Object Often a mock function takes a reference to object as an argument. When matching the argument, you may not want to compare the entire object against a fixed @@ -1262,7 +1262,7 @@ Matcher<Foo> IsFoo(const Foo& foo) { } ``` -#### Validating the Value Pointed to by a Pointer Argument +### Validating the Value Pointed to by a Pointer Argument C++ functions often take pointers as arguments. You can use matchers like `IsNull()`, `NotNull()`, and other comparison matchers to match a pointer, but @@ -1270,8 +1270,8 @@ what if you want to make sure the value *pointed to* by the pointer, instead of the pointer itself, has a certain property? Well, you can use the `Pointee(m)` matcher. -`Pointee(m)` matches a pointer if `m` matches the value the pointer points to. -For example: +`Pointee(m)` matches a pointer if and only if `m` matches the value the pointer +points to. For example: ```cpp using ::testing::Ge; @@ -1304,7 +1304,7 @@ What if you have a pointer to pointer? You guessed it - you can use nested `Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points to a number less than 3 (what a mouthful...). -#### Testing a Certain Property of an Object +### Testing a Certain Property of an Object Sometimes you want to specify that an object argument has a certain property, but there is no existing matcher that does this. If you want good error @@ -1350,7 +1350,7 @@ Matcher<const Foo&> BarPlusBazEq(int expected_sum) { EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; ``` -#### Matching Containers +### Matching Containers Sometimes an STL container (e.g. list, vector, map, ...) is passed to a mock function and you may want to validate it. Since most STL containers support the @@ -1446,7 +1446,7 @@ using testing::Pair; with containers whose element order are undefined (e.g. `hash_map`) you should use `WhenSorted` around `ElementsAre`. -#### Sharing Matchers +### Sharing Matchers Under the hood, a gMock matcher object consists of a pointer to a ref-counted implementation object. Copying matchers is allowed and very efficient, as only @@ -1467,7 +1467,7 @@ using ::testing::Matcher; ... use in_range as a matcher in multiple EXPECT_CALLs ... ``` -#### Matchers must have no side-effects {#PureMatchers} +### Matchers must have no side-effects {#PureMatchers} WARNING: gMock does not guarantee when or how many times a matcher will be invoked. Therefore, all matchers must be *purely functional*: they cannot have @@ -1479,9 +1479,9 @@ it is one of the standard matchers, or a custom matcher). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and gMock. -### Setting Expectations +## Setting Expectations -#### Knowing When to Expect {#UseOnCall} +### Knowing When to Expect {#UseOnCall} <!-- GOOGLETEST_CM0018 DO NOT DELETE --> @@ -1534,7 +1534,7 @@ message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO NOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test that's a pain to maintain. -#### Ignoring Uninteresting Calls +### Ignoring Uninteresting Calls If you are not interested in how a mock method is called, just don't say anything about it. In this case, if the method is ever called, gMock will @@ -1547,7 +1547,7 @@ Please note that once you expressed interest in a particular mock method (via function is called but the arguments don't match any `EXPECT_CALL()` statement, it will be an error. -#### Disallowing Unexpected Calls +### Disallowing Unexpected Calls If a mock method shouldn't be called at all, explicitly say so: @@ -1573,7 +1573,7 @@ using ::testing::Gt; A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` statements will be an error. -#### Understanding Uninteresting vs Unexpected Calls {#uninteresting-vs-unexpected} +### Understanding Uninteresting vs Unexpected Calls {#uninteresting-vs-unexpected} *Uninteresting* calls and *unexpected* calls are different concepts in gMock. *Very* different. @@ -1648,7 +1648,7 @@ Note that the order of the two `EXPECT_CALL`s is important, as a newer For more on uninteresting calls, nice mocks, and strict mocks, read ["The Nice, the Strict, and the Naggy"](#NiceStrictNaggy). -#### Ignoring Uninteresting Arguments {#ParameterlessExpectations} +### Ignoring Uninteresting Arguments {#ParameterlessExpectations} If your test doesn't care about the parameters (it only cares about the number or order of calls), you can often simply omit the parameter list: @@ -1674,7 +1674,7 @@ SaveArg actions to [save the values for later verification](#SaveArgVerify). If you do that, you can easily differentiate calling the method the wrong number of times from calling it with the wrong arguments. -#### Expecting Ordered Calls {#OrderedCalls} +### Expecting Ordered Calls {#OrderedCalls} Although an `EXPECT_CALL()` statement defined earlier takes precedence when gMock tries to match a function call with an expectation, by default calls don't @@ -1705,7 +1705,7 @@ In this example, we expect a call to `foo.DoThis(5)`, followed by two calls to a call to `foo.DoThis(6)`. If a call occurred out-of-order, gMock will report an error. -#### Expecting Partially Ordered Calls {#PartialOrder} +### Expecting Partially Ordered Calls {#PartialOrder} Sometimes requiring everything to occur in a predetermined order can lead to brittle tests. For example, we may care about `A` occurring before both `B` and @@ -1763,7 +1763,7 @@ specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`): This means that A must occur before B and C, and C must occur before D. There's no restriction about the order other than these. -#### Controlling When an Expectation Retires +### Controlling When an Expectation Retires When a mock method is called, gMock only considers expectations that are still active. An expectation is active when created, and becomes inactive (aka @@ -1816,9 +1816,9 @@ Here #2 can be used only once, so if you have two warnings with the message `"File too large."`, the first will match #2 and the second will match #1 - there will be no error. -### Using Actions +## Using Actions -#### Returning References from Mock Methods +### Returning References from Mock Methods If a mock function's return type is a reference, you need to use `ReturnRef()` instead of `Return()` to return a result: @@ -1838,7 +1838,7 @@ class MockFoo : public Foo { ... ``` -#### Returning Live Values from Mock Methods +### Returning Live Values from Mock Methods The `Return(x)` action saves a copy of `x` when the action is created, and always returns the same value whenever it's executed. Sometimes you may want to @@ -1900,7 +1900,7 @@ using testing::ReturnPointee; EXPECT_EQ(42, foo.GetValue()); // This will succeed now. ``` -#### Combining Actions +### Combining Actions Want to do more than one thing when a function is called? That's fine. `DoAll()` allow you to do sequence of actions every time. Only the return value of the @@ -1922,7 +1922,7 @@ class MockFoo : public Foo { action_n)); ``` -#### Verifying Complex Arguments {#SaveArgVerify} +### Verifying Complex Arguments {#SaveArgVerify} If you want to verify that a method is called with a particular argument but the match criteria is complex, it can be difficult to distinguish between @@ -1946,7 +1946,7 @@ You can instead save the arguments and test them individually: EXPECT_THAT(actual_proto, EqualsProto( ... )); ``` -#### Mocking Side Effects {#MockingSideEffects} +### Mocking Side Effects {#MockingSideEffects} Sometimes a method exhibits its effect not via returning a value but via side effects. For example, it may change some global state or modify an output @@ -2045,7 +2045,7 @@ class MockRolodex : public Rolodex { .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); ``` -#### Changing a Mock Object's Behavior Based on the State +### Changing a Mock Object's Behavior Based on the State If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the @@ -2091,7 +2091,7 @@ ACTION_P(ReturnPointee, p) { return *p; } Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call. -#### Setting the Default Value for a Return Type {#DefaultValue} +### Setting the Default Value for a Return Type {#DefaultValue} If a mock method's return type is a built-in C++ type or pointer, by default it will return 0 when invoked. Also, in C++ 11 and above, a mock method whose @@ -2134,7 +2134,7 @@ to understand. We recommend you to use this feature judiciously. For example, you may want to make sure the `Set()` and `Clear()` calls are right next to the code that uses your mock. -#### Setting the Default Actions for a Mock Method +### Setting the Default Actions for a Mock Method You've learned how to change the default value of a given type. However, this may be too coarse for your purpose: perhaps you have two mock methods with the @@ -2172,7 +2172,7 @@ Note that both `ON_CALL` and `EXPECT_CALL` have the same "later statements take precedence" rule, but they don't interact. That is, `EXPECT_CALL`s have their own precedence order distinct from the `ON_CALL` precedence order. -#### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions} +### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions} If the built-in actions don't suit you, you can use an existing callable (function, `std::function`, method, functor, lambda as an action. @@ -2236,7 +2236,7 @@ as long as it's safe to do so - nice, huh? ... Invoke(implicit_cast<Closure*>(done)) ...; // The cast is necessary. ``` -#### Using Functions with Extra Info as Actions +### Using Functions with Extra Info as Actions The function or functor you call using `Invoke()` must have the same number of arguments as the mock function you use it for. Sometimes you may have a function @@ -2266,7 +2266,7 @@ TEST_F(FooTest, Test) { } ``` -#### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments +### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments `Invoke()` is very useful for doing actions that are more complex. It passes the mock function's arguments to the function, etc being invoked such that the @@ -2322,7 +2322,7 @@ bool Job2(int n, char c) { ... } // The cast is necessary. ``` -#### Invoking an Argument of the Mock Function +### Invoking an Argument of the Mock Function Sometimes a mock function will receive a function pointer, a functor (in other words, a "callable") as an argument, e.g. @@ -2421,7 +2421,7 @@ temporary value: // are kept inside the InvokeArgument action. ``` -#### Ignoring an Action's Result +### Ignoring an Action's Result Sometimes you have an action that returns *something*, but you need an action that returns `void` (perhaps you want to use it in a mock function that returns @@ -2459,7 +2459,7 @@ class MockFoo : public Foo { Note that you **cannot** use `IgnoreResult()` on an action that already returns `void`. Doing so will lead to ugly compiler errors. -#### Selecting an Action's Arguments {#SelectingArgs} +### Selecting an Action's Arguments {#SelectingArgs} Say you have a mock function `Foo()` that takes seven arguments, and you have a custom action that you want to invoke when `Foo()` is called. Trouble is, the @@ -2543,7 +2543,7 @@ Here are more tips: if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work. -#### Ignoring Arguments in Action Functions +### Ignoring Arguments in Action Functions The [selecting-an-action's-arguments](#SelectingArgs) recipe showed us one way to make a mock function and an action with incompatible argument lists fit @@ -2600,7 +2600,7 @@ double DistanceToOrigin(Unused, double x, double y) { .WillOnce(Invoke(DistanceToOrigin)); ``` -#### Sharing Actions +### Sharing Actions Just like matchers, a gMock action object consists of a pointer to a ref-counted implementation object. Therefore copying actions is also allowed and very @@ -2656,7 +2656,7 @@ using ::testing::Action; foo.DoThat(); // Returns 3 - the counter is shared. ``` -#### Testing Asynchronous Behavior +### Testing Asynchronous Behavior One oft-encountered problem with gMock is that it can be hard to test asynchronous behavior. Suppose you had a `EventQueue` class that you wanted to @@ -2705,9 +2705,9 @@ our test will run forever. It will eventually time-out and fail, but it will take longer and be slightly harder to debug. To alleviate this problem, you can use `WaitForNotificationWithTimeout(ms)` instead of `WaitForNotification()`. -### Misc Recipes on Using gMock +## Misc Recipes on Using gMock -#### Mocking Methods That Use Move-Only Types +### Mocking Methods That Use Move-Only Types C++11 introduced *move-only types*. A move-only-typed value can be moved from one object to another, but cannot be copied. `std::unique_ptr<T>` is probably @@ -2847,7 +2847,7 @@ implemented yet. If this is blocking you, please file a bug. A few actions (e.g. `DoAll`) copy their arguments internally, so they can never work with non-copyable objects; you'll have to use functors instead. -##### Legacy workarounds for move-only types {#LegacyMoveOnly} +#### Legacy workarounds for move-only types {#LegacyMoveOnly} Support for move-only function arguments was only introduced to gMock in April 2017. In older code, you may encounter the following workaround for the lack of @@ -2879,7 +2879,7 @@ method: mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0); ``` -#### Making the Compilation Faster +### Making the Compilation Faster Believe it or not, the *vast majority* of the time spent on compiling a mock class is in generating its constructor and destructor, as they perform @@ -2943,7 +2943,7 @@ MockFoo::MockFoo() {} MockFoo::~MockFoo() {} ``` -#### Forcing a Verification +### Forcing a Verification When it's being destroyed, your friendly mock object will automatically verify that all expectations on it have been satisfied, and will generate googletest @@ -2984,7 +2984,7 @@ indicate whether the verification was successful (`true` for yes), so you can wrap that function call inside a `ASSERT_TRUE()` if there is no point going further when the verification has failed. -#### Using Check Points {#UsingCheckPoints} +### Using Check Points {#UsingCheckPoints} Sometimes you may want to "reset" a mock object at various check points in your test: at each check point, you verify that all existing expectations on the mock @@ -3048,7 +3048,7 @@ point "1", the second `Bar("a")` must happen after check point "2", and nothing should happen between the two check points. The explicit check points make it easy to tell which `Bar("a")` is called by which call to `Foo()`. -#### Mocking Destructors +### Mocking Destructors Sometimes you want to make sure a mock object is destructed at the right time, e.g. after `bar->A()` is called but before `bar->B()` is called. We already know @@ -3096,7 +3096,7 @@ testing when its `Die()` method is called: And that's that. -#### Using gMock and Threads {#UsingThreads} +### Using gMock and Threads {#UsingThreads} In a **unit** test, it's best if you could isolate and test a piece of code in a single-threaded context. That avoids race conditions and dead locks, and makes @@ -3154,7 +3154,7 @@ Also, remember that `DefaultValue<T>` is a global resource that potentially affects *all* living mock objects in your program. Naturally, you won't want to mess with it from multiple threads or when there still are mocks in action. -#### Controlling How Much Information gMock Prints +### Controlling How Much Information gMock Prints When gMock sees something that has the potential of being an error (e.g. a mock function with no expectation is called, a.k.a. an uninteresting call, which is @@ -3193,7 +3193,7 @@ warning messages, remember that you can control their amount with the Now, judiciously use the right flag to enable gMock serve you better! -#### Gaining Super Vision into Mock Calls +### Gaining Super Vision into Mock Calls You have a test using gMock. It fails: gMock tells you some expectations aren't satisfied. However, you aren't sure why: Is there a typo somewhere in the @@ -3273,7 +3273,7 @@ command line. <!-- GOOGLETEST_CM0025 DO NOT DELETE --> -#### Running Tests in Emacs +### Running Tests in Emacs If you build and run your tests in Emacs using the `M-x google-compile` command (as many googletest users do), the source file locations of gMock and googletest @@ -3293,9 +3293,9 @@ Then you can type `M-m` to start a build (if you want to run the test as well, just make sure `foo_test.run` or `runtests` is in the build command you supply after typing `M-m`), or `M-up`/`M-down` to move back and forth between errors. -### Extending gMock +## Extending gMock -#### Writing New Matchers Quickly {#NewMatchers} +### Writing New Matchers Quickly {#NewMatchers} WARNING: gMock does not guarantee when or how many times a matcher will be invoked. Therefore, all matchers must be functionally pure. See @@ -3409,7 +3409,7 @@ any type where the value of `(arg % 7) == 0` can be implicitly converted to a `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on. -#### Writing New Parameterized Matchers Quickly +### Writing New Parameterized Matchers Quickly Sometimes you'll want to define a matcher that has parameters. For that you can use the macro: @@ -3546,7 +3546,7 @@ matcher parameters, which in general leads to better compiler error messages that pay off in the long run. They also allow overloading matchers based on parameter types (as opposed to just based on the number of parameters). -#### Writing New Monomorphic Matchers +### Writing New Monomorphic Matchers A matcher of argument type `T` implements `::testing::MatcherInterface<T>` and does two things: it tests whether a value of type `T` matches the matcher, and @@ -3573,7 +3573,7 @@ class MatcherInterface { public: virtual ~MatcherInterface(); - // Returns true if the matcher matches x; also explains the match + // Returns true if and only if the matcher matches x; also explains the match // result to 'listener'. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; @@ -3652,7 +3652,7 @@ Expected: is divisible by 7 Actual: 23 (the remainder is 2) ``` -#### Writing New Polymorphic Matchers +### Writing New Polymorphic Matchers You've learned how to write your own matchers in the previous recipe. Just one problem: a matcher created using `MakeMatcher()` only works for one particular @@ -3688,10 +3688,10 @@ class NotNullMatcher { } // Describes the property of a value matching this matcher. - void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; } + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } // Describes the property of a value NOT matching this matcher. - void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } }; // To construct a polymorphic matcher, pass an instance of the class @@ -3712,7 +3712,7 @@ virtual. Like in a monomorphic matcher, you may explain the match result by streaming additional information to the `listener` argument in `MatchAndExplain()`. -#### Writing New Cardinalities +### Writing New Cardinalities A cardinality is used in `Times()` to tell gMock how many times you expect a call to occur. It doesn't have to be exact. For example, you can say @@ -3727,14 +3727,15 @@ class CardinalityInterface { public: virtual ~CardinalityInterface(); - // Returns true if call_count calls will satisfy this cardinality. + // Returns true if and only if call_count calls will satisfy this cardinality. virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - // Returns true if call_count calls will saturate this cardinality. + // Returns true if and only if call_count calls will saturate this + // cardinality. virtual bool IsSaturatedByCallCount(int call_count) const = 0; // Describes self to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; + virtual void DescribeTo(std::ostream* os) const = 0; }; ``` @@ -3756,7 +3757,7 @@ class EvenNumberCardinality : public CardinalityInterface { return false; } - void DescribeTo(::std::ostream* os) const { + void DescribeTo(std::ostream* os) const { *os << "called even number of times"; } }; @@ -3770,7 +3771,7 @@ Cardinality EvenNumber() { .Times(EvenNumber()); ``` -#### Writing New Actions Quickly {#QuickNewActions} +### Writing New Actions Quickly {#QuickNewActions} If the built-in actions don't work for you, you can easily define your own one. Just define a functor class with a (possibly templated) call operator, matching @@ -3799,7 +3800,7 @@ struct MultiplyBy { // EXPECT_CALL(...).WillOnce(MultiplyBy{7}); ``` -##### Legacy macro-based Actions +#### Legacy macro-based Actions Before C++11, the functor-based actions were not supported; the old way of writing actions was through a set of `ACTION*` macros. We suggest to avoid them @@ -3878,7 +3879,7 @@ Pre-defined Symbol | Is Bound To `return_type` | the type `int` `function_type` | the type `int(bool, int*)` -##### Legacy macro-based parameterized Actions +#### Legacy macro-based parameterized Actions Sometimes you'll want to parameterize an action you define. For that we have another macro @@ -3937,7 +3938,7 @@ ACTION_P(Plus, a) { ... } ACTION_P2(Plus, a, b) { ... } ``` -#### Restricting the Type of an Argument or Parameter in an ACTION +### Restricting the Type of an Argument or Parameter in an ACTION For maximum brevity and reusability, the `ACTION*` macros don't ask you to provide the types of the mock function arguments and the action parameters. @@ -3965,7 +3966,7 @@ ACTION_P(Bar, param) { where `StaticAssertTypeEq` is a compile-time assertion in googletest that verifies two types are the same. -#### Writing New Action Templates Quickly +### Writing New Action Templates Quickly Sometimes you want to give an action explicit template parameters that cannot be inferred from its value parameters. `ACTION_TEMPLATE()` supports that and can be @@ -4035,7 +4036,7 @@ Are we using a single-template-parameter action where `bool` refers to the type of `x`, or a two-template-parameter action where the compiler is asked to infer the type of `x`? -#### Using the ACTION Object's Type +### Using the ACTION Object's Type If you are writing a function that returns an `ACTION` object, you'll need to know its type. The type depends on the macro used to define the action and the @@ -4062,7 +4063,7 @@ Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, and etc) for actions with different numbers of value parameters, or the action definitions cannot be overloaded on the number of them. -#### Writing New Monomorphic Actions {#NewMonoActions} +### Writing New Monomorphic Actions {#NewMonoActions} While the `ACTION*` macros are very convenient, sometimes they are inappropriate. For example, despite the tricks shown in the previous recipes, @@ -4119,7 +4120,7 @@ Action<IncrementMethod> IncrementArgument() { foo.Baz(&n); // Should return 5 and change n to 6. ``` -#### Writing New Polymorphic Actions {#NewPolyActions} +### Writing New Polymorphic Actions {#NewPolyActions} The previous recipe showed you how to define your own action. This is all good, except that you need to know the type of the function in which the action will @@ -4195,7 +4196,7 @@ class MockFoo : public Foo { foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". ``` -#### Teaching gMock How to Print Your Values +### Teaching gMock How to Print Your Values When an uninteresting or unexpected call occurs, gMock prints the argument values and the stack trace to help you debug. Assertion macros like @@ -4210,12 +4211,12 @@ prints the raw bytes in the value and hopes that you the user can figure it out. explains how to extend the printer to do a better job at printing your particular type than to dump the bytes. -### Useful Mocks Created Using gMock +## Useful Mocks Created Using gMock <!--#include file="includes/g3_testing_LOGs.md"--> <!--#include file="includes/g3_mock_callbacks.md"--> -#### Mock std::function {#MockFunction} +### Mock std::function {#MockFunction} `std::function` is a general function type introduced in C++11. It is a preferred way of passing callbacks to new interfaces. Functions are copiable, diff --git a/googlemock/docs/for_dummies.md b/googlemock/docs/for_dummies.md index e11c18d9..93cf06f3 100644 --- a/googlemock/docs/for_dummies.md +++ b/googlemock/docs/for_dummies.md @@ -213,7 +213,7 @@ specific domain much better than `Foo` does. Once you have a mock class, using it is easy. The typical work flow is: 1. Import the gMock names from the `testing` namespace such that you can use - them unqualified (You only have to do it once per file. Remember that + them unqualified (You only have to do it once per file). Remember that namespaces are a good idea. 2. Create some mock objects. 3. Specify your expectations on them (How many times will a method be called? diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index 9605c43a..f12d39be 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -99,7 +99,8 @@ struct BuiltInDefaultValueGetter<T, false> { template <typename T> class BuiltInDefaultValue { public: - // This function returns true if type T has a built-in default value. + // This function returns true if and only if type T has a built-in default + // value. static bool Exists() { return ::std::is_default_constructible<T>::value; } @@ -208,7 +209,7 @@ class DefaultValue { producer_ = nullptr; } - // Returns true if the user has set the default value for type T. + // Returns true if and only if the user has set the default value for type T. static bool IsSet() { return producer_ != nullptr; } // Returns true if T has a default return value set by the user or there @@ -269,7 +270,7 @@ class DefaultValue<T&> { // Unsets the default value for type T&. static void Clear() { address_ = nullptr; } - // Returns true if the user has set the default value for type T&. + // Returns true if and only if the user has set the default value for type T&. static bool IsSet() { return address_ != nullptr; } // Returns true if T has a default return value set by the user or there @@ -375,7 +376,7 @@ class Action { template <typename Func> explicit Action(const Action<Func>& action) : fun_(action.fun_) {} - // Returns true if this is the DoDefault() action. + // Returns true if and only if this is the DoDefault() action. bool IsDoDefault() const { return fun_ == nullptr; } // Performs the action. Note that this method is const even though @@ -395,7 +396,7 @@ class Action { template <typename G> friend class Action; - // fun_ is an empty function if this is the DoDefault() action. + // fun_ is an empty function if and only if this is the DoDefault() action. ::std::function<F> fun_; }; @@ -619,7 +620,7 @@ class ReturnVoidAction { // Allows Return() to be used in any void-returning function. template <typename Result, typename ArgumentTuple> static void Perform(const ArgumentTuple&) { - CompileAssertTypesEqual<void, Result>(); + static_assert(std::is_void<Result>::value, "Result should be void."); } }; @@ -842,7 +843,7 @@ class IgnoreResultAction { typedef typename internal::Function<F>::Result Result; // Asserts at compile time that F returns void. - CompileAssertTypesEqual<void, Result>(); + static_assert(std::is_void<Result>::value, "Result type should be void."); return Action<F>(new Impl<F>(action_)); } diff --git a/googlemock/include/gmock/gmock-cardinalities.h b/googlemock/include/gmock/gmock-cardinalities.h index 4b269a3e..46e01e10 100644 --- a/googlemock/include/gmock/gmock-cardinalities.h +++ b/googlemock/include/gmock/gmock-cardinalities.h @@ -70,10 +70,12 @@ class CardinalityInterface { virtual int ConservativeLowerBound() const { return 0; } virtual int ConservativeUpperBound() const { return INT_MAX; } - // Returns true if call_count calls will satisfy this cardinality. + // Returns true if and only if call_count calls will satisfy this + // cardinality. virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - // Returns true if call_count calls will saturate this cardinality. + // Returns true if and only if call_count calls will saturate this + // cardinality. virtual bool IsSaturatedByCallCount(int call_count) const = 0; // Describes self to an ostream. @@ -98,17 +100,19 @@ class GTEST_API_ Cardinality { int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } - // Returns true if call_count calls will satisfy this cardinality. + // Returns true if and only if call_count calls will satisfy this + // cardinality. bool IsSatisfiedByCallCount(int call_count) const { return impl_->IsSatisfiedByCallCount(call_count); } - // Returns true if call_count calls will saturate this cardinality. + // Returns true if and only if call_count calls will saturate this + // cardinality. bool IsSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count); } - // Returns true if call_count calls will over-saturate this + // Returns true if and only if call_count calls will over-saturate this // cardinality, i.e. exceed the maximum number of allowed calls. bool IsOverSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count) && diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index b1c0dc04..4428ec14 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -133,14 +133,14 @@ class MatcherCastImpl { // a user-defined conversion from M to T if one exists (assuming M is // a value). return CastImpl(polymorphic_matcher_or_value, - bool_constant<std::is_convertible<M, Matcher<T>>::value>(), - bool_constant<std::is_convertible<M, T>::value>()); + std::is_convertible<M, Matcher<T>>{}, + std::is_convertible<M, T>{}); } private: template <bool Ignore> static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value, - bool_constant<true> /* convertible_to_matcher */, + std::true_type /* convertible_to_matcher */, bool_constant<Ignore>) { // M is implicitly convertible to Matcher<T>, which means that either // M is a polymorphic matcher or Matcher<T> has an implicit constructor @@ -157,8 +157,8 @@ class MatcherCastImpl { // matcher. It's a value of a type implicitly convertible to T. Use direct // initialization to create a matcher. static Matcher<T> CastImpl(const M& value, - bool_constant<false> /* convertible_to_matcher */, - bool_constant<true> /* convertible_to_T */) { + std::false_type /* convertible_to_matcher */, + std::true_type /* convertible_to_T */) { return Matcher<T>(ImplicitCast_<T>(value)); } @@ -173,8 +173,8 @@ class MatcherCastImpl { // // We don't define this method inline as we need the declaration of Eq(). static Matcher<T> CastImpl(const M& value, - bool_constant<false> /* convertible_to_matcher */, - bool_constant<false> /* convertible_to_T */); + std::false_type /* convertible_to_matcher */, + std::false_type /* convertible_to_T */); }; // This more specialized version is used when MatcherCast()'s argument @@ -358,8 +358,8 @@ template <size_t N> class TuplePrefix { public: // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true - // if the first N fields of matcher_tuple matches the first N - // fields of value_tuple, respectively. + // if and only if the first N fields of matcher_tuple matches + // the first N fields of value_tuple, respectively. template <typename MatcherTuple, typename ValueTuple> static bool Matches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { @@ -417,8 +417,8 @@ class TuplePrefix<0> { ::std::ostream* /* os */) {} }; -// TupleMatches(matcher_tuple, value_tuple) returns true if all -// matchers in matcher_tuple match the corresponding fields in +// TupleMatches(matcher_tuple, value_tuple) returns true if and only if +// all matchers in matcher_tuple match the corresponding fields in // value_tuple. It is a compiler error if matcher_tuple and // value_tuple have different number of fields or incompatible field // types. @@ -1607,9 +1607,8 @@ class PointeeMatcher { template <typename Pointer> class Impl : public MatcherInterface<Pointer> { public: - typedef - typename PointeeOf<typename std::remove_const<GTEST_REMOVE_REFERENCE_( - Pointer)>::type>::type Pointee; + typedef typename PointeeOf<GTEST_REMOVE_REFERENCE_AND_CONST_(Pointer)>::type + Pointee; explicit Impl(const InnerMatcher& matcher) : matcher_(MatcherCast<const Pointee&>(matcher)) {} @@ -1859,7 +1858,9 @@ struct CallableTraits { static void CheckIsValid(Functor /* functor */) {} template <typename T> - static auto Invoke(Functor f, T arg) -> decltype(f(arg)) { return f(arg); } + static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) { + return f(arg); + } }; // Specialization for function pointers. @@ -1890,7 +1891,7 @@ class ResultOfMatcher { template <typename T> operator Matcher<T>() const { - return Matcher<T>(new Impl<T>(callable_, matcher_)); + return Matcher<T>(new Impl<const T&>(callable_, matcher_)); } private: @@ -2069,15 +2070,15 @@ class ContainerEqMatcher { typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; + static_assert(!std::is_const<Container>::value, + "Container type must not be const"); + static_assert(!std::is_reference<Container>::value, + "Container type must not be a reference"); + // We make a copy of expected in case the elements in it are modified // after this matcher is created. explicit ContainerEqMatcher(const Container& expected) - : expected_(View::Copy(expected)) { - // Makes sure the user doesn't instantiate this class template - // with a const or reference type. - (void)testing::StaticAssertTypeEq<Container, - GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>(); - } + : expected_(View::Copy(expected)) {} void DescribeTo(::std::ostream* os) const { *os << "equals "; @@ -2244,15 +2245,15 @@ class PointwiseMatcher { typedef typename RhsView::type RhsStlContainer; typedef typename RhsStlContainer::value_type RhsValue; + static_assert(!std::is_const<RhsContainer>::value, + "RhsContainer type must not be const"); + static_assert(!std::is_reference<RhsContainer>::value, + "RhsContainer type must not be a reference"); + // Like ContainerEq, we make a copy of rhs in case the elements in // it are modified after this matcher is created. PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs) - : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) { - // Makes sure the user doesn't instantiate this class template - // with a const or reference type. - (void)testing::StaticAssertTypeEq<RhsContainer, - GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>(); - } + : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {} template <typename LhsContainer> operator Matcher<LhsContainer>() const { @@ -2531,7 +2532,8 @@ class KeyMatcherImpl : public MatcherInterface<PairType> { testing::SafeMatcherCast<const KeyType&>(inner_matcher)) { } - // Returns true if 'key_value.first' (the key) matches the inner matcher. + // Returns true if and only if 'key_value.first' (the key) matches the inner + // matcher. bool MatchAndExplain(PairType key_value, MatchResultListener* listener) const override { StringMatchResultListener inner_listener; @@ -2613,8 +2615,8 @@ class PairMatcherImpl : public MatcherInterface<PairType> { second_matcher_.DescribeNegationTo(os); } - // Returns true if 'a_pair.first' matches first_matcher and 'a_pair.second' - // matches second_matcher. + // Returns true if and only if 'a_pair.first' matches first_matcher and + // 'a_pair.second' matches second_matcher. bool MatchAndExplain(PairType a_pair, MatchResultListener* listener) const override { if (!listener->IsInterested()) { @@ -3149,8 +3151,8 @@ class ElementsAreArrayMatcher { // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm, -// second) is a polymorphic matcher that matches a value x if tm -// matches tuple (x, second). Useful for implementing +// second) is a polymorphic matcher that matches a value x if and only if +// tm matches tuple (x, second). Useful for implementing // UnorderedPointwise() in terms of UnorderedElementsAreArray(). // // BoundSecondMatcher is copyable and assignable, as we need to put @@ -3214,8 +3216,8 @@ class BoundSecondMatcher { // Given a 2-tuple matcher tm and a value second, // MatcherBindSecond(tm, second) returns a matcher that matches a -// value x if tm matches tuple (x, second). Useful for implementing -// UnorderedPointwise() in terms of UnorderedElementsAreArray(). +// value x if and only if tm matches tuple (x, second). Useful for +// implementing UnorderedPointwise() in terms of UnorderedElementsAreArray(). template <typename Tuple2Matcher, typename Second> BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond( const Tuple2Matcher& tm, const Second& second) { @@ -3600,8 +3602,8 @@ inline Matcher<T> An() { return A<T>(); } template <typename T, typename M> Matcher<T> internal::MatcherCastImpl<T, M>::CastImpl( - const M& value, internal::bool_constant<false> /* convertible_to_matcher */, - internal::bool_constant<false> /* convertible_to_T */) { + const M& value, std::false_type /* convertible_to_matcher */, + std::false_type /* convertible_to_T */) { return Eq(value); } @@ -3706,7 +3708,7 @@ WhenDynamicCastTo(const Matcher<To>& inner_matcher) { // Creates a matcher that matches an object whose given field matches // 'matcher'. For example, // Field(&Foo::number, Ge(5)) -// matches a Foo object x if x.number >= 5. +// matches a Foo object x if and only if x.number >= 5. template <typename Class, typename FieldType, typename FieldMatcher> inline PolymorphicMatcher< internal::FieldMatcher<Class, FieldType> > Field( @@ -3733,7 +3735,7 @@ inline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType> > Field( // Creates a matcher that matches an object whose given property // matches 'matcher'. For example, // Property(&Foo::str, StartsWith("hi")) -// matches a Foo object x if x.str() starts with "hi". +// matches a Foo object x if and only if x.str() starts with "hi". template <typename Class, typename PropertyType, typename PropertyMatcher> inline PolymorphicMatcher<internal::PropertyMatcher< Class, PropertyType, PropertyType (Class::*)() const> > @@ -3788,11 +3790,10 @@ Property(const std::string& property_name, property_name, property, MatcherCast<const PropertyType&>(matcher))); } -// Creates a matcher that matches an object if the result of applying -// a callable to x matches 'matcher'. -// For example, +// Creates a matcher that matches an object if and only if the result of +// applying a callable to x matches 'matcher'. For example, // ResultOf(f, StartsWith("hi")) -// matches a Foo object x if f(x) starts with "hi". +// matches a Foo object x if and only if f(x) starts with "hi". // `callable` parameter can be a function, function pointer, or a functor. It is // required to keep no state affecting the results of the calls on it and make // no assumptions about how many calls will be made. Any state it keeps must be @@ -4342,7 +4343,7 @@ inline internal::MatcherAsPredicate<M> Matches(M matcher) { return internal::MatcherAsPredicate<M>(matcher); } -// Returns true if the value matches the matcher. +// Returns true if and only if the value matches the matcher. template <typename T, typename M> inline bool Value(const T& value, M matcher) { return testing::Matches(matcher)(value); @@ -4548,8 +4549,8 @@ PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith( // These macros allow using matchers to check values in Google Test // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) -// succeed if the value matches the matcher. If the assertion fails, -// the value and the description of the matcher will be printed. +// succeed if and only if the value matches the matcher. If the assertion +// fails, the value and the description of the matcher will be printed. #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\ ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\ diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index 0d1adda5..80c13b55 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -332,7 +332,7 @@ class OnCallSpec : public UntypedOnCallSpecBase { return *this; } - // Returns true if the given arguments match the matchers. + // Returns true if and only if the given arguments match the matchers. bool Matches(const ArgumentTuple& args) const { return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } @@ -390,7 +390,7 @@ class GTEST_API_ Mock { GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies all expectations on the given mock object and clears its - // default actions and expectations. Returns true if the + // default actions and expectations. Returns true if and only if the // verification was successful. static bool VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); @@ -516,7 +516,8 @@ class GTEST_API_ Expectation { // The compiler-generated copy ctor and operator= work exactly as // intended, so we don't need to define our own. - // Returns true if rhs references the same expectation as this object does. + // Returns true if and only if rhs references the same expectation as this + // object does. bool operator==(const Expectation& rhs) const { return expectation_base_ == rhs.expectation_base_; } @@ -598,8 +599,8 @@ class ExpectationSet { // The compiler-generator ctor and operator= works exactly as // intended, so we don't need to define our own. - // Returns true if rhs contains the same set of Expectation objects - // as this does. + // Returns true if and only if rhs contains the same set of Expectation + // objects as this does. bool operator==(const ExpectationSet& rhs) const { return expectations_ == rhs.expectations_; } @@ -760,8 +761,8 @@ class GTEST_API_ ExpectationBase { // by the subclasses to implement the .Times() clause. void SpecifyCardinality(const Cardinality& cardinality); - // Returns true if the user specified the cardinality explicitly - // using a .Times(). + // Returns true if and only if the user specified the cardinality + // explicitly using a .Times(). bool cardinality_specified() const { return cardinality_specified_; } // Sets the cardinality of this expectation spec. @@ -777,7 +778,7 @@ class GTEST_API_ ExpectationBase { void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); - // Returns true if this expectation is retired. + // Returns true if and only if this expectation is retired. bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); @@ -791,28 +792,29 @@ class GTEST_API_ ExpectationBase { retired_ = true; } - // Returns true if this expectation is satisfied. + // Returns true if and only if this expectation is satisfied. bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSatisfiedByCallCount(call_count_); } - // Returns true if this expectation is saturated. + // Returns true if and only if this expectation is saturated. bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSaturatedByCallCount(call_count_); } - // Returns true if this expectation is over-saturated. + // Returns true if and only if this expectation is over-saturated. bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsOverSaturatedByCallCount(call_count_); } - // Returns true if all pre-requisites of this expectation are satisfied. + // Returns true if and only if all pre-requisites of this expectation are + // satisfied. bool AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); @@ -855,7 +857,7 @@ class GTEST_API_ ExpectationBase { const char* file_; // The file that contains the expectation. int line_; // The line number of the expectation. const std::string source_text_; // The EXPECT_CALL(...) source text. - // True if the cardinality is specified explicitly. + // True if and only if the cardinality is specified explicitly. bool cardinality_specified_; Cardinality cardinality_; // The cardinality of the expectation. // The immediate pre-requisites (i.e. expectations that must be @@ -869,7 +871,7 @@ class GTEST_API_ ExpectationBase { // This group of fields are the current state of the expectation, // and can change as the mock function is called. int call_count_; // How many times this expectation has been invoked. - bool retired_; // True if this expectation has retired. + bool retired_; // True if and only if this expectation has retired. UntypedActions untyped_actions_; bool extra_matcher_specified_; bool repeated_action_specified_; // True if a WillRepeatedly() was specified. @@ -1087,14 +1089,15 @@ class TypedExpectation : public ExpectationBase { // statement finishes and when the current thread holds // g_gmock_mutex. - // Returns true if this expectation matches the given arguments. + // Returns true if and only if this expectation matches the given arguments. bool Matches(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } - // Returns true if this expectation should handle the given arguments. + // Returns true if and only if this expectation should handle the given + // arguments. bool ShouldHandleArguments(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); @@ -1320,8 +1323,8 @@ class ReferenceOrValueWrapper { // Provides nondestructive access to the underlying value/reference. // Always returns a const reference (more precisely, - // const RemoveReference<T>&). The behavior of calling this after - // calling Unwrap on the same object is unspecified. + // const std::add_lvalue_reference<T>::type). The behavior of calling this + // after calling Unwrap on the same object is unspecified. const T& Peek() const { return value_; } diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index 1770d5e7..584afa98 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -157,11 +157,11 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint); static_cast< ::testing::internal::TypeKind>( \ ::testing::internal::KindOf<type>::value) -// Evaluates to true if integer type T is signed. +// Evaluates to true if and only if integer type T is signed. #define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0) // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value -// is true if arithmetic type From can be losslessly converted to +// is true if and only if arithmetic type From can be losslessly converted to // arithmetic type To. // // It's the user's responsibility to ensure that both From and To are @@ -192,8 +192,8 @@ template <typename From> struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool> : public std::false_type {}; -// Converting an integer to another non-bool integer is lossless if -// the target type's range encloses the source type's range. +// Converting an integer to another non-bool integer is lossless +// if and only if the target type's range encloses the source type's range. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To> : public bool_constant< @@ -224,14 +224,14 @@ struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To> : public std::false_type {}; // Converting a floating-point to another floating-point is lossless -// if the target type is at least as big as the source type. +// if and only if the target type is at least as big as the source type. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl< kFloatingPoint, From, kFloatingPoint, To> : public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT -// LosslessArithmeticConvertible<From, To>::value is true if arithmetic -// type From can be losslessly converted to arithmetic type To. +// LosslessArithmeticConvertible<From, To>::value is true if and only if +// arithmetic type From can be losslessly converted to arithmetic type To. // // It's the user's responsibility to ensure that both From and To are // raw (i.e. has no CV modifier, is not a pointer, and is not a @@ -305,11 +305,11 @@ const char kWarningVerbosity[] = "warning"; // No logs are printed. const char kErrorVerbosity[] = "error"; -// Returns true if a log with the given severity is visible according -// to the --gmock_verbose flag. +// Returns true if and only if a log with the given severity is visible +// according to the --gmock_verbose flag. GTEST_API_ bool LogIsVisible(LogSeverity severity); -// Prints the given message to stdout if 'severity' >= the level +// Prints the given message to stdout if and only if 'severity' >= the level // specified by the --gmock_verbose flag. If stack_frames_to_skip >= // 0, also prints the stack trace excluding the top // stack_frames_to_skip frames. In opt mode, any positive @@ -334,12 +334,6 @@ class WithoutMatchers { // Internal use only: access the singleton instance of WithoutMatchers. GTEST_API_ WithoutMatchers GetWithoutMatchers(); -// Type traits. - -// remove_reference<T>::type removes the reference from type T, if any. -template <typename T> struct remove_reference { typedef T type; }; // NOLINT -template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT - // Disable MSVC warnings for infinite recursion, since in this case the // the recursion is unreachable. #ifdef _MSC_VER @@ -388,9 +382,8 @@ class StlContainerView { typedef const type& const_reference; static const_reference ConstReference(const RawContainer& container) { - // Ensures that RawContainer is not a const type. - testing::StaticAssertTypeEq< - RawContainer, typename std::remove_const<RawContainer>::type>(); + static_assert(!std::is_const<RawContainer>::value, + "RawContainer type must not be const"); return container; } static type Copy(const RawContainer& container) { return container; } @@ -410,8 +403,8 @@ class StlContainerView<Element[N]> { typedef const type const_reference; static const_reference ConstReference(const Element (&array)[N]) { - // Ensures that Element is not a const type. - testing::StaticAssertTypeEq<Element, RawElement>(); + static_assert(std::is_same<Element, RawElement>::value, + "Element type must not be const"); return type(array, N, RelationToSourceReference()); } static type Copy(const Element (&array)[N]) { @@ -497,8 +490,7 @@ struct Function<R(Args...)> { using Result = R; static constexpr size_t ArgumentCount = sizeof...(Args); template <size_t I> - using Arg = ElemFromList<I, typename MakeIndexSequence<sizeof...(Args)>::type, - Args...>; + using Arg = ElemFromList<I, Args...>; using ArgumentTuple = std::tuple<Args...>; using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>; using MakeResultVoid = void(Args...); diff --git a/googlemock/src/gmock-internal-utils.cc b/googlemock/src/gmock-internal-utils.cc index 1292e1d8..e5b54798 100644 --- a/googlemock/src/gmock-internal-utils.cc +++ b/googlemock/src/gmock-internal-utils.cc @@ -123,8 +123,8 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter() { // Protects global resources (stdout in particular) used by Log(). static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex); -// Returns true if a log with the given severity is visible according -// to the --gmock_verbose flag. +// Returns true if and only if a log with the given severity is visible +// according to the --gmock_verbose flag. GTEST_API_ bool LogIsVisible(LogSeverity severity) { if (GMOCK_FLAG(verbose) == kInfoVerbosity) { // Always show the log if --gmock_verbose=info. @@ -139,7 +139,7 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) { } } -// Prints the given message to stdout if 'severity' >= the level +// Prints the given message to stdout if and only if 'severity' >= the level // specified by the --gmock_verbose flag. If stack_frames_to_skip >= // 0, also prints the stack trace excluding the top // stack_frames_to_skip frames. In opt mode, any positive diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index f6705a32..81ea9894 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -36,14 +36,17 @@ #include "gmock/gmock-spec-builders.h" #include <stdlib.h> + #include <iostream> // NOLINT #include <map> #include <memory> #include <set> #include <string> #include <vector> + #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "gtest/internal/gtest-port.h" #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC # include <unistd.h> // NOLINT @@ -70,7 +73,8 @@ GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const std::string& message) { ::std::ostringstream s; - s << file << ":" << line << ": " << message << ::std::endl; + s << internal::FormatFileLocation(file, line) << " " << message + << ::std::endl; Log(severity, s.str(), 0); } @@ -126,8 +130,8 @@ void ExpectationBase::RetireAllPreRequisites() } } -// Returns true if all pre-requisites of this expectation have been -// satisfied. +// Returns true if and only if all pre-requisites of this expectation +// have been satisfied. bool ExpectationBase::AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); @@ -384,7 +388,7 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith( const CallReaction reaction = Mock::GetReactionOnUninterestingCalls(MockObject()); - // True if we need to print this call's arguments and return + // True if and only if we need to print this call's arguments and return // value. This definition must be kept in sync with // the behavior of ReportUninterestingCall(). const bool need_to_report_uninteresting_call = @@ -435,7 +439,8 @@ UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith( &ss, &why); const bool found = untyped_expectation != nullptr; - // True if we need to print the call's arguments and return value. + // True if and only if we need to print the call's arguments + // and return value. // This definition must be kept in sync with the uses of Expect() // and Log() in this function. const bool need_to_report_call = @@ -574,7 +579,7 @@ struct MockObjectState { int first_used_line; ::std::string first_used_test_suite; ::std::string first_used_test; - bool leakable; // true if it's OK to leak the object. + bool leakable; // true if and only if it's OK to leak the object. FunctionMockers function_mockers; // All registered methods of the object. }; @@ -718,7 +723,7 @@ bool Mock::VerifyAndClearExpectations(void* mock_obj) } // Verifies all expectations on the given mock object and clears its -// default actions and expectations. Returns true if the +// default actions and expectations. Returns true if and only if the // verification was successful. bool Mock::VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { diff --git a/googlemock/src/gmock.cc b/googlemock/src/gmock.cc index ce926f2d..32b2a739 100644 --- a/googlemock/src/gmock.cc +++ b/googlemock/src/gmock.cc @@ -34,8 +34,8 @@ namespace testing { GMOCK_DEFINE_bool_(catch_leaked_mocks, true, - "true if Google Mock should report leaked mock objects " - "as failures."); + "true if and only if Google Mock should report leaked " + "mock objects as failures."); GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity, "Controls how verbose Google Mock's output is." diff --git a/googlemock/test/gmock-cardinalities_test.cc b/googlemock/test/gmock-cardinalities_test.cc index 66042d40..ca97cae2 100644 --- a/googlemock/test/gmock-cardinalities_test.cc +++ b/googlemock/test/gmock-cardinalities_test.cc @@ -395,12 +395,14 @@ TEST(ExactlyTest, HasCorrectBounds) { class EvenCardinality : public CardinalityInterface { public: - // Returns true if call_count calls will satisfy this cardinality. + // Returns true if and only if call_count calls will satisfy this + // cardinality. bool IsSatisfiedByCallCount(int call_count) const override { return (call_count % 2 == 0); } - // Returns true if call_count calls will saturate this cardinality. + // Returns true if and only if call_count calls will saturate this + // cardinality. bool IsSaturatedByCallCount(int /* call_count */) const override { return false; } diff --git a/googlemock/test/gmock-internal-utils_test.cc b/googlemock/test/gmock-internal-utils_test.cc index 67b7077f..19ba6fe5 100644 --- a/googlemock/test/gmock-internal-utils_test.cc +++ b/googlemock/test/gmock-internal-utils_test.cc @@ -40,7 +40,6 @@ #include <memory> #include <sstream> #include <string> -#include <type_traits> #include <vector> #include "gmock/gmock.h" @@ -125,15 +124,17 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) { } TEST(PointeeOfTest, WorksForSmartPointers) { - CompileAssertTypesEqual<int, PointeeOf<std::unique_ptr<int> >::type>(); - CompileAssertTypesEqual<std::string, - PointeeOf<std::shared_ptr<std::string> >::type>(); + EXPECT_TRUE( + (std::is_same<int, PointeeOf<std::unique_ptr<int>>::type>::value)); + EXPECT_TRUE( + (std::is_same<std::string, + PointeeOf<std::shared_ptr<std::string>>::type>::value)); } TEST(PointeeOfTest, WorksForRawPointers) { - CompileAssertTypesEqual<int, PointeeOf<int*>::type>(); - CompileAssertTypesEqual<const char, PointeeOf<const char*>::type>(); - CompileAssertTypesEqual<void, PointeeOf<void*>::type>(); + EXPECT_TRUE((std::is_same<int, PointeeOf<int*>::type>::value)); + EXPECT_TRUE((std::is_same<const char, PointeeOf<const char*>::type>::value)); + EXPECT_TRUE((std::is_void<PointeeOf<void*>::type>::value)); } TEST(GetRawPointerTest, WorksForSmartPointers) { @@ -506,18 +507,6 @@ TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) { TestLogWithSeverity("invalid", kWarning, true); } -#endif // GTEST_HAS_STREAM_REDIRECTION - -TEST(TypeTraitsTest, remove_reference) { - EXPECT_TRUE((std::is_same<char, remove_reference<char&>::type>::value)); - EXPECT_TRUE( - (std::is_same<const int, remove_reference<const int&>::type>::value)); - EXPECT_TRUE((std::is_same<int, remove_reference<int>::type>::value)); - EXPECT_TRUE((std::is_same<double*, remove_reference<double*>::type>::value)); -} - -#if GTEST_HAS_STREAM_REDIRECTION - // Verifies that Log() behaves correctly for the given verbosity level // and log severity. std::string GrabOutput(void(*logger)(), const char* verbosity) { @@ -676,63 +665,66 @@ TEST(StlContainerViewTest, WorksForDynamicNativeArray) { TEST(FunctionTest, Nullary) { typedef Function<int()> F; // NOLINT EXPECT_EQ(0u, F::ArgumentCount); - CompileAssertTypesEqual<int, F::Result>(); - CompileAssertTypesEqual<std::tuple<>, F::ArgumentTuple>(); - CompileAssertTypesEqual<std::tuple<>, F::ArgumentMatcherTuple>(); - CompileAssertTypesEqual<void(), F::MakeResultVoid>(); - CompileAssertTypesEqual<IgnoredValue(), F::MakeResultIgnoredValue>(); + EXPECT_TRUE((std::is_same<int, F::Result>::value)); + EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentTuple>::value)); + EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentMatcherTuple>::value)); + EXPECT_TRUE((std::is_same<void(), F::MakeResultVoid>::value)); + EXPECT_TRUE((std::is_same<IgnoredValue(), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, Unary) { typedef Function<int(bool)> F; // NOLINT EXPECT_EQ(1u, F::ArgumentCount); - CompileAssertTypesEqual<int, F::Result>(); - CompileAssertTypesEqual<bool, F::Arg<0>::type>(); - CompileAssertTypesEqual<std::tuple<bool>, F::ArgumentTuple>(); - CompileAssertTypesEqual<std::tuple<Matcher<bool> >, - F::ArgumentMatcherTuple>(); - CompileAssertTypesEqual<void(bool), F::MakeResultVoid>(); // NOLINT - CompileAssertTypesEqual<IgnoredValue(bool), // NOLINT - F::MakeResultIgnoredValue>(); + EXPECT_TRUE((std::is_same<int, F::Result>::value)); + EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); + EXPECT_TRUE((std::is_same<std::tuple<bool>, F::ArgumentTuple>::value)); + EXPECT_TRUE(( + std::is_same<std::tuple<Matcher<bool>>, F::ArgumentMatcherTuple>::value)); + EXPECT_TRUE((std::is_same<void(bool), F::MakeResultVoid>::value)); // NOLINT + EXPECT_TRUE((std::is_same<IgnoredValue(bool), // NOLINT + F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, Binary) { typedef Function<int(bool, const long&)> F; // NOLINT EXPECT_EQ(2u, F::ArgumentCount); - CompileAssertTypesEqual<int, F::Result>(); - CompileAssertTypesEqual<bool, F::Arg<0>::type>(); - CompileAssertTypesEqual<const long&, F::Arg<1>::type>(); // NOLINT - CompileAssertTypesEqual<std::tuple<bool, const long&>, // NOLINT - F::ArgumentTuple>(); - CompileAssertTypesEqual< - std::tuple<Matcher<bool>, Matcher<const long&> >, // NOLINT - F::ArgumentMatcherTuple>(); - CompileAssertTypesEqual<void(bool, const long&), F::MakeResultVoid>(); // NOLINT - CompileAssertTypesEqual<IgnoredValue(bool, const long&), // NOLINT - F::MakeResultIgnoredValue>(); + EXPECT_TRUE((std::is_same<int, F::Result>::value)); + EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); + EXPECT_TRUE((std::is_same<const long&, F::Arg<1>::type>::value)); // NOLINT + EXPECT_TRUE((std::is_same<std::tuple<bool, const long&>, // NOLINT + F::ArgumentTuple>::value)); + EXPECT_TRUE( + (std::is_same<std::tuple<Matcher<bool>, Matcher<const long&>>, // NOLINT + F::ArgumentMatcherTuple>::value)); + EXPECT_TRUE((std::is_same<void(bool, const long&), // NOLINT + F::MakeResultVoid>::value)); + EXPECT_TRUE((std::is_same<IgnoredValue(bool, const long&), // NOLINT + F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, LongArgumentList) { typedef Function<char(bool, int, char*, int&, const long&)> F; // NOLINT EXPECT_EQ(5u, F::ArgumentCount); - CompileAssertTypesEqual<char, F::Result>(); - CompileAssertTypesEqual<bool, F::Arg<0>::type>(); - CompileAssertTypesEqual<int, F::Arg<1>::type>(); - CompileAssertTypesEqual<char*, F::Arg<2>::type>(); - CompileAssertTypesEqual<int&, F::Arg<3>::type>(); - CompileAssertTypesEqual<const long&, F::Arg<4>::type>(); // NOLINT - CompileAssertTypesEqual< - std::tuple<bool, int, char*, int&, const long&>, // NOLINT - F::ArgumentTuple>(); - CompileAssertTypesEqual< - std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>, - Matcher<const long&> >, // NOLINT - F::ArgumentMatcherTuple>(); - CompileAssertTypesEqual<void(bool, int, char*, int&, const long&), // NOLINT - F::MakeResultVoid>(); - CompileAssertTypesEqual< - IgnoredValue(bool, int, char*, int&, const long&), // NOLINT - F::MakeResultIgnoredValue>(); + EXPECT_TRUE((std::is_same<char, F::Result>::value)); + EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); + EXPECT_TRUE((std::is_same<int, F::Arg<1>::type>::value)); + EXPECT_TRUE((std::is_same<char*, F::Arg<2>::type>::value)); + EXPECT_TRUE((std::is_same<int&, F::Arg<3>::type>::value)); + EXPECT_TRUE((std::is_same<const long&, F::Arg<4>::type>::value)); // NOLINT + EXPECT_TRUE( + (std::is_same<std::tuple<bool, int, char*, int&, const long&>, // NOLINT + F::ArgumentTuple>::value)); + EXPECT_TRUE( + (std::is_same< + std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>, + Matcher<const long&>>, // NOLINT + F::ArgumentMatcherTuple>::value)); + EXPECT_TRUE( + (std::is_same<void(bool, int, char*, int&, const long&), // NOLINT + F::MakeResultVoid>::value)); + EXPECT_TRUE(( + std::is_same<IgnoredValue(bool, int, char*, int&, const long&), // NOLINT + F::MakeResultIgnoredValue>::value)); } } // namespace diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index a61d040b..03735267 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -956,10 +956,9 @@ TEST(TypedEqTest, CanDescribeSelf) { // Tests that TypedEq<T>(v) has type Matcher<T>. -// Type<T>::IsTypeOf(v) compiles if the type of value v is T, where T -// is a "bare" type (i.e. not in the form of const U or U&). If v's -// type is not T, the compiler will generate a message about -// "undefined reference". +// Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where +// T is a "bare" type (i.e. not in the form of const U or U&). If v's type is +// not T, the compiler will generate a message about "undefined reference". template <typename T> struct Type { static bool IsTypeOf(const T& /* v */) { return true; } @@ -2640,8 +2639,8 @@ class IsGreaterThan { // For testing Truly(). const int foo = 0; -// This predicate returns true if the argument references foo and has -// a zero value. +// This predicate returns true if and only if the argument references foo and +// has a zero value. bool ReferencesFooAndIsZero(const int& n) { return (&n == &foo) && (n == 0); } @@ -3594,7 +3593,7 @@ class Uncopyable { GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable); }; -// Returns true if x.value() is positive. +// Returns true if and only if x.value() is positive. bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; } MATCHER_P(UncopyableIs, inner_matcher, "") { @@ -4319,6 +4318,16 @@ TEST(ResultOfTest, WorksForLambdas) { EXPECT_FALSE(matcher.Matches(1)); } +TEST(ResultOfTest, WorksForNonCopyableArguments) { + Matcher<std::unique_ptr<int>> matcher = ResultOf( + [](const std::unique_ptr<int>& str_len) { + return std::string(static_cast<size_t>(*str_len), 'x'); + }, + "xxx"); + EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3)))); + EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1)))); +} + const int* ReferencingFunction(const int& n) { return &n; } struct ReferencingFunctor { diff --git a/googlemock/test/gmock-more-actions_test.cc b/googlemock/test/gmock-more-actions_test.cc index b4e0fc30..97ec5cf0 100644 --- a/googlemock/test/gmock-more-actions_test.cc +++ b/googlemock/test/gmock-more-actions_test.cc @@ -57,7 +57,6 @@ using testing::ReturnPointee; using testing::SaveArg; using testing::SaveArgPointee; using testing::SetArgReferee; -using testing::StaticAssertTypeEq; using testing::Unused; using testing::WithArg; using testing::WithoutArgs; diff --git a/googlemock/test/gmock-spec-builders_test.cc b/googlemock/test/gmock-spec-builders_test.cc index 95b4b8b7..7bf5a8ad 100644 --- a/googlemock/test/gmock-spec-builders_test.cc +++ b/googlemock/test/gmock-spec-builders_test.cc @@ -1952,12 +1952,14 @@ TEST(DeletingMockEarlyTest, Failure2) { class EvenNumberCardinality : public CardinalityInterface { public: - // Returns true if call_count calls will satisfy this cardinality. + // Returns true if and only if call_count calls will satisfy this + // cardinality. bool IsSatisfiedByCallCount(int call_count) const override { return call_count % 2 == 0; } - // Returns true if call_count calls will saturate this cardinality. + // Returns true if and only if call_count calls will saturate this + // cardinality. bool IsSaturatedByCallCount(int /* call_count */) const override { return false; } diff --git a/googletest/cmake/gtest.pc.in b/googletest/cmake/gtest.pc.in index 9aae29e2..e7967ad5 100644 --- a/googletest/cmake/gtest.pc.in +++ b/googletest/cmake/gtest.pc.in @@ -1,6 +1,5 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: gtest Description: GoogleTest (without main() function) diff --git a/googletest/cmake/gtest_main.pc.in b/googletest/cmake/gtest_main.pc.in index 915f2973..fe25d9c7 100644 --- a/googletest/cmake/gtest_main.pc.in +++ b/googletest/cmake/gtest_main.pc.in @@ -1,6 +1,5 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: gtest_main Description: GoogleTest (with main() function) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 51005e93..179118dc 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -464,9 +464,10 @@ You can call the function to assert that types `T1` and `T2` are the same. The function does nothing if the assertion is satisfied. If the types are different, the function call will -fail to compile, and the compiler error message will likely (depending on the -compiler) show you the actual values of `T1` and `T2`. This is mainly useful -inside template code. +fail to compile, the compiler error message will say that +`T1 and T2 are not the same type` and most likely (depending on the compiler) +show you the actual values of `T1` and `T2`. This is mainly useful inside +template code. **Caveat**: When used inside a member function of a class template or a function template, `StaticAssertTypeEq<T1, T2>()` is effective only if the function is @@ -641,7 +642,7 @@ Fatal assertion | Nonfatal assertion where `statement` is a statement that is expected to cause the process to die, `predicate` is a function or function object that evaluates an integer exit -status, and `matcher` is either a GMock matcher matching a `const std::string&` +status, and `matcher` is either a gMock matcher matching a `const std::string&` or a (Perl) regular expression - either of which is matched against the stderr output of `statement`. For legacy reasons, a bare string (i.e. with no matcher) is interpreted as `ContainsRegex(str)`, **not** `Eq(str)`. Note that `statement` @@ -656,7 +657,7 @@ As usual, the `ASSERT` variants abort the current test function, while the > has called `exit()` or `_exit()` with a non-zero value, or it may be killed by > a signal. > -> This means that if `*statement*` terminates the process with a 0 exit code, it +> This means that if *`statement`* terminates the process with a 0 exit code, it > is *not* considered a crash by `EXPECT_DEATH`. Use `EXPECT_EXIT` instead if > this is the case, or if you want to restrict the exit code more precisely. @@ -686,7 +687,7 @@ Note that a death test only cares about three things: 2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero? And -3. does the stderr output match `regex`? +3. does the stderr output match `matcher`? In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as googletest assertions don't abort @@ -1131,7 +1132,7 @@ will output XML like this: > * `RecordProperty()` is a static member of the `Test` class. Therefore it > needs to be prefixed with `::testing::Test::` if used outside of the > `TEST` body and the test fixture class. -> * `*key*` must be a valid XML attribute name, and cannot conflict with the +> * *`key`* must be a valid XML attribute name, and cannot conflict with the > ones already used by googletest (`name`, `status`, `time`, `classname`, > `type_param`, and `value_param`). > * Calling `RecordProperty()` outside of the lifespan of a test is allowed. @@ -1903,8 +1904,6 @@ To obtain a `TestInfo` object for the currently running test, call const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); - - printf("We are in test %s of test suite %s.\n", test_info->name(), test_info->test_suite_name()); diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index 9949fec2..05ecdd7d 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -298,7 +298,7 @@ In the end, this boils down to good concurrent programming. You have to make sure that there is no race conditions or dead locks in your program. No silver bullet - sorry! -## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? +## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp} The first thing to remember is that googletest does **not** reuse the same test fixture object across multiple tests. For each `TEST_F`, googletest will create @@ -531,8 +531,8 @@ There are several good reasons: ## What can the statement argument in ASSERT_DEATH() be? -`ASSERT_DEATH(*statement*, *regex*)` (or any death assertion macro) can be used -wherever `*statement*` is valid. So basically `*statement*` can be any C++ +`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used +wherever *`statement`* is valid. So basically *`statement`* can be any C++ statement that makes sense in the current context. In particular, it can reference global and/or local variables, and can be: diff --git a/googletest/docs/pkgconfig.md b/googletest/docs/pkgconfig.md index b7758738..117166cf 100644 --- a/googletest/docs/pkgconfig.md +++ b/googletest/docs/pkgconfig.md @@ -98,7 +98,7 @@ test('first_and_only_test', testapp) Since `pkg-config` is a small Unix command-line utility, it can be used in handwritten `Makefile`s too: -```Makefile +```makefile GTEST_CFLAGS = `pkg-config --cflags gtest_main` GTEST_LIBS = `pkg-config --libs gtest_main` @@ -139,3 +139,81 @@ export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig ``` pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`. + +### Using pkg-config in a cross-compilation setting + +Pkg-config can be used in a cross-compilation setting too. To do this, let's +assume the final prefix of the cross-compiled installation will be `/usr`, and +your sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using + +``` +mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr .. +``` + +Install into the sysroot using `DESTDIR`: + +``` +make -j install DESTDIR=/home/MYUSER/sysroot +``` + +Before we continue, it is recommended to **always** define the following two +variables for pkg-config in a cross-compilation setting: + +``` +export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes +export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes +``` + +otherwise `pkg-config` will filter `-I` and `-L` flags against standard prefixes +such as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 for +reasons why this stripping needs to occur usually). + +If you look at the generated pkg-config file, it will look something like + +``` +libdir=/usr/lib64 +includedir=/usr/include + +Name: gtest +Description: GoogleTest (without main() function) +Version: 1.10.0 +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgtest -lpthread +Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread +``` + +Notice that the sysroot is not included in `libdir` and `includedir`! If you try +to run `pkg-config` with the correct +`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc` +file, you will get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include +$ pkg-config --libs gtest +-L/usr/lib64 -lgtest -lpthread +``` + +which is obviously wrong and points to the `CBUILD` and not `CHOST` root. In +order to use this in a cross-compilation setting, we need to tell pkg-config to +inject the actual sysroot into `-I` and `-L` variables. Let us now tell +pkg-config about the actual sysroot + +``` +export PKG_CONFIG_DIR= +export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot +export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig +``` + +and running `pkg-config` again we get + +``` +$ pkg-config --cflags gtest +-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include +$ pkg-config --libs gtest +-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread +``` + +which contains the correct sysroot now. For a more comprehensive guide to also +including `${CHOST}` in build system calls, see the excellent tutorial by Diego +Elio Pettenò: https://autotools.io/pkgconfig/cross-compiling.html diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index caf9c43c..0317692b 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -5,9 +5,9 @@ *googletest* helps you write better C++ tests. googletest is a testing framework developed by the Testing Technology team with -Google's specific requirements and constraints in mind. No matter whether you -work on Linux, Windows, or a Mac, if you write C++ code, googletest can help -you. And it supports *any* kind of tests, not just unit tests. +Google's specific requirements and constraints in mind. Whether you work on +Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it +supports *any* kind of tests, not just unit tests. So what makes a good test, and how does googletest fit in? We believe: @@ -21,7 +21,7 @@ So what makes a good test, and how does googletest fit in? We believe: easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base. 3. Tests should be *portable* and *reusable*. Google has a lot of code that is - platform-neutral, its tests should also be platform-neutral. googletest + platform-neutral; its tests should also be platform-neutral. googletest works on different OSes, with different compilers, with or without exceptions, so googletest tests can work with a variety of configurations. 4. When tests fail, they should provide as much *information* about the problem @@ -44,18 +44,17 @@ minutes to learn the basics and get started. So let's go! ## Beware of the nomenclature -_Note:_ There might be some confusion of idea due to different -definitions of the terms _Test_, _Test Case_ and _Test Suite_, so beware -of misunderstanding these. +_Note:_ There might be some confusion arising from different definitions of the +terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these. Historically, googletest started to use the term _Test Case_ for grouping -related tests, whereas current publications including the International Software -Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) and various -textbooks on Software Quality use the term _[Test Suite][istqb test suite]_ for -this. +related tests, whereas current publications, including International Software +Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and +various textbooks on software quality, use the term +_[Test Suite][istqb test suite]_ for this. -The related term _Test_, as it is used in the googletest, is corresponding to -the term _[Test Case][istqb test case]_ of ISTQB and others. +The related term _Test_, as it is used in googletest, corresponds to the term +_[Test Case][istqb test case]_ of ISTQB and others. The term _Test_ is commonly of broad enough sense, including ISTQB's definition of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as @@ -120,7 +119,7 @@ Depending on the nature of the leak, it may or may not be worth fixing - so keep this in mind if you get a heap checker error in addition to assertion errors. To provide a custom failure message, simply stream it into the macro using the -`<<` operator, or a sequence of such operators. An example: +`<<` operator or a sequence of such operators. An example: ```c++ ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; @@ -166,16 +165,16 @@ Fatal assertion | Nonfatal assertion | Verifies Value arguments must be comparable by the assertion's comparison operator or you'll get a compiler error. We used to require the arguments to support the -`<<` operator for streaming to an `ostream`, but it's no longer necessary. If +`<<` operator for streaming to an `ostream`, but this is no longer necessary. If `<<` is supported, it will be called to print the arguments when the assertion fails; otherwise googletest will attempt to print them in the best way it can. -For more details and how to customize the printing of the arguments, see -[documentation](../../googlemock/docs/cook_book.md#teaching-gmock-how-to-print-your-values) +For more details and how to customize the printing of the arguments, see the +[documentation](../../googlemock/docs/cook_book.md#teaching-gmock-how-to-print-your-values). These assertions can work with a user-defined type, but only if you define the -corresponding comparison operator (e.g. `==`, `<`, etc). Since this is -discouraged by the Google [C++ Style -Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading), +corresponding comparison operator (e.g., `==` or `<`). Since this is discouraged +by the Google +[C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading), you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of two objects of a user-defined type. @@ -185,8 +184,8 @@ values on failure. Arguments are always evaluated exactly once. Therefore, it's OK for the arguments to have side effects. However, as with any ordinary C/C++ function, -the arguments' evaluation order is undefined (i.e. the compiler is free to -choose any order) and your code should not depend on any particular argument +the arguments' evaluation order is undefined (i.e., the compiler is free to +choose any order), and your code should not depend on any particular argument evaluation order. `ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it @@ -199,7 +198,7 @@ objects, you should use `ASSERT_EQ`. When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)` instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is -typed while `NULL` is not. See [FAQ](faq.md) for more details. +typed, while `NULL` is not. See the [FAQ](faq.md) for more details. If you're working with floating point numbers, you may want to use the floating point variations of some of these macros in order to avoid problems caused by @@ -246,7 +245,7 @@ Advanced googletest Guide. To create a test: -1. Use the `TEST()` macro to define and name a test function, These are +1. Use the `TEST()` macro to define and name a test function. These are ordinary C++ functions that don't return a value. 2. In this function, along with any valid C++ statements you want to include, use the various googletest assertions to check values. @@ -263,7 +262,7 @@ TEST(TestSuiteName, TestName) { `TEST()` arguments go from general to specific. The *first* argument is the name of the test suite, and the *second* argument is the test's name within the test case. Both names must be valid C++ identifiers, and they should not contain -underscore (`_`). A test's *full name* consists of its containing test suite and +any underscores (`_`). A test's *full name* consists of its containing test suite and its individual name. Tests from different test suites can have the same individual name. @@ -290,7 +289,7 @@ TEST(FactorialTest, HandlesPositiveInput) { } ``` -googletest groups the test results by test suites, so logically-related tests +googletest groups the test results by test suites, so logically related tests should be in the same test suite; in other words, the first argument to their `TEST()` should be the same. In the above example, we have two tests, `HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test @@ -302,25 +301,25 @@ for **Availability**: Linux, Windows, Mac. -## Test Fixtures: Using the Same Data Configuration for Multiple Tests +## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests} If you find yourself writing two or more tests that operate on similar data, you -can use a *test fixture*. It allows you to reuse the same configuration of +can use a *test fixture*. This allows you to reuse the same configuration of 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 the objects for each test. A common mistake is to spell `SetUp()` as **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you - spelled it correctly + spelled it correctly. 4. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read - the [FAQ](faq.md). + the [FAQ](faq.md#CtorVsSetUp). 5. If needed, define subroutines for your tests to share. When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to @@ -344,9 +343,9 @@ Also, you must first define a test fixture class before using it in a `TEST_F()`, or you'll get the compiler error "`virtual outside class declaration`". -For each test defined with `TEST_F()` , googletest will create a *fresh* test -fixture at runtime, immediately initialize it via `SetUp()` , run the test, -clean up by calling `TearDown()` , and then delete the test fixture. Note that +For each test defined with `TEST_F()`, googletest will create a *fresh* test +fixture at runtime, immediately initialize it via `SetUp()`, run the test, +clean up by calling `TearDown()`, and then delete the test fixture. Note that different tests in the same test suite have different test fixture objects, and googletest always deletes a test fixture before it creates the next one. googletest does **not** reuse the same test fixture for multiple tests. Any @@ -424,9 +423,9 @@ would lead to a segfault when `n` is `NULL`. When these tests run, the following happens: -1. googletest constructs a `QueueTest` object (let's call it `t1` ). -2. `t1.SetUp()` initializes `t1` . -3. The first test ( `IsEmptyInitially` ) runs on `t1` . +1. googletest constructs a `QueueTest` object (let's call it `t1`). +2. `t1.SetUp()` initializes `t1`. +3. The first test (`IsEmptyInitially`) runs on `t1`. 4. `t1.TearDown()` cleans up after the test finishes. 5. `t1` is destructed. 6. The above steps are repeated on another `QueueTest` object, this time @@ -440,14 +439,14 @@ When these tests run, the following happens: unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them. -After defining your tests, you can run them with `RUN_ALL_TESTS()` , which +After defining your tests, you can run them with `RUN_ALL_TESTS()`, which returns `0` if all the tests are successful, or `1` otherwise. Note that -`RUN_ALL_TESTS()` runs *all tests* in your link unit -- they can be from +`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different test suites, or even different source files. When invoked, the `RUN_ALL_TESTS()` macro: -* Saves the state of all googletest flags +* Saves the state of all googletest flags. * Creates a test fixture object for the first test. @@ -459,7 +458,7 @@ When invoked, the `RUN_ALL_TESTS()` macro: * Deletes the fixture. -* Restores the state of all googletest flags +* Restores the state of all googletest flags. * Repeats the above steps for the next test, until all tests have run. @@ -472,7 +471,7 @@ If a fatal failure happens the subsequent steps will be skipped. > return the value of `RUN_ALL_TESTS()`. > > Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than -> once conflicts with some advanced googletest features (e.g. thread-safe +> once conflicts with some advanced googletest features (e.g., thread-safe > [death tests](advanced.md#death-tests)) and thus is not supported. **Availability**: Linux, Windows, Mac. @@ -480,7 +479,7 @@ If a fatal failure happens the subsequent steps will be skipped. ## Writing the main() Function Write your own main() function, which should return the value of -`RUN_ALL_TESTS()` +`RUN_ALL_TESTS()`. You can start from this boilerplate: @@ -544,14 +543,14 @@ int main(int argc, char **argv) { 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 -[AdvancedGuide](advanced.md). You **must** call this function before calling +the [AdvancedGuide](advanced.md). You **must** call this function before calling `RUN_ALL_TESTS()`, or the flags won't be properly initialized. On Windows, `InitGoogleTest()` also works with wide strings, so it can be used in programs compiled in `UNICODE` mode as well. But maybe you think that writing all those main() functions is too much work? We -agree with you completely and that's why Google Test provides a basic +agree with you completely, and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go. diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index cec9629e..dc878ffb 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -276,20 +276,20 @@ class GTEST_API_ KilledBySignal { // This macro is used for implementing macros such as // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where // death tests are not supported. Those macros must compile on such systems -// if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on -// systems that support death tests. This allows one to write such a macro -// on a system that does not support death tests and be sure that it will -// compile on a death-test supporting system. It is exposed publicly so that -// systems that have death-tests with stricter requirements than -// GTEST_HAS_DEATH_TEST can write their own equivalent of -// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED. +// if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters +// on systems that support death tests. This allows one to write such a macro on +// a system that does not support death tests and be sure that it will compile +// on a death-test supporting system. It is exposed publicly so that systems +// that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST +// can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and +// ASSERT_DEATH_IF_SUPPORTED. // // Parameters: // statement - A statement that a macro such as EXPECT_DEATH would test // for program termination. This macro has to make sure this // statement is compiled but not executed, to ensure that // EXPECT_DEATH_IF_SUPPORTED compiles with a certain -// parameter if EXPECT_DEATH compiles with it. +// parameter if and only if EXPECT_DEATH compiles with it. // regex - A regex that a macro such as EXPECT_DEATH would use to test // the output of statement. This parameter has to be // compiled but not evaluated by this macro, to ensure that diff --git a/googletest/include/gtest/gtest-matchers.h b/googletest/include/gtest/gtest-matchers.h index c10d650b..d9b28e08 100644 --- a/googletest/include/gtest/gtest-matchers.h +++ b/googletest/include/gtest/gtest-matchers.h @@ -96,8 +96,8 @@ class MatchResultListener { // Returns the underlying ostream. ::std::ostream* stream() { return stream_; } - // Returns true if the listener is interested in an explanation of - // the match result. A matcher's MatchAndExplain() method can use + // Returns true if and only if the listener is interested in an explanation + // of the match result. A matcher's MatchAndExplain() method can use // this information to avoid generating the explanation when no one // intends to hear it. bool IsInterested() const { return stream_ != nullptr; } @@ -141,8 +141,8 @@ class MatcherDescriberInterface { template <typename T> class MatcherInterface : public MatcherDescriberInterface { public: - // Returns true if the matcher matches x; also explains the match - // result to 'listener' if necessary (see the next paragraph), in + // Returns true if and only if the matcher matches x; also explains the + // match result to 'listener' if necessary (see the next paragraph), in // the form of a non-restrictive relative clause ("which ...", // "whose ...", etc) that describes x. For example, the // MatchAndExplain() method of the Pointee(...) matcher should @@ -258,13 +258,13 @@ class StreamMatchResultListener : public MatchResultListener { template <typename T> class MatcherBase { public: - // Returns true if the matcher matches x; also explains the match - // result to 'listener'. + // Returns true if and only if the matcher matches x; also explains the + // match result to 'listener'. bool MatchAndExplain(const T& x, MatchResultListener* listener) const { return impl_->MatchAndExplain(x, listener); } - // Returns true if this matcher matches x. + // Returns true if and only if this matcher matches x. bool Matches(const T& x) const { DummyMatchResultListener dummy; return MatchAndExplain(x, &dummy); @@ -474,13 +474,13 @@ class PolymorphicMatcher { public: explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} - virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); } + void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); } - virtual void DescribeNegationTo(::std::ostream* os) const { + void DescribeNegationTo(::std::ostream* os) const override { impl_.DescribeNegationTo(os); } - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { + bool MatchAndExplain(T x, MatchResultListener* listener) const override { return impl_.MatchAndExplain(x, listener); } diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index d7c9dd8c..f61e3c5d 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -58,7 +58,9 @@ class FooTest : public ::testing::TestWithParam<const char*> { // Then, use the TEST_P macro to define as many parameterized tests // for this fixture as you want. The _P suffix is for "parameterized" -// or "pattern", whichever you prefer to think. +// or "pattern", whichever you prefer to think. The arguments to the +// TEST_P macro are the test_suite_name and test_case (both which must be +// non-empty) that will form the test name. TEST_P(FooTest, DoesBlah) { // Inside a test, access the test parameter with the GetParam() method @@ -101,10 +103,10 @@ INSTANTIATE_TEST_SUITE_P(InstantiationName, // To distinguish different instances of the pattern, (yes, you // can instantiate it more than once) the first argument to the -// INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the -// actual test suite name. Remember to pick unique prefixes for different -// instantiations. The tests from the instantiation above will have -// these names: +// INSTANTIATE_TEST_SUITE_P macro is a prefix (which must be non-empty) that +// will be added to the actual test suite name. Remember to pick unique prefixes +// for different instantiations. The tests from the instantiation above will +// have these names: // // * InstantiationName/FooTest.DoesBlah/0 for "meeny" // * InstantiationName/FooTest.DoesBlah/1 for "miny" @@ -174,6 +176,7 @@ TEST_P(DerivedTest, DoesBlah) { #endif // 0 +#include <iterator> #include <utility> #include "gtest/internal/gtest-internal.h" @@ -292,10 +295,9 @@ internal::ParamGenerator<T> Range(T start, T end) { // template <typename ForwardIterator> internal::ParamGenerator< - typename ::testing::internal::IteratorTraits<ForwardIterator>::value_type> + typename std::iterator_traits<ForwardIterator>::value_type> ValuesIn(ForwardIterator begin, ForwardIterator end) { - typedef typename ::testing::internal::IteratorTraits<ForwardIterator> - ::value_type ParamType; + typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType; return internal::ParamGenerator<ParamType>( new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end)); } @@ -412,18 +414,22 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) { } #define TEST_P(test_suite_name, test_name) \ + static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ + "test_suite_name must not be empty"); \ + static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \ + "test_name must not be empty"); \ class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ : public test_suite_name { \ public: \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ - virtual void TestBody(); \ + void TestBody() override; \ \ private: \ static int AddToRegistry() { \ ::testing::UnitTest::GetInstance() \ ->parameterized_test_registry() \ .GetTestSuitePatternHolder<test_suite_name>( \ - #test_suite_name, \ + GTEST_STRINGIFY_(test_suite_name), \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ ->AddTestPattern( \ GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \ @@ -458,6 +464,10 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) { #define GTEST_GET_SECOND_(first, second, ...) second #define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ + static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ + "test_suite_name must not be empty"); \ + static_assert(sizeof(GTEST_STRINGIFY_(prefix)) > 1, \ + "prefix must not be empty"); \ static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \ gtest_##prefix##test_suite_name##_EvalGenerator_() { \ return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \ @@ -483,10 +493,11 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) { ::testing::UnitTest::GetInstance() \ ->parameterized_test_registry() \ .GetTestSuitePatternHolder<test_suite_name>( \ - #test_suite_name, \ + GTEST_STRINGIFY_(test_suite_name), \ ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ ->AddTestSuiteInstantiation( \ - #prefix, >est_##prefix##test_suite_name##_EvalGenerator_, \ + GTEST_STRINGIFY_(prefix), \ + >est_##prefix##test_suite_name##_EvalGenerator_, \ >est_##prefix##test_suite_name##_EvalGenerateName_, \ __FILE__, __LINE__) diff --git a/googletest/include/gtest/gtest-test-part.h b/googletest/include/gtest/gtest-test-part.h index 4f189b6e..05a79853 100644 --- a/googletest/include/gtest/gtest-test-part.h +++ b/googletest/include/gtest/gtest-test-part.h @@ -87,19 +87,19 @@ class GTEST_API_ TestPartResult { // Gets the message associated with the test part. const char* message() const { return message_.c_str(); } - // Returns true if the test part was skipped. + // Returns true if and only if the test part was skipped. bool skipped() const { return type_ == kSkip; } - // Returns true if the test part passed. + // Returns true if and only if the test part passed. bool passed() const { return type_ == kSuccess; } - // Returns true if the test part non-fatally failed. + // Returns true if and only if the test part non-fatally failed. bool nonfatally_failed() const { return type_ == kNonFatalFailure; } - // Returns true if the test part fatally failed. + // Returns true if and only if the test part fatally failed. bool fatally_failed() const { return type_ == kFatalFailure; } - // Returns true if the test part failed. + // Returns true if and only if the test part failed. bool failed() const { return fatally_failed() || nonfatally_failed(); } private: diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index dfe7c786..37a1762b 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -308,7 +308,7 @@ class GTEST_API_ AssertionResult { return *this; } - // Returns true if the assertion succeeded. + // Returns true if and only if the assertion succeeded. operator bool() const { return success_; } // NOLINT // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. @@ -432,16 +432,16 @@ class GTEST_API_ Test { static void SetUpTestCase() {} #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - // Returns true if the current test has a fatal failure. + // Returns true if and only if the current test has a fatal failure. static bool HasFatalFailure(); - // Returns true if the current test has a non-fatal failure. + // Returns true if and only if the current test has a non-fatal failure. static bool HasNonfatalFailure(); - // Returns true if the current test was skipped. + // Returns true if and only if the current test was skipped. static bool IsSkipped(); - // Returns true if the current test has a (either fatal or + // Returns true if and only if the current test has a (either fatal or // non-fatal) failure. static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } @@ -472,8 +472,8 @@ class GTEST_API_ Test { virtual void TearDown(); private: - // Returns true if the current test has the same fixture class as - // the first test in the current test suite. + // Returns true if and only if the current test has the same fixture class + // as the first test in the current test suite. static bool HasSameFixtureClass(); // Runs the test after the test fixture has been set up. @@ -574,19 +574,19 @@ class GTEST_API_ TestResult { // Returns the number of the test properties. int test_property_count() const; - // Returns true if the test passed (i.e. no test part failed). + // Returns true if and only if the test passed (i.e. no test part failed). bool Passed() const { return !Skipped() && !Failed(); } - // Returns true if the test was skipped. + // Returns true if and only if the test was skipped. bool Skipped() const; - // Returns true if the test failed. + // Returns true if and only if the test failed. bool Failed() const; - // Returns true if the test fatally failed. + // Returns true if and only if the test fatally failed. bool HasFatalFailure() const; - // Returns true if the test has a non-fatal failure. + // Returns true if and only if the test has a non-fatal failure. bool HasNonfatalFailure() const; // Returns the elapsed time, in milliseconds. @@ -750,7 +750,7 @@ class GTEST_API_ TestInfo { // contains the character 'A' or starts with "Foo.". bool should_run() const { return should_run_; } - // Returns true if this test will appear in the XML report. + // Returns true if and only if this test will appear in the XML report. bool is_reportable() const { // The XML report includes tests matching the filter, excluding those // run in other shards. @@ -808,12 +808,12 @@ class GTEST_API_ TestInfo { // value-parameterized test. const std::unique_ptr<const ::std::string> value_param_; internal::CodeLocation location_; - const internal::TypeId fixture_class_id_; // ID of the test fixture class - bool should_run_; // True if this test should run - bool is_disabled_; // True if this test is disabled - bool matches_filter_; // True if this test matches the - // user-specified filter. - bool is_in_another_shard_; // Will be run in another shard. + const internal::TypeId fixture_class_id_; // ID of the test fixture class + bool should_run_; // True if and only if this test should run + bool is_disabled_; // True if and only if this test is disabled + bool matches_filter_; // True if this test matches the + // user-specified filter. + bool is_in_another_shard_; // Will be run in another shard. internal::TestFactoryBase* const factory_; // The factory that creates // the test object @@ -885,10 +885,10 @@ class GTEST_API_ TestSuite { // Gets the number of all tests in this test suite. int total_test_count() const; - // Returns true if the test suite passed. + // Returns true if and only if the test suite passed. bool Passed() const { return !Failed(); } - // Returns true if the test suite failed. + // Returns true if and only if the test suite failed. bool Failed() const { return failed_test_count() > 0; } // Returns the elapsed time, in milliseconds. @@ -956,33 +956,33 @@ class GTEST_API_ TestSuite { } } - // Returns true if test passed. + // Returns true if and only if test passed. static bool TestPassed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Passed(); } - // Returns true if test skipped. + // Returns true if and only if test skipped. static bool TestSkipped(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Skipped(); } - // Returns true if test failed. + // Returns true if and only if test failed. static bool TestFailed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Failed(); } - // Returns true if the test is disabled and will be reported in the XML - // report. + // Returns true if and only if the test is disabled and will be reported in + // the XML report. static bool TestReportableDisabled(const TestInfo* test_info) { return test_info->is_reportable() && test_info->is_disabled_; } - // Returns true if test is disabled. + // Returns true if and only if test is disabled. static bool TestDisabled(const TestInfo* test_info) { return test_info->is_disabled_; } - // Returns true if this test will appear in the XML report. + // Returns true if and only if this test will appear in the XML report. static bool TestReportable(const TestInfo* test_info) { return test_info->is_reportable(); } @@ -1014,7 +1014,7 @@ class GTEST_API_ TestSuite { internal::SetUpTestSuiteFunc set_up_tc_; // Pointer to the function that tears down the test suite. internal::TearDownTestSuiteFunc tear_down_tc_; - // True if any test in this test suite should run. + // True if and only if any test in this test suite should run. bool should_run_; // The start time, in milliseconds since UNIX Epoch. TimeInMillis start_timestamp_; @@ -1349,11 +1349,12 @@ class GTEST_API_ UnitTest { // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const; - // Returns true if the unit test passed (i.e. all test suites passed). + // Returns true if and only if the unit test passed (i.e. all test suites + // passed). bool Passed() const; - // Returns true if the unit test failed (i.e. some test suite failed - // or something outside of all tests failed). + // Returns true if and only if the unit test failed (i.e. some test suite + // failed or something outside of all tests failed). bool Failed() const; // Gets the i-th test suite among all the test suites. i can range from 0 to @@ -2265,10 +2266,9 @@ class GTEST_API_ ScopedTrace { ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ __FILE__, __LINE__, (message)) - // Compile-time assertion for type equality. -// StaticAssertTypeEq<type1, type2>() compiles if type1 and type2 are -// the same type. The value it returns is not interesting. +// StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2 +// are the same type. The value it returns is not interesting. // // Instead of making StaticAssertTypeEq a class template, we make it a // function template that invokes a helper class template. This @@ -2297,8 +2297,8 @@ class GTEST_API_ ScopedTrace { // // to cause a compiler error. template <typename T1, typename T2> -bool StaticAssertTypeEq() { - (void)internal::StaticAssertTypeEqHelper<T1, T2>(); +constexpr bool StaticAssertTypeEq() noexcept { + static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type"); return true; } diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h index 5d21bbc5..c11b1015 100644 --- a/googletest/include/gtest/internal/gtest-filepath.h +++ b/googletest/include/gtest/internal/gtest-filepath.h @@ -110,7 +110,7 @@ class GTEST_API_ FilePath { const FilePath& base_name, const char* extension); - // Returns true if the path is "". + // Returns true if and only if the path is "". bool IsEmpty() const { return pathname_.empty(); } // If input name has a trailing separator character, removes it and returns diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index 37daf214..ebfe3c9d 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -189,7 +189,7 @@ GTEST_API_ std::string DiffStrings(const std::string& left, // expected_value: "5" // actual_value: "6" // -// The ignoring_case parameter is true if the assertion is a +// The ignoring_case parameter is true if and only if the assertion is a // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will // be inserted into the message. GTEST_API_ AssertionResult EqFailure(const char* expected_expression, @@ -318,15 +318,15 @@ class FloatingPoint { // Returns the sign bit of this number. Bits sign_bit() const { return kSignBitMask & u_.bits_; } - // Returns true if this is NAN (not a number). + // Returns true if and only if this is NAN (not a number). bool is_nan() const { // It's a NAN if the exponent bits are all ones and the fraction // bits are not entirely zeros. return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); } - // Returns true if this number is at most kMaxUlps ULP's away from - // rhs. In particular, this function: + // Returns true if and only if this number is at most kMaxUlps ULP's away + // from rhs. In particular, this function: // // - returns false if either number is (or both are) NAN. // - treats really large numbers as almost equal to infinity. @@ -847,39 +847,16 @@ class GTEST_API_ Random { GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); }; -// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a -// compiler error if T1 and T2 are different types. -template <typename T1, typename T2> -struct CompileAssertTypesEqual; - -template <typename T> -struct CompileAssertTypesEqual<T, T> { -}; - -// Removes the reference from a type if it is a reference type, -// otherwise leaves it unchanged. This is the same as -// tr1::remove_reference, which is not widely available yet. -template <typename T> -struct RemoveReference { typedef T type; }; // NOLINT -template <typename T> -struct RemoveReference<T&> { typedef T type; }; // NOLINT - -// A handy wrapper around RemoveReference that works when the argument -// T depends on template parameters. -#define GTEST_REMOVE_REFERENCE_(T) \ - typename ::testing::internal::RemoveReference<T>::type - // Turns const U&, U&, const U, and U all into U. #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ - typename std::remove_const<GTEST_REMOVE_REFERENCE_(T)>::type + typename std::remove_const<typename std::remove_reference<T>::type>::type // IsAProtocolMessage<T>::value is a compile-time bool constant that's -// true if T is type proto2::Message or a subclass of it. +// true if and only if T is type proto2::Message or a subclass of it. template <typename T> struct IsAProtocolMessage : public bool_constant< - std::is_convertible<const T*, const ::proto2::Message*>::value> { -}; + std::is_convertible<const T*, const ::proto2::Message*>::value> {}; // When the compiler sees expression IsContainerTest<C>(0), if C is an // STL-style container class, the first overload of IsContainerTest @@ -1092,10 +1069,9 @@ class NativeArray { } private: - enum { - kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper< - Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value - }; + static_assert(!std::is_const<Element>::value, "Type must not be const"); + static_assert(!std::is_reference<Element>::value, + "Type must not be a reference"); // Initializes this object with a copy of the input. void InitCopy(const Element* array, size_t a_size) { @@ -1148,25 +1124,29 @@ struct MakeIndexSequence template <> struct MakeIndexSequence<0> : IndexSequence<> {}; -// FIXME: This implementation of ElemFromList is O(1) in instantiation depth, -// but it is O(N^2) in total instantiations. Not sure if this is the best -// tradeoff, as it will make it somewhat slow to compile. -template <typename T, size_t, size_t> -struct ElemFromListImpl {}; - -template <typename T, size_t I> -struct ElemFromListImpl<T, I, I> { - using type = T; +template <size_t> +struct Ignore { + Ignore(...); // NOLINT }; -// Get the Nth element from T... -// It uses O(1) instantiation depth. -template <size_t N, typename I, typename... T> -struct ElemFromList; +template <typename> +struct ElemFromListImpl; +template <size_t... I> +struct ElemFromListImpl<IndexSequence<I...>> { + // We make Ignore a template to solve a problem with MSVC. + // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but + // MSVC doesn't understand how to deal with that pack expansion. + // Use `0 * I` to have a single instantiation of Ignore. + template <typename R> + static R Apply(Ignore<0 * I>..., R (*)(), ...); +}; -template <size_t N, size_t... I, typename... T> -struct ElemFromList<N, IndexSequence<I...>, T...> - : ElemFromListImpl<T, N, I>... {}; +template <size_t N, typename... T> +struct ElemFromList { + using type = + decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply( + static_cast<T (*)()>(nullptr)...)); +}; template <typename... T> class FlatTuple; @@ -1176,9 +1156,7 @@ struct FlatTupleElemBase; template <typename... T, size_t I> struct FlatTupleElemBase<FlatTuple<T...>, I> { - using value_type = - typename ElemFromList<I, typename MakeIndexSequence<sizeof...(T)>::type, - T...>::type; + using value_type = typename ElemFromList<I, T...>::type; FlatTupleElemBase() = default; explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {} value_type value; @@ -1216,12 +1194,12 @@ class FlatTuple explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {} template <size_t I> - const typename ElemFromList<I, Indices, T...>::type& Get() const { + const typename ElemFromList<I, T...>::type& Get() const { return static_cast<const FlatTupleElemBase<FlatTuple, I>*>(this)->value; } template <size_t I> - typename ElemFromList<I, Indices, T...>::type& Get() { + typename ElemFromList<I, T...>::type& Get() { return static_cast<FlatTupleElemBase<FlatTuple, I>*>(this)->value; } }; @@ -1372,13 +1350,17 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; } // Helper macro for defining tests. #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \ + static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ + "test_suite_name must not be empty"); \ + static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \ + "test_name must not be empty"); \ class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ : public parent_class { \ public: \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ \ private: \ - virtual void TestBody(); \ + void TestBody() override; \ static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ test_name)); \ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index a637602c..f6433c58 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -202,11 +202,6 @@ // Mutex, MutexLock, ThreadLocal, GetThreadCount() // - synchronization primitives. // -// Template meta programming: -// IteratorTraits - partial implementation of std::iterator_traits, which -// is not available in libCstd when compiled with Sun C++. -// -// // Regular expressions: // RE - a simple regular expression class using the POSIX // Extended Regular Expression syntax on UNIX-like platforms @@ -362,7 +357,8 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; # include <android/api-level.h> // NOLINT #endif -// Defines this to true if Google Test can use POSIX regular expressions. +// Defines this to true if and only if Google Test can use POSIX regular +// expressions. #ifndef GTEST_HAS_POSIX_RE # if GTEST_OS_LINUX_ANDROID // On Android, <regex.h> is only available starting with Gingerbread. @@ -403,7 +399,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. # if defined(_MSC_VER) && defined(_CPPUNWIND) -// MSVC defines _CPPUNWIND to 1 if exceptions are enabled. +// MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__BORLANDC__) // C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS @@ -414,16 +410,17 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; # endif // _HAS_EXCEPTIONS # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS # elif defined(__clang__) -// clang defines __EXCEPTIONS if exceptions are enabled before clang 220714, -// but if cleanups are enabled after that. In Obj-C++ files, there can be -// cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions -// are disabled. clang has __has_feature(cxx_exceptions) which checks for C++ -// exceptions starting at clang r206352, but which checked for cleanups prior to -// that. To reliably check for C++ exception availability with clang, check for +// clang defines __EXCEPTIONS if and only if exceptions are enabled before clang +// 220714, but if and only if cleanups are enabled after that. In Obj-C++ files, +// there can be cleanups for ObjC exceptions which also need cleanups, even if +// C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which +// checks for C++ exceptions starting at clang r206352, but which checked for +// cleanups prior to that. To reliably check for C++ exception availability with +// clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) # elif defined(__GNUC__) && __EXCEPTIONS -// gcc defines __EXCEPTIONS to 1 if exceptions are enabled. +// gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of @@ -431,7 +428,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // they are enabled unless the user tells us otherwise. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__IBMCPP__) && __EXCEPTIONS -// xlC defines __EXCEPTIONS to 1 if exceptions are enabled. +// xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to @@ -444,15 +441,6 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; # endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS -#if !defined(GTEST_HAS_STD_STRING) -// Even though we don't use this macro any longer, we keep it in case -// some clients still depend on it. -# define GTEST_HAS_STD_STRING 1 -#elif !GTEST_HAS_STD_STRING -// The user told us that ::std::string isn't available. -# error "::std::string isn't available." -#endif // !defined(GTEST_HAS_STD_STRING) - #ifndef GTEST_HAS_STD_WSTRING // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. @@ -472,13 +460,14 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; # ifdef _MSC_VER -# ifdef _CPPRTTI // MSVC defines this macro if RTTI is enabled. +#ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled. # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif -// Starting with version 4.3.2, gcc defines __GXX_RTTI if RTTI is enabled. +// Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is +// enabled. # elif defined(__GNUC__) # ifdef __GXX_RTTI @@ -858,17 +847,6 @@ class Secret; // expression is false, compiler will issue an error containing this identifier. #define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) -// StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. -// -// This template is declared, but intentionally undefined. -template <typename T1, typename T2> -struct StaticAssertTypeEqHelper; - -template <typename T> -struct StaticAssertTypeEqHelper<T, T> { - enum { value = true }; -}; - // Evaluates to the number of elements in 'array'. #define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) @@ -899,9 +877,9 @@ class GTEST_API_ RE { // Returns the string representation of the regex. const char* pattern() const { return pattern_; } - // FullMatch(str, re) returns true if regular expression re matches - // the entire str. - // PartialMatch(str, re) returns true if regular expression re + // FullMatch(str, re) returns true if and only if regular expression re + // matches the entire str. + // PartialMatch(str, re) returns true if and only if regular expression re // matches a substring of str (including str itself). static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); @@ -1243,7 +1221,8 @@ class GTEST_API_ AutoHandle { void Reset(Handle handle); private: - // Returns true if the handle is a valid handle object that can be closed. + // Returns true if and only if the handle is a valid handle object that can be + // closed. bool IsCloseable() const; Handle handle_; @@ -1345,7 +1324,8 @@ class ThreadWithParam : public ThreadWithParamBase { // When non-NULL, used to block execution until the controller thread // notifies. Notification* const thread_can_start_; - bool finished_; // true if we know that the thread function has finished. + bool finished_; // true if and only if we know that the thread function has + // finished. pthread_t thread_; // The native thread object. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); @@ -1819,7 +1799,7 @@ class GTEST_API_ ThreadLocal { class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} - virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } + ValueHolder* MakeNewHolder() const override { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); @@ -1828,7 +1808,7 @@ class GTEST_API_ ThreadLocal { class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} - virtual ValueHolder* MakeNewHolder() const { + ValueHolder* MakeNewHolder() const override { return new ValueHolder(value_); } @@ -1901,22 +1881,6 @@ GTEST_API_ size_t GetThreadCount(); template <bool B> using bool_constant = std::integral_constant<bool, B>; -template <typename Iterator> -struct IteratorTraits { - typedef typename Iterator::value_type value_type; -}; - - -template <typename T> -struct IteratorTraits<T*> { - typedef T value_type; -}; - -template <typename T> -struct IteratorTraits<const T*> { - typedef T value_type; -}; - #if GTEST_OS_WINDOWS # define GTEST_PATH_SEP_ "\\" # define GTEST_HAS_ALT_PATH_SEP_ 1 diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 26d8407f..82aaa63b 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -94,7 +94,8 @@ class GTEST_API_ String { static const char* Utf16ToAnsi(LPCWSTR utf16_str); #endif - // Compares two C strings. Returns true if they have the same content. + // Compares two C strings. Returns true if and only if they have the same + // content. // // Unlike strcmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, @@ -107,16 +108,16 @@ class GTEST_API_ String { // returned. static std::string ShowWideCString(const wchar_t* wide_c_str); - // Compares two wide C strings. Returns true if they have the same - // content. + // Compares two wide C strings. Returns true if and only if they have the + // same content. // // Unlike wcscmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); - // Compares two C strings, ignoring case. Returns true if they - // have the same content. + // Compares two C strings, ignoring case. Returns true if and only if + // they have the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL C string, @@ -124,8 +125,8 @@ class GTEST_API_ String { static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs); - // Compares two wide C strings, ignoring case. Returns true if they - // have the same content. + // Compares two wide C strings, ignoring case. Returns true if and only if + // they have the same content. // // Unlike wcscasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL wide C string, @@ -139,8 +140,8 @@ class GTEST_API_ String { static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); - // Returns true if the given string ends with the given suffix, ignoring - // case. Any string is considered to end with an empty suffix. + // Returns true if and only if the given string ends with the given suffix, + // ignoring case. Any string is considered to end with an empty suffix. static bool EndsWithCaseInsensitive( const std::string& str, const std::string& suffix); diff --git a/googletest/samples/prime_tables.h b/googletest/samples/prime_tables.h index 4178e70c..72539bf1 100644 --- a/googletest/samples/prime_tables.h +++ b/googletest/samples/prime_tables.h @@ -43,7 +43,7 @@ class PrimeTable { public: virtual ~PrimeTable() {} - // Returns true if n is a prime number. + // Returns true if and only if n is a prime number. virtual bool IsPrime(int n) const = 0; // Returns the smallest prime number greater than p; or returns -1 diff --git a/googletest/samples/sample1.cc b/googletest/samples/sample1.cc index 58dbf170..1d427597 100644 --- a/googletest/samples/sample1.cc +++ b/googletest/samples/sample1.cc @@ -41,7 +41,7 @@ int Factorial(int n) { return result; } -// Returns true if n is a prime number. +// Returns true if and only if n is a prime number. bool IsPrime(int n) { // Trivial case 1: small numbers if (n <= 1) return false; diff --git a/googletest/samples/sample1.h b/googletest/samples/sample1.h index a90eae43..12e49dea 100644 --- a/googletest/samples/sample1.h +++ b/googletest/samples/sample1.h @@ -35,7 +35,7 @@ // Returns n! (the factorial of n). For negative n, n! is defined to be 1. int Factorial(int n); -// Returns true if n is a prime number. +// Returns true if and only if n is a prime number. bool IsPrime(int n); #endif // GTEST_SAMPLES_SAMPLE1_H_ diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index e5ec287d..da09a1cf 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -122,8 +122,8 @@ GTEST_DEFINE_string_( "Indicates the file, line number, temporal index of " "the single death test to run, and a file descriptor to " "which a success code may be sent, all separated by " - "the '|' characters. This flag is specified if and only if the current " - "process is a sub-process launched for running a thread-safe " + "the '|' characters. This flag is specified if and only if the " + "current process is a sub-process launched for running a thread-safe " "death test. FOR INTERNAL USE ONLY."); } // namespace internal @@ -563,8 +563,8 @@ static ::std::string FormatDeathTestOutput(const ::std::string& output) { // status_ok: true if exit_status is acceptable in the context of // this particular death test, which fails if it is false // -// Returns true if all of the above conditions are met. Otherwise, the -// first failing condition, in the order given above, is the one that is +// Returns true if and only if all of the above conditions are met. Otherwise, +// the first failing condition, in the order given above, is the one that is // reported. Also sets the last death test message string. bool DeathTestImpl::Passed(bool status_ok) { if (!spawned()) diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc index 322fbb1b..bd7b99ff 100644 --- a/googletest/src/gtest-filepath.cc +++ b/googletest/src/gtest-filepath.cc @@ -93,8 +93,8 @@ static bool IsPathSeparator(char c) { // Returns the current working directory, or "" if unsuccessful. FilePath FilePath::GetCurrentDir() { #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ - GTEST_OS_WINDOWS_RT || ARDUINO - // Windows CE and Arduino don't have a current directory, so we just return + GTEST_OS_WINDOWS_RT || ARDUINO || defined(ESP_PLATFORM) + // These platforms do not have a current directory, so we just return // something reasonable. return FilePath(kCurrentDirectoryString); #elif GTEST_OS_WINDOWS diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index e29d9927..8ed70daa 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -99,14 +99,14 @@ const char kFlagfileFlag[] = "flagfile"; // A valid random seed must be in [1, kMaxRandomSeed]. const int kMaxRandomSeed = 99999; -// g_help_flag is true if the --help flag or an equivalent form is -// specified on the command line. +// g_help_flag is true if and only if the --help flag or an equivalent form +// is specified on the command line. GTEST_API_ extern bool g_help_flag; // Returns the current time in milliseconds. GTEST_API_ TimeInMillis GetTimeInMillis(); -// Returns true if Google Test should use colors in the output. +// Returns true if and only if Google Test should use colors in the output. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); // Formats the given time in milliseconds as seconds. @@ -266,8 +266,8 @@ GTEST_API_ bool ShouldShard(const char* total_shards_str, GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); // Given the total number of shards, the shard index, and the test id, -// returns true if the test should be run on this shard. The test id is -// some arbitrary but unique non-negative integer assigned to each test +// returns true if and only if the test should be run on this shard. The test id +// is some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. GTEST_API_ bool ShouldRunTestOnShard( int total_shards, int shard_index, int test_id); @@ -352,7 +352,7 @@ class TestPropertyKeyIs { // TestPropertyKeyIs has NO default constructor. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} - // Returns true if the test name of test property matches on key_. + // Returns true if and only if the test name of test property matches on key_. bool operator()(const TestProperty& test_property) const { return test_property.key() == key_; } @@ -385,15 +385,15 @@ class GTEST_API_ UnitTestOptions { // Functions for processing the gtest_filter flag. - // Returns true if the wildcard pattern matches the string. The - // first ':' or '\0' character in pattern marks the end of it. + // Returns true if and only if the wildcard pattern matches the string. + // The first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. static bool PatternMatchesString(const char *pattern, const char *str); - // Returns true if the user-specified filter matches the test suite - // name and the test name. + // Returns true if and only if the user-specified filter matches the test + // suite name and the test name. static bool FilterMatchesTest(const std::string& test_suite_name, const std::string& test_name); @@ -577,11 +577,12 @@ class GTEST_API_ UnitTestImpl { // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } - // Returns true if the unit test passed (i.e. all test suites passed). + // Returns true if and only if the unit test passed (i.e. all test suites + // passed). bool Passed() const { return !Failed(); } - // Returns true if the unit test failed (i.e. some test suite failed - // or something outside of all tests failed). + // Returns true if and only if the unit test failed (i.e. some test suite + // failed or something outside of all tests failed). bool Failed() const { return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed(); } @@ -911,7 +912,7 @@ class GTEST_API_ UnitTestImpl { // desired. OsStackTraceGetterInterface* os_stack_trace_getter_; - // True if PostFlagParsingInit() has been called. + // True if and only if PostFlagParsingInit() has been called. bool post_flag_parse_init_performed_; // The random number seed used at the beginning of the test run. diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index 9024f030..fc5ba6be 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -715,7 +715,7 @@ RE::~RE() { free(const_cast<char*>(pattern_)); } -// Returns true if regular expression re matches the entire str. +// Returns true if and only if regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; @@ -723,8 +723,8 @@ bool RE::FullMatch(const char* str, const RE& re) { return regexec(&re.full_regex_, str, 1, &match, 0) == 0; } -// Returns true if regular expression re matches a substring of str -// (including str itself). +// Returns true if and only if regular expression re matches a substring of +// str (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; @@ -764,14 +764,14 @@ void RE::Init(const char* regex) { #elif GTEST_USES_SIMPLE_RE -// Returns true if ch appears anywhere in str (excluding the +// Returns true if and only if ch appears anywhere in str (excluding the // terminating '\0' character). bool IsInSet(char ch, const char* str) { return ch != '\0' && strchr(str, ch) != nullptr; } -// Returns true if ch belongs to the given classification. Unlike -// similar functions in <ctype.h>, these aren't affected by the +// Returns true if and only if ch belongs to the given classification. +// Unlike similar functions in <ctype.h>, these aren't affected by the // current locale. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } bool IsAsciiPunct(char ch) { @@ -784,13 +784,13 @@ bool IsAsciiWordChar(char ch) { ('0' <= ch && ch <= '9') || ch == '_'; } -// Returns true if "\\c" is a supported escape sequence. +// Returns true if and only if "\\c" is a supported escape sequence. bool IsValidEscape(char c) { return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); } -// Returns true if the given atom (specified by escaped and pattern) -// matches ch. The result is undefined if the atom is invalid. +// Returns true if and only if the given atom (specified by escaped and +// pattern) matches ch. The result is undefined if the atom is invalid. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { if (escaped) { // "\\p" where p is pattern_char. switch (pattern_char) { @@ -828,7 +828,7 @@ bool ValidateRegex(const char* regex) { bool is_valid = true; - // True if ?, *, or + can follow the previous atom. + // True if and only if ?, *, or + can follow the previous atom. bool prev_repeatable = false; for (int i = 0; regex[i]; i++) { if (regex[i] == '\\') { // An escape sequence @@ -904,8 +904,8 @@ bool MatchRepetitionAndRegexAtHead( return false; } -// Returns true if regex matches a prefix of str. regex must be a -// valid simple regular expression and not start with "^", or the +// Returns true if and only if regex matches a prefix of str. regex must +// be a valid simple regular expression and not start with "^", or the // result is undefined. bool MatchRegexAtHead(const char* regex, const char* str) { if (*regex == '\0') // An empty regex matches a prefix of anything. @@ -935,8 +935,8 @@ bool MatchRegexAtHead(const char* regex, const char* str) { } } -// Returns true if regex matches any substring of str. regex must be -// a valid simple regular expression, or the result is undefined. +// Returns true if and only if regex matches any substring of str. regex must +// be a valid simple regular expression, or the result is undefined. // // The algorithm is recursive, but the recursion depth doesn't exceed // the regex length, so we won't need to worry about running out of @@ -964,13 +964,13 @@ RE::~RE() { free(const_cast<char*>(full_pattern_)); } -// Returns true if regular expression re matches the entire str. +// Returns true if and only if regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); } -// Returns true if regular expression re matches a substring of str -// (including str itself). +// Returns true if and only if regular expression re matches a substring of +// str (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); } @@ -1102,13 +1102,10 @@ class CapturedStream { // code as part of a regular standalone executable, which doesn't // run in a Dalvik process (e.g. when running it through 'adb shell'). // - // The location /sdcard is directly accessible from native code - // and is the only location (unofficially) supported by the Android - // team. It's generally a symlink to the real SD Card mount point - // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or - // other OEM-customized locations. Never rely on these, and always - // use /sdcard. - char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; + // 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. + char name_template[] = "/data/local/tmp/gtest_captured_stream.XXXXXX"; # else char name_template[] = "/tmp/captured_stream.XXXXXX"; # endif // GTEST_OS_LINUX_ANDROID @@ -1330,7 +1327,7 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value) { // Reads and returns the Boolean environment variable corresponding to // the given flag; if it's not set, returns default_value. // -// The value is considered true if it's not "0". +// The value is considered true if and only if it's not "0". bool BoolFromGTestEnv(const char* flag, bool default_value) { #if defined(GTEST_GET_BOOL_FROM_ENV_) return GTEST_GET_BOOL_FROM_ENV_(flag, default_value); diff --git a/googletest/src/gtest-test-part.cc b/googletest/src/gtest-test-part.cc index 178317a6..a938683c 100644 --- a/googletest/src/gtest-test-part.cc +++ b/googletest/src/gtest-test-part.cc @@ -31,6 +31,8 @@ // The Google C++ Testing and Mocking Framework (Google Test) #include "gtest/gtest-test-part.h" + +#include "gtest/internal/gtest-port.h" #include "src/gtest-internal-inl.h" namespace testing { @@ -46,7 +48,9 @@ std::string TestPartResult::ExtractSummary(const char* message) { // Prints a TestPartResult object. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { - return os << result.file_name() << ":" << result.line_number() << ": " + return os << internal::FormatFileLocation(result.file_name(), + result.line_number()) + << " " << (result.type() == TestPartResult::kSuccess ? "Success" : result.type() == TestPartResult::kSkip diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index cbd48d31..a5b4e5ac 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -177,8 +177,8 @@ namespace internal { // stack trace. const char kStackTraceMarker[] = "\nStack trace:\n"; -// g_help_flag is true if the --help flag or an equivalent form is -// specified on the command line. +// g_help_flag is true if and only if the --help flag or an equivalent form +// is specified on the command line. bool g_help_flag = false; // Utilty function to Open File for Writing @@ -215,15 +215,14 @@ GTEST_DEFINE_bool_( "Run disabled tests too, in addition to the tests normally being run."); GTEST_DEFINE_bool_( - break_on_failure, - internal::BoolFromGTestEnv("break_on_failure", false), - "True if a failed assertion should be a debugger break-point."); + break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false), + "True if and only if a failed assertion should be a debugger " + "break-point."); -GTEST_DEFINE_bool_( - catch_exceptions, - internal::BoolFromGTestEnv("catch_exceptions", true), - "True if " GTEST_NAME_ - " should catch exceptions and treat them as test failures."); +GTEST_DEFINE_bool_(catch_exceptions, + internal::BoolFromGTestEnv("catch_exceptions", true), + "True if and only if " GTEST_NAME_ + " should catch exceptions and treat them as test failures."); GTEST_DEFINE_string_( color, @@ -270,17 +269,13 @@ GTEST_DEFINE_string_( "executable's name and, if necessary, made unique by adding " "digits."); -GTEST_DEFINE_bool_( - print_time, - internal::BoolFromGTestEnv("print_time", true), - "True if " GTEST_NAME_ - " should display elapsed time in text output."); +GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true), + "True if and only if " GTEST_NAME_ + " should display elapsed time in text output."); -GTEST_DEFINE_bool_( - print_utf8, - internal::BoolFromGTestEnv("print_utf8", true), - "True if " GTEST_NAME_ - " prints UTF8 characters as text."); +GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true), + "True if and only if " GTEST_NAME_ + " prints UTF8 characters as text."); GTEST_DEFINE_int32_( random_seed, @@ -294,16 +289,14 @@ GTEST_DEFINE_int32_( "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); -GTEST_DEFINE_bool_( - show_internal_stack_frames, false, - "True if " GTEST_NAME_ " should include internal stack frames when " - "printing test failure stack traces."); +GTEST_DEFINE_bool_(show_internal_stack_frames, false, + "True if and only if " GTEST_NAME_ + " should include internal stack frames when " + "printing test failure stack traces."); -GTEST_DEFINE_bool_( - shuffle, - internal::BoolFromGTestEnv("shuffle", false), - "True if " GTEST_NAME_ - " should randomize tests' order on every run."); +GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false), + "True if and only if " GTEST_NAME_ + " should randomize tests' order on every run."); GTEST_DEFINE_int32_( stack_trace_depth, @@ -354,7 +347,7 @@ UInt32 Random::Generate(UInt32 range) { return state_ % range; } -// GTestIsInitialized() returns true if the user has initialized +// GTestIsInitialized() returns true if and only if the user has initialized // Google Test. Useful for catching the user mistake of not initializing // Google Test before calling RUN_ALL_TESTS(). static bool GTestIsInitialized() { return GetArgvs().size() > 0; } @@ -371,18 +364,18 @@ static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list, return sum; } -// Returns true if the test suite passed. +// Returns true if and only if the test suite passed. static bool TestSuitePassed(const TestSuite* test_suite) { return test_suite->should_run() && test_suite->Passed(); } -// Returns true if the test suite failed. +// Returns true if and only if the test suite failed. static bool TestSuiteFailed(const TestSuite* test_suite) { return test_suite->should_run() && test_suite->Failed(); } -// Returns true if test_suite contains at least one test that should -// run. +// Returns true if and only if test_suite contains at least one test that +// should run. static bool ShouldRunTestSuite(const TestSuite* test_suite) { return test_suite->should_run(); } @@ -482,8 +475,8 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { return result.string(); } -// Returns true if the wildcard pattern matches the string. The -// first ':' or '\0' character in pattern marks the end of it. +// Returns true if and only if the wildcard pattern matches the string. +// The first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. @@ -525,8 +518,8 @@ bool UnitTestOptions::MatchesFilter( } } -// Returns true if the user-specified filter matches the test suite -// name and the test name. +// Returns true if and only if the user-specified filter matches the test +// suite name and the test name. bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, const std::string& test_name) { const std::string& full_name = test_suite_name + "." + test_name.c_str(); @@ -910,7 +903,8 @@ const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { #endif // GTEST_OS_WINDOWS_MOBILE -// Compares two C strings. Returns true if they have the same content. +// Compares two C strings. Returns true if and only if they have the same +// content. // // Unlike strcmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, @@ -1320,7 +1314,7 @@ std::vector<std::string> SplitEscapedString(const std::string& str) { // lhs_value: "5" // rhs_value: "6" // -// The ignoring_case parameter is true if the assertion is a +// The ignoring_case parameter is true if and only if the assertion is a // *_STRCASEEQ*. When it's true, the string "Ignoring case" will // be inserted into the message. AssertionResult EqFailure(const char* lhs_expression, @@ -1563,9 +1557,9 @@ namespace { // Helper functions for implementing IsSubString() and IsNotSubstring(). -// This group of overloaded functions return true if needle is a -// substring of haystack. NULL is considered a substring of itself -// only. +// This group of overloaded functions return true if and only if needle +// is a substring of haystack. NULL is considered a substring of +// itself only. bool IsSubstringPred(const char* needle, const char* haystack) { if (needle == nullptr || haystack == nullptr) return needle == haystack; @@ -1865,8 +1859,8 @@ std::string String::ShowWideCString(const wchar_t * wide_c_str) { return internal::WideStringToUtf8(wide_c_str, -1); } -// Compares two wide C strings. Returns true if they have the same -// content. +// Compares two wide C strings. Returns true if and only if they have the +// same content. // // Unlike wcscmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, @@ -1910,7 +1904,7 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, << " vs " << PrintToString(s2); } -// Compares two C strings, ignoring case. Returns true if they have +// Compares two C strings, ignoring case. Returns true if and only if they have // the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). A @@ -1922,18 +1916,18 @@ bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { return posix::StrCaseCmp(lhs, rhs) == 0; } - // Compares two wide C strings, ignoring case. Returns true if they - // have the same content. - // - // Unlike wcscasecmp(), this function can handle NULL argument(s). - // A NULL C string is considered different to any non-NULL wide C string, - // including the empty string. - // NB: The implementations on different platforms slightly differ. - // On windows, this method uses _wcsicmp which compares according to LC_CTYPE - // environment variable. On GNU platform this method uses wcscasecmp - // which compares according to LC_CTYPE category of the current locale. - // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the - // current locale. +// Compares two wide C strings, ignoring case. Returns true if and only if they +// have the same content. +// +// Unlike wcscasecmp(), this function can handle NULL argument(s). +// A NULL C string is considered different to any non-NULL wide C string, +// including the empty string. +// NB: The implementations on different platforms slightly differ. +// On windows, this method uses _wcsicmp which compares according to LC_CTYPE +// environment variable. On GNU platform this method uses wcscasecmp +// which compares according to LC_CTYPE category of the current locale. +// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the +// current locale. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == nullptr) return rhs == nullptr; @@ -1956,7 +1950,7 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, #endif // OS selector } -// Returns true if str ends with the given suffix, ignoring case. +// Returns true if and only if str ends with the given suffix, ignoring case. // Any string is considered to end with an empty suffix. bool String::EndsWithCaseInsensitive( const std::string& str, const std::string& suffix) { @@ -2198,12 +2192,12 @@ static bool TestPartSkipped(const TestPartResult& result) { return result.skipped(); } -// Returns true if the test was skipped. +// Returns true if and only if the test was skipped. bool TestResult::Skipped() const { return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0; } -// Returns true if the test failed. +// Returns true if and only if the test failed. bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { if (GetTestPartResult(i).failed()) @@ -2212,22 +2206,22 @@ bool TestResult::Failed() const { return false; } -// Returns true if the test part fatally failed. +// Returns true if and only if the test part fatally failed. static bool TestPartFatallyFailed(const TestPartResult& result) { return result.fatally_failed(); } -// Returns true if the test fatally failed. +// Returns true if and only if the test fatally failed. bool TestResult::HasFatalFailure() const { return CountIf(test_part_results_, TestPartFatallyFailed) > 0; } -// Returns true if the test part non-fatally failed. +// Returns true if and only if the test part non-fatally failed. static bool TestPartNonfatallyFailed(const TestPartResult& result) { return result.nonfatally_failed(); } -// Returns true if the test has a non-fatal failure. +// Returns true if and only if the test has a non-fatal failure. bool TestResult::HasNonfatalFailure() const { return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; } @@ -2523,18 +2517,18 @@ void Test::Run() { this, &Test::TearDown, "TearDown()"); } -// Returns true if the current test has a fatal failure. +// Returns true if and only if the current test has a fatal failure. bool Test::HasFatalFailure() { return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); } -// Returns true if the current test has a non-fatal failure. +// Returns true if and only if the current test has a non-fatal failure. bool Test::HasNonfatalFailure() { return internal::GetUnitTestImpl()->current_test_result()-> HasNonfatalFailure(); } -// Returns true if the current test was skipped. +// Returns true if and only if the current test was skipped. bool Test::IsSkipped() { return internal::GetUnitTestImpl()->current_test_result()->Skipped(); } @@ -2633,7 +2627,7 @@ class TestNameIs { explicit TestNameIs(const char* name) : name_(name) {} - // Returns true if the test name of test_info matches name_. + // Returns true if and only if the test name of test_info matches name_. bool operator()(const TestInfo * test_info) const { return test_info && test_info->name() == name_; } @@ -2992,7 +2986,7 @@ static const char* GetAnsiColorCode(GTestColor color) { #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE -// Returns true if Google Test should use colors in the output. +// Returns true if and only if Google Test should use colors in the output. bool ShouldUseColor(bool stdout_is_tty) { const char* const gtest_color = GTEST_FLAG(color).c_str(); @@ -3038,7 +3032,7 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_start(args, fmt); #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \ - GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT + GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM) const bool use_color = AlwaysFalse(); #else static const bool in_color_mode = @@ -4709,11 +4703,12 @@ internal::TimeInMillis UnitTest::elapsed_time() const { return impl()->elapsed_time(); } -// Returns true if the unit test passed (i.e. all test suites passed). +// Returns true if and only if the unit test passed (i.e. all test suites +// passed). bool UnitTest::Passed() const { return impl()->Passed(); } -// Returns true if the unit test failed (i.e. some test suite failed -// or something outside of all tests failed). +// Returns true if and only if the unit test failed (i.e. some test suite +// failed or something outside of all tests failed). bool UnitTest::Failed() const { return impl()->Failed(); } // Gets the i-th test suite among all the test suites. i can range from 0 to @@ -5161,7 +5156,7 @@ class TestSuiteNameIs { // Constructor. explicit TestSuiteNameIs(const std::string& name) : name_(name) {} - // Returns true if the name of test_suite matches name_. + // Returns true if and only if the name of test_suite matches name_. bool operator()(const TestSuite* test_suite) const { return test_suite != nullptr && strcmp(test_suite->name(), name_.c_str()) == 0; @@ -5232,7 +5227,8 @@ static void TearDownEnvironment(Environment* env) { env->TearDown(); } // All other functions called from RunAllTests() may safely assume that // parameterized tests are ready to be counted and run. bool UnitTestImpl::RunAllTests() { - // True if Google Test is initialized before RUN_ALL_TESTS() is called. + // True if and only if Google Test is initialized before RUN_ALL_TESTS() is + // called. const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized(); // Do not run any test if the --help flag was specified. @@ -5248,7 +5244,7 @@ bool UnitTestImpl::RunAllTests() { // protocol. internal::WriteToShardStatusFileIfNeeded(); - // True if we are in a subprocess for running a thread-safe-style + // True if and only if we are in a subprocess for running a thread-safe-style // death test. bool in_subprocess_for_death_test = false; @@ -5281,7 +5277,7 @@ bool UnitTestImpl::RunAllTests() { random_seed_ = GTEST_FLAG(shuffle) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; - // True if at least one test has failed. + // True if and only if at least one test has failed. bool failed = false; TestEventListener* repeater = listeners()->repeater(); @@ -5479,8 +5475,8 @@ Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { } // Given the total number of shards, the shard index, and the test id, -// returns true if the test should be run on this shard. The test id is -// some arbitrary but unique non-negative integer assigned to each test +// returns true if and only if the test should be run on this shard. The test id +// is some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { return (test_id % total_shards) == shard_index; @@ -6053,7 +6049,7 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { void ParseGoogleTestFlagsOnly(int* argc, char** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); - // Fix the value of *_NSGetArgc() on macOS, but if + // Fix the value of *_NSGetArgc() on macOS, but if and only if // *_NSGetArgv() == argv // Only applicable to char** version of argv #if GTEST_OS_MAC diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc index 814d7713..cba906cc 100644 --- a/googletest/test/googletest-death-test-test.cc +++ b/googletest/test/googletest-death-test-test.cc @@ -141,7 +141,7 @@ class TestForDeathTest : public testing::Test { DieInside("MemberFunction"); } - // True if MemberFunction() should die. + // True if and only if MemberFunction() should die. bool should_die_; const FilePath original_dir_; }; @@ -158,7 +158,7 @@ class MayDie { } private: - // True if MemberFunction() should die. + // True if and only if MemberFunction() should die. bool should_die_; }; @@ -573,8 +573,8 @@ TEST_F(TestForDeathTest, ErrorMessageMismatch) { }, "died but not with expected error"); } -// On exit, *aborted will be true if the EXPECT_DEATH() statement -// aborted the function. +// On exit, *aborted will be true if and only if the EXPECT_DEATH() +// statement aborted the function. void ExpectDeathTestHelper(bool* aborted) { *aborted = true; EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index 038de921..de777cff 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -966,9 +966,9 @@ Expected equality of these values: Stack trace: (omitted) [0;31m[ FAILED ] [mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -[0;32m[----------] [m1 test from EmptyBasenameParamInst -[0;32m[ RUN ] [mEmptyBasenameParamInst.Passes/0 -[0;32m[ OK ] [mEmptyBasenameParamInst.Passes/0 +[0;32m[----------] [m1 test from All/EmptyBasenameParamInst +[0;32m[ RUN ] [mAll/EmptyBasenameParamInst.Passes/0 +[0;32m[ OK ] [mAll/EmptyBasenameParamInst.Passes/0 [0;32m[----------] [m2 tests from PrintingStrings/ParamTest [0;32m[ RUN ] [mPrintingStrings/ParamTest.Success/a [0;32m[ OK ] [mPrintingStrings/ParamTest.Success/a diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index 4f716d84..8de2bd12 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -102,7 +102,7 @@ class EmptyBasenameParamInst : public testing::TestWithParam<int> {}; TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); } -INSTANTIATE_TEST_SUITE_P(, EmptyBasenameParamInst, testing::Values(1)); +INSTANTIATE_TEST_SUITE_P(All, EmptyBasenameParamInst, testing::Values(1)); static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc index 6c187dff..2740aaab 100644 --- a/googletest/test/googletest-param-test-test.cc +++ b/googletest/test/googletest-param-test-test.cc @@ -37,6 +37,7 @@ # include <algorithm> # include <iostream> # include <list> +# include <set> # include <sstream> # include <string> # include <vector> @@ -802,7 +803,7 @@ TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name()); - EXPECT_STREQ("FooSomeTestName", test_info->name()); + EXPECT_STREQ("FooSomeTestName/0", test_info->name()); } INSTANTIATE_TEST_SUITE_P(FortyTwo, MacroNamingTest, Values(42)); @@ -819,6 +820,36 @@ TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), EXPECT_STREQ("FooSomeTestName", test_info->name()); } +TEST(MacroNameing, LookupNames) { + std::set<std::string> know_suite_names, know_test_names; + + auto ins = testing::UnitTest::GetInstance(); + int ts = 0; + while (const testing::TestSuite* suite = ins->GetTestSuite(ts++)) { + know_suite_names.insert(suite->name()); + + int ti = 0; + while (const testing::TestInfo* info = suite->GetTestInfo(ti++)) { + know_test_names.insert(std::string(suite->name()) + "." + info->name()); + } + } + + // Check that the expected form of the test suit name actualy exists. + EXPECT_NE( // + know_suite_names.find("FortyTwo/MacroNamingTest"), + know_suite_names.end()); + EXPECT_NE( + know_suite_names.find("MacroNamingTestNonParametrized"), + know_suite_names.end()); + // Check that the expected form of the test name actualy exists. + EXPECT_NE( // + know_test_names.find("FortyTwo/MacroNamingTest.FooSomeTestName/0"), + know_test_names.end()); + EXPECT_NE( + know_test_names.find("MacroNamingTestNonParametrized.FooSomeTestName"), + know_test_names.end()); +} + // Tests that user supplied custom parameter names are working correctly. // Runs the test with a builtin helper method which uses PrintToString, // as well as a custom function and custom functor to ensure all possible diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 42035cc9..60d637c3 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -201,24 +201,6 @@ TEST(ImplicitCastTest, CanUseImplicitConstructor) { EXPECT_TRUE(converted); } -TEST(IteratorTraitsTest, WorksForSTLContainerIterators) { - StaticAssertTypeEq<int, - IteratorTraits< ::std::vector<int>::const_iterator>::value_type>(); - StaticAssertTypeEq<bool, - IteratorTraits< ::std::list<bool>::iterator>::value_type>(); -} - -TEST(IteratorTraitsTest, WorksForPointerToNonConst) { - StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>(); - StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>(); -} - -TEST(IteratorTraitsTest, WorksForPointerToConst) { - StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>(); - StaticAssertTypeEq<const void*, - IteratorTraits<const void* const*>::value_type>(); -} - TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { if (AlwaysFalse()) GTEST_CHECK_(false) << "This should never be executed; " diff --git a/googletest/test/googletest-throw-on-failure-test.py b/googletest/test/googletest-throw-on-failure-test.py index a38cd33f..ea627c47 100755 --- a/googletest/test/googletest-throw-on-failure-test.py +++ b/googletest/test/googletest-throw-on-failure-test.py @@ -86,7 +86,7 @@ class ThrowOnFailureTest(gtest_test_utils.TestCase): variable; None if the variable should be unset. flag_value: value of the --gtest_break_on_failure flag; None if the flag should not be present. - should_fail: True if the program is expected to fail. + should_fail: True if and only if the program is expected to fail. """ SetEnvVar(THROW_ON_FAILURE, env_var_value) diff --git a/googletest/test/gtest_environment_test.cc b/googletest/test/gtest_environment_test.cc index 58908e63..064bfc50 100644 --- a/googletest/test/gtest_environment_test.cc +++ b/googletest/test/gtest_environment_test.cc @@ -116,7 +116,7 @@ void Check(bool condition, const char* msg) { } } -// Runs the tests. Return true if successful. +// Runs the tests. Return true if and only if successful. // // The 'failure' parameter specifies the type of failure that should // be generated by the global set-up. diff --git a/googletest/test/gtest_pred_impl_unittest.cc b/googletest/test/gtest_pred_impl_unittest.cc index 4d77896f..1afe5e2d 100644 --- a/googletest/test/gtest_pred_impl_unittest.cc +++ b/googletest/test/gtest_pred_impl_unittest.cc @@ -144,10 +144,10 @@ class Predicate1Test : public testing::Test { } } - // true if the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true if the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; @@ -539,10 +539,10 @@ class Predicate2Test : public testing::Test { } } - // true if the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true if the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; @@ -976,10 +976,10 @@ class Predicate3Test : public testing::Test { } } - // true if the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true if the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; @@ -1455,10 +1455,10 @@ class Predicate4Test : public testing::Test { } } - // true if the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true if the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; @@ -1976,10 +1976,10 @@ class Predicate5Test : public testing::Test { } } - // true if the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true if the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; diff --git a/googletest/test/gtest_premature_exit_test.cc b/googletest/test/gtest_premature_exit_test.cc index 777a8bf8..1d1187ef 100644 --- a/googletest/test/gtest_premature_exit_test.cc +++ b/googletest/test/gtest_premature_exit_test.cc @@ -45,7 +45,7 @@ namespace { class PrematureExitTest : public Test { public: - // Returns true if the given file exists. + // Returns true if and only if the given file exists. static bool FileExists(const char* filepath) { StatStruct stat; return Stat(filepath, &stat) == 0; @@ -61,7 +61,7 @@ class PrematureExitTest : public Test { } } - // Returns true if the premature-exit file exists. + // Returns true if and only if the premature-exit file exists. bool PrematureExitFileExists() const { return FileExists(premature_exit_file_path_); } diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py index abd56eca..ef9363c3 100755 --- a/googletest/test/gtest_test_utils.py +++ b/googletest/test/gtest_test_utils.py @@ -215,10 +215,11 @@ class Subprocess: Returns: An object that represents outcome of the executed process. It has the following attributes: - terminated_by_signal True if the child process has been terminated - by a signal. + terminated_by_signal True if and only if the child process has been + terminated by a signal. signal Sygnal that terminated the child process. - exited True if the child process exited normally. + exited True if and only if the child process exited + normally. exit_code The code with which the child process exited. output Child process's stdout and stderr output combined in a string. diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 5020d732..8312bd10 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -233,7 +233,6 @@ using testing::internal::AppendUserMessage; using testing::internal::ArrayAwareFind; using testing::internal::ArrayEq; using testing::internal::CodePointToUtf8; -using testing::internal::CompileAssertTypesEqual; using testing::internal::CopyArray; using testing::internal::CountIf; using testing::internal::EqFailure; @@ -262,7 +261,6 @@ using testing::internal::OsStackTraceGetterInterface; using testing::internal::ParseInt32Flag; using testing::internal::RelationToSourceCopy; using testing::internal::RelationToSourceReference; -using testing::internal::RemoveReference; using testing::internal::ShouldRunTestOnShard; using testing::internal::ShouldShard; using testing::internal::ShouldUseColor; @@ -2169,12 +2167,12 @@ static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ = // First, some predicates and predicate-formatters needed by the tests. -// Returns true if the argument is an even number. +// Returns true if and only if the argument is an even number. bool IsEven(int n) { return (n % 2) == 0; } -// A functor that returns true if the argument is an even number. +// A functor that returns true if and only if the argument is an even number. struct IsEvenFunctor { bool operator()(int n) { return IsEven(n); } }; @@ -2218,13 +2216,13 @@ struct AssertIsEvenFunctor { } }; -// Returns true if the sum of the arguments is an even number. +// Returns true if and only if the sum of the arguments is an even number. bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); } -// A functor that returns true if the sum of the arguments is an even -// number. +// A functor that returns true if and only if the sum of the arguments is an +// even number. struct SumIsEven3Functor { bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); @@ -5345,7 +5343,7 @@ TEST_P(CodeLocationForTESTP, Verify) { VERIFY_CODE_LOCATION; } -INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0)); +INSTANTIATE_TEST_SUITE_P(All, CodeLocationForTESTP, Values(0)); template <typename T> class CodeLocationForTYPEDTEST : public Test { @@ -7103,42 +7101,12 @@ TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) { EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value); } -// Tests that CompileAssertTypesEqual compiles when the type arguments are -// equal. -TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) { - CompileAssertTypesEqual<void, void>(); - CompileAssertTypesEqual<int*, int*>(); -} - -// Tests that RemoveReference does not affect non-reference types. -TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) { - CompileAssertTypesEqual<int, RemoveReference<int>::type>(); - CompileAssertTypesEqual<const char, RemoveReference<const char>::type>(); -} - -// Tests that RemoveReference removes reference from reference types. -TEST(RemoveReferenceTest, RemovesReference) { - CompileAssertTypesEqual<int, RemoveReference<int&>::type>(); - CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>(); -} - -// Tests GTEST_REMOVE_REFERENCE_. - -template <typename T1, typename T2> -void TestGTestRemoveReference() { - CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>(); -} - -TEST(RemoveReferenceTest, MacroVersion) { - TestGTestRemoveReference<int, int>(); - TestGTestRemoveReference<const char, const char&>(); -} - // Tests GTEST_REMOVE_REFERENCE_AND_CONST_. template <typename T1, typename T2> void TestGTestRemoveReferenceAndConst() { - CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>(); + static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value, + "GTEST_REMOVE_REFERENCE_AND_CONST_ failed."); } TEST(RemoveReferenceToConstTest, Works) { @@ -7153,7 +7121,8 @@ TEST(RemoveReferenceToConstTest, Works) { template <typename T1, typename T2> void TestGTestReferenceToConst() { - CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>(); + static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value, + "GTEST_REFERENCE_TO_CONST_ failed."); } TEST(GTestReferenceToConstTest, Works) { @@ -7384,20 +7353,15 @@ TEST(IndexSequence, MakeIndexSequence) { // ElemFromList TEST(ElemFromList, Basic) { using testing::internal::ElemFromList; - using Idx = testing::internal::MakeIndexSequence<3>::type; - EXPECT_TRUE(( - std::is_same<int, ElemFromList<0, Idx, int, double, char>::type>::value)); EXPECT_TRUE( - (std::is_same<double, - ElemFromList<1, Idx, int, double, char>::type>::value)); + (std::is_same<int, ElemFromList<0, int, double, char>::type>::value)); EXPECT_TRUE( - (std::is_same<char, - ElemFromList<2, Idx, int, double, char>::type>::value)); + (std::is_same<double, ElemFromList<1, int, double, char>::type>::value)); EXPECT_TRUE( - (std::is_same< - char, ElemFromList<7, testing::internal::MakeIndexSequence<12>::type, - int, int, int, int, int, int, int, char, int, int, - int, int>::type>::value)); + (std::is_same<char, ElemFromList<2, int, double, char>::type>::value)); + EXPECT_TRUE(( + std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int, + char, int, int, int, int>::type>::value)); } // FlatTuple |