- 3.0.1 core module.
gmock-actions.h
Go to the documentation of this file.
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 
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file implements some commonly used actions.
34 
35 // GOOGLETEST_CM0002 DO NOT DELETE
36 
37 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
38 #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
39 
40 #ifndef _WIN32_WCE
41 # include <errno.h>
42 #endif
43 
44 #include <algorithm>
45 #include <functional>
46 #include <memory>
47 #include <string>
48 #include <type_traits>
49 #include <utility>
50 
53 
54 #ifdef _MSC_VER
55 # pragma warning(push)
56 # pragma warning(disable:4100)
57 #endif
58 
59 namespace testing {
60 
61 // To implement an action Foo, define:
62 // 1. a class FooAction that implements the ActionInterface interface, and
63 // 2. a factory function that creates an Action object from a
64 // const FooAction*.
65 //
66 // The two-level delegation design follows that of Matcher, providing
67 // consistency for extension developers. It also eases ownership
68 // management as Action objects can now be copied like plain values.
69 
70 namespace internal {
71 
72 // BuiltInDefaultValueGetter<T, true>::Get() returns a
73 // default-constructed T value. BuiltInDefaultValueGetter<T,
74 // false>::Get() crashes with an error.
75 //
76 // This primary template is used when kDefaultConstructible is true.
77 template <typename T, bool kDefaultConstructible>
79  static T Get() { return T(); }
80 };
81 template <typename T>
82 struct BuiltInDefaultValueGetter<T, false> {
83  static T Get() {
84  Assert(false, __FILE__, __LINE__,
85  "Default action undefined for the function return type.");
86  return internal::Invalid<T>();
87  // The above statement will never be reached, but is required in
88  // order for this function to compile.
89  }
90 };
91 
92 // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
93 // for type T, which is NULL when T is a raw pointer type, 0 when T is
94 // a numeric type, false when T is bool, or "" when T is string or
95 // std::string. In addition, in C++11 and above, it turns a
96 // default-constructed T value if T is default constructible. For any
97 // other type T, the built-in default T value is undefined, and the
98 // function will abort the process.
99 template <typename T>
101  public:
102  // This function returns true iff type T has a built-in default value.
103  static bool Exists() {
105  }
106 
107  static T Get() {
110  }
111 };
112 
113 // This partial specialization says that we use the same built-in
114 // default value for T and const T.
115 template <typename T>
117  public:
118  static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
119  static T Get() { return BuiltInDefaultValue<T>::Get(); }
120 };
121 
122 // This partial specialization defines the default values for pointer
123 // types.
124 template <typename T>
126  public:
127  static bool Exists() { return true; }
128  static T* Get() { return nullptr; }
129 };
130 
131 // The following specializations define the default values for
132 // specific types we care about.
133 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
134  template <> \
135  class BuiltInDefaultValue<type> { \
136  public: \
137  static bool Exists() { return true; } \
138  static type Get() { return value; } \
139  }
140 
147 
148 // There's no need for a default action for signed wchar_t, as that
149 // type is the same as wchar_t for gcc, and invalid for MSVC.
150 //
151 // There's also no need for a default action for unsigned wchar_t, as
152 // that type is the same as unsigned int for gcc, and invalid for
153 // MSVC.
154 #if GMOCK_WCHAR_T_IS_NATIVE_
155 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
156 #endif
157 
158 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
159 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
162 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
163 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
168 
169 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
170 
171 } // namespace internal
172 
173 // When an unexpected function call is encountered, Google Mock will
174 // let it return a default value if the user has specified one for its
175 // return type, or if the return type has a built-in default value;
176 // otherwise Google Mock won't know what value to return and will have
177 // to abort the process.
178 //
179 // The DefaultValue<T> class allows a user to specify the
180 // default value for a type T that is both copyable and publicly
181 // destructible (i.e. anything that can be used as a function return
182 // type). The usage is:
183 //
184 // // Sets the default value for type T to be foo.
185 // DefaultValue<T>::Set(foo);
186 template <typename T>
188  public:
189  // Sets the default value for type T; requires T to be
190  // copy-constructable and have a public destructor.
191  static void Set(T x) {
192  delete producer_;
193  producer_ = new FixedValueProducer(x);
194  }
195 
196  // Provides a factory function to be called to generate the default value.
197  // This method can be used even if T is only move-constructible, but it is not
198  // limited to that case.
199  typedef T (*FactoryFunction)();
200  static void SetFactory(FactoryFunction factory) {
201  delete producer_;
202  producer_ = new FactoryValueProducer(factory);
203  }
204 
205  // Unsets the default value for type T.
206  static void Clear() {
207  delete producer_;
208  producer_ = nullptr;
209  }
210 
211  // Returns true iff the user has set the default value for type T.
212  static bool IsSet() { return producer_ != nullptr; }
213 
214  // Returns true if T has a default return value set by the user or there
215  // exists a built-in default value.
216  static bool Exists() {
217  return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
218  }
219 
220  // Returns the default value for type T if the user has set one;
221  // otherwise returns the built-in default value. Requires that Exists()
222  // is true, which ensures that the return value is well-defined.
223  static T Get() {
224  return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
225  : producer_->Produce();
226  }
227 
228  private:
229  class ValueProducer {
230  public:
231  virtual ~ValueProducer() {}
232  virtual T Produce() = 0;
233  };
234 
235  class FixedValueProducer : public ValueProducer {
236  public:
237  explicit FixedValueProducer(T value) : value_(value) {}
238  T Produce() override { return value_; }
239 
240  private:
241  const T value_;
242  GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
243  };
244 
245  class FactoryValueProducer : public ValueProducer {
246  public:
247  explicit FactoryValueProducer(FactoryFunction factory)
248  : factory_(factory) {}
249  T Produce() override { return factory_(); }
250 
251  private:
252  const FactoryFunction factory_;
253  GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
254  };
255 
256  static ValueProducer* producer_;
257 };
258 
259 // This partial specialization allows a user to set default values for
260 // reference types.
261 template <typename T>
262 class DefaultValue<T&> {
263  public:
264  // Sets the default value for type T&.
265  static void Set(T& x) { // NOLINT
266  address_ = &x;
267  }
268 
269  // Unsets the default value for type T&.
270  static void Clear() { address_ = nullptr; }
271 
272  // Returns true iff the user has set the default value for type T&.
273  static bool IsSet() { return address_ != nullptr; }
274 
275  // Returns true if T has a default return value set by the user or there
276  // exists a built-in default value.
277  static bool Exists() {
278  return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
279  }
280 
281  // Returns the default value for type T& if the user has set one;
282  // otherwise returns the built-in default value if there is one;
283  // otherwise aborts the process.
284  static T& Get() {
285  return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
286  : *address_;
287  }
288 
289  private:
290  static T* address_;
291 };
292 
293 // This specialization allows DefaultValue<void>::Get() to
294 // compile.
295 template <>
296 class DefaultValue<void> {
297  public:
298  static bool Exists() { return true; }
299  static void Get() {}
300 };
301 
302 // Points to the user-set default value for type T.
303 template <typename T>
305 
306 // Points to the user-set default value for type T&.
307 template <typename T>
308 T* DefaultValue<T&>::address_ = nullptr;
309 
310 // Implement this interface to define an action for function type F.
311 template <typename F>
313  public:
316 
318  virtual ~ActionInterface() {}
319 
320  // Performs the action. This method is not const, as in general an
321  // action can have side effects and be stateful. For example, a
322  // get-the-next-element-from-the-collection action will need to
323  // remember the current element.
324  virtual Result Perform(const ArgumentTuple& args) = 0;
325 
326  private:
328 };
329 
330 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
331 // object that represents an action to be taken when a mock function
332 // of type F is called. The implementation of Action<T> is just a
333 // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
334 // You can view an object implementing ActionInterface<F> as a
335 // concrete action (including its current state), and an Action<F>
336 // object as a handle to it.
337 template <typename F>
338 class Action {
339  // Adapter class to allow constructing Action from a legacy ActionInterface.
340  // New code should create Actions from functors instead.
341  struct ActionAdapter {
342  // Adapter must be copyable to satisfy std::function requirements.
343  ::std::shared_ptr<ActionInterface<F>> impl_;
344 
345  template <typename... Args>
346  typename internal::Function<F>::Result operator()(Args&&... args) {
347  return impl_->Perform(
348  ::std::forward_as_tuple(::std::forward<Args>(args)...));
349  }
350  };
351 
352  public:
355 
356  // Constructs a null Action. Needed for storing Action objects in
357  // STL containers.
358  Action() {}
359 
360  // Construct an Action from a specified callable.
361  // This cannot take std::function directly, because then Action would not be
362  // directly constructible from lambda (it would require two conversions).
363  template <typename G,
364  typename = typename ::std::enable_if<
365  ::std::is_constructible<::std::function<F>, G>::value>::type>
366  Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
367 
368  // Constructs an Action from its implementation.
369  explicit Action(ActionInterface<F>* impl)
370  : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
371 
372  // This constructor allows us to turn an Action<Func> object into an
373  // Action<F>, as long as F's arguments can be implicitly converted
374  // to Func's and Func's return type can be implicitly converted to F's.
375  template <typename Func>
376  explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
377 
378  // Returns true iff this is the DoDefault() action.
379  bool IsDoDefault() const { return fun_ == nullptr; }
380 
381  // Performs the action. Note that this method is const even though
382  // the corresponding method in ActionInterface is not. The reason
383  // is that a const Action<F> means that it cannot be re-bound to
384  // another concrete action, not that the concrete action it binds to
385  // cannot change state. (Think of the difference between a const
386  // pointer and a pointer to const.)
387  Result Perform(ArgumentTuple args) const {
388  if (IsDoDefault()) {
389  internal::IllegalDoDefault(__FILE__, __LINE__);
390  }
391  return internal::Apply(fun_, ::std::move(args));
392  }
393 
394  private:
395  template <typename G>
396  friend class Action;
397 
398  // fun_ is an empty function iff this is the DoDefault() action.
399  ::std::function<F> fun_;
400 };
401 
402 // The PolymorphicAction class template makes it easy to implement a
403 // polymorphic action (i.e. an action that can be used in mock
404 // functions of than one type, e.g. Return()).
405 //
406 // To define a polymorphic action, a user first provides a COPYABLE
407 // implementation class that has a Perform() method template:
408 //
409 // class FooAction {
410 // public:
411 // template <typename Result, typename ArgumentTuple>
412 // Result Perform(const ArgumentTuple& args) const {
413 // // Processes the arguments and returns a result, using
414 // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
415 // }
416 // ...
417 // };
418 //
419 // Then the user creates the polymorphic action using
420 // MakePolymorphicAction(object) where object has type FooAction. See
421 // the definition of Return(void) and SetArgumentPointee<N>(value) for
422 // complete examples.
423 template <typename Impl>
425  public:
426  explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
427 
428  template <typename F>
429  operator Action<F>() const {
430  return Action<F>(new MonomorphicImpl<F>(impl_));
431  }
432 
433  private:
434  template <typename F>
435  class MonomorphicImpl : public ActionInterface<F> {
436  public:
437  typedef typename internal::Function<F>::Result Result;
438  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
439 
440  explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
441 
442  Result Perform(const ArgumentTuple& args) override {
443  return impl_.template Perform<Result>(args);
444  }
445 
446  private:
447  Impl impl_;
448 
449  GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
450  };
451 
452  Impl impl_;
453 
455 };
456 
457 // Creates an Action from its implementation and returns it. The
458 // created Action object owns the implementation.
459 template <typename F>
461  return Action<F>(impl);
462 }
463 
464 // Creates a polymorphic action from its implementation. This is
465 // easier to use than the PolymorphicAction<Impl> constructor as it
466 // doesn't require you to explicitly write the template argument, e.g.
467 //
468 // MakePolymorphicAction(foo);
469 // vs
470 // PolymorphicAction<TypeOfFoo>(foo);
471 template <typename Impl>
473  return PolymorphicAction<Impl>(impl);
474 }
475 
476 namespace internal {
477 
478 // Helper struct to specialize ReturnAction to execute a move instead of a copy
479 // on return. Useful for move-only types, but could be used on any type.
480 template <typename T>
482  explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
484 };
485 
486 // Implements the polymorphic Return(x) action, which can be used in
487 // any function that returns the type of x, regardless of the argument
488 // types.
489 //
490 // Note: The value passed into Return must be converted into
491 // Function<F>::Result when this action is cast to Action<F> rather than
492 // when that action is performed. This is important in scenarios like
493 //
494 // MOCK_METHOD1(Method, T(U));
495 // ...
496 // {
497 // Foo foo;
498 // X x(&foo);
499 // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
500 // }
501 //
502 // In the example above the variable x holds reference to foo which leaves
503 // scope and gets destroyed. If copying X just copies a reference to foo,
504 // that copy will be left with a hanging reference. If conversion to T
505 // makes a copy of foo, the above code is safe. To support that scenario, we
506 // need to make sure that the type conversion happens inside the EXPECT_CALL
507 // statement, and conversion of the result of Return to Action<T(U)> is a
508 // good place for that.
509 //
510 // The real life example of the above scenario happens when an invocation
511 // of gtl::Container() is passed into Return.
512 //
513 template <typename R>
515  public:
516  // Constructs a ReturnAction object from the value to be returned.
517  // 'value' is passed by value instead of by const reference in order
518  // to allow Return("string literal") to compile.
519  explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
520 
521  // This template type conversion operator allows Return(x) to be
522  // used in ANY function that returns x's type.
523  template <typename F>
524  operator Action<F>() const { // NOLINT
525  // Assert statement belongs here because this is the best place to verify
526  // conditions on F. It produces the clearest error messages
527  // in most compilers.
528  // Impl really belongs in this scope as a local class but can't
529  // because MSVC produces duplicate symbols in different translation units
530  // in this case. Until MS fixes that bug we put Impl into the class scope
531  // and put the typedef both here (for use in assert statement) and
532  // in the Impl class. But both definitions must be the same.
533  typedef typename Function<F>::Result Result;
536  use_ReturnRef_instead_of_Return_to_return_a_reference);
537  static_assert(!std::is_void<Result>::value,
538  "Can't use Return() on an action expected to return `void`.");
539  return Action<F>(new Impl<R, F>(value_));
540  }
541 
542  private:
543  // Implements the Return(x) action for a particular function type F.
544  template <typename R_, typename F>
545  class Impl : public ActionInterface<F> {
546  public:
547  typedef typename Function<F>::Result Result;
548  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
549 
550  // The implicit cast is necessary when Result has more than one
551  // single-argument constructor (e.g. Result is std::vector<int>) and R
552  // has a type conversion operator template. In that case, value_(value)
553  // won't compile as the compiler doesn't known which constructor of
554  // Result to call. ImplicitCast_ forces the compiler to convert R to
555  // Result without considering explicit constructors, thus resolving the
556  // ambiguity. value_ is then initialized using its copy constructor.
557  explicit Impl(const std::shared_ptr<R>& value)
558  : value_before_cast_(*value),
559  value_(ImplicitCast_<Result>(value_before_cast_)) {}
560 
561  Result Perform(const ArgumentTuple&) override { return value_; }
562 
563  private:
565  Result_cannot_be_a_reference_type);
566  // We save the value before casting just in case it is being cast to a
567  // wrapper type.
568  R value_before_cast_;
569  Result value_;
570 
572  };
573 
574  // Partially specialize for ByMoveWrapper. This version of ReturnAction will
575  // move its contents instead.
576  template <typename R_, typename F>
577  class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
578  public:
579  typedef typename Function<F>::Result Result;
580  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
581 
582  explicit Impl(const std::shared_ptr<R>& wrapper)
583  : performed_(false), wrapper_(wrapper) {}
584 
585  Result Perform(const ArgumentTuple&) override {
586  GTEST_CHECK_(!performed_)
587  << "A ByMove() action should only be performed once.";
588  performed_ = true;
589  return std::move(wrapper_->payload);
590  }
591 
592  private:
593  bool performed_;
594  const std::shared_ptr<R> wrapper_;
595 
597  };
598 
599  const std::shared_ptr<R> value_;
600 
602 };
603 
604 // Implements the ReturnNull() action.
606  public:
607  // Allows ReturnNull() to be used in any pointer-returning function. In C++11
608  // this is enforced by returning nullptr, and in non-C++11 by asserting a
609  // pointer type on compile time.
610  template <typename Result, typename ArgumentTuple>
611  static Result Perform(const ArgumentTuple&) {
612  return nullptr;
613  }
614 };
615 
616 // Implements the Return() action.
618  public:
619  // Allows Return() to be used in any void-returning function.
620  template <typename Result, typename ArgumentTuple>
621  static void Perform(const ArgumentTuple&) {
623  }
624 };
625 
626 // Implements the polymorphic ReturnRef(x) action, which can be used
627 // in any function that returns a reference to the type of x,
628 // regardless of the argument types.
629 template <typename T>
631  public:
632  // Constructs a ReturnRefAction object from the reference to be returned.
633  explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
634 
635  // This template type conversion operator allows ReturnRef(x) to be
636  // used in ANY function that returns a reference to x's type.
637  template <typename F>
638  operator Action<F>() const {
639  typedef typename Function<F>::Result Result;
640  // Asserts that the function return type is a reference. This
641  // catches the user error of using ReturnRef(x) when Return(x)
642  // should be used, and generates some helpful error message.
644  use_Return_instead_of_ReturnRef_to_return_a_value);
645  return Action<F>(new Impl<F>(ref_));
646  }
647 
648  private:
649  // Implements the ReturnRef(x) action for a particular function type F.
650  template <typename F>
651  class Impl : public ActionInterface<F> {
652  public:
653  typedef typename Function<F>::Result Result;
654  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
655 
656  explicit Impl(T& ref) : ref_(ref) {} // NOLINT
657 
658  Result Perform(const ArgumentTuple&) override { return ref_; }
659 
660  private:
661  T& ref_;
662 
664  };
665 
666  T& ref_;
667 
669 };
670 
671 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
672 // used in any function that returns a reference to the type of x,
673 // regardless of the argument types.
674 template <typename T>
676  public:
677  // Constructs a ReturnRefOfCopyAction object from the reference to
678  // be returned.
679  explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
680 
681  // This template type conversion operator allows ReturnRefOfCopy(x) to be
682  // used in ANY function that returns a reference to x's type.
683  template <typename F>
684  operator Action<F>() const {
685  typedef typename Function<F>::Result Result;
686  // Asserts that the function return type is a reference. This
687  // catches the user error of using ReturnRefOfCopy(x) when Return(x)
688  // should be used, and generates some helpful error message.
691  use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
692  return Action<F>(new Impl<F>(value_));
693  }
694 
695  private:
696  // Implements the ReturnRefOfCopy(x) action for a particular function type F.
697  template <typename F>
698  class Impl : public ActionInterface<F> {
699  public:
700  typedef typename Function<F>::Result Result;
701  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
702 
703  explicit Impl(const T& value) : value_(value) {} // NOLINT
704 
705  Result Perform(const ArgumentTuple&) override { return value_; }
706 
707  private:
708  T value_;
709 
711  };
712 
713  const T value_;
714 
716 };
717 
718 // Implements the polymorphic DoDefault() action.
720  public:
721  // This template type conversion operator allows DoDefault() to be
722  // used in any function.
723  template <typename F>
724  operator Action<F>() const { return Action<F>(); } // NOLINT
725 };
726 
727 // Implements the Assign action to set a given pointer referent to a
728 // particular value.
729 template <typename T1, typename T2>
731  public:
732  AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
733 
734  template <typename Result, typename ArgumentTuple>
735  void Perform(const ArgumentTuple& /* args */) const {
736  *ptr_ = value_;
737  }
738 
739  private:
740  T1* const ptr_;
741  const T2 value_;
742 
744 };
745 
746 #if !GTEST_OS_WINDOWS_MOBILE
747 
748 // Implements the SetErrnoAndReturn action to simulate return from
749 // various system calls and libc functions.
750 template <typename T>
752  public:
753  SetErrnoAndReturnAction(int errno_value, T result)
754  : errno_(errno_value),
755  result_(result) {}
756  template <typename Result, typename ArgumentTuple>
757  Result Perform(const ArgumentTuple& /* args */) const {
758  errno = errno_;
759  return result_;
760  }
761 
762  private:
763  const int errno_;
764  const T result_;
765 
767 };
768 
769 #endif // !GTEST_OS_WINDOWS_MOBILE
770 
771 // Implements the SetArgumentPointee<N>(x) action for any function
772 // whose N-th argument (0-based) is a pointer to x's type.
773 template <size_t N, typename A, typename = void>
775  A value;
776 
777  template <typename... Args>
778  void operator()(const Args&... args) const {
779  *::std::get<N>(std::tie(args...)) = value;
780  }
781 };
782 
783 // Implements the Invoke(object_ptr, &Class::Method) action.
784 template <class Class, typename MethodPtr>
786  Class* const obj_ptr;
787  const MethodPtr method_ptr;
788 
789  template <typename... Args>
790  auto operator()(Args&&... args) const
791  -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
792  return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
793  }
794 };
795 
796 // Implements the InvokeWithoutArgs(f) action. The template argument
797 // FunctionImpl is the implementation type of f, which can be either a
798 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
799 // Action<F> as long as f's type is compatible with F.
800 template <typename FunctionImpl>
802  FunctionImpl function_impl;
803 
804  // Allows InvokeWithoutArgs(f) to be used as any action whose type is
805  // compatible with f.
806  template <typename... Args>
807  auto operator()(const Args&...) -> decltype(function_impl()) {
808  return function_impl();
809  }
810 };
811 
812 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
813 template <class Class, typename MethodPtr>
815  Class* const obj_ptr;
816  const MethodPtr method_ptr;
817 
819 
820  template <typename... Args>
821  ReturnType operator()(const Args&...) const {
822  return (obj_ptr->*method_ptr)();
823  }
824 };
825 
826 // Implements the IgnoreResult(action) action.
827 template <typename A>
829  public:
830  explicit IgnoreResultAction(const A& action) : action_(action) {}
831 
832  template <typename F>
833  operator Action<F>() const {
834  // Assert statement belongs here because this is the best place to verify
835  // conditions on F. It produces the clearest error messages
836  // in most compilers.
837  // Impl really belongs in this scope as a local class but can't
838  // because MSVC produces duplicate symbols in different translation units
839  // in this case. Until MS fixes that bug we put Impl into the class scope
840  // and put the typedef both here (for use in assert statement) and
841  // in the Impl class. But both definitions must be the same.
842  typedef typename internal::Function<F>::Result Result;
843 
844  // Asserts at compile time that F returns void.
846 
847  return Action<F>(new Impl<F>(action_));
848  }
849 
850  private:
851  template <typename F>
852  class Impl : public ActionInterface<F> {
853  public:
854  typedef typename internal::Function<F>::Result Result;
855  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
856 
857  explicit Impl(const A& action) : action_(action) {}
858 
859  void Perform(const ArgumentTuple& args) override {
860  // Performs the action and ignores its result.
861  action_.Perform(args);
862  }
863 
864  private:
865  // Type OriginalFunction is the same as F except that its return
866  // type is IgnoredValue.
868  OriginalFunction;
869 
870  const Action<OriginalFunction> action_;
871 
873  };
874 
875  const A action_;
876 
878 };
879 
880 template <typename InnerAction, size_t... I>
882  InnerAction action;
883 
884  // The inner action could be anything convertible to Action<X>.
885  // We use the conversion operator to detect the signature of the inner Action.
886  template <typename R, typename... Args>
887  operator Action<R(Args...)>() const { // NOLINT
888  Action<R(typename std::tuple_element<I, std::tuple<Args...>>::type...)>
889  converted(action);
890 
891  return [converted](Args... args) -> R {
892  return converted.Perform(std::forward_as_tuple(
893  std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
894  };
895  }
896 };
897 
898 template <typename... Actions>
899 struct DoAllAction {
900  private:
901  template <typename... Args, size_t... I>
902  std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
903  return {std::get<I>(actions)...};
904  }
905 
906  public:
907  std::tuple<Actions...> actions;
908 
909  template <typename R, typename... Args>
910  operator Action<R(Args...)>() const { // NOLINT
911  struct Op {
912  std::vector<Action<void(Args...)>> converted;
913  Action<R(Args...)> last;
914  R operator()(Args... args) const {
915  auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
916  for (auto& a : converted) {
917  a.Perform(tuple_args);
918  }
919  return last.Perform(tuple_args);
920  }
921  };
922  return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()),
923  std::get<sizeof...(Actions) - 1>(actions)};
924  }
925 };
926 
927 } // namespace internal
928 
929 // An Unused object can be implicitly constructed from ANY value.
930 // This is handy when defining actions that ignore some or all of the
931 // mock function arguments. For example, given
932 //
933 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
934 // MOCK_METHOD3(Bar, double(int index, double x, double y));
935 //
936 // instead of
937 //
938 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
939 // return sqrt(x*x + y*y);
940 // }
941 // double DistanceToOriginWithIndex(int index, double x, double y) {
942 // return sqrt(x*x + y*y);
943 // }
944 // ...
945 // EXPECT_CALL(mock, Foo("abc", _, _))
946 // .WillOnce(Invoke(DistanceToOriginWithLabel));
947 // EXPECT_CALL(mock, Bar(5, _, _))
948 // .WillOnce(Invoke(DistanceToOriginWithIndex));
949 //
950 // you could write
951 //
952 // // We can declare any uninteresting argument as Unused.
953 // double DistanceToOrigin(Unused, double x, double y) {
954 // return sqrt(x*x + y*y);
955 // }
956 // ...
957 // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
958 // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
960 
961 // Creates an action that does actions a1, a2, ..., sequentially in
962 // each invocation.
963 template <typename... Action>
965  Action&&... action) {
966  return {std::forward_as_tuple(std::forward<Action>(action)...)};
967 }
968 
969 // WithArg<k>(an_action) creates an action that passes the k-th
970 // (0-based) argument of the mock function to an_action and performs
971 // it. It adapts an action accepting one argument to one that accepts
972 // multiple arguments. For convenience, we also provide
973 // WithArgs<k>(an_action) (defined below) as a synonym.
974 template <size_t k, typename InnerAction>
976 WithArg(InnerAction&& action) {
977  return {std::forward<InnerAction>(action)};
978 }
979 
980 // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
981 // the selected arguments of the mock function to an_action and
982 // performs it. It serves as an adaptor between actions with
983 // different argument lists.
984 template <size_t k, size_t... ks, typename InnerAction>
985 internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
986 WithArgs(InnerAction&& action) {
987  return {std::forward<InnerAction>(action)};
988 }
989 
990 // WithoutArgs(inner_action) can be used in a mock function with a
991 // non-empty argument list to perform inner_action, which takes no
992 // argument. In other words, it adapts an action accepting no
993 // argument to one that accepts (and ignores) arguments.
994 template <typename InnerAction>
995 internal::WithArgsAction<typename std::decay<InnerAction>::type>
996 WithoutArgs(InnerAction&& action) {
997  return {std::forward<InnerAction>(action)};
998 }
999 
1000 // Creates an action that returns 'value'. 'value' is passed by value
1001 // instead of const reference - otherwise Return("string literal")
1002 // will trigger a compiler error about using array as initializer.
1003 template <typename R>
1005  return internal::ReturnAction<R>(std::move(value));
1006 }
1007 
1008 // Creates an action that returns NULL.
1011 }
1012 
1013 // Creates an action that returns from a void function.
1016 }
1017 
1018 // Creates an action that returns the reference to a variable.
1019 template <typename R>
1022 }
1023 
1024 // Creates an action that returns the reference to a copy of the
1025 // argument. The copy is created when the action is constructed and
1026 // lives as long as the action.
1027 template <typename R>
1030 }
1031 
1032 // Modifies the parent action (a Return() action) to perform a move of the
1033 // argument instead of a copy.
1034 // Return(ByMove()) actions can only be executed once and will assert this
1035 // invariant.
1036 template <typename R>
1038  return internal::ByMoveWrapper<R>(std::move(x));
1039 }
1040 
1041 // Creates an action that does the default action for the give mock function.
1043  return internal::DoDefaultAction();
1044 }
1045 
1046 // Creates an action that sets the variable pointed by the N-th
1047 // (0-based) function argument to 'value'.
1048 template <size_t N, typename T>
1050  return {std::move(x)};
1051 }
1052 
1053 // The following version is DEPRECATED.
1054 template <size_t N, typename T>
1056  return {std::move(x)};
1057 }
1058 
1059 // Creates an action that sets a pointer referent to a given value.
1060 template <typename T1, typename T2>
1063 }
1064 
1065 #if !GTEST_OS_WINDOWS_MOBILE
1066 
1067 // Creates an action that sets errno and returns the appropriate error.
1068 template <typename T>
1070 SetErrnoAndReturn(int errval, T result) {
1071  return MakePolymorphicAction(
1072  internal::SetErrnoAndReturnAction<T>(errval, result));
1073 }
1074 
1075 #endif // !GTEST_OS_WINDOWS_MOBILE
1076 
1077 // Various overloads for Invoke().
1078 
1079 // Legacy function.
1080 // Actions can now be implicitly constructed from callables. No need to create
1081 // wrapper objects.
1082 // This function exists for backwards compatibility.
1083 template <typename FunctionImpl>
1084 typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
1085  return std::forward<FunctionImpl>(function_impl);
1086 }
1087 
1088 // Creates an action that invokes the given method on the given object
1089 // with the mock function's arguments.
1090 template <class Class, typename MethodPtr>
1092  MethodPtr method_ptr) {
1093  return {obj_ptr, method_ptr};
1094 }
1095 
1096 // Creates an action that invokes 'function_impl' with no argument.
1097 template <typename FunctionImpl>
1099 InvokeWithoutArgs(FunctionImpl function_impl) {
1100  return {std::move(function_impl)};
1101 }
1102 
1103 // Creates an action that invokes the given method on the given object
1104 // with no argument.
1105 template <class Class, typename MethodPtr>
1107  Class* obj_ptr, MethodPtr method_ptr) {
1108  return {obj_ptr, method_ptr};
1109 }
1110 
1111 // Creates an action that performs an_action and throws away its
1112 // result. In other words, it changes the return type of an_action to
1113 // void. an_action MUST NOT return void, or the code won't compile.
1114 template <typename A>
1115 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1116  return internal::IgnoreResultAction<A>(an_action);
1117 }
1118 
1119 // Creates a reference wrapper for the given L-value. If necessary,
1120 // you can explicitly specify the type of the reference. For example,
1121 // suppose 'derived' is an object of type Derived, ByRef(derived)
1122 // would wrap a Derived&. If you want to wrap a const Base& instead,
1123 // where Base is a base class of Derived, just write:
1124 //
1125 // ByRef<const Base>(derived)
1126 //
1127 // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
1128 // However, it may still be used for consistency with ByMove().
1129 template <typename T>
1130 inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
1131  return ::std::reference_wrapper<T>(l_value);
1132 }
1133 
1134 } // namespace testing
1135 
1136 #ifdef _MSC_VER
1137 # pragma warning(pop)
1138 #endif
1139 
1140 
1141 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
auto Apply(F &&f, Tuple &&args) -> decltype(ApplyImpl(std::forward< F >(f), std::forward< Tuple >(args), make_int_pack< std::tuple_size< Tuple >::value >()))
Definition: gmock-internal-utils.h:525
static Result Perform(const ArgumentTuple &)
Definition: gmock-actions.h:611
Definition: gmock-actions.h:78
PolymorphicAction< internal::ReturnNullAction > ReturnNull()
Definition: gmock-actions.h:1009
ByMoveWrapper(T value)
Definition: gmock-actions.h:482
Definition: gmock-actions.h:59
internal::IgnoredValue Unused
Definition: gmock-actions.h:959
static bool Exists()
Definition: gmock-actions.h:118
static T * Get()
Definition: gmock-actions.h:128
static bool Exists()
Definition: gmock-actions.h:103
GTEST_API_ void IllegalDoDefault(const char *file, int line)
Definition: gmock-internal-utils.cc:189
static void SetFactory(FactoryFunction factory)
Definition: gmock-actions.h:200
PolymorphicAction< internal::AssignAction< T1, T2 > > Assign(T1 *ptr, T2 val)
Definition: gmock-actions.h:1061
const MethodPtr method_ptr
Definition: gmock-actions.h:787
static void Set(T x)
Definition: gmock-actions.h:191
AssignAction(T1 *ptr, T2 value)
Definition: gmock-actions.h:732
Action(const Action< Func > &action)
Definition: gmock-actions.h:376
PolymorphicAction(const Impl &impl)
Definition: gmock-actions.h:426
internal::DoAllAction< typename std::decay< Action >::type... > DoAll(Action &&...action)
Definition: gmock-actions.h:964
IgnoreResultAction(const A &action)
Definition: gmock-actions.h:830
static void Set(T &x)
Definition: gmock-actions.h:265
ReturnType operator()(const Args &...) const
Definition: gmock-actions.h:821
static T Get()
Definition: gmock-actions.h:107
Definition: gtest-internal.h:853
std::tuple< Actions... > actions
Definition: gmock-actions.h:907
internal::InvokeWithoutArgsAction< typename std::decay< FunctionImpl >::type > InvokeWithoutArgs(FunctionImpl function_impl)
Definition: gmock-actions.h:1099
auto operator()(Args &&...args) const -> decltype((obj_ptr-> *method_ptr)(std::forward< Args >(args)...))
Definition: gmock-actions.h:790
static void Get()
Definition: gmock-actions.h:299
Definition: gmock-actions.h:630
internal::WithArgsAction< typename std::decay< InnerAction >::type, k, ks... > WithArgs(InnerAction &&action)
Definition: gmock-actions.h:986
static void Perform(const ArgumentTuple &)
Definition: gmock-actions.h:621
static bool IsSet()
Definition: gmock-actions.h:212
PolymorphicAction< Impl > MakePolymorphicAction(const Impl &impl)
Definition: gmock-actions.h:472
#define GTEST_DISALLOW_ASSIGN_(type)
Definition: gtest-port.h:683
static T Get()
Definition: gmock-actions.h:79
inline::std::reference_wrapper< T > ByRef(T &l_value)
Definition: gmock-actions.h:1130
PolymorphicAction< internal::SetErrnoAndReturnAction< T > > SetErrnoAndReturn(int errval, T result)
Definition: gmock-actions.h:1070
Definition: gmock-actions.h:514
internal::ReturnRefAction< R > ReturnRef(R &x)
Definition: gmock-actions.h:1020
std::decay< FunctionImpl >::type Invoke(FunctionImpl &&function_impl)
Definition: gmock-actions.h:1084
void operator()(const Args &...args) const
Definition: gmock-actions.h:778
Definition: gmock-actions.h:187
Definition: gmock-actions.h:338
const MethodPtr method_ptr
Definition: gmock-actions.h:816
static bool Exists()
Definition: gmock-actions.h:127
static T Get()
Definition: gmock-actions.h:119
internal::SetArgumentPointeeAction< N, T > SetArgPointee(T x)
Definition: gmock-actions.h:1049
Definition: gmock-actions.h:774
Action(ActionInterface< F > *impl)
Definition: gmock-actions.h:369
#define GTEST_COMPILE_ASSERT_(expr, msg)
Definition: gtest-port.h:859
virtual ~ActionInterface()
Definition: gmock-actions.h:318
static T & Get()
Definition: gmock-actions.h:284
Definition: gmock-actions.h:719
static bool Exists()
Definition: gmock-actions.h:216
#define GTEST_CHECK_(condition)
Definition: gtest-port.h:1014
internal::WithArgsAction< typename std::decay< InnerAction >::type > WithoutArgs(InnerAction &&action)
Definition: gmock-actions.h:996
internal::ReturnRefOfCopyAction< R > ReturnRefOfCopy(const R &x)
Definition: gmock-actions.h:1028
Definition: gmock-actions.h:605
Definition: gmock-actions.h:801
SetErrnoAndReturnAction(int errno_value, T result)
Definition: gmock-actions.h:753
FunctionImpl function_impl
Definition: gmock-actions.h:802
Class *const obj_ptr
Definition: gmock-actions.h:815
static bool Exists()
Definition: gmock-actions.h:277
Definition: gtest-internal.h:1172
Class *const obj_ptr
Definition: gmock-actions.h:786
internal::SetArgumentPointeeAction< N, T > SetArgumentPointee(T x)
Definition: gmock-actions.h:1055
Definition: gmock-internal-utils.h:356
Definition: gmock-actions.h:312
Definition: gtest-internal.h:1153
ReturnRefOfCopyAction(const T &value)
Definition: gmock-actions.h:679
internal::Function< F >::ArgumentTuple ArgumentTuple
Definition: gmock-actions.h:354
Definition: gmock-actions.h:881
Definition: gmock-actions.h:730
GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void,)
internal::Function< F >::Result Result
Definition: gmock-actions.h:314
Definition: gmock-actions.h:828
bool IsDoDefault() const
Definition: gmock-actions.h:379
InnerAction action
Definition: gmock-actions.h:882
int value
Definition: gmock-matchers_test.cc:657
T payload
Definition: gmock-actions.h:483
Definition: gmock-actions.h:617
internal::Function< F >::ArgumentTuple ArgumentTuple
Definition: gmock-actions.h:315
static void Clear()
Definition: gmock-actions.h:270
Definition: gmock-actions.h:751
Definition: gmock-actions.h:424
auto operator()(const Args &...) -> decltype(function_impl())
Definition: gmock-actions.h:807
internal::DoDefaultAction DoDefault()
Definition: gmock-actions.h:1042
internal::ReturnAction< R > Return(R value)
Definition: gmock-actions.h:1004
int x
Definition: gmock-matchers_test.cc:3610
void Assert(bool condition, const char *file, int line)
Definition: gmock-internal-utils.h:292
Definition: gmock-actions.h:481
type
Definition: upload.py:443
Definition: gmock-internal-utils.h:546
const
Definition: upload.py:398
Result Perform(const ArgumentTuple &) const
Definition: gmock-actions.h:757
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
Definition: gtest-port.h:688
internal::ByMoveWrapper< R > ByMove(R x)
Definition: gmock-actions.h:1037
TypeWithSize< 8 >::UInt UInt64
Definition: gtest-port.h:2219
internal::WithArgsAction< typename std::decay< InnerAction >::type, k > WithArg(InnerAction &&action)
Definition: gmock-actions.h:976
static bool IsSet()
Definition: gmock-actions.h:273
static void Clear()
Definition: gmock-actions.h:206
Definition: gmock-actions.h:899
internal::Function< F >::Result Result
Definition: gmock-actions.h:353
ReturnRefAction(T &ref)
Definition: gmock-actions.h:633
void Perform(const ArgumentTuple &) const
Definition: gmock-actions.h:735
ReturnAction(R value)
Definition: gmock-actions.h:519
internal::IgnoreResultAction< A > IgnoreResult(const A &an_action)
Definition: gmock-actions.h:1115
TypeWithSize< 8 >::Int Int64
Definition: gtest-port.h:2218
Definition: gmock-actions.h:100
A value
Definition: gmock-actions.h:775
Definition: gmock-actions.h:675
static T Get()
Definition: gmock-actions.h:83
Action()
Definition: gmock-actions.h:358
Result Perform(ArgumentTuple args) const
Definition: gmock-actions.h:387
Definition: gmock-actions.h:785
ActionInterface()
Definition: gmock-actions.h:317
typename std::result_of< MethodPtr(Class *)>::type ReturnType
Definition: gmock-actions.h:818
Action(G &&fun)
Definition: gmock-actions.h:366
static bool Exists()
Definition: gmock-actions.h:298
static T Get()
Definition: gmock-actions.h:223
Action< F > MakeAction(ActionInterface< F > *impl)
Definition: gmock-actions.h:460
Definition: gtest-internal.h:110
action
Definition: upload.py:393