| 1 | // Copyright 2007, Google Inc. |
| 2 | // All rights reserved. |
| 3 | // |
| 4 | // Redistribution and use in source and binary forms, with or without |
| 5 | // modification, are permitted provided that the following conditions are |
| 6 | // met: |
| 7 | // |
| 8 | // * Redistributions of source code must retain the above copyright |
| 9 | // notice, this list of conditions and the following disclaimer. |
| 10 | // * Redistributions in binary form must reproduce the above |
| 11 | // copyright notice, this list of conditions and the following disclaimer |
| 12 | // in the documentation and/or other materials provided with the |
| 13 | // distribution. |
| 14 | // * Neither the name of Google Inc. nor the names of its |
| 15 | // contributors may be used to endorse or promote products derived from |
| 16 | // this software without specific prior written permission. |
| 17 | // |
| 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | |
| 30 | // Google Mock - a framework for writing C++ mock classes. |
| 31 | // |
| 32 | // The ACTION* family of macros can be used in a namespace scope to |
| 33 | // define custom actions easily. The syntax: |
| 34 | // |
| 35 | // ACTION(name) { statements; } |
| 36 | // |
| 37 | // will define an action with the given name that executes the |
| 38 | // statements. The value returned by the statements will be used as |
| 39 | // the return value of the action. Inside the statements, you can |
| 40 | // refer to the K-th (0-based) argument of the mock function by |
| 41 | // 'argK', and refer to its type by 'argK_type'. For example: |
| 42 | // |
| 43 | // ACTION(IncrementArg1) { |
| 44 | // arg1_type temp = arg1; |
| 45 | // return ++(*temp); |
| 46 | // } |
| 47 | // |
| 48 | // allows you to write |
| 49 | // |
| 50 | // ...WillOnce(IncrementArg1()); |
| 51 | // |
| 52 | // You can also refer to the entire argument tuple and its type by |
| 53 | // 'args' and 'args_type', and refer to the mock function type and its |
| 54 | // return type by 'function_type' and 'return_type'. |
| 55 | // |
| 56 | // Note that you don't need to specify the types of the mock function |
| 57 | // arguments. However rest assured that your code is still type-safe: |
| 58 | // you'll get a compiler error if *arg1 doesn't support the ++ |
| 59 | // operator, or if the type of ++(*arg1) isn't compatible with the |
| 60 | // mock function's return type, for example. |
| 61 | // |
| 62 | // Sometimes you'll want to parameterize the action. For that you can use |
| 63 | // another macro: |
| 64 | // |
| 65 | // ACTION_P(name, param_name) { statements; } |
| 66 | // |
| 67 | // For example: |
| 68 | // |
| 69 | // ACTION_P(Add, n) { return arg0 + n; } |
| 70 | // |
| 71 | // will allow you to write: |
| 72 | // |
| 73 | // ...WillOnce(Add(5)); |
| 74 | // |
| 75 | // Note that you don't need to provide the type of the parameter |
| 76 | // either. If you need to reference the type of a parameter named |
| 77 | // 'foo', you can write 'foo_type'. For example, in the body of |
| 78 | // ACTION_P(Add, n) above, you can write 'n_type' to refer to the type |
| 79 | // of 'n'. |
| 80 | // |
| 81 | // We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support |
| 82 | // multi-parameter actions. |
| 83 | // |
| 84 | // For the purpose of typing, you can view |
| 85 | // |
| 86 | // ACTION_Pk(Foo, p1, ..., pk) { ... } |
| 87 | // |
| 88 | // as shorthand for |
| 89 | // |
| 90 | // template <typename p1_type, ..., typename pk_type> |
| 91 | // FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... } |
| 92 | // |
| 93 | // In particular, you can provide the template type arguments |
| 94 | // explicitly when invoking Foo(), as in Foo<long, bool>(5, false); |
| 95 | // although usually you can rely on the compiler to infer the types |
| 96 | // for you automatically. You can assign the result of expression |
| 97 | // Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ..., |
| 98 | // pk_type>. This can be useful when composing actions. |
| 99 | // |
| 100 | // You can also overload actions with different numbers of parameters: |
| 101 | // |
| 102 | // ACTION_P(Plus, a) { ... } |
| 103 | // ACTION_P2(Plus, a, b) { ... } |
| 104 | // |
| 105 | // While it's tempting to always use the ACTION* macros when defining |
| 106 | // a new action, you should also consider implementing ActionInterface |
| 107 | // or using MakePolymorphicAction() instead, especially if you need to |
| 108 | // use the action a lot. While these approaches require more work, |
| 109 | // they give you more control on the types of the mock function |
| 110 | // arguments and the action parameters, which in general leads to |
| 111 | // better compiler error messages that pay off in the long run. They |
| 112 | // also allow overloading actions based on parameter types (as opposed |
| 113 | // to just based on the number of parameters). |
| 114 | // |
| 115 | // CAVEAT: |
| 116 | // |
| 117 | // ACTION*() can only be used in a namespace scope as templates cannot be |
| 118 | // declared inside of a local class. |
| 119 | // Users can, however, define any local functors (e.g. a lambda) that |
| 120 | // can be used as actions. |
| 121 | // |
| 122 | // MORE INFORMATION: |
| 123 | // |
| 124 | // To learn more about using these macros, please search for 'ACTION' on |
| 125 | // https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md |
| 126 | |
| 127 | // IWYU pragma: private, include "gmock/gmock.h" |
| 128 | // IWYU pragma: friend gmock/.* |
| 129 | |
| 130 | #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ |
| 131 | #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ |
| 132 | |
| 133 | #ifndef _WIN32_WCE |
| 134 | #include <errno.h> |
| 135 | #endif |
| 136 | |
| 137 | #include <algorithm> |
| 138 | #include <functional> |
| 139 | #include <memory> |
| 140 | #include <string> |
| 141 | #include <tuple> |
| 142 | #include <type_traits> |
| 143 | #include <utility> |
| 144 | |
| 145 | #include "gmock/internal/gmock-internal-utils.h" |
| 146 | #include "gmock/internal/gmock-port.h" |
| 147 | #include "gmock/internal/gmock-pp.h" |
| 148 | |
| 149 | #ifdef _MSC_VER |
| 150 | #pragma warning(push) |
| 151 | #pragma warning(disable : 4100) |
| 152 | #endif |
| 153 | |
| 154 | namespace testing { |
| 155 | |
| 156 | // To implement an action Foo, define: |
| 157 | // 1. a class FooAction that implements the ActionInterface interface, and |
| 158 | // 2. a factory function that creates an Action object from a |
| 159 | // const FooAction*. |
| 160 | // |
| 161 | // The two-level delegation design follows that of Matcher, providing |
| 162 | // consistency for extension developers. It also eases ownership |
| 163 | // management as Action objects can now be copied like plain values. |
| 164 | |
| 165 | namespace internal { |
| 166 | |
| 167 | // BuiltInDefaultValueGetter<T, true>::Get() returns a |
| 168 | // default-constructed T value. BuiltInDefaultValueGetter<T, |
| 169 | // false>::Get() crashes with an error. |
| 170 | // |
| 171 | // This primary template is used when kDefaultConstructible is true. |
| 172 | template <typename T, bool kDefaultConstructible> |
| 173 | struct BuiltInDefaultValueGetter { |
| 174 | static T Get() { return T(); } |
| 175 | }; |
| 176 | template <typename T> |
| 177 | struct BuiltInDefaultValueGetter<T, false> { |
| 178 | static T Get() { |
| 179 | Assert(condition: false, __FILE__, __LINE__, |
| 180 | msg: "Default action undefined for the function return type." ); |
| 181 | return internal::Invalid<T>(); |
| 182 | // The above statement will never be reached, but is required in |
| 183 | // order for this function to compile. |
| 184 | } |
| 185 | }; |
| 186 | |
| 187 | // BuiltInDefaultValue<T>::Get() returns the "built-in" default value |
| 188 | // for type T, which is NULL when T is a raw pointer type, 0 when T is |
| 189 | // a numeric type, false when T is bool, or "" when T is string or |
| 190 | // std::string. In addition, in C++11 and above, it turns a |
| 191 | // default-constructed T value if T is default constructible. For any |
| 192 | // other type T, the built-in default T value is undefined, and the |
| 193 | // function will abort the process. |
| 194 | template <typename T> |
| 195 | class BuiltInDefaultValue { |
| 196 | public: |
| 197 | // This function returns true if and only if type T has a built-in default |
| 198 | // value. |
| 199 | static bool Exists() { return ::std::is_default_constructible<T>::value; } |
| 200 | |
| 201 | static T Get() { |
| 202 | return BuiltInDefaultValueGetter< |
| 203 | T, ::std::is_default_constructible<T>::value>::Get(); |
| 204 | } |
| 205 | }; |
| 206 | |
| 207 | // This partial specialization says that we use the same built-in |
| 208 | // default value for T and const T. |
| 209 | template <typename T> |
| 210 | class BuiltInDefaultValue<const T> { |
| 211 | public: |
| 212 | static bool Exists() { return BuiltInDefaultValue<T>::Exists(); } |
| 213 | static T Get() { return BuiltInDefaultValue<T>::Get(); } |
| 214 | }; |
| 215 | |
| 216 | // This partial specialization defines the default values for pointer |
| 217 | // types. |
| 218 | template <typename T> |
| 219 | class BuiltInDefaultValue<T*> { |
| 220 | public: |
| 221 | static bool Exists() { return true; } |
| 222 | static T* Get() { return nullptr; } |
| 223 | }; |
| 224 | |
| 225 | // The following specializations define the default values for |
| 226 | // specific types we care about. |
| 227 | #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ |
| 228 | template <> \ |
| 229 | class BuiltInDefaultValue<type> { \ |
| 230 | public: \ |
| 231 | static bool Exists() { return true; } \ |
| 232 | static type Get() { return value; } \ |
| 233 | } |
| 234 | |
| 235 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT |
| 236 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "" ); |
| 237 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); |
| 238 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); |
| 239 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); |
| 240 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); |
| 241 | |
| 242 | // There's no need for a default action for signed wchar_t, as that |
| 243 | // type is the same as wchar_t for gcc, and invalid for MSVC. |
| 244 | // |
| 245 | // There's also no need for a default action for unsigned wchar_t, as |
| 246 | // that type is the same as unsigned int for gcc, and invalid for |
| 247 | // MSVC. |
| 248 | #if GMOCK_WCHAR_T_IS_NATIVE_ |
| 249 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT |
| 250 | #endif |
| 251 | |
| 252 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT |
| 253 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT |
| 254 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); |
| 255 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); |
| 256 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT |
| 257 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT |
| 258 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT |
| 259 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT |
| 260 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); |
| 261 | GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); |
| 262 | |
| 263 | #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ |
| 264 | |
| 265 | // Partial implementations of metaprogramming types from the standard library |
| 266 | // not available in C++11. |
| 267 | |
| 268 | template <typename P> |
| 269 | struct negation |
| 270 | // NOLINTNEXTLINE |
| 271 | : std::integral_constant<bool, bool(!P::value)> {}; |
| 272 | |
| 273 | // Base case: with zero predicates the answer is always true. |
| 274 | template <typename...> |
| 275 | struct conjunction : std::true_type {}; |
| 276 | |
| 277 | // With a single predicate, the answer is that predicate. |
| 278 | template <typename P1> |
| 279 | struct conjunction<P1> : P1 {}; |
| 280 | |
| 281 | // With multiple predicates the answer is the first predicate if that is false, |
| 282 | // and we recurse otherwise. |
| 283 | template <typename P1, typename... Ps> |
| 284 | struct conjunction<P1, Ps...> |
| 285 | : std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {}; |
| 286 | |
| 287 | template <typename...> |
| 288 | struct disjunction : std::false_type {}; |
| 289 | |
| 290 | template <typename P1> |
| 291 | struct disjunction<P1> : P1 {}; |
| 292 | |
| 293 | template <typename P1, typename... Ps> |
| 294 | struct disjunction<P1, Ps...> |
| 295 | // NOLINTNEXTLINE |
| 296 | : std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {}; |
| 297 | |
| 298 | template <typename...> |
| 299 | using void_t = void; |
| 300 | |
| 301 | // Detects whether an expression of type `From` can be implicitly converted to |
| 302 | // `To` according to [conv]. In C++17, [conv]/3 defines this as follows: |
| 303 | // |
| 304 | // An expression e can be implicitly converted to a type T if and only if |
| 305 | // the declaration T t=e; is well-formed, for some invented temporary |
| 306 | // variable t ([dcl.init]). |
| 307 | // |
| 308 | // [conv]/2 implies we can use function argument passing to detect whether this |
| 309 | // initialization is valid. |
| 310 | // |
| 311 | // Note that this is distinct from is_convertible, which requires this be valid: |
| 312 | // |
| 313 | // To test() { |
| 314 | // return declval<From>(); |
| 315 | // } |
| 316 | // |
| 317 | // In particular, is_convertible doesn't give the correct answer when `To` and |
| 318 | // `From` are the same non-moveable type since `declval<From>` will be an rvalue |
| 319 | // reference, defeating the guaranteed copy elision that would otherwise make |
| 320 | // this function work. |
| 321 | // |
| 322 | // REQUIRES: `From` is not cv void. |
| 323 | template <typename From, typename To> |
| 324 | struct is_implicitly_convertible { |
| 325 | private: |
| 326 | // A function that accepts a parameter of type T. This can be called with type |
| 327 | // U successfully only if U is implicitly convertible to T. |
| 328 | template <typename T> |
| 329 | static void Accept(T); |
| 330 | |
| 331 | // A function that creates a value of type T. |
| 332 | template <typename T> |
| 333 | static T Make(); |
| 334 | |
| 335 | // An overload be selected when implicit conversion from T to To is possible. |
| 336 | template <typename T, typename = decltype(Accept<To>(Make<T>()))> |
| 337 | static std::true_type TestImplicitConversion(int); |
| 338 | |
| 339 | // A fallback overload selected in all other cases. |
| 340 | template <typename T> |
| 341 | static std::false_type TestImplicitConversion(...); |
| 342 | |
| 343 | public: |
| 344 | using type = decltype(TestImplicitConversion<From>(0)); |
| 345 | static constexpr bool value = type::value; |
| 346 | }; |
| 347 | |
| 348 | // Like std::invoke_result_t from C++17, but works only for objects with call |
| 349 | // operators (not e.g. member function pointers, which we don't need specific |
| 350 | // support for in OnceAction because std::function deals with them). |
| 351 | template <typename F, typename... Args> |
| 352 | using call_result_t = decltype(std::declval<F>()(std::declval<Args>()...)); |
| 353 | |
| 354 | template <typename Void, typename R, typename F, typename... Args> |
| 355 | struct is_callable_r_impl : std::false_type {}; |
| 356 | |
| 357 | // Specialize the struct for those template arguments where call_result_t is |
| 358 | // well-formed. When it's not, the generic template above is chosen, resulting |
| 359 | // in std::false_type. |
| 360 | template <typename R, typename F, typename... Args> |
| 361 | struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...> |
| 362 | : std::conditional< |
| 363 | std::is_void<R>::value, // |
| 364 | std::true_type, // |
| 365 | is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {}; |
| 366 | |
| 367 | // Like std::is_invocable_r from C++17, but works only for objects with call |
| 368 | // operators. See the note on call_result_t. |
| 369 | template <typename R, typename F, typename... Args> |
| 370 | using is_callable_r = is_callable_r_impl<void, R, F, Args...>; |
| 371 | |
| 372 | // Like std::as_const from C++17. |
| 373 | template <typename T> |
| 374 | typename std::add_const<T>::type& as_const(T& t) { |
| 375 | return t; |
| 376 | } |
| 377 | |
| 378 | } // namespace internal |
| 379 | |
| 380 | // Specialized for function types below. |
| 381 | template <typename F> |
| 382 | class OnceAction; |
| 383 | |
| 384 | // An action that can only be used once. |
| 385 | // |
| 386 | // This is accepted by WillOnce, which doesn't require the underlying action to |
| 387 | // be copy-constructible (only move-constructible), and promises to invoke it as |
| 388 | // an rvalue reference. This allows the action to work with move-only types like |
| 389 | // std::move_only_function in a type-safe manner. |
| 390 | // |
| 391 | // For example: |
| 392 | // |
| 393 | // // Assume we have some API that needs to accept a unique pointer to some |
| 394 | // // non-copyable object Foo. |
| 395 | // void AcceptUniquePointer(std::unique_ptr<Foo> foo); |
| 396 | // |
| 397 | // // We can define an action that provides a Foo to that API. Because It |
| 398 | // // has to give away its unique pointer, it must not be called more than |
| 399 | // // once, so its call operator is &&-qualified. |
| 400 | // struct ProvideFoo { |
| 401 | // std::unique_ptr<Foo> foo; |
| 402 | // |
| 403 | // void operator()() && { |
| 404 | // AcceptUniquePointer(std::move(Foo)); |
| 405 | // } |
| 406 | // }; |
| 407 | // |
| 408 | // // This action can be used with WillOnce. |
| 409 | // EXPECT_CALL(mock, Call) |
| 410 | // .WillOnce(ProvideFoo{std::make_unique<Foo>(...)}); |
| 411 | // |
| 412 | // // But a call to WillRepeatedly will fail to compile. This is correct, |
| 413 | // // since the action cannot correctly be used repeatedly. |
| 414 | // EXPECT_CALL(mock, Call) |
| 415 | // .WillRepeatedly(ProvideFoo{std::make_unique<Foo>(...)}); |
| 416 | // |
| 417 | // A less-contrived example would be an action that returns an arbitrary type, |
| 418 | // whose &&-qualified call operator is capable of dealing with move-only types. |
| 419 | template <typename Result, typename... Args> |
| 420 | class OnceAction<Result(Args...)> final { |
| 421 | private: |
| 422 | // True iff we can use the given callable type (or lvalue reference) directly |
| 423 | // via StdFunctionAdaptor. |
| 424 | template <typename Callable> |
| 425 | using IsDirectlyCompatible = internal::conjunction< |
| 426 | // It must be possible to capture the callable in StdFunctionAdaptor. |
| 427 | std::is_constructible<typename std::decay<Callable>::type, Callable>, |
| 428 | // The callable must be compatible with our signature. |
| 429 | internal::is_callable_r<Result, typename std::decay<Callable>::type, |
| 430 | Args...>>; |
| 431 | |
| 432 | // True iff we can use the given callable type via StdFunctionAdaptor once we |
| 433 | // ignore incoming arguments. |
| 434 | template <typename Callable> |
| 435 | using IsCompatibleAfterIgnoringArguments = internal::conjunction< |
| 436 | // It must be possible to capture the callable in a lambda. |
| 437 | std::is_constructible<typename std::decay<Callable>::type, Callable>, |
| 438 | // The callable must be invocable with zero arguments, returning something |
| 439 | // convertible to Result. |
| 440 | internal::is_callable_r<Result, typename std::decay<Callable>::type>>; |
| 441 | |
| 442 | public: |
| 443 | // Construct from a callable that is directly compatible with our mocked |
| 444 | // signature: it accepts our function type's arguments and returns something |
| 445 | // convertible to our result type. |
| 446 | template <typename Callable, |
| 447 | typename std::enable_if< |
| 448 | internal::conjunction< |
| 449 | // Teach clang on macOS that we're not talking about a |
| 450 | // copy/move constructor here. Otherwise it gets confused |
| 451 | // when checking the is_constructible requirement of our |
| 452 | // traits above. |
| 453 | internal::negation<std::is_same< |
| 454 | OnceAction, typename std::decay<Callable>::type>>, |
| 455 | IsDirectlyCompatible<Callable>> // |
| 456 | ::value, |
| 457 | int>::type = 0> |
| 458 | OnceAction(Callable&& callable) // NOLINT |
| 459 | : function_(StdFunctionAdaptor<typename std::decay<Callable>::type>( |
| 460 | {}, std::forward<Callable>(callable))) {} |
| 461 | |
| 462 | // As above, but for a callable that ignores the mocked function's arguments. |
| 463 | template <typename Callable, |
| 464 | typename std::enable_if< |
| 465 | internal::conjunction< |
| 466 | // Teach clang on macOS that we're not talking about a |
| 467 | // copy/move constructor here. Otherwise it gets confused |
| 468 | // when checking the is_constructible requirement of our |
| 469 | // traits above. |
| 470 | internal::negation<std::is_same< |
| 471 | OnceAction, typename std::decay<Callable>::type>>, |
| 472 | // Exclude callables for which the overload above works. |
| 473 | // We'd rather provide the arguments if possible. |
| 474 | internal::negation<IsDirectlyCompatible<Callable>>, |
| 475 | IsCompatibleAfterIgnoringArguments<Callable>>::value, |
| 476 | int>::type = 0> |
| 477 | OnceAction(Callable&& callable) // NOLINT |
| 478 | // Call the constructor above with a callable |
| 479 | // that ignores the input arguments. |
| 480 | : OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{ |
| 481 | std::forward<Callable>(callable)}) {} |
| 482 | |
| 483 | // We are naturally copyable because we store only an std::function, but |
| 484 | // semantically we should not be copyable. |
| 485 | OnceAction(const OnceAction&) = delete; |
| 486 | OnceAction& operator=(const OnceAction&) = delete; |
| 487 | OnceAction(OnceAction&&) = default; |
| 488 | |
| 489 | // Invoke the underlying action callable with which we were constructed, |
| 490 | // handing it the supplied arguments. |
| 491 | Result Call(Args... args) && { |
| 492 | return function_(std::forward<Args>(args)...); |
| 493 | } |
| 494 | |
| 495 | private: |
| 496 | // An adaptor that wraps a callable that is compatible with our signature and |
| 497 | // being invoked as an rvalue reference so that it can be used as an |
| 498 | // StdFunctionAdaptor. This throws away type safety, but that's fine because |
| 499 | // this is only used by WillOnce, which we know calls at most once. |
| 500 | // |
| 501 | // Once we have something like std::move_only_function from C++23, we can do |
| 502 | // away with this. |
| 503 | template <typename Callable> |
| 504 | class StdFunctionAdaptor final { |
| 505 | public: |
| 506 | // A tag indicating that the (otherwise universal) constructor is accepting |
| 507 | // the callable itself, instead of e.g. stealing calls for the move |
| 508 | // constructor. |
| 509 | struct CallableTag final {}; |
| 510 | |
| 511 | template <typename F> |
| 512 | explicit StdFunctionAdaptor(CallableTag, F&& callable) |
| 513 | : callable_(std::make_shared<Callable>(std::forward<F>(callable))) {} |
| 514 | |
| 515 | // Rather than explicitly returning Result, we return whatever the wrapped |
| 516 | // callable returns. This allows for compatibility with existing uses like |
| 517 | // the following, when the mocked function returns void: |
| 518 | // |
| 519 | // EXPECT_CALL(mock_fn_, Call) |
| 520 | // .WillOnce([&] { |
| 521 | // [...] |
| 522 | // return 0; |
| 523 | // }); |
| 524 | // |
| 525 | // Such a callable can be turned into std::function<void()>. If we use an |
| 526 | // explicit return type of Result here then it *doesn't* work with |
| 527 | // std::function, because we'll get a "void function should not return a |
| 528 | // value" error. |
| 529 | // |
| 530 | // We need not worry about incompatible result types because the SFINAE on |
| 531 | // OnceAction already checks this for us. std::is_invocable_r_v itself makes |
| 532 | // the same allowance for void result types. |
| 533 | template <typename... ArgRefs> |
| 534 | internal::call_result_t<Callable, ArgRefs...> operator()( |
| 535 | ArgRefs&&... args) const { |
| 536 | return std::move(*callable_)(std::forward<ArgRefs>(args)...); |
| 537 | } |
| 538 | |
| 539 | private: |
| 540 | // We must put the callable on the heap so that we are copyable, which |
| 541 | // std::function needs. |
| 542 | std::shared_ptr<Callable> callable_; |
| 543 | }; |
| 544 | |
| 545 | // An adaptor that makes a callable that accepts zero arguments callable with |
| 546 | // our mocked arguments. |
| 547 | template <typename Callable> |
| 548 | struct IgnoreIncomingArguments { |
| 549 | internal::call_result_t<Callable> operator()(Args&&...) { |
| 550 | return std::move(callable)(); |
| 551 | } |
| 552 | |
| 553 | Callable callable; |
| 554 | }; |
| 555 | |
| 556 | std::function<Result(Args...)> function_; |
| 557 | }; |
| 558 | |
| 559 | // When an unexpected function call is encountered, Google Mock will |
| 560 | // let it return a default value if the user has specified one for its |
| 561 | // return type, or if the return type has a built-in default value; |
| 562 | // otherwise Google Mock won't know what value to return and will have |
| 563 | // to abort the process. |
| 564 | // |
| 565 | // The DefaultValue<T> class allows a user to specify the |
| 566 | // default value for a type T that is both copyable and publicly |
| 567 | // destructible (i.e. anything that can be used as a function return |
| 568 | // type). The usage is: |
| 569 | // |
| 570 | // // Sets the default value for type T to be foo. |
| 571 | // DefaultValue<T>::Set(foo); |
| 572 | template <typename T> |
| 573 | class DefaultValue { |
| 574 | public: |
| 575 | // Sets the default value for type T; requires T to be |
| 576 | // copy-constructable and have a public destructor. |
| 577 | static void Set(T x) { |
| 578 | delete producer_; |
| 579 | producer_ = new FixedValueProducer(x); |
| 580 | } |
| 581 | |
| 582 | // Provides a factory function to be called to generate the default value. |
| 583 | // This method can be used even if T is only move-constructible, but it is not |
| 584 | // limited to that case. |
| 585 | typedef T (*FactoryFunction)(); |
| 586 | static void SetFactory(FactoryFunction factory) { |
| 587 | delete producer_; |
| 588 | producer_ = new FactoryValueProducer(factory); |
| 589 | } |
| 590 | |
| 591 | // Unsets the default value for type T. |
| 592 | static void Clear() { |
| 593 | delete producer_; |
| 594 | producer_ = nullptr; |
| 595 | } |
| 596 | |
| 597 | // Returns true if and only if the user has set the default value for type T. |
| 598 | static bool IsSet() { return producer_ != nullptr; } |
| 599 | |
| 600 | // Returns true if T has a default return value set by the user or there |
| 601 | // exists a built-in default value. |
| 602 | static bool Exists() { |
| 603 | return IsSet() || internal::BuiltInDefaultValue<T>::Exists(); |
| 604 | } |
| 605 | |
| 606 | // Returns the default value for type T if the user has set one; |
| 607 | // otherwise returns the built-in default value. Requires that Exists() |
| 608 | // is true, which ensures that the return value is well-defined. |
| 609 | static T Get() { |
| 610 | return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get() |
| 611 | : producer_->Produce(); |
| 612 | } |
| 613 | |
| 614 | private: |
| 615 | class ValueProducer { |
| 616 | public: |
| 617 | virtual ~ValueProducer() {} |
| 618 | virtual T Produce() = 0; |
| 619 | }; |
| 620 | |
| 621 | class FixedValueProducer : public ValueProducer { |
| 622 | public: |
| 623 | explicit FixedValueProducer(T value) : value_(value) {} |
| 624 | T Produce() override { return value_; } |
| 625 | |
| 626 | private: |
| 627 | const T value_; |
| 628 | FixedValueProducer(const FixedValueProducer&) = delete; |
| 629 | FixedValueProducer& operator=(const FixedValueProducer&) = delete; |
| 630 | }; |
| 631 | |
| 632 | class FactoryValueProducer : public ValueProducer { |
| 633 | public: |
| 634 | explicit FactoryValueProducer(FactoryFunction factory) |
| 635 | : factory_(factory) {} |
| 636 | T Produce() override { return factory_(); } |
| 637 | |
| 638 | private: |
| 639 | const FactoryFunction factory_; |
| 640 | FactoryValueProducer(const FactoryValueProducer&) = delete; |
| 641 | FactoryValueProducer& operator=(const FactoryValueProducer&) = delete; |
| 642 | }; |
| 643 | |
| 644 | static ValueProducer* producer_; |
| 645 | }; |
| 646 | |
| 647 | // This partial specialization allows a user to set default values for |
| 648 | // reference types. |
| 649 | template <typename T> |
| 650 | class DefaultValue<T&> { |
| 651 | public: |
| 652 | // Sets the default value for type T&. |
| 653 | static void Set(T& x) { // NOLINT |
| 654 | address_ = &x; |
| 655 | } |
| 656 | |
| 657 | // Unsets the default value for type T&. |
| 658 | static void Clear() { address_ = nullptr; } |
| 659 | |
| 660 | // Returns true if and only if the user has set the default value for type T&. |
| 661 | static bool IsSet() { return address_ != nullptr; } |
| 662 | |
| 663 | // Returns true if T has a default return value set by the user or there |
| 664 | // exists a built-in default value. |
| 665 | static bool Exists() { |
| 666 | return IsSet() || internal::BuiltInDefaultValue<T&>::Exists(); |
| 667 | } |
| 668 | |
| 669 | // Returns the default value for type T& if the user has set one; |
| 670 | // otherwise returns the built-in default value if there is one; |
| 671 | // otherwise aborts the process. |
| 672 | static T& Get() { |
| 673 | return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get() |
| 674 | : *address_; |
| 675 | } |
| 676 | |
| 677 | private: |
| 678 | static T* address_; |
| 679 | }; |
| 680 | |
| 681 | // This specialization allows DefaultValue<void>::Get() to |
| 682 | // compile. |
| 683 | template <> |
| 684 | class DefaultValue<void> { |
| 685 | public: |
| 686 | static bool Exists() { return true; } |
| 687 | static void Get() {} |
| 688 | }; |
| 689 | |
| 690 | // Points to the user-set default value for type T. |
| 691 | template <typename T> |
| 692 | typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr; |
| 693 | |
| 694 | // Points to the user-set default value for type T&. |
| 695 | template <typename T> |
| 696 | T* DefaultValue<T&>::address_ = nullptr; |
| 697 | |
| 698 | // Implement this interface to define an action for function type F. |
| 699 | template <typename F> |
| 700 | class ActionInterface { |
| 701 | public: |
| 702 | typedef typename internal::Function<F>::Result Result; |
| 703 | typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; |
| 704 | |
| 705 | ActionInterface() {} |
| 706 | virtual ~ActionInterface() {} |
| 707 | |
| 708 | // Performs the action. This method is not const, as in general an |
| 709 | // action can have side effects and be stateful. For example, a |
| 710 | // get-the-next-element-from-the-collection action will need to |
| 711 | // remember the current element. |
| 712 | virtual Result Perform(const ArgumentTuple& args) = 0; |
| 713 | |
| 714 | private: |
| 715 | ActionInterface(const ActionInterface&) = delete; |
| 716 | ActionInterface& operator=(const ActionInterface&) = delete; |
| 717 | }; |
| 718 | |
| 719 | template <typename F> |
| 720 | class Action; |
| 721 | |
| 722 | // An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment) |
| 723 | // object that represents an action to be taken when a mock function of type |
| 724 | // R(Args...) is called. The implementation of Action<T> is just a |
| 725 | // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action! You |
| 726 | // can view an object implementing ActionInterface<F> as a concrete action |
| 727 | // (including its current state), and an Action<F> object as a handle to it. |
| 728 | template <typename R, typename... Args> |
| 729 | class Action<R(Args...)> { |
| 730 | private: |
| 731 | using F = R(Args...); |
| 732 | |
| 733 | // Adapter class to allow constructing Action from a legacy ActionInterface. |
| 734 | // New code should create Actions from functors instead. |
| 735 | struct ActionAdapter { |
| 736 | // Adapter must be copyable to satisfy std::function requirements. |
| 737 | ::std::shared_ptr<ActionInterface<F>> impl_; |
| 738 | |
| 739 | template <typename... InArgs> |
| 740 | typename internal::Function<F>::Result operator()(InArgs&&... args) { |
| 741 | return impl_->Perform( |
| 742 | ::std::forward_as_tuple(::std::forward<InArgs>(args)...)); |
| 743 | } |
| 744 | }; |
| 745 | |
| 746 | template <typename G> |
| 747 | using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>; |
| 748 | |
| 749 | public: |
| 750 | typedef typename internal::Function<F>::Result Result; |
| 751 | typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; |
| 752 | |
| 753 | // Constructs a null Action. Needed for storing Action objects in |
| 754 | // STL containers. |
| 755 | Action() {} |
| 756 | |
| 757 | // Construct an Action from a specified callable. |
| 758 | // This cannot take std::function directly, because then Action would not be |
| 759 | // directly constructible from lambda (it would require two conversions). |
| 760 | template < |
| 761 | typename G, |
| 762 | typename = typename std::enable_if<internal::disjunction< |
| 763 | IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>, |
| 764 | G>>::value>::type> |
| 765 | Action(G&& fun) { // NOLINT |
| 766 | Init(::std::forward<G>(fun), IsCompatibleFunctor<G>()); |
| 767 | } |
| 768 | |
| 769 | // Constructs an Action from its implementation. |
| 770 | explicit Action(ActionInterface<F>* impl) |
| 771 | : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {} |
| 772 | |
| 773 | // This constructor allows us to turn an Action<Func> object into an |
| 774 | // Action<F>, as long as F's arguments can be implicitly converted |
| 775 | // to Func's and Func's return type can be implicitly converted to F's. |
| 776 | template <typename Func> |
| 777 | Action(const Action<Func>& action) // NOLINT |
| 778 | : fun_(action.fun_) {} |
| 779 | |
| 780 | // Returns true if and only if this is the DoDefault() action. |
| 781 | bool IsDoDefault() const { return fun_ == nullptr; } |
| 782 | |
| 783 | // Performs the action. Note that this method is const even though |
| 784 | // the corresponding method in ActionInterface is not. The reason |
| 785 | // is that a const Action<F> means that it cannot be re-bound to |
| 786 | // another concrete action, not that the concrete action it binds to |
| 787 | // cannot change state. (Think of the difference between a const |
| 788 | // pointer and a pointer to const.) |
| 789 | Result Perform(ArgumentTuple args) const { |
| 790 | if (IsDoDefault()) { |
| 791 | internal::IllegalDoDefault(__FILE__, __LINE__); |
| 792 | } |
| 793 | return internal::Apply(fun_, ::std::move(args)); |
| 794 | } |
| 795 | |
| 796 | // An action can be used as a OnceAction, since it's obviously safe to call it |
| 797 | // once. |
| 798 | operator OnceAction<F>() const { // NOLINT |
| 799 | // Return a OnceAction-compatible callable that calls Perform with the |
| 800 | // arguments it is provided. We could instead just return fun_, but then |
| 801 | // we'd need to handle the IsDoDefault() case separately. |
| 802 | struct OA { |
| 803 | Action<F> action; |
| 804 | |
| 805 | R operator()(Args... args) && { |
| 806 | return action.Perform( |
| 807 | std::forward_as_tuple(std::forward<Args>(args)...)); |
| 808 | } |
| 809 | }; |
| 810 | |
| 811 | return OA{*this}; |
| 812 | } |
| 813 | |
| 814 | private: |
| 815 | template <typename G> |
| 816 | friend class Action; |
| 817 | |
| 818 | template <typename G> |
| 819 | void Init(G&& g, ::std::true_type) { |
| 820 | fun_ = ::std::forward<G>(g); |
| 821 | } |
| 822 | |
| 823 | template <typename G> |
| 824 | void Init(G&& g, ::std::false_type) { |
| 825 | fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)}; |
| 826 | } |
| 827 | |
| 828 | template <typename FunctionImpl> |
| 829 | struct IgnoreArgs { |
| 830 | template <typename... InArgs> |
| 831 | Result operator()(const InArgs&...) const { |
| 832 | return function_impl(); |
| 833 | } |
| 834 | |
| 835 | FunctionImpl function_impl; |
| 836 | }; |
| 837 | |
| 838 | // fun_ is an empty function if and only if this is the DoDefault() action. |
| 839 | ::std::function<F> fun_; |
| 840 | }; |
| 841 | |
| 842 | // The PolymorphicAction class template makes it easy to implement a |
| 843 | // polymorphic action (i.e. an action that can be used in mock |
| 844 | // functions of than one type, e.g. Return()). |
| 845 | // |
| 846 | // To define a polymorphic action, a user first provides a COPYABLE |
| 847 | // implementation class that has a Perform() method template: |
| 848 | // |
| 849 | // class FooAction { |
| 850 | // public: |
| 851 | // template <typename Result, typename ArgumentTuple> |
| 852 | // Result Perform(const ArgumentTuple& args) const { |
| 853 | // // Processes the arguments and returns a result, using |
| 854 | // // std::get<N>(args) to get the N-th (0-based) argument in the tuple. |
| 855 | // } |
| 856 | // ... |
| 857 | // }; |
| 858 | // |
| 859 | // Then the user creates the polymorphic action using |
| 860 | // MakePolymorphicAction(object) where object has type FooAction. See |
| 861 | // the definition of Return(void) and SetArgumentPointee<N>(value) for |
| 862 | // complete examples. |
| 863 | template <typename Impl> |
| 864 | class PolymorphicAction { |
| 865 | public: |
| 866 | explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} |
| 867 | |
| 868 | template <typename F> |
| 869 | operator Action<F>() const { |
| 870 | return Action<F>(new MonomorphicImpl<F>(impl_)); |
| 871 | } |
| 872 | |
| 873 | private: |
| 874 | template <typename F> |
| 875 | class MonomorphicImpl : public ActionInterface<F> { |
| 876 | public: |
| 877 | typedef typename internal::Function<F>::Result Result; |
| 878 | typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; |
| 879 | |
| 880 | explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} |
| 881 | |
| 882 | Result Perform(const ArgumentTuple& args) override { |
| 883 | return impl_.template Perform<Result>(args); |
| 884 | } |
| 885 | |
| 886 | private: |
| 887 | Impl impl_; |
| 888 | }; |
| 889 | |
| 890 | Impl impl_; |
| 891 | }; |
| 892 | |
| 893 | // Creates an Action from its implementation and returns it. The |
| 894 | // created Action object owns the implementation. |
| 895 | template <typename F> |
| 896 | Action<F> MakeAction(ActionInterface<F>* impl) { |
| 897 | return Action<F>(impl); |
| 898 | } |
| 899 | |
| 900 | // Creates a polymorphic action from its implementation. This is |
| 901 | // easier to use than the PolymorphicAction<Impl> constructor as it |
| 902 | // doesn't require you to explicitly write the template argument, e.g. |
| 903 | // |
| 904 | // MakePolymorphicAction(foo); |
| 905 | // vs |
| 906 | // PolymorphicAction<TypeOfFoo>(foo); |
| 907 | template <typename Impl> |
| 908 | inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) { |
| 909 | return PolymorphicAction<Impl>(impl); |
| 910 | } |
| 911 | |
| 912 | namespace internal { |
| 913 | |
| 914 | // Helper struct to specialize ReturnAction to execute a move instead of a copy |
| 915 | // on return. Useful for move-only types, but could be used on any type. |
| 916 | template <typename T> |
| 917 | struct ByMoveWrapper { |
| 918 | explicit ByMoveWrapper(T value) : payload(std::move(value)) {} |
| 919 | T payload; |
| 920 | }; |
| 921 | |
| 922 | // The general implementation of Return(R). Specializations follow below. |
| 923 | template <typename R> |
| 924 | class ReturnAction final { |
| 925 | public: |
| 926 | explicit ReturnAction(R value) : value_(std::move(value)) {} |
| 927 | |
| 928 | template <typename U, typename... Args, |
| 929 | typename = typename std::enable_if<conjunction< |
| 930 | // See the requirements documented on Return. |
| 931 | negation<std::is_same<void, U>>, // |
| 932 | negation<std::is_reference<U>>, // |
| 933 | std::is_convertible<R, U>, // |
| 934 | std::is_move_constructible<U>>::value>::type> |
| 935 | operator OnceAction<U(Args...)>() && { // NOLINT |
| 936 | return Impl<U>(std::move(value_)); |
| 937 | } |
| 938 | |
| 939 | template <typename U, typename... Args, |
| 940 | typename = typename std::enable_if<conjunction< |
| 941 | // See the requirements documented on Return. |
| 942 | negation<std::is_same<void, U>>, // |
| 943 | negation<std::is_reference<U>>, // |
| 944 | std::is_convertible<const R&, U>, // |
| 945 | std::is_copy_constructible<U>>::value>::type> |
| 946 | operator Action<U(Args...)>() const { // NOLINT |
| 947 | return Impl<U>(value_); |
| 948 | } |
| 949 | |
| 950 | private: |
| 951 | // Implements the Return(x) action for a mock function that returns type U. |
| 952 | template <typename U> |
| 953 | class Impl final { |
| 954 | public: |
| 955 | // The constructor used when the return value is allowed to move from the |
| 956 | // input value (i.e. we are converting to OnceAction). |
| 957 | explicit Impl(R&& input_value) |
| 958 | : state_(new State(std::move(input_value))) {} |
| 959 | |
| 960 | // The constructor used when the return value is not allowed to move from |
| 961 | // the input value (i.e. we are converting to Action). |
| 962 | explicit Impl(const R& input_value) : state_(new State(input_value)) {} |
| 963 | |
| 964 | U operator()() && { return std::move(state_->value); } |
| 965 | U operator()() const& { return state_->value; } |
| 966 | |
| 967 | private: |
| 968 | // We put our state on the heap so that the compiler-generated copy/move |
| 969 | // constructors work correctly even when U is a reference-like type. This is |
| 970 | // necessary only because we eagerly create State::value (see the note on |
| 971 | // that symbol for details). If we instead had only the input value as a |
| 972 | // member then the default constructors would work fine. |
| 973 | // |
| 974 | // For example, when R is std::string and U is std::string_view, value is a |
| 975 | // reference to the string backed by input_value. The copy constructor would |
| 976 | // copy both, so that we wind up with a new input_value object (with the |
| 977 | // same contents) and a reference to the *old* input_value object rather |
| 978 | // than the new one. |
| 979 | struct State { |
| 980 | explicit State(const R& input_value_in) |
| 981 | : input_value(input_value_in), |
| 982 | // Make an implicit conversion to Result before initializing the U |
| 983 | // object we store, avoiding calling any explicit constructor of U |
| 984 | // from R. |
| 985 | // |
| 986 | // This simulates the language rules: a function with return type U |
| 987 | // that does `return R()` requires R to be implicitly convertible to |
| 988 | // U, and uses that path for the conversion, even U Result has an |
| 989 | // explicit constructor from R. |
| 990 | value(ImplicitCast_<U>(internal::as_const(input_value))) {} |
| 991 | |
| 992 | // As above, but for the case where we're moving from the ReturnAction |
| 993 | // object because it's being used as a OnceAction. |
| 994 | explicit State(R&& input_value_in) |
| 995 | : input_value(std::move(input_value_in)), |
| 996 | // For the same reason as above we make an implicit conversion to U |
| 997 | // before initializing the value. |
| 998 | // |
| 999 | // Unlike above we provide the input value as an rvalue to the |
| 1000 | // implicit conversion because this is a OnceAction: it's fine if it |
| 1001 | // wants to consume the input value. |
| 1002 | value(ImplicitCast_<U>(std::move(input_value))) {} |
| 1003 | |
| 1004 | // A copy of the value originally provided by the user. We retain this in |
| 1005 | // addition to the value of the mock function's result type below in case |
| 1006 | // the latter is a reference-like type. See the std::string_view example |
| 1007 | // in the documentation on Return. |
| 1008 | R input_value; |
| 1009 | |
| 1010 | // The value we actually return, as the type returned by the mock function |
| 1011 | // itself. |
| 1012 | // |
| 1013 | // We eagerly initialize this here, rather than lazily doing the implicit |
| 1014 | // conversion automatically each time Perform is called, for historical |
| 1015 | // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126) |
| 1016 | // made the Action<U()> conversion operator eagerly convert the R value to |
| 1017 | // U, but without keeping the R alive. This broke the use case discussed |
| 1018 | // in the documentation for Return, making reference-like types such as |
| 1019 | // std::string_view not safe to use as U where the input type R is a |
| 1020 | // value-like type such as std::string. |
| 1021 | // |
| 1022 | // The example the commit gave was not very clear, nor was the issue |
| 1023 | // thread (https://github.com/google/googlemock/issues/86), but it seems |
| 1024 | // the worry was about reference-like input types R that flatten to a |
| 1025 | // value-like type U when being implicitly converted. An example of this |
| 1026 | // is std::vector<bool>::reference, which is often a proxy type with an |
| 1027 | // reference to the underlying vector: |
| 1028 | // |
| 1029 | // // Helper method: have the mock function return bools according |
| 1030 | // // to the supplied script. |
| 1031 | // void SetActions(MockFunction<bool(size_t)>& mock, |
| 1032 | // const std::vector<bool>& script) { |
| 1033 | // for (size_t i = 0; i < script.size(); ++i) { |
| 1034 | // EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i])); |
| 1035 | // } |
| 1036 | // } |
| 1037 | // |
| 1038 | // TEST(Foo, Bar) { |
| 1039 | // // Set actions using a temporary vector, whose operator[] |
| 1040 | // // returns proxy objects that references that will be |
| 1041 | // // dangling once the call to SetActions finishes and the |
| 1042 | // // vector is destroyed. |
| 1043 | // MockFunction<bool(size_t)> mock; |
| 1044 | // SetActions(mock, {false, true}); |
| 1045 | // |
| 1046 | // EXPECT_FALSE(mock.AsStdFunction()(0)); |
| 1047 | // EXPECT_TRUE(mock.AsStdFunction()(1)); |
| 1048 | // } |
| 1049 | // |
| 1050 | // This eager conversion helps with a simple case like this, but doesn't |
| 1051 | // fully make these types work in general. For example the following still |
| 1052 | // uses a dangling reference: |
| 1053 | // |
| 1054 | // TEST(Foo, Baz) { |
| 1055 | // MockFunction<std::vector<std::string>()> mock; |
| 1056 | // |
| 1057 | // // Return the same vector twice, and then the empty vector |
| 1058 | // // thereafter. |
| 1059 | // auto action = Return(std::initializer_list<std::string>{ |
| 1060 | // "taco", "burrito", |
| 1061 | // }); |
| 1062 | // |
| 1063 | // EXPECT_CALL(mock, Call) |
| 1064 | // .WillOnce(action) |
| 1065 | // .WillOnce(action) |
| 1066 | // .WillRepeatedly(Return(std::vector<std::string>{})); |
| 1067 | // |
| 1068 | // EXPECT_THAT(mock.AsStdFunction()(), |
| 1069 | // ElementsAre("taco", "burrito")); |
| 1070 | // EXPECT_THAT(mock.AsStdFunction()(), |
| 1071 | // ElementsAre("taco", "burrito")); |
| 1072 | // EXPECT_THAT(mock.AsStdFunction()(), IsEmpty()); |
| 1073 | // } |
| 1074 | // |
| 1075 | U value; |
| 1076 | }; |
| 1077 | |
| 1078 | const std::shared_ptr<State> state_; |
| 1079 | }; |
| 1080 | |
| 1081 | R value_; |
| 1082 | }; |
| 1083 | |
| 1084 | // A specialization of ReturnAction<R> when R is ByMoveWrapper<T> for some T. |
| 1085 | // |
| 1086 | // This version applies the type system-defeating hack of moving from T even in |
| 1087 | // the const call operator, checking at runtime that it isn't called more than |
| 1088 | // once, since the user has declared their intent to do so by using ByMove. |
| 1089 | template <typename T> |
| 1090 | class ReturnAction<ByMoveWrapper<T>> final { |
| 1091 | public: |
| 1092 | explicit ReturnAction(ByMoveWrapper<T> wrapper) |
| 1093 | : state_(new State(std::move(wrapper.payload))) {} |
| 1094 | |
| 1095 | T operator()() const { |
| 1096 | GTEST_CHECK_(!state_->called) |
| 1097 | << "A ByMove() action must be performed at most once." ; |
| 1098 | |
| 1099 | state_->called = true; |
| 1100 | return std::move(state_->value); |
| 1101 | } |
| 1102 | |
| 1103 | private: |
| 1104 | // We store our state on the heap so that we are copyable as required by |
| 1105 | // Action, despite the fact that we are stateful and T may not be copyable. |
| 1106 | struct State { |
| 1107 | explicit State(T&& value_in) : value(std::move(value_in)) {} |
| 1108 | |
| 1109 | T value; |
| 1110 | bool called = false; |
| 1111 | }; |
| 1112 | |
| 1113 | const std::shared_ptr<State> state_; |
| 1114 | }; |
| 1115 | |
| 1116 | // Implements the ReturnNull() action. |
| 1117 | class ReturnNullAction { |
| 1118 | public: |
| 1119 | // Allows ReturnNull() to be used in any pointer-returning function. In C++11 |
| 1120 | // this is enforced by returning nullptr, and in non-C++11 by asserting a |
| 1121 | // pointer type on compile time. |
| 1122 | template <typename Result, typename ArgumentTuple> |
| 1123 | static Result Perform(const ArgumentTuple&) { |
| 1124 | return nullptr; |
| 1125 | } |
| 1126 | }; |
| 1127 | |
| 1128 | // Implements the Return() action. |
| 1129 | class ReturnVoidAction { |
| 1130 | public: |
| 1131 | // Allows Return() to be used in any void-returning function. |
| 1132 | template <typename Result, typename ArgumentTuple> |
| 1133 | static void Perform(const ArgumentTuple&) { |
| 1134 | static_assert(std::is_void<Result>::value, "Result should be void." ); |
| 1135 | } |
| 1136 | }; |
| 1137 | |
| 1138 | // Implements the polymorphic ReturnRef(x) action, which can be used |
| 1139 | // in any function that returns a reference to the type of x, |
| 1140 | // regardless of the argument types. |
| 1141 | template <typename T> |
| 1142 | class ReturnRefAction { |
| 1143 | public: |
| 1144 | // Constructs a ReturnRefAction object from the reference to be returned. |
| 1145 | explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT |
| 1146 | |
| 1147 | // This template type conversion operator allows ReturnRef(x) to be |
| 1148 | // used in ANY function that returns a reference to x's type. |
| 1149 | template <typename F> |
| 1150 | operator Action<F>() const { |
| 1151 | typedef typename Function<F>::Result Result; |
| 1152 | // Asserts that the function return type is a reference. This |
| 1153 | // catches the user error of using ReturnRef(x) when Return(x) |
| 1154 | // should be used, and generates some helpful error message. |
| 1155 | static_assert(std::is_reference<Result>::value, |
| 1156 | "use Return instead of ReturnRef to return a value" ); |
| 1157 | return Action<F>(new Impl<F>(ref_)); |
| 1158 | } |
| 1159 | |
| 1160 | private: |
| 1161 | // Implements the ReturnRef(x) action for a particular function type F. |
| 1162 | template <typename F> |
| 1163 | class Impl : public ActionInterface<F> { |
| 1164 | public: |
| 1165 | typedef typename Function<F>::Result Result; |
| 1166 | typedef typename Function<F>::ArgumentTuple ArgumentTuple; |
| 1167 | |
| 1168 | explicit Impl(T& ref) : ref_(ref) {} // NOLINT |
| 1169 | |
| 1170 | Result Perform(const ArgumentTuple&) override { return ref_; } |
| 1171 | |
| 1172 | private: |
| 1173 | T& ref_; |
| 1174 | }; |
| 1175 | |
| 1176 | T& ref_; |
| 1177 | }; |
| 1178 | |
| 1179 | // Implements the polymorphic ReturnRefOfCopy(x) action, which can be |
| 1180 | // used in any function that returns a reference to the type of x, |
| 1181 | // regardless of the argument types. |
| 1182 | template <typename T> |
| 1183 | class ReturnRefOfCopyAction { |
| 1184 | public: |
| 1185 | // Constructs a ReturnRefOfCopyAction object from the reference to |
| 1186 | // be returned. |
| 1187 | explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT |
| 1188 | |
| 1189 | // This template type conversion operator allows ReturnRefOfCopy(x) to be |
| 1190 | // used in ANY function that returns a reference to x's type. |
| 1191 | template <typename F> |
| 1192 | operator Action<F>() const { |
| 1193 | typedef typename Function<F>::Result Result; |
| 1194 | // Asserts that the function return type is a reference. This |
| 1195 | // catches the user error of using ReturnRefOfCopy(x) when Return(x) |
| 1196 | // should be used, and generates some helpful error message. |
| 1197 | static_assert(std::is_reference<Result>::value, |
| 1198 | "use Return instead of ReturnRefOfCopy to return a value" ); |
| 1199 | return Action<F>(new Impl<F>(value_)); |
| 1200 | } |
| 1201 | |
| 1202 | private: |
| 1203 | // Implements the ReturnRefOfCopy(x) action for a particular function type F. |
| 1204 | template <typename F> |
| 1205 | class Impl : public ActionInterface<F> { |
| 1206 | public: |
| 1207 | typedef typename Function<F>::Result Result; |
| 1208 | typedef typename Function<F>::ArgumentTuple ArgumentTuple; |
| 1209 | |
| 1210 | explicit Impl(const T& value) : value_(value) {} // NOLINT |
| 1211 | |
| 1212 | Result Perform(const ArgumentTuple&) override { return value_; } |
| 1213 | |
| 1214 | private: |
| 1215 | T value_; |
| 1216 | }; |
| 1217 | |
| 1218 | const T value_; |
| 1219 | }; |
| 1220 | |
| 1221 | // Implements the polymorphic ReturnRoundRobin(v) action, which can be |
| 1222 | // used in any function that returns the element_type of v. |
| 1223 | template <typename T> |
| 1224 | class ReturnRoundRobinAction { |
| 1225 | public: |
| 1226 | explicit ReturnRoundRobinAction(std::vector<T> values) { |
| 1227 | GTEST_CHECK_(!values.empty()) |
| 1228 | << "ReturnRoundRobin requires at least one element." ; |
| 1229 | state_->values = std::move(values); |
| 1230 | } |
| 1231 | |
| 1232 | template <typename... Args> |
| 1233 | T operator()(Args&&...) const { |
| 1234 | return state_->Next(); |
| 1235 | } |
| 1236 | |
| 1237 | private: |
| 1238 | struct State { |
| 1239 | T Next() { |
| 1240 | T ret_val = values[i++]; |
| 1241 | if (i == values.size()) i = 0; |
| 1242 | return ret_val; |
| 1243 | } |
| 1244 | |
| 1245 | std::vector<T> values; |
| 1246 | size_t i = 0; |
| 1247 | }; |
| 1248 | std::shared_ptr<State> state_ = std::make_shared<State>(); |
| 1249 | }; |
| 1250 | |
| 1251 | // Implements the polymorphic DoDefault() action. |
| 1252 | class DoDefaultAction { |
| 1253 | public: |
| 1254 | // This template type conversion operator allows DoDefault() to be |
| 1255 | // used in any function. |
| 1256 | template <typename F> |
| 1257 | operator Action<F>() const { |
| 1258 | return Action<F>(); |
| 1259 | } // NOLINT |
| 1260 | }; |
| 1261 | |
| 1262 | // Implements the Assign action to set a given pointer referent to a |
| 1263 | // particular value. |
| 1264 | template <typename T1, typename T2> |
| 1265 | class AssignAction { |
| 1266 | public: |
| 1267 | AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} |
| 1268 | |
| 1269 | template <typename Result, typename ArgumentTuple> |
| 1270 | void Perform(const ArgumentTuple& /* args */) const { |
| 1271 | *ptr_ = value_; |
| 1272 | } |
| 1273 | |
| 1274 | private: |
| 1275 | T1* const ptr_; |
| 1276 | const T2 value_; |
| 1277 | }; |
| 1278 | |
| 1279 | #if !GTEST_OS_WINDOWS_MOBILE |
| 1280 | |
| 1281 | // Implements the SetErrnoAndReturn action to simulate return from |
| 1282 | // various system calls and libc functions. |
| 1283 | template <typename T> |
| 1284 | class SetErrnoAndReturnAction { |
| 1285 | public: |
| 1286 | SetErrnoAndReturnAction(int errno_value, T result) |
| 1287 | : errno_(errno_value), result_(result) {} |
| 1288 | template <typename Result, typename ArgumentTuple> |
| 1289 | Result Perform(const ArgumentTuple& /* args */) const { |
| 1290 | errno = errno_; |
| 1291 | return result_; |
| 1292 | } |
| 1293 | |
| 1294 | private: |
| 1295 | const int errno_; |
| 1296 | const T result_; |
| 1297 | }; |
| 1298 | |
| 1299 | #endif // !GTEST_OS_WINDOWS_MOBILE |
| 1300 | |
| 1301 | // Implements the SetArgumentPointee<N>(x) action for any function |
| 1302 | // whose N-th argument (0-based) is a pointer to x's type. |
| 1303 | template <size_t N, typename A, typename = void> |
| 1304 | struct SetArgumentPointeeAction { |
| 1305 | A value; |
| 1306 | |
| 1307 | template <typename... Args> |
| 1308 | void operator()(const Args&... args) const { |
| 1309 | *::std::get<N>(std::tie(args...)) = value; |
| 1310 | } |
| 1311 | }; |
| 1312 | |
| 1313 | // Implements the Invoke(object_ptr, &Class::Method) action. |
| 1314 | template <class Class, typename MethodPtr> |
| 1315 | struct InvokeMethodAction { |
| 1316 | Class* const obj_ptr; |
| 1317 | const MethodPtr method_ptr; |
| 1318 | |
| 1319 | template <typename... Args> |
| 1320 | auto operator()(Args&&... args) const |
| 1321 | -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) { |
| 1322 | return (obj_ptr->*method_ptr)(std::forward<Args>(args)...); |
| 1323 | } |
| 1324 | }; |
| 1325 | |
| 1326 | // Implements the InvokeWithoutArgs(f) action. The template argument |
| 1327 | // FunctionImpl is the implementation type of f, which can be either a |
| 1328 | // function pointer or a functor. InvokeWithoutArgs(f) can be used as an |
| 1329 | // Action<F> as long as f's type is compatible with F. |
| 1330 | template <typename FunctionImpl> |
| 1331 | struct InvokeWithoutArgsAction { |
| 1332 | FunctionImpl function_impl; |
| 1333 | |
| 1334 | // Allows InvokeWithoutArgs(f) to be used as any action whose type is |
| 1335 | // compatible with f. |
| 1336 | template <typename... Args> |
| 1337 | auto operator()(const Args&...) -> decltype(function_impl()) { |
| 1338 | return function_impl(); |
| 1339 | } |
| 1340 | }; |
| 1341 | |
| 1342 | // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. |
| 1343 | template <class Class, typename MethodPtr> |
| 1344 | struct InvokeMethodWithoutArgsAction { |
| 1345 | Class* const obj_ptr; |
| 1346 | const MethodPtr method_ptr; |
| 1347 | |
| 1348 | using ReturnType = |
| 1349 | decltype((std::declval<Class*>()->*std::declval<MethodPtr>())()); |
| 1350 | |
| 1351 | template <typename... Args> |
| 1352 | ReturnType operator()(const Args&...) const { |
| 1353 | return (obj_ptr->*method_ptr)(); |
| 1354 | } |
| 1355 | }; |
| 1356 | |
| 1357 | // Implements the IgnoreResult(action) action. |
| 1358 | template <typename A> |
| 1359 | class IgnoreResultAction { |
| 1360 | public: |
| 1361 | explicit IgnoreResultAction(const A& action) : action_(action) {} |
| 1362 | |
| 1363 | template <typename F> |
| 1364 | operator Action<F>() const { |
| 1365 | // Assert statement belongs here because this is the best place to verify |
| 1366 | // conditions on F. It produces the clearest error messages |
| 1367 | // in most compilers. |
| 1368 | // Impl really belongs in this scope as a local class but can't |
| 1369 | // because MSVC produces duplicate symbols in different translation units |
| 1370 | // in this case. Until MS fixes that bug we put Impl into the class scope |
| 1371 | // and put the typedef both here (for use in assert statement) and |
| 1372 | // in the Impl class. But both definitions must be the same. |
| 1373 | typedef typename internal::Function<F>::Result Result; |
| 1374 | |
| 1375 | // Asserts at compile time that F returns void. |
| 1376 | static_assert(std::is_void<Result>::value, "Result type should be void." ); |
| 1377 | |
| 1378 | return Action<F>(new Impl<F>(action_)); |
| 1379 | } |
| 1380 | |
| 1381 | private: |
| 1382 | template <typename F> |
| 1383 | class Impl : public ActionInterface<F> { |
| 1384 | public: |
| 1385 | typedef typename internal::Function<F>::Result Result; |
| 1386 | typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; |
| 1387 | |
| 1388 | explicit Impl(const A& action) : action_(action) {} |
| 1389 | |
| 1390 | void Perform(const ArgumentTuple& args) override { |
| 1391 | // Performs the action and ignores its result. |
| 1392 | action_.Perform(args); |
| 1393 | } |
| 1394 | |
| 1395 | private: |
| 1396 | // Type OriginalFunction is the same as F except that its return |
| 1397 | // type is IgnoredValue. |
| 1398 | typedef |
| 1399 | typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction; |
| 1400 | |
| 1401 | const Action<OriginalFunction> action_; |
| 1402 | }; |
| 1403 | |
| 1404 | const A action_; |
| 1405 | }; |
| 1406 | |
| 1407 | template <typename InnerAction, size_t... I> |
| 1408 | struct WithArgsAction { |
| 1409 | InnerAction inner_action; |
| 1410 | |
| 1411 | // The signature of the function as seen by the inner action, given an out |
| 1412 | // action with the given result and argument types. |
| 1413 | template <typename R, typename... Args> |
| 1414 | using InnerSignature = |
| 1415 | R(typename std::tuple_element<I, std::tuple<Args...>>::type...); |
| 1416 | |
| 1417 | // Rather than a call operator, we must define conversion operators to |
| 1418 | // particular action types. This is necessary for embedded actions like |
| 1419 | // DoDefault(), which rely on an action conversion operators rather than |
| 1420 | // providing a call operator because even with a particular set of arguments |
| 1421 | // they don't have a fixed return type. |
| 1422 | |
| 1423 | template <typename R, typename... Args, |
| 1424 | typename std::enable_if< |
| 1425 | std::is_convertible< |
| 1426 | InnerAction, |
| 1427 | // Unfortunately we can't use the InnerSignature alias here; |
| 1428 | // MSVC complains about the I parameter pack not being |
| 1429 | // expanded (error C3520) despite it being expanded in the |
| 1430 | // type alias. |
| 1431 | // TupleElement is also an MSVC workaround. |
| 1432 | // See its definition for details. |
| 1433 | OnceAction<R(internal::TupleElement< |
| 1434 | I, std::tuple<Args...>>...)>>::value, |
| 1435 | int>::type = 0> |
| 1436 | operator OnceAction<R(Args...)>() && { // NOLINT |
| 1437 | struct OA { |
| 1438 | OnceAction<InnerSignature<R, Args...>> inner_action; |
| 1439 | |
| 1440 | R operator()(Args&&... args) && { |
| 1441 | return std::move(inner_action) |
| 1442 | .Call(std::get<I>( |
| 1443 | std::forward_as_tuple(std::forward<Args>(args)...))...); |
| 1444 | } |
| 1445 | }; |
| 1446 | |
| 1447 | return OA{std::move(inner_action)}; |
| 1448 | } |
| 1449 | |
| 1450 | template <typename R, typename... Args, |
| 1451 | typename std::enable_if< |
| 1452 | std::is_convertible< |
| 1453 | const InnerAction&, |
| 1454 | // Unfortunately we can't use the InnerSignature alias here; |
| 1455 | // MSVC complains about the I parameter pack not being |
| 1456 | // expanded (error C3520) despite it being expanded in the |
| 1457 | // type alias. |
| 1458 | // TupleElement is also an MSVC workaround. |
| 1459 | // See its definition for details. |
| 1460 | Action<R(internal::TupleElement< |
| 1461 | I, std::tuple<Args...>>...)>>::value, |
| 1462 | int>::type = 0> |
| 1463 | operator Action<R(Args...)>() const { // NOLINT |
| 1464 | Action<InnerSignature<R, Args...>> converted(inner_action); |
| 1465 | |
| 1466 | return [converted](Args&&... args) -> R { |
| 1467 | return converted.Perform(std::forward_as_tuple( |
| 1468 | std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...)); |
| 1469 | }; |
| 1470 | } |
| 1471 | }; |
| 1472 | |
| 1473 | template <typename... Actions> |
| 1474 | class DoAllAction; |
| 1475 | |
| 1476 | // Base case: only a single action. |
| 1477 | template <typename FinalAction> |
| 1478 | class DoAllAction<FinalAction> { |
| 1479 | public: |
| 1480 | struct UserConstructorTag {}; |
| 1481 | |
| 1482 | template <typename T> |
| 1483 | explicit DoAllAction(UserConstructorTag, T&& action) |
| 1484 | : final_action_(std::forward<T>(action)) {} |
| 1485 | |
| 1486 | // Rather than a call operator, we must define conversion operators to |
| 1487 | // particular action types. This is necessary for embedded actions like |
| 1488 | // DoDefault(), which rely on an action conversion operators rather than |
| 1489 | // providing a call operator because even with a particular set of arguments |
| 1490 | // they don't have a fixed return type. |
| 1491 | |
| 1492 | template <typename R, typename... Args, |
| 1493 | typename std::enable_if< |
| 1494 | std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value, |
| 1495 | int>::type = 0> |
| 1496 | operator OnceAction<R(Args...)>() && { // NOLINT |
| 1497 | return std::move(final_action_); |
| 1498 | } |
| 1499 | |
| 1500 | template < |
| 1501 | typename R, typename... Args, |
| 1502 | typename std::enable_if< |
| 1503 | std::is_convertible<const FinalAction&, Action<R(Args...)>>::value, |
| 1504 | int>::type = 0> |
| 1505 | operator Action<R(Args...)>() const { // NOLINT |
| 1506 | return final_action_; |
| 1507 | } |
| 1508 | |
| 1509 | private: |
| 1510 | FinalAction final_action_; |
| 1511 | }; |
| 1512 | |
| 1513 | // Recursive case: support N actions by calling the initial action and then |
| 1514 | // calling through to the base class containing N-1 actions. |
| 1515 | template <typename InitialAction, typename... OtherActions> |
| 1516 | class DoAllAction<InitialAction, OtherActions...> |
| 1517 | : private DoAllAction<OtherActions...> { |
| 1518 | private: |
| 1519 | using Base = DoAllAction<OtherActions...>; |
| 1520 | |
| 1521 | // The type of reference that should be provided to an initial action for a |
| 1522 | // mocked function parameter of type T. |
| 1523 | // |
| 1524 | // There are two quirks here: |
| 1525 | // |
| 1526 | // * Unlike most forwarding functions, we pass scalars through by value. |
| 1527 | // This isn't strictly necessary because an lvalue reference would work |
| 1528 | // fine too and be consistent with other non-reference types, but it's |
| 1529 | // perhaps less surprising. |
| 1530 | // |
| 1531 | // For example if the mocked function has signature void(int), then it |
| 1532 | // might seem surprising for the user's initial action to need to be |
| 1533 | // convertible to Action<void(const int&)>. This is perhaps less |
| 1534 | // surprising for a non-scalar type where there may be a performance |
| 1535 | // impact, or it might even be impossible, to pass by value. |
| 1536 | // |
| 1537 | // * More surprisingly, `const T&` is often not a const reference type. |
| 1538 | // By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to |
| 1539 | // U& or U&& for some non-scalar type U, then InitialActionArgType<T> is |
| 1540 | // U&. In other words, we may hand over a non-const reference. |
| 1541 | // |
| 1542 | // So for example, given some non-scalar type Obj we have the following |
| 1543 | // mappings: |
| 1544 | // |
| 1545 | // T InitialActionArgType<T> |
| 1546 | // ------- ----------------------- |
| 1547 | // Obj const Obj& |
| 1548 | // Obj& Obj& |
| 1549 | // Obj&& Obj& |
| 1550 | // const Obj const Obj& |
| 1551 | // const Obj& const Obj& |
| 1552 | // const Obj&& const Obj& |
| 1553 | // |
| 1554 | // In other words, the initial actions get a mutable view of an non-scalar |
| 1555 | // argument if and only if the mock function itself accepts a non-const |
| 1556 | // reference type. They are never given an rvalue reference to an |
| 1557 | // non-scalar type. |
| 1558 | // |
| 1559 | // This situation makes sense if you imagine use with a matcher that is |
| 1560 | // designed to write through a reference. For example, if the caller wants |
| 1561 | // to fill in a reference argument and then return a canned value: |
| 1562 | // |
| 1563 | // EXPECT_CALL(mock, Call) |
| 1564 | // .WillOnce(DoAll(SetArgReferee<0>(17), Return(19))); |
| 1565 | // |
| 1566 | template <typename T> |
| 1567 | using InitialActionArgType = |
| 1568 | typename std::conditional<std::is_scalar<T>::value, T, const T&>::type; |
| 1569 | |
| 1570 | public: |
| 1571 | struct UserConstructorTag {}; |
| 1572 | |
| 1573 | template <typename T, typename... U> |
| 1574 | explicit DoAllAction(UserConstructorTag, T&& initial_action, |
| 1575 | U&&... other_actions) |
| 1576 | : Base({}, std::forward<U>(other_actions)...), |
| 1577 | initial_action_(std::forward<T>(initial_action)) {} |
| 1578 | |
| 1579 | template <typename R, typename... Args, |
| 1580 | typename std::enable_if< |
| 1581 | conjunction< |
| 1582 | // Both the initial action and the rest must support |
| 1583 | // conversion to OnceAction. |
| 1584 | std::is_convertible< |
| 1585 | InitialAction, |
| 1586 | OnceAction<void(InitialActionArgType<Args>...)>>, |
| 1587 | std::is_convertible<Base, OnceAction<R(Args...)>>>::value, |
| 1588 | int>::type = 0> |
| 1589 | operator OnceAction<R(Args...)>() && { // NOLINT |
| 1590 | // Return an action that first calls the initial action with arguments |
| 1591 | // filtered through InitialActionArgType, then forwards arguments directly |
| 1592 | // to the base class to deal with the remaining actions. |
| 1593 | struct OA { |
| 1594 | OnceAction<void(InitialActionArgType<Args>...)> initial_action; |
| 1595 | OnceAction<R(Args...)> remaining_actions; |
| 1596 | |
| 1597 | R operator()(Args... args) && { |
| 1598 | std::move(initial_action) |
| 1599 | .Call(static_cast<InitialActionArgType<Args>>(args)...); |
| 1600 | |
| 1601 | return std::move(remaining_actions).Call(std::forward<Args>(args)...); |
| 1602 | } |
| 1603 | }; |
| 1604 | |
| 1605 | return OA{ |
| 1606 | std::move(initial_action_), |
| 1607 | std::move(static_cast<Base&>(*this)), |
| 1608 | }; |
| 1609 | } |
| 1610 | |
| 1611 | template < |
| 1612 | typename R, typename... Args, |
| 1613 | typename std::enable_if< |
| 1614 | conjunction< |
| 1615 | // Both the initial action and the rest must support conversion to |
| 1616 | // Action. |
| 1617 | std::is_convertible<const InitialAction&, |
| 1618 | Action<void(InitialActionArgType<Args>...)>>, |
| 1619 | std::is_convertible<const Base&, Action<R(Args...)>>>::value, |
| 1620 | int>::type = 0> |
| 1621 | operator Action<R(Args...)>() const { // NOLINT |
| 1622 | // Return an action that first calls the initial action with arguments |
| 1623 | // filtered through InitialActionArgType, then forwards arguments directly |
| 1624 | // to the base class to deal with the remaining actions. |
| 1625 | struct OA { |
| 1626 | Action<void(InitialActionArgType<Args>...)> initial_action; |
| 1627 | Action<R(Args...)> remaining_actions; |
| 1628 | |
| 1629 | R operator()(Args... args) const { |
| 1630 | initial_action.Perform(std::forward_as_tuple( |
| 1631 | static_cast<InitialActionArgType<Args>>(args)...)); |
| 1632 | |
| 1633 | return remaining_actions.Perform( |
| 1634 | std::forward_as_tuple(std::forward<Args>(args)...)); |
| 1635 | } |
| 1636 | }; |
| 1637 | |
| 1638 | return OA{ |
| 1639 | initial_action_, |
| 1640 | static_cast<const Base&>(*this), |
| 1641 | }; |
| 1642 | } |
| 1643 | |
| 1644 | private: |
| 1645 | InitialAction initial_action_; |
| 1646 | }; |
| 1647 | |
| 1648 | template <typename T, typename... Params> |
| 1649 | struct ReturnNewAction { |
| 1650 | T* operator()() const { |
| 1651 | return internal::Apply( |
| 1652 | [](const Params&... unpacked_params) { |
| 1653 | return new T(unpacked_params...); |
| 1654 | }, |
| 1655 | params); |
| 1656 | } |
| 1657 | std::tuple<Params...> params; |
| 1658 | }; |
| 1659 | |
| 1660 | template <size_t k> |
| 1661 | struct ReturnArgAction { |
| 1662 | template <typename... Args, |
| 1663 | typename = typename std::enable_if<(k < sizeof...(Args))>::type> |
| 1664 | auto operator()(Args&&... args) const -> decltype(std::get<k>( |
| 1665 | std::forward_as_tuple(std::forward<Args>(args)...))) { |
| 1666 | return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...)); |
| 1667 | } |
| 1668 | }; |
| 1669 | |
| 1670 | template <size_t k, typename Ptr> |
| 1671 | struct SaveArgAction { |
| 1672 | Ptr pointer; |
| 1673 | |
| 1674 | template <typename... Args> |
| 1675 | void operator()(const Args&... args) const { |
| 1676 | *pointer = std::get<k>(std::tie(args...)); |
| 1677 | } |
| 1678 | }; |
| 1679 | |
| 1680 | template <size_t k, typename Ptr> |
| 1681 | struct SaveArgPointeeAction { |
| 1682 | Ptr pointer; |
| 1683 | |
| 1684 | template <typename... Args> |
| 1685 | void operator()(const Args&... args) const { |
| 1686 | *pointer = *std::get<k>(std::tie(args...)); |
| 1687 | } |
| 1688 | }; |
| 1689 | |
| 1690 | template <size_t k, typename T> |
| 1691 | struct SetArgRefereeAction { |
| 1692 | T value; |
| 1693 | |
| 1694 | template <typename... Args> |
| 1695 | void operator()(Args&&... args) const { |
| 1696 | using argk_type = |
| 1697 | typename ::std::tuple_element<k, std::tuple<Args...>>::type; |
| 1698 | static_assert(std::is_lvalue_reference<argk_type>::value, |
| 1699 | "Argument must be a reference type." ); |
| 1700 | std::get<k>(std::tie(args...)) = value; |
| 1701 | } |
| 1702 | }; |
| 1703 | |
| 1704 | template <size_t k, typename I1, typename I2> |
| 1705 | struct SetArrayArgumentAction { |
| 1706 | I1 first; |
| 1707 | I2 last; |
| 1708 | |
| 1709 | template <typename... Args> |
| 1710 | void operator()(const Args&... args) const { |
| 1711 | auto value = std::get<k>(std::tie(args...)); |
| 1712 | for (auto it = first; it != last; ++it, (void)++value) { |
| 1713 | *value = *it; |
| 1714 | } |
| 1715 | } |
| 1716 | }; |
| 1717 | |
| 1718 | template <size_t k> |
| 1719 | struct DeleteArgAction { |
| 1720 | template <typename... Args> |
| 1721 | void operator()(const Args&... args) const { |
| 1722 | delete std::get<k>(std::tie(args...)); |
| 1723 | } |
| 1724 | }; |
| 1725 | |
| 1726 | template <typename Ptr> |
| 1727 | struct ReturnPointeeAction { |
| 1728 | Ptr pointer; |
| 1729 | template <typename... Args> |
| 1730 | auto operator()(const Args&...) const -> decltype(*pointer) { |
| 1731 | return *pointer; |
| 1732 | } |
| 1733 | }; |
| 1734 | |
| 1735 | #if GTEST_HAS_EXCEPTIONS |
| 1736 | template <typename T> |
| 1737 | struct ThrowAction { |
| 1738 | T exception; |
| 1739 | // We use a conversion operator to adapt to any return type. |
| 1740 | template <typename R, typename... Args> |
| 1741 | operator Action<R(Args...)>() const { // NOLINT |
| 1742 | T copy = exception; |
| 1743 | return [copy](Args...) -> R { throw copy; }; |
| 1744 | } |
| 1745 | }; |
| 1746 | #endif // GTEST_HAS_EXCEPTIONS |
| 1747 | |
| 1748 | } // namespace internal |
| 1749 | |
| 1750 | // An Unused object can be implicitly constructed from ANY value. |
| 1751 | // This is handy when defining actions that ignore some or all of the |
| 1752 | // mock function arguments. For example, given |
| 1753 | // |
| 1754 | // MOCK_METHOD3(Foo, double(const string& label, double x, double y)); |
| 1755 | // MOCK_METHOD3(Bar, double(int index, double x, double y)); |
| 1756 | // |
| 1757 | // instead of |
| 1758 | // |
| 1759 | // double DistanceToOriginWithLabel(const string& label, double x, double y) { |
| 1760 | // return sqrt(x*x + y*y); |
| 1761 | // } |
| 1762 | // double DistanceToOriginWithIndex(int index, double x, double y) { |
| 1763 | // return sqrt(x*x + y*y); |
| 1764 | // } |
| 1765 | // ... |
| 1766 | // EXPECT_CALL(mock, Foo("abc", _, _)) |
| 1767 | // .WillOnce(Invoke(DistanceToOriginWithLabel)); |
| 1768 | // EXPECT_CALL(mock, Bar(5, _, _)) |
| 1769 | // .WillOnce(Invoke(DistanceToOriginWithIndex)); |
| 1770 | // |
| 1771 | // you could write |
| 1772 | // |
| 1773 | // // We can declare any uninteresting argument as Unused. |
| 1774 | // double DistanceToOrigin(Unused, double x, double y) { |
| 1775 | // return sqrt(x*x + y*y); |
| 1776 | // } |
| 1777 | // ... |
| 1778 | // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); |
| 1779 | // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); |
| 1780 | typedef internal::IgnoredValue Unused; |
| 1781 | |
| 1782 | // Creates an action that does actions a1, a2, ..., sequentially in |
| 1783 | // each invocation. All but the last action will have a readonly view of the |
| 1784 | // arguments. |
| 1785 | template <typename... Action> |
| 1786 | internal::DoAllAction<typename std::decay<Action>::type...> DoAll( |
| 1787 | Action&&... action) { |
| 1788 | return internal::DoAllAction<typename std::decay<Action>::type...>( |
| 1789 | {}, std::forward<Action>(action)...); |
| 1790 | } |
| 1791 | |
| 1792 | // WithArg<k>(an_action) creates an action that passes the k-th |
| 1793 | // (0-based) argument of the mock function to an_action and performs |
| 1794 | // it. It adapts an action accepting one argument to one that accepts |
| 1795 | // multiple arguments. For convenience, we also provide |
| 1796 | // WithArgs<k>(an_action) (defined below) as a synonym. |
| 1797 | template <size_t k, typename InnerAction> |
| 1798 | internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg( |
| 1799 | InnerAction&& action) { |
| 1800 | return {std::forward<InnerAction>(action)}; |
| 1801 | } |
| 1802 | |
| 1803 | // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes |
| 1804 | // the selected arguments of the mock function to an_action and |
| 1805 | // performs it. It serves as an adaptor between actions with |
| 1806 | // different argument lists. |
| 1807 | template <size_t k, size_t... ks, typename InnerAction> |
| 1808 | internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...> |
| 1809 | WithArgs(InnerAction&& action) { |
| 1810 | return {std::forward<InnerAction>(action)}; |
| 1811 | } |
| 1812 | |
| 1813 | // WithoutArgs(inner_action) can be used in a mock function with a |
| 1814 | // non-empty argument list to perform inner_action, which takes no |
| 1815 | // argument. In other words, it adapts an action accepting no |
| 1816 | // argument to one that accepts (and ignores) arguments. |
| 1817 | template <typename InnerAction> |
| 1818 | internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs( |
| 1819 | InnerAction&& action) { |
| 1820 | return {std::forward<InnerAction>(action)}; |
| 1821 | } |
| 1822 | |
| 1823 | // Creates an action that returns a value. |
| 1824 | // |
| 1825 | // The returned type can be used with a mock function returning a non-void, |
| 1826 | // non-reference type U as follows: |
| 1827 | // |
| 1828 | // * If R is convertible to U and U is move-constructible, then the action can |
| 1829 | // be used with WillOnce. |
| 1830 | // |
| 1831 | // * If const R& is convertible to U and U is copy-constructible, then the |
| 1832 | // action can be used with both WillOnce and WillRepeatedly. |
| 1833 | // |
| 1834 | // The mock expectation contains the R value from which the U return value is |
| 1835 | // constructed (a move/copy of the argument to Return). This means that the R |
| 1836 | // value will survive at least until the mock object's expectations are cleared |
| 1837 | // or the mock object is destroyed, meaning that U can safely be a |
| 1838 | // reference-like type such as std::string_view: |
| 1839 | // |
| 1840 | // // The mock function returns a view of a copy of the string fed to |
| 1841 | // // Return. The view is valid even after the action is performed. |
| 1842 | // MockFunction<std::string_view()> mock; |
| 1843 | // EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco"))); |
| 1844 | // const std::string_view result = mock.AsStdFunction()(); |
| 1845 | // EXPECT_EQ("taco", result); |
| 1846 | // |
| 1847 | template <typename R> |
| 1848 | internal::ReturnAction<R> Return(R value) { |
| 1849 | return internal::ReturnAction<R>(std::move(value)); |
| 1850 | } |
| 1851 | |
| 1852 | // Creates an action that returns NULL. |
| 1853 | inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() { |
| 1854 | return MakePolymorphicAction(impl: internal::ReturnNullAction()); |
| 1855 | } |
| 1856 | |
| 1857 | // Creates an action that returns from a void function. |
| 1858 | inline PolymorphicAction<internal::ReturnVoidAction> Return() { |
| 1859 | return MakePolymorphicAction(impl: internal::ReturnVoidAction()); |
| 1860 | } |
| 1861 | |
| 1862 | // Creates an action that returns the reference to a variable. |
| 1863 | template <typename R> |
| 1864 | inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT |
| 1865 | return internal::ReturnRefAction<R>(x); |
| 1866 | } |
| 1867 | |
| 1868 | // Prevent using ReturnRef on reference to temporary. |
| 1869 | template <typename R, R* = nullptr> |
| 1870 | internal::ReturnRefAction<R> ReturnRef(R&&) = delete; |
| 1871 | |
| 1872 | // Creates an action that returns the reference to a copy of the |
| 1873 | // argument. The copy is created when the action is constructed and |
| 1874 | // lives as long as the action. |
| 1875 | template <typename R> |
| 1876 | inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) { |
| 1877 | return internal::ReturnRefOfCopyAction<R>(x); |
| 1878 | } |
| 1879 | |
| 1880 | // DEPRECATED: use Return(x) directly with WillOnce. |
| 1881 | // |
| 1882 | // Modifies the parent action (a Return() action) to perform a move of the |
| 1883 | // argument instead of a copy. |
| 1884 | // Return(ByMove()) actions can only be executed once and will assert this |
| 1885 | // invariant. |
| 1886 | template <typename R> |
| 1887 | internal::ByMoveWrapper<R> ByMove(R x) { |
| 1888 | return internal::ByMoveWrapper<R>(std::move(x)); |
| 1889 | } |
| 1890 | |
| 1891 | // Creates an action that returns an element of `vals`. Calling this action will |
| 1892 | // repeatedly return the next value from `vals` until it reaches the end and |
| 1893 | // will restart from the beginning. |
| 1894 | template <typename T> |
| 1895 | internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) { |
| 1896 | return internal::ReturnRoundRobinAction<T>(std::move(vals)); |
| 1897 | } |
| 1898 | |
| 1899 | // Creates an action that returns an element of `vals`. Calling this action will |
| 1900 | // repeatedly return the next value from `vals` until it reaches the end and |
| 1901 | // will restart from the beginning. |
| 1902 | template <typename T> |
| 1903 | internal::ReturnRoundRobinAction<T> ReturnRoundRobin( |
| 1904 | std::initializer_list<T> vals) { |
| 1905 | return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals)); |
| 1906 | } |
| 1907 | |
| 1908 | // Creates an action that does the default action for the give mock function. |
| 1909 | inline internal::DoDefaultAction DoDefault() { |
| 1910 | return internal::DoDefaultAction(); |
| 1911 | } |
| 1912 | |
| 1913 | // Creates an action that sets the variable pointed by the N-th |
| 1914 | // (0-based) function argument to 'value'. |
| 1915 | template <size_t N, typename T> |
| 1916 | internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) { |
| 1917 | return {std::move(value)}; |
| 1918 | } |
| 1919 | |
| 1920 | // The following version is DEPRECATED. |
| 1921 | template <size_t N, typename T> |
| 1922 | internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) { |
| 1923 | return {std::move(value)}; |
| 1924 | } |
| 1925 | |
| 1926 | // Creates an action that sets a pointer referent to a given value. |
| 1927 | template <typename T1, typename T2> |
| 1928 | PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) { |
| 1929 | return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); |
| 1930 | } |
| 1931 | |
| 1932 | #if !GTEST_OS_WINDOWS_MOBILE |
| 1933 | |
| 1934 | // Creates an action that sets errno and returns the appropriate error. |
| 1935 | template <typename T> |
| 1936 | PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn( |
| 1937 | int errval, T result) { |
| 1938 | return MakePolymorphicAction( |
| 1939 | internal::SetErrnoAndReturnAction<T>(errval, result)); |
| 1940 | } |
| 1941 | |
| 1942 | #endif // !GTEST_OS_WINDOWS_MOBILE |
| 1943 | |
| 1944 | // Various overloads for Invoke(). |
| 1945 | |
| 1946 | // Legacy function. |
| 1947 | // Actions can now be implicitly constructed from callables. No need to create |
| 1948 | // wrapper objects. |
| 1949 | // This function exists for backwards compatibility. |
| 1950 | template <typename FunctionImpl> |
| 1951 | typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) { |
| 1952 | return std::forward<FunctionImpl>(function_impl); |
| 1953 | } |
| 1954 | |
| 1955 | // Creates an action that invokes the given method on the given object |
| 1956 | // with the mock function's arguments. |
| 1957 | template <class Class, typename MethodPtr> |
| 1958 | internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr, |
| 1959 | MethodPtr method_ptr) { |
| 1960 | return {obj_ptr, method_ptr}; |
| 1961 | } |
| 1962 | |
| 1963 | // Creates an action that invokes 'function_impl' with no argument. |
| 1964 | template <typename FunctionImpl> |
| 1965 | internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type> |
| 1966 | InvokeWithoutArgs(FunctionImpl function_impl) { |
| 1967 | return {std::move(function_impl)}; |
| 1968 | } |
| 1969 | |
| 1970 | // Creates an action that invokes the given method on the given object |
| 1971 | // with no argument. |
| 1972 | template <class Class, typename MethodPtr> |
| 1973 | internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs( |
| 1974 | Class* obj_ptr, MethodPtr method_ptr) { |
| 1975 | return {obj_ptr, method_ptr}; |
| 1976 | } |
| 1977 | |
| 1978 | // Creates an action that performs an_action and throws away its |
| 1979 | // result. In other words, it changes the return type of an_action to |
| 1980 | // void. an_action MUST NOT return void, or the code won't compile. |
| 1981 | template <typename A> |
| 1982 | inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) { |
| 1983 | return internal::IgnoreResultAction<A>(an_action); |
| 1984 | } |
| 1985 | |
| 1986 | // Creates a reference wrapper for the given L-value. If necessary, |
| 1987 | // you can explicitly specify the type of the reference. For example, |
| 1988 | // suppose 'derived' is an object of type Derived, ByRef(derived) |
| 1989 | // would wrap a Derived&. If you want to wrap a const Base& instead, |
| 1990 | // where Base is a base class of Derived, just write: |
| 1991 | // |
| 1992 | // ByRef<const Base>(derived) |
| 1993 | // |
| 1994 | // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper. |
| 1995 | // However, it may still be used for consistency with ByMove(). |
| 1996 | template <typename T> |
| 1997 | inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT |
| 1998 | return ::std::reference_wrapper<T>(l_value); |
| 1999 | } |
| 2000 | |
| 2001 | // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new |
| 2002 | // instance of type T, constructed on the heap with constructor arguments |
| 2003 | // a1, a2, ..., and a_k. The caller assumes ownership of the returned value. |
| 2004 | template <typename T, typename... Params> |
| 2005 | internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew( |
| 2006 | Params&&... params) { |
| 2007 | return {std::forward_as_tuple(std::forward<Params>(params)...)}; |
| 2008 | } |
| 2009 | |
| 2010 | // Action ReturnArg<k>() returns the k-th argument of the mock function. |
| 2011 | template <size_t k> |
| 2012 | internal::ReturnArgAction<k> ReturnArg() { |
| 2013 | return {}; |
| 2014 | } |
| 2015 | |
| 2016 | // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the |
| 2017 | // mock function to *pointer. |
| 2018 | template <size_t k, typename Ptr> |
| 2019 | internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) { |
| 2020 | return {pointer}; |
| 2021 | } |
| 2022 | |
| 2023 | // Action SaveArgPointee<k>(pointer) saves the value pointed to |
| 2024 | // by the k-th (0-based) argument of the mock function to *pointer. |
| 2025 | template <size_t k, typename Ptr> |
| 2026 | internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) { |
| 2027 | return {pointer}; |
| 2028 | } |
| 2029 | |
| 2030 | // Action SetArgReferee<k>(value) assigns 'value' to the variable |
| 2031 | // referenced by the k-th (0-based) argument of the mock function. |
| 2032 | template <size_t k, typename T> |
| 2033 | internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee( |
| 2034 | T&& value) { |
| 2035 | return {std::forward<T>(value)}; |
| 2036 | } |
| 2037 | |
| 2038 | // Action SetArrayArgument<k>(first, last) copies the elements in |
| 2039 | // source range [first, last) to the array pointed to by the k-th |
| 2040 | // (0-based) argument, which can be either a pointer or an |
| 2041 | // iterator. The action does not take ownership of the elements in the |
| 2042 | // source range. |
| 2043 | template <size_t k, typename I1, typename I2> |
| 2044 | internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first, |
| 2045 | I2 last) { |
| 2046 | return {first, last}; |
| 2047 | } |
| 2048 | |
| 2049 | // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock |
| 2050 | // function. |
| 2051 | template <size_t k> |
| 2052 | internal::DeleteArgAction<k> DeleteArg() { |
| 2053 | return {}; |
| 2054 | } |
| 2055 | |
| 2056 | // This action returns the value pointed to by 'pointer'. |
| 2057 | template <typename Ptr> |
| 2058 | internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) { |
| 2059 | return {pointer}; |
| 2060 | } |
| 2061 | |
| 2062 | // Action Throw(exception) can be used in a mock function of any type |
| 2063 | // to throw the given exception. Any copyable value can be thrown. |
| 2064 | #if GTEST_HAS_EXCEPTIONS |
| 2065 | template <typename T> |
| 2066 | internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) { |
| 2067 | return {std::forward<T>(exception)}; |
| 2068 | } |
| 2069 | #endif // GTEST_HAS_EXCEPTIONS |
| 2070 | |
| 2071 | namespace internal { |
| 2072 | |
| 2073 | // A macro from the ACTION* family (defined later in gmock-generated-actions.h) |
| 2074 | // defines an action that can be used in a mock function. Typically, |
| 2075 | // these actions only care about a subset of the arguments of the mock |
| 2076 | // function. For example, if such an action only uses the second |
| 2077 | // argument, it can be used in any mock function that takes >= 2 |
| 2078 | // arguments where the type of the second argument is compatible. |
| 2079 | // |
| 2080 | // Therefore, the action implementation must be prepared to take more |
| 2081 | // arguments than it needs. The ExcessiveArg type is used to |
| 2082 | // represent those excessive arguments. In order to keep the compiler |
| 2083 | // error messages tractable, we define it in the testing namespace |
| 2084 | // instead of testing::internal. However, this is an INTERNAL TYPE |
| 2085 | // and subject to change without notice, so a user MUST NOT USE THIS |
| 2086 | // TYPE DIRECTLY. |
| 2087 | struct ExcessiveArg {}; |
| 2088 | |
| 2089 | // Builds an implementation of an Action<> for some particular signature, using |
| 2090 | // a class defined by an ACTION* macro. |
| 2091 | template <typename F, typename Impl> |
| 2092 | struct ActionImpl; |
| 2093 | |
| 2094 | template <typename Impl> |
| 2095 | struct ImplBase { |
| 2096 | struct Holder { |
| 2097 | // Allows each copy of the Action<> to get to the Impl. |
| 2098 | explicit operator const Impl&() const { return *ptr; } |
| 2099 | std::shared_ptr<Impl> ptr; |
| 2100 | }; |
| 2101 | using type = typename std::conditional<std::is_constructible<Impl>::value, |
| 2102 | Impl, Holder>::type; |
| 2103 | }; |
| 2104 | |
| 2105 | template <typename R, typename... Args, typename Impl> |
| 2106 | struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type { |
| 2107 | using Base = typename ImplBase<Impl>::type; |
| 2108 | using function_type = R(Args...); |
| 2109 | using args_type = std::tuple<Args...>; |
| 2110 | |
| 2111 | ActionImpl() = default; // Only defined if appropriate for Base. |
| 2112 | explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {} |
| 2113 | |
| 2114 | R operator()(Args&&... arg) const { |
| 2115 | static constexpr size_t kMaxArgs = |
| 2116 | sizeof...(Args) <= 10 ? sizeof...(Args) : 10; |
| 2117 | return Apply(MakeIndexSequence<kMaxArgs>{}, |
| 2118 | MakeIndexSequence<10 - kMaxArgs>{}, |
| 2119 | args_type{std::forward<Args>(arg)...}); |
| 2120 | } |
| 2121 | |
| 2122 | template <std::size_t... arg_id, std::size_t... excess_id> |
| 2123 | R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>, |
| 2124 | const args_type& args) const { |
| 2125 | // Impl need not be specific to the signature of action being implemented; |
| 2126 | // only the implementing function body needs to have all of the specific |
| 2127 | // types instantiated. Up to 10 of the args that are provided by the |
| 2128 | // args_type get passed, followed by a dummy of unspecified type for the |
| 2129 | // remainder up to 10 explicit args. |
| 2130 | static constexpr ExcessiveArg kExcessArg{}; |
| 2131 | return static_cast<const Impl&>(*this) |
| 2132 | .template gmock_PerformImpl< |
| 2133 | /*function_type=*/function_type, /*return_type=*/R, |
| 2134 | /*args_type=*/args_type, |
| 2135 | /*argN_type=*/ |
| 2136 | typename std::tuple_element<arg_id, args_type>::type...>( |
| 2137 | /*args=*/args, std::get<arg_id>(args)..., |
| 2138 | ((void)excess_id, kExcessArg)...); |
| 2139 | } |
| 2140 | }; |
| 2141 | |
| 2142 | // Stores a default-constructed Impl as part of the Action<>'s |
| 2143 | // std::function<>. The Impl should be trivial to copy. |
| 2144 | template <typename F, typename Impl> |
| 2145 | ::testing::Action<F> MakeAction() { |
| 2146 | return ::testing::Action<F>(ActionImpl<F, Impl>()); |
| 2147 | } |
| 2148 | |
| 2149 | // Stores just the one given instance of Impl. |
| 2150 | template <typename F, typename Impl> |
| 2151 | ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) { |
| 2152 | return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl))); |
| 2153 | } |
| 2154 | |
| 2155 | #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ |
| 2156 | , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ |
| 2157 | #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ |
| 2158 | const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \ |
| 2159 | GMOCK_INTERNAL_ARG_UNUSED, , 10) |
| 2160 | |
| 2161 | #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i |
| 2162 | #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \ |
| 2163 | const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10) |
| 2164 | |
| 2165 | #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type |
| 2166 | #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \ |
| 2167 | GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10)) |
| 2168 | |
| 2169 | #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type |
| 2170 | #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \ |
| 2171 | GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params)) |
| 2172 | |
| 2173 | #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type |
| 2174 | #define GMOCK_ACTION_TYPE_PARAMS_(params) \ |
| 2175 | GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params)) |
| 2176 | |
| 2177 | #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \ |
| 2178 | , param##_type gmock_p##i |
| 2179 | #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \ |
| 2180 | GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params)) |
| 2181 | |
| 2182 | #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \ |
| 2183 | , std::forward<param##_type>(gmock_p##i) |
| 2184 | #define GMOCK_ACTION_GVALUE_PARAMS_(params) \ |
| 2185 | GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params)) |
| 2186 | |
| 2187 | #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \ |
| 2188 | , param(::std::forward<param##_type>(gmock_p##i)) |
| 2189 | #define GMOCK_ACTION_INIT_PARAMS_(params) \ |
| 2190 | GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params)) |
| 2191 | |
| 2192 | #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param; |
| 2193 | #define GMOCK_ACTION_FIELD_PARAMS_(params) \ |
| 2194 | GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) |
| 2195 | |
| 2196 | #define GMOCK_INTERNAL_ACTION(name, full_name, params) \ |
| 2197 | template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ |
| 2198 | class full_name { \ |
| 2199 | public: \ |
| 2200 | explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ |
| 2201 | : impl_(std::make_shared<gmock_Impl>( \ |
| 2202 | GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ |
| 2203 | full_name(const full_name&) = default; \ |
| 2204 | full_name(full_name&&) noexcept = default; \ |
| 2205 | template <typename F> \ |
| 2206 | operator ::testing::Action<F>() const { \ |
| 2207 | return ::testing::internal::MakeAction<F>(impl_); \ |
| 2208 | } \ |
| 2209 | \ |
| 2210 | private: \ |
| 2211 | class gmock_Impl { \ |
| 2212 | public: \ |
| 2213 | explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ |
| 2214 | : GMOCK_ACTION_INIT_PARAMS_(params) {} \ |
| 2215 | template <typename function_type, typename return_type, \ |
| 2216 | typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ |
| 2217 | return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ |
| 2218 | GMOCK_ACTION_FIELD_PARAMS_(params) \ |
| 2219 | }; \ |
| 2220 | std::shared_ptr<const gmock_Impl> impl_; \ |
| 2221 | }; \ |
| 2222 | template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ |
| 2223 | inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ |
| 2224 | GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ |
| 2225 | template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ |
| 2226 | inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ |
| 2227 | GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ |
| 2228 | return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \ |
| 2229 | GMOCK_ACTION_GVALUE_PARAMS_(params)); \ |
| 2230 | } \ |
| 2231 | template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ |
| 2232 | template <typename function_type, typename return_type, typename args_type, \ |
| 2233 | GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ |
| 2234 | return_type \ |
| 2235 | full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \ |
| 2236 | GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const |
| 2237 | |
| 2238 | } // namespace internal |
| 2239 | |
| 2240 | // Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored. |
| 2241 | #define ACTION(name) \ |
| 2242 | class name##Action { \ |
| 2243 | public: \ |
| 2244 | explicit name##Action() noexcept {} \ |
| 2245 | name##Action(const name##Action&) noexcept {} \ |
| 2246 | template <typename F> \ |
| 2247 | operator ::testing::Action<F>() const { \ |
| 2248 | return ::testing::internal::MakeAction<F, gmock_Impl>(); \ |
| 2249 | } \ |
| 2250 | \ |
| 2251 | private: \ |
| 2252 | class gmock_Impl { \ |
| 2253 | public: \ |
| 2254 | template <typename function_type, typename return_type, \ |
| 2255 | typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ |
| 2256 | return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ |
| 2257 | }; \ |
| 2258 | }; \ |
| 2259 | inline name##Action name() GTEST_MUST_USE_RESULT_; \ |
| 2260 | inline name##Action name() { return name##Action(); } \ |
| 2261 | template <typename function_type, typename return_type, typename args_type, \ |
| 2262 | GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ |
| 2263 | return_type name##Action::gmock_Impl::gmock_PerformImpl( \ |
| 2264 | GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const |
| 2265 | |
| 2266 | #define ACTION_P(name, ...) \ |
| 2267 | GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__)) |
| 2268 | |
| 2269 | #define ACTION_P2(name, ...) \ |
| 2270 | GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__)) |
| 2271 | |
| 2272 | #define ACTION_P3(name, ...) \ |
| 2273 | GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__)) |
| 2274 | |
| 2275 | #define ACTION_P4(name, ...) \ |
| 2276 | GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__)) |
| 2277 | |
| 2278 | #define ACTION_P5(name, ...) \ |
| 2279 | GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__)) |
| 2280 | |
| 2281 | #define ACTION_P6(name, ...) \ |
| 2282 | GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__)) |
| 2283 | |
| 2284 | #define ACTION_P7(name, ...) \ |
| 2285 | GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__)) |
| 2286 | |
| 2287 | #define ACTION_P8(name, ...) \ |
| 2288 | GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__)) |
| 2289 | |
| 2290 | #define ACTION_P9(name, ...) \ |
| 2291 | GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__)) |
| 2292 | |
| 2293 | #define ACTION_P10(name, ...) \ |
| 2294 | GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__)) |
| 2295 | |
| 2296 | } // namespace testing |
| 2297 | |
| 2298 | #ifdef _MSC_VER |
| 2299 | #pragma warning(pop) |
| 2300 | #endif |
| 2301 | |
| 2302 | #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ |
| 2303 | |