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