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
51#include "gmock/internal/gmock-internal-utils.h"
52#include "gmock/internal/gmock-port.h"
53
54#ifdef _MSC_VER
55# pragma warning(push)
56# pragma warning(disable:4100)
57#endif
58
59namespace 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
70namespace 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.
77template <typename T, bool kDefaultConstructible>
78struct BuiltInDefaultValueGetter {
79 static T Get() { return T(); }
80};
81template <typename T>
82struct 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.
99template <typename T>
100class BuiltInDefaultValue {
101 public:
102 // This function returns true iff type T has a built-in default value.
103 static bool Exists() {
104 return ::std::is_default_constructible<T>::value;
105 }
106
107 static T Get() {
108 return BuiltInDefaultValueGetter<
109 T, ::std::is_default_constructible<T>::value>::Get();
110 }
111};
112
113// This partial specialization says that we use the same built-in
114// default value for T and const T.
115template <typename T>
116class BuiltInDefaultValue<const 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.
124template <typename T>
125class BuiltInDefaultValue<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
141GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
142GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
143GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
144GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
145GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
146GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
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_
155GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
156#endif
157
158GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
159GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
160GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
161GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
162GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
163GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
164GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
165GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
166GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
167GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
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);
186template <typename T>
187class DefaultValue {
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.
261template <typename T>
262class 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.
295template <>
296class 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.
303template <typename T>
304typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
305
306// Points to the user-set default value for type T&.
307template <typename T>
308T* DefaultValue<T&>::address_ = nullptr;
309
310// Implement this interface to define an action for function type F.
311template <typename F>
312class ActionInterface {
313 public:
314 typedef typename internal::Function<F>::Result Result;
315 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
316
317 ActionInterface() {}
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:
327 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
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.
337template <typename F>
338class 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:
353 typedef typename internal::Function<F>::Result Result;
354 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
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.
423template <typename Impl>
424class PolymorphicAction {
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
454 GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
455};
456
457// Creates an Action from its implementation and returns it. The
458// created Action object owns the implementation.
459template <typename F>
460Action<F> MakeAction(ActionInterface<F>* impl) {
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);
471template <typename Impl>
472inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
473 return PolymorphicAction<Impl>(impl);
474}
475
476namespace 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.
480template <typename T>
481struct ByMoveWrapper {
482 explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
483 T payload;
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//
513template <typename R>
514class ReturnAction {
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;
534 GTEST_COMPILE_ASSERT_(
535 !is_reference<Result>::value,
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:
564 GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
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
571 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
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
596 GTEST_DISALLOW_ASSIGN_(Impl);
597 };
598
599 const std::shared_ptr<R> value_;
600
601 GTEST_DISALLOW_ASSIGN_(ReturnAction);
602};
603
604// Implements the ReturnNull() action.
605class ReturnNullAction {
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.
617class ReturnVoidAction {
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&) {
622 CompileAssertTypesEqual<void, Result>();
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.
629template <typename T>
630class ReturnRefAction {
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.
643 GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
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
663 GTEST_DISALLOW_ASSIGN_(Impl);
664 };
665
666 T& ref_;
667
668 GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
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.
674template <typename T>
675class ReturnRefOfCopyAction {
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.
689 GTEST_COMPILE_ASSERT_(
690 internal::is_reference<Result>::value,
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
710 GTEST_DISALLOW_ASSIGN_(Impl);
711 };
712
713 const T value_;
714
715 GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
716};
717
718// Implements the polymorphic DoDefault() action.
719class DoDefaultAction {
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.
729template <typename T1, typename T2>
730class AssignAction {
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
743 GTEST_DISALLOW_ASSIGN_(AssignAction);
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.
750template <typename T>
751class SetErrnoAndReturnAction {
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
766 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
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.
773template <size_t N, typename A, typename = void>
774struct SetArgumentPointeeAction {
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.
784template <class Class, typename MethodPtr>
785struct InvokeMethodAction {
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.
800template <typename FunctionImpl>
801struct InvokeWithoutArgsAction {
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.
813template <class Class, typename MethodPtr>
814struct InvokeMethodWithoutArgsAction {
815 Class* const obj_ptr;
816 const MethodPtr method_ptr;
817
818 using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
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.
827template <typename A>
828class IgnoreResultAction {
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.
845 CompileAssertTypesEqual<void, Result>();
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.
867 typedef typename internal::Function<F>::MakeResultIgnoredValue
868 OriginalFunction;
869
870 const Action<OriginalFunction> action_;
871
872 GTEST_DISALLOW_ASSIGN_(Impl);
873 };
874
875 const A action_;
876
877 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
878};
879
880template <typename InnerAction, size_t... I>
881struct WithArgsAction {
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
898template <typename... Actions>
899struct 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));
959typedef internal::IgnoredValue Unused;
960
961// Creates an action that does actions a1, a2, ..., sequentially in
962// each invocation.
963template <typename... Action>
964internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
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.
974template <size_t k, typename InnerAction>
975internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
976WithArg(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.
984template <size_t k, size_t... ks, typename InnerAction>
985internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
986WithArgs(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.
994template <typename InnerAction>
995internal::WithArgsAction<typename std::decay<InnerAction>::type>
996WithoutArgs(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.
1003template <typename R>
1004internal::ReturnAction<R> Return(R value) {
1005 return internal::ReturnAction<R>(std::move(value));
1006}
1007
1008// Creates an action that returns NULL.
1009inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1010 return MakePolymorphicAction(internal::ReturnNullAction());
1011}
1012
1013// Creates an action that returns from a void function.
1014inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1015 return MakePolymorphicAction(internal::ReturnVoidAction());
1016}
1017
1018// Creates an action that returns the reference to a variable.
1019template <typename R>
1020inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
1021 return internal::ReturnRefAction<R>(x);
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.
1027template <typename R>
1028inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1029 return internal::ReturnRefOfCopyAction<R>(x);
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.
1036template <typename R>
1037internal::ByMoveWrapper<R> ByMove(R x) {
1038 return internal::ByMoveWrapper<R>(std::move(x));
1039}
1040
1041// Creates an action that does the default action for the give mock function.
1042inline internal::DoDefaultAction DoDefault() {
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'.
1048template <size_t N, typename T>
1049internal::SetArgumentPointeeAction<N, T> SetArgPointee(T x) {
1050 return {std::move(x)};
1051}
1052
1053// The following version is DEPRECATED.
1054template <size_t N, typename T>
1055internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T x) {
1056 return {std::move(x)};
1057}
1058
1059// Creates an action that sets a pointer referent to a given value.
1060template <typename T1, typename T2>
1061PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
1062 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1063}
1064
1065#if !GTEST_OS_WINDOWS_MOBILE
1066
1067// Creates an action that sets errno and returns the appropriate error.
1068template <typename T>
1069PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
1070SetErrnoAndReturn(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.
1083template <typename FunctionImpl>
1084typename 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.
1090template <class Class, typename MethodPtr>
1091internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
1092 MethodPtr method_ptr) {
1093 return {obj_ptr, method_ptr};
1094}
1095
1096// Creates an action that invokes 'function_impl' with no argument.
1097template <typename FunctionImpl>
1098internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
1099InvokeWithoutArgs(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.
1105template <class Class, typename MethodPtr>
1106internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
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.
1114template <typename A>
1115inline 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().
1129template <typename T>
1130inline ::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_
1142