Compare commits

78 Commits

Author SHA1 Message Date
Abseil Team
94f756749c Export Test - Do Not Merge
Remove the CMAKE_CXX_STANDARD from GoogleTest's CMakeLists.txt

This causes ABI issues since it can create a mixed-mode build.  The
value should be inherited from the top-level build if it needs to be
set.

PiperOrigin-RevId: 294730724
2020-02-13 12:05:32 -05:00
Abseil Team
6f5fd0d719 Googletest export
Add gmock Matcher<std::string_view> specialization.

PiperOrigin-RevId: 294443240
2020-02-11 15:50:26 -05:00
Abseil Team
d0930731d6 Googletest export
Fix gmock_gen to use MOCK_METHOD instead of old style macros.  Fix several
related bugs in argument parsing and return types.
- handle commas more correctly in return types
- handle commas correctly in arguments
- handle default values more correctly

PiperOrigin-RevId: 294435093
2020-02-11 15:50:18 -05:00
Abseil Team
56de7cc8b5 Googletest export
Fix gmock_gen to use MOCK_METHOD instead of old style macros.

PiperOrigin-RevId: 294360947
2020-02-11 15:50:10 -05:00
Abseil Team
360f5f70a3 Googletest export
Fix gmock_gen to use MOCK_METHOD instead of old style macros.

PiperOrigin-RevId: 294332975
2020-02-11 15:50:01 -05:00
Abseil Team
139fa202c9 Googletest export
Refactor function GetNextPrime so that the loop precondition is checked before
loop instead of during every loop run.  Also by removing the loop condition,
it shows that the only exit from the loop is the return statement.

PiperOrigin-RevId: 293932783
2020-02-11 15:49:53 -05:00
Abseil Team
41b5f149ab Googletest export
Get rid of gmock-generated-matchers.h and gmock-generated-matchers.h.pump.

Stop using pump for MATCHER* macroses generation.

PiperOrigin-RevId: 293878808
2020-02-07 18:20:45 -05:00
durandal
2d6d7a01c9 Googletest export
Tag the function generated by MATCHER with GTEST_ATTRIBUTE_UNUSED_ to fix CI builds of gmock-matchers_test.cc vs. -Wunused-function.

See https://github.com/google/googletest/pull/2697 for breakage.

PiperOrigin-RevId: 293669752
2020-02-07 13:35:36 -05:00
Abseil Team
fbf67a70d0 Googletest export
Get rid of gmock-generated-function-mockers.h and
gmock-generated-function-mockers.h.pump.

Stop using pump for GMOCK_METHOD* macroses generation.

PiperOrigin-RevId: 293454519
2020-02-07 13:35:27 -05:00
Abseil Team
11d9834e98 Googletest export
...text exposed to GitHub repo https://www.github.com/google/googletest

PiperOrigin-RevId: 293438092
2020-02-07 13:35:19 -05:00
Abseil Team
d02e277275 Googletest export
Pass method's parameters count to internal GMOCK_METHOD* macro.

This will help removing copypaste in every GMOCK_METHOD* macro in future.

PiperOrigin-RevId: 292932554
2020-02-07 13:35:10 -05:00
Abseil Team
4f6609129a Googletest export
Fix std::move to std::forward where appropriate to support reference types.

PiperOrigin-RevId: 292923058
2020-02-07 13:35:00 -05:00
Abseil Team
74b44b2d0f Googletest export
Disable warning C4800 for Visual Studio 2019.

The compiler warning C4800 is disabled by default in Visual Studio 2019,
but it can be enabled on the command line. The only version of
Visual Studio that does not support warning C4800 is Visual Studio 2017.

PiperOrigin-RevId: 292624510
2020-02-07 13:34:51 -05:00
Abseil Team
572e261b60 Googletest export
Fix use of reserved names.
Minimize code duplication needed for explict-vs-nonexplicit constructor.

PiperOrigin-RevId: 292555014
2020-02-07 13:34:42 -05:00
Abseil Team
7bc671b8e0 Googletest export
Add documentation for ASSERT_DEBUG_DEATH/EXPECT_DEBUG_DEATH

PiperOrigin-RevId: 292138974
2020-02-07 13:34:33 -05:00
Abseil Team
38f6608e87 Googletest export
Add includes for type_traits and utility to gmock-function-mocker.h: macros in the file require these headers.

PiperOrigin-RevId: 291782497
2020-02-07 13:34:26 -05:00
Abseil Team
d6ce39edf6 Googletest export
Create implementation macroses for matchers to move variadic parameters to the
end of parameters list.

To save backward compatibility, old macroses will be still taking `description`
parameter as the last one. But they will use INTERNAL macro that takes
`description` as the second parameter.

PiperOrigin-RevId: 291724469
2020-02-07 13:34:18 -05:00
Abseil Team
7413280c52 Googletest export
Adds missing `#define` guard around `TEST_F(...)`

PiperOrigin-RevId: 291703056
2020-02-07 13:34:11 -05:00
Abseil Team
87061810f4 Googletest export
Move part of functionality of Matcher* class to the base one. Reduce copypaste.

Make constructor and conversion operator of Matcher* class independent of pump.

PiperOrigin-RevId: 291405510
2020-02-07 13:34:03 -05:00
Abseil Team
f1a6db9d4a Googletest export
Deleted an orphaned duplicate file and exclude another that shouldn't be part of :gtest_all_test.

This showed up while trying to debug the presubmit failure for: https://github.com/google/googletest/pull/2683

PiperOrigin-RevId: 291398123
2020-02-07 13:33:55 -05:00
Abseil Team
22397f28ef Googletest export
Add missing explicit keyword for gmock_Impl constructor.

When switching to using GMOCK_PP in ACTION* macroses `explicit` keyword was
missed in gmock_Impl constructor causing ClangTidy warnings in ACTION_P macro.

PiperOrigin-RevId: 291159975
2020-02-07 13:33:47 -05:00
Abseil Team
10b1902d89 Googletest export
Fix SCOPED_TRACE() message header in example

PiperOrigin-RevId: 290800241
2020-01-21 16:26:40 -05:00
Abseil Team
d01e356e15 Googletest export
Allow copying of the string in MatchAndExplain.

Otherwise, conversions from std::string_view to std::string will fail as being
explicit

PiperOrigin-RevId: 290301103
2020-01-21 16:26:33 -05:00
Xiaoyi Zhang
9417fb401a Merge pull request #2665 from bysreg:fix_noshortcircuitfailure_detectsflakyshortcircuit_test
PiperOrigin-RevId: 290256504
2020-01-21 16:26:24 -05:00
Xiaoyi Zhang
c59c7bab50 Merge pull request #2672 from ivan1993br:ivan1993br-platformio_update
PiperOrigin-RevId: 290255937
2020-01-21 16:26:16 -05:00
Abseil Team
18b67bfc58 Googletest export
Add extra filtering so that the reported message differentiates between the case where INSTANTIATE_TEST_SUITE_P is missing vs. the case where TEST_P is missing.

PiperOrigin-RevId: 290114508
2020-01-21 16:26:08 -05:00
Abseil Team
8b4817e3df Googletest export
Correct the spelling of PARAMETERIZED.

PiperOrigin-RevId: 289897278
2020-01-16 13:56:21 -05:00
Abseil Team
5336106b66 Googletest export
Use GMOCK_PP to create GMOCK_INTERNAL_ACTION macro.

Create GMOCK_INTERNAL_ACTION macro that generates ACTION_P* macroses using
GMOCK_PP.

PiperOrigin-RevId: 289815906
2020-01-16 13:56:12 -05:00
Abseil Team
3e79d366e3 Googletest export
Wire up things to support marking a type paramaterized test as allowed to be un-instantiated.

PiperOrigin-RevId: 289699939
2020-01-16 13:56:04 -05:00
Abseil Team
7a8591e6e4 Googletest export
Use GMOCK_PP to generate args boilerplate.

Move common args describing part to separate macroses that uses GMOCK_PP to
generate sequences.

PiperOrigin-RevId: 289655624
2020-01-16 13:55:54 -05:00
Abseil Team
0b024bd91a Googletest export
Add GTEST_ALLOW_UNINSTANTIATED_PARAMTERIZED_TEST to mark a paramaterized test as allowed to be un-instantiated.

This allows test suites, that are defined in libraries and, for other reasons, get linked in (which should probably be avoided, but isn't always possible) to be marked as allowed to go uninstantiated.

This can also be used to grandfather existing issues and expedite adoption of the checks with regards to new cases before they can be fixed.

PiperOrigin-RevId: 289581573
2020-01-16 13:55:45 -05:00
Abseil Team
ed16134fb3 Googletest export
Change testing::TempDir() return value for Android

PiperOrigin-RevId: 289102017
2020-01-16 13:55:36 -05:00
Ivan Oliveira Tarifa
aa4315646b Remove exclusion of *-main and*-all targets
Removing exclusion of *-main and*-all targets from the library.json used on platformio.
2020-01-15 08:45:14 -03:00
Muhammad Hilman Beyri
c7137f0b84 Use IsReadableTypeName IsReadableTypeName in OfType function in gmock-matchers_test.cc 2020-01-12 21:29:54 -05:00
Muhammad Hilman Beyri
3aa538cbfc fix unit test failure on NoShortCircuitOnFailure and DetectsFlakyShortCircuit when GTEST_HAS_RTTI is 1 2020-01-12 16:53:09 -05:00
Abseil Team
d854bd6acc Googletest export
Removing GTEST_API from TrueWithString.
This type is only used in test code on one side of a DLL boundary so it is not
necessary.

PiperOrigin-RevId: 288927929
2020-01-09 18:25:32 -05:00
Abseil Team
c901f67ddf Googletest export
Move part of functionality of Action* class to the base one. Reduce copypaste.

Make constructor and conversion operator of Action* class independent of pump.

PiperOrigin-RevId: 288907005
2020-01-09 18:25:24 -05:00
Abseil Team
8417b73322 Googletest export
Close #2658
Mark test case destrucors as override.

PiperOrigin-RevId: 288507991
2020-01-09 18:25:16 -05:00
Abseil Team
4b9c1691c4 Googletest export
Use C++11 variadic templates for Invoke in gmock-generated-actions.h.

Replace InvokeArgumentAdl with Invoke that uses C++11 variadic templates.

PiperOrigin-RevId: 288449236
2020-01-09 18:25:08 -05:00
Abseil Team
306f3754a7 Googletest export
Explicitly default copy constructor in BoundSecondMatcher

Since C++11, implicit defaulting of copy constructors is deprecated for types
with user-defined copy assignment operators, so we should explicitly default the
copy constructor of BoundSecondMatcher.

PiperOrigin-RevId: 287587847
2020-01-02 16:49:38 -05:00
Andy Soffer
07ab939af7 Merge pull request #2632 from Kravlalala:cmake/mingw_msys_build
PiperOrigin-RevId: 287587126
2020-01-02 16:49:30 -05:00
Abseil Team
0d98d87e10 Googletest export
Add missing period.

PiperOrigin-RevId: 287553550
2020-01-02 16:49:22 -05:00
Abseil Team
153909f096 Googletest export
Fix typo in example.

PiperOrigin-RevId: 287212448
2020-01-02 16:49:14 -05:00
Andy Soffer
fbe34cecf4 Merge pull request #2639 from trzecieu:trzeci/move_ctor_assign
PiperOrigin-RevId: 286896167
2020-01-02 16:49:07 -05:00
Abseil Team
a13a062618 Googletest export
Add option (default to disabled) to make C++ type parameterized tests (TYPED_TEST_P) fail when they're not instantiated.

When an un-instantiated TYPED_TEST_P is found, a new test will be inserted that emits a suitable message. For now, that is just a notice, but the hope it to flip the bit to make it fail by default.

PiperOrigin-RevId: 286408038
2020-01-02 16:48:59 -05:00
Andy Soffer
008629ae21 Merge pull request #2624 from ShabbyX:master
PiperOrigin-RevId: 286397298
2020-01-02 16:48:50 -05:00
Abseil Team
d0a521255e Googletest export
Use C++11 variadic templates for InvokeArgumentAdl in gmock-generated-actions.h.

Make InvokeArgumentAdl use variadic templates to generate its overloads instead
of using pump.py syntax.

PiperOrigin-RevId: 286267615
2020-01-02 16:48:42 -05:00
Abseil Team
6f1a8ffde9 Googletest export
Use C++11 variadic templates for InvokeArgumentAdl in gmock-generated-actions.h.

Make InvokeArgumentAdl use variadic templates to generate its overloads instead
of using pump.py syntax.

PiperOrigin-RevId: 286148805
2020-01-02 16:48:34 -05:00
Piotr Paczkowski (trzeci.eu)
bf31ed376a Make move operation noexcept. 2019-12-20 09:51:35 +01:00
Piotr Paczkowski (trzeci.eu)
cc05a3ca01 Define default destructor for test classes 2019-12-20 09:45:28 +01:00
Piotr Paczkowski (trzeci.eu)
05701fee28 Deleted functions as part of public interface 2019-12-20 09:41:58 +01:00
Piotr Paczkowski (trzeci.eu)
77b3a250ea Review notes: Return T& from assignment operators 2019-12-20 09:39:06 +01:00
trzeci
9d8222ad66 Disable move constructor and assignment operator for test classes.
Disable move operations for TEST() and TEST_F() macros.
Previous implementation disabled only copy ctor and assing operator, but
this was violating rule of 5[1], which was captured by static code analysis tools
like clang-tidy `cppcoreguidelines-special-member-functions`.

[1]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all
2019-12-17 23:43:31 +01:00
CJ Johnson
d166e09483 Merge pull request #2590 from kuzkry:remove-workaround_g++-stale-comments
PiperOrigin-RevId: 285812343
2019-12-16 16:03:59 -05:00
krzysio
0a0c826629 Googletest export
Don't use fully qualified ::std types in code examples.

Having a nested user-defined 'std' namespace anywhere in a program is a minefield and shouldn't be either explicitly supported or implicitly condoned.

PiperOrigin-RevId: 285790182
2019-12-16 16:03:51 -05:00
Shahbaz Youssefi
1800a38fb7 Revert "Googletest export": disallow empty prefix
This reverts commit 20b5b8ecc7.
Reason for revert: Breaks existing applications, such as ANGLE
(angleproject.org), requires adding an extra prefix that needs to be
typed for no reason (when testing from command line) and increases the
logs' sizes by a non-trivial amount due to the very large number of
tests ANGLE runs.

Original commit message:

    Add a compile time check to ensure that the parameters to TEST_P and
    INSTANTIATE_TEST_SUITE_P are not empty. Some compilers already fail
    in that case and, even where it works, it's likely to result in
    technically invalid code by virtue of creating reserved identifiers:
    https://en.cppreference.com/w/cpp/language/identifiers

First, every project is perfectly capable of adding a prefix if they
want to support such a compiler. This change penalizes every
project.

Second, using a prefix such as `_p` also results in reserved
identifiers, so this change is not really solving the problem.  For that
matter, instead of generating `gtest_##prefix##...`, you can generate
`gtest_x##prefix##...` to correctly fix the issue, including when empty
prefixes are used.
2019-12-16 13:01:59 -05:00
Shahbaz Youssefi
4b7809c2f5 Revert "Googletest export": Remove test for empty prefix
This reverts commit 4c25e2b87f.
Reason for revert: Reverting the commit that disallows empty prefixes.

Original commit message:

    Remove a test case rendered obsolete by disallowing empty argument for INSTANTIATE_TEST_SUITE_P.
    Remove the code that it was testing.
2019-12-16 13:01:52 -05:00
Shahbaz Youssefi
d201646906 Workaround VS bug w.r.t empty arguments to macros
Empty arguments can be passed to macros per C99 and C++11 specs, which
can then be forwarded to other macros.

Visual Studio's compiler has a bug in the following situation:

    #define A(x) #x
    #define B(x, y) A(x)
    B(, b)

In the above case, Visual Studio first expands x to nothing, then
complains that A is not invoked with the right amount of arguments.
However, x in A(x) is still one argument, even if it expands to no
preprocessing tokens.  See also https://stackoverflow.com/a/7674214.
2019-12-16 11:27:52 -05:00
Matt Calabrese
5b162a79d4 Merge pull request #2589 from kuzkry:remove-workaround_g++-no-space-after-first-macro-argument
PiperOrigin-RevId: 285255373
2019-12-13 12:58:11 -05:00
Abseil Team
d16f86ff1c Googletest export
Add GTEST_API_ to correct a build failure under MSCV.

PiperOrigin-RevId: 285208464
2019-12-13 12:58:02 -05:00
Abseil Team
d8eeb9760a Googletest export
Use C++11 variadic templates for ActionHelper in gmock-generated-actions.h.

Make ActionHelper use variadic templates to generate Perform static member function specializations instead of using pump.py syntax.

PiperOrigin-RevId: 284988441
2019-12-13 12:57:53 -05:00
Abseil Team
d442089d53 Googletest export
Detect when C++ parametric tests (TEST_P) are not instantiated.

When an un-instantiated TEST_P is found, a new test will be inserted that will emit a warning message.

This can be made to error with minor code edits.
In the future, that is intended to be the default.

PiperOrigin-RevId: 284901666
2019-12-13 12:57:44 -05:00
Matt Calabrese
88ba008c23 Merge pull request #2595 from kuzkry:remove-workaround_msvc-warning-4355
PiperOrigin-RevId: 284234675
2019-12-13 12:57:35 -05:00
Matt Calabrese
a3097c826e Merge pull request #2592 from kuzkry:remove-workaround_msvc-error-C2665
PiperOrigin-RevId: 284207090
2019-12-13 12:57:26 -05:00
misterg
6251071a20 Googletest export
Require all appveyor googletest windows builds to work on Pull Requests to increase CI coverage

PiperOrigin-RevId: 284206759
2019-12-13 12:57:17 -05:00
Ilya Kravchuk
20b8e7a1c8 Activate GNU extensions in case of MSYS generator 2019-12-13 13:47:04 +03:00
Mark Barolak
78fdd6c00b Merge pull request #2609 from kuzkry:revert-2596
PiperOrigin-RevId: 284041013
2019-12-06 11:34:42 -05:00
Abseil Team
9ed99c6c83 Googletest export
Change googletest to notice failures during SetUpTestSuite() and TearDownTestSuite().

Previously, errors that occurred during those functions were logged but otherwise ignored. After this change, such failures will cause the test to fail and a brief summary will be printed at the bottom of the test log.

See https://github.com/google/googletest/issues/2330.

PiperOrigin-RevId: 284033342
2019-12-06 11:34:34 -05:00
Abseil Team
2002f267f0 Googletest export
Update example Environment class destructor annotation

PiperOrigin-RevId: 283986183
2019-12-05 14:41:59 -05:00
Mark Barolak
1d563578c8 Merge pull request #2594 from kuzkry:remove-workaround_msvc-unneeded-const-dropping
PiperOrigin-RevId: 283979494
2019-12-05 14:41:50 -05:00
Abseil Team
cf75d4b92e Googletest export
Internal change

PiperOrigin-RevId: 283948137
2019-12-05 14:41:41 -05:00
Krystian Kuzniarek
3957b8898b Revert "remove MSVC workaround: wmain link error in the static library"
This reverts commit 298a40f023.
2019-11-27 15:01:03 +01:00
Krystian Kuzniarek
967d8e05c2 Revert "unify googletest and googlemock main functions"
This reverts commit a909becdc5.
2019-11-27 15:00:52 +01:00
Krystian Kuzniarek
6748df1eab remove MSVC workaround: cease const dropping 2019-11-22 17:17:41 +01:00
Krystian Kuzniarek
ecefcbd4aa remove MSVC workaround: warning 4355 2019-11-22 17:15:23 +01:00
Krystian Kuzniarek
a5136dbdd2 remove MSVC workaround: error C2665 2019-11-22 17:12:11 +01:00
Krystian Kuzniarek
a91e4e73b7 remove stale comments about older GCC versions 2019-11-22 17:09:52 +01:00
Krystian Kuzniarek
e1dd49835e remove g++ 2.95.0 workaround: no space after first comma in macros 2019-11-22 17:09:03 +01:00
55 changed files with 3954 additions and 6906 deletions

View File

@@ -10,12 +10,8 @@ endif (POLICY CMP0048)
project(googletest-distribution) project(googletest-distribution)
set(GOOGLETEST_VERSION 1.10.0) set(GOOGLETEST_VERSION 1.10.0)
if (CMAKE_VERSION VERSION_LESS "3.1") if (CMAKE_VERSION VERSION_GREATER_EQUAL "3.1")
add_definitions(-std=c++11) if(NOT CYGWIN AND NOT MSYS)
else()
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(NOT CYGWIN)
set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_EXTENSIONS OFF)
endif() endif()
endif() endif()

View File

@@ -80,7 +80,7 @@ fairly rigid coding style, as defined by the
will be expected to conform to the style outlined will be expected to conform to the style outlined
[here](https://google.github.io/styleguide/cppguide.html). Use [here](https://google.github.io/styleguide/cppguide.html). Use
[.clang-format](https://github.com/google/googletest/blob/master/.clang-format) [.clang-format](https://github.com/google/googletest/blob/master/.clang-format)
to check your formatting to check your formatting.
## Requirements for Contributors ## Requirements for Contributors

View File

@@ -8,6 +8,7 @@ environment:
generator: "Visual Studio 15 2017" generator: "Visual Studio 15 2017"
build_system: cmake build_system: cmake
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
enabled_on_pr: yes
- compiler: msvc-15-seh - compiler: msvc-15-seh
generator: "Visual Studio 15 2017 Win64" generator: "Visual Studio 15 2017 Win64"
@@ -28,6 +29,7 @@ environment:
- compiler: msvc-14-seh - compiler: msvc-14-seh
build_system: cmake build_system: cmake
generator: "Visual Studio 14 2015 Win64" generator: "Visual Studio 14 2015 Win64"
enabled_on_pr: yes
- compiler: gcc-6.3.0-posix - compiler: gcc-6.3.0-posix
build_system: cmake build_system: cmake

View File

@@ -166,7 +166,6 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_test(gmock_ex_test gmock_main) cxx_test(gmock_ex_test gmock_main)
cxx_test(gmock-function-mocker_test gmock_main) cxx_test(gmock-function-mocker_test gmock_main)
cxx_test(gmock-generated-actions_test gmock_main) cxx_test(gmock-generated-actions_test gmock_main)
cxx_test(gmock-generated-function-mockers_test gmock_main)
cxx_test(gmock-generated-matchers_test gmock_main) cxx_test(gmock-generated-matchers_test gmock_main)
cxx_test(gmock-internal-utils_test gmock_main) cxx_test(gmock-internal-utils_test gmock_main)
cxx_test(gmock-matchers_test gmock_main) cxx_test(gmock-matchers_test gmock_main)

View File

@@ -489,7 +489,7 @@ which must be a permanent callback.
| Matcher | Description | | Matcher | Description |
| :----------------------------------- | :------------------------------------ | | :----------------------------------- | :------------------------------------ |
| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | | `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | | `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. |
| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | | `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
<!-- mdformat on --> <!-- mdformat on -->

View File

@@ -1024,9 +1024,8 @@ using ::testing::Lt;
says that the first argument of `InRange()` must not be 0, and must be less than says that the first argument of `InRange()` must not be 0, and must be less than
the second argument. the second argument.
The expression inside `With()` must be a matcher of type The expression inside `With()` must be a matcher of type `Matcher<std::tuple<A1,
`Matcher< ::std::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the types of ..., An>>`, where `A1`, ..., `An` are the types of the function arguments.
the function arguments.
You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms
are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`. are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`.
@@ -1054,8 +1053,8 @@ complete list.
Note that if you want to pass the arguments to a predicate of your own (e.g. Note that if you want to pass the arguments to a predicate of your own (e.g.
`.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to
take a `::std::tuple` as its argument; gMock will pass the `n` selected take a `std::tuple` as its argument; gMock will pass the `n` selected arguments
arguments as *one* single tuple to the predicate. as *one* single tuple to the predicate.
### Using Matchers as Predicates ### Using Matchers as Predicates
@@ -1331,11 +1330,11 @@ class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
return (foo.bar() + foo.baz()) == expected_sum_; return (foo.bar() + foo.baz()) == expected_sum_;
} }
void DescribeTo(::std::ostream* os) const override { void DescribeTo(std::ostream* os) const override {
*os << "bar() + baz() equals " << expected_sum_; *os << "bar() + baz() equals " << expected_sum_;
} }
void DescribeNegationTo(::std::ostream* os) const override { void DescribeNegationTo(std::ostream* os) const override {
*os << "bar() + baz() does not equal " << expected_sum_; *os << "bar() + baz() does not equal " << expected_sum_;
} }
private: private:
@@ -2203,7 +2202,7 @@ class Helper {
.WillOnce(&CalculateSum) .WillOnce(&CalculateSum)
.WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1))); .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1)));
EXPECT_CALL(foo, ComplexJob(_)) EXPECT_CALL(foo, ComplexJob(_))
.WillOnce(Invoke(&helper, &Helper::ComplexJob)); .WillOnce(Invoke(&helper, &Helper::ComplexJob))
.WillRepeatedly([](int x) { return x > 0; }); .WillRepeatedly([](int x) { return x > 0; });
foo.Sum(5, 6); // Invokes CalculateSum(5, 6). foo.Sum(5, 6); // Invokes CalculateSum(5, 6).
@@ -3565,7 +3564,7 @@ class MatchResultListener {
MatchResultListener& operator<<(const T& x); MatchResultListener& operator<<(const T& x);
// Returns the underlying ostream. // Returns the underlying ostream.
::std::ostream* stream(); std::ostream* stream();
}; };
template <typename T> template <typename T>
@@ -3578,10 +3577,10 @@ class MatcherInterface {
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
// Describes this matcher to an ostream. // Describes this matcher to an ostream.
virtual void DescribeTo(::std::ostream* os) const = 0; virtual void DescribeTo(std::ostream* os) const = 0;
// Describes the negation of this matcher to an ostream. // Describes the negation of this matcher to an ostream.
virtual void DescribeNegationTo(::std::ostream* os) const; virtual void DescribeNegationTo(std::ostream* os) const;
}; };
``` ```
@@ -3609,11 +3608,11 @@ class DivisibleBy7Matcher : public MatcherInterface<int> {
return (n % 7) == 0; return (n % 7) == 0;
} }
void DescribeTo(::std::ostream* os) const override { void DescribeTo(std::ostream* os) const override {
*os << "is divisible by 7"; *os << "is divisible by 7";
} }
void DescribeNegationTo(::std::ostream* os) const override { void DescribeNegationTo(std::ostream* os) const override {
*os << "is not divisible by 7"; *os << "is not divisible by 7";
} }
}; };
@@ -3995,7 +3994,7 @@ ACTION_TEMPLATE(DuplicateArg,
// Note the comma between int and k: // Note the comma between int and k:
HAS_2_TEMPLATE_PARAMS(int, k, typename, T), HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
AND_1_VALUE_PARAMS(output)) { AND_1_VALUE_PARAMS(output)) {
*output = T(::std::get<k>(args)); *output = T(std::get<k>(args));
} }
``` ```
@@ -4087,7 +4086,7 @@ class ActionInterface {
// //
// For example, if F is int(bool, const string&), then Result would // For example, if F is int(bool, const string&), then Result would
// be int, and ArgumentTuple would be ::std::tuple<bool, const string&>. // be int, and ArgumentTuple would be std::tuple<bool, const string&>.
virtual Result Perform(const ArgumentTuple& args) = 0; virtual Result Perform(const ArgumentTuple& args) = 0;
}; };
``` ```
@@ -4102,8 +4101,8 @@ typedef int IncrementMethod(int*);
class IncrementArgumentAction : public ActionInterface<IncrementMethod> { class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
public: public:
int Perform(const ::std::tuple<int*>& args) override { int Perform(const std::tuple<int*>& args) override {
int* p = ::std::get<0>(args); // Grabs the first argument. int* p = std::get<0>(args); // Grabs the first argument.
return *p++; return *p++;
} }
}; };
@@ -4148,8 +4147,8 @@ class ReturnSecondArgumentAction {
public: public:
template <typename Result, typename ArgumentTuple> template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple& args) const { Result Perform(const ArgumentTuple& args) const {
// To get the i-th (0-based) argument, use ::std::get(args). // To get the i-th (0-based) argument, use std::get(args).
return ::std::get<1>(args); return std::get<1>(args);
} }
}; };
``` ```

View File

@@ -30,7 +30,100 @@
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements some commonly used actions. // The ACTION* family of macros can be used in a namespace scope to
// define custom actions easily. The syntax:
//
// ACTION(name) { statements; }
//
// will define an action with the given name that executes the
// statements. The value returned by the statements will be used as
// the return value of the action. Inside the statements, you can
// refer to the K-th (0-based) argument of the mock function by
// 'argK', and refer to its type by 'argK_type'. For example:
//
// ACTION(IncrementArg1) {
// arg1_type temp = arg1;
// return ++(*temp);
// }
//
// allows you to write
//
// ...WillOnce(IncrementArg1());
//
// You can also refer to the entire argument tuple and its type by
// 'args' and 'args_type', and refer to the mock function type and its
// return type by 'function_type' and 'return_type'.
//
// Note that you don't need to specify the types of the mock function
// arguments. However rest assured that your code is still type-safe:
// you'll get a compiler error if *arg1 doesn't support the ++
// operator, or if the type of ++(*arg1) isn't compatible with the
// mock function's return type, for example.
//
// Sometimes you'll want to parameterize the action. For that you can use
// another macro:
//
// ACTION_P(name, param_name) { statements; }
//
// For example:
//
// ACTION_P(Add, n) { return arg0 + n; }
//
// will allow you to write:
//
// ...WillOnce(Add(5));
//
// Note that you don't need to provide the type of the parameter
// either. If you need to reference the type of a parameter named
// 'foo', you can write 'foo_type'. For example, in the body of
// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
// of 'n'.
//
// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
// multi-parameter actions.
//
// For the purpose of typing, you can view
//
// ACTION_Pk(Foo, p1, ..., pk) { ... }
//
// as shorthand for
//
// template <typename p1_type, ..., typename pk_type>
// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
//
// In particular, you can provide the template type arguments
// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
// although usually you can rely on the compiler to infer the types
// for you automatically. You can assign the result of expression
// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
// pk_type>. This can be useful when composing actions.
//
// You can also overload actions with different numbers of parameters:
//
// ACTION_P(Plus, a) { ... }
// ACTION_P2(Plus, a, b) { ... }
//
// While it's tempting to always use the ACTION* macros when defining
// a new action, you should also consider implementing ActionInterface
// or using MakePolymorphicAction() instead, especially if you need to
// use the action a lot. While these approaches require more work,
// they give you more control on the types of the mock function
// arguments and the action parameters, which in general leads to
// better compiler error messages that pay off in the long run. They
// also allow overloading actions based on parameter types (as opposed
// to just based on the number of parameters).
//
// CAVEAT:
//
// ACTION*() can only be used in a namespace scope as templates cannot be
// declared inside of a local class.
// Users can, however, define any local functors (e.g. a lambda) that
// can be used as actions.
//
// MORE INFORMATION:
//
// To learn more about using these macros, please search for 'ACTION' on
// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
// GOOGLETEST_CM0002 DO NOT DELETE // GOOGLETEST_CM0002 DO NOT DELETE
@@ -50,6 +143,7 @@
#include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gmock/internal/gmock-pp.h"
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) # pragma warning(push)
@@ -1184,6 +1278,254 @@ inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
return ::std::reference_wrapper<T>(l_value); return ::std::reference_wrapper<T>(l_value);
} }
namespace internal {
// A macro from the ACTION* family (defined later in gmock-generated-actions.h)
// defines an action that can be used in a mock function. Typically,
// these actions only care about a subset of the arguments of the mock
// function. For example, if such an action only uses the second
// argument, it can be used in any mock function that takes >= 2
// arguments where the type of the second argument is compatible.
//
// Therefore, the action implementation must be prepared to take more
// arguments than it needs. The ExcessiveArg type is used to
// represent those excessive arguments. In order to keep the compiler
// error messages tractable, we define it in the testing namespace
// instead of testing::internal. However, this is an INTERNAL TYPE
// and subject to change without notice, so a user MUST NOT USE THIS
// TYPE DIRECTLY.
struct ExcessiveArg {};
// A helper class needed for implementing the ACTION* macros.
template <typename Result, class Impl>
class ActionHelper {
public:
template <typename... Ts>
static Result Perform(Impl* impl, const std::tuple<Ts...>& args) {
return Apply(impl, args, MakeIndexSequence<sizeof...(Ts)>{},
MakeIndexSequence<10 - sizeof...(Ts)>{});
}
private:
template <typename... Ts, std::size_t... tuple_ids, std::size_t... rest_ids>
static Result Apply(Impl* impl, const std::tuple<Ts...>& args,
IndexSequence<tuple_ids...>, IndexSequence<rest_ids...>) {
return impl->template gmock_PerformImpl<Ts...>(
args, std::get<tuple_ids>(args)...,
((void)rest_ids, ExcessiveArg())...);
}
};
// A helper base class needed for implementing the ACTION* macros.
// Implements constructor and conversion operator for Action.
//
// Template specialization for parameterless Action.
template <typename Derived>
class ActionImpl {
public:
ActionImpl() = default;
template <typename F>
operator ::testing::Action<F>() const { // NOLINT(runtime/explicit)
return ::testing::Action<F>(new typename Derived::template gmock_Impl<F>());
}
};
// Template specialization for parameterized Action.
template <template <typename...> class Derived, typename... Ts>
class ActionImpl<Derived<Ts...>> {
public:
explicit ActionImpl(Ts... params) : params_(std::forward<Ts>(params)...) {}
template <typename F>
operator ::testing::Action<F>() const { // NOLINT(runtime/explicit)
return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
}
private:
template <typename F, std::size_t... tuple_ids>
::testing::Action<F> Apply(IndexSequence<tuple_ids...>) const {
return ::testing::Action<F>(new
typename Derived<Ts...>::template gmock_Impl<F>(
std::get<tuple_ids>(params_)...));
}
std::tuple<Ts...> params_;
};
namespace invoke_argument {
// Appears in InvokeArgumentAdl's argument list to help avoid
// accidental calls to user functions of the same name.
struct AdlTag {};
// InvokeArgumentAdl - a helper for InvokeArgument.
// The basic overloads are provided here for generic functors.
// Overloads for other custom-callables are provided in the
// internal/custom/gmock-generated-actions.h header.
template <typename F, typename... Args>
auto InvokeArgumentAdl(AdlTag, F f, Args... args) -> decltype(f(args...)) {
return f(args...);
}
} // namespace invoke_argument
#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
, const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
GMOCK_INTERNAL_ARG_UNUSED, , 10)
#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
#define GMOCK_ACTION_TYPE_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
, param##_type gmock_p##i
#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
, std::forward<param##_type>(gmock_p##i)
#define GMOCK_ACTION_GVALUE_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
, param(::std::forward<param##_type>(gmock_p##i))
#define GMOCK_ACTION_INIT_PARAMS_(params) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
#define GMOCK_ACTION_FIELD_PARAMS_(params) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
#define GMOCK_INTERNAL_ACTION(name, full_name, params) \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
class full_name : public ::testing::internal::ActionImpl< \
full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>> { \
using base_type = ::testing::internal::ActionImpl<full_name>; \
\
public: \
using base_type::base_type; \
template <typename F> \
class gmock_Impl : public ::testing::ActionInterface<F> { \
public: \
typedef F function_type; \
typedef typename ::testing::internal::Function<F>::Result return_type; \
typedef \
typename ::testing::internal::Function<F>::ArgumentTuple args_type; \
explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
: GMOCK_ACTION_INIT_PARAMS_(params) {} \
return_type Perform(const args_type& args) override { \
return ::testing::internal::ActionHelper<return_type, \
gmock_Impl>::Perform(this, \
args); \
} \
template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
GMOCK_ACTION_FIELD_PARAMS_(params) \
\
private: \
GTEST_DISALLOW_ASSIGN_(gmock_Impl); \
}; \
\
private: \
GTEST_DISALLOW_ASSIGN_(full_name); \
}; \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
GMOCK_ACTION_GVALUE_PARAMS_(params)); \
} \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
template <typename F> \
template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
typename ::testing::internal::Function<F>::Result \
full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl< \
F>::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) \
const
} // namespace internal
#define ACTION(name) \
class name##Action : public ::testing::internal::ActionImpl<name##Action> { \
using base_type = ::testing::internal::ActionImpl<name##Action>; \
\
public: \
using base_type::base_type; \
template <typename F> \
class gmock_Impl : public ::testing::ActionInterface<F> { \
public: \
typedef F function_type; \
typedef typename ::testing::internal::Function<F>::Result return_type; \
typedef \
typename ::testing::internal::Function<F>::ArgumentTuple args_type; \
gmock_Impl() {} \
return_type Perform(const args_type& args) override { \
return ::testing::internal::ActionHelper<return_type, \
gmock_Impl>::Perform(this, \
args); \
} \
template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
\
private: \
GTEST_DISALLOW_ASSIGN_(gmock_Impl); \
}; \
\
private: \
GTEST_DISALLOW_ASSIGN_(name##Action); \
}; \
inline name##Action name() { return name##Action(); } \
template <typename F> \
template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
typename ::testing::internal::Function<F>::Result \
name##Action::gmock_Impl<F>::gmock_PerformImpl( \
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
#define ACTION_P(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
#define ACTION_P2(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
#define ACTION_P3(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
#define ACTION_P4(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
#define ACTION_P5(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
#define ACTION_P6(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
#define ACTION_P7(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
#define ACTION_P8(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
#define ACTION_P9(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
#define ACTION_P10(name, ...) \
GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
} // namespace testing } // namespace testing
#ifdef _MSC_VER #ifdef _MSC_VER

View File

@@ -36,14 +36,36 @@
#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT #ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT #define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
#include "gmock/gmock-generated-function-mockers.h" // NOLINT #include <type_traits> // IWYU pragma: keep
#include <utility> // IWYU pragma: keep
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-pp.h" #include "gmock/internal/gmock-pp.h"
namespace testing { namespace testing {
namespace internal { namespace internal {
template <typename T> template <typename T>
using identity_t = T; using identity_t = T;
template <typename MockType>
const MockType* AdjustConstness_const(const MockType* mock) {
return mock;
}
template <typename MockType>
MockType* AdjustConstness_(const MockType* mock) {
return const_cast<MockType*>(mock);
}
} // namespace internal } // namespace internal
// The style guide prohibits "using" statements in a namespace scope
// inside a header file. However, the FunctionMocker class template
// is meant to be defined in the ::testing namespace. The following
// line is just a trick for working around a bug in MSVC 8.0, which
// cannot handle it if we define FunctionMocker in ::testing.
using internal::FunctionMocker;
} // namespace testing } // namespace testing
#define MOCK_METHOD(...) \ #define MOCK_METHOD(...) \
@@ -241,36 +263,196 @@ using identity_t = T;
GMOCK_PP_IDENTITY) \ GMOCK_PP_IDENTITY) \
(_elem) (_elem)
#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ #define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \ GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i gmock_a##_i
#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ #define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
::std::forward<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \ ::std::forward<GMOCK_INTERNAL_ARG_O( \
GMOCK_PP_REMOVE_PARENS(_Signature))>( \ _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)
gmock_a##_i)
#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ #define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
GMOCK_INTERNAL_MATCHER_O(typename, GMOCK_PP_INC(_i), \ GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
GMOCK_PP_REMOVE_PARENS(_Signature)) \
gmock_a##_i gmock_a##_i
#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ #define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
gmock_a##_i gmock_a##_i
#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ #define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_COMMA_IF(_i) \
::testing::A<GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \ ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()
GMOCK_PP_REMOVE_PARENS(_Signature))>()
#define GMOCK_INTERNAL_ARG_O(_tn, _i, ...) GMOCK_ARG_(_tn, _i, __VA_ARGS__) #define GMOCK_INTERNAL_ARG_O(_i, ...) \
typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type
#define GMOCK_INTERNAL_MATCHER_O(_tn, _i, ...) \ #define GMOCK_INTERNAL_MATCHER_O(_i, ...) \
GMOCK_MATCHER_(_tn, _i, __VA_ARGS__) const ::testing::Matcher<typename ::testing::internal::Function< \
__VA_ARGS__>::template Arg<_i>::type>&
#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)
#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)
#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)
#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)
#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)
#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)
#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)
#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)
#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)
#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)
#define MOCK_METHOD10(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)
#define MOCK_CONST_METHOD0(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)
#define MOCK_CONST_METHOD1(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)
#define MOCK_CONST_METHOD2(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)
#define MOCK_CONST_METHOD3(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)
#define MOCK_CONST_METHOD4(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)
#define MOCK_CONST_METHOD5(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)
#define MOCK_CONST_METHOD6(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)
#define MOCK_CONST_METHOD7(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)
#define MOCK_CONST_METHOD8(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)
#define MOCK_CONST_METHOD9(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)
#define MOCK_CONST_METHOD10(m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)
#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)
#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)
#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)
#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)
#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)
#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)
#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)
#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)
#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)
#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)
#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)
#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)
#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)
#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)
#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)
#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)
#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)
#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)
#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)
#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)
#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)
#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)
#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)
#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)
#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)
#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)
#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)
#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)
#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)
#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)
#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)
#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)
#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)
#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \
GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
args_num, ::testing::internal::identity_t<__VA_ARGS__>); \
GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, \
(::testing::internal::identity_t<__VA_ARGS__>))
#define GMOCK_MOCKER_(arity, constness, Method) \
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ #endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_

File diff suppressed because it is too large Load Diff

View File

@@ -49,158 +49,9 @@ $$}} This meta comment fixes auto-indentation in editors.
#include "gmock/gmock-actions.h" #include "gmock/gmock-actions.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
namespace testing {
namespace internal {
// A macro from the ACTION* family (defined later in this file)
// defines an action that can be used in a mock function. Typically,
// these actions only care about a subset of the arguments of the mock
// function. For example, if such an action only uses the second
// argument, it can be used in any mock function that takes >= 2
// arguments where the type of the second argument is compatible.
//
// Therefore, the action implementation must be prepared to take more
// arguments than it needs. The ExcessiveArg type is used to
// represent those excessive arguments. In order to keep the compiler
// error messages tractable, we define it in the testing namespace
// instead of testing::internal. However, this is an INTERNAL TYPE
// and subject to change without notice, so a user MUST NOT USE THIS
// TYPE DIRECTLY.
struct ExcessiveArg {};
// A helper class needed for implementing the ACTION* macros.
template <typename Result, class Impl>
class ActionHelper {
public:
$range i 0..n
$for i
[[
$var template = [[$if i==0 [[]] $else [[
$range j 0..i-1
template <$for j, [[typename A$j]]>
]]]]
$range j 0..i-1
$var As = [[$for j, [[A$j]]]]
$var as = [[$for j, [[std::get<$j>(args)]]]]
$range k 1..n-i
$var eas = [[$for k, [[ExcessiveArg()]]]]
$var arg_list = [[$if (i==0) | (i==n) [[$as$eas]] $else [[$as, $eas]]]]
$template
static Result Perform(Impl* impl, const ::std::tuple<$As>& args) {
return impl->template gmock_PerformImpl<$As>(args, $arg_list);
}
]]
};
} // namespace internal
} // namespace testing
// The ACTION* family of macros can be used in a namespace scope to
// define custom actions easily. The syntax:
//
// ACTION(name) { statements; }
//
// will define an action with the given name that executes the
// statements. The value returned by the statements will be used as
// the return value of the action. Inside the statements, you can
// refer to the K-th (0-based) argument of the mock function by
// 'argK', and refer to its type by 'argK_type'. For example:
//
// ACTION(IncrementArg1) {
// arg1_type temp = arg1;
// return ++(*temp);
// }
//
// allows you to write
//
// ...WillOnce(IncrementArg1());
//
// You can also refer to the entire argument tuple and its type by
// 'args' and 'args_type', and refer to the mock function type and its
// return type by 'function_type' and 'return_type'.
//
// Note that you don't need to specify the types of the mock function
// arguments. However rest assured that your code is still type-safe:
// you'll get a compiler error if *arg1 doesn't support the ++
// operator, or if the type of ++(*arg1) isn't compatible with the
// mock function's return type, for example.
//
// Sometimes you'll want to parameterize the action. For that you can use
// another macro:
//
// ACTION_P(name, param_name) { statements; }
//
// For example:
//
// ACTION_P(Add, n) { return arg0 + n; }
//
// will allow you to write:
//
// ...WillOnce(Add(5));
//
// Note that you don't need to provide the type of the parameter
// either. If you need to reference the type of a parameter named
// 'foo', you can write 'foo_type'. For example, in the body of
// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
// of 'n'.
//
// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P$n to support
// multi-parameter actions.
//
// For the purpose of typing, you can view
//
// ACTION_Pk(Foo, p1, ..., pk) { ... }
//
// as shorthand for
//
// template <typename p1_type, ..., typename pk_type>
// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
//
// In particular, you can provide the template type arguments
// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
// although usually you can rely on the compiler to infer the types
// for you automatically. You can assign the result of expression
// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
// pk_type>. This can be useful when composing actions.
//
// You can also overload actions with different numbers of parameters:
//
// ACTION_P(Plus, a) { ... }
// ACTION_P2(Plus, a, b) { ... }
//
// While it's tempting to always use the ACTION* macros when defining
// a new action, you should also consider implementing ActionInterface
// or using MakePolymorphicAction() instead, especially if you need to
// use the action a lot. While these approaches require more work,
// they give you more control on the types of the mock function
// arguments and the action parameters, which in general leads to
// better compiler error messages that pay off in the long run. They
// also allow overloading actions based on parameter types (as opposed
// to just based on the number of parameters).
//
// CAVEAT:
//
// ACTION*() can only be used in a namespace scope as templates cannot be
// declared inside of a local class.
// Users can, however, define any local functors (e.g. a lambda) that
// can be used as actions.
//
// MORE INFORMATION:
//
// To learn more about using these macros, please search for 'ACTION' on
// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
$range i 0..n $range i 0..n
$range k 0..n-1 $range k 0..n-1
// An internal macro needed for implementing ACTION*().
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
const args_type& args GTEST_ATTRIBUTE_UNUSED_
$for k [[, \
const arg$k[[]]_type& arg$k GTEST_ATTRIBUTE_UNUSED_]]
// Sometimes you want to give an action explicit template parameters // Sometimes you want to give an action explicit template parameters
// that cannot be inferred from its value parameters. ACTION() and // that cannot be inferred from its value parameters. ACTION() and
@@ -399,9 +250,8 @@ $range k 0..n-1
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\ Perform(this, args);\
}\ }\
template <$for k, [[typename arg$k[[]]_type]]>\ template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>\
return_type gmock_PerformImpl(const args_type& args[[]] return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const;\
$for k [[, const arg$k[[]]_type& arg$k]]) const;\
GMOCK_INTERNAL_DEFN_##value_params\ GMOCK_INTERNAL_DEFN_##value_params\
private:\ private:\
GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
@@ -428,10 +278,7 @@ $for k [[, const arg$k[[]]_type& arg$k]]) const;\
template <GMOCK_INTERNAL_DECL_##template_params\ template <GMOCK_INTERNAL_DECL_##template_params\
GMOCK_INTERNAL_DECL_TYPE_##value_params>\ GMOCK_INTERNAL_DECL_TYPE_##value_params>\
template <typename F>\ template <typename F>\
template <typename arg0_type, typename arg1_type, typename arg2_type, \ template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>\
typename arg3_type, typename arg4_type, typename arg5_type, \
typename arg6_type, typename arg7_type, typename arg8_type, \
typename arg9_type>\
typename ::testing::internal::Function<F>::Result\ typename ::testing::internal::Function<F>::Result\
GMOCK_ACTION_CLASS_(name, value_params)<\ GMOCK_ACTION_CLASS_(name, value_params)<\
GMOCK_INTERNAL_LIST_##template_params\ GMOCK_INTERNAL_LIST_##template_params\
@@ -439,77 +286,6 @@ $for k [[, const arg$k[[]]_type& arg$k]]) const;\
gmock_PerformImpl(\ gmock_PerformImpl(\
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
$for i
[[
$var template = [[$if i==0 [[]] $else [[
$range j 0..i-1
template <$for j, [[typename p$j##_type]]>\
]]]]
$var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]]
$else [[P$i]]]]]]
$range j 0..i-1
$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::forward<p$j##_type>(gmock_p$j))]]]]]]
$var param_field_decls = [[$for j
[[
p$j##_type p$j;\
]]]]
$var param_field_decls2 = [[$for j
[[
p$j##_type p$j;\
]]]]
$var params = [[$for j, [[p$j]]]]
$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
$var typename_arg_types = [[$for k, [[typename arg$k[[]]_type]]]]
$var arg_types_and_names = [[$for k, [[const arg$k[[]]_type& arg$k]]]]
$var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]]
$else [[ACTION_P$i]]]]
#define $macro_name(name$for j [[, p$j]])\$template
class $class_name {\
public:\
[[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {}\
template <typename F>\
class gmock_Impl : public ::testing::ActionInterface<F> {\
public:\
typedef F function_type;\
typedef typename ::testing::internal::Function<F>::Result return_type;\
typedef typename ::testing::internal::Function<F>::ArgumentTuple\
args_type;\
[[$if i==1 [[explicit ]]]]gmock_Impl($ctor_param_list)$inits {}\
return_type Perform(const args_type& args) override {\
return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\
Perform(this, args);\
}\
template <$typename_arg_types>\
return_type gmock_PerformImpl(const args_type& args, [[]]
$arg_types_and_names) const;\$param_field_decls
private:\
GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
};\
template <typename F> operator ::testing::Action<F>() const {\
return ::testing::Action<F>(new gmock_Impl<F>($params));\
}\$param_field_decls2
private:\
GTEST_DISALLOW_ASSIGN_($class_name);\
};\$template
inline $class_name$param_types name($param_types_and_names) {\
return $class_name$param_types($params);\
}\$template
template <typename F>\
template <$typename_arg_types>\
typename ::testing::internal::Function<F>::Result\
$class_name$param_types::gmock_Impl<F>::gmock_PerformImpl(\
GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
]]
$$ } // This meta comment fixes auto-indentation in Emacs. It won't
$$ // show up in the generated code.
namespace testing { namespace testing {
@@ -554,32 +330,6 @@ namespace testing {
// InvokeArgument action from temporary values and have it performed // InvokeArgument action from temporary values and have it performed
// later. // later.
namespace internal {
namespace invoke_argument {
// Appears in InvokeArgumentAdl's argument list to help avoid
// accidental calls to user functions of the same name.
struct AdlTag {};
// InvokeArgumentAdl - a helper for InvokeArgument.
// The basic overloads are provided here for generic functors.
// Overloads for other custom-callables are provided in the
// internal/custom/gmock-generated-actions.h header.
$range i 0..n
$for i
[[
$range j 1..i
template <typename R, typename F[[$for j [[, typename A$j]]]]>
R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) {
return f([[$for j, [[a$j]]]]);
}
]]
} // namespace invoke_argument
} // namespace internal
$range i 0..n $range i 0..n
$for i [[ $for i [[
$range j 0..i-1 $range j 0..i-1
@@ -588,9 +338,8 @@ ACTION_TEMPLATE(InvokeArgument,
HAS_1_TEMPLATE_PARAMS(int, k), HAS_1_TEMPLATE_PARAMS(int, k),
AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) { AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) {
using internal::invoke_argument::InvokeArgumentAdl; using internal::invoke_argument::InvokeArgumentAdl;
return InvokeArgumentAdl<return_type>( return InvokeArgumentAdl(internal::invoke_argument::AdlTag(),
internal::invoke_argument::AdlTag(), ::std::get<k>(args)$for j[[, p$j]]);
::std::get<k>(args)$for j [[, p$j]]);
} }
]] ]]

View File

@@ -1,752 +0,0 @@
// This file was GENERATED by command:
// pump.py gmock-generated-function-mockers.h.pump
// DO NOT EDIT BY HAND!!!
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements function mockers of various arities.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#include <functional>
#include <utility>
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-internal-utils.h"
namespace testing {
namespace internal {
// Removes the given pointer; this is a helper for the expectation setter method
// for parameterless matchers.
//
// We want to make sure that the user cannot set a parameterless expectation on
// overloaded methods, including methods which are overloaded on const. Example:
//
// class MockClass {
// MOCK_METHOD0(GetName, string&());
// MOCK_CONST_METHOD0(GetName, const string&());
// };
//
// TEST() {
// // This should be an error, as it's not clear which overload is expected.
// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value));
// }
//
// Here are the generated expectation-setter methods:
//
// class MockClass {
// // Overload 1
// MockSpec<string&()> gmock_GetName() { ... }
// // Overload 2. Declared const so that the compiler will generate an
// // error when trying to resolve between this and overload 4 in
// // 'gmock_GetName(WithoutMatchers(), nullptr)'.
// MockSpec<string&()> gmock_GetName(
// const WithoutMatchers&, const Function<string&()>*) const {
// // Removes const from this, calls overload 1
// return AdjustConstness_(this)->gmock_GetName();
// }
//
// // Overload 3
// const string& gmock_GetName() const { ... }
// // Overload 4
// MockSpec<const string&()> gmock_GetName(
// const WithoutMatchers&, const Function<const string&()>*) const {
// // Does not remove const, calls overload 3
// return AdjustConstness_const(this)->gmock_GetName();
// }
// }
//
template <typename MockType>
const MockType* AdjustConstness_const(const MockType* mock) {
return mock;
}
// Removes const from and returns the given pointer; this is a helper for the
// expectation setter method for parameterless matchers.
template <typename MockType>
MockType* AdjustConstness_(const MockType* mock) {
return const_cast<MockType*>(mock);
}
} // namespace internal
// The style guide prohibits "using" statements in a namespace scope
// inside a header file. However, the FunctionMocker class template
// is meant to be defined in the ::testing namespace. The following
// line is just a trick for working around a bug in MSVC 8.0, which
// cannot handle it if we define FunctionMocker in ::testing.
using internal::FunctionMocker;
// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
// We define this as a variadic macro in case F contains unprotected
// commas (the same reason that we use variadic macros in other places
// in this file).
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_RESULT_(tn, ...) \
tn ::testing::internal::Function<__VA_ARGS__>::Result
// The type of argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_ARG_(tn, N, ...) \
tn ::testing::internal::Function<__VA_ARGS__>::template Arg<N-1>::type
// The matcher type for argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_MATCHER_(tn, N, ...) \
const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
// The variable for mocking the given method.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_MOCKER_(arity, constness, Method) \
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \
static_assert(0 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
) constness { \
GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(0, constness, Method).Invoke(); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method() constness { \
GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(0, constness, Method).With(); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \
static_assert(1 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(1, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \
GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \
static_assert(2 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2) constness { \
GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(2, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \
GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \
static_assert(3 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, \
__VA_ARGS__) gmock_a3) constness { \
GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(3, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \
GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \
static_assert(4 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(4, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \
GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \
static_assert(5 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5) constness { \
GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(5, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \
GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \
static_assert(6 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, \
__VA_ARGS__) gmock_a6) constness { \
GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(6, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \
GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \
static_assert(7 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(7, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \
GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \
static_assert(8 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
__VA_ARGS__) gmock_a8) constness { \
GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(8, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
::std::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \
GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \
static_assert(9 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
__VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, \
__VA_ARGS__) gmock_a9) constness { \
GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(9, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
::std::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \
::std::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \
GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \
gmock_a9); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \
Method)
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \
static_assert(10 == \
::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \
"MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \
__VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \
__VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \
__VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \
GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \
GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_(10, constness, \
Method).Invoke(::std::forward<GMOCK_ARG_(tn, 1, \
__VA_ARGS__)>(gmock_a1), \
::std::forward<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(gmock_a2), \
::std::forward<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(gmock_a3), \
::std::forward<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(gmock_a4), \
::std::forward<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(gmock_a5), \
::std::forward<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(gmock_a6), \
::std::forward<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(gmock_a7), \
::std::forward<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(gmock_a8), \
::std::forward<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(gmock_a9), \
::std::forward<GMOCK_ARG_(tn, 10, __VA_ARGS__)>(gmock_a10)); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \
GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \
GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \
GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \
GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \
GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \
GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \
GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \
GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \
GMOCK_MATCHER_(tn, 10, \
__VA_ARGS__) gmock_a10) constness { \
GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \
gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \
gmock_a10); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method(::testing::A<GMOCK_ARG_(tn, 1, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 2, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 3, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 4, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 5, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 6, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 7, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 8, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 9, __VA_ARGS__)>(), \
::testing::A<GMOCK_ARG_(tn, 10, __VA_ARGS__)>()); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \
Method)
#define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__)
#define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__)
#define MOCK_METHOD2(m, ...) GMOCK_METHOD2_(, , , m, __VA_ARGS__)
#define MOCK_METHOD3(m, ...) GMOCK_METHOD3_(, , , m, __VA_ARGS__)
#define MOCK_METHOD4(m, ...) GMOCK_METHOD4_(, , , m, __VA_ARGS__)
#define MOCK_METHOD5(m, ...) GMOCK_METHOD5_(, , , m, __VA_ARGS__)
#define MOCK_METHOD6(m, ...) GMOCK_METHOD6_(, , , m, __VA_ARGS__)
#define MOCK_METHOD7(m, ...) GMOCK_METHOD7_(, , , m, __VA_ARGS__)
#define MOCK_METHOD8(m, ...) GMOCK_METHOD8_(, , , m, __VA_ARGS__)
#define MOCK_METHOD9(m, ...) GMOCK_METHOD9_(, , , m, __VA_ARGS__)
#define MOCK_METHOD10(m, ...) GMOCK_METHOD10_(, , , m, __VA_ARGS__)
#define MOCK_CONST_METHOD0(m, ...) GMOCK_METHOD0_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD1(m, ...) GMOCK_METHOD1_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD2(m, ...) GMOCK_METHOD2_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD3(m, ...) GMOCK_METHOD3_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD4(m, ...) GMOCK_METHOD4_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD5(m, ...) GMOCK_METHOD5_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD6(m, ...) GMOCK_METHOD6_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD7(m, ...) GMOCK_METHOD7_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD8(m, ...) GMOCK_METHOD8_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD9(m, ...) GMOCK_METHOD9_(, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD10(m, ...) GMOCK_METHOD10_(, const, , m, __VA_ARGS__)
#define MOCK_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__)
#define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_T(m, ...) \
GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_T(m, ...) \
GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_T(m, ...) \
GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_T(m, ...) \
GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_T(m, ...) \
GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_T(m, ...) \
GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_T(m, ...) \
GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_T(m, ...) \
GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_T(m, ...) \
GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_T(m, ...) \
GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_T(m, ...) \
GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__)
#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD0_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD1_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD2_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD3_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD4_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD5_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD6_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD7_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD8_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD9_(, , ct, m, __VA_ARGS__)
#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD10_(, , ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__)
#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__)
#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__)
#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__)
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_

View File

@@ -1,227 +0,0 @@
$$ -*- mode: c++; -*-
$$ This is a Pump source file. Please use Pump to convert
$$ it to gmock-generated-function-mockers.h.
$$
$var n = 10 $$ The maximum arity we support.
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements function mockers of various arities.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
#include <functional>
#include <utility>
#include "gmock/gmock-spec-builders.h"
#include "gmock/internal/gmock-internal-utils.h"
namespace testing {
namespace internal {
$range i 0..n
// Removes the given pointer; this is a helper for the expectation setter method
// for parameterless matchers.
//
// We want to make sure that the user cannot set a parameterless expectation on
// overloaded methods, including methods which are overloaded on const. Example:
//
// class MockClass {
// MOCK_METHOD0(GetName, string&());
// MOCK_CONST_METHOD0(GetName, const string&());
// };
//
// TEST() {
// // This should be an error, as it's not clear which overload is expected.
// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value));
// }
//
// Here are the generated expectation-setter methods:
//
// class MockClass {
// // Overload 1
// MockSpec<string&()> gmock_GetName() { ... }
// // Overload 2. Declared const so that the compiler will generate an
// // error when trying to resolve between this and overload 4 in
// // 'gmock_GetName(WithoutMatchers(), nullptr)'.
// MockSpec<string&()> gmock_GetName(
// const WithoutMatchers&, const Function<string&()>*) const {
// // Removes const from this, calls overload 1
// return AdjustConstness_(this)->gmock_GetName();
// }
//
// // Overload 3
// const string& gmock_GetName() const { ... }
// // Overload 4
// MockSpec<const string&()> gmock_GetName(
// const WithoutMatchers&, const Function<const string&()>*) const {
// // Does not remove const, calls overload 3
// return AdjustConstness_const(this)->gmock_GetName();
// }
// }
//
template <typename MockType>
const MockType* AdjustConstness_const(const MockType* mock) {
return mock;
}
// Removes const from and returns the given pointer; this is a helper for the
// expectation setter method for parameterless matchers.
template <typename MockType>
MockType* AdjustConstness_(const MockType* mock) {
return const_cast<MockType*>(mock);
}
} // namespace internal
// The style guide prohibits "using" statements in a namespace scope
// inside a header file. However, the FunctionMocker class template
// is meant to be defined in the ::testing namespace. The following
// line is just a trick for working around a bug in MSVC 8.0, which
// cannot handle it if we define FunctionMocker in ::testing.
using internal::FunctionMocker;
// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
// We define this as a variadic macro in case F contains unprotected
// commas (the same reason that we use variadic macros in other places
// in this file).
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_RESULT_(tn, ...) \
tn ::testing::internal::Function<__VA_ARGS__>::Result
// The type of argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_ARG_(tn, N, ...) \
tn ::testing::internal::Function<__VA_ARGS__>::template Arg<N-1>::type
// The matcher type for argument N of the given function type.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_MATCHER_(tn, N, ...) \
const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
// The variable for mocking the given method.
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_MOCKER_(arity, constness, Method) \
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
$for i [[
$range j 1..i
$var arg_as = [[$for j, [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
$var as = [[$for j, \
[[::std::forward<GMOCK_ARG_(tn, $j, __VA_ARGS__)>(gmock_a$j)]]]]
$var matcher_arg_as = [[$for j, \
[[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
$var matcher_as = [[$for j, [[gmock_a$j]]]]
$var anything_matchers = [[$for j, \
[[::testing::A<GMOCK_ARG_(tn, $j, __VA_ARGS__)>()]]]]
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \
static_assert($i == ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, "MOCK_METHOD<N> must match argument count.");\
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
$arg_as) constness { \
GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \
return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \
} \
::testing::MockSpec<__VA_ARGS__> \
gmock_##Method($matcher_arg_as) constness { \
GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \
return GMOCK_MOCKER_($i, constness, Method).With($matcher_as); \
} \
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
const ::testing::internal::WithoutMatchers&, \
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
return ::testing::internal::AdjustConstness_##constness(this)-> \
gmock_##Method($anything_matchers); \
} \
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method)
]]
$for i [[
#define MOCK_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, , , m, __VA_ARGS__)
]]
$for i [[
#define MOCK_CONST_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, const, , m, __VA_ARGS__)
]]
$for i [[
#define MOCK_METHOD$i[[]]_T(m, ...) GMOCK_METHOD$i[[]]_(typename, , , m, __VA_ARGS__)
]]
$for i [[
#define MOCK_CONST_METHOD$i[[]]_T(m, ...) \
GMOCK_METHOD$i[[]]_(typename, const, , m, __VA_ARGS__)
]]
$for i [[
#define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD$i[[]]_(, , ct, m, __VA_ARGS__)
]]
$for i [[
#define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD$i[[]]_(, const, ct, m, __VA_ARGS__)
]]
$for i [[
#define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD$i[[]]_(typename, , ct, m, __VA_ARGS__)
]]
$for i [[
#define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
GMOCK_METHOD$i[[]]_(typename, const, ct, m, __VA_ARGS__)
]]
} // namespace testing
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_

File diff suppressed because it is too large Load Diff

View File

@@ -1,346 +0,0 @@
$$ -*- mode: c++; -*-
$$ This is a Pump source file. Please use Pump to convert
$$ it to gmock-generated-matchers.h.
$$
$var n = 10 $$ The maximum arity we support.
$$ }} This line fixes auto-indentation of the following code in Emacs.
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file implements some commonly used variadic matchers.
// GOOGLETEST_CM0002 DO NOT DELETE
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
#include <iterator>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock-matchers.h"
// The MATCHER* family of macros can be used in a namespace scope to
// define custom matchers easily.
//
// Basic Usage
// ===========
//
// The syntax
//
// MATCHER(name, description_string) { statements; }
//
// defines a matcher with the given name that executes the statements,
// which must return a bool to indicate if the match succeeds. Inside
// the statements, you can refer to the value being matched by 'arg',
// and refer to its type by 'arg_type'.
//
// The description string documents what the matcher does, and is used
// to generate the failure message when the match fails. Since a
// MATCHER() is usually defined in a header file shared by multiple
// C++ source files, we require the description to be a C-string
// literal to avoid possible side effects. It can be empty, in which
// case we'll use the sequence of words in the matcher name as the
// description.
//
// For example:
//
// MATCHER(IsEven, "") { return (arg % 2) == 0; }
//
// allows you to write
//
// // Expects mock_foo.Bar(n) to be called where n is even.
// EXPECT_CALL(mock_foo, Bar(IsEven()));
//
// or,
//
// // Verifies that the value of some_expression is even.
// EXPECT_THAT(some_expression, IsEven());
//
// If the above assertion fails, it will print something like:
//
// Value of: some_expression
// Expected: is even
// Actual: 7
//
// where the description "is even" is automatically calculated from the
// matcher name IsEven.
//
// Argument Type
// =============
//
// Note that the type of the value being matched (arg_type) is
// determined by the context in which you use the matcher and is
// supplied to you by the compiler, so you don't need to worry about
// declaring it (nor can you). This allows the matcher to be
// polymorphic. For example, IsEven() can be used to match any type
// where the value of "(arg % 2) == 0" can be implicitly converted to
// a bool. In the "Bar(IsEven())" example above, if method Bar()
// takes an int, 'arg_type' will be int; if it takes an unsigned long,
// 'arg_type' will be unsigned long; and so on.
//
// Parameterizing Matchers
// =======================
//
// Sometimes you'll want to parameterize the matcher. For that you
// can use another macro:
//
// MATCHER_P(name, param_name, description_string) { statements; }
//
// For example:
//
// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
//
// will allow you to write:
//
// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
//
// which may lead to this message (assuming n is 10):
//
// Value of: Blah("a")
// Expected: has absolute value 10
// Actual: -9
//
// Note that both the matcher description and its parameter are
// printed, making the message human-friendly.
//
// In the matcher definition body, you can write 'foo_type' to
// reference the type of a parameter named 'foo'. For example, in the
// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
// 'value_type' to refer to the type of 'value'.
//
// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
// support multi-parameter matchers.
//
// Describing Parameterized Matchers
// =================================
//
// The last argument to MATCHER*() is a string-typed expression. The
// expression can reference all of the matcher's parameters and a
// special bool-typed variable named 'negation'. When 'negation' is
// false, the expression should evaluate to the matcher's description;
// otherwise it should evaluate to the description of the negation of
// the matcher. For example,
//
// using testing::PrintToString;
//
// MATCHER_P2(InClosedRange, low, hi,
// std::string(negation ? "is not" : "is") + " in range [" +
// PrintToString(low) + ", " + PrintToString(hi) + "]") {
// return low <= arg && arg <= hi;
// }
// ...
// EXPECT_THAT(3, InClosedRange(4, 6));
// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
//
// would generate two failures that contain the text:
//
// Expected: is in range [4, 6]
// ...
// Expected: is not in range [2, 4]
//
// If you specify "" as the description, the failure message will
// contain the sequence of words in the matcher name followed by the
// parameter values printed as a tuple. For example,
//
// MATCHER_P2(InClosedRange, low, hi, "") { ... }
// ...
// EXPECT_THAT(3, InClosedRange(4, 6));
// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
//
// would generate two failures that contain the text:
//
// Expected: in closed range (4, 6)
// ...
// Expected: not (in closed range (2, 4))
//
// Types of Matcher Parameters
// ===========================
//
// For the purpose of typing, you can view
//
// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
//
// as shorthand for
//
// template <typename p1_type, ..., typename pk_type>
// FooMatcherPk<p1_type, ..., pk_type>
// Foo(p1_type p1, ..., pk_type pk) { ... }
//
// When you write Foo(v1, ..., vk), the compiler infers the types of
// the parameters v1, ..., and vk for you. If you are not happy with
// the result of the type inference, you can specify the types by
// explicitly instantiating the template, as in Foo<long, bool>(5,
// false). As said earlier, you don't get to (or need to) specify
// 'arg_type' as that's determined by the context in which the matcher
// is used. You can assign the result of expression Foo(p1, ..., pk)
// to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
// can be useful when composing matchers.
//
// While you can instantiate a matcher template with reference types,
// passing the parameters by pointer usually makes your code more
// readable. If, however, you still want to pass a parameter by
// reference, be aware that in the failure message generated by the
// matcher you will see the value of the referenced object but not its
// address.
//
// Explaining Match Results
// ========================
//
// Sometimes the matcher description alone isn't enough to explain why
// the match has failed or succeeded. For example, when expecting a
// long string, it can be very helpful to also print the diff between
// the expected string and the actual one. To achieve that, you can
// optionally stream additional information to a special variable
// named result_listener, whose type is a pointer to class
// MatchResultListener:
//
// MATCHER_P(EqualsLongString, str, "") {
// if (arg == str) return true;
//
// *result_listener << "the difference: "
/// << DiffStrings(str, arg);
// return false;
// }
//
// Overloading Matchers
// ====================
//
// You can overload matchers with different numbers of parameters:
//
// MATCHER_P(Blah, a, description_string1) { ... }
// MATCHER_P2(Blah, a, b, description_string2) { ... }
//
// Caveats
// =======
//
// When defining a new matcher, you should also consider implementing
// MatcherInterface or using MakePolymorphicMatcher(). These
// approaches require more work than the MATCHER* macros, but also
// give you more control on the types of the value being matched and
// the matcher parameters, which may leads to better compiler error
// messages when the matcher is used wrong. They also allow
// overloading matchers based on parameter types (as opposed to just
// based on the number of parameters).
//
// MATCHER*() can only be used in a namespace scope as templates cannot be
// declared inside of a local class.
//
// More Information
// ================
//
// To learn more about using these macros, please search for 'MATCHER'
// on
// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
$range i 0..n
$for i
[[
$var macro_name = [[$if i==0 [[MATCHER]] $elif i==1 [[MATCHER_P]]
$else [[MATCHER_P$i]]]]
$var class_name = [[name##Matcher[[$if i==0 [[]] $elif i==1 [[P]]
$else [[P$i]]]]]]
$range j 0..i-1
$var template = [[$if i==0 [[]] $else [[
template <$for j, [[typename p$j##_type]]>\
]]]]
$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
$var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]]
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]]
$var params = [[$for j, [[p$j]]]]
$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
$var param_field_decls = [[$for j
[[
p$j##_type const p$j;\
]]]]
$var param_field_decls2 = [[$for j
[[
p$j##_type const p$j;\
]]]]
#define $macro_name(name$for j [[, p$j]], description)\$template
class $class_name {\
public:\
template <typename arg_type>\
class gmock_Impl : public ::testing::MatcherInterface<\
GTEST_REFERENCE_TO_CONST_(arg_type)> {\
public:\
[[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\
$impl_inits {}\
bool MatchAndExplain(\
GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
::testing::MatchResultListener* result_listener) const override;\
void DescribeTo(::std::ostream* gmock_os) const override {\
*gmock_os << FormatDescription(false);\
}\
void DescribeNegationTo(::std::ostream* gmock_os) const override {\
*gmock_os << FormatDescription(true);\
}\$param_field_decls
private:\
::std::string FormatDescription(bool negation) const {\
::std::string gmock_description = (description);\
if (!gmock_description.empty()) {\
return gmock_description;\
}\
return ::testing::internal::FormatMatcherDescription(\
negation, #name, \
::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
::std::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\
}\
};\
template <typename arg_type>\
operator ::testing::Matcher<arg_type>() const {\
return ::testing::Matcher<arg_type>(\
new gmock_Impl<arg_type>($params));\
}\
[[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\
}\$param_field_decls2
private:\
};\$template
inline $class_name$param_types name($param_types_and_names) {\
return $class_name$param_types($params);\
}\$template
template <typename arg_type>\
bool $class_name$param_types::gmock_Impl<arg_type>::MatchAndExplain(\
GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
const
]]
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_

View File

@@ -30,7 +30,220 @@
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements some commonly used argument matchers. More // The MATCHER* family of macros can be used in a namespace scope to
// define custom matchers easily.
//
// Basic Usage
// ===========
//
// The syntax
//
// MATCHER(name, description_string) { statements; }
//
// defines a matcher with the given name that executes the statements,
// which must return a bool to indicate if the match succeeds. Inside
// the statements, you can refer to the value being matched by 'arg',
// and refer to its type by 'arg_type'.
//
// The description string documents what the matcher does, and is used
// to generate the failure message when the match fails. Since a
// MATCHER() is usually defined in a header file shared by multiple
// C++ source files, we require the description to be a C-string
// literal to avoid possible side effects. It can be empty, in which
// case we'll use the sequence of words in the matcher name as the
// description.
//
// For example:
//
// MATCHER(IsEven, "") { return (arg % 2) == 0; }
//
// allows you to write
//
// // Expects mock_foo.Bar(n) to be called where n is even.
// EXPECT_CALL(mock_foo, Bar(IsEven()));
//
// or,
//
// // Verifies that the value of some_expression is even.
// EXPECT_THAT(some_expression, IsEven());
//
// If the above assertion fails, it will print something like:
//
// Value of: some_expression
// Expected: is even
// Actual: 7
//
// where the description "is even" is automatically calculated from the
// matcher name IsEven.
//
// Argument Type
// =============
//
// Note that the type of the value being matched (arg_type) is
// determined by the context in which you use the matcher and is
// supplied to you by the compiler, so you don't need to worry about
// declaring it (nor can you). This allows the matcher to be
// polymorphic. For example, IsEven() can be used to match any type
// where the value of "(arg % 2) == 0" can be implicitly converted to
// a bool. In the "Bar(IsEven())" example above, if method Bar()
// takes an int, 'arg_type' will be int; if it takes an unsigned long,
// 'arg_type' will be unsigned long; and so on.
//
// Parameterizing Matchers
// =======================
//
// Sometimes you'll want to parameterize the matcher. For that you
// can use another macro:
//
// MATCHER_P(name, param_name, description_string) { statements; }
//
// For example:
//
// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
//
// will allow you to write:
//
// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
//
// which may lead to this message (assuming n is 10):
//
// Value of: Blah("a")
// Expected: has absolute value 10
// Actual: -9
//
// Note that both the matcher description and its parameter are
// printed, making the message human-friendly.
//
// In the matcher definition body, you can write 'foo_type' to
// reference the type of a parameter named 'foo'. For example, in the
// body of MATCHER_P(HasAbsoluteValue, value) above, you can write
// 'value_type' to refer to the type of 'value'.
//
// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to
// support multi-parameter matchers.
//
// Describing Parameterized Matchers
// =================================
//
// The last argument to MATCHER*() is a string-typed expression. The
// expression can reference all of the matcher's parameters and a
// special bool-typed variable named 'negation'. When 'negation' is
// false, the expression should evaluate to the matcher's description;
// otherwise it should evaluate to the description of the negation of
// the matcher. For example,
//
// using testing::PrintToString;
//
// MATCHER_P2(InClosedRange, low, hi,
// std::string(negation ? "is not" : "is") + " in range [" +
// PrintToString(low) + ", " + PrintToString(hi) + "]") {
// return low <= arg && arg <= hi;
// }
// ...
// EXPECT_THAT(3, InClosedRange(4, 6));
// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
//
// would generate two failures that contain the text:
//
// Expected: is in range [4, 6]
// ...
// Expected: is not in range [2, 4]
//
// If you specify "" as the description, the failure message will
// contain the sequence of words in the matcher name followed by the
// parameter values printed as a tuple. For example,
//
// MATCHER_P2(InClosedRange, low, hi, "") { ... }
// ...
// EXPECT_THAT(3, InClosedRange(4, 6));
// EXPECT_THAT(3, Not(InClosedRange(2, 4)));
//
// would generate two failures that contain the text:
//
// Expected: in closed range (4, 6)
// ...
// Expected: not (in closed range (2, 4))
//
// Types of Matcher Parameters
// ===========================
//
// For the purpose of typing, you can view
//
// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
//
// as shorthand for
//
// template <typename p1_type, ..., typename pk_type>
// FooMatcherPk<p1_type, ..., pk_type>
// Foo(p1_type p1, ..., pk_type pk) { ... }
//
// When you write Foo(v1, ..., vk), the compiler infers the types of
// the parameters v1, ..., and vk for you. If you are not happy with
// the result of the type inference, you can specify the types by
// explicitly instantiating the template, as in Foo<long, bool>(5,
// false). As said earlier, you don't get to (or need to) specify
// 'arg_type' as that's determined by the context in which the matcher
// is used. You can assign the result of expression Foo(p1, ..., pk)
// to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This
// can be useful when composing matchers.
//
// While you can instantiate a matcher template with reference types,
// passing the parameters by pointer usually makes your code more
// readable. If, however, you still want to pass a parameter by
// reference, be aware that in the failure message generated by the
// matcher you will see the value of the referenced object but not its
// address.
//
// Explaining Match Results
// ========================
//
// Sometimes the matcher description alone isn't enough to explain why
// the match has failed or succeeded. For example, when expecting a
// long string, it can be very helpful to also print the diff between
// the expected string and the actual one. To achieve that, you can
// optionally stream additional information to a special variable
// named result_listener, whose type is a pointer to class
// MatchResultListener:
//
// MATCHER_P(EqualsLongString, str, "") {
// if (arg == str) return true;
//
// *result_listener << "the difference: "
/// << DiffStrings(str, arg);
// return false;
// }
//
// Overloading Matchers
// ====================
//
// You can overload matchers with different numbers of parameters:
//
// MATCHER_P(Blah, a, description_string1) { ... }
// MATCHER_P2(Blah, a, b, description_string2) { ... }
//
// Caveats
// =======
//
// When defining a new matcher, you should also consider implementing
// MatcherInterface or using MakePolymorphicMatcher(). These
// approaches require more work than the MATCHER* macros, but also
// give you more control on the types of the value being matched and
// the matcher parameters, which may leads to better compiler error
// messages when the matcher is used wrong. They also allow
// overloading matchers based on parameter types (as opposed to just
// based on the number of parameters).
//
// MATCHER*() can only be used in a namespace scope as templates cannot be
// declared inside of a local class.
//
// More Information
// ================
//
// To learn more about using these macros, please search for 'MATCHER'
// on
// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md
//
// This file also implements some commonly used argument matchers. More
// matchers can be defined by the user implementing the // matchers can be defined by the user implementing the
// MatcherInterface<T> interface if necessary. // MatcherInterface<T> interface if necessary.
// //
@@ -57,6 +270,7 @@
#include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gmock/internal/gmock-pp.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
// MSVC warning C5046 is new as of VS2017 version 15.8. // MSVC warning C5046 is new as of VS2017 version 15.8.
@@ -236,6 +450,50 @@ class MatcherCastImpl<T, Matcher<T> > {
static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; } static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
}; };
// Template specialization for parameterless Matcher.
template <typename Derived>
class MatcherBaseImpl {
public:
MatcherBaseImpl() = default;
template <typename T>
operator ::testing::Matcher<T>() const { // NOLINT(runtime/explicit)
return ::testing::Matcher<T>(new
typename Derived::template gmock_Impl<T>());
}
};
// Template specialization for Matcher with parameters.
template <template <typename...> class Derived, typename... Ts>
class MatcherBaseImpl<Derived<Ts...>> {
public:
// Mark the constructor explicit for single argument T to avoid implicit
// conversions.
template <typename E = std::enable_if<sizeof...(Ts) == 1>,
typename E::type* = nullptr>
explicit MatcherBaseImpl(Ts... params)
: params_(std::forward<Ts>(params)...) {}
template <typename E = std::enable_if<sizeof...(Ts) != 1>,
typename = typename E::type>
MatcherBaseImpl(Ts... params) // NOLINT
: params_(std::forward<Ts>(params)...) {}
template <typename F>
operator ::testing::Matcher<F>() const { // NOLINT(runtime/explicit)
return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
}
private:
template <typename F, std::size_t... tuple_ids>
::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const {
return ::testing::Matcher<F>(
new typename Derived<Ts...>::template gmock_Impl<F>(
std::get<tuple_ids>(params_)...));
}
const std::tuple<Ts...> params_;
};
} // namespace internal } // namespace internal
// In order to be safe and clear, casting between different matcher // In order to be safe and clear, casting between different matcher
@@ -648,15 +906,15 @@ class StrEqualityMatcher {
bool case_sensitive) bool case_sensitive)
: string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
bool MatchAndExplain(const absl::string_view& s, bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const { MatchResultListener* listener) const {
// This should fail to compile if absl::string_view is used with wide // This should fail to compile if StringView is used with wide
// strings. // strings.
const StringType& str = std::string(s); const StringType& str = std::string(s);
return MatchAndExplain(str, listener); return MatchAndExplain(str, listener);
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly: // Accepts pointer types, particularly:
// const char* // const char*
@@ -674,11 +932,11 @@ class StrEqualityMatcher {
// Matches anything that can convert to StringType. // Matches anything that can convert to StringType.
// //
// This is a template, not just a plain function with const StringType&, // This is a template, not just a plain function with const StringType&,
// because absl::string_view has some interfering non-explicit constructors. // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType> template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s, bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const { MatchResultListener* /* listener */) const {
const StringType& s2(s); const StringType s2(s);
const bool eq = case_sensitive_ ? s2 == string_ : const bool eq = case_sensitive_ ? s2 == string_ :
CaseInsensitiveStringEquals(s2, string_); CaseInsensitiveStringEquals(s2, string_);
return expect_eq_ == eq; return expect_eq_ == eq;
@@ -718,15 +976,15 @@ class HasSubstrMatcher {
explicit HasSubstrMatcher(const StringType& substring) explicit HasSubstrMatcher(const StringType& substring)
: substring_(substring) {} : substring_(substring) {}
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
bool MatchAndExplain(const absl::string_view& s, bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const { MatchResultListener* listener) const {
// This should fail to compile if absl::string_view is used with wide // This should fail to compile if StringView is used with wide
// strings. // strings.
const StringType& str = std::string(s); const StringType& str = std::string(s);
return MatchAndExplain(str, listener); return MatchAndExplain(str, listener);
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly: // Accepts pointer types, particularly:
// const char* // const char*
@@ -741,7 +999,7 @@ class HasSubstrMatcher {
// Matches anything that can convert to StringType. // Matches anything that can convert to StringType.
// //
// This is a template, not just a plain function with const StringType&, // This is a template, not just a plain function with const StringType&,
// because absl::string_view has some interfering non-explicit constructors. // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType> template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s, bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const { MatchResultListener* /* listener */) const {
@@ -774,15 +1032,15 @@ class StartsWithMatcher {
explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
} }
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
bool MatchAndExplain(const absl::string_view& s, bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const { MatchResultListener* listener) const {
// This should fail to compile if absl::string_view is used with wide // This should fail to compile if StringView is used with wide
// strings. // strings.
const StringType& str = std::string(s); const StringType& str = std::string(s);
return MatchAndExplain(str, listener); return MatchAndExplain(str, listener);
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly: // Accepts pointer types, particularly:
// const char* // const char*
@@ -797,7 +1055,7 @@ class StartsWithMatcher {
// Matches anything that can convert to StringType. // Matches anything that can convert to StringType.
// //
// This is a template, not just a plain function with const StringType&, // This is a template, not just a plain function with const StringType&,
// because absl::string_view has some interfering non-explicit constructors. // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType> template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s, bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const { MatchResultListener* /* listener */) const {
@@ -830,15 +1088,15 @@ class EndsWithMatcher {
public: public:
explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
bool MatchAndExplain(const absl::string_view& s, bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const { MatchResultListener* listener) const {
// This should fail to compile if absl::string_view is used with wide // This should fail to compile if StringView is used with wide
// strings. // strings.
const StringType& str = std::string(s); const StringType& str = std::string(s);
return MatchAndExplain(str, listener); return MatchAndExplain(str, listener);
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly: // Accepts pointer types, particularly:
// const char* // const char*
@@ -853,7 +1111,7 @@ class EndsWithMatcher {
// Matches anything that can convert to StringType. // Matches anything that can convert to StringType.
// //
// This is a template, not just a plain function with const StringType&, // This is a template, not just a plain function with const StringType&,
// because absl::string_view has some interfering non-explicit constructors. // because StringView has some interfering non-explicit constructors.
template <typename MatcheeStringType> template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s, bool MatchAndExplain(const MatcheeStringType& s,
MatchResultListener* /* listener */) const { MatchResultListener* /* listener */) const {
@@ -3169,6 +3427,8 @@ class BoundSecondMatcher {
BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second) BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
: tuple2_matcher_(tm), second_value_(second) {} : tuple2_matcher_(tm), second_value_(second) {}
BoundSecondMatcher(const BoundSecondMatcher& other) = default;
template <typename T> template <typename T>
operator Matcher<T>() const { operator Matcher<T>() const {
return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_)); return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
@@ -4044,11 +4304,7 @@ template <typename Container>
inline PolymorphicMatcher<internal::ContainerEqMatcher< inline PolymorphicMatcher<internal::ContainerEqMatcher<
typename std::remove_const<Container>::type>> typename std::remove_const<Container>::type>>
ContainerEq(const Container& rhs) { ContainerEq(const Container& rhs) {
// This following line is for working around a bug in MSVC 8.0, return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
// which causes Container to be a const type sometimes.
typedef typename std::remove_const<Container>::type RawContainer;
return MakePolymorphicMatcher(
internal::ContainerEqMatcher<RawContainer>(rhs));
} }
// Returns a matcher that matches a container that, when sorted using // Returns a matcher that matches a container that, when sorted using
@@ -4081,12 +4337,8 @@ template <typename TupleMatcher, typename Container>
inline internal::PointwiseMatcher<TupleMatcher, inline internal::PointwiseMatcher<TupleMatcher,
typename std::remove_const<Container>::type> typename std::remove_const<Container>::type>
Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
// This following line is for working around a bug in MSVC 8.0, return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,
// which causes Container to be a const type sometimes (e.g. when rhs);
// rhs is a const int[])..
typedef typename std::remove_const<Container>::type RawContainer;
return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
tuple_matcher, rhs);
} }
@@ -4117,14 +4369,9 @@ inline internal::UnorderedElementsAreArrayMatcher<
typename std::remove_const<RhsContainer>::type>::type::value_type>> typename std::remove_const<RhsContainer>::type>::type::value_type>>
UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
const RhsContainer& rhs_container) { const RhsContainer& rhs_container) {
// This following line is for working around a bug in MSVC 8.0,
// which causes RhsContainer to be a const type sometimes (e.g. when
// rhs_container is a const int[]).
typedef typename std::remove_const<RhsContainer>::type RawRhsContainer;
// RhsView allows the same code to handle RhsContainer being a // RhsView allows the same code to handle RhsContainer being a
// STL-style container and it being a native C-style array. // STL-style container and it being a native C-style array.
typedef typename internal::StlContainerView<RawRhsContainer> RhsView; typedef typename internal::StlContainerView<RhsContainer> RhsView;
typedef typename RhsView::type RhsStlContainer; typedef typename RhsView::type RhsStlContainer;
typedef typename RhsStlContainer::value_type Second; typedef typename RhsStlContainer::value_type Second;
const RhsStlContainer& rhs_stl_container = const RhsStlContainer& rhs_stl_container =
@@ -4566,6 +4813,156 @@ PolymorphicMatcher<internal::variant_matcher::VariantMatcher<T> > VariantWith(
#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\ #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
// MATCHER* macroses itself are listed below.
#define MATCHER(name, description) \
class name##Matcher \
: public ::testing::internal::MatcherBaseImpl<name##Matcher> { \
public: \
template <typename arg_type> \
class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
public: \
gmock_Impl() {} \
bool MatchAndExplain( \
const arg_type& arg, \
::testing::MatchResultListener* result_listener) const override; \
void DescribeTo(::std::ostream* gmock_os) const override { \
*gmock_os << FormatDescription(false); \
} \
void DescribeNegationTo(::std::ostream* gmock_os) const override { \
*gmock_os << FormatDescription(true); \
} \
\
private: \
::std::string FormatDescription(bool negation) const { \
::std::string gmock_description = (description); \
if (!gmock_description.empty()) { \
return gmock_description; \
} \
return ::testing::internal::FormatMatcherDescription(negation, #name, \
{}); \
} \
}; \
}; \
GTEST_ATTRIBUTE_UNUSED_ inline name##Matcher name() { return {}; } \
template <typename arg_type> \
bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain( \
const arg_type& arg, \
::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \
const
#define MATCHER_P(name, p0, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (p0))
#define MATCHER_P2(name, p0, p1, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (p0, p1))
#define MATCHER_P3(name, p0, p1, p2, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (p0, p1, p2))
#define MATCHER_P4(name, p0, p1, p2, p3, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, (p0, p1, p2, p3))
#define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \
(p0, p1, p2, p3, p4))
#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description, \
(p0, p1, p2, p3, p4, p5))
#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description, \
(p0, p1, p2, p3, p4, p5, p6))
#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description, \
(p0, p1, p2, p3, p4, p5, p6, p7))
#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description, \
(p0, p1, p2, p3, p4, p5, p6, p7, p8))
#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \
GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description, \
(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))
#define GMOCK_INTERNAL_MATCHER(name, full_name, description, args) \
template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
class full_name : public ::testing::internal::MatcherBaseImpl< \
full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \
public: \
using full_name::MatcherBaseImpl::MatcherBaseImpl; \
template <typename arg_type> \
class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> { \
public: \
explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) \
: GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {} \
bool MatchAndExplain( \
const arg_type& arg, \
::testing::MatchResultListener* result_listener) const override; \
void DescribeTo(::std::ostream* gmock_os) const override { \
*gmock_os << FormatDescription(false); \
} \
void DescribeNegationTo(::std::ostream* gmock_os) const override { \
*gmock_os << FormatDescription(true); \
} \
GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
\
private: \
::std::string FormatDescription(bool negation) const { \
::std::string gmock_description = (description); \
if (!gmock_description.empty()) { \
return gmock_description; \
} \
return ::testing::internal::FormatMatcherDescription( \
negation, #name, \
::testing::internal::UniversalTersePrintTupleFieldsToStrings( \
::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args)))); \
} \
}; \
}; \
template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name( \
GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) { \
return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>( \
GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args)); \
} \
template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)> \
template <typename arg_type> \
bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl< \
arg_type>::MatchAndExplain(const arg_type& arg, \
::testing::MatchResultListener* \
result_listener GTEST_ATTRIBUTE_UNUSED_) \
const
#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \
GMOCK_PP_TAIL( \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))
#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \
, typename arg##_type
#define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))
#define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \
, arg##_type
#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \
GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH( \
GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))
#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \
, arg##_type gmock_p##i
#define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))
#define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \
, arg(::std::forward<arg##_type>(gmock_p##i))
#define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)
#define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \
const arg##_type arg;
#define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))
#define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg
#define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \
GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))
#define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \
, gmock_p##i
} // namespace testing } // namespace testing
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046

View File

@@ -30,7 +30,7 @@
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file implements some matchers that depend on gmock-generated-matchers.h. // This file implements some matchers that depend on gmock-matchers.h.
// //
// Note that tests are implemented in gmock-matchers_test.cc rather than // Note that tests are implemented in gmock-matchers_test.cc rather than
// gmock-more-matchers-test.cc. // gmock-more-matchers-test.cc.
@@ -40,7 +40,7 @@
#ifndef GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ #ifndef GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
#define GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
#include "gmock/gmock-generated-matchers.h" #include "gmock/gmock-matchers.h"
namespace testing { namespace testing {

View File

@@ -1350,12 +1350,6 @@ class ReferenceOrValueWrapper<T&> {
T* value_ptr_; T* value_ptr_;
}; };
// MSVC warns about using 'this' in base member initializer list, so
// we need to temporarily disable the warning. We have to do it for
// the entire class to suppress the warning, even though it's about
// the constructor only.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
// C++ treats the void type specially. For example, you cannot define // C++ treats the void type specially. For example, you cannot define
// a void-typed variable or pass a void value to a function. // a void-typed variable or pass a void value to a function.
// ActionResultHolder<T> holds a value of type T, where T must be a // ActionResultHolder<T> holds a value of type T, where T must be a
@@ -1786,8 +1780,6 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
} }
}; // class FunctionMocker }; // class FunctionMocker
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355
// Reports an uninteresting call (whose description is in msg) in the // Reports an uninteresting call (whose description is in msg) in the
// manner specified by 'reaction'. // manner specified by 'reaction'.
void ReportUninterestingCall(CallReaction reaction, const std::string& msg); void ReportUninterestingCall(CallReaction reaction, const std::string& msg);

View File

@@ -60,8 +60,6 @@
#include "gmock/gmock-cardinalities.h" #include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-function-mocker.h" #include "gmock/gmock-function-mocker.h"
#include "gmock/gmock-generated-actions.h" #include "gmock/gmock-generated-actions.h"
#include "gmock/gmock-generated-function-mockers.h"
#include "gmock/gmock-generated-matchers.h"
#include "gmock/gmock-matchers.h" #include "gmock/gmock-matchers.h"
#include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-actions.h"
#include "gmock/gmock-more-matchers.h" #include "gmock/gmock-more-matchers.h"

View File

@@ -86,6 +86,14 @@
#define GMOCK_PP_IF(_Cond, _Then, _Else) \ #define GMOCK_PP_IF(_Cond, _Then, _Else) \
GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else)
// Similar to GMOCK_PP_IF but takes _Then and _Else in parentheses.
//
// GMOCK_PP_GENERIC_IF(1, (a, b, c), (d, e, f)) => a, b, c
// GMOCK_PP_GENERIC_IF(0, (a, b, c), (d, e, f)) => d, e, f
//
#define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \
GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else))
// Evaluates to the number of arguments after expansion. Identifies 'empty' as // Evaluates to the number of arguments after expansion. Identifies 'empty' as
// 0. // 0.
// //

File diff suppressed because it is too large Load Diff

View File

@@ -35,11 +35,11 @@ from cpp import utils
# Preserve compatibility with Python 2.3. # Preserve compatibility with Python 2.3.
try: try:
_dummy = set _dummy = set
except NameError: except NameError:
import sets import sets
set = sets.Set set = sets.Set
_VERSION = (1, 0, 1) # The version of this script. _VERSION = (1, 0, 1) # The version of this script.
# How many spaces to indent. Can set me with the INDENT environment variable. # How many spaces to indent. Can set me with the INDENT environment variable.
@@ -47,202 +47,199 @@ _INDENT = 2
def _RenderType(ast_type): def _RenderType(ast_type):
"""Renders the potentially recursively templated type into a string. """Renders the potentially recursively templated type into a string.
Args: Args:
ast_type: The AST of the type. ast_type: The AST of the type.
Returns: Returns:
Rendered string and a boolean to indicate whether we have multiple args Rendered string of the type.
(which is not handled correctly).
""" """
has_multiarg_error = False # Add modifiers like 'const'.
# Add modifiers like 'const'. modifiers = ''
modifiers = '' if ast_type.modifiers:
if ast_type.modifiers: modifiers = ' '.join(ast_type.modifiers) + ' '
modifiers = ' '.join(ast_type.modifiers) + ' ' return_type = modifiers + ast_type.name
return_type = modifiers + ast_type.name if ast_type.templated_types:
if ast_type.templated_types: # Collect template args.
# Collect template args. template_args = []
template_args = [] for arg in ast_type.templated_types:
for arg in ast_type.templated_types: rendered_arg = _RenderType(arg)
rendered_arg, e = _RenderType(arg) template_args.append(rendered_arg)
if e: has_multiarg_error = True return_type += '<' + ', '.join(template_args) + '>'
template_args.append(rendered_arg) if ast_type.pointer:
return_type += '<' + ', '.join(template_args) + '>' return_type += '*'
# We are actually not handling multi-template-args correctly. So mark it. if ast_type.reference:
if len(template_args) > 1: return_type += '&'
has_multiarg_error = True return return_type
if ast_type.pointer:
return_type += '*'
if ast_type.reference:
return_type += '&'
return return_type, has_multiarg_error
def _GetNumParameters(parameters, source): def _GenerateArg(source):
num_parameters = len(parameters) """Strips out comments, default arguments, and redundant spaces from a single argument.
if num_parameters == 1:
first_param = parameters[0] Args:
if source[first_param.start:first_param.end].strip() == 'void': source: A string for a single argument.
# We must treat T(void) as a function with no parameters.
return 0 Returns:
return num_parameters Rendered string of the argument.
"""
# Remove end of line comments before eliminating newlines.
arg = re.sub(r'//.*', '', source)
# Remove c-style comments.
arg = re.sub(r'/\*.*\*/', '', arg)
# Remove default arguments.
arg = re.sub(r'=.*', '', arg)
# Collapse spaces and newlines into a single space.
arg = re.sub(r'\s+', ' ', arg)
return arg.strip()
def _EscapeForMacro(s):
"""Escapes a string for use as an argument to a C++ macro."""
paren_count = 0
for c in s:
if c == '(':
paren_count += 1
elif c == ')':
paren_count -= 1
elif c == ',' and paren_count == 0:
return '(' + s + ')'
return s
def _GenerateMethods(output_lines, source, class_node): def _GenerateMethods(output_lines, source, class_node):
function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | function_type = (
ast.FUNCTION_OVERRIDE) ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | ast.FUNCTION_OVERRIDE)
ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
indent = ' ' * _INDENT indent = ' ' * _INDENT
for node in class_node.body: for node in class_node.body:
# We only care about virtual functions. # We only care about virtual functions.
if (isinstance(node, ast.Function) and if (isinstance(node, ast.Function) and node.modifiers & function_type and
node.modifiers & function_type and not node.modifiers & ctor_or_dtor):
not node.modifiers & ctor_or_dtor): # Pick out all the elements we need from the original function.
# Pick out all the elements we need from the original function. modifiers = 'override'
const = '' if node.modifiers & ast.FUNCTION_CONST:
if node.modifiers & ast.FUNCTION_CONST: modifiers = 'const, ' + modifiers
const = 'CONST_'
num_parameters = _GetNumParameters(node.parameters, source)
return_type = 'void'
if node.return_type:
return_type, has_multiarg_error = _RenderType(node.return_type)
if has_multiarg_error:
for line in [
'// The following line won\'t really compile, as the return',
'// type has multiple template arguments. To fix it, use a',
'// typedef for the return type.']:
output_lines.append(indent + line)
tmpl = ''
if class_node.templated_types:
tmpl = '_T'
mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl)
args = '' return_type = 'void'
if node.parameters: if node.return_type:
# Get the full text of the parameters from the start return_type = _EscapeForMacro(_RenderType(node.return_type))
# of the first parameter to the end of the last parameter.
start = node.parameters[0].start
end = node.parameters[-1].end
# Remove // comments.
args_strings = re.sub(r'//.*', '', source[start:end])
# Remove /* comments */.
args_strings = re.sub(r'/\*.*\*/', '', args_strings)
# Remove default arguments.
args_strings = re.sub(r'=.*,', ',', args_strings)
args_strings = re.sub(r'=.*', '', args_strings)
# Condense multiple spaces and eliminate newlines putting the
# parameters together on a single line. Ensure there is a
# space in an argument which is split by a newline without
# intervening whitespace, e.g.: int\nBar
args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
# Create the mock method definition. args = []
output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name), for p in node.parameters:
'%s%s(%s));' % (indent * 3, return_type, args)]) arg = _GenerateArg(source[p.start:p.end])
args.append(_EscapeForMacro(arg))
# Create the mock method definition.
output_lines.extend([
'%sMOCK_METHOD(%s, %s, (%s), (%s));' %
(indent, return_type, node.name, ', '.join(args), modifiers)
])
def _GenerateMocks(filename, source, ast_list, desired_class_names): def _GenerateMocks(filename, source, ast_list, desired_class_names):
processed_class_names = set() processed_class_names = set()
lines = [] lines = []
for node in ast_list: for node in ast_list:
if (isinstance(node, ast.Class) and node.body and if (isinstance(node, ast.Class) and node.body and
# desired_class_names being None means that all classes are selected. # desired_class_names being None means that all classes are selected.
(not desired_class_names or node.name in desired_class_names)): (not desired_class_names or node.name in desired_class_names)):
class_name = node.name class_name = node.name
parent_name = class_name parent_name = class_name
processed_class_names.add(class_name) processed_class_names.add(class_name)
class_node = node class_node = node
# Add namespace before the class. # Add namespace before the class.
if class_node.namespace: if class_node.namespace:
lines.extend(['namespace %s {' % n for n in class_node.namespace]) # } lines.extend(['namespace %s {' % n for n in class_node.namespace]) # }
lines.append('') lines.append('')
# Add template args for templated classes. # Add template args for templated classes.
if class_node.templated_types: if class_node.templated_types:
# TODO(paulchang): The AST doesn't preserve template argument order, # TODO(paulchang): The AST doesn't preserve template argument order,
# so we have to make up names here. # so we have to make up names here.
# TODO(paulchang): Handle non-type template arguments (e.g. # TODO(paulchang): Handle non-type template arguments (e.g.
# template<typename T, int N>). # template<typename T, int N>).
template_arg_count = len(class_node.templated_types.keys()) template_arg_count = len(class_node.templated_types.keys())
template_args = ['T%d' % n for n in range(template_arg_count)] template_args = ['T%d' % n for n in range(template_arg_count)]
template_decls = ['typename ' + arg for arg in template_args] template_decls = ['typename ' + arg for arg in template_args]
lines.append('template <' + ', '.join(template_decls) + '>') lines.append('template <' + ', '.join(template_decls) + '>')
parent_name += '<' + ', '.join(template_args) + '>' parent_name += '<' + ', '.join(template_args) + '>'
# Add the class prolog. # Add the class prolog.
lines.append('class Mock%s : public %s {' # } lines.append('class Mock%s : public %s {' # }
% (class_name, parent_name)) % (class_name, parent_name))
lines.append('%spublic:' % (' ' * (_INDENT // 2))) lines.append('%spublic:' % (' ' * (_INDENT // 2)))
# Add all the methods. # Add all the methods.
_GenerateMethods(lines, source, class_node) _GenerateMethods(lines, source, class_node)
# Close the class. # Close the class.
if lines: if lines:
# If there are no virtual methods, no need for a public label. # If there are no virtual methods, no need for a public label.
if len(lines) == 2: if len(lines) == 2:
del lines[-1] del lines[-1]
# Only close the class if there really is a class. # Only close the class if there really is a class.
lines.append('};') lines.append('};')
lines.append('') # Add an extra newline. lines.append('') # Add an extra newline.
# Close the namespace. # Close the namespace.
if class_node.namespace: if class_node.namespace:
for i in range(len(class_node.namespace) - 1, -1, -1): for i in range(len(class_node.namespace) - 1, -1, -1):
lines.append('} // namespace %s' % class_node.namespace[i]) lines.append('} // namespace %s' % class_node.namespace[i])
lines.append('') # Add an extra newline. lines.append('') # Add an extra newline.
if desired_class_names: if desired_class_names:
missing_class_name_list = list(desired_class_names - processed_class_names) missing_class_name_list = list(desired_class_names - processed_class_names)
if missing_class_name_list: if missing_class_name_list:
missing_class_name_list.sort() missing_class_name_list.sort()
sys.stderr.write('Class(es) not found in %s: %s\n' % sys.stderr.write('Class(es) not found in %s: %s\n' %
(filename, ', '.join(missing_class_name_list))) (filename, ', '.join(missing_class_name_list)))
elif not processed_class_names: elif not processed_class_names:
sys.stderr.write('No class found in %s\n' % filename) sys.stderr.write('No class found in %s\n' % filename)
return lines return lines
def main(argv=sys.argv): def main(argv=sys.argv):
if len(argv) < 2: if len(argv) < 2:
sys.stderr.write('Google Mock Class Generator v%s\n\n' % sys.stderr.write('Google Mock Class Generator v%s\n\n' %
'.'.join(map(str, _VERSION))) '.'.join(map(str, _VERSION)))
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
return 1 return 1
global _INDENT global _INDENT
try: try:
_INDENT = int(os.environ['INDENT']) _INDENT = int(os.environ['INDENT'])
except KeyError: except KeyError:
pass pass
except: except:
sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT')) sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
filename = argv[1] filename = argv[1]
desired_class_names = None # None means all classes in the source file. desired_class_names = None # None means all classes in the source file.
if len(argv) >= 3: if len(argv) >= 3:
desired_class_names = set(argv[2:]) desired_class_names = set(argv[2:])
source = utils.ReadFile(filename) source = utils.ReadFile(filename)
if source is None: if source is None:
return 1 return 1
builder = ast.BuilderFromSource(source, filename) builder = ast.BuilderFromSource(source, filename)
try: try:
entire_ast = filter(None, builder.Generate()) entire_ast = filter(None, builder.Generate())
except KeyboardInterrupt: except KeyboardInterrupt:
return return
except: except:
# An error message was already printed since we couldn't parse. # An error message was already printed since we couldn't parse.
sys.exit(1) sys.exit(1)
else: else:
lines = _GenerateMocks(filename, source, entire_ast, desired_class_names) lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
sys.stdout.write('\n'.join(lines)) sys.stdout.write('\n'.join(lines))
if __name__ == '__main__': if __name__ == '__main__':
main(sys.argv) main(sys.argv)

View File

@@ -29,43 +29,43 @@ from cpp import gmock_class
class TestCase(unittest.TestCase): class TestCase(unittest.TestCase):
"""Helper class that adds assert methods.""" """Helper class that adds assert methods."""
@staticmethod @staticmethod
def StripLeadingWhitespace(lines): def StripLeadingWhitespace(lines):
"""Strip leading whitespace in each line in 'lines'.""" """Strip leading whitespace in each line in 'lines'."""
return '\n'.join([s.lstrip() for s in lines.split('\n')]) return '\n'.join([s.lstrip() for s in lines.split('\n')])
def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines): def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines):
"""Specialized assert that ignores the indent level.""" """Specialized assert that ignores the indent level."""
self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines)) self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines))
class GenerateMethodsTest(TestCase): class GenerateMethodsTest(TestCase):
@staticmethod @staticmethod
def GenerateMethodSource(cpp_source): def GenerateMethodSource(cpp_source):
"""Convert C++ source to Google Mock output source lines.""" """Convert C++ source to Google Mock output source lines."""
method_source_lines = [] method_source_lines = []
# <test> is a pseudo-filename, it is not read or written. # <test> is a pseudo-filename, it is not read or written.
builder = ast.BuilderFromSource(cpp_source, '<test>') builder = ast.BuilderFromSource(cpp_source, '<test>')
ast_list = list(builder.Generate()) ast_list = list(builder.Generate())
gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0]) gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0])
return '\n'.join(method_source_lines) return '\n'.join(method_source_lines)
def testSimpleMethod(self): def testSimpleMethod(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual int Bar(); virtual int Bar();
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testSimpleConstructorsAndDestructor(self): def testSimpleConstructorsAndDestructor(self):
source = """ source = """
class Foo { class Foo {
public: public:
Foo(); Foo();
@@ -76,26 +76,26 @@ class Foo {
virtual int Bar() = 0; virtual int Bar() = 0;
}; };
""" """
# The constructors and destructor should be ignored. # The constructors and destructor should be ignored.
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testVirtualDestructor(self): def testVirtualDestructor(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual ~Foo(); virtual ~Foo();
virtual int Bar() = 0; virtual int Bar() = 0;
}; };
""" """
# The destructor should be ignored. # The destructor should be ignored.
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testExplicitlyDefaultedConstructorsAndDestructor(self): def testExplicitlyDefaultedConstructorsAndDestructor(self):
source = """ source = """
class Foo { class Foo {
public: public:
Foo() = default; Foo() = default;
@@ -105,13 +105,13 @@ class Foo {
virtual int Bar() = 0; virtual int Bar() = 0;
}; };
""" """
# The constructors and destructor should be ignored. # The constructors and destructor should be ignored.
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testExplicitlyDeletedConstructorsAndDestructor(self): def testExplicitlyDeletedConstructorsAndDestructor(self):
source = """ source = """
class Foo { class Foo {
public: public:
Foo() = delete; Foo() = delete;
@@ -121,69 +121,69 @@ class Foo {
virtual int Bar() = 0; virtual int Bar() = 0;
}; };
""" """
# The constructors and destructor should be ignored. # The constructors and destructor should be ignored.
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testSimpleOverrideMethod(self): def testSimpleOverrideMethod(self):
source = """ source = """
class Foo { class Foo {
public: public:
int Bar() override; int Bar() override;
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testSimpleConstMethod(self): def testSimpleConstMethod(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual void Bar(bool flag) const; virtual void Bar(bool flag) const;
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));', 'MOCK_METHOD(void, Bar, (bool flag), (const, override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testExplicitVoid(self): def testExplicitVoid(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual int Bar(void); virtual int Bar(void);
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0(Bar,\nint(void));', 'MOCK_METHOD(int, Bar, (void), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testStrangeNewlineInParameter(self): def testStrangeNewlineInParameter(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual void Bar(int virtual void Bar(int
a) = 0; a) = 0;
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nvoid(int a));', 'MOCK_METHOD(void, Bar, (int a), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testDefaultParameters(self): def testDefaultParameters(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual void Bar(int a, char c = 'x') = 0; virtual void Bar(int a, char c = 'x') = 0;
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\nvoid(int a, char c ));', 'MOCK_METHOD(void, Bar, (int a, char c), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testMultipleDefaultParameters(self): def testMultipleDefaultParameters(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual void Bar( virtual void Bar(
@@ -195,47 +195,58 @@ class Foo {
int const *& rp = aDefaultPointer) = 0; int const *& rp = aDefaultPointer) = 0;
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
"MOCK_METHOD7(Bar,\n" 'MOCK_METHOD(void, Bar, '
"void(int a , char c , const int* const p , const std::string& s , char tab[] , int const *& rp ));", '(int a, char c, const int* const p, const std::string& s, char tab[], int const *& rp), '
self.GenerateMethodSource(source)) '(override));', self.GenerateMethodSource(source))
def testConstDefaultParameter(self): def testMultipleSingleLineDefaultParameters(self):
source = """ source = """
class Foo {
public:
virtual void Bar(int a = 42, int b = 43, int c = 44) = 0;
};
"""
self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD(void, Bar, (int a, int b, int c), (override));',
self.GenerateMethodSource(source))
def testConstDefaultParameter(self):
source = """
class Test { class Test {
public: public:
virtual bool Bar(const int test_arg = 42) = 0; virtual bool Bar(const int test_arg = 42) = 0;
}; };
""" """
expected = 'MOCK_METHOD1(Bar,\nbool(const int test_arg ));' self.assertEqualIgnoreLeadingWhitespace(
self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD(bool, Bar, (const int test_arg), (override));',
expected, self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testConstRefDefaultParameter(self): def testConstRefDefaultParameter(self):
source = """ source = """
class Test { class Test {
public: public:
virtual bool Bar(const std::string& test_arg = "42" ) = 0; virtual bool Bar(const std::string& test_arg = "42" ) = 0;
}; };
""" """
expected = 'MOCK_METHOD1(Bar,\nbool(const std::string& test_arg ));' self.assertEqualIgnoreLeadingWhitespace(
self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD(bool, Bar, (const std::string& test_arg), (override));',
expected, self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testRemovesCommentsWhenDefaultsArePresent(self): def testRemovesCommentsWhenDefaultsArePresent(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual void Bar(int a = 42 /* a comment */, virtual void Bar(int a = 42 /* a comment */,
char /* other comment */ c= 'x') = 0; char /* other comment */ c= 'x') = 0;
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\nvoid(int a , char c));', 'MOCK_METHOD(void, Bar, (int a, char c), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testDoubleSlashCommentsInParameterListAreRemoved(self): def testDoubleSlashCommentsInParameterListAreRemoved(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual void Bar(int a, // inline comments should be elided. virtual void Bar(int a, // inline comments should be elided.
@@ -243,117 +254,111 @@ class Foo {
) const = 0; ) const = 0;
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));', 'MOCK_METHOD(void, Bar, (int a, int b), (const, override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testCStyleCommentsInParameterListAreNotRemoved(self): def testCStyleCommentsInParameterListAreNotRemoved(self):
# NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these
# comments. Also note that C style comments after the last parameter # comments. Also note that C style comments after the last parameter
# are still elided. # are still elided.
source = """ source = """
class Foo { class Foo {
public: public:
virtual const string& Bar(int /* keeper */, int b); virtual const string& Bar(int /* keeper */, int b);
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\nconst string&(int , int b));', 'MOCK_METHOD(const string&, Bar, (int, int b), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testArgsOfTemplateTypes(self): def testArgsOfTemplateTypes(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual int Bar(const vector<int>& v, map<int, string>* output); virtual int Bar(const vector<int>& v, map<int, string>* output);
};""" };"""
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD2(Bar,\n' 'MOCK_METHOD(int, Bar, (const vector<int>& v, (map<int, string>* output)), (override));',
'int(const vector<int>& v, map<int, string>* output));', self.GenerateMethodSource(source))
self.GenerateMethodSource(source))
def testReturnTypeWithOneTemplateArg(self): def testReturnTypeWithOneTemplateArg(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual vector<int>* Bar(int n); virtual vector<int>* Bar(int n);
};""" };"""
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nvector<int>*(int n));', 'MOCK_METHOD(vector<int>*, Bar, (int n), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testReturnTypeWithManyTemplateArgs(self): def testReturnTypeWithManyTemplateArgs(self):
source = """ source = """
class Foo { class Foo {
public: public:
virtual map<int, string> Bar(); virtual map<int, string> Bar();
};""" };"""
# Comparing the comment text is brittle - we'll think of something self.assertEqualIgnoreLeadingWhitespace(
# better in case this gets annoying, but for now let's keep it simple. 'MOCK_METHOD((map<int, string>), Bar, (), (override));',
self.assertEqualIgnoreLeadingWhitespace( self.GenerateMethodSource(source))
'// The following line won\'t really compile, as the return\n'
'// type has multiple template arguments. To fix it, use a\n'
'// typedef for the return type.\n'
'MOCK_METHOD0(Bar,\nmap<int, string>());',
self.GenerateMethodSource(source))
def testSimpleMethodInTemplatedClass(self): def testSimpleMethodInTemplatedClass(self):
source = """ source = """
template<class T> template<class T>
class Foo { class Foo {
public: public:
virtual int Bar(); virtual int Bar();
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD0_T(Bar,\nint());', 'MOCK_METHOD(int, Bar, (), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testPointerArgWithoutNames(self): def testPointerArgWithoutNames(self):
source = """ source = """
class Foo { class Foo {
virtual int Bar(C*); virtual int Bar(C*);
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nint(C*));', 'MOCK_METHOD(int, Bar, (C*), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testReferenceArgWithoutNames(self): def testReferenceArgWithoutNames(self):
source = """ source = """
class Foo { class Foo {
virtual int Bar(C&); virtual int Bar(C&);
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nint(C&));', 'MOCK_METHOD(int, Bar, (C&), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
def testArrayArgWithoutNames(self): def testArrayArgWithoutNames(self):
source = """ source = """
class Foo { class Foo {
virtual int Bar(C[]); virtual int Bar(C[]);
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(
'MOCK_METHOD1(Bar,\nint(C[]));', 'MOCK_METHOD(int, Bar, (C[]), (override));',
self.GenerateMethodSource(source)) self.GenerateMethodSource(source))
class GenerateMocksTest(TestCase): class GenerateMocksTest(TestCase):
@staticmethod @staticmethod
def GenerateMocks(cpp_source): def GenerateMocks(cpp_source):
"""Convert C++ source to complete Google Mock output source.""" """Convert C++ source to complete Google Mock output source."""
# <test> is a pseudo-filename, it is not read or written. # <test> is a pseudo-filename, it is not read or written.
filename = '<test>' filename = '<test>'
builder = ast.BuilderFromSource(cpp_source, filename) builder = ast.BuilderFromSource(cpp_source, filename)
ast_list = list(builder.Generate()) ast_list = list(builder.Generate())
lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None) lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None)
return '\n'.join(lines) return '\n'.join(lines)
def testNamespaces(self): def testNamespaces(self):
source = """ source = """
namespace Foo { namespace Foo {
namespace Bar { class Forward; } namespace Bar { class Forward; }
namespace Baz { namespace Baz {
@@ -366,96 +371,91 @@ class Test {
} // namespace Baz } // namespace Baz
} // namespace Foo } // namespace Foo
""" """
expected = """\ expected = """\
namespace Foo { namespace Foo {
namespace Baz { namespace Baz {
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD0(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
} // namespace Baz } // namespace Baz
} // namespace Foo } // namespace Foo
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testClassWithStorageSpecifierMacro(self): def testClassWithStorageSpecifierMacro(self):
source = """ source = """
class STORAGE_SPECIFIER Test { class STORAGE_SPECIFIER Test {
public: public:
virtual void Foo(); virtual void Foo();
}; };
""" """
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD0(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testTemplatedForwardDeclaration(self): def testTemplatedForwardDeclaration(self):
source = """ source = """
template <class T> class Forward; // Forward declaration should be ignored. template <class T> class Forward; // Forward declaration should be ignored.
class Test { class Test {
public: public:
virtual void Foo(); virtual void Foo();
}; };
""" """
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD0(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testTemplatedClass(self): def testTemplatedClass(self):
source = """ source = """
template <typename S, typename T> template <typename S, typename T>
class Test { class Test {
public: public:
virtual void Foo(); virtual void Foo();
}; };
""" """
expected = """\ expected = """\
template <typename T0, typename T1> template <typename T0, typename T1>
class MockTest : public Test<T0, T1> { class MockTest : public Test<T0, T1> {
public: public:
MOCK_METHOD0_T(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testTemplateInATemplateTypedef(self): def testTemplateInATemplateTypedef(self):
source = """ source = """
class Test { class Test {
public: public:
typedef std::vector<std::list<int>> FooType; typedef std::vector<std::list<int>> FooType;
virtual void Bar(const FooType& test_arg); virtual void Bar(const FooType& test_arg);
}; };
""" """
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD1(Bar, MOCK_METHOD(void, Bar, (const FooType& test_arg), (override));
void(const FooType& test_arg));
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testTemplateInATemplateTypedefWithComma(self): def testTemplateInATemplateTypedefWithComma(self):
source = """ source = """
class Test { class Test {
public: public:
typedef std::function<void( typedef std::function<void(
@@ -463,18 +463,33 @@ class Test {
virtual void Bar(const FooType& test_arg); virtual void Bar(const FooType& test_arg);
}; };
""" """
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD1(Bar, MOCK_METHOD(void, Bar, (const FooType& test_arg), (override));
void(const FooType& test_arg));
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testEnumType(self): def testParenthesizedCommaInArg(self):
source = """ source = """
class Test {
public:
virtual void Bar(std::function<void(int, int)> f);
};
"""
expected = """\
class MockTest : public Test {
public:
MOCK_METHOD(void, Bar, (std::function<void(int, int)> f), (override));
};
"""
self.assertEqualIgnoreLeadingWhitespace(expected,
self.GenerateMocks(source))
def testEnumType(self):
source = """
class Test { class Test {
public: public:
enum Bar { enum Bar {
@@ -483,18 +498,17 @@ class Test {
virtual void Foo(); virtual void Foo();
}; };
""" """
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD0(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testEnumClassType(self): def testEnumClassType(self):
source = """ source = """
class Test { class Test {
public: public:
enum class Bar { enum class Bar {
@@ -503,18 +517,17 @@ class Test {
virtual void Foo(); virtual void Foo();
}; };
""" """
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD0(Foo, MOCK_METHOD(void, Foo, (), (override));
void());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
def testStdFunction(self): def testStdFunction(self):
source = """ source = """
class Test { class Test {
public: public:
Test(std::function<int(std::string)> foo) : foo_(foo) {} Test(std::function<int(std::string)> foo) : foo_(foo) {}
@@ -525,16 +538,15 @@ class Test {
std::function<int(std::string)> foo_; std::function<int(std::string)> foo_;
}; };
""" """
expected = """\ expected = """\
class MockTest : public Test { class MockTest : public Test {
public: public:
MOCK_METHOD0(foo, MOCK_METHOD(std::function<int (std::string)>, foo, (), (override));
std::function<int (std::string)>());
}; };
""" """
self.assertEqualIgnoreLeadingWhitespace( self.assertEqualIgnoreLeadingWhitespace(expected,
expected, self.GenerateMocks(source)) self.GenerateMocks(source))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@@ -34,7 +34,6 @@
// utilities for defining matchers. // utilities for defining matchers.
#include "gmock/gmock-matchers.h" #include "gmock/gmock-matchers.h"
#include "gmock/gmock-generated-matchers.h"
#include <string.h> #include <string.h>
#include <iostream> #include <iostream>

View File

@@ -48,14 +48,21 @@ void loop() { RUN_ALL_TESTS(); }
#endif #endif
#else #else
#if __MSC_VER
// MS C++ compiler/linker has a bug on Windows (not on Windows CE), which
// causes a link error when _tmain is defined in a static library and UNICODE
// is enabled. For this reason instead of _tmain, main function is used on
// Windows. See the following link to track the current status of this bug:
// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library
// // NOLINT
#if GTEST_OS_WINDOWS_MOBILE
# include <tchar.h> // NOLINT # include <tchar.h> // NOLINT
GTEST_API_ int _tmain(int argc, TCHAR** argv) { GTEST_API_ int _tmain(int argc, TCHAR** argv) {
#else #else
GTEST_API_ int main(int argc, char** argv) { GTEST_API_ int main(int argc, char** argv) {
#endif // __MSC_VER #endif // GTEST_OS_WINDOWS_MOBILE
std::cout << "Running main() from " << __FILE__ << '\n'; std::cout << "Running main() from gmock_main.cc\n";
// Since Google Mock depends on Google Test, InitGoogleMock() is // Since Google Mock depends on Google Test, InitGoogleMock() is
// also responsible for initializing Google Test. Therefore there's // also responsible for initializing Google Test. Therefore there's
// no need for calling testing::InitGoogleTest() separately. // no need for calling testing::InitGoogleTest() separately.

View File

@@ -31,7 +31,7 @@
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the function mocker classes. // This file tests the function mocker classes.
#include "gmock/gmock-generated-function-mockers.h" #include "gmock/gmock-function-mocker.h"
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but // MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
@@ -183,182 +183,238 @@ class MockFoo : public FooInterface {
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
}; };
class LegacyMockFoo : public FooInterface {
public:
LegacyMockFoo() {}
// Makes sure that a mock function parameter can be named.
MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
MOCK_METHOD0(Nullary, int()); // NOLINT
// Makes sure that a mock function parameter can be unnamed.
MOCK_METHOD1(Unary, bool(int)); // NOLINT
MOCK_METHOD2(Binary, long(short, int)); // NOLINT
MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT
double, unsigned, char*, const std::string& str));
MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
MOCK_METHOD1(TakesConstReference, std::string(const int&));
MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());
MOCK_CONST_METHOD1(ReturnTypeWithComma,
std::map<int, std::string>(int)); // NOLINT
MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, char(char)); // NOLINT
MOCK_METHOD0(OverloadedOnConstness, int()); // NOLINT
MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT
MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
MOCK_METHOD1(TypeWithComma,
int(const std::map<int, std::string>&)); // NOLINT
MOCK_METHOD1(TypeWithTemplatedCopyCtor,
int(const TemplatedCopyable<int>&)); // NOLINT
MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool));
MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int));
#if GTEST_OS_WINDOWS
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); // NOLINT
MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
int(bool b, char c, short d, int e, // NOLINT
long f, float g, double h, // NOLINT
unsigned i, char* j, const std::string& k));
MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst,
char(int)); // NOLINT
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
std::map<int, std::string>());
#endif // GTEST_OS_WINDOWS
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockFoo);
};
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) # pragma warning(pop)
#endif #endif
class MockMethodFunctionMockerTest : public testing::Test { template <class T>
class FunctionMockerTest : public testing::Test {
protected: protected:
MockMethodFunctionMockerTest() : foo_(&mock_foo_) {} FunctionMockerTest() : foo_(&mock_foo_) {}
FooInterface* const foo_; FooInterface* const foo_;
MockFoo mock_foo_; T mock_foo_;
}; };
using FunctionMockerTestTypes = ::testing::Types<MockFoo, LegacyMockFoo>;
TYPED_TEST_SUITE(FunctionMockerTest, FunctionMockerTestTypes);
// Tests mocking a void-returning function. // Tests mocking a void-returning function.
TEST_F(MockMethodFunctionMockerTest, MocksVoidFunction) { TYPED_TEST(FunctionMockerTest, MocksVoidFunction) {
EXPECT_CALL(mock_foo_, VoidReturning(Lt(100))); EXPECT_CALL(this->mock_foo_, VoidReturning(Lt(100)));
foo_->VoidReturning(0); this->foo_->VoidReturning(0);
} }
// Tests mocking a nullary function. // Tests mocking a nullary function.
TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunction) { TYPED_TEST(FunctionMockerTest, MocksNullaryFunction) {
EXPECT_CALL(mock_foo_, Nullary()) EXPECT_CALL(this->mock_foo_, Nullary())
.WillOnce(DoDefault()) .WillOnce(DoDefault())
.WillOnce(Return(1)); .WillOnce(Return(1));
EXPECT_EQ(0, foo_->Nullary()); EXPECT_EQ(0, this->foo_->Nullary());
EXPECT_EQ(1, foo_->Nullary()); EXPECT_EQ(1, this->foo_->Nullary());
} }
// Tests mocking a unary function. // Tests mocking a unary function.
TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunction) { TYPED_TEST(FunctionMockerTest, MocksUnaryFunction) {
EXPECT_CALL(mock_foo_, Unary(Eq(2))) EXPECT_CALL(this->mock_foo_, Unary(Eq(2))).Times(2).WillOnce(Return(true));
.Times(2)
.WillOnce(Return(true));
EXPECT_TRUE(foo_->Unary(2)); EXPECT_TRUE(this->foo_->Unary(2));
EXPECT_FALSE(foo_->Unary(2)); EXPECT_FALSE(this->foo_->Unary(2));
} }
// Tests mocking a binary function. // Tests mocking a binary function.
TEST_F(MockMethodFunctionMockerTest, MocksBinaryFunction) { TYPED_TEST(FunctionMockerTest, MocksBinaryFunction) {
EXPECT_CALL(mock_foo_, Binary(2, _)) EXPECT_CALL(this->mock_foo_, Binary(2, _)).WillOnce(Return(3));
.WillOnce(Return(3));
EXPECT_EQ(3, foo_->Binary(2, 1)); EXPECT_EQ(3, this->foo_->Binary(2, 1));
} }
// Tests mocking a decimal function. // Tests mocking a decimal function.
TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunction) { TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), EXPECT_CALL(this->mock_foo_,
Lt(100), 5U, NULL, "hi")) Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(5)); .WillOnce(Return(5));
EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
} }
// Tests mocking a function that takes a non-const reference. // Tests mocking a function that takes a non-const reference.
TEST_F(MockMethodFunctionMockerTest, TYPED_TEST(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
MocksFunctionWithNonConstReferenceArgument) {
int a = 0; int a = 0;
EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a))) EXPECT_CALL(this->mock_foo_, TakesNonConstReference(Ref(a)))
.WillOnce(Return(true)); .WillOnce(Return(true));
EXPECT_TRUE(foo_->TakesNonConstReference(a)); EXPECT_TRUE(this->foo_->TakesNonConstReference(a));
} }
// Tests mocking a function that takes a const reference. // Tests mocking a function that takes a const reference.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstReferenceArgument) { TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
int a = 0; int a = 0;
EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a))) EXPECT_CALL(this->mock_foo_, TakesConstReference(Ref(a)))
.WillOnce(Return("Hello")); .WillOnce(Return("Hello"));
EXPECT_EQ("Hello", foo_->TakesConstReference(a)); EXPECT_EQ("Hello", this->foo_->TakesConstReference(a));
} }
// Tests mocking a function that takes a const variable. // Tests mocking a function that takes a const variable.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstArgument) { TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstArgument) {
EXPECT_CALL(mock_foo_, TakesConst(Lt(10))) EXPECT_CALL(this->mock_foo_, TakesConst(Lt(10))).WillOnce(DoDefault());
.WillOnce(DoDefault());
EXPECT_FALSE(foo_->TakesConst(5)); EXPECT_FALSE(this->foo_->TakesConst(5));
} }
// Tests mocking functions overloaded on the number of arguments. // Tests mocking functions overloaded on the number of arguments.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) { TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber()) EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber())
.WillOnce(Return(1)); .WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_)) EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber(_))
.WillOnce(Return(2)); .WillOnce(Return(2));
EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1)); EXPECT_EQ(2, this->foo_->OverloadedOnArgumentNumber(1));
EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber()); EXPECT_EQ(1, this->foo_->OverloadedOnArgumentNumber());
} }
// Tests mocking functions overloaded on the types of argument. // Tests mocking functions overloaded on the types of argument.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) { TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>())) EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(An<int>()))
.WillOnce(Return(1)); .WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a'))) EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
.WillOnce(Return('b')); .WillOnce(Return('b'));
EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0)); EXPECT_EQ(1, this->foo_->OverloadedOnArgumentType(0));
EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a')); EXPECT_EQ('b', this->foo_->OverloadedOnArgumentType('a'));
} }
// Tests mocking functions overloaded on the const-ness of this object. // Tests mocking functions overloaded on the const-ness of this object.
TEST_F(MockMethodFunctionMockerTest, TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
MocksFunctionsOverloadedOnConstnessOfThis) { EXPECT_CALL(this->mock_foo_, OverloadedOnConstness());
EXPECT_CALL(mock_foo_, OverloadedOnConstness()); EXPECT_CALL(Const(this->mock_foo_), OverloadedOnConstness())
EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
.WillOnce(Return('a')); .WillOnce(Return('a'));
EXPECT_EQ(0, foo_->OverloadedOnConstness()); EXPECT_EQ(0, this->foo_->OverloadedOnConstness());
EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness()); EXPECT_EQ('a', Const(*this->foo_).OverloadedOnConstness());
} }
TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithComma) { TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithComma) {
const std::map<int, std::string> a_map; const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, ReturnTypeWithComma()) EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma()).WillOnce(Return(a_map));
.WillOnce(Return(a_map)); EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma(42)).WillOnce(Return(a_map));
EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma()); EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42)); EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma(42));
} }
TEST_F(MockMethodFunctionMockerTest, MocksTypeWithTemplatedCopyCtor) { TYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true)); EXPECT_CALL(this->mock_foo_, TypeWithTemplatedCopyCtor(_))
EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>())); .WillOnce(Return(true));
EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
} }
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype. // Tests mocking a nullary function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunctionWithCallType) { TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTNullary()) EXPECT_CALL(this->mock_foo_, CTNullary())
.WillOnce(Return(-1)) .WillOnce(Return(-1))
.WillOnce(Return(0)); .WillOnce(Return(0));
EXPECT_EQ(-1, foo_->CTNullary()); EXPECT_EQ(-1, this->foo_->CTNullary());
EXPECT_EQ(0, foo_->CTNullary()); EXPECT_EQ(0, this->foo_->CTNullary());
} }
// Tests mocking a unary function with calltype. // Tests mocking a unary function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunctionWithCallType) { TYPED_TEST(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTUnary(Eq(2))) EXPECT_CALL(this->mock_foo_, CTUnary(Eq(2)))
.Times(2) .Times(2)
.WillOnce(Return(true)) .WillOnce(Return(true))
.WillOnce(Return(false)); .WillOnce(Return(false));
EXPECT_TRUE(foo_->CTUnary(2)); EXPECT_TRUE(this->foo_->CTUnary(2));
EXPECT_FALSE(foo_->CTUnary(2)); EXPECT_FALSE(this->foo_->CTUnary(2));
} }
// Tests mocking a decimal function with calltype. // Tests mocking a decimal function with calltype.
TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunctionWithCallType) { TYPED_TEST(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), EXPECT_CALL(this->mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),
Lt(100), 5U, NULL, "hi")) Lt(100), 5U, NULL, "hi"))
.WillOnce(Return(10)); .WillOnce(Return(10));
EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi")); EXPECT_EQ(10, this->foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi"));
} }
// Tests mocking functions overloaded on the const-ness of this object. // Tests mocking functions overloaded on the const-ness of this object.
TEST_F(MockMethodFunctionMockerTest, MocksFunctionsConstFunctionWithCallType) { TYPED_TEST(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
EXPECT_CALL(Const(mock_foo_), CTConst(_)) EXPECT_CALL(Const(this->mock_foo_), CTConst(_)).WillOnce(Return('a'));
.WillOnce(Return('a'));
EXPECT_EQ('a', Const(*foo_).CTConst(0)); EXPECT_EQ('a', Const(*this->foo_).CTConst(0));
} }
TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithCommaAndCallType) { TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
const std::map<int, std::string> a_map; const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, CTReturnTypeWithComma()) EXPECT_CALL(this->mock_foo_, CTReturnTypeWithComma()).WillOnce(Return(a_map));
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma()); EXPECT_EQ(a_map, this->mock_foo_.CTReturnTypeWithComma());
} }
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
@@ -373,20 +429,33 @@ class MockB {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
}; };
class LegacyMockB {
public:
LegacyMockB() {}
MOCK_METHOD0(DoB, void());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockB);
};
template <typename T>
class ExpectCallTest : public ::testing::Test {};
using ExpectCallTestTypes = ::testing::Types<MockB, LegacyMockB>;
TYPED_TEST_SUITE(ExpectCallTest, ExpectCallTestTypes);
// Tests that functions with no EXPECT_CALL() rules can be called any // Tests that functions with no EXPECT_CALL() rules can be called any
// number of times. // number of times.
TEST(MockMethodExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) { TYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
{ { TypeParam b; }
MockB b;
}
{ {
MockB b; TypeParam b;
b.DoB(); b.DoB();
} }
{ {
MockB b; TypeParam b;
b.DoB(); b.DoB();
b.DoB(); b.DoB();
} }
@@ -425,9 +494,33 @@ class MockStack : public StackInterface<T> {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
}; };
template <typename T>
class LegacyMockStack : public StackInterface<T> {
public:
LegacyMockStack() {}
MOCK_METHOD1_T(Push, void(const T& elem));
MOCK_METHOD0_T(Pop, void());
MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT
MOCK_CONST_METHOD0_T(GetTop, const T&());
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); // NOLINT
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStack);
};
template <typename T>
class TemplateMockTest : public ::testing::Test {};
using TemplateMockTestTypes =
::testing::Types<MockStack<int>, LegacyMockStack<int>>;
TYPED_TEST_SUITE(TemplateMockTest, TemplateMockTestTypes);
// Tests that template mock works. // Tests that template mock works.
TEST(MockMethodTemplateMockTest, Works) { TYPED_TEST(TemplateMockTest, Works) {
MockStack<int> mock; TypeParam mock;
EXPECT_CALL(mock, GetSize()) EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0)) .WillOnce(Return(0))
@@ -448,8 +541,8 @@ TEST(MockMethodTemplateMockTest, Works) {
EXPECT_EQ(0, mock.GetSize()); EXPECT_EQ(0, mock.GetSize());
} }
TEST(MockMethodTemplateMockTest, MethodWithCommaInReturnTypeWorks) { TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
MockStack<int> mock; TypeParam mock;
const std::map<int, int> a_map; const std::map<int, int> a_map;
EXPECT_CALL(mock, ReturnTypeWithComma()) EXPECT_CALL(mock, ReturnTypeWithComma())
@@ -493,9 +586,31 @@ class MockStackWithCallType : public StackInterfaceWithCallType<T> {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
}; };
template <typename T>
class LegacyMockStackWithCallType : public StackInterfaceWithCallType<T> {
public:
LegacyMockStackWithCallType() {}
MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockStackWithCallType);
};
template <typename T>
class TemplateMockTestWithCallType : public ::testing::Test {};
using TemplateMockTestWithCallTypeTypes =
::testing::Types<MockStackWithCallType<int>,
LegacyMockStackWithCallType<int>>;
TYPED_TEST_SUITE(TemplateMockTestWithCallType,
TemplateMockTestWithCallTypeTypes);
// Tests that template mock with calltype works. // Tests that template mock with calltype works.
TEST(MockMethodTemplateMockTestWithCallType, Works) { TYPED_TEST(TemplateMockTestWithCallType, Works) {
MockStackWithCallType<int> mock; TypeParam mock;
EXPECT_CALL(mock, GetSize()) EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0)) .WillOnce(Return(0))
@@ -522,6 +637,11 @@ TEST(MockMethodTemplateMockTestWithCallType, Works) {
MOCK_METHOD(int, Overloaded, (int), (const)); \ MOCK_METHOD(int, Overloaded, (int), (const)); \
MOCK_METHOD(bool, Overloaded, (bool f, int n)) MOCK_METHOD(bool, Overloaded, (bool f, int n))
#define LEGACY_MY_MOCK_METHODS1_ \
MOCK_METHOD0(Overloaded, void()); \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD2(Overloaded, bool(bool f, int n))
class MockOverloadedOnArgNumber { class MockOverloadedOnArgNumber {
public: public:
MockOverloadedOnArgNumber() {} MockOverloadedOnArgNumber() {}
@@ -532,8 +652,25 @@ class MockOverloadedOnArgNumber {
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber); GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
}; };
TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) { class LegacyMockOverloadedOnArgNumber {
MockOverloadedOnArgNumber mock; public:
LegacyMockOverloadedOnArgNumber() {}
LEGACY_MY_MOCK_METHODS1_;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LegacyMockOverloadedOnArgNumber);
};
template <typename T>
class OverloadedMockMethodTest : public ::testing::Test {};
using OverloadedMockMethodTestTypes =
::testing::Types<MockOverloadedOnArgNumber,
LegacyMockOverloadedOnArgNumber>;
TYPED_TEST_SUITE(OverloadedMockMethodTest, OverloadedMockMethodTestTypes);
TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
TypeParam mock;
EXPECT_CALL(mock, Overloaded()); EXPECT_CALL(mock, Overloaded());
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true)); EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
@@ -658,11 +795,35 @@ struct MockMethodSizes4 {
MOCK_METHOD(void, func, (int, int, int, int)); MOCK_METHOD(void, func, (int, int, int, int));
}; };
struct LegacyMockMethodSizes0 {
MOCK_METHOD0(func, void());
};
struct LegacyMockMethodSizes1 {
MOCK_METHOD1(func, void(int));
};
struct LegacyMockMethodSizes2 {
MOCK_METHOD2(func, void(int, int));
};
struct LegacyMockMethodSizes3 {
MOCK_METHOD3(func, void(int, int, int));
};
struct LegacyMockMethodSizes4 {
MOCK_METHOD4(func, void(int, int, int, int));
};
TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes1));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes2));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes3));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes4));
EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(MockMethodSizes0));
} }
void hasTwoParams(int, int); void hasTwoParams(int, int);

View File

@@ -1,659 +0,0 @@
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the function mocker classes.
#include "gmock/gmock-generated-function-mockers.h"
#if GTEST_OS_WINDOWS
// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
// we are getting compiler errors if we use basetyps.h, hence including
// objbase.h for definition of STDMETHOD.
# include <objbase.h>
#endif // GTEST_OS_WINDOWS
#include <map>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace testing {
namespace gmock_generated_function_mockers_test {
using testing::_;
using testing::A;
using testing::An;
using testing::AnyNumber;
using testing::Const;
using testing::DoDefault;
using testing::Eq;
using testing::Lt;
using testing::MockFunction;
using testing::Ref;
using testing::Return;
using testing::ReturnRef;
using testing::TypedEq;
template<typename T>
class TemplatedCopyable {
public:
TemplatedCopyable() {}
template <typename U>
TemplatedCopyable(const U& other) {} // NOLINT
};
class FooInterface {
public:
virtual ~FooInterface() {}
virtual void VoidReturning(int x) = 0;
virtual int Nullary() = 0;
virtual bool Unary(int x) = 0;
virtual long Binary(short x, int y) = 0; // NOLINT
virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT
float g, double h, unsigned i, char* j,
const std::string& k) = 0;
virtual bool TakesNonConstReference(int& n) = 0; // NOLINT
virtual std::string TakesConstReference(const int& n) = 0;
virtual bool TakesConst(const int x) = 0;
virtual int OverloadedOnArgumentNumber() = 0;
virtual int OverloadedOnArgumentNumber(int n) = 0;
virtual int OverloadedOnArgumentType(int n) = 0;
virtual char OverloadedOnArgumentType(char c) = 0;
virtual int OverloadedOnConstness() = 0;
virtual char OverloadedOnConstness() const = 0;
virtual int TypeWithHole(int (*func)()) = 0;
virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;
virtual int TypeWithTemplatedCopyCtor(
const TemplatedCopyable<int>& a_vector) = 0;
#if GTEST_OS_WINDOWS
STDMETHOD_(int, CTNullary)() = 0;
STDMETHOD_(bool, CTUnary)(int x) = 0;
STDMETHOD_(int, CTDecimal)
(bool b, char c, short d, int e, long f, // NOLINT
float g, double h, unsigned i, char* j, const std::string& k) = 0;
STDMETHOD_(char, CTConst)(int x) const = 0;
#endif // GTEST_OS_WINDOWS
};
// Const qualifiers on arguments were once (incorrectly) considered
// significant in determining whether two virtual functions had the same
// signature. This was fixed in Visual Studio 2008. However, the compiler
// still emits a warning that alerts about this change in behavior.
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4373)
#endif
class MockFoo : public FooInterface {
public:
MockFoo() {}
// Makes sure that a mock function parameter can be named.
MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT
MOCK_METHOD0(Nullary, int()); // NOLINT
// Makes sure that a mock function parameter can be unnamed.
MOCK_METHOD1(Unary, bool(int)); // NOLINT
MOCK_METHOD2(Binary, long(short, int)); // NOLINT
MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT
double, unsigned, char*, const std::string& str));
MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
MOCK_METHOD1(TakesConstReference, std::string(const int&));
MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());
MOCK_CONST_METHOD1(ReturnTypeWithComma,
std::map<int, std::string>(int)); // NOLINT
MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, int(int)); // NOLINT
MOCK_METHOD1(OverloadedOnArgumentType, char(char)); // NOLINT
MOCK_METHOD0(OverloadedOnConstness, int()); // NOLINT
MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT
MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
MOCK_METHOD1(TypeWithComma,
int(const std::map<int, std::string>&)); // NOLINT
MOCK_METHOD1(TypeWithTemplatedCopyCtor,
int(const TemplatedCopyable<int>&)); // NOLINT
#if GTEST_OS_WINDOWS
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int));
MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
int(bool b, char c, short d, int e, long f,
float g, double h, unsigned i, char* j,
const std::string& k));
MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int));
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
std::map<int, std::string>());
#endif // GTEST_OS_WINDOWS
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
};
#ifdef _MSC_VER
# pragma warning(pop)
#endif
class FunctionMockerTest : public testing::Test {
protected:
FunctionMockerTest() : foo_(&mock_foo_) {}
FooInterface* const foo_;
MockFoo mock_foo_;
};
// Tests mocking a void-returning function.
TEST_F(FunctionMockerTest, MocksVoidFunction) {
EXPECT_CALL(mock_foo_, VoidReturning(Lt(100)));
foo_->VoidReturning(0);
}
// Tests mocking a nullary function.
TEST_F(FunctionMockerTest, MocksNullaryFunction) {
EXPECT_CALL(mock_foo_, Nullary())
.WillOnce(DoDefault())
.WillOnce(Return(1));
EXPECT_EQ(0, foo_->Nullary());
EXPECT_EQ(1, foo_->Nullary());
}
// Tests mocking a unary function.
TEST_F(FunctionMockerTest, MocksUnaryFunction) {
EXPECT_CALL(mock_foo_, Unary(Eq(2)))
.Times(2)
.WillOnce(Return(true));
EXPECT_TRUE(foo_->Unary(2));
EXPECT_FALSE(foo_->Unary(2));
}
// Tests mocking a binary function.
TEST_F(FunctionMockerTest, MocksBinaryFunction) {
EXPECT_CALL(mock_foo_, Binary(2, _))
.WillOnce(Return(3));
EXPECT_EQ(3, foo_->Binary(2, 1));
}
// Tests mocking a decimal function.
TEST_F(FunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
nullptr, "hi"))
.WillOnce(Return(5));
EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
}
// Tests mocking a function that takes a non-const reference.
TEST_F(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {
int a = 0;
EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a)))
.WillOnce(Return(true));
EXPECT_TRUE(foo_->TakesNonConstReference(a));
}
// Tests mocking a function that takes a const reference.
TEST_F(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {
int a = 0;
EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a)))
.WillOnce(Return("Hello"));
EXPECT_EQ("Hello", foo_->TakesConstReference(a));
}
// Tests mocking a function that takes a const variable.
TEST_F(FunctionMockerTest, MocksFunctionWithConstArgument) {
EXPECT_CALL(mock_foo_, TakesConst(Lt(10)))
.WillOnce(DoDefault());
EXPECT_FALSE(foo_->TakesConst(5));
}
// Tests mocking functions overloaded on the number of arguments.
TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber())
.WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_))
.WillOnce(Return(2));
EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1));
EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber());
}
// Tests mocking functions overloaded on the types of argument.
TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An<int>()))
.WillOnce(Return(1));
EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))
.WillOnce(Return('b'));
EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0));
EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a'));
}
// Tests mocking functions overloaded on the const-ness of this object.
TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
EXPECT_CALL(mock_foo_, OverloadedOnConstness());
EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness())
.WillOnce(Return('a'));
EXPECT_EQ(0, foo_->OverloadedOnConstness());
EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
}
TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) {
const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
}
TEST_F(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {
EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true));
EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));
}
#if GTEST_OS_WINDOWS
// Tests mocking a nullary function with calltype.
TEST_F(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTNullary())
.WillOnce(Return(-1))
.WillOnce(Return(0));
EXPECT_EQ(-1, foo_->CTNullary());
EXPECT_EQ(0, foo_->CTNullary());
}
// Tests mocking a unary function with calltype.
TEST_F(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTUnary(Eq(2)))
.Times(2)
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_TRUE(foo_->CTUnary(2));
EXPECT_FALSE(foo_->CTUnary(2));
}
// Tests mocking a decimal function with calltype.
TEST_F(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
nullptr, "hi"))
.WillOnce(Return(10));
EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
}
// Tests mocking functions overloaded on the const-ness of this object.
TEST_F(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
EXPECT_CALL(Const(mock_foo_), CTConst(_))
.WillOnce(Return('a'));
EXPECT_EQ('a', Const(*foo_).CTConst(0));
}
TEST_F(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
const std::map<int, std::string> a_map;
EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
}
#endif // GTEST_OS_WINDOWS
class MockB {
public:
MockB() {}
MOCK_METHOD0(DoB, void());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
};
// Tests that functions with no EXPECT_CALL() ruls can be called any
// number of times.
TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {
{
MockB b;
}
{
MockB b;
b.DoB();
}
{
MockB b;
b.DoB();
b.DoB();
}
}
// Tests mocking template interfaces.
template <typename T>
class StackInterface {
public:
virtual ~StackInterface() {}
// Template parameter appears in function parameter.
virtual void Push(const T& value) = 0;
virtual void Pop() = 0;
virtual int GetSize() const = 0;
// Template parameter appears in function return type.
virtual const T& GetTop() const = 0;
};
template <typename T>
class MockStack : public StackInterface<T> {
public:
MockStack() {}
MOCK_METHOD1_T(Push, void(const T& elem));
MOCK_METHOD0_T(Pop, void());
MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT
MOCK_CONST_METHOD0_T(GetTop, const T&());
// Tests that the function return type can contain unprotected comma.
MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); // NOLINT
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
};
// Tests that template mock works.
TEST(TemplateMockTest, Works) {
MockStack<int> mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
.WillOnce(Return(1))
.WillOnce(Return(0));
EXPECT_CALL(mock, Push(_));
int n = 5;
EXPECT_CALL(mock, GetTop())
.WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize());
mock.Push(5);
EXPECT_EQ(1, mock.GetSize());
EXPECT_EQ(5, mock.GetTop());
mock.Pop();
EXPECT_EQ(0, mock.GetSize());
}
TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
MockStack<int> mock;
const std::map<int, int> a_map;
EXPECT_CALL(mock, ReturnTypeWithComma())
.WillOnce(Return(a_map));
EXPECT_CALL(mock, ReturnTypeWithComma(1))
.WillOnce(Return(a_map));
EXPECT_EQ(a_map, mock.ReturnTypeWithComma());
EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
}
#if GTEST_OS_WINDOWS
// Tests mocking template interfaces with calltype.
template <typename T>
class StackInterfaceWithCallType {
public:
virtual ~StackInterfaceWithCallType() {}
// Template parameter appears in function parameter.
STDMETHOD_(void, Push)(const T& value) = 0;
STDMETHOD_(void, Pop)() = 0;
STDMETHOD_(int, GetSize)() const = 0;
// Template parameter appears in function return type.
STDMETHOD_(const T&, GetTop)() const = 0;
};
template <typename T>
class MockStackWithCallType : public StackInterfaceWithCallType<T> {
public:
MockStackWithCallType() {}
MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));
MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());
MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType);
};
// Tests that template mock with calltype works.
TEST(TemplateMockTestWithCallType, Works) {
MockStackWithCallType<int> mock;
EXPECT_CALL(mock, GetSize())
.WillOnce(Return(0))
.WillOnce(Return(1))
.WillOnce(Return(0));
EXPECT_CALL(mock, Push(_));
int n = 5;
EXPECT_CALL(mock, GetTop())
.WillOnce(ReturnRef(n));
EXPECT_CALL(mock, Pop())
.Times(AnyNumber());
EXPECT_EQ(0, mock.GetSize());
mock.Push(5);
EXPECT_EQ(1, mock.GetSize());
EXPECT_EQ(5, mock.GetTop());
mock.Pop();
EXPECT_EQ(0, mock.GetSize());
}
#endif // GTEST_OS_WINDOWS
#define MY_MOCK_METHODS1_ \
MOCK_METHOD0(Overloaded, void()); \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD2(Overloaded, bool(bool f, int n))
class MockOverloadedOnArgNumber {
public:
MockOverloadedOnArgNumber() {}
MY_MOCK_METHODS1_;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber);
};
TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {
MockOverloadedOnArgNumber mock;
EXPECT_CALL(mock, Overloaded());
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));
mock.Overloaded();
EXPECT_EQ(2, mock.Overloaded(1));
EXPECT_TRUE(mock.Overloaded(true, 1));
}
#define MY_MOCK_METHODS2_ \
MOCK_CONST_METHOD1(Overloaded, int(int n)); \
MOCK_METHOD1(Overloaded, int(int n))
class MockOverloadedOnConstness {
public:
MockOverloadedOnConstness() {}
MY_MOCK_METHODS2_;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness);
};
TEST(OverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) {
MockOverloadedOnConstness mock;
const MockOverloadedOnConstness* const_mock = &mock;
EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));
EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3));
EXPECT_EQ(2, mock.Overloaded(1));
EXPECT_EQ(3, const_mock->Overloaded(1));
}
TEST(MockFunctionTest, WorksForVoidNullary) {
MockFunction<void()> foo;
EXPECT_CALL(foo, Call());
foo.Call();
}
TEST(MockFunctionTest, WorksForNonVoidNullary) {
MockFunction<int()> foo;
EXPECT_CALL(foo, Call())
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, foo.Call());
EXPECT_EQ(2, foo.Call());
}
TEST(MockFunctionTest, WorksForVoidUnary) {
MockFunction<void(int)> foo;
EXPECT_CALL(foo, Call(1));
foo.Call(1);
}
TEST(MockFunctionTest, WorksForNonVoidBinary) {
MockFunction<int(bool, int)> foo;
EXPECT_CALL(foo, Call(false, 42))
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_CALL(foo, Call(true, Ge(100)))
.WillOnce(Return(3));
EXPECT_EQ(1, foo.Call(false, 42));
EXPECT_EQ(2, foo.Call(false, 42));
EXPECT_EQ(3, foo.Call(true, 120));
}
TEST(MockFunctionTest, WorksFor10Arguments) {
MockFunction<int(bool a0, char a1, int a2, int a3, int a4,
int a5, int a6, char a7, int a8, bool a9)> foo;
EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _))
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true));
EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false));
}
TEST(MockFunctionTest, AsStdFunction) {
MockFunction<int(int)> foo;
auto call = [](const std::function<int(int)> &f, int i) {
return f(i);
};
EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));
EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));
EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));
EXPECT_EQ(-2, call(foo.AsStdFunction(), 2));
}
TEST(MockFunctionTest, AsStdFunctionReturnsReference) {
MockFunction<int&()> foo;
int value = 1;
EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value));
int& ref = foo.AsStdFunction()();
EXPECT_EQ(1, ref);
value = 2;
EXPECT_EQ(2, ref);
}
TEST(MockFunctionTest, AsStdFunctionWithReferenceParameter) {
MockFunction<int(int &)> foo;
auto call = [](const std::function<int(int& )> &f, int &i) {
return f(i);
};
int i = 42;
EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1));
EXPECT_EQ(-1, call(foo.AsStdFunction(), i));
}
struct MockMethodSizes0 {
MOCK_METHOD0(func, void());
};
struct MockMethodSizes1 {
MOCK_METHOD1(func, void(int));
};
struct MockMethodSizes2 {
MOCK_METHOD2(func, void(int, int));
};
struct MockMethodSizes3 {
MOCK_METHOD3(func, void(int, int, int));
};
struct MockMethodSizes4 {
MOCK_METHOD4(func, void(int, int, int, int));
};
TEST(MockFunctionTest, MockMethodSizeOverhead) {
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
}
} // namespace gmock_generated_function_mockers_test
} // namespace testing

View File

@@ -39,7 +39,7 @@
# pragma warning(disable:4100) # pragma warning(disable:4100)
#endif #endif
#include "gmock/gmock-generated-matchers.h" #include "gmock/gmock-matchers.h"
#include <array> #include <array>
#include <iterator> #include <iterator>
@@ -392,13 +392,6 @@ TEST(ElementsAreTest, AcceptsStringLiteral) {
EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too"))); EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
} }
#ifndef _MSC_VER
// The following test passes a value of type const char[] to a
// function template that expects const T&. Some versions of MSVC
// generates a compiler error C2665 for that. We believe it's a bug
// in MSVC. Therefore this test is #if-ed out for MSVC.
// Declared here with the size unknown. Defined AFTER the following test. // Declared here with the size unknown. Defined AFTER the following test.
extern const char kHi[]; extern const char kHi[];
@@ -415,8 +408,6 @@ TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
const char kHi[] = "hi"; const char kHi[] = "hi";
#endif // _MSC_VER
TEST(ElementsAreTest, MakesCopyOfArguments) { TEST(ElementsAreTest, MakesCopyOfArguments) {
int x = 1; int x = 1;
int y = 2; int y = 2;
@@ -773,9 +764,16 @@ MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) { TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
UncopyableFoo foo1('1'), foo2('2'), foo3('3'); UncopyableFoo foo1('1'), foo2('2'), foo3('3');
const Matcher<const UncopyableFoo&> m = const Matcher<const UncopyableFoo&> const_m =
ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2); ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
EXPECT_TRUE(const_m.Matches(foo1));
EXPECT_TRUE(const_m.Matches(foo2));
EXPECT_FALSE(const_m.Matches(foo3));
const Matcher<UncopyableFoo&> m =
ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
EXPECT_TRUE(m.Matches(foo1)); EXPECT_TRUE(m.Matches(foo1));
EXPECT_TRUE(m.Matches(foo2)); EXPECT_TRUE(m.Matches(foo2));
EXPECT_FALSE(m.Matches(foo3)); EXPECT_FALSE(m.Matches(foo3));

View File

@@ -140,7 +140,7 @@ Matcher<int> GreaterThan(int n) {
std::string OfType(const std::string& type_name) { std::string OfType(const std::string& type_name) {
#if GTEST_HAS_RTTI #if GTEST_HAS_RTTI
return " (of type " + type_name + ")"; return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
#else #else
return ""; return "";
#endif #endif
@@ -351,43 +351,43 @@ TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
EXPECT_FALSE(m2.Matches("hello")); EXPECT_FALSE(m2.Matches("hello"));
} }
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that a C-string literal can be implicitly converted to a // Tests that a C-string literal can be implicitly converted to a
// Matcher<absl::string_view> or Matcher<const absl::string_view&>. // Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
Matcher<absl::string_view> m1 = "cats"; Matcher<internal::StringView> m1 = "cats";
EXPECT_TRUE(m1.Matches("cats")); EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs")); EXPECT_FALSE(m1.Matches("dogs"));
Matcher<const absl::string_view&> m2 = "cats"; Matcher<const internal::StringView&> m2 = "cats";
EXPECT_TRUE(m2.Matches("cats")); EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs")); EXPECT_FALSE(m2.Matches("dogs"));
} }
// Tests that a std::string object can be implicitly converted to a // Tests that a std::string object can be implicitly converted to a
// Matcher<absl::string_view> or Matcher<const absl::string_view&>. // Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
Matcher<absl::string_view> m1 = std::string("cats"); Matcher<internal::StringView> m1 = std::string("cats");
EXPECT_TRUE(m1.Matches("cats")); EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs")); EXPECT_FALSE(m1.Matches("dogs"));
Matcher<const absl::string_view&> m2 = std::string("cats"); Matcher<const internal::StringView&> m2 = std::string("cats");
EXPECT_TRUE(m2.Matches("cats")); EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs")); EXPECT_FALSE(m2.Matches("dogs"));
} }
// Tests that a absl::string_view object can be implicitly converted to a // Tests that a StringView object can be implicitly converted to a
// Matcher<absl::string_view> or Matcher<const absl::string_view&>. // Matcher<StringView> or Matcher<const StringView&>.
TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
Matcher<absl::string_view> m1 = absl::string_view("cats"); Matcher<internal::StringView> m1 = internal::StringView("cats");
EXPECT_TRUE(m1.Matches("cats")); EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs")); EXPECT_FALSE(m1.Matches("dogs"));
Matcher<const absl::string_view&> m2 = absl::string_view("cats"); Matcher<const internal::StringView&> m2 = internal::StringView("cats");
EXPECT_TRUE(m2.Matches("cats")); EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs")); EXPECT_FALSE(m2.Matches("dogs"));
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that a std::reference_wrapper<std::string> object can be implicitly // Tests that a std::reference_wrapper<std::string> object can be implicitly
// converted to a Matcher<std::string> or Matcher<const std::string&> via Eq(). // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
@@ -1235,17 +1235,17 @@ TEST(StrEqTest, MatchesEqualString) {
EXPECT_TRUE(m2.Matches("Hello")); EXPECT_TRUE(m2.Matches("Hello"));
EXPECT_FALSE(m2.Matches("Hi")); EXPECT_FALSE(m2.Matches("Hi"));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const absl::string_view&> m3 = StrEq("Hello"); Matcher<const internal::StringView&> m3 = StrEq("Hello");
EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
EXPECT_FALSE(m3.Matches(absl::string_view())); EXPECT_FALSE(m3.Matches(internal::StringView()));
Matcher<const absl::string_view&> m_empty = StrEq(""); Matcher<const internal::StringView&> m_empty = StrEq("");
EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
EXPECT_TRUE(m_empty.Matches(absl::string_view())); EXPECT_TRUE(m_empty.Matches(internal::StringView()));
EXPECT_FALSE(m_empty.Matches(absl::string_view("hello"))); EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
TEST(StrEqTest, CanDescribeSelf) { TEST(StrEqTest, CanDescribeSelf) {
@@ -1272,12 +1272,12 @@ TEST(StrNeTest, MatchesUnequalString) {
EXPECT_TRUE(m2.Matches("hello")); EXPECT_TRUE(m2.Matches("hello"));
EXPECT_FALSE(m2.Matches("Hello")); EXPECT_FALSE(m2.Matches("Hello"));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const absl::string_view> m3 = StrNe("Hello"); Matcher<const internal::StringView> m3 = StrNe("Hello");
EXPECT_TRUE(m3.Matches(absl::string_view(""))); EXPECT_TRUE(m3.Matches(internal::StringView("")));
EXPECT_TRUE(m3.Matches(absl::string_view())); EXPECT_TRUE(m3.Matches(internal::StringView()));
EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
TEST(StrNeTest, CanDescribeSelf) { TEST(StrNeTest, CanDescribeSelf) {
@@ -1296,13 +1296,13 @@ TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
EXPECT_TRUE(m2.Matches("hello")); EXPECT_TRUE(m2.Matches("hello"));
EXPECT_FALSE(m2.Matches("Hi")); EXPECT_FALSE(m2.Matches("Hi"));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello")); Matcher<const internal::StringView&> m3 = StrCaseEq(std::string("Hello"));
EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
EXPECT_TRUE(m3.Matches(absl::string_view("hello"))); EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
EXPECT_FALSE(m3.Matches(absl::string_view("Hi"))); EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
EXPECT_FALSE(m3.Matches(absl::string_view())); EXPECT_FALSE(m3.Matches(internal::StringView()));
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
@@ -1346,13 +1346,13 @@ TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
EXPECT_TRUE(m2.Matches("")); EXPECT_TRUE(m2.Matches(""));
EXPECT_FALSE(m2.Matches("Hello")); EXPECT_FALSE(m2.Matches("Hello"));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const absl::string_view> m3 = StrCaseNe("Hello"); Matcher<const internal::StringView> m3 = StrCaseNe("Hello");
EXPECT_TRUE(m3.Matches(absl::string_view("Hi"))); EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
EXPECT_TRUE(m3.Matches(absl::string_view())); EXPECT_TRUE(m3.Matches(internal::StringView()));
EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
TEST(StrCaseNeTest, CanDescribeSelf) { TEST(StrCaseNeTest, CanDescribeSelf) {
@@ -1393,25 +1393,25 @@ TEST(HasSubstrTest, WorksForCStrings) {
EXPECT_FALSE(m_empty.Matches(nullptr)); EXPECT_FALSE(m_empty.Matches(nullptr));
} }
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that HasSubstr() works for matching absl::string_view-typed values. // Tests that HasSubstr() works for matching StringView-typed values.
TEST(HasSubstrTest, WorksForStringViewClasses) { TEST(HasSubstrTest, WorksForStringViewClasses) {
const Matcher<absl::string_view> m1 = HasSubstr("foo"); const Matcher<internal::StringView> m1 = HasSubstr("foo");
EXPECT_TRUE(m1.Matches(absl::string_view("I love food."))); EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
EXPECT_FALSE(m1.Matches(absl::string_view("tofo"))); EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
EXPECT_FALSE(m1.Matches(absl::string_view())); EXPECT_FALSE(m1.Matches(internal::StringView()));
const Matcher<const absl::string_view&> m2 = HasSubstr("foo"); const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
EXPECT_TRUE(m2.Matches(absl::string_view("I love food."))); EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
EXPECT_FALSE(m2.Matches(absl::string_view("tofo"))); EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
EXPECT_FALSE(m2.Matches(absl::string_view())); EXPECT_FALSE(m2.Matches(internal::StringView()));
const Matcher<const absl::string_view&> m3 = HasSubstr(""); const Matcher<const internal::StringView&> m3 = HasSubstr("");
EXPECT_TRUE(m3.Matches(absl::string_view("foo"))); EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
EXPECT_TRUE(m3.Matches(absl::string_view(""))); EXPECT_TRUE(m3.Matches(internal::StringView("")));
EXPECT_TRUE(m3.Matches(absl::string_view())); EXPECT_TRUE(m3.Matches(internal::StringView()));
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Tests that HasSubstr(s) describes itself properly. // Tests that HasSubstr(s) describes itself properly.
TEST(HasSubstrTest, CanDescribeSelf) { TEST(HasSubstrTest, CanDescribeSelf) {
@@ -1648,12 +1648,12 @@ TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
EXPECT_FALSE(m2.Matches("H")); EXPECT_FALSE(m2.Matches("H"));
EXPECT_FALSE(m2.Matches(" Hi")); EXPECT_FALSE(m2.Matches(" Hi"));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<absl::string_view> m_empty = StartsWith(""); const Matcher<internal::StringView> m_empty = StartsWith("");
EXPECT_TRUE(m_empty.Matches(absl::string_view())); EXPECT_TRUE(m_empty.Matches(internal::StringView()));
EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty"))); EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
TEST(StartsWithTest, CanDescribeSelf) { TEST(StartsWithTest, CanDescribeSelf) {
@@ -1676,13 +1676,13 @@ TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
EXPECT_FALSE(m2.Matches("i")); EXPECT_FALSE(m2.Matches("i"));
EXPECT_FALSE(m2.Matches("Hi ")); EXPECT_FALSE(m2.Matches("Hi "));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<const absl::string_view&> m4 = EndsWith(""); const Matcher<const internal::StringView&> m4 = EndsWith("");
EXPECT_TRUE(m4.Matches("Hi")); EXPECT_TRUE(m4.Matches("Hi"));
EXPECT_TRUE(m4.Matches("")); EXPECT_TRUE(m4.Matches(""));
EXPECT_TRUE(m4.Matches(absl::string_view())); EXPECT_TRUE(m4.Matches(internal::StringView()));
EXPECT_TRUE(m4.Matches(absl::string_view(""))); EXPECT_TRUE(m4.Matches(internal::StringView("")));
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
TEST(EndsWithTest, CanDescribeSelf) { TEST(EndsWithTest, CanDescribeSelf) {
@@ -1703,16 +1703,16 @@ TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
EXPECT_FALSE(m2.Matches("az1")); EXPECT_FALSE(m2.Matches("az1"));
EXPECT_FALSE(m2.Matches("1az")); EXPECT_FALSE(m2.Matches("1az"));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z"); const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
EXPECT_TRUE(m3.Matches(absl::string_view("az"))); EXPECT_TRUE(m3.Matches(internal::StringView("az")));
EXPECT_TRUE(m3.Matches(absl::string_view("abcz"))); EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
EXPECT_FALSE(m3.Matches(absl::string_view("1az"))); EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
EXPECT_FALSE(m3.Matches(absl::string_view())); EXPECT_FALSE(m3.Matches(internal::StringView()));
const Matcher<const absl::string_view&> m4 = MatchesRegex(""); const Matcher<const internal::StringView&> m4 = MatchesRegex("");
EXPECT_TRUE(m4.Matches(absl::string_view(""))); EXPECT_TRUE(m4.Matches(internal::StringView("")));
EXPECT_TRUE(m4.Matches(absl::string_view())); EXPECT_TRUE(m4.Matches(internal::StringView()));
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
TEST(MatchesRegexTest, CanDescribeSelf) { TEST(MatchesRegexTest, CanDescribeSelf) {
@@ -1722,10 +1722,10 @@ TEST(MatchesRegexTest, CanDescribeSelf) {
Matcher<const char*> m2 = MatchesRegex(new RE("a.*")); Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*")); Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3)); EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
// Tests ContainsRegex(). // Tests ContainsRegex().
@@ -1741,16 +1741,17 @@ TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
EXPECT_TRUE(m2.Matches("az1")); EXPECT_TRUE(m2.Matches("az1"));
EXPECT_FALSE(m2.Matches("1a")); EXPECT_FALSE(m2.Matches("1a"));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z")); const Matcher<const internal::StringView&> m3 =
EXPECT_TRUE(m3.Matches(absl::string_view("azbz"))); ContainsRegex(new RE("a.*z"));
EXPECT_TRUE(m3.Matches(absl::string_view("az1"))); EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
EXPECT_FALSE(m3.Matches(absl::string_view("1a"))); EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
EXPECT_FALSE(m3.Matches(absl::string_view())); EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
const Matcher<const absl::string_view&> m4 = ContainsRegex(""); EXPECT_FALSE(m3.Matches(internal::StringView()));
EXPECT_TRUE(m4.Matches(absl::string_view(""))); const Matcher<const internal::StringView&> m4 = ContainsRegex("");
EXPECT_TRUE(m4.Matches(absl::string_view())); EXPECT_TRUE(m4.Matches(internal::StringView("")));
#endif // GTEST_HAS_ABSL EXPECT_TRUE(m4.Matches(internal::StringView()));
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
TEST(ContainsRegexTest, CanDescribeSelf) { TEST(ContainsRegexTest, CanDescribeSelf) {
@@ -1760,10 +1761,10 @@ TEST(ContainsRegexTest, CanDescribeSelf) {
Matcher<const char*> m2 = ContainsRegex(new RE("a.*")); Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*")); Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3)); EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} }
// Tests for wide strings. // Tests for wide strings.
@@ -2875,6 +2876,33 @@ TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
EXPECT_EQ("", listener2.str()); EXPECT_EQ("", listener2.str());
} }
MATCHER(ConstructNoArg, "") { return true; }
MATCHER_P(Construct1Arg, arg1, "") { return true; }
MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
TEST(MatcherConstruct, ExplicitVsImplicit) {
{
// No arg constructor can be constructed with empty brace.
ConstructNoArgMatcher m = {};
(void)m;
// And with no args
ConstructNoArgMatcher m2;
(void)m2;
}
{
// The one arg constructor has an explicit constructor.
// This is to prevent the implicit conversion.
using M = Construct1ArgMatcherP<int>;
EXPECT_TRUE((std::is_constructible<M, int>::value));
EXPECT_FALSE((std::is_convertible<int, M>::value));
}
{
// Multiple arg matchers can be constructed with an implicit construction.
Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
(void)m;
}
}
MATCHER_P(Really, inner_matcher, "") { MATCHER_P(Really, inner_matcher, "") {
return ExplainMatchResult(inner_matcher, arg, result_listener); return ExplainMatchResult(inner_matcher, arg, result_listener);
} }
@@ -6885,7 +6913,8 @@ TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
EXPECT_FALSE(result); // Implicit cast to bool. EXPECT_FALSE(result); // Implicit cast to bool.
std::string expect = std::string expect =
"Value of: dummy-name\nExpected: [DescribeTo]\n" "Value of: dummy-name\nExpected: [DescribeTo]\n"
" Actual: 1, [MatchAndExplain]"; " Actual: 1" +
OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
EXPECT_EQ(expect, result.message()); EXPECT_EQ(expect, result.message());
} }
@@ -6896,7 +6925,8 @@ TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
"Value of: dummy-name\nExpected: [DescribeTo]\n" "Value of: dummy-name\nExpected: [DescribeTo]\n"
" The matcher failed on the initial attempt; but passed when rerun to " " The matcher failed on the initial attempt; but passed when rerun to "
"generate the explanation.\n" "generate the explanation.\n"
" Actual: 2, [MatchAndExplain]"; " Actual: 2" +
OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
EXPECT_EQ(expect, result.message()); EXPECT_EQ(expect, result.message());
} }

View File

@@ -38,7 +38,6 @@
#include "test/gmock-actions_test.cc" #include "test/gmock-actions_test.cc"
#include "test/gmock-cardinalities_test.cc" #include "test/gmock-cardinalities_test.cc"
#include "test/gmock-generated-actions_test.cc" #include "test/gmock-generated-actions_test.cc"
#include "test/gmock-generated-function-mockers_test.cc"
#include "test/gmock-generated-matchers_test.cc" #include "test/gmock-generated-matchers_test.cc"
#include "test/gmock-internal-utils_test.cc" #include "test/gmock-internal-utils_test.cc"
#include "test/gmock-matchers_test.cc" #include "test/gmock-matchers_test.cc"

View File

@@ -638,6 +638,7 @@ Fatal assertion | Nonfatal assertion
------------------------------------------------ | ------------------------------------------------ | -------- ------------------------------------------------ | ------------------------------------------------ | --------
`ASSERT_DEATH(statement, matcher);` | `EXPECT_DEATH(statement, matcher);` | `statement` crashes with the given error `ASSERT_DEATH(statement, matcher);` | `EXPECT_DEATH(statement, matcher);` | `statement` crashes with the given error
`ASSERT_DEATH_IF_SUPPORTED(statement, matcher);` | `EXPECT_DEATH_IF_SUPPORTED(statement, matcher);` | if death tests are supported, verifies that `statement` crashes with the given error; otherwise verifies nothing `ASSERT_DEATH_IF_SUPPORTED(statement, matcher);` | `EXPECT_DEATH_IF_SUPPORTED(statement, matcher);` | if death tests are supported, verifies that `statement` crashes with the given error; otherwise verifies nothing
`ASSERT_DEBUG_DEATH(statement, matcher);` | `EXPECT_DEBUG_DEATH(statement, matcher);` | `statement` crashes with the given error **in debug mode**. When not in debug (i.e. `NDEBUG` is defined), this just executes `statement`
`ASSERT_EXIT(statement, predicate, matcher);` | `EXPECT_EXIT(statement, predicate, matcher);` | `statement` exits with the given error, and its exit code matches `predicate` `ASSERT_EXIT(statement, predicate, matcher);` | `EXPECT_EXIT(statement, predicate, matcher);` | `statement` exits with the given error, and its exit code matches `predicate`
where `statement` is a statement that is expected to cause the process to die, where `statement` is a statement that is expected to cause the process to die,
@@ -955,7 +956,7 @@ path/to/foo_test.cc:11: Failure
Value of: Bar(n) Value of: Bar(n)
Expected: 1 Expected: 1
Actual: 2 Actual: 2
Trace: Google Test trace:
path/to/foo_test.cc:17: A path/to/foo_test.cc:17: A
path/to/foo_test.cc:12: Failure path/to/foo_test.cc:12: Failure
@@ -1231,7 +1232,7 @@ environment, which knows how to set-up and tear-down:
```c++ ```c++
class Environment : public ::testing::Environment { class Environment : public ::testing::Environment {
public: public:
virtual ~Environment() {} ~Environment() override {}
// Override this to define how to set up the environment. // Override this to define how to set up the environment.
void SetUp() override {} void SetUp() override {}
@@ -1377,6 +1378,17 @@ function scope.
NOTE: Don't forget this step! If you do your test will silently pass, but none NOTE: Don't forget this step! If you do your test will silently pass, but none
of its suites will ever run! of its suites will ever run!
There is work in progress to make omitting `INSTANTIATE_TEST_SUITE_P` show up
under the `GoogleTestVerification` test suite and to then make that an error.
If you have a test suite where that omission is not an error, for example it is
in a library that may be linked in for other reason or where the list of test
cases is dynamic and may be empty, then this check can be suppressed by tagging
the test suite:
```c++
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);
```
To distinguish different instances of the pattern (yes, you can instantiate it To distinguish different instances of the pattern (yes, you can instantiate it
more than once), the first argument to `INSTANTIATE_TEST_SUITE_P` is a prefix more than once), the first argument to `INSTANTIATE_TEST_SUITE_P` is a prefix
that will be added to the actual test suite name. Remember to pick unique that will be added to the actual test suite name. Remember to pick unique

View File

@@ -384,18 +384,18 @@ class GTEST_API_ Matcher<std::string>
Matcher(const char* s); // NOLINT Matcher(const char* s); // NOLINT
}; };
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
// The following two specializations allow the user to write str // The following two specializations allow the user to write str
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
// matcher is expected. // matcher is expected.
template <> template <>
class GTEST_API_ Matcher<const absl::string_view&> class GTEST_API_ Matcher<const internal::StringView&>
: public internal::MatcherBase<const absl::string_view&> { : public internal::MatcherBase<const internal::StringView&> {
public: public:
Matcher() {} Matcher() {}
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl) explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
: internal::MatcherBase<const absl::string_view&>(impl) {} : internal::MatcherBase<const internal::StringView&>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where // Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object. // str is a std::string object.
@@ -404,20 +404,20 @@ class GTEST_API_ Matcher<const absl::string_view&>
// Allows the user to write "foo" instead of Eq("foo") sometimes. // Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT Matcher(const char* s); // NOLINT
// Allows the user to pass absl::string_views directly. // Allows the user to pass absl::string_views or std::string_views directly.
Matcher(absl::string_view s); // NOLINT Matcher(internal::StringView s); // NOLINT
}; };
template <> template <>
class GTEST_API_ Matcher<absl::string_view> class GTEST_API_ Matcher<internal::StringView>
: public internal::MatcherBase<absl::string_view> { : public internal::MatcherBase<internal::StringView> {
public: public:
Matcher() {} Matcher() {}
explicit Matcher(const MatcherInterface<const absl::string_view&>* impl) explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
: internal::MatcherBase<absl::string_view>(impl) {} : internal::MatcherBase<internal::StringView>(impl) {}
explicit Matcher(const MatcherInterface<absl::string_view>* impl) explicit Matcher(const MatcherInterface<internal::StringView>* impl)
: internal::MatcherBase<absl::string_view>(impl) {} : internal::MatcherBase<internal::StringView>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where // Allows the user to write str instead of Eq(str) sometimes, where
// str is a std::string object. // str is a std::string object.
@@ -426,10 +426,10 @@ class GTEST_API_ Matcher<absl::string_view>
// Allows the user to write "foo" instead of Eq("foo") sometimes. // Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT Matcher(const char* s); // NOLINT
// Allows the user to pass absl::string_views directly. // Allows the user to pass absl::string_views or std::string_views directly.
Matcher(absl::string_view s); // NOLINT Matcher(internal::StringView s); // NOLINT
}; };
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Prints a matcher in a human-readable format. // Prints a matcher in a human-readable format.
template <typename T> template <typename T>
@@ -620,12 +620,12 @@ class MatchesRegexMatcher {
MatchesRegexMatcher(const RE* regex, bool full_match) MatchesRegexMatcher(const RE* regex, bool full_match)
: regex_(regex), full_match_(full_match) {} : regex_(regex), full_match_(full_match) {}
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
bool MatchAndExplain(const absl::string_view& s, bool MatchAndExplain(const internal::StringView& s,
MatchResultListener* listener) const { MatchResultListener* listener) const {
return MatchAndExplain(std::string(s), listener); return MatchAndExplain(std::string(s), listener);
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Accepts pointer types, particularly: // Accepts pointer types, particularly:
// const char* // const char*

View File

@@ -58,9 +58,7 @@ class FooTest : public ::testing::TestWithParam<const char*> {
// Then, use the TEST_P macro to define as many parameterized tests // Then, use the TEST_P macro to define as many parameterized tests
// for this fixture as you want. The _P suffix is for "parameterized" // for this fixture as you want. The _P suffix is for "parameterized"
// or "pattern", whichever you prefer to think. The arguments to the // or "pattern", whichever you prefer to think.
// 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) { TEST_P(FooTest, DoesBlah) {
// Inside a test, access the test parameter with the GetParam() method // Inside a test, access the test parameter with the GetParam() method
@@ -103,10 +101,10 @@ INSTANTIATE_TEST_SUITE_P(InstantiationName,
// To distinguish different instances of the pattern, (yes, you // To distinguish different instances of the pattern, (yes, you
// can instantiate it more than once) the first argument to the // can instantiate it more than once) the first argument to the
// INSTANTIATE_TEST_SUITE_P macro is a prefix (which must be non-empty) that // INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the
// will be added to the actual test suite name. Remember to pick unique prefixes // actual test suite name. Remember to pick unique prefixes for different
// for different instantiations. The tests from the instantiation above will // instantiations. The tests from the instantiation above will have
// have these names: // these names:
// //
// * InstantiationName/FooTest.DoesBlah/0 for "meeny" // * InstantiationName/FooTest.DoesBlah/0 for "meeny"
// * InstantiationName/FooTest.DoesBlah/1 for "miny" // * InstantiationName/FooTest.DoesBlah/1 for "miny"
@@ -414,10 +412,6 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
} }
#define TEST_P(test_suite_name, test_name) \ #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) \ class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
: public test_suite_name { \ : public test_suite_name { \
public: \ public: \
@@ -464,10 +458,6 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
#define GTEST_GET_SECOND_(first, second, ...) second #define GTEST_GET_SECOND_(first, second, ...) second
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ #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> \ static ::testing::internal::ParamGenerator<test_suite_name::ParamType> \
gtest_##prefix##test_suite_name##_EvalGenerator_() { \ gtest_##prefix##test_suite_name##_EvalGenerator_() { \
return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \ return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \
@@ -501,6 +491,13 @@ internal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {
&gtest_##prefix##test_suite_name##_EvalGenerateName_, \ &gtest_##prefix##test_suite_name##_EvalGenerateName_, \
__FILE__, __LINE__) __FILE__, __LINE__)
// Allow Marking a Parameterized test class as not needing to be instantiated.
#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T) \
namespace gtest_do_not_use_outside_namespace_scope {} \
static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \
GTEST_STRINGIFY_(T))
// Legacy API is deprecated but still available // Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
#define INSTANTIATE_TEST_CASE_P \ #define INSTANTIATE_TEST_CASE_P \

View File

@@ -135,9 +135,9 @@ enum TypeKind {
kProtobuf, // a protobuf type kProtobuf, // a protobuf type
kConvertibleToInteger, // a type implicitly convertible to BiggestInt kConvertibleToInteger, // a type implicitly convertible to BiggestInt
// (e.g. a named or unnamed enum type) // (e.g. a named or unnamed enum type)
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
kConvertibleToStringView, // a type implicitly convertible to kConvertibleToStringView, // a type implicitly convertible to
// absl::string_view // absl::string_view or std::string_view
#endif #endif
kOtherType // anything else kOtherType // anything else
}; };
@@ -191,12 +191,13 @@ class TypeWithoutFormatter<T, kConvertibleToInteger> {
} }
}; };
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
template <typename T> template <typename T>
class TypeWithoutFormatter<T, kConvertibleToStringView> { class TypeWithoutFormatter<T, kConvertibleToStringView> {
public: public:
// Since T has neither operator<< nor PrintTo() but can be implicitly // Since T has neither operator<< nor PrintTo() but can be implicitly
// converted to absl::string_view, we print it as a absl::string_view. // converted to absl::string_view, we print it as a absl::string_view
// (or std::string_view).
// //
// Note: the implementation is further below, as it depends on // Note: the implementation is further below, as it depends on
// internal::PrintTo symbol which is defined later in the file. // internal::PrintTo symbol which is defined later in the file.
@@ -237,9 +238,9 @@ template <typename Char, typename CharTraits, typename T>
const T&, internal::BiggestInt>::value const T&, internal::BiggestInt>::value
? kConvertibleToInteger ? kConvertibleToInteger
: :
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
std::is_convertible< std::is_convertible<
const T&, absl::string_view>::value const T&, internal::StringView>::value
? kConvertibleToStringView ? kConvertibleToStringView
: :
#endif #endif
@@ -601,12 +602,12 @@ inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
} }
#endif // GTEST_HAS_STD_WSTRING #endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
// Overload for absl::string_view. // Overload for internal::StringView.
inline void PrintTo(absl::string_view sp, ::std::ostream* os) { inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
PrintTo(::std::string(sp), os); PrintTo(::std::string(sp), os);
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; } inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
@@ -899,12 +900,12 @@ Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
} // namespace internal } // namespace internal
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
namespace internal2 { namespace internal2 {
template <typename T> template <typename T>
void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue( void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
const T& value, ::std::ostream* os) { const T& value, ::std::ostream* os) {
internal::PrintTo(absl::string_view(value), os); internal::PrintTo(internal::StringView(value), os);
} }
} // namespace internal2 } // namespace internal2
#endif #endif

View File

@@ -297,7 +297,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
static const char* const GTEST_REGISTERED_TEST_NAMES_( \ static const char* const GTEST_REGISTERED_TEST_NAMES_( \
SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \ SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
__FILE__, __LINE__, #__VA_ARGS__) GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
// Legacy API is deprecated but still available // Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_

View File

@@ -177,6 +177,7 @@ class FuchsiaDeathTest;
class UnitTestImpl* GetUnitTestImpl(); class UnitTestImpl* GetUnitTestImpl();
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message); const std::string& message);
std::set<std::string>* GetIgnoredParameterizedTestSuites();
} // namespace internal } // namespace internal
@@ -278,7 +279,11 @@ class GTEST_API_ AssertionResult {
// Used in EXPECT_TRUE/FALSE(assertion_result). // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult& other); AssertionResult(const AssertionResult& other);
#if defined(_MSC_VER) && _MSC_VER < 1910 // C4800 is a level 3 warning in Visual Studio 2015 and earlier.
// This warning is not emitted in Visual Studio 2017.
// This warning is off by default starting in Visual Studio 2019 but can be
// enabled with command-line options.
#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
#endif #endif
@@ -298,7 +303,7 @@ class GTEST_API_ AssertionResult {
= nullptr) = nullptr)
: success_(success) {} : success_(success) {}
#if defined(_MSC_VER) && _MSC_VER < 1910 #if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
#endif #endif
@@ -412,8 +417,6 @@ class GTEST_API_ Test {
// test in test case Foo. Hence a sub-class can define its own // test in test case Foo. Hence a sub-class can define its own
// SetUpTestSuite() method to shadow the one defined in the super // SetUpTestSuite() method to shadow the one defined in the super
// class. // class.
// Failures that happen during SetUpTestSuite are logged but otherwise
// ignored.
static void SetUpTestSuite() {} static void SetUpTestSuite() {}
// Tears down the stuff shared by all tests in this test suite. // Tears down the stuff shared by all tests in this test suite.
@@ -422,8 +425,6 @@ class GTEST_API_ Test {
// test in test case Foo. Hence a sub-class can define its own // test in test case Foo. Hence a sub-class can define its own
// TearDownTestSuite() method to shadow the one defined in the super // TearDownTestSuite() method to shadow the one defined in the super
// class. // class.
// Failures that happen during TearDownTestSuite are logged but otherwise
// ignored.
static void TearDownTestSuite() {} static void TearDownTestSuite() {}
// Legacy API is deprecated but still available // Legacy API is deprecated but still available
@@ -889,7 +890,9 @@ class GTEST_API_ TestSuite {
bool Passed() const { return !Failed(); } bool Passed() const { return !Failed(); }
// Returns true if and only if the test suite failed. // Returns true if and only if the test suite failed.
bool Failed() const { return failed_test_count() > 0; } bool Failed() const {
return failed_test_count() > 0 || ad_hoc_test_result().Failed();
}
// Returns the elapsed time, in milliseconds. // Returns the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; } TimeInMillis elapsed_time() const { return elapsed_time_; }
@@ -1420,6 +1423,7 @@ class GTEST_API_ UnitTest {
friend class internal::StreamingListenerTest; friend class internal::StreamingListenerTest;
friend class internal::UnitTestRecordPropertyTestHelper; friend class internal::UnitTestRecordPropertyTestHelper;
friend Environment* AddGlobalTestEnvironment(Environment* env); friend Environment* AddGlobalTestEnvironment(Environment* env);
friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
friend internal::UnitTestImpl* internal::GetUnitTestImpl(); friend internal::UnitTestImpl* internal::GetUnitTestImpl();
friend void internal::ReportFailureInUnknownLocation( friend void internal::ReportFailureInUnknownLocation(
TestPartResult::Type result_type, TestPartResult::Type result_type,
@@ -2364,9 +2368,11 @@ constexpr bool StaticAssertTypeEq() noexcept {
// } // }
// //
// GOOGLETEST_CM0011 DO NOT DELETE // GOOGLETEST_CM0011 DO NOT DELETE
#if !GTEST_DONT_DEFINE_TEST
#define TEST_F(test_fixture, test_name)\ #define TEST_F(test_fixture, test_name)\
GTEST_TEST_(test_fixture, test_name, test_fixture, \ GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>()) ::testing::internal::GetTypeId<test_fixture>())
#endif // !GTEST_DONT_DEFINE_TEST
// Returns a path to temporary directory. // Returns a path to temporary directory.
// Tries to determine an appropriate directory for the platform. // Tries to determine an appropriate directory for the platform.

View File

@@ -79,7 +79,16 @@
#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
// Stringifies its argument. // Stringifies its argument.
#define GTEST_STRINGIFY_(name) #name // Work around a bug in visual studio which doesn't accept code like this:
//
// #define GTEST_STRINGIFY_(name) #name
// #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
// MACRO(, x, y)
//
// Complaining about the argument to GTEST_STRINGIFY_ being empty.
// This is allowed by the spec.
#define GTEST_STRINGIFY_HELPER_(name, ...) #name
#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
namespace proto2 { class Message; } namespace proto2 { class Message; }
@@ -608,8 +617,9 @@ class GTEST_API_ TypedTestSuitePState {
// Verifies that registered_tests match the test names in // Verifies that registered_tests match the test names in
// defined_test_names_; returns registered_tests if successful, or // defined_test_names_; returns registered_tests if successful, or
// aborts the program otherwise. // aborts the program otherwise.
const char* VerifyRegisteredTestNames( const char* VerifyRegisteredTestNames(const char* test_suite_name,
const char* file, int line, const char* registered_tests); const char* file, int line,
const char* registered_tests);
private: private:
typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap; typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
@@ -741,6 +751,11 @@ class TypeParameterizedTest<Fixture, TestSel, internal::None> {
} }
}; };
GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
CodeLocation code_location);
GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(
const char* case_name);
// TypeParameterizedTestSuite<Fixture, Tests, Types>::Register() // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
// registers *all combinations* of 'Tests' and 'Types' with Google // registers *all combinations* of 'Tests' and 'Types' with Google
// Test. The return value is insignificant - we just need to return // Test. The return value is insignificant - we just need to return
@@ -753,6 +768,7 @@ class TypeParameterizedTestSuite {
const char* test_names, const char* test_names,
const std::vector<std::string>& type_names = const std::vector<std::string>& type_names =
GenerateNames<DefaultNameGenerator, Types>()) { GenerateNames<DefaultNameGenerator, Types>()) {
RegisterTypeParameterizedTestSuiteInstantiation(case_name);
std::string test_name = StripTrailingSpaces( std::string test_name = StripTrailingSpaces(
GetPrefixUntilComma(test_names)); GetPrefixUntilComma(test_names));
if (!state->TestExists(test_name)) { if (!state->TestExists(test_name)) {
@@ -828,7 +844,7 @@ struct GTEST_API_ ConstCharPtr {
// Helper for declaring std::string within 'if' statement // Helper for declaring std::string within 'if' statement
// in pre C++17 build environment. // in pre C++17 build environment.
struct GTEST_API_ TrueWithString { struct TrueWithString {
TrueWithString() = default; TrueWithString() = default;
explicit TrueWithString(const char* str) : value(str) {} explicit TrueWithString(const char* str) : value(str) {}
explicit TrueWithString(const std::string& str) : value(str) {} explicit TrueWithString(const std::string& str) : value(str) {}
@@ -1389,12 +1405,15 @@ constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
: public parent_class { \ : public parent_class { \
public: \ public: \
GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)); \
GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)); \
\ \
private: \ private: \
void TestBody() override; \ void TestBody() override; \
static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
test_name)); \
}; \ }; \
\ \
::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \

View File

@@ -42,12 +42,14 @@
#include <memory> #include <memory>
#include <set> #include <set>
#include <tuple> #include <tuple>
#include <type_traits>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include "gtest/gtest-printers.h" #include "gtest/gtest-printers.h"
#include "gtest/gtest-test-part.h"
namespace testing { namespace testing {
// Input to a parameterized test name generator, describing a test parameter. // Input to a parameterized test name generator, describing a test parameter.
@@ -472,6 +474,17 @@ class ParameterizedTestSuiteInfoBase {
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase); GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase);
}; };
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Report a the name of a test_suit as safe to ignore
// as the side effect of construction of this type.
struct MarkAsIgnored {
explicit MarkAsIgnored(const char* test_suite);
};
GTEST_API_ void InsertSyntheticTestCase(const std::string& name,
CodeLocation location, bool has_test_p);
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// //
// ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P // ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P
@@ -522,11 +535,13 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
return 0; // Return value used only to run this method in namespace scope. return 0; // Return value used only to run this method in namespace scope.
} }
// UnitTest class invokes this method to register tests in this test suite // UnitTest class invokes this method to register tests in this test suite
// test suites right before running tests in RUN_ALL_TESTS macro. // right before running tests in RUN_ALL_TESTS macro.
// This method should not be called more than once on any single // This method should not be called more than once on any single
// instance of a ParameterizedTestSuiteInfoBase derived class. // instance of a ParameterizedTestSuiteInfoBase derived class.
// UnitTest has a guard to prevent from calling this method more than once. // UnitTest has a guard to prevent from calling this method more than once.
void RegisterTests() override { void RegisterTests() override {
bool generated_instantiations = false;
for (typename TestInfoContainer::iterator test_it = tests_.begin(); for (typename TestInfoContainer::iterator test_it = tests_.begin();
test_it != tests_.end(); ++test_it) { test_it != tests_.end(); ++test_it) {
std::shared_ptr<TestInfo> test_info = *test_it; std::shared_ptr<TestInfo> test_info = *test_it;
@@ -549,6 +564,8 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
for (typename ParamGenerator<ParamType>::iterator param_it = for (typename ParamGenerator<ParamType>::iterator param_it =
generator.begin(); generator.begin();
param_it != generator.end(); ++param_it, ++i) { param_it != generator.end(); ++param_it, ++i) {
generated_instantiations = true;
Message test_name_stream; Message test_name_stream;
std::string param_name = name_func( std::string param_name = name_func(
@@ -565,7 +582,10 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
test_param_names.insert(param_name); test_param_names.insert(param_name);
test_name_stream << test_info->test_base_name << "/" << param_name; if (!test_info->test_base_name.empty()) {
test_name_stream << test_info->test_base_name << "/";
}
test_name_stream << param_name;
MakeAndRegisterTestInfo( MakeAndRegisterTestInfo(
test_suite_name.c_str(), test_name_stream.GetString().c_str(), test_suite_name.c_str(), test_name_stream.GetString().c_str(),
nullptr, // No type parameter. nullptr, // No type parameter.
@@ -577,6 +597,12 @@ class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {
} // for param_it } // for param_it
} // for gen_it } // for gen_it
} // for test_it } // for test_it
if (!generated_instantiations) {
// There are no generaotrs, or they all generate nothing ...
InsertSyntheticTestCase(GetTestSuiteName(), code_location_,
!tests_.empty());
}
} // RegisterTests } // RegisterTests
private: private:
@@ -714,6 +740,34 @@ class ParameterizedTestSuiteRegistry {
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry); GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry);
}; };
// Keep track of what type-parameterized test suite are defined and
// where as well as which are intatiated. This allows susequently
// identifying suits that are defined but never used.
class TypeParameterizedTestSuiteRegistry {
public:
// Add a suite definition
void RegisterTestSuite(const char* test_suite_name,
CodeLocation code_location);
// Add an instantiation of a suit.
void RegisterInstantiation(const char* test_suite_name);
// For each suit repored as defined but not reported as instantiation,
// emit a test that reports that fact (configurably, as an error).
void CheckForInstantiations();
private:
struct TypeParameterizedTestSuiteInfo {
explicit TypeParameterizedTestSuiteInfo(CodeLocation c)
: code_location(c), instantiated(false) {}
CodeLocation code_location;
bool instantiated;
};
std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;
};
} // namespace internal } // namespace internal
// Forward declarations of ValuesIn(), which is implemented in // Forward declarations of ValuesIn(), which is implemented in

View File

@@ -190,13 +190,18 @@
// GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.
// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a
// variable don't have to be used. // variable don't have to be used.
// GTEST_DISALLOW_ASSIGN_ - disables operator=. // GTEST_DISALLOW_ASSIGN_ - disables copy operator=.
// GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=.
// GTEST_DISALLOW_MOVE_ASSIGN_ - disables move operator=.
// GTEST_DISALLOW_MOVE_AND_ASSIGN_ - disables move ctor and operator=.
// GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used.
// GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is
// suppressed (constant conditional). // suppressed (constant conditional).
// GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127
// is suppressed. // is suppressed.
// GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
// Matcher<absl::string_view>
// specializations.
// //
// Synchronization: // Synchronization:
// Mutex, MutexLock, ThreadLocal, GetThreadCount() // Mutex, MutexLock, ThreadLocal, GetThreadCount()
@@ -666,10 +671,10 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
#endif #endif
// A macro to disallow operator= // A macro to disallow copy operator=
// This should be used in the private: declarations for a class. // This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_ASSIGN_(type) \ #define GTEST_DISALLOW_ASSIGN_(type) \
void operator=(type const &) = delete type& operator=(type const &) = delete
// A macro to disallow copy constructor and operator= // A macro to disallow copy constructor and operator=
// This should be used in the private: declarations for a class. // This should be used in the private: declarations for a class.
@@ -677,6 +682,17 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;
type(type const &) = delete; \ type(type const &) = delete; \
GTEST_DISALLOW_ASSIGN_(type) GTEST_DISALLOW_ASSIGN_(type)
// A macro to disallow move operator=
// This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_MOVE_ASSIGN_(type) \
type& operator=(type &&) noexcept = delete
// A macro to disallow move constructor and operator=
// This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
type(type &&) noexcept = delete; \
GTEST_DISALLOW_MOVE_ASSIGN_(type)
// Tell the compiler to warn about unused return values for functions declared // Tell the compiler to warn about unused return values for functions declared
// with this macro. The macro should be used on function declarations // with this macro. The macro should be used on function declarations
// following the argument list: // following the argument list:
@@ -2207,4 +2223,32 @@ const char* StringFromGTestEnv(const char* flag, const char* default_val);
#endif // !defined(GTEST_INTERNAL_DEPRECATED) #endif // !defined(GTEST_INTERNAL_DEPRECATED)
#if GTEST_HAS_ABSL
// Always use absl::string_view for Matcher<> specializations if googletest
// is built with absl support.
# define GTEST_INTERNAL_HAS_STRING_VIEW 1
#include "absl/strings/string_view.h"
namespace testing {
namespace internal {
using StringView = ::absl::string_view;
} // namespace internal
} // namespace testing
#else
# ifdef __has_include
# if __has_include(<string_view>) && __cplusplus >= 201703L
// Otherwise for C++17 and higher use std::string_view for Matcher<>
// specializations.
# define GTEST_INTERNAL_HAS_STRING_VIEW 1
#include <string_view>
namespace testing {
namespace internal {
using StringView = ::std::string_view;
} // namespace internal
} // namespace testing
// The case where absl is configured NOT to alias std::string_view is not
// supported.
# endif // __has_include(<string_view>) && __cplusplus >= 201703L
# endif // __has_include
#endif // GTEST_HAS_ABSL
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_

View File

@@ -66,11 +66,11 @@ class OnTheFlyPrimeTable : public PrimeTable {
} }
int GetNextPrime(int p) const override { int GetNextPrime(int p) const override {
for (int n = p + 1; n > 0; n++) { if (p < 0) return -1;
for (int n = p + 1;; n++) {
if (IsPrime(n)) return n; if (IsPrime(n)) return n;
} }
return -1;
} }
}; };

View File

@@ -698,6 +698,17 @@ class GTEST_API_ UnitTestImpl {
return parameterized_test_registry_; return parameterized_test_registry_;
} }
std::set<std::string>* ignored_parameterized_test_suites() {
return &ignored_parameterized_test_suites_;
}
// Returns TypeParameterizedTestSuiteRegistry object used to keep track of
// type-parameterized tests and instantiations of them.
internal::TypeParameterizedTestSuiteRegistry&
type_parameterized_test_registry() {
return type_parameterized_test_registry_;
}
// Sets the TestSuite object for the test that's currently running. // Sets the TestSuite object for the test that's currently running.
void set_current_test_suite(TestSuite* a_current_test_suite) { void set_current_test_suite(TestSuite* a_current_test_suite) {
current_test_suite_ = a_current_test_suite; current_test_suite_ = a_current_test_suite;
@@ -874,6 +885,12 @@ class GTEST_API_ UnitTestImpl {
// ParameterizedTestRegistry object used to register value-parameterized // ParameterizedTestRegistry object used to register value-parameterized
// tests. // tests.
internal::ParameterizedTestSuiteRegistry parameterized_test_registry_; internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
internal::TypeParameterizedTestSuiteRegistry
type_parameterized_test_registry_;
// The set holding the name of parameterized
// test suites that may go uninstantiated.
std::set<std::string> ignored_parameterized_test_suites_;
// Indicates whether RegisterParameterizedTests() has been called already. // Indicates whether RegisterParameterizedTests() has been called already.
bool parameterized_tests_registered_; bool parameterized_tests_registered_;

View File

@@ -58,40 +58,40 @@ Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
// s. // s.
Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); } Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
// Constructs a matcher that matches a const absl::string_view& whose value is // Constructs a matcher that matches a const StringView& whose value is
// equal to s. // equal to s.
Matcher<const absl::string_view&>::Matcher(const std::string& s) { Matcher<const internal::StringView&>::Matcher(const std::string& s) {
*this = Eq(s); *this = Eq(s);
} }
// Constructs a matcher that matches a const absl::string_view& whose value is // Constructs a matcher that matches a const StringView& whose value is
// equal to s. // equal to s.
Matcher<const absl::string_view&>::Matcher(const char* s) { Matcher<const internal::StringView&>::Matcher(const char* s) {
*this = Eq(std::string(s)); *this = Eq(std::string(s));
} }
// Constructs a matcher that matches a const absl::string_view& whose value is // Constructs a matcher that matches a const StringView& whose value is
// equal to s. // equal to s.
Matcher<const absl::string_view&>::Matcher(absl::string_view s) { Matcher<const internal::StringView&>::Matcher(internal::StringView s) {
*this = Eq(std::string(s)); *this = Eq(std::string(s));
} }
// Constructs a matcher that matches a absl::string_view whose value is equal to // Constructs a matcher that matches a StringView whose value is equal to
// s. // s.
Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); } Matcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); }
// Constructs a matcher that matches a absl::string_view whose value is equal to // Constructs a matcher that matches a StringView whose value is equal to
// s. // s.
Matcher<absl::string_view>::Matcher(const char* s) { Matcher<internal::StringView>::Matcher(const char* s) {
*this = Eq(std::string(s)); *this = Eq(std::string(s));
} }
// Constructs a matcher that matches a absl::string_view whose value is equal to // Constructs a matcher that matches a StringView whose value is equal to
// s. // s.
Matcher<absl::string_view>::Matcher(absl::string_view s) { Matcher<internal::StringView>::Matcher(internal::StringView s) {
*this = Eq(std::string(s)); *this = Eq(std::string(s));
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
} // namespace testing } // namespace testing

View File

@@ -58,7 +58,10 @@ static std::vector<std::string> SplitIntoTestNames(const char* src) {
// registered_tests_; returns registered_tests if successful, or // registered_tests_; returns registered_tests if successful, or
// aborts the program otherwise. // aborts the program otherwise.
const char* TypedTestSuitePState::VerifyRegisteredTestNames( const char* TypedTestSuitePState::VerifyRegisteredTestNames(
const char* file, int line, const char* registered_tests) { const char* test_suite_name, const char* file, int line,
const char* registered_tests) {
RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line));
typedef RegisteredTestsMap::const_iterator RegisteredTestIter; typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
registered_ = true; registered_ = true;

View File

@@ -407,6 +407,162 @@ void AssertHelper::operator=(const Message& message) const {
); // NOLINT ); // NOLINT
} }
namespace {
// When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P
// to creates test cases for it, a syntetic test case is
// inserted to report ether an error or a log message.
//
// This configuration bit will likely be removed at some point.
constexpr bool kErrorOnUninstantiatedParameterizedTest = false;
constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = false;
// A test that fails at a given file/line location with a given message.
class FailureTest : public Test {
public:
explicit FailureTest(const CodeLocation& loc, std::string error_message,
bool as_error)
: loc_(loc),
error_message_(std::move(error_message)),
as_error_(as_error) {}
void TestBody() override {
if (as_error_) {
AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),
loc_.line, "") = Message() << error_message_;
} else {
std::cout << error_message_ << std::endl;
}
}
private:
const CodeLocation loc_;
const std::string error_message_;
const bool as_error_;
};
} // namespace
std::set<std::string>* GetIgnoredParameterizedTestSuites() {
return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();
}
// Add a given test_suit to the list of them allow to go un-instantiated.
MarkAsIgnored::MarkAsIgnored(const char* test_suite) {
GetIgnoredParameterizedTestSuites()->insert(test_suite);
}
// If this parameterized test suite has no instantiations (and that
// has not been marked as okay), emit a test case reporting that.
void InsertSyntheticTestCase(const std::string& name, CodeLocation location,
bool has_test_p) {
const auto& ignored = *GetIgnoredParameterizedTestSuites();
if (ignored.find(name) != ignored.end()) return;
const char kMissingInstantiation[] = //
" is defined via TEST_P, but never instantiated. None of the test cases "
"will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only "
"ones provided expand to nothing."
"\n\n"
"Ideally, TEST_P definitions should only ever be included as part of "
"binaries that intend to use them. (As opposed to, for example, being "
"placed in a library that may be linked in to get other utilities.)";
const char kMissingTestCase[] = //
" is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are "
"defined via TEST_P . No test cases will run."
"\n\n"
"Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from "
"code that always depend on code that provides TEST_P. Failing to do "
"so is often an indication of dead code, e.g. the last TEST_P was "
"removed but the rest got left behind.";
std::string message =
"Paramaterized test suite " + name +
(has_test_p ? kMissingInstantiation : kMissingTestCase) +
"\n\n"
"To suppress this error for this test suite, insert the following line "
"(in a non-header) in the namespace it is defined in:"
"\n\n"
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");";
std::string full_name = "UninstantiatedParamaterizedTestSuite<" + name + ">";
RegisterTest( //
"GoogleTestVerification", full_name.c_str(),
nullptr, // No type parameter.
nullptr, // No value parameter.
location.file.c_str(), location.line, [message, location] {
return new FailureTest(location, message,
kErrorOnUninstantiatedParameterizedTest);
});
}
void RegisterTypeParameterizedTestSuite(const char* test_suite_name,
CodeLocation code_location) {
GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(
test_suite_name, code_location);
}
void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {
GetUnitTestImpl()
->type_parameterized_test_registry()
.RegisterInstantiation(case_name);
}
void TypeParameterizedTestSuiteRegistry::RegisterTestSuite(
const char* test_suite_name, CodeLocation code_location) {
suites_.emplace(std::string(test_suite_name),
TypeParameterizedTestSuiteInfo(code_location));
}
void TypeParameterizedTestSuiteRegistry::RegisterInstantiation(
const char* test_suite_name) {
auto it = suites_.find(std::string(test_suite_name));
if (it != suites_.end()) {
it->second.instantiated = true;
} else {
GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '"
<< test_suite_name << "'";
}
}
void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {
const auto& ignored = *GetIgnoredParameterizedTestSuites();
for (const auto& testcase : suites_) {
if (testcase.second.instantiated) continue;
if (ignored.find(testcase.first) != ignored.end()) continue;
std::string message =
"Type paramaterized test suite " + testcase.first +
" is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated "
"via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run."
"\n\n"
"Ideally, TYPED_TEST_P definitions should only ever be included as "
"part of binaries that intend to use them. (As opposed to, for "
"example, being placed in a library that may be linked in to get other "
"utilities.)"
"\n\n"
"To suppress this error for this test suite, insert the following line "
"(in a non-header) in the namespace it is definedin in:"
"\n\n"
"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" +
testcase.first + ");";
std::string full_name =
"UninstantiatedTypeParamaterizedTestSuite<" + testcase.first + ">";
RegisterTest( //
"GoogleTestVerification", full_name.c_str(),
nullptr, // No type parameter.
nullptr, // No value parameter.
testcase.second.code_location.file.c_str(),
testcase.second.code_location.line, [message, testcase] {
return new FailureTest(testcase.second.code_location, message,
kErrorOnUninstantiatedTypeParameterizedTest);
});
}
}
// A copy of all command line arguments. Set by InitGoogleTest(). // A copy of all command line arguments. Set by InitGoogleTest().
static ::std::vector<std::string> g_argvs; static ::std::vector<std::string> g_argvs;
@@ -2650,6 +2806,7 @@ namespace internal {
void UnitTestImpl::RegisterParameterizedTests() { void UnitTestImpl::RegisterParameterizedTests() {
if (!parameterized_tests_registered_) { if (!parameterized_tests_registered_) {
parameterized_test_registry_.RegisterTests(); parameterized_test_registry_.RegisterTests();
type_parameterized_test_registry_.CheckForInstantiations();
parameterized_tests_registered_ = true; parameterized_tests_registered_ = true;
} }
} }
@@ -3138,6 +3295,7 @@ class PrettyUnitTestResultPrinter : public TestEventListener {
private: private:
static void PrintFailedTests(const UnitTest& unit_test); static void PrintFailedTests(const UnitTest& unit_test);
static void PrintFailedTestSuites(const UnitTest& unit_test);
static void PrintSkippedTests(const UnitTest& unit_test); static void PrintSkippedTests(const UnitTest& unit_test);
}; };
@@ -3290,9 +3448,8 @@ void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
// Internal helper for printing the list of failed tests. // Internal helper for printing the list of failed tests.
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
const int failed_test_count = unit_test.failed_test_count(); const int failed_test_count = unit_test.failed_test_count();
if (failed_test_count == 0) { ColoredPrintf(COLOR_RED, "[ FAILED ] ");
return; printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
}
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
const TestSuite& test_suite = *unit_test.GetTestSuite(i); const TestSuite& test_suite = *unit_test.GetTestSuite(i);
@@ -3310,6 +3467,30 @@ void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
printf("\n"); printf("\n");
} }
} }
printf("\n%2d FAILED %s\n", failed_test_count,
failed_test_count == 1 ? "TEST" : "TESTS");
}
// Internal helper for printing the list of test suite failures not covered by
// PrintFailedTests.
void PrettyUnitTestResultPrinter::PrintFailedTestSuites(
const UnitTest& unit_test) {
int suite_failure_count = 0;
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
const TestSuite& test_suite = *unit_test.GetTestSuite(i);
if (!test_suite.should_run()) {
continue;
}
if (test_suite.ad_hoc_test_result().Failed()) {
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name());
++suite_failure_count;
}
}
if (suite_failure_count > 0) {
printf("\n%2d FAILED TEST %s\n", suite_failure_count,
suite_failure_count == 1 ? "SUITE" : "SUITES");
}
} }
// Internal helper for printing the list of skipped tests. // Internal helper for printing the list of skipped tests.
@@ -3357,19 +3538,14 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
PrintSkippedTests(unit_test); PrintSkippedTests(unit_test);
} }
int num_failures = unit_test.failed_test_count();
if (!unit_test.Passed()) { if (!unit_test.Passed()) {
const int failed_test_count = unit_test.failed_test_count();
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
PrintFailedTests(unit_test); PrintFailedTests(unit_test);
printf("\n%2d FAILED %s\n", num_failures, PrintFailedTestSuites(unit_test);
num_failures == 1 ? "TEST" : "TESTS");
} }
int num_disabled = unit_test.reportable_disabled_test_count(); int num_disabled = unit_test.reportable_disabled_test_count();
if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
if (!num_failures) { if (unit_test.Passed()) {
printf("\n"); // Add a spacer if no FAILURE banner is displayed. printf("\n"); // Add a spacer if no FAILURE banner is displayed.
} }
ColoredPrintf(COLOR_YELLOW, ColoredPrintf(COLOR_YELLOW,
@@ -6151,7 +6327,11 @@ std::string TempDir() {
else else
return std::string(temp_dir) + "\\"; return std::string(temp_dir) + "\\";
#elif GTEST_OS_LINUX_ANDROID #elif GTEST_OS_LINUX_ANDROID
return "/sdcard/"; const char* temp_dir = internal::posix::GetEnv("TEST_TMPDIR");
if (temp_dir == nullptr || temp_dir[0] == '\0')
return "/data/local/tmp/";
else
return temp_dir;
#else #else
return "/tmp/"; return "/tmp/";
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE

View File

@@ -27,7 +27,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream> #include <cstdio>
#include "gtest/gtest.h" #include "gtest/gtest.h"
#if GTEST_OS_ESP8266 || GTEST_OS_ESP32 #if GTEST_OS_ESP8266 || GTEST_OS_ESP32
@@ -45,14 +45,9 @@ void loop() { RUN_ALL_TESTS(); }
#endif #endif
#else #else
#if __MSC_VER
# include <tchar.h> // NOLINT
GTEST_API_ int _tmain(int argc, TCHAR** argv) { GTEST_API_ int main(int argc, char **argv) {
#else printf("Running main() from %s\n", __FILE__);
GTEST_API_ int main(int argc, char** argv) {
#endif // __MSC_VER
std::cout << "Running main() from " << __FILE__ << '\n';
testing::InitGoogleTest(&argc, argv); testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }

View File

@@ -56,6 +56,7 @@ cc_test(
"gtest-listener_test.cc", "gtest-listener_test.cc",
"gtest-unittest-api_test.cc", "gtest-unittest-api_test.cc",
"googletest-param-test-test.cc", "googletest-param-test-test.cc",
"googletest-param-test2-test.cc",
"googletest-catch-exceptions-test_.cc", "googletest-catch-exceptions-test_.cc",
"googletest-color-test_.cc", "googletest-color-test_.cc",
"googletest-env-var-test_.cc", "googletest-env-var-test_.cc",
@@ -65,6 +66,7 @@ cc_test(
"googletest-output-test_.cc", "googletest-output-test_.cc",
"googletest-list-tests-unittest_.cc", "googletest-list-tests-unittest_.cc",
"googletest-shuffle-test_.cc", "googletest-shuffle-test_.cc",
"googletest-setuptestsuite-test_.cc",
"googletest-uninitialized-test_.cc", "googletest-uninitialized-test_.cc",
"googletest-death-test_ex_test.cc", "googletest-death-test_ex_test.cc",
"googletest-param-test-test", "googletest-param-test-test",
@@ -423,6 +425,21 @@ py_test(
deps = [":gtest_test_utils"], deps = [":gtest_test_utils"],
) )
cc_binary(
name = "googletest-setuptestsuite-test_",
testonly = 1,
srcs = ["googletest-setuptestsuite-test_.cc"],
deps = ["//:gtest_main"],
)
py_test(
name = "googletest-setuptestsuite-test",
size = "medium",
srcs = ["googletest-setuptestsuite-test.py"],
data = [":googletest-setuptestsuite-test_"],
deps = [":gtest_test_utils"],
)
cc_binary( cc_binary(
name = "googletest-uninitialized-test_", name = "googletest-uninitialized-test_",
testonly = 1, testonly = 1,

View File

@@ -12,7 +12,7 @@ Expected equality of these values:
3 3
Stack trace: (omitted) Stack trace: (omitted)
[==========] Running 84 tests from 39 test suites. [==========] Running 88 tests from 41 test suites.
[----------] Global test environment set-up. [----------] Global test environment set-up.
FooEnvironment::SetUp() called. FooEnvironment::SetUp() called.
BarEnvironment::SetUp() called. BarEnvironment::SetUp() called.
@@ -966,6 +966,9 @@ Expected equality of these values:
Stack trace: (omitted) Stack trace: (omitted)
[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 [ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2
[----------] 1 test from EmptyBasenameParamInst
[ RUN ] EmptyBasenameParamInst.Passes/0
[ OK ] EmptyBasenameParamInst.Passes/0
[----------] 2 tests from PrintingStrings/ParamTest [----------] 2 tests from PrintingStrings/ParamTest
[ RUN ] PrintingStrings/ParamTest.Success/a [ RUN ] PrintingStrings/ParamTest.Success/a
[ OK ] PrintingStrings/ParamTest.Success/a [ OK ] PrintingStrings/ParamTest.Success/a
@@ -979,6 +982,34 @@ Expected failure
Stack trace: (omitted) Stack trace: (omitted)
[ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" [ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a"
[----------] 3 tests from GoogleTestVerification
[ RUN ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<NoTests>
Paramaterized test suite NoTests is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are defined via TEST_P . No test cases will run.
Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from code that always depend on code that provides TEST_P. Failing to do so is often an indication of dead code, e.g. the last TEST_P was removed but the rest got left behind.
To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NoTests);
[ OK ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<NoTests>
[ RUN ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<DetectNotInstantiatedTest>
Paramaterized test suite DetectNotInstantiatedTest is defined via TEST_P, but never instantiated. None of the test cases will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only ones provided expand to nothing.
Ideally, TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)
To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTest);
[ OK ] GoogleTestVerification.UninstantiatedParamaterizedTestSuite<DetectNotInstantiatedTest>
[ RUN ] GoogleTestVerification.UninstantiatedTypeParamaterizedTestSuite<DetectNotInstantiatedTypesTest>
Type paramaterized test suite DetectNotInstantiatedTypesTest is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run.
Ideally, TYPED_TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)
To suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is definedin in:
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTypesTest);
[ OK ] GoogleTestVerification.UninstantiatedTypeParamaterizedTestSuite<DetectNotInstantiatedTypesTest>
[----------] Global test environment tear-down [----------] Global test environment tear-down
BarEnvironment::TearDown() called. BarEnvironment::TearDown() called.
googletest-output-test_.cc:#: Failure googletest-output-test_.cc:#: Failure
@@ -992,8 +1023,8 @@ Failed
Expected fatal failure. Expected fatal failure.
Stack trace: (omitted) Stack trace: (omitted)
[==========] 84 tests from 39 test suites ran. [==========] 88 tests from 41 test suites ran.
[ PASSED ] 30 tests. [ PASSED ] 34 tests.
[ FAILED ] 54 tests, listed below: [ FAILED ] 54 tests, listed below:
[ FAILED ] NonfatalFailureTest.EscapesStringOperands [ FAILED ] NonfatalFailureTest.EscapesStringOperands
[ FAILED ] NonfatalFailureTest.DiffForLongStrings [ FAILED ] NonfatalFailureTest.DiffForLongStrings

View File

@@ -29,7 +29,7 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests the text output of Google C++ Testing and Mocking Framework. r"""Tests the text output of Google C++ Testing and Mocking Framework.
To update the golden file: To update the golden file:
googletest_output_test.py --build_dir=BUILD/DIR --gengolden googletest_output_test.py --build_dir=BUILD/DIR --gengolden

View File

@@ -96,6 +96,14 @@ INSTANTIATE_TEST_SUITE_P(PrintingFailingParams,
FailingParamTest, FailingParamTest,
testing::Values(2)); testing::Values(2));
// Tests that an empty value for the test suite basename yields just
// the test name without any prior /
class EmptyBasenameParamInst : public testing::TestWithParam<int> {};
TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); }
INSTANTIATE_TEST_SUITE_P(, EmptyBasenameParamInst, testing::Values(1));
static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; static const char kGoldenString[] = "\"Line\0 1\"\nLine 2";
TEST(NonfatalFailureTest, EscapesStringOperands) { TEST(NonfatalFailureTest, EscapesStringOperands) {
@@ -782,6 +790,17 @@ INSTANTIATE_TEST_SUITE_P(PrintingStrings,
testing::Values(std::string("a")), testing::Values(std::string("a")),
ParamNameFunc); ParamNameFunc);
// The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.
using NoTests = ParamTest;
INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello"));
// fails under kErrorOnUninstantiatedParameterizedTest=true
class DetectNotInstantiatedTest : public testing::TestWithParam<int> {};
TEST_P(DetectNotInstantiatedTest, Used) { }
// This would make the test failure from the above go away.
// INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));
// This #ifdef block tests the output of typed tests. // This #ifdef block tests the output of typed tests.
#if GTEST_HAS_TYPED_TEST #if GTEST_HAS_TYPED_TEST
@@ -861,6 +880,21 @@ class TypedTestPNames {
INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
TypedTestPNames); TypedTestPNames);
template <typename T>
class DetectNotInstantiatedTypesTest : public testing::Test {};
TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest);
TYPED_TEST_P(DetectNotInstantiatedTypesTest, Used) {
TypeParam instantiate;
(void)instantiate;
}
REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
// kErrorOnUninstantiatedTypeParameterizedTest=true would make the above fail.
// Adding the following would make that test failure go away.
//
// typedef ::testing::Types<char, int, unsigned int> MyTypes;
// INSTANTIATE_TYPED_TEST_SUITE_P(All, DetectNotInstantiatedTypesTest, MyTypes);
#endif // GTEST_HAS_TYPED_TEST_P #endif // GTEST_HAS_TYPED_TEST_P
#if GTEST_HAS_DEATH_TEST #if GTEST_HAS_DEATH_TEST

View File

@@ -1068,6 +1068,38 @@ TEST_P(MyEnumTest, ChecksParamMoreThanZero) { EXPECT_GE(10, GetParam()); }
INSTANTIATE_TEST_SUITE_P(MyEnumTests, MyEnumTest, INSTANTIATE_TEST_SUITE_P(MyEnumTests, MyEnumTest,
::testing::Values(ENUM1, ENUM2, 0)); ::testing::Values(ENUM1, ENUM2, 0));
namespace works_here {
// Never used not instantiated, this should work.
class NotUsedTest : public testing::TestWithParam<int> {};
///////
// Never used not instantiated, this should work.
template <typename T>
class NotUsedTypeTest : public testing::Test {};
TYPED_TEST_SUITE_P(NotUsedTypeTest);
// Used but not instantiated, this would fail. but...
class NotInstantiatedTest : public testing::TestWithParam<int> {};
// ... we mark is as allowed.
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest);
TEST_P(NotInstantiatedTest, Used) { }
using OtherName = NotInstantiatedTest;
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName);
TEST_P(OtherName, Used) { }
// Used but not instantiated, this would fail. but...
template <typename T>
class NotInstantiatedTypeTest : public testing::Test {};
TYPED_TEST_SUITE_P(NotInstantiatedTypeTest);
// ... we mark is as allowed.
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest);
TYPED_TEST_P(NotInstantiatedTypeTest, Used) { }
REGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used);
} // namespace works_here
int main(int argc, char **argv) { int main(int argc, char **argv) {
// Used in TestGenerationTest test suite. // Used in TestGenerationTest test suite.
AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());

View File

@@ -760,22 +760,22 @@ TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a)); EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
} }
#if GTEST_HAS_ABSL #if GTEST_INTERNAL_HAS_STRING_VIEW
// Tests printing ::absl::string_view. // Tests printing internal::StringView.
TEST(PrintStringViewTest, SimpleStringView) { TEST(PrintStringViewTest, SimpleStringView) {
const ::absl::string_view sp = "Hello"; const internal::StringView sp = "Hello";
EXPECT_EQ("\"Hello\"", Print(sp)); EXPECT_EQ("\"Hello\"", Print(sp));
} }
TEST(PrintStringViewTest, UnprintableCharacters) { TEST(PrintStringViewTest, UnprintableCharacters) {
const char str[] = "NUL (\0) and \r\t"; const char str[] = "NUL (\0) and \r\t";
const ::absl::string_view sp(str, sizeof(str) - 1); const internal::StringView sp(str, sizeof(str) - 1);
EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp)); EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
} }
#endif // GTEST_HAS_ABSL #endif // GTEST_INTERNAL_HAS_STRING_VIEW
// Tests printing STL containers. // Tests printing STL containers.

View File

@@ -0,0 +1,54 @@
#!/usr/bin/env python
#
# Copyright 2019, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that SetUpTestSuite and TearDownTestSuite errors are noticed."""
import gtest_test_utils
COMMAND = gtest_test_utils.GetTestExecutablePath(
'googletest-setuptestsuite-test_')
class GTestSetUpTestSuiteTest(gtest_test_utils.TestCase):
def testSetupErrorAndTearDownError(self):
p = gtest_test_utils.Subprocess(COMMAND)
self.assertNotEqual(p.exit_code, 0, msg=p.output)
self.assertIn(
'[ FAILED ] SetupFailTest: SetUpTestSuite or TearDownTestSuite\n'
'[ FAILED ] TearDownFailTest: SetUpTestSuite or TearDownTestSuite\n'
'\n'
' 2 FAILED TEST SUITES\n',
p.output)
if __name__ == '__main__':
gtest_test_utils.Main()

View File

@@ -27,35 +27,23 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Tests for Google Test itself. This verifies that the basic constructs of
// Google Test work.
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "googletest-param-test-test.h"
using ::testing::Values; class SetupFailTest : public ::testing::Test {
using ::testing::internal::ParamGenerator; protected:
static void SetUpTestSuite() {
ASSERT_EQ("", "SET_UP_FAIL");
}
};
// Tests that generators defined in a different translation unit TEST_F(SetupFailTest, NoopPassingTest) {}
// are functional. The test using extern_gen_2 is defined
// in googletest-param-test-test.cc.
ParamGenerator<int> extern_gen_2 = Values(33);
// Tests that a parameterized test case can be defined in one translation unit class TearDownFailTest : public ::testing::Test {
// and instantiated in another. The test is defined in protected:
// googletest-param-test-test.cc and ExternalInstantiationTest fixture class is static void TearDownTestSuite() {
// defined in gtest-param-test_test.h. ASSERT_EQ("", "TEAR_DOWN_FAIL");
INSTANTIATE_TEST_SUITE_P(MultiplesOf33, }
ExternalInstantiationTest, };
Values(33, 66));
// Tests that a parameterized test case can be instantiated
// in multiple translation units. Another instantiation is defined
// in googletest-param-test-test.cc and
// InstantiationInMultipleTranslationUnitsTest fixture is defined in
// gtest-param-test_test.h
INSTANTIATE_TEST_SUITE_P(Sequence2,
InstantiationInMultipleTranslationUnitsTest,
Values(42*3, 42*4, 42*5));
TEST_F(TearDownFailTest, NoopPassingTest) {}

View File

@@ -228,7 +228,7 @@ class TypedTestSuitePStateTest : public Test {
TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) { TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) {
const char* tests = "A, B, C"; const char* tests = "A, B, C";
EXPECT_EQ(tests, EXPECT_EQ(tests,
state_.VerifyRegisteredTestNames("foo.cc", 1, tests)); state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests));
} }
// Makes sure that the order of the tests and spaces around the names // Makes sure that the order of the tests and spaces around the names
@@ -236,33 +236,33 @@ TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) {
TEST_F(TypedTestSuitePStateTest, IgnoresOrderAndSpaces) { TEST_F(TypedTestSuitePStateTest, IgnoresOrderAndSpaces) {
const char* tests = "A,C, B"; const char* tests = "A,C, B";
EXPECT_EQ(tests, EXPECT_EQ(tests,
state_.VerifyRegisteredTestNames("foo.cc", 1, tests)); state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests));
} }
using TypedTestSuitePStateDeathTest = TypedTestSuitePStateTest; using TypedTestSuitePStateDeathTest = TypedTestSuitePStateTest;
TEST_F(TypedTestSuitePStateDeathTest, DetectsDuplicates) { TEST_F(TypedTestSuitePStateDeathTest, DetectsDuplicates) {
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(
state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, A, C"), state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, A, C"),
"foo\\.cc.1.?: Test A is listed more than once\\."); "foo\\.cc.1.?: Test A is listed more than once\\.");
} }
TEST_F(TypedTestSuitePStateDeathTest, DetectsExtraTest) { TEST_F(TypedTestSuitePStateDeathTest, DetectsExtraTest) {
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(
state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C, D"), state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C, D"),
"foo\\.cc.1.?: No test named D can be found in this test suite\\."); "foo\\.cc.1.?: No test named D can be found in this test suite\\.");
} }
TEST_F(TypedTestSuitePStateDeathTest, DetectsMissedTest) { TEST_F(TypedTestSuitePStateDeathTest, DetectsMissedTest) {
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(
state_.VerifyRegisteredTestNames("foo.cc", 1, "A, C"), state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, C"),
"foo\\.cc.1.?: You forgot to list test B\\."); "foo\\.cc.1.?: You forgot to list test B\\.");
} }
// Tests that defining a test for a parameterized test case generates // Tests that defining a test for a parameterized test case generates
// a run-time error if the test case has been registered. // a run-time error if the test case has been registered.
TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) { TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) {
state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C"); state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C");
EXPECT_DEATH_IF_SUPPORTED( EXPECT_DEATH_IF_SUPPORTED(
state_.AddTestName("foo.cc", 2, "FooTest", "D"), state_.AddTestName("foo.cc", 2, "FooTest", "D"),
"foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P" "foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P"

View File

@@ -2923,22 +2923,18 @@ TEST_F(FloatTest, Commutative) {
TEST_F(FloatTest, EXPECT_NEAR) { TEST_F(FloatTest, EXPECT_NEAR) {
EXPECT_NEAR(-1.0f, -1.1f, 0.2f); EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
EXPECT_NEAR(2.0f, 3.0f, 1.0f); EXPECT_NEAR(2.0f, 3.0f, 1.0f);
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
"The difference between 1.0f and 1.5f is 0.5, " "The difference between 1.0f and 1.5f is 0.5, "
"which exceeds 0.25f"); "which exceeds 0.25f");
// To work around a bug in gcc 2.95.0, there is intentionally no
// space after the first comma in the previous line.
} }
// Tests ASSERT_NEAR. // Tests ASSERT_NEAR.
TEST_F(FloatTest, ASSERT_NEAR) { TEST_F(FloatTest, ASSERT_NEAR) {
ASSERT_NEAR(-1.0f, -1.1f, 0.2f); ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
ASSERT_NEAR(2.0f, 3.0f, 1.0f); ASSERT_NEAR(2.0f, 3.0f, 1.0f);
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
"The difference between 1.0f and 1.5f is 0.5, " "The difference between 1.0f and 1.5f is 0.5, "
"which exceeds 0.25f"); "which exceeds 0.25f");
// To work around a bug in gcc 2.95.0, there is intentionally no
// space after the first comma in the previous line.
} }
// Tests the cases where FloatLE() should succeed. // Tests the cases where FloatLE() should succeed.
@@ -3079,8 +3075,6 @@ TEST_F(DoubleTest, EXPECT_NEAR) {
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, " "The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25"); "which exceeds 0.25");
// To work around a bug in gcc 2.95.0, there is intentionally no
// space after the first comma in the previous statement.
} }
// Tests ASSERT_NEAR. // Tests ASSERT_NEAR.
@@ -3090,8 +3084,6 @@ TEST_F(DoubleTest, ASSERT_NEAR) {
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, " "The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25"); "which exceeds 0.25");
// To work around a bug in gcc 2.95.0, there is intentionally no
// space after the first comma in the previous statement.
} }
// Tests the cases where DoubleLE() should succeed. // Tests the cases where DoubleLE() should succeed.
@@ -3736,10 +3728,6 @@ TEST(AssertionTest, ASSERT_EQ) {
TEST(AssertionTest, ASSERT_EQ_NULL) { TEST(AssertionTest, ASSERT_EQ_NULL) {
// A success. // A success.
const char* p = nullptr; const char* p = nullptr;
// Some older GCC versions may issue a spurious warning in this or the next
// assertion statement. This warning should not be suppressed with
// static_cast since the test verifies the ability to use bare NULL as the
// expected parameter to the macro.
ASSERT_EQ(nullptr, p); ASSERT_EQ(nullptr, p);
// A failure. // A failure.
@@ -4321,10 +4309,8 @@ TEST(AssertionWithMessageTest, ASSERT_STR) {
TEST(AssertionWithMessageTest, ASSERT_FLOATING) { TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
ASSERT_FLOAT_EQ(1, 1) << "This should succeed."; ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
ASSERT_DOUBLE_EQ(1, 1) << "This should succeed."; ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
"Expect failure."); "Expect failure.");
// To work around a bug in gcc 2.95.0, there is intentionally no
// space after the first comma in the previous statement.
} }
// Tests using ASSERT_FALSE with a streamed message. // Tests using ASSERT_FALSE with a streamed message.
@@ -4465,10 +4451,6 @@ TEST(ExpectTest, EXPECT_EQ_Double) {
TEST(ExpectTest, EXPECT_EQ_NULL) { TEST(ExpectTest, EXPECT_EQ_NULL) {
// A success. // A success.
const char* p = nullptr; const char* p = nullptr;
// Some older GCC versions may issue a spurious warning in this or the next
// assertion statement. This warning should not be suppressed with
// static_cast since the test verifies the ability to use bare NULL as the
// expected parameter to the macro.
EXPECT_EQ(nullptr, p); EXPECT_EQ(nullptr, p);
// A failure. // A failure.
@@ -5355,7 +5337,7 @@ TEST_P(CodeLocationForTESTP, Verify) {
VERIFY_CODE_LOCATION; VERIFY_CODE_LOCATION;
} }
INSTANTIATE_TEST_SUITE_P(All, CodeLocationForTESTP, Values(0)); INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
template <typename T> template <typename T>
class CodeLocationForTYPEDTEST : public Test { class CodeLocationForTYPEDTEST : public Test {
@@ -7446,22 +7428,7 @@ TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
} }
// Tests ad_hoc_test_result(). // Tests ad_hoc_test_result().
TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
class AdHocTestResultTest : public testing::Test {
protected:
static void SetUpTestSuite() {
FAIL() << "A failure happened inside SetUpTestSuite().";
}
};
TEST_F(AdHocTestResultTest, AdHocTestResultForTestSuiteShowsFailure) {
const testing::TestResult& test_result = testing::UnitTest::GetInstance()
->current_test_suite()
->ad_hoc_test_result();
EXPECT_TRUE(test_result.Failed());
}
TEST_F(AdHocTestResultTest, AdHocTestResultTestForUnitTestDoesNotShowFailure) {
const testing::TestResult& test_result = const testing::TestResult& test_result =
testing::UnitTest::GetInstance()->ad_hoc_test_result(); testing::UnitTest::GetInstance()->ad_hoc_test_result();
EXPECT_FALSE(test_result.Failed()); EXPECT_FALSE(test_result.Failed());

View File

@@ -25,14 +25,10 @@
"ci", "ci",
"googlemock/cmake", "googlemock/cmake",
"googlemock/scripts", "googlemock/scripts",
"googlemock/src/gmock-all.cc",
"googlemock/src/gmock_main.cc",
"googlemock/test", "googlemock/test",
"googlemock/CMakeLists.txt", "googlemock/CMakeLists.txt",
"googletest/cmake", "googletest/cmake",
"googletest/scripts", "googletest/scripts",
"googletest/src/gtest-all.cc",
"googletest/src/gtest_main.cc",
"googletest/test", "googletest/test",
"googletest/CMakeLists.txt" "googletest/CMakeLists.txt"
] ]