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 // Author: wan@google.com (Zhanyong Wan)
31
32 // Google Mock - a framework for writing C++ mock classes.
33 //
34 // This file implements some commonly used actions.
35
36 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
37 #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
38
39 #include <algorithm>
40 #include <string>
41
42 #ifndef _WIN32_WCE
43 #include <errno.h>
44 #endif
45
46 #include <gmock/gmock-printers.h>
47 #include <gmock/internal/gmock-internal-utils.h>
48 #include <gmock/internal/gmock-port.h>
49
50 namespace testing {
51
52 // To implement an action Foo, define:
53 // 1. a class FooAction that implements the ActionInterface interface, and
54 // 2. a factory function that creates an Action object from a
55 // const FooAction*.
56 //
57 // The two-level delegation design follows that of Matcher, providing
58 // consistency for extension developers. It also eases ownership
59 // management as Action objects can now be copied like plain values.
60
61 namespace internal {
62
63 template <typename F>
64 class MonomorphicDoDefaultActionImpl;
65
66 template <typename F1, typename F2>
67 class ActionAdaptor;
68
69 // BuiltInDefaultValue<T>::Get() returns the "built-in" default
70 // value for type T, which is NULL when T is a pointer type, 0 when T
71 // is a numeric type, false when T is bool, or "" when T is string or
72 // std::string. For any other type T, this value is undefined and the
73 // function will abort the process.
74 template <typename T>
75 class BuiltInDefaultValue {
76 public:
77 // This function returns true iff type T has a built-in default value.
Exists()78 static bool Exists() { return false; }
Get()79 static T Get() {
80 Assert(false, __FILE__, __LINE__,
81 "Default action undefined for the function return type.");
82 return internal::Invalid<T>();
83 // The above statement will never be reached, but is required in
84 // order for this function to compile.
85 }
86 };
87
88 // This partial specialization says that we use the same built-in
89 // default value for T and const T.
90 template <typename T>
91 class BuiltInDefaultValue<const T> {
92 public:
Exists()93 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
Get()94 static T Get() { return BuiltInDefaultValue<T>::Get(); }
95 };
96
97 // This partial specialization defines the default values for pointer
98 // types.
99 template <typename T>
100 class BuiltInDefaultValue<T*> {
101 public:
Exists()102 static bool Exists() { return true; }
Get()103 static T* Get() { return NULL; }
104 };
105
106 // The following specializations define the default values for
107 // specific types we care about.
108 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
109 template <> \
110 class BuiltInDefaultValue<type> { \
111 public: \
112 static bool Exists() { return true; } \
113 static type Get() { return value; } \
114 }
115
116 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
117 #if GTEST_HAS_GLOBAL_STRING
118 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
119 #endif // GTEST_HAS_GLOBAL_STRING
120 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
121 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
122 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
123 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
124 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
125
126 // There's no need for a default action for signed wchar_t, as that
127 // type is the same as wchar_t for gcc, and invalid for MSVC.
128 //
129 // There's also no need for a default action for unsigned wchar_t, as
130 // that type is the same as unsigned int for gcc, and invalid for
131 // MSVC.
132 #if GMOCK_WCHAR_T_IS_NATIVE_
133 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
134 #endif
135
136 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
137 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
138 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
139 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
140 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
141 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
142 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
143 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
144 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
145 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
146
147 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
148
149 } // namespace internal
150
151 // When an unexpected function call is encountered, Google Mock will
152 // let it return a default value if the user has specified one for its
153 // return type, or if the return type has a built-in default value;
154 // otherwise Google Mock won't know what value to return and will have
155 // to abort the process.
156 //
157 // The DefaultValue<T> class allows a user to specify the
158 // default value for a type T that is both copyable and publicly
159 // destructible (i.e. anything that can be used as a function return
160 // type). The usage is:
161 //
162 // // Sets the default value for type T to be foo.
163 // DefaultValue<T>::Set(foo);
164 template <typename T>
165 class DefaultValue {
166 public:
167 // Sets the default value for type T; requires T to be
168 // copy-constructable and have a public destructor.
Set(T x)169 static void Set(T x) {
170 delete value_;
171 value_ = new T(x);
172 }
173
174 // Unsets the default value for type T.
Clear()175 static void Clear() {
176 delete value_;
177 value_ = NULL;
178 }
179
180 // Returns true iff the user has set the default value for type T.
IsSet()181 static bool IsSet() { return value_ != NULL; }
182
183 // Returns true if T has a default return value set by the user or there
184 // exists a built-in default value.
Exists()185 static bool Exists() {
186 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
187 }
188
189 // Returns the default value for type T if the user has set one;
190 // otherwise returns the built-in default value if there is one;
191 // otherwise aborts the process.
Get()192 static T Get() {
193 return value_ == NULL ?
194 internal::BuiltInDefaultValue<T>::Get() : *value_;
195 }
196 private:
197 static const T* value_;
198 };
199
200 // This partial specialization allows a user to set default values for
201 // reference types.
202 template <typename T>
203 class DefaultValue<T&> {
204 public:
205 // Sets the default value for type T&.
Set(T & x)206 static void Set(T& x) { // NOLINT
207 address_ = &x;
208 }
209
210 // Unsets the default value for type T&.
Clear()211 static void Clear() {
212 address_ = NULL;
213 }
214
215 // Returns true iff the user has set the default value for type T&.
IsSet()216 static bool IsSet() { return address_ != NULL; }
217
218 // Returns true if T has a default return value set by the user or there
219 // exists a built-in default value.
Exists()220 static bool Exists() {
221 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
222 }
223
224 // Returns the default value for type T& if the user has set one;
225 // otherwise returns the built-in default value if there is one;
226 // otherwise aborts the process.
Get()227 static T& Get() {
228 return address_ == NULL ?
229 internal::BuiltInDefaultValue<T&>::Get() : *address_;
230 }
231 private:
232 static T* address_;
233 };
234
235 // This specialization allows DefaultValue<void>::Get() to
236 // compile.
237 template <>
238 class DefaultValue<void> {
239 public:
Exists()240 static bool Exists() { return true; }
Get()241 static void Get() {}
242 };
243
244 // Points to the user-set default value for type T.
245 template <typename T>
246 const T* DefaultValue<T>::value_ = NULL;
247
248 // Points to the user-set default value for type T&.
249 template <typename T>
250 T* DefaultValue<T&>::address_ = NULL;
251
252 // Implement this interface to define an action for function type F.
253 template <typename F>
254 class ActionInterface {
255 public:
256 typedef typename internal::Function<F>::Result Result;
257 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
258
ActionInterface()259 ActionInterface() : is_do_default_(false) {}
260
~ActionInterface()261 virtual ~ActionInterface() {}
262
263 // Performs the action. This method is not const, as in general an
264 // action can have side effects and be stateful. For example, a
265 // get-the-next-element-from-the-collection action will need to
266 // remember the current element.
267 virtual Result Perform(const ArgumentTuple& args) = 0;
268
269 // Returns true iff this is the DoDefault() action.
IsDoDefault()270 bool IsDoDefault() const { return is_do_default_; }
271
272 private:
273 template <typename Function>
274 friend class internal::MonomorphicDoDefaultActionImpl;
275
276 // This private constructor is reserved for implementing
277 // DoDefault(), the default action for a given mock function.
ActionInterface(bool is_do_default)278 explicit ActionInterface(bool is_do_default)
279 : is_do_default_(is_do_default) {}
280
281 // True iff this action is DoDefault().
282 const bool is_do_default_;
283
284 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
285 };
286
287 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
288 // object that represents an action to be taken when a mock function
289 // of type F is called. The implementation of Action<T> is just a
290 // linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
291 // Don't inherit from Action!
292 //
293 // You can view an object implementing ActionInterface<F> as a
294 // concrete action (including its current state), and an Action<F>
295 // object as a handle to it.
296 template <typename F>
297 class Action {
298 public:
299 typedef typename internal::Function<F>::Result Result;
300 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
301
302 // Constructs a null Action. Needed for storing Action objects in
303 // STL containers.
Action()304 Action() : impl_(NULL) {}
305
306 // Constructs an Action from its implementation.
Action(ActionInterface<F> * impl)307 explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
308
309 // Copy constructor.
Action(const Action & action)310 Action(const Action& action) : impl_(action.impl_) {}
311
312 // This constructor allows us to turn an Action<Func> object into an
313 // Action<F>, as long as F's arguments can be implicitly converted
314 // to Func's and Func's return type can be implicitly converted to
315 // F's.
316 template <typename Func>
317 explicit Action(const Action<Func>& action);
318
319 // Returns true iff this is the DoDefault() action.
IsDoDefault()320 bool IsDoDefault() const { return impl_->IsDoDefault(); }
321
322 // Performs the action. Note that this method is const even though
323 // the corresponding method in ActionInterface is not. The reason
324 // is that a const Action<F> means that it cannot be re-bound to
325 // another concrete action, not that the concrete action it binds to
326 // cannot change state. (Think of the difference between a const
327 // pointer and a pointer to const.)
Perform(const ArgumentTuple & args)328 Result Perform(const ArgumentTuple& args) const {
329 return impl_->Perform(args);
330 }
331
332 private:
333 template <typename F1, typename F2>
334 friend class internal::ActionAdaptor;
335
336 internal::linked_ptr<ActionInterface<F> > impl_;
337 };
338
339 // The PolymorphicAction class template makes it easy to implement a
340 // polymorphic action (i.e. an action that can be used in mock
341 // functions of than one type, e.g. Return()).
342 //
343 // To define a polymorphic action, a user first provides a COPYABLE
344 // implementation class that has a Perform() method template:
345 //
346 // class FooAction {
347 // public:
348 // template <typename Result, typename ArgumentTuple>
349 // Result Perform(const ArgumentTuple& args) const {
350 // // Processes the arguments and returns a result, using
351 // // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
352 // }
353 // ...
354 // };
355 //
356 // Then the user creates the polymorphic action using
357 // MakePolymorphicAction(object) where object has type FooAction. See
358 // the definition of Return(void) and SetArgumentPointee<N>(value) for
359 // complete examples.
360 template <typename Impl>
361 class PolymorphicAction {
362 public:
PolymorphicAction(const Impl & impl)363 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
364
365 template <typename F>
366 operator Action<F>() const {
367 return Action<F>(new MonomorphicImpl<F>(impl_));
368 }
369
370 private:
371 template <typename F>
372 class MonomorphicImpl : public ActionInterface<F> {
373 public:
374 typedef typename internal::Function<F>::Result Result;
375 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
376
MonomorphicImpl(const Impl & impl)377 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
378
Perform(const ArgumentTuple & args)379 virtual Result Perform(const ArgumentTuple& args) {
380 return impl_.template Perform<Result>(args);
381 }
382
383 private:
384 Impl impl_;
385
386 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
387 };
388
389 Impl impl_;
390
391 GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
392 };
393
394 // Creates an Action from its implementation and returns it. The
395 // created Action object owns the implementation.
396 template <typename F>
MakeAction(ActionInterface<F> * impl)397 Action<F> MakeAction(ActionInterface<F>* impl) {
398 return Action<F>(impl);
399 }
400
401 // Creates a polymorphic action from its implementation. This is
402 // easier to use than the PolymorphicAction<Impl> constructor as it
403 // doesn't require you to explicitly write the template argument, e.g.
404 //
405 // MakePolymorphicAction(foo);
406 // vs
407 // PolymorphicAction<TypeOfFoo>(foo);
408 template <typename Impl>
MakePolymorphicAction(const Impl & impl)409 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
410 return PolymorphicAction<Impl>(impl);
411 }
412
413 namespace internal {
414
415 // Allows an Action<F2> object to pose as an Action<F1>, as long as F2
416 // and F1 are compatible.
417 template <typename F1, typename F2>
418 class ActionAdaptor : public ActionInterface<F1> {
419 public:
420 typedef typename internal::Function<F1>::Result Result;
421 typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
422
ActionAdaptor(const Action<F2> & from)423 explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
424
Perform(const ArgumentTuple & args)425 virtual Result Perform(const ArgumentTuple& args) {
426 return impl_->Perform(args);
427 }
428
429 private:
430 const internal::linked_ptr<ActionInterface<F2> > impl_;
431
432 GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
433 };
434
435 // Implements the polymorphic Return(x) action, which can be used in
436 // any function that returns the type of x, regardless of the argument
437 // types.
438 //
439 // Note: The value passed into Return must be converted into
440 // Function<F>::Result when this action is cast to Action<F> rather than
441 // when that action is performed. This is important in scenarios like
442 //
443 // MOCK_METHOD1(Method, T(U));
444 // ...
445 // {
446 // Foo foo;
447 // X x(&foo);
448 // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
449 // }
450 //
451 // In the example above the variable x holds reference to foo which leaves
452 // scope and gets destroyed. If copying X just copies a reference to foo,
453 // that copy will be left with a hanging reference. If conversion to T
454 // makes a copy of foo, the above code is safe. To support that scenario, we
455 // need to make sure that the type conversion happens inside the EXPECT_CALL
456 // statement, and conversion of the result of Return to Action<T(U)> is a
457 // good place for that.
458 //
459 template <typename R>
460 class ReturnAction {
461 public:
462 // Constructs a ReturnAction object from the value to be returned.
463 // 'value' is passed by value instead of by const reference in order
464 // to allow Return("string literal") to compile.
ReturnAction(R value)465 explicit ReturnAction(R value) : value_(value) {}
466
467 // This template type conversion operator allows Return(x) to be
468 // used in ANY function that returns x's type.
469 template <typename F>
470 operator Action<F>() const {
471 // Assert statement belongs here because this is the best place to verify
472 // conditions on F. It produces the clearest error messages
473 // in most compilers.
474 // Impl really belongs in this scope as a local class but can't
475 // because MSVC produces duplicate symbols in different translation units
476 // in this case. Until MS fixes that bug we put Impl into the class scope
477 // and put the typedef both here (for use in assert statement) and
478 // in the Impl class. But both definitions must be the same.
479 typedef typename Function<F>::Result Result;
480 GMOCK_COMPILE_ASSERT_(
481 !internal::is_reference<Result>::value,
482 use_ReturnRef_instead_of_Return_to_return_a_reference);
483 return Action<F>(new Impl<F>(value_));
484 }
485
486 private:
487 // Implements the Return(x) action for a particular function type F.
488 template <typename F>
489 class Impl : public ActionInterface<F> {
490 public:
491 typedef typename Function<F>::Result Result;
492 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
493
494 // The implicit cast is necessary when Result has more than one
495 // single-argument constructor (e.g. Result is std::vector<int>) and R
496 // has a type conversion operator template. In that case, value_(value)
497 // won't compile as the compiler doesn't known which constructor of
498 // Result to call. implicit_cast forces the compiler to convert R to
499 // Result without considering explicit constructors, thus resolving the
500 // ambiguity. value_ is then initialized using its copy constructor.
Impl(R value)501 explicit Impl(R value)
502 : value_(::testing::internal::implicit_cast<Result>(value)) {}
503
Perform(const ArgumentTuple &)504 virtual Result Perform(const ArgumentTuple&) { return value_; }
505
506 private:
507 GMOCK_COMPILE_ASSERT_(!internal::is_reference<Result>::value,
508 Result_cannot_be_a_reference_type);
509 Result value_;
510
511 GTEST_DISALLOW_ASSIGN_(Impl);
512 };
513
514 R value_;
515
516 GTEST_DISALLOW_ASSIGN_(ReturnAction);
517 };
518
519 // Implements the ReturnNull() action.
520 class ReturnNullAction {
521 public:
522 // Allows ReturnNull() to be used in any pointer-returning function.
523 template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple &)524 static Result Perform(const ArgumentTuple&) {
525 GMOCK_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
526 ReturnNull_can_be_used_to_return_a_pointer_only);
527 return NULL;
528 }
529 };
530
531 // Implements the Return() action.
532 class ReturnVoidAction {
533 public:
534 // Allows Return() to be used in any void-returning function.
535 template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple &)536 static void Perform(const ArgumentTuple&) {
537 CompileAssertTypesEqual<void, Result>();
538 }
539 };
540
541 // Implements the polymorphic ReturnRef(x) action, which can be used
542 // in any function that returns a reference to the type of x,
543 // regardless of the argument types.
544 template <typename T>
545 class ReturnRefAction {
546 public:
547 // Constructs a ReturnRefAction object from the reference to be returned.
ReturnRefAction(T & ref)548 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
549
550 // This template type conversion operator allows ReturnRef(x) to be
551 // used in ANY function that returns a reference to x's type.
552 template <typename F>
553 operator Action<F>() const {
554 typedef typename Function<F>::Result Result;
555 // Asserts that the function return type is a reference. This
556 // catches the user error of using ReturnRef(x) when Return(x)
557 // should be used, and generates some helpful error message.
558 GMOCK_COMPILE_ASSERT_(internal::is_reference<Result>::value,
559 use_Return_instead_of_ReturnRef_to_return_a_value);
560 return Action<F>(new Impl<F>(ref_));
561 }
562
563 private:
564 // Implements the ReturnRef(x) action for a particular function type F.
565 template <typename F>
566 class Impl : public ActionInterface<F> {
567 public:
568 typedef typename Function<F>::Result Result;
569 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
570
Impl(T & ref)571 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
572
Perform(const ArgumentTuple &)573 virtual Result Perform(const ArgumentTuple&) {
574 return ref_;
575 }
576
577 private:
578 T& ref_;
579
580 GTEST_DISALLOW_ASSIGN_(Impl);
581 };
582
583 T& ref_;
584
585 GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
586 };
587
588 // Implements the DoDefault() action for a particular function type F.
589 template <typename F>
590 class MonomorphicDoDefaultActionImpl : public ActionInterface<F> {
591 public:
592 typedef typename Function<F>::Result Result;
593 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
594
MonomorphicDoDefaultActionImpl()595 MonomorphicDoDefaultActionImpl() : ActionInterface<F>(true) {}
596
597 // For technical reasons, DoDefault() cannot be used inside a
598 // composite action (e.g. DoAll(...)). It can only be used at the
599 // top level in an EXPECT_CALL(). If this function is called, the
600 // user must be using DoDefault() inside a composite action, and we
601 // have to generate a run-time error.
Perform(const ArgumentTuple &)602 virtual Result Perform(const ArgumentTuple&) {
603 Assert(false, __FILE__, __LINE__,
604 "You are using DoDefault() inside a composite action like "
605 "DoAll() or WithArgs(). This is not supported for technical "
606 "reasons. Please instead spell out the default action, or "
607 "assign the default action to an Action variable and use "
608 "the variable in various places.");
609 return internal::Invalid<Result>();
610 // The above statement will never be reached, but is required in
611 // order for this function to compile.
612 }
613 };
614
615 // Implements the polymorphic DoDefault() action.
616 class DoDefaultAction {
617 public:
618 // This template type conversion operator allows DoDefault() to be
619 // used in any function.
620 template <typename F>
621 operator Action<F>() const {
622 return Action<F>(new MonomorphicDoDefaultActionImpl<F>);
623 }
624 };
625
626 // Implements the Assign action to set a given pointer referent to a
627 // particular value.
628 template <typename T1, typename T2>
629 class AssignAction {
630 public:
AssignAction(T1 * ptr,T2 value)631 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
632
633 template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple &)634 void Perform(const ArgumentTuple& /* args */) const {
635 *ptr_ = value_;
636 }
637
638 private:
639 T1* const ptr_;
640 const T2 value_;
641
642 GTEST_DISALLOW_ASSIGN_(AssignAction);
643 };
644
645 #if !GTEST_OS_WINDOWS_MOBILE
646
647 // Implements the SetErrnoAndReturn action to simulate return from
648 // various system calls and libc functions.
649 template <typename T>
650 class SetErrnoAndReturnAction {
651 public:
SetErrnoAndReturnAction(int errno_value,T result)652 SetErrnoAndReturnAction(int errno_value, T result)
653 : errno_(errno_value),
654 result_(result) {}
655 template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple &)656 Result Perform(const ArgumentTuple& /* args */) const {
657 errno = errno_;
658 return result_;
659 }
660
661 private:
662 const int errno_;
663 const T result_;
664
665 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
666 };
667
668 #endif // !GTEST_OS_WINDOWS_MOBILE
669
670 // Implements the SetArgumentPointee<N>(x) action for any function
671 // whose N-th argument (0-based) is a pointer to x's type. The
672 // template parameter kIsProto is true iff type A is ProtocolMessage,
673 // proto2::Message, or a sub-class of those.
674 template <size_t N, typename A, bool kIsProto>
675 class SetArgumentPointeeAction {
676 public:
677 // Constructs an action that sets the variable pointed to by the
678 // N-th function argument to 'value'.
SetArgumentPointeeAction(const A & value)679 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
680
681 template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple & args)682 void Perform(const ArgumentTuple& args) const {
683 CompileAssertTypesEqual<void, Result>();
684 *::std::tr1::get<N>(args) = value_;
685 }
686
687 private:
688 const A value_;
689
690 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
691 };
692
693 template <size_t N, typename Proto>
694 class SetArgumentPointeeAction<N, Proto, true> {
695 public:
696 // Constructs an action that sets the variable pointed to by the
697 // N-th function argument to 'proto'. Both ProtocolMessage and
698 // proto2::Message have the CopyFrom() method, so the same
699 // implementation works for both.
SetArgumentPointeeAction(const Proto & proto)700 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
701 proto_->CopyFrom(proto);
702 }
703
704 template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple & args)705 void Perform(const ArgumentTuple& args) const {
706 CompileAssertTypesEqual<void, Result>();
707 ::std::tr1::get<N>(args)->CopyFrom(*proto_);
708 }
709
710 private:
711 const internal::linked_ptr<Proto> proto_;
712
713 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
714 };
715
716 // Implements the InvokeWithoutArgs(f) action. The template argument
717 // FunctionImpl is the implementation type of f, which can be either a
718 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
719 // Action<F> as long as f's type is compatible with F (i.e. f can be
720 // assigned to a tr1::function<F>).
721 template <typename FunctionImpl>
722 class InvokeWithoutArgsAction {
723 public:
724 // The c'tor makes a copy of function_impl (either a function
725 // pointer or a functor).
InvokeWithoutArgsAction(FunctionImpl function_impl)726 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
727 : function_impl_(function_impl) {}
728
729 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
730 // compatible with f.
731 template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple &)732 Result Perform(const ArgumentTuple&) { return function_impl_(); }
733
734 private:
735 FunctionImpl function_impl_;
736
737 GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
738 };
739
740 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
741 template <class Class, typename MethodPtr>
742 class InvokeMethodWithoutArgsAction {
743 public:
InvokeMethodWithoutArgsAction(Class * obj_ptr,MethodPtr method_ptr)744 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
745 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
746
747 template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple &)748 Result Perform(const ArgumentTuple&) const {
749 return (obj_ptr_->*method_ptr_)();
750 }
751
752 private:
753 Class* const obj_ptr_;
754 const MethodPtr method_ptr_;
755
756 GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
757 };
758
759 // Implements the IgnoreResult(action) action.
760 template <typename A>
761 class IgnoreResultAction {
762 public:
IgnoreResultAction(const A & action)763 explicit IgnoreResultAction(const A& action) : action_(action) {}
764
765 template <typename F>
766 operator Action<F>() const {
767 // Assert statement belongs here because this is the best place to verify
768 // conditions on F. It produces the clearest error messages
769 // in most compilers.
770 // Impl really belongs in this scope as a local class but can't
771 // because MSVC produces duplicate symbols in different translation units
772 // in this case. Until MS fixes that bug we put Impl into the class scope
773 // and put the typedef both here (for use in assert statement) and
774 // in the Impl class. But both definitions must be the same.
775 typedef typename internal::Function<F>::Result Result;
776
777 // Asserts at compile time that F returns void.
778 CompileAssertTypesEqual<void, Result>();
779
780 return Action<F>(new Impl<F>(action_));
781 }
782
783 private:
784 template <typename F>
785 class Impl : public ActionInterface<F> {
786 public:
787 typedef typename internal::Function<F>::Result Result;
788 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
789
Impl(const A & action)790 explicit Impl(const A& action) : action_(action) {}
791
Perform(const ArgumentTuple & args)792 virtual void Perform(const ArgumentTuple& args) {
793 // Performs the action and ignores its result.
794 action_.Perform(args);
795 }
796
797 private:
798 // Type OriginalFunction is the same as F except that its return
799 // type is IgnoredValue.
800 typedef typename internal::Function<F>::MakeResultIgnoredValue
801 OriginalFunction;
802
803 const Action<OriginalFunction> action_;
804
805 GTEST_DISALLOW_ASSIGN_(Impl);
806 };
807
808 const A action_;
809
810 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
811 };
812
813 // A ReferenceWrapper<T> object represents a reference to type T,
814 // which can be either const or not. It can be explicitly converted
815 // from, and implicitly converted to, a T&. Unlike a reference,
816 // ReferenceWrapper<T> can be copied and can survive template type
817 // inference. This is used to support by-reference arguments in the
818 // InvokeArgument<N>(...) action. The idea was from "reference
819 // wrappers" in tr1, which we don't have in our source tree yet.
820 template <typename T>
821 class ReferenceWrapper {
822 public:
823 // Constructs a ReferenceWrapper<T> object from a T&.
ReferenceWrapper(T & l_value)824 explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
825
826 // Allows a ReferenceWrapper<T> object to be implicitly converted to
827 // a T&.
828 operator T&() const { return *pointer_; }
829 private:
830 T* pointer_;
831 };
832
833 // Allows the expression ByRef(x) to be printed as a reference to x.
834 template <typename T>
PrintTo(const ReferenceWrapper<T> & ref,::std::ostream * os)835 void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
836 T& value = ref;
837 UniversalPrinter<T&>::Print(value, os);
838 }
839
840 // Does two actions sequentially. Used for implementing the DoAll(a1,
841 // a2, ...) action.
842 template <typename Action1, typename Action2>
843 class DoBothAction {
844 public:
DoBothAction(Action1 action1,Action2 action2)845 DoBothAction(Action1 action1, Action2 action2)
846 : action1_(action1), action2_(action2) {}
847
848 // This template type conversion operator allows DoAll(a1, ..., a_n)
849 // to be used in ANY function of compatible type.
850 template <typename F>
851 operator Action<F>() const {
852 return Action<F>(new Impl<F>(action1_, action2_));
853 }
854
855 private:
856 // Implements the DoAll(...) action for a particular function type F.
857 template <typename F>
858 class Impl : public ActionInterface<F> {
859 public:
860 typedef typename Function<F>::Result Result;
861 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
862 typedef typename Function<F>::MakeResultVoid VoidResult;
863
Impl(const Action<VoidResult> & action1,const Action<F> & action2)864 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
865 : action1_(action1), action2_(action2) {}
866
Perform(const ArgumentTuple & args)867 virtual Result Perform(const ArgumentTuple& args) {
868 action1_.Perform(args);
869 return action2_.Perform(args);
870 }
871
872 private:
873 const Action<VoidResult> action1_;
874 const Action<F> action2_;
875
876 GTEST_DISALLOW_ASSIGN_(Impl);
877 };
878
879 Action1 action1_;
880 Action2 action2_;
881
882 GTEST_DISALLOW_ASSIGN_(DoBothAction);
883 };
884
885 } // namespace internal
886
887 // An Unused object can be implicitly constructed from ANY value.
888 // This is handy when defining actions that ignore some or all of the
889 // mock function arguments. For example, given
890 //
891 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
892 // MOCK_METHOD3(Bar, double(int index, double x, double y));
893 //
894 // instead of
895 //
896 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
897 // return sqrt(x*x + y*y);
898 // }
899 // double DistanceToOriginWithIndex(int index, double x, double y) {
900 // return sqrt(x*x + y*y);
901 // }
902 // ...
903 // EXEPCT_CALL(mock, Foo("abc", _, _))
904 // .WillOnce(Invoke(DistanceToOriginWithLabel));
905 // EXEPCT_CALL(mock, Bar(5, _, _))
906 // .WillOnce(Invoke(DistanceToOriginWithIndex));
907 //
908 // you could write
909 //
910 // // We can declare any uninteresting argument as Unused.
911 // double DistanceToOrigin(Unused, double x, double y) {
912 // return sqrt(x*x + y*y);
913 // }
914 // ...
915 // EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
916 // EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
917 typedef internal::IgnoredValue Unused;
918
919 // This constructor allows us to turn an Action<From> object into an
920 // Action<To>, as long as To's arguments can be implicitly converted
921 // to From's and From's return type cann be implicitly converted to
922 // To's.
923 template <typename To>
924 template <typename From>
Action(const Action<From> & from)925 Action<To>::Action(const Action<From>& from)
926 : impl_(new internal::ActionAdaptor<To, From>(from)) {}
927
928 // Creates an action that returns 'value'. 'value' is passed by value
929 // instead of const reference - otherwise Return("string literal")
930 // will trigger a compiler error about using array as initializer.
931 template <typename R>
Return(R value)932 internal::ReturnAction<R> Return(R value) {
933 return internal::ReturnAction<R>(value);
934 }
935
936 // Creates an action that returns NULL.
ReturnNull()937 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
938 return MakePolymorphicAction(internal::ReturnNullAction());
939 }
940
941 // Creates an action that returns from a void function.
Return()942 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
943 return MakePolymorphicAction(internal::ReturnVoidAction());
944 }
945
946 // Creates an action that returns the reference to a variable.
947 template <typename R>
ReturnRef(R & x)948 inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
949 return internal::ReturnRefAction<R>(x);
950 }
951
952 // Creates an action that does the default action for the give mock function.
DoDefault()953 inline internal::DoDefaultAction DoDefault() {
954 return internal::DoDefaultAction();
955 }
956
957 // Creates an action that sets the variable pointed by the N-th
958 // (0-based) function argument to 'value'.
959 template <size_t N, typename T>
960 PolymorphicAction<
961 internal::SetArgumentPointeeAction<
962 N, T, internal::IsAProtocolMessage<T>::value> >
SetArgumentPointee(const T & x)963 SetArgumentPointee(const T& x) {
964 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
965 N, T, internal::IsAProtocolMessage<T>::value>(x));
966 }
967
968 // Creates an action that sets a pointer referent to a given value.
969 template <typename T1, typename T2>
Assign(T1 * ptr,T2 val)970 PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
971 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
972 }
973
974 #if !GTEST_OS_WINDOWS_MOBILE
975
976 // Creates an action that sets errno and returns the appropriate error.
977 template <typename T>
978 PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
SetErrnoAndReturn(int errval,T result)979 SetErrnoAndReturn(int errval, T result) {
980 return MakePolymorphicAction(
981 internal::SetErrnoAndReturnAction<T>(errval, result));
982 }
983
984 #endif // !GTEST_OS_WINDOWS_MOBILE
985
986 // Various overloads for InvokeWithoutArgs().
987
988 // Creates an action that invokes 'function_impl' with no argument.
989 template <typename FunctionImpl>
990 PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
InvokeWithoutArgs(FunctionImpl function_impl)991 InvokeWithoutArgs(FunctionImpl function_impl) {
992 return MakePolymorphicAction(
993 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
994 }
995
996 // Creates an action that invokes the given method on the given object
997 // with no argument.
998 template <class Class, typename MethodPtr>
999 PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
InvokeWithoutArgs(Class * obj_ptr,MethodPtr method_ptr)1000 InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
1001 return MakePolymorphicAction(
1002 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
1003 obj_ptr, method_ptr));
1004 }
1005
1006 // Creates an action that performs an_action and throws away its
1007 // result. In other words, it changes the return type of an_action to
1008 // void. an_action MUST NOT return void, or the code won't compile.
1009 template <typename A>
IgnoreResult(const A & an_action)1010 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1011 return internal::IgnoreResultAction<A>(an_action);
1012 }
1013
1014 // Creates a reference wrapper for the given L-value. If necessary,
1015 // you can explicitly specify the type of the reference. For example,
1016 // suppose 'derived' is an object of type Derived, ByRef(derived)
1017 // would wrap a Derived&. If you want to wrap a const Base& instead,
1018 // where Base is a base class of Derived, just write:
1019 //
1020 // ByRef<const Base>(derived)
1021 template <typename T>
ByRef(T & l_value)1022 inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
1023 return internal::ReferenceWrapper<T>(l_value);
1024 }
1025
1026 } // namespace testing
1027
1028 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
1029