blob: d965e1084c6c8a537adccad0df9869bd57a9e310 [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>
zhanyong.wan5b5d62f2009-03-11 23:37:56 +000041
42#ifndef _WIN32_WCE
shiqiane35fdd92008-12-10 05:08:54 +000043#include <errno.h>
zhanyong.wan5b5d62f2009-03-11 23:37:56 +000044#endif
45
zhanyong.wana18423e2009-07-22 23:58:19 +000046#include <gmock/gmock-printers.h>
shiqiane35fdd92008-12-10 05:08:54 +000047#include <gmock/internal/gmock-internal-utils.h>
48#include <gmock/internal/gmock-port.h>
49
50namespace 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
61namespace internal {
62
63template <typename F>
64class MonomorphicDoDefaultActionImpl;
65
66template <typename F1, typename F2>
67class 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.
74template <typename T>
75class BuiltInDefaultValue {
76 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +000077 // This function returns true iff type T has a built-in default value.
78 static bool Exists() { return false; }
shiqiane35fdd92008-12-10 05:08:54 +000079 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.
90template <typename T>
91class BuiltInDefaultValue<const T> {
92 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +000093 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
shiqiane35fdd92008-12-10 05:08:54 +000094 static T Get() { return BuiltInDefaultValue<T>::Get(); }
95};
96
97// This partial specialization defines the default values for pointer
98// types.
99template <typename T>
100class BuiltInDefaultValue<T*> {
101 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000102 static bool Exists() { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000103 static T* Get() { return NULL; }
104};
105
106// The following specializations define the default values for
107// specific types we care about.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000108#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
shiqiane35fdd92008-12-10 05:08:54 +0000109 template <> \
110 class BuiltInDefaultValue<type> { \
111 public: \
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000112 static bool Exists() { return true; } \
shiqiane35fdd92008-12-10 05:08:54 +0000113 static type Get() { return value; } \
114 }
115
zhanyong.wane0d051e2009-02-19 00:33:37 +0000116GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000117#if GTEST_HAS_GLOBAL_STRING
zhanyong.wane0d051e2009-02-19 00:33:37 +0000118GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
shiqiane35fdd92008-12-10 05:08:54 +0000119#endif // GTEST_HAS_GLOBAL_STRING
zhanyong.wane0d051e2009-02-19 00:33:37 +0000120GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
zhanyong.wane0d051e2009-02-19 00:33:37 +0000121GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
122GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
123GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
124GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
shiqiane35fdd92008-12-10 05:08:54 +0000125
shiqiane35fdd92008-12-10 05:08:54 +0000126// 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.
zhanyong.wan95b12332009-09-25 18:55:50 +0000132#if GMOCK_WCHAR_T_IS_NATIVE_
zhanyong.wane0d051e2009-02-19 00:33:37 +0000133GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000134#endif
135
zhanyong.wane0d051e2009-02-19 00:33:37 +0000136GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
137GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
138GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
139GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
140GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
141GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
142GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
143GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
144GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
145GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
shiqiane35fdd92008-12-10 05:08:54 +0000146
zhanyong.wane0d051e2009-02-19 00:33:37 +0000147#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
shiqiane35fdd92008-12-10 05:08:54 +0000148
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);
164template <typename T>
165class DefaultValue {
166 public:
167 // Sets the default value for type T; requires T to be
168 // copy-constructable and have a public destructor.
169 static void Set(T x) {
170 delete value_;
171 value_ = new T(x);
172 }
173
174 // Unsets the default value for type T.
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.
181 static bool IsSet() { return value_ != NULL; }
182
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000183 // Returns true if T has a default return value set by the user or there
184 // exists a built-in default value.
185 static bool Exists() {
186 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
187 }
188
shiqiane35fdd92008-12-10 05:08:54 +0000189 // 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.
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.
202template <typename T>
203class DefaultValue<T&> {
204 public:
205 // Sets the default value for type T&.
206 static void Set(T& x) { // NOLINT
207 address_ = &x;
208 }
209
210 // Unsets the default value for type T&.
211 static void Clear() {
212 address_ = NULL;
213 }
214
215 // Returns true iff the user has set the default value for type T&.
216 static bool IsSet() { return address_ != NULL; }
217
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000218 // Returns true if T has a default return value set by the user or there
219 // exists a built-in default value.
220 static bool Exists() {
221 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
222 }
223
shiqiane35fdd92008-12-10 05:08:54 +0000224 // 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.
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.
237template <>
238class DefaultValue<void> {
239 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000240 static bool Exists() { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000241 static void Get() {}
242};
243
244// Points to the user-set default value for type T.
245template <typename T>
246const T* DefaultValue<T>::value_ = NULL;
247
248// Points to the user-set default value for type T&.
249template <typename T>
250T* DefaultValue<T&>::address_ = NULL;
251
252// Implement this interface to define an action for function type F.
253template <typename F>
254class ActionInterface {
255 public:
256 typedef typename internal::Function<F>::Result Result;
257 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
258
259 ActionInterface() : is_do_default_(false) {}
260
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.
270 bool IsDoDefault() const { return is_do_default_; }
271 private:
272 template <typename Function>
273 friend class internal::MonomorphicDoDefaultActionImpl;
274
275 // This private constructor is reserved for implementing
276 // DoDefault(), the default action for a given mock function.
277 explicit ActionInterface(bool is_do_default)
278 : is_do_default_(is_do_default) {}
279
280 // True iff this action is DoDefault().
281 const bool is_do_default_;
282};
283
284// An Action<F> is a copyable and IMMUTABLE (except by assignment)
285// object that represents an action to be taken when a mock function
286// of type F is called. The implementation of Action<T> is just a
287// linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
288// Don't inherit from Action!
289//
290// You can view an object implementing ActionInterface<F> as a
291// concrete action (including its current state), and an Action<F>
292// object as a handle to it.
293template <typename F>
294class Action {
295 public:
296 typedef typename internal::Function<F>::Result Result;
297 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
298
299 // Constructs a null Action. Needed for storing Action objects in
300 // STL containers.
301 Action() : impl_(NULL) {}
302
303 // Constructs an Action from its implementation.
304 explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
305
306 // Copy constructor.
307 Action(const Action& action) : impl_(action.impl_) {}
308
309 // This constructor allows us to turn an Action<Func> object into an
310 // Action<F>, as long as F's arguments can be implicitly converted
vladloseva070cbd2009-11-18 00:09:28 +0000311 // to Func's and Func's return type can be implicitly converted to
shiqiane35fdd92008-12-10 05:08:54 +0000312 // F's.
313 template <typename Func>
314 explicit Action(const Action<Func>& action);
315
316 // Returns true iff this is the DoDefault() action.
317 bool IsDoDefault() const { return impl_->IsDoDefault(); }
318
319 // Performs the action. Note that this method is const even though
320 // the corresponding method in ActionInterface is not. The reason
321 // is that a const Action<F> means that it cannot be re-bound to
322 // another concrete action, not that the concrete action it binds to
323 // cannot change state. (Think of the difference between a const
324 // pointer and a pointer to const.)
325 Result Perform(const ArgumentTuple& args) const {
326 return impl_->Perform(args);
327 }
328 private:
329 template <typename F1, typename F2>
330 friend class internal::ActionAdaptor;
331
332 internal::linked_ptr<ActionInterface<F> > impl_;
333};
334
335// The PolymorphicAction class template makes it easy to implement a
336// polymorphic action (i.e. an action that can be used in mock
337// functions of than one type, e.g. Return()).
338//
339// To define a polymorphic action, a user first provides a COPYABLE
340// implementation class that has a Perform() method template:
341//
342// class FooAction {
343// public:
344// template <typename Result, typename ArgumentTuple>
345// Result Perform(const ArgumentTuple& args) const {
346// // Processes the arguments and returns a result, using
347// // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
348// }
349// ...
350// };
351//
352// Then the user creates the polymorphic action using
353// MakePolymorphicAction(object) where object has type FooAction. See
354// the definition of Return(void) and SetArgumentPointee<N>(value) for
355// complete examples.
356template <typename Impl>
357class PolymorphicAction {
358 public:
359 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
360
361 template <typename F>
362 operator Action<F>() const {
363 return Action<F>(new MonomorphicImpl<F>(impl_));
364 }
365 private:
366 template <typename F>
367 class MonomorphicImpl : public ActionInterface<F> {
368 public:
369 typedef typename internal::Function<F>::Result Result;
370 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
371
372 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
373
374 virtual Result Perform(const ArgumentTuple& args) {
375 return impl_.template Perform<Result>(args);
376 }
377
378 private:
379 Impl impl_;
380 };
381
382 Impl impl_;
383};
384
385// Creates an Action from its implementation and returns it. The
386// created Action object owns the implementation.
387template <typename F>
388Action<F> MakeAction(ActionInterface<F>* impl) {
389 return Action<F>(impl);
390}
391
392// Creates a polymorphic action from its implementation. This is
393// easier to use than the PolymorphicAction<Impl> constructor as it
394// doesn't require you to explicitly write the template argument, e.g.
395//
396// MakePolymorphicAction(foo);
397// vs
398// PolymorphicAction<TypeOfFoo>(foo);
399template <typename Impl>
400inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
401 return PolymorphicAction<Impl>(impl);
402}
403
404namespace internal {
405
406// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
407// and F1 are compatible.
408template <typename F1, typename F2>
409class ActionAdaptor : public ActionInterface<F1> {
410 public:
411 typedef typename internal::Function<F1>::Result Result;
412 typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
413
414 explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
415
416 virtual Result Perform(const ArgumentTuple& args) {
417 return impl_->Perform(args);
418 }
419 private:
420 const internal::linked_ptr<ActionInterface<F2> > impl_;
421};
422
423// Implements the polymorphic Return(x) action, which can be used in
424// any function that returns the type of x, regardless of the argument
425// types.
vladloseva070cbd2009-11-18 00:09:28 +0000426//
427// Note: The value passed into Return must be converted into
428// Function<F>::Result when this action is cast to Action<F> rather than
429// when that action is performed. This is important in scenarios like
430//
431// MOCK_METHOD1(Method, T(U));
432// ...
433// {
434// Foo foo;
435// X x(&foo);
436// EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
437// }
438//
439// In the example above the variable x holds reference to foo which leaves
440// scope and gets destroyed. If copying X just copies a reference to foo,
441// that copy will be left with a hanging reference. If conversion to T
442// makes a copy of foo, the above code is safe. To support that scenario, we
443// need to make sure that the type conversion happens inside the EXPECT_CALL
444// statement, and conversion of the result of Return to Action<T(U)> is a
445// good place for that.
446//
shiqiane35fdd92008-12-10 05:08:54 +0000447template <typename R>
448class ReturnAction {
449 public:
450 // Constructs a ReturnAction object from the value to be returned.
451 // 'value' is passed by value instead of by const reference in order
452 // to allow Return("string literal") to compile.
453 explicit ReturnAction(R value) : value_(value) {}
454
455 // This template type conversion operator allows Return(x) to be
456 // used in ANY function that returns x's type.
457 template <typename F>
458 operator Action<F>() const {
459 // Assert statement belongs here because this is the best place to verify
460 // conditions on F. It produces the clearest error messages
461 // in most compilers.
462 // Impl really belongs in this scope as a local class but can't
463 // because MSVC produces duplicate symbols in different translation units
464 // in this case. Until MS fixes that bug we put Impl into the class scope
465 // and put the typedef both here (for use in assert statement) and
466 // in the Impl class. But both definitions must be the same.
467 typedef typename Function<F>::Result Result;
zhanyong.wane0d051e2009-02-19 00:33:37 +0000468 GMOCK_COMPILE_ASSERT_(
469 !internal::is_reference<Result>::value,
470 use_ReturnRef_instead_of_Return_to_return_a_reference);
shiqiane35fdd92008-12-10 05:08:54 +0000471 return Action<F>(new Impl<F>(value_));
472 }
473 private:
474 // Implements the Return(x) action for a particular function type F.
475 template <typename F>
476 class Impl : public ActionInterface<F> {
477 public:
478 typedef typename Function<F>::Result Result;
479 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
480
vladloseva070cbd2009-11-18 00:09:28 +0000481 // The implicit cast is necessary when Result has more than one
482 // single-argument constructor (e.g. Result is std::vector<int>) and R
483 // has a type conversion operator template. In that case, value_(value)
484 // won't compile as the compiler doesn't known which constructor of
485 // Result to call. implicit_cast forces the compiler to convert R to
486 // Result without considering explicit constructors, thus resolving the
487 // ambiguity. value_ is then initialized using its copy constructor.
488 explicit Impl(R value)
489 : value_(::testing::internal::implicit_cast<Result>(value)) {}
shiqiane35fdd92008-12-10 05:08:54 +0000490
491 virtual Result Perform(const ArgumentTuple&) { return value_; }
492
493 private:
vladloseva070cbd2009-11-18 00:09:28 +0000494 GMOCK_COMPILE_ASSERT_(!internal::is_reference<Result>::value,
495 Result_cannot_be_a_reference_type);
496 Result value_;
shiqiane35fdd92008-12-10 05:08:54 +0000497 };
498
499 R value_;
500};
501
502// Implements the ReturnNull() action.
503class ReturnNullAction {
504 public:
505 // Allows ReturnNull() to be used in any pointer-returning function.
506 template <typename Result, typename ArgumentTuple>
507 static Result Perform(const ArgumentTuple&) {
zhanyong.wane0d051e2009-02-19 00:33:37 +0000508 GMOCK_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
509 ReturnNull_can_be_used_to_return_a_pointer_only);
shiqiane35fdd92008-12-10 05:08:54 +0000510 return NULL;
511 }
512};
513
514// Implements the Return() action.
515class ReturnVoidAction {
516 public:
517 // Allows Return() to be used in any void-returning function.
518 template <typename Result, typename ArgumentTuple>
519 static void Perform(const ArgumentTuple&) {
520 CompileAssertTypesEqual<void, Result>();
521 }
522};
523
524// Implements the polymorphic ReturnRef(x) action, which can be used
525// in any function that returns a reference to the type of x,
526// regardless of the argument types.
527template <typename T>
528class ReturnRefAction {
529 public:
530 // Constructs a ReturnRefAction object from the reference to be returned.
531 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
532
533 // This template type conversion operator allows ReturnRef(x) to be
534 // used in ANY function that returns a reference to x's type.
535 template <typename F>
536 operator Action<F>() const {
537 typedef typename Function<F>::Result Result;
538 // Asserts that the function return type is a reference. This
539 // catches the user error of using ReturnRef(x) when Return(x)
540 // should be used, and generates some helpful error message.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000541 GMOCK_COMPILE_ASSERT_(internal::is_reference<Result>::value,
542 use_Return_instead_of_ReturnRef_to_return_a_value);
shiqiane35fdd92008-12-10 05:08:54 +0000543 return Action<F>(new Impl<F>(ref_));
544 }
545 private:
546 // Implements the ReturnRef(x) action for a particular function type F.
547 template <typename F>
548 class Impl : public ActionInterface<F> {
549 public:
550 typedef typename Function<F>::Result Result;
551 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
552
553 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
554
555 virtual Result Perform(const ArgumentTuple&) {
556 return ref_;
557 }
558 private:
559 T& ref_;
560 };
561
562 T& ref_;
563};
564
565// Implements the DoDefault() action for a particular function type F.
566template <typename F>
567class MonomorphicDoDefaultActionImpl : public ActionInterface<F> {
568 public:
569 typedef typename Function<F>::Result Result;
570 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
571
572 MonomorphicDoDefaultActionImpl() : ActionInterface<F>(true) {}
573
574 // For technical reasons, DoDefault() cannot be used inside a
575 // composite action (e.g. DoAll(...)). It can only be used at the
576 // top level in an EXPECT_CALL(). If this function is called, the
577 // user must be using DoDefault() inside a composite action, and we
578 // have to generate a run-time error.
579 virtual Result Perform(const ArgumentTuple&) {
580 Assert(false, __FILE__, __LINE__,
581 "You are using DoDefault() inside a composite action like "
582 "DoAll() or WithArgs(). This is not supported for technical "
583 "reasons. Please instead spell out the default action, or "
584 "assign the default action to an Action variable and use "
585 "the variable in various places.");
586 return internal::Invalid<Result>();
587 // The above statement will never be reached, but is required in
588 // order for this function to compile.
589 }
590};
591
592// Implements the polymorphic DoDefault() action.
593class DoDefaultAction {
594 public:
595 // This template type conversion operator allows DoDefault() to be
596 // used in any function.
597 template <typename F>
598 operator Action<F>() const {
599 return Action<F>(new MonomorphicDoDefaultActionImpl<F>);
600 }
601};
602
603// Implements the Assign action to set a given pointer referent to a
604// particular value.
605template <typename T1, typename T2>
606class AssignAction {
607 public:
608 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
609
610 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000611 void Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000612 *ptr_ = value_;
613 }
614 private:
615 T1* const ptr_;
616 const T2 value_;
617};
618
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000619#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000620
shiqiane35fdd92008-12-10 05:08:54 +0000621// Implements the SetErrnoAndReturn action to simulate return from
622// various system calls and libc functions.
623template <typename T>
624class SetErrnoAndReturnAction {
625 public:
626 SetErrnoAndReturnAction(int errno_value, T result)
627 : errno_(errno_value),
628 result_(result) {}
629 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000630 Result Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000631 errno = errno_;
632 return result_;
633 }
634 private:
635 const int errno_;
636 const T result_;
637};
638
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000639#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000640
shiqiane35fdd92008-12-10 05:08:54 +0000641// Implements the SetArgumentPointee<N>(x) action for any function
642// whose N-th argument (0-based) is a pointer to x's type. The
643// template parameter kIsProto is true iff type A is ProtocolMessage,
644// proto2::Message, or a sub-class of those.
645template <size_t N, typename A, bool kIsProto>
646class SetArgumentPointeeAction {
647 public:
648 // Constructs an action that sets the variable pointed to by the
649 // N-th function argument to 'value'.
650 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
651
652 template <typename Result, typename ArgumentTuple>
653 void Perform(const ArgumentTuple& args) const {
654 CompileAssertTypesEqual<void, Result>();
655 *::std::tr1::get<N>(args) = value_;
656 }
657
658 private:
659 const A value_;
660};
661
662template <size_t N, typename Proto>
663class SetArgumentPointeeAction<N, Proto, true> {
664 public:
665 // Constructs an action that sets the variable pointed to by the
666 // N-th function argument to 'proto'. Both ProtocolMessage and
667 // proto2::Message have the CopyFrom() method, so the same
668 // implementation works for both.
669 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
670 proto_->CopyFrom(proto);
671 }
672
673 template <typename Result, typename ArgumentTuple>
674 void Perform(const ArgumentTuple& args) const {
675 CompileAssertTypesEqual<void, Result>();
676 ::std::tr1::get<N>(args)->CopyFrom(*proto_);
677 }
678 private:
679 const internal::linked_ptr<Proto> proto_;
680};
681
shiqiane35fdd92008-12-10 05:08:54 +0000682// Implements the InvokeWithoutArgs(f) action. The template argument
683// FunctionImpl is the implementation type of f, which can be either a
684// function pointer or a functor. InvokeWithoutArgs(f) can be used as an
685// Action<F> as long as f's type is compatible with F (i.e. f can be
686// assigned to a tr1::function<F>).
687template <typename FunctionImpl>
688class InvokeWithoutArgsAction {
689 public:
690 // The c'tor makes a copy of function_impl (either a function
691 // pointer or a functor).
692 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
693 : function_impl_(function_impl) {}
694
695 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
696 // compatible with f.
697 template <typename Result, typename ArgumentTuple>
698 Result Perform(const ArgumentTuple&) { return function_impl_(); }
699 private:
700 FunctionImpl function_impl_;
701};
702
703// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
704template <class Class, typename MethodPtr>
705class InvokeMethodWithoutArgsAction {
706 public:
707 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
708 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
709
710 template <typename Result, typename ArgumentTuple>
711 Result Perform(const ArgumentTuple&) const {
712 return (obj_ptr_->*method_ptr_)();
713 }
714 private:
715 Class* const obj_ptr_;
716 const MethodPtr method_ptr_;
717};
718
719// Implements the IgnoreResult(action) action.
720template <typename A>
721class IgnoreResultAction {
722 public:
723 explicit IgnoreResultAction(const A& action) : action_(action) {}
724
725 template <typename F>
726 operator Action<F>() const {
727 // Assert statement belongs here because this is the best place to verify
728 // conditions on F. It produces the clearest error messages
729 // in most compilers.
730 // Impl really belongs in this scope as a local class but can't
731 // because MSVC produces duplicate symbols in different translation units
732 // in this case. Until MS fixes that bug we put Impl into the class scope
733 // and put the typedef both here (for use in assert statement) and
734 // in the Impl class. But both definitions must be the same.
735 typedef typename internal::Function<F>::Result Result;
736
737 // Asserts at compile time that F returns void.
738 CompileAssertTypesEqual<void, Result>();
739
740 return Action<F>(new Impl<F>(action_));
741 }
742 private:
743 template <typename F>
744 class Impl : public ActionInterface<F> {
745 public:
746 typedef typename internal::Function<F>::Result Result;
747 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
748
749 explicit Impl(const A& action) : action_(action) {}
750
751 virtual void Perform(const ArgumentTuple& args) {
752 // Performs the action and ignores its result.
753 action_.Perform(args);
754 }
755
756 private:
757 // Type OriginalFunction is the same as F except that its return
758 // type is IgnoredValue.
759 typedef typename internal::Function<F>::MakeResultIgnoredValue
760 OriginalFunction;
761
762 const Action<OriginalFunction> action_;
763 };
764
765 const A action_;
766};
767
zhanyong.wana18423e2009-07-22 23:58:19 +0000768// A ReferenceWrapper<T> object represents a reference to type T,
769// which can be either const or not. It can be explicitly converted
770// from, and implicitly converted to, a T&. Unlike a reference,
771// ReferenceWrapper<T> can be copied and can survive template type
772// inference. This is used to support by-reference arguments in the
773// InvokeArgument<N>(...) action. The idea was from "reference
774// wrappers" in tr1, which we don't have in our source tree yet.
775template <typename T>
776class ReferenceWrapper {
777 public:
778 // Constructs a ReferenceWrapper<T> object from a T&.
779 explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
780
781 // Allows a ReferenceWrapper<T> object to be implicitly converted to
782 // a T&.
783 operator T&() const { return *pointer_; }
784 private:
785 T* pointer_;
786};
787
788// Allows the expression ByRef(x) to be printed as a reference to x.
789template <typename T>
790void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
791 T& value = ref;
792 UniversalPrinter<T&>::Print(value, os);
793}
794
795// Does two actions sequentially. Used for implementing the DoAll(a1,
796// a2, ...) action.
797template <typename Action1, typename Action2>
798class DoBothAction {
799 public:
800 DoBothAction(Action1 action1, Action2 action2)
801 : action1_(action1), action2_(action2) {}
802
803 // This template type conversion operator allows DoAll(a1, ..., a_n)
804 // to be used in ANY function of compatible type.
805 template <typename F>
806 operator Action<F>() const {
807 return Action<F>(new Impl<F>(action1_, action2_));
808 }
809
810 private:
811 // Implements the DoAll(...) action for a particular function type F.
812 template <typename F>
813 class Impl : public ActionInterface<F> {
814 public:
815 typedef typename Function<F>::Result Result;
816 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
817 typedef typename Function<F>::MakeResultVoid VoidResult;
818
819 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
820 : action1_(action1), action2_(action2) {}
821
822 virtual Result Perform(const ArgumentTuple& args) {
823 action1_.Perform(args);
824 return action2_.Perform(args);
825 }
826
827 private:
828 const Action<VoidResult> action1_;
829 const Action<F> action2_;
830 };
831
832 Action1 action1_;
833 Action2 action2_;
834};
835
shiqiane35fdd92008-12-10 05:08:54 +0000836} // namespace internal
837
838// An Unused object can be implicitly constructed from ANY value.
839// This is handy when defining actions that ignore some or all of the
840// mock function arguments. For example, given
841//
842// MOCK_METHOD3(Foo, double(const string& label, double x, double y));
843// MOCK_METHOD3(Bar, double(int index, double x, double y));
844//
845// instead of
846//
847// double DistanceToOriginWithLabel(const string& label, double x, double y) {
848// return sqrt(x*x + y*y);
849// }
850// double DistanceToOriginWithIndex(int index, double x, double y) {
851// return sqrt(x*x + y*y);
852// }
853// ...
854// EXEPCT_CALL(mock, Foo("abc", _, _))
855// .WillOnce(Invoke(DistanceToOriginWithLabel));
856// EXEPCT_CALL(mock, Bar(5, _, _))
857// .WillOnce(Invoke(DistanceToOriginWithIndex));
858//
859// you could write
860//
861// // We can declare any uninteresting argument as Unused.
862// double DistanceToOrigin(Unused, double x, double y) {
863// return sqrt(x*x + y*y);
864// }
865// ...
866// EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
867// EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
868typedef internal::IgnoredValue Unused;
869
870// This constructor allows us to turn an Action<From> object into an
871// Action<To>, as long as To's arguments can be implicitly converted
872// to From's and From's return type cann be implicitly converted to
873// To's.
874template <typename To>
875template <typename From>
876Action<To>::Action(const Action<From>& from)
877 : impl_(new internal::ActionAdaptor<To, From>(from)) {}
878
879// Creates an action that returns 'value'. 'value' is passed by value
880// instead of const reference - otherwise Return("string literal")
881// will trigger a compiler error about using array as initializer.
882template <typename R>
883internal::ReturnAction<R> Return(R value) {
884 return internal::ReturnAction<R>(value);
885}
886
887// Creates an action that returns NULL.
888inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
889 return MakePolymorphicAction(internal::ReturnNullAction());
890}
891
892// Creates an action that returns from a void function.
893inline PolymorphicAction<internal::ReturnVoidAction> Return() {
894 return MakePolymorphicAction(internal::ReturnVoidAction());
895}
896
897// Creates an action that returns the reference to a variable.
898template <typename R>
899inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
900 return internal::ReturnRefAction<R>(x);
901}
902
903// Creates an action that does the default action for the give mock function.
904inline internal::DoDefaultAction DoDefault() {
905 return internal::DoDefaultAction();
906}
907
908// Creates an action that sets the variable pointed by the N-th
909// (0-based) function argument to 'value'.
910template <size_t N, typename T>
911PolymorphicAction<
912 internal::SetArgumentPointeeAction<
913 N, T, internal::IsAProtocolMessage<T>::value> >
914SetArgumentPointee(const T& x) {
915 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
916 N, T, internal::IsAProtocolMessage<T>::value>(x));
917}
918
shiqiane35fdd92008-12-10 05:08:54 +0000919// Creates an action that sets a pointer referent to a given value.
920template <typename T1, typename T2>
921PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
922 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
923}
924
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000925#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000926
shiqiane35fdd92008-12-10 05:08:54 +0000927// Creates an action that sets errno and returns the appropriate error.
928template <typename T>
929PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
930SetErrnoAndReturn(int errval, T result) {
931 return MakePolymorphicAction(
932 internal::SetErrnoAndReturnAction<T>(errval, result));
933}
934
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000935#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000936
shiqiane35fdd92008-12-10 05:08:54 +0000937// Various overloads for InvokeWithoutArgs().
938
939// Creates an action that invokes 'function_impl' with no argument.
940template <typename FunctionImpl>
941PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
942InvokeWithoutArgs(FunctionImpl function_impl) {
943 return MakePolymorphicAction(
944 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
945}
946
947// Creates an action that invokes the given method on the given object
948// with no argument.
949template <class Class, typename MethodPtr>
950PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
951InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
952 return MakePolymorphicAction(
953 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
954 obj_ptr, method_ptr));
955}
956
957// Creates an action that performs an_action and throws away its
958// result. In other words, it changes the return type of an_action to
959// void. an_action MUST NOT return void, or the code won't compile.
960template <typename A>
961inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
962 return internal::IgnoreResultAction<A>(an_action);
963}
964
zhanyong.wana18423e2009-07-22 23:58:19 +0000965// Creates a reference wrapper for the given L-value. If necessary,
966// you can explicitly specify the type of the reference. For example,
967// suppose 'derived' is an object of type Derived, ByRef(derived)
968// would wrap a Derived&. If you want to wrap a const Base& instead,
969// where Base is a base class of Derived, just write:
970//
971// ByRef<const Base>(derived)
972template <typename T>
973inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
974 return internal::ReferenceWrapper<T>(l_value);
975}
976
shiqiane35fdd92008-12-10 05:08:54 +0000977} // namespace testing
978
979#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_