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/master/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 { GetBuiltInDefaultValueGetter174 static T Get() { return T(); } 175 }; 176 template <typename T> 177 struct BuiltInDefaultValueGetter<T, false> { 178 static T Get() { 179 Assert(false, __FILE__, __LINE__, 180 "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 // Simple two-arg form of std::disjunction. 266 template <typename P, typename Q> 267 using disjunction = typename ::std::conditional<P::value, P, Q>::type; 268 269 } // namespace internal 270 271 // When an unexpected function call is encountered, Google Mock will 272 // let it return a default value if the user has specified one for its 273 // return type, or if the return type has a built-in default value; 274 // otherwise Google Mock won't know what value to return and will have 275 // to abort the process. 276 // 277 // The DefaultValue<T> class allows a user to specify the 278 // default value for a type T that is both copyable and publicly 279 // destructible (i.e. anything that can be used as a function return 280 // type). The usage is: 281 // 282 // // Sets the default value for type T to be foo. 283 // DefaultValue<T>::Set(foo); 284 template <typename T> 285 class DefaultValue { 286 public: 287 // Sets the default value for type T; requires T to be 288 // copy-constructable and have a public destructor. 289 static void Set(T x) { 290 delete producer_; 291 producer_ = new FixedValueProducer(x); 292 } 293 294 // Provides a factory function to be called to generate the default value. 295 // This method can be used even if T is only move-constructible, but it is not 296 // limited to that case. 297 typedef T (*FactoryFunction)(); 298 static void SetFactory(FactoryFunction factory) { 299 delete producer_; 300 producer_ = new FactoryValueProducer(factory); 301 } 302 303 // Unsets the default value for type T. 304 static void Clear() { 305 delete producer_; 306 producer_ = nullptr; 307 } 308 309 // Returns true if and only if the user has set the default value for type T. 310 static bool IsSet() { return producer_ != nullptr; } 311 312 // Returns true if T has a default return value set by the user or there 313 // exists a built-in default value. 314 static bool Exists() { 315 return IsSet() || internal::BuiltInDefaultValue<T>::Exists(); 316 } 317 318 // Returns the default value for type T if the user has set one; 319 // otherwise returns the built-in default value. Requires that Exists() 320 // is true, which ensures that the return value is well-defined. 321 static T Get() { 322 return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get() 323 : producer_->Produce(); 324 } 325 326 private: 327 class ValueProducer { 328 public: 329 virtual ~ValueProducer() {} 330 virtual T Produce() = 0; 331 }; 332 333 class FixedValueProducer : public ValueProducer { 334 public: 335 explicit FixedValueProducer(T value) : value_(value) {} 336 T Produce() override { return value_; } 337 338 private: 339 const T value_; 340 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer); 341 }; 342 343 class FactoryValueProducer : public ValueProducer { 344 public: 345 explicit FactoryValueProducer(FactoryFunction factory) 346 : factory_(factory) {} 347 T Produce() override { return factory_(); } 348 349 private: 350 const FactoryFunction factory_; 351 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer); 352 }; 353 354 static ValueProducer* producer_; 355 }; 356 357 // This partial specialization allows a user to set default values for 358 // reference types. 359 template <typename T> 360 class DefaultValue<T&> { 361 public: 362 // Sets the default value for type T&. 363 static void Set(T& x) { // NOLINT 364 address_ = &x; 365 } 366 367 // Unsets the default value for type T&. 368 static void Clear() { address_ = nullptr; } 369 370 // Returns true if and only if the user has set the default value for type T&. 371 static bool IsSet() { return address_ != nullptr; } 372 373 // Returns true if T has a default return value set by the user or there 374 // exists a built-in default value. 375 static bool Exists() { 376 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists(); 377 } 378 379 // Returns the default value for type T& if the user has set one; 380 // otherwise returns the built-in default value if there is one; 381 // otherwise aborts the process. 382 static T& Get() { 383 return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get() 384 : *address_; 385 } 386 387 private: 388 static T* address_; 389 }; 390 391 // This specialization allows DefaultValue<void>::Get() to 392 // compile. 393 template <> 394 class DefaultValue<void> { 395 public: 396 static bool Exists() { return true; } 397 static void Get() {} 398 }; 399 400 // Points to the user-set default value for type T. 401 template <typename T> 402 typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr; 403 404 // Points to the user-set default value for type T&. 405 template <typename T> 406 T* DefaultValue<T&>::address_ = nullptr; 407 408 // Implement this interface to define an action for function type F. 409 template <typename F> 410 class ActionInterface { 411 public: 412 typedef typename internal::Function<F>::Result Result; 413 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; 414 415 ActionInterface() {} 416 virtual ~ActionInterface() {} 417 418 // Performs the action. This method is not const, as in general an 419 // action can have side effects and be stateful. For example, a 420 // get-the-next-element-from-the-collection action will need to 421 // remember the current element. 422 virtual Result Perform(const ArgumentTuple& args) = 0; 423 424 private: 425 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface); 426 }; 427 428 // An Action<F> is a copyable and IMMUTABLE (except by assignment) 429 // object that represents an action to be taken when a mock function 430 // of type F is called. The implementation of Action<T> is just a 431 // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action! 432 // You can view an object implementing ActionInterface<F> as a 433 // concrete action (including its current state), and an Action<F> 434 // object as a handle to it. 435 template <typename F> 436 class Action { 437 // Adapter class to allow constructing Action from a legacy ActionInterface. 438 // New code should create Actions from functors instead. 439 struct ActionAdapter { 440 // Adapter must be copyable to satisfy std::function requirements. 441 ::std::shared_ptr<ActionInterface<F>> impl_; 442 443 template <typename... Args> 444 typename internal::Function<F>::Result operator()(Args&&... args) { 445 return impl_->Perform( 446 ::std::forward_as_tuple(::std::forward<Args>(args)...)); 447 } 448 }; 449 450 template <typename G> 451 using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>; 452 453 public: 454 typedef typename internal::Function<F>::Result Result; 455 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; 456 457 // Constructs a null Action. Needed for storing Action objects in 458 // STL containers. 459 Action() {} 460 461 // Construct an Action from a specified callable. 462 // This cannot take std::function directly, because then Action would not be 463 // directly constructible from lambda (it would require two conversions). 464 template < 465 typename G, 466 typename = typename std::enable_if<internal::disjunction< 467 IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>, 468 G>>::value>::type> 469 Action(G&& fun) { // NOLINT 470 Init(::std::forward<G>(fun), IsCompatibleFunctor<G>()); 471 } 472 473 // Constructs an Action from its implementation. 474 explicit Action(ActionInterface<F>* impl) 475 : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {} 476 477 // This constructor allows us to turn an Action<Func> object into an 478 // Action<F>, as long as F's arguments can be implicitly converted 479 // to Func's and Func's return type can be implicitly converted to F's. 480 template <typename Func> 481 explicit Action(const Action<Func>& action) : fun_(action.fun_) {} 482 483 // Returns true if and only if this is the DoDefault() action. 484 bool IsDoDefault() const { return fun_ == nullptr; } 485 486 // Performs the action. Note that this method is const even though 487 // the corresponding method in ActionInterface is not. The reason 488 // is that a const Action<F> means that it cannot be re-bound to 489 // another concrete action, not that the concrete action it binds to 490 // cannot change state. (Think of the difference between a const 491 // pointer and a pointer to const.) 492 Result Perform(ArgumentTuple args) const { 493 if (IsDoDefault()) { 494 internal::IllegalDoDefault(__FILE__, __LINE__); 495 } 496 return internal::Apply(fun_, ::std::move(args)); 497 } 498 499 private: 500 template <typename G> 501 friend class Action; 502 503 template <typename G> 504 void Init(G&& g, ::std::true_type) { 505 fun_ = ::std::forward<G>(g); 506 } 507 508 template <typename G> 509 void Init(G&& g, ::std::false_type) { 510 fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)}; 511 } 512 513 template <typename FunctionImpl> 514 struct IgnoreArgs { 515 template <typename... Args> 516 Result operator()(const Args&...) const { 517 return function_impl(); 518 } 519 520 FunctionImpl function_impl; 521 }; 522 523 // fun_ is an empty function if and only if this is the DoDefault() action. 524 ::std::function<F> fun_; 525 }; 526 527 // The PolymorphicAction class template makes it easy to implement a 528 // polymorphic action (i.e. an action that can be used in mock 529 // functions of than one type, e.g. Return()). 530 // 531 // To define a polymorphic action, a user first provides a COPYABLE 532 // implementation class that has a Perform() method template: 533 // 534 // class FooAction { 535 // public: 536 // template <typename Result, typename ArgumentTuple> 537 // Result Perform(const ArgumentTuple& args) const { 538 // // Processes the arguments and returns a result, using 539 // // std::get<N>(args) to get the N-th (0-based) argument in the tuple. 540 // } 541 // ... 542 // }; 543 // 544 // Then the user creates the polymorphic action using 545 // MakePolymorphicAction(object) where object has type FooAction. See 546 // the definition of Return(void) and SetArgumentPointee<N>(value) for 547 // complete examples. 548 template <typename Impl> 549 class PolymorphicAction { 550 public: 551 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} 552 553 template <typename F> 554 operator Action<F>() const { 555 return Action<F>(new MonomorphicImpl<F>(impl_)); 556 } 557 558 private: 559 template <typename F> 560 class MonomorphicImpl : public ActionInterface<F> { 561 public: 562 typedef typename internal::Function<F>::Result Result; 563 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; 564 565 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} 566 567 Result Perform(const ArgumentTuple& args) override { 568 return impl_.template Perform<Result>(args); 569 } 570 571 private: 572 Impl impl_; 573 }; 574 575 Impl impl_; 576 }; 577 578 // Creates an Action from its implementation and returns it. The 579 // created Action object owns the implementation. 580 template <typename F> 581 Action<F> MakeAction(ActionInterface<F>* impl) { 582 return Action<F>(impl); 583 } 584 585 // Creates a polymorphic action from its implementation. This is 586 // easier to use than the PolymorphicAction<Impl> constructor as it 587 // doesn't require you to explicitly write the template argument, e.g. 588 // 589 // MakePolymorphicAction(foo); 590 // vs 591 // PolymorphicAction<TypeOfFoo>(foo); 592 template <typename Impl> 593 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) { 594 return PolymorphicAction<Impl>(impl); 595 } 596 597 namespace internal { 598 599 // Helper struct to specialize ReturnAction to execute a move instead of a copy 600 // on return. Useful for move-only types, but could be used on any type. 601 template <typename T> 602 struct ByMoveWrapper { 603 explicit ByMoveWrapper(T value) : payload(std::move(value)) {} 604 T payload; 605 }; 606 607 // Implements the polymorphic Return(x) action, which can be used in 608 // any function that returns the type of x, regardless of the argument 609 // types. 610 // 611 // Note: The value passed into Return must be converted into 612 // Function<F>::Result when this action is cast to Action<F> rather than 613 // when that action is performed. This is important in scenarios like 614 // 615 // MOCK_METHOD1(Method, T(U)); 616 // ... 617 // { 618 // Foo foo; 619 // X x(&foo); 620 // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x)); 621 // } 622 // 623 // In the example above the variable x holds reference to foo which leaves 624 // scope and gets destroyed. If copying X just copies a reference to foo, 625 // that copy will be left with a hanging reference. If conversion to T 626 // makes a copy of foo, the above code is safe. To support that scenario, we 627 // need to make sure that the type conversion happens inside the EXPECT_CALL 628 // statement, and conversion of the result of Return to Action<T(U)> is a 629 // good place for that. 630 // 631 // The real life example of the above scenario happens when an invocation 632 // of gtl::Container() is passed into Return. 633 // 634 template <typename R> 635 class ReturnAction { 636 public: 637 // Constructs a ReturnAction object from the value to be returned. 638 // 'value' is passed by value instead of by const reference in order 639 // to allow Return("string literal") to compile. 640 explicit ReturnAction(R value) : value_(new R(std::move(value))) {} 641 642 // This template type conversion operator allows Return(x) to be 643 // used in ANY function that returns x's type. 644 template <typename F> 645 operator Action<F>() const { // NOLINT 646 // Assert statement belongs here because this is the best place to verify 647 // conditions on F. It produces the clearest error messages 648 // in most compilers. 649 // Impl really belongs in this scope as a local class but can't 650 // because MSVC produces duplicate symbols in different translation units 651 // in this case. Until MS fixes that bug we put Impl into the class scope 652 // and put the typedef both here (for use in assert statement) and 653 // in the Impl class. But both definitions must be the same. 654 typedef typename Function<F>::Result Result; 655 GTEST_COMPILE_ASSERT_( 656 !std::is_reference<Result>::value, 657 use_ReturnRef_instead_of_Return_to_return_a_reference); 658 static_assert(!std::is_void<Result>::value, 659 "Can't use Return() on an action expected to return `void`."); 660 return Action<F>(new Impl<R, F>(value_)); 661 } 662 663 private: 664 // Implements the Return(x) action for a particular function type F. 665 template <typename R_, typename F> 666 class Impl : public ActionInterface<F> { 667 public: 668 typedef typename Function<F>::Result Result; 669 typedef typename Function<F>::ArgumentTuple ArgumentTuple; 670 671 // The implicit cast is necessary when Result has more than one 672 // single-argument constructor (e.g. Result is std::vector<int>) and R 673 // has a type conversion operator template. In that case, value_(value) 674 // won't compile as the compiler doesn't known which constructor of 675 // Result to call. ImplicitCast_ forces the compiler to convert R to 676 // Result without considering explicit constructors, thus resolving the 677 // ambiguity. value_ is then initialized using its copy constructor. 678 explicit Impl(const std::shared_ptr<R>& value) 679 : value_before_cast_(*value), 680 value_(ImplicitCast_<Result>(value_before_cast_)) {} 681 682 Result Perform(const ArgumentTuple&) override { return value_; } 683 684 private: 685 GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value, 686 Result_cannot_be_a_reference_type); 687 // We save the value before casting just in case it is being cast to a 688 // wrapper type. 689 R value_before_cast_; 690 Result value_; 691 692 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); 693 }; 694 695 // Partially specialize for ByMoveWrapper. This version of ReturnAction will 696 // move its contents instead. 697 template <typename R_, typename F> 698 class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> { 699 public: 700 typedef typename Function<F>::Result Result; 701 typedef typename Function<F>::ArgumentTuple ArgumentTuple; 702 703 explicit Impl(const std::shared_ptr<R>& wrapper) 704 : performed_(false), wrapper_(wrapper) {} 705 706 Result Perform(const ArgumentTuple&) override { 707 GTEST_CHECK_(!performed_) 708 << "A ByMove() action should only be performed once."; 709 performed_ = true; 710 return std::move(wrapper_->payload); 711 } 712 713 private: 714 bool performed_; 715 const std::shared_ptr<R> wrapper_; 716 }; 717 718 const std::shared_ptr<R> value_; 719 }; 720 721 // Implements the ReturnNull() action. 722 class ReturnNullAction { 723 public: 724 // Allows ReturnNull() to be used in any pointer-returning function. In C++11 725 // this is enforced by returning nullptr, and in non-C++11 by asserting a 726 // pointer type on compile time. 727 template <typename Result, typename ArgumentTuple> 728 static Result Perform(const ArgumentTuple&) { 729 return nullptr; 730 } 731 }; 732 733 // Implements the Return() action. 734 class ReturnVoidAction { 735 public: 736 // Allows Return() to be used in any void-returning function. 737 template <typename Result, typename ArgumentTuple> 738 static void Perform(const ArgumentTuple&) { 739 static_assert(std::is_void<Result>::value, "Result should be void."); 740 } 741 }; 742 743 // Implements the polymorphic ReturnRef(x) action, which can be used 744 // in any function that returns a reference to the type of x, 745 // regardless of the argument types. 746 template <typename T> 747 class ReturnRefAction { 748 public: 749 // Constructs a ReturnRefAction object from the reference to be returned. 750 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT 751 752 // This template type conversion operator allows ReturnRef(x) to be 753 // used in ANY function that returns a reference to x's type. 754 template <typename F> 755 operator Action<F>() const { 756 typedef typename Function<F>::Result Result; 757 // Asserts that the function return type is a reference. This 758 // catches the user error of using ReturnRef(x) when Return(x) 759 // should be used, and generates some helpful error message. 760 GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value, 761 use_Return_instead_of_ReturnRef_to_return_a_value); 762 return Action<F>(new Impl<F>(ref_)); 763 } 764 765 private: 766 // Implements the ReturnRef(x) action for a particular function type F. 767 template <typename F> 768 class Impl : public ActionInterface<F> { 769 public: 770 typedef typename Function<F>::Result Result; 771 typedef typename Function<F>::ArgumentTuple ArgumentTuple; 772 773 explicit Impl(T& ref) : ref_(ref) {} // NOLINT 774 775 Result Perform(const ArgumentTuple&) override { return ref_; } 776 777 private: 778 T& ref_; 779 }; 780 781 T& ref_; 782 }; 783 784 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be 785 // used in any function that returns a reference to the type of x, 786 // regardless of the argument types. 787 template <typename T> 788 class ReturnRefOfCopyAction { 789 public: 790 // Constructs a ReturnRefOfCopyAction object from the reference to 791 // be returned. 792 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT 793 794 // This template type conversion operator allows ReturnRefOfCopy(x) to be 795 // used in ANY function that returns a reference to x's type. 796 template <typename F> 797 operator Action<F>() const { 798 typedef typename Function<F>::Result Result; 799 // Asserts that the function return type is a reference. This 800 // catches the user error of using ReturnRefOfCopy(x) when Return(x) 801 // should be used, and generates some helpful error message. 802 GTEST_COMPILE_ASSERT_( 803 std::is_reference<Result>::value, 804 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); 805 return Action<F>(new Impl<F>(value_)); 806 } 807 808 private: 809 // Implements the ReturnRefOfCopy(x) action for a particular function type F. 810 template <typename F> 811 class Impl : public ActionInterface<F> { 812 public: 813 typedef typename Function<F>::Result Result; 814 typedef typename Function<F>::ArgumentTuple ArgumentTuple; 815 816 explicit Impl(const T& value) : value_(value) {} // NOLINT 817 818 Result Perform(const ArgumentTuple&) override { return value_; } 819 820 private: 821 T value_; 822 }; 823 824 const T value_; 825 }; 826 827 // Implements the polymorphic ReturnRoundRobin(v) action, which can be 828 // used in any function that returns the element_type of v. 829 template <typename T> 830 class ReturnRoundRobinAction { 831 public: 832 explicit ReturnRoundRobinAction(std::vector<T> values) { 833 GTEST_CHECK_(!values.empty()) 834 << "ReturnRoundRobin requires at least one element."; 835 state_->values = std::move(values); 836 } 837 838 template <typename... Args> 839 T operator()(Args&&...) const { 840 return state_->Next(); 841 } 842 843 private: 844 struct State { 845 T Next() { 846 T ret_val = values[i++]; 847 if (i == values.size()) i = 0; 848 return ret_val; 849 } 850 851 std::vector<T> values; 852 size_t i = 0; 853 }; 854 std::shared_ptr<State> state_ = std::make_shared<State>(); 855 }; 856 857 // Implements the polymorphic DoDefault() action. 858 class DoDefaultAction { 859 public: 860 // This template type conversion operator allows DoDefault() to be 861 // used in any function. 862 template <typename F> 863 operator Action<F>() const { 864 return Action<F>(); 865 } // NOLINT 866 }; 867 868 // Implements the Assign action to set a given pointer referent to a 869 // particular value. 870 template <typename T1, typename T2> 871 class AssignAction { 872 public: 873 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} 874 875 template <typename Result, typename ArgumentTuple> 876 void Perform(const ArgumentTuple& /* args */) const { 877 *ptr_ = value_; 878 } 879 880 private: 881 T1* const ptr_; 882 const T2 value_; 883 }; 884 885 #if !GTEST_OS_WINDOWS_MOBILE 886 887 // Implements the SetErrnoAndReturn action to simulate return from 888 // various system calls and libc functions. 889 template <typename T> 890 class SetErrnoAndReturnAction { 891 public: 892 SetErrnoAndReturnAction(int errno_value, T result) 893 : errno_(errno_value), result_(result) {} 894 template <typename Result, typename ArgumentTuple> 895 Result Perform(const ArgumentTuple& /* args */) const { 896 errno = errno_; 897 return result_; 898 } 899 900 private: 901 const int errno_; 902 const T result_; 903 }; 904 905 #endif // !GTEST_OS_WINDOWS_MOBILE 906 907 // Implements the SetArgumentPointee<N>(x) action for any function 908 // whose N-th argument (0-based) is a pointer to x's type. 909 template <size_t N, typename A, typename = void> 910 struct SetArgumentPointeeAction { 911 A value; 912 913 template <typename... Args> 914 void operator()(const Args&... args) const { 915 *::std::get<N>(std::tie(args...)) = value; 916 } 917 }; 918 919 // Implements the Invoke(object_ptr, &Class::Method) action. 920 template <class Class, typename MethodPtr> 921 struct InvokeMethodAction { 922 Class* const obj_ptr; 923 const MethodPtr method_ptr; 924 925 template <typename... Args> 926 auto operator()(Args&&... args) const 927 -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) { 928 return (obj_ptr->*method_ptr)(std::forward<Args>(args)...); 929 } 930 }; 931 932 // Implements the InvokeWithoutArgs(f) action. The template argument 933 // FunctionImpl is the implementation type of f, which can be either a 934 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an 935 // Action<F> as long as f's type is compatible with F. 936 template <typename FunctionImpl> 937 struct InvokeWithoutArgsAction { 938 FunctionImpl function_impl; 939 940 // Allows InvokeWithoutArgs(f) to be used as any action whose type is 941 // compatible with f. 942 template <typename... Args> 943 auto operator()(const Args&...) -> decltype(function_impl()) { 944 return function_impl(); 945 } 946 }; 947 948 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. 949 template <class Class, typename MethodPtr> 950 struct InvokeMethodWithoutArgsAction { 951 Class* const obj_ptr; 952 const MethodPtr method_ptr; 953 954 using ReturnType = 955 decltype((std::declval<Class*>()->*std::declval<MethodPtr>())()); 956 957 template <typename... Args> 958 ReturnType operator()(const Args&...) const { 959 return (obj_ptr->*method_ptr)(); 960 } 961 }; 962 963 // Implements the IgnoreResult(action) action. 964 template <typename A> 965 class IgnoreResultAction { 966 public: 967 explicit IgnoreResultAction(const A& action) : action_(action) {} 968 969 template <typename F> 970 operator Action<F>() const { 971 // Assert statement belongs here because this is the best place to verify 972 // conditions on F. It produces the clearest error messages 973 // in most compilers. 974 // Impl really belongs in this scope as a local class but can't 975 // because MSVC produces duplicate symbols in different translation units 976 // in this case. Until MS fixes that bug we put Impl into the class scope 977 // and put the typedef both here (for use in assert statement) and 978 // in the Impl class. But both definitions must be the same. 979 typedef typename internal::Function<F>::Result Result; 980 981 // Asserts at compile time that F returns void. 982 static_assert(std::is_void<Result>::value, "Result type should be void."); 983 984 return Action<F>(new Impl<F>(action_)); 985 } 986 987 private: 988 template <typename F> 989 class Impl : public ActionInterface<F> { 990 public: 991 typedef typename internal::Function<F>::Result Result; 992 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; 993 994 explicit Impl(const A& action) : action_(action) {} 995 996 void Perform(const ArgumentTuple& args) override { 997 // Performs the action and ignores its result. 998 action_.Perform(args); 999 } 1000 1001 private: 1002 // Type OriginalFunction is the same as F except that its return 1003 // type is IgnoredValue. 1004 typedef 1005 typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction; 1006 1007 const Action<OriginalFunction> action_; 1008 }; 1009 1010 const A action_; 1011 }; 1012 1013 template <typename InnerAction, size_t... I> 1014 struct WithArgsAction { 1015 InnerAction action; 1016 1017 // The inner action could be anything convertible to Action<X>. 1018 // We use the conversion operator to detect the signature of the inner Action. 1019 template <typename R, typename... Args> 1020 operator Action<R(Args...)>() const { // NOLINT 1021 using TupleType = std::tuple<Args...>; 1022 Action<R(typename std::tuple_element<I, TupleType>::type...)> converted( 1023 action); 1024 1025 return [converted](Args... args) -> R { 1026 return converted.Perform(std::forward_as_tuple( 1027 std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...)); 1028 }; 1029 } 1030 }; 1031 1032 template <typename... Actions> 1033 struct DoAllAction { 1034 private: 1035 template <typename T> 1036 using NonFinalType = 1037 typename std::conditional<std::is_scalar<T>::value, T, const T&>::type; 1038 1039 template <typename ActionT, size_t... I> 1040 std::vector<ActionT> Convert(IndexSequence<I...>) const { 1041 return {ActionT(std::get<I>(actions))...}; 1042 } 1043 1044 public: 1045 std::tuple<Actions...> actions; 1046 1047 template <typename R, typename... Args> 1048 operator Action<R(Args...)>() const { // NOLINT 1049 struct Op { 1050 std::vector<Action<void(NonFinalType<Args>...)>> converted; 1051 Action<R(Args...)> last; 1052 R operator()(Args... args) const { 1053 auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...); 1054 for (auto& a : converted) { 1055 a.Perform(tuple_args); 1056 } 1057 return last.Perform(std::move(tuple_args)); 1058 } 1059 }; 1060 return Op{Convert<Action<void(NonFinalType<Args>...)>>( 1061 MakeIndexSequence<sizeof...(Actions) - 1>()), 1062 std::get<sizeof...(Actions) - 1>(actions)}; 1063 } 1064 }; 1065 1066 template <typename T, typename... Params> 1067 struct ReturnNewAction { 1068 T* operator()() const { 1069 return internal::Apply( 1070 [](const Params&... unpacked_params) { 1071 return new T(unpacked_params...); 1072 }, 1073 params); 1074 } 1075 std::tuple<Params...> params; 1076 }; 1077 1078 template <size_t k> 1079 struct ReturnArgAction { 1080 template <typename... Args> 1081 auto operator()(Args&&... args) const -> decltype(std::get<k>( 1082 std::forward_as_tuple(std::forward<Args>(args)...))) { 1083 return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...)); 1084 } 1085 }; 1086 1087 template <size_t k, typename Ptr> 1088 struct SaveArgAction { 1089 Ptr pointer; 1090 1091 template <typename... Args> 1092 void operator()(const Args&... args) const { 1093 *pointer = std::get<k>(std::tie(args...)); 1094 } 1095 }; 1096 1097 template <size_t k, typename Ptr> 1098 struct SaveArgPointeeAction { 1099 Ptr pointer; 1100 1101 template <typename... Args> 1102 void operator()(const Args&... args) const { 1103 *pointer = *std::get<k>(std::tie(args...)); 1104 } 1105 }; 1106 1107 template <size_t k, typename T> 1108 struct SetArgRefereeAction { 1109 T value; 1110 1111 template <typename... Args> 1112 void operator()(Args&&... args) const { 1113 using argk_type = 1114 typename ::std::tuple_element<k, std::tuple<Args...>>::type; 1115 static_assert(std::is_lvalue_reference<argk_type>::value, 1116 "Argument must be a reference type."); 1117 std::get<k>(std::tie(args...)) = value; 1118 } 1119 }; 1120 1121 template <size_t k, typename I1, typename I2> 1122 struct SetArrayArgumentAction { 1123 I1 first; 1124 I2 last; 1125 1126 template <typename... Args> 1127 void operator()(const Args&... args) const { 1128 auto value = std::get<k>(std::tie(args...)); 1129 for (auto it = first; it != last; ++it, (void)++value) { 1130 *value = *it; 1131 } 1132 } 1133 }; 1134 1135 template <size_t k> 1136 struct DeleteArgAction { 1137 template <typename... Args> 1138 void operator()(const Args&... args) const { 1139 delete std::get<k>(std::tie(args...)); 1140 } 1141 }; 1142 1143 template <typename Ptr> 1144 struct ReturnPointeeAction { 1145 Ptr pointer; 1146 template <typename... Args> 1147 auto operator()(const Args&...) const -> decltype(*pointer) { 1148 return *pointer; 1149 } 1150 }; 1151 1152 #if GTEST_HAS_EXCEPTIONS 1153 template <typename T> 1154 struct ThrowAction { 1155 T exception; 1156 // We use a conversion operator to adapt to any return type. 1157 template <typename R, typename... Args> 1158 operator Action<R(Args...)>() const { // NOLINT 1159 T copy = exception; 1160 return [copy](Args...) -> R { throw copy; }; 1161 } 1162 }; 1163 #endif // GTEST_HAS_EXCEPTIONS 1164 1165 } // namespace internal 1166 1167 // An Unused object can be implicitly constructed from ANY value. 1168 // This is handy when defining actions that ignore some or all of the 1169 // mock function arguments. For example, given 1170 // 1171 // MOCK_METHOD3(Foo, double(const string& label, double x, double y)); 1172 // MOCK_METHOD3(Bar, double(int index, double x, double y)); 1173 // 1174 // instead of 1175 // 1176 // double DistanceToOriginWithLabel(const string& label, double x, double y) { 1177 // return sqrt(x*x + y*y); 1178 // } 1179 // double DistanceToOriginWithIndex(int index, double x, double y) { 1180 // return sqrt(x*x + y*y); 1181 // } 1182 // ... 1183 // EXPECT_CALL(mock, Foo("abc", _, _)) 1184 // .WillOnce(Invoke(DistanceToOriginWithLabel)); 1185 // EXPECT_CALL(mock, Bar(5, _, _)) 1186 // .WillOnce(Invoke(DistanceToOriginWithIndex)); 1187 // 1188 // you could write 1189 // 1190 // // We can declare any uninteresting argument as Unused. 1191 // double DistanceToOrigin(Unused, double x, double y) { 1192 // return sqrt(x*x + y*y); 1193 // } 1194 // ... 1195 // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); 1196 // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); 1197 typedef internal::IgnoredValue Unused; 1198 1199 // Creates an action that does actions a1, a2, ..., sequentially in 1200 // each invocation. All but the last action will have a readonly view of the 1201 // arguments. 1202 template <typename... Action> 1203 internal::DoAllAction<typename std::decay<Action>::type...> DoAll( 1204 Action&&... action) { 1205 return {std::forward_as_tuple(std::forward<Action>(action)...)}; 1206 } 1207 1208 // WithArg<k>(an_action) creates an action that passes the k-th 1209 // (0-based) argument of the mock function to an_action and performs 1210 // it. It adapts an action accepting one argument to one that accepts 1211 // multiple arguments. For convenience, we also provide 1212 // WithArgs<k>(an_action) (defined below) as a synonym. 1213 template <size_t k, typename InnerAction> 1214 internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg( 1215 InnerAction&& action) { 1216 return {std::forward<InnerAction>(action)}; 1217 } 1218 1219 // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes 1220 // the selected arguments of the mock function to an_action and 1221 // performs it. It serves as an adaptor between actions with 1222 // different argument lists. 1223 template <size_t k, size_t... ks, typename InnerAction> 1224 internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...> 1225 WithArgs(InnerAction&& action) { 1226 return {std::forward<InnerAction>(action)}; 1227 } 1228 1229 // WithoutArgs(inner_action) can be used in a mock function with a 1230 // non-empty argument list to perform inner_action, which takes no 1231 // argument. In other words, it adapts an action accepting no 1232 // argument to one that accepts (and ignores) arguments. 1233 template <typename InnerAction> 1234 internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs( 1235 InnerAction&& action) { 1236 return {std::forward<InnerAction>(action)}; 1237 } 1238 1239 // Creates an action that returns 'value'. 'value' is passed by value 1240 // instead of const reference - otherwise Return("string literal") 1241 // will trigger a compiler error about using array as initializer. 1242 template <typename R> 1243 internal::ReturnAction<R> Return(R value) { 1244 return internal::ReturnAction<R>(std::move(value)); 1245 } 1246 1247 // Creates an action that returns NULL. 1248 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() { 1249 return MakePolymorphicAction(internal::ReturnNullAction()); 1250 } 1251 1252 // Creates an action that returns from a void function. 1253 inline PolymorphicAction<internal::ReturnVoidAction> Return() { 1254 return MakePolymorphicAction(internal::ReturnVoidAction()); 1255 } 1256 1257 // Creates an action that returns the reference to a variable. 1258 template <typename R> 1259 inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT 1260 return internal::ReturnRefAction<R>(x); 1261 } 1262 1263 // Prevent using ReturnRef on reference to temporary. 1264 template <typename R, R* = nullptr> 1265 internal::ReturnRefAction<R> ReturnRef(R&&) = delete; 1266 1267 // Creates an action that returns the reference to a copy of the 1268 // argument. The copy is created when the action is constructed and 1269 // lives as long as the action. 1270 template <typename R> 1271 inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) { 1272 return internal::ReturnRefOfCopyAction<R>(x); 1273 } 1274 1275 // Modifies the parent action (a Return() action) to perform a move of the 1276 // argument instead of a copy. 1277 // Return(ByMove()) actions can only be executed once and will assert this 1278 // invariant. 1279 template <typename R> 1280 internal::ByMoveWrapper<R> ByMove(R x) { 1281 return internal::ByMoveWrapper<R>(std::move(x)); 1282 } 1283 1284 // Creates an action that returns an element of `vals`. Calling this action will 1285 // repeatedly return the next value from `vals` until it reaches the end and 1286 // will restart from the beginning. 1287 template <typename T> 1288 internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) { 1289 return internal::ReturnRoundRobinAction<T>(std::move(vals)); 1290 } 1291 1292 // Creates an action that returns an element of `vals`. Calling this action will 1293 // repeatedly return the next value from `vals` until it reaches the end and 1294 // will restart from the beginning. 1295 template <typename T> 1296 internal::ReturnRoundRobinAction<T> ReturnRoundRobin( 1297 std::initializer_list<T> vals) { 1298 return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals)); 1299 } 1300 1301 // Creates an action that does the default action for the give mock function. 1302 inline internal::DoDefaultAction DoDefault() { 1303 return internal::DoDefaultAction(); 1304 } 1305 1306 // Creates an action that sets the variable pointed by the N-th 1307 // (0-based) function argument to 'value'. 1308 template <size_t N, typename T> 1309 internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) { 1310 return {std::move(value)}; 1311 } 1312 1313 // The following version is DEPRECATED. 1314 template <size_t N, typename T> 1315 internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) { 1316 return {std::move(value)}; 1317 } 1318 1319 // Creates an action that sets a pointer referent to a given value. 1320 template <typename T1, typename T2> 1321 PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) { 1322 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); 1323 } 1324 1325 #if !GTEST_OS_WINDOWS_MOBILE 1326 1327 // Creates an action that sets errno and returns the appropriate error. 1328 template <typename T> 1329 PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn( 1330 int errval, T result) { 1331 return MakePolymorphicAction( 1332 internal::SetErrnoAndReturnAction<T>(errval, result)); 1333 } 1334 1335 #endif // !GTEST_OS_WINDOWS_MOBILE 1336 1337 // Various overloads for Invoke(). 1338 1339 // Legacy function. 1340 // Actions can now be implicitly constructed from callables. No need to create 1341 // wrapper objects. 1342 // This function exists for backwards compatibility. 1343 template <typename FunctionImpl> 1344 typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) { 1345 return std::forward<FunctionImpl>(function_impl); 1346 } 1347 1348 // Creates an action that invokes the given method on the given object 1349 // with the mock function's arguments. 1350 template <class Class, typename MethodPtr> 1351 internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr, 1352 MethodPtr method_ptr) { 1353 return {obj_ptr, method_ptr}; 1354 } 1355 1356 // Creates an action that invokes 'function_impl' with no argument. 1357 template <typename FunctionImpl> 1358 internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type> 1359 InvokeWithoutArgs(FunctionImpl function_impl) { 1360 return {std::move(function_impl)}; 1361 } 1362 1363 // Creates an action that invokes the given method on the given object 1364 // with no argument. 1365 template <class Class, typename MethodPtr> 1366 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs( 1367 Class* obj_ptr, MethodPtr method_ptr) { 1368 return {obj_ptr, method_ptr}; 1369 } 1370 1371 // Creates an action that performs an_action and throws away its 1372 // result. In other words, it changes the return type of an_action to 1373 // void. an_action MUST NOT return void, or the code won't compile. 1374 template <typename A> 1375 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) { 1376 return internal::IgnoreResultAction<A>(an_action); 1377 } 1378 1379 // Creates a reference wrapper for the given L-value. If necessary, 1380 // you can explicitly specify the type of the reference. For example, 1381 // suppose 'derived' is an object of type Derived, ByRef(derived) 1382 // would wrap a Derived&. If you want to wrap a const Base& instead, 1383 // where Base is a base class of Derived, just write: 1384 // 1385 // ByRef<const Base>(derived) 1386 // 1387 // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper. 1388 // However, it may still be used for consistency with ByMove(). 1389 template <typename T> 1390 inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT 1391 return ::std::reference_wrapper<T>(l_value); 1392 } 1393 1394 // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new 1395 // instance of type T, constructed on the heap with constructor arguments 1396 // a1, a2, ..., and a_k. The caller assumes ownership of the returned value. 1397 template <typename T, typename... Params> 1398 internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew( 1399 Params&&... params) { 1400 return {std::forward_as_tuple(std::forward<Params>(params)...)}; 1401 } 1402 1403 // Action ReturnArg<k>() returns the k-th argument of the mock function. 1404 template <size_t k> 1405 internal::ReturnArgAction<k> ReturnArg() { 1406 return {}; 1407 } 1408 1409 // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the 1410 // mock function to *pointer. 1411 template <size_t k, typename Ptr> 1412 internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) { 1413 return {pointer}; 1414 } 1415 1416 // Action SaveArgPointee<k>(pointer) saves the value pointed to 1417 // by the k-th (0-based) argument of the mock function to *pointer. 1418 template <size_t k, typename Ptr> 1419 internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) { 1420 return {pointer}; 1421 } 1422 1423 // Action SetArgReferee<k>(value) assigns 'value' to the variable 1424 // referenced by the k-th (0-based) argument of the mock function. 1425 template <size_t k, typename T> 1426 internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee( 1427 T&& value) { 1428 return {std::forward<T>(value)}; 1429 } 1430 1431 // Action SetArrayArgument<k>(first, last) copies the elements in 1432 // source range [first, last) to the array pointed to by the k-th 1433 // (0-based) argument, which can be either a pointer or an 1434 // iterator. The action does not take ownership of the elements in the 1435 // source range. 1436 template <size_t k, typename I1, typename I2> 1437 internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first, 1438 I2 last) { 1439 return {first, last}; 1440 } 1441 1442 // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock 1443 // function. 1444 template <size_t k> 1445 internal::DeleteArgAction<k> DeleteArg() { 1446 return {}; 1447 } 1448 1449 // This action returns the value pointed to by 'pointer'. 1450 template <typename Ptr> 1451 internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) { 1452 return {pointer}; 1453 } 1454 1455 // Action Throw(exception) can be used in a mock function of any type 1456 // to throw the given exception. Any copyable value can be thrown. 1457 #if GTEST_HAS_EXCEPTIONS 1458 template <typename T> 1459 internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) { 1460 return {std::forward<T>(exception)}; 1461 } 1462 #endif // GTEST_HAS_EXCEPTIONS 1463 1464 namespace internal { 1465 1466 // A macro from the ACTION* family (defined later in gmock-generated-actions.h) 1467 // defines an action that can be used in a mock function. Typically, 1468 // these actions only care about a subset of the arguments of the mock 1469 // function. For example, if such an action only uses the second 1470 // argument, it can be used in any mock function that takes >= 2 1471 // arguments where the type of the second argument is compatible. 1472 // 1473 // Therefore, the action implementation must be prepared to take more 1474 // arguments than it needs. The ExcessiveArg type is used to 1475 // represent those excessive arguments. In order to keep the compiler 1476 // error messages tractable, we define it in the testing namespace 1477 // instead of testing::internal. However, this is an INTERNAL TYPE 1478 // and subject to change without notice, so a user MUST NOT USE THIS 1479 // TYPE DIRECTLY. 1480 struct ExcessiveArg {}; 1481 1482 // Builds an implementation of an Action<> for some particular signature, using 1483 // a class defined by an ACTION* macro. 1484 template <typename F, typename Impl> 1485 struct ActionImpl; 1486 1487 template <typename Impl> 1488 struct ImplBase { 1489 struct Holder { 1490 // Allows each copy of the Action<> to get to the Impl. 1491 explicit operator const Impl&() const { return *ptr; } 1492 std::shared_ptr<Impl> ptr; 1493 }; 1494 using type = typename std::conditional<std::is_constructible<Impl>::value, 1495 Impl, Holder>::type; 1496 }; 1497 1498 template <typename R, typename... Args, typename Impl> 1499 struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type { 1500 using Base = typename ImplBase<Impl>::type; 1501 using function_type = R(Args...); 1502 using args_type = std::tuple<Args...>; 1503 1504 ActionImpl() = default; // Only defined if appropriate for Base. 1505 explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {} 1506 1507 R operator()(Args&&... arg) const { 1508 static constexpr size_t kMaxArgs = 1509 sizeof...(Args) <= 10 ? sizeof...(Args) : 10; 1510 return Apply(MakeIndexSequence<kMaxArgs>{}, 1511 MakeIndexSequence<10 - kMaxArgs>{}, 1512 args_type{std::forward<Args>(arg)...}); 1513 } 1514 1515 template <std::size_t... arg_id, std::size_t... excess_id> 1516 R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>, 1517 const args_type& args) const { 1518 // Impl need not be specific to the signature of action being implemented; 1519 // only the implementing function body needs to have all of the specific 1520 // types instantiated. Up to 10 of the args that are provided by the 1521 // args_type get passed, followed by a dummy of unspecified type for the 1522 // remainder up to 10 explicit args. 1523 static constexpr ExcessiveArg kExcessArg{}; 1524 return static_cast<const Impl&>(*this) 1525 .template gmock_PerformImpl< 1526 /*function_type=*/function_type, /*return_type=*/R, 1527 /*args_type=*/args_type, 1528 /*argN_type=*/ 1529 typename std::tuple_element<arg_id, args_type>::type...>( 1530 /*args=*/args, std::get<arg_id>(args)..., 1531 ((void)excess_id, kExcessArg)...); 1532 } 1533 }; 1534 1535 // Stores a default-constructed Impl as part of the Action<>'s 1536 // std::function<>. The Impl should be trivial to copy. 1537 template <typename F, typename Impl> 1538 ::testing::Action<F> MakeAction() { 1539 return ::testing::Action<F>(ActionImpl<F, Impl>()); 1540 } 1541 1542 // Stores just the one given instance of Impl. 1543 template <typename F, typename Impl> 1544 ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) { 1545 return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl))); 1546 } 1547 1548 #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ 1549 , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ 1550 #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ 1551 const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \ 1552 GMOCK_INTERNAL_ARG_UNUSED, , 10) 1553 1554 #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i 1555 #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \ 1556 const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10) 1557 1558 #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type 1559 #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \ 1560 GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10)) 1561 1562 #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type 1563 #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \ 1564 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params)) 1565 1566 #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type 1567 #define GMOCK_ACTION_TYPE_PARAMS_(params) \ 1568 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params)) 1569 1570 #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \ 1571 , param##_type gmock_p##i 1572 #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \ 1573 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params)) 1574 1575 #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \ 1576 , std::forward<param##_type>(gmock_p##i) 1577 #define GMOCK_ACTION_GVALUE_PARAMS_(params) \ 1578 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params)) 1579 1580 #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \ 1581 , param(::std::forward<param##_type>(gmock_p##i)) 1582 #define GMOCK_ACTION_INIT_PARAMS_(params) \ 1583 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params)) 1584 1585 #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param; 1586 #define GMOCK_ACTION_FIELD_PARAMS_(params) \ 1587 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) 1588 1589 #define GMOCK_INTERNAL_ACTION(name, full_name, params) \ 1590 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ 1591 class full_name { \ 1592 public: \ 1593 explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ 1594 : impl_(std::make_shared<gmock_Impl>( \ 1595 GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ 1596 full_name(const full_name&) = default; \ 1597 full_name(full_name&&) noexcept = default; \ 1598 template <typename F> \ 1599 operator ::testing::Action<F>() const { \ 1600 return ::testing::internal::MakeAction<F>(impl_); \ 1601 } \ 1602 \ 1603 private: \ 1604 class gmock_Impl { \ 1605 public: \ 1606 explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ 1607 : GMOCK_ACTION_INIT_PARAMS_(params) {} \ 1608 template <typename function_type, typename return_type, \ 1609 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ 1610 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ 1611 GMOCK_ACTION_FIELD_PARAMS_(params) \ 1612 }; \ 1613 std::shared_ptr<const gmock_Impl> impl_; \ 1614 }; \ 1615 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ 1616 inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ 1617 GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ 1618 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ 1619 inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ 1620 GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ 1621 return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \ 1622 GMOCK_ACTION_GVALUE_PARAMS_(params)); \ 1623 } \ 1624 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ 1625 template <typename function_type, typename return_type, typename args_type, \ 1626 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ 1627 return_type \ 1628 full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \ 1629 GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const 1630 1631 } // namespace internal 1632 1633 // Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored. 1634 #define ACTION(name) \ 1635 class name##Action { \ 1636 public: \ 1637 explicit name##Action() noexcept {} \ 1638 name##Action(const name##Action&) noexcept {} \ 1639 template <typename F> \ 1640 operator ::testing::Action<F>() const { \ 1641 return ::testing::internal::MakeAction<F, gmock_Impl>(); \ 1642 } \ 1643 \ 1644 private: \ 1645 class gmock_Impl { \ 1646 public: \ 1647 template <typename function_type, typename return_type, \ 1648 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ 1649 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ 1650 }; \ 1651 }; \ 1652 inline name##Action name() GTEST_MUST_USE_RESULT_; \ 1653 inline name##Action name() { return name##Action(); } \ 1654 template <typename function_type, typename return_type, typename args_type, \ 1655 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ 1656 return_type name##Action::gmock_Impl::gmock_PerformImpl( \ 1657 GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const 1658 1659 #define ACTION_P(name, ...) \ 1660 GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__)) 1661 1662 #define ACTION_P2(name, ...) \ 1663 GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__)) 1664 1665 #define ACTION_P3(name, ...) \ 1666 GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__)) 1667 1668 #define ACTION_P4(name, ...) \ 1669 GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__)) 1670 1671 #define ACTION_P5(name, ...) \ 1672 GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__)) 1673 1674 #define ACTION_P6(name, ...) \ 1675 GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__)) 1676 1677 #define ACTION_P7(name, ...) \ 1678 GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__)) 1679 1680 #define ACTION_P8(name, ...) \ 1681 GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__)) 1682 1683 #define ACTION_P9(name, ...) \ 1684 GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__)) 1685 1686 #define ACTION_P10(name, ...) \ 1687 GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__)) 1688 1689 } // namespace testing 1690 1691 #ifdef _MSC_VER 1692 #pragma warning(pop) 1693 #endif 1694 1695 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ 1696