blob: 007ad9d3606eb6b97ed5835d8db300c1599b07f0 [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_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000271
shiqiane35fdd92008-12-10 05:08:54 +0000272 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.
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_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000283
284 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
shiqiane35fdd92008-12-10 05:08:54 +0000285};
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.
296template <typename F>
297class 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.
304 Action() : impl_(NULL) {}
305
306 // Constructs an Action from its implementation.
307 explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
308
309 // Copy constructor.
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
vladloseva070cbd2009-11-18 00:09:28 +0000314 // to Func's and Func's return type can be implicitly converted to
shiqiane35fdd92008-12-10 05:08:54 +0000315 // F's.
316 template <typename Func>
317 explicit Action(const Action<Func>& action);
318
319 // Returns true iff this is the DoDefault() action.
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.)
328 Result Perform(const ArgumentTuple& args) const {
329 return impl_->Perform(args);
330 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000331
shiqiane35fdd92008-12-10 05:08:54 +0000332 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.
360template <typename Impl>
361class PolymorphicAction {
362 public:
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 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000369
shiqiane35fdd92008-12-10 05:08:54 +0000370 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
377 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
378
379 virtual Result Perform(const ArgumentTuple& args) {
380 return impl_.template Perform<Result>(args);
381 }
382
383 private:
384 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000385
386 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000387 };
388
389 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000390
391 GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
shiqiane35fdd92008-12-10 05:08:54 +0000392};
393
394// Creates an Action from its implementation and returns it. The
395// created Action object owns the implementation.
396template <typename F>
397Action<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);
408template <typename Impl>
409inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
410 return PolymorphicAction<Impl>(impl);
411}
412
413namespace internal {
414
415// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
416// and F1 are compatible.
417template <typename F1, typename F2>
418class ActionAdaptor : public ActionInterface<F1> {
419 public:
420 typedef typename internal::Function<F1>::Result Result;
421 typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
422
423 explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
424
425 virtual Result Perform(const ArgumentTuple& args) {
426 return impl_->Perform(args);
427 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000428
shiqiane35fdd92008-12-10 05:08:54 +0000429 private:
430 const internal::linked_ptr<ActionInterface<F2> > impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000431
432 GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
shiqiane35fdd92008-12-10 05:08:54 +0000433};
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.
vladloseva070cbd2009-11-18 00:09:28 +0000438//
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//
shiqiane35fdd92008-12-10 05:08:54 +0000459template <typename R>
460class 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.
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;
zhanyong.wane0d051e2009-02-19 00:33:37 +0000480 GMOCK_COMPILE_ASSERT_(
481 !internal::is_reference<Result>::value,
482 use_ReturnRef_instead_of_Return_to_return_a_reference);
shiqiane35fdd92008-12-10 05:08:54 +0000483 return Action<F>(new Impl<F>(value_));
484 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000485
shiqiane35fdd92008-12-10 05:08:54 +0000486 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
vladloseva070cbd2009-11-18 00:09:28 +0000494 // 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.
501 explicit Impl(R value)
502 : value_(::testing::internal::implicit_cast<Result>(value)) {}
shiqiane35fdd92008-12-10 05:08:54 +0000503
504 virtual Result Perform(const ArgumentTuple&) { return value_; }
505
506 private:
vladloseva070cbd2009-11-18 00:09:28 +0000507 GMOCK_COMPILE_ASSERT_(!internal::is_reference<Result>::value,
508 Result_cannot_be_a_reference_type);
509 Result value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000510
511 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000512 };
513
514 R value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000515
516 GTEST_DISALLOW_ASSIGN_(ReturnAction);
shiqiane35fdd92008-12-10 05:08:54 +0000517};
518
519// Implements the ReturnNull() action.
520class ReturnNullAction {
521 public:
522 // Allows ReturnNull() to be used in any pointer-returning function.
523 template <typename Result, typename ArgumentTuple>
524 static Result Perform(const ArgumentTuple&) {
zhanyong.wane0d051e2009-02-19 00:33:37 +0000525 GMOCK_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
526 ReturnNull_can_be_used_to_return_a_pointer_only);
shiqiane35fdd92008-12-10 05:08:54 +0000527 return NULL;
528 }
529};
530
531// Implements the Return() action.
532class ReturnVoidAction {
533 public:
534 // Allows Return() to be used in any void-returning function.
535 template <typename Result, typename 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.
544template <typename T>
545class ReturnRefAction {
546 public:
547 // Constructs a ReturnRefAction object from the reference to be returned.
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.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000558 GMOCK_COMPILE_ASSERT_(internal::is_reference<Result>::value,
559 use_Return_instead_of_ReturnRef_to_return_a_value);
shiqiane35fdd92008-12-10 05:08:54 +0000560 return Action<F>(new Impl<F>(ref_));
561 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000562
shiqiane35fdd92008-12-10 05:08:54 +0000563 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
571 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
572
573 virtual Result Perform(const ArgumentTuple&) {
574 return ref_;
575 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000576
shiqiane35fdd92008-12-10 05:08:54 +0000577 private:
578 T& ref_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000579
580 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000581 };
582
583 T& ref_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000584
585 GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
shiqiane35fdd92008-12-10 05:08:54 +0000586};
587
588// Implements the DoDefault() action for a particular function type F.
589template <typename F>
590class MonomorphicDoDefaultActionImpl : public ActionInterface<F> {
591 public:
592 typedef typename Function<F>::Result Result;
593 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
594
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.
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.
616class 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.
628template <typename T1, typename T2>
629class AssignAction {
630 public:
631 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
632
633 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000634 void Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000635 *ptr_ = value_;
636 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000637
shiqiane35fdd92008-12-10 05:08:54 +0000638 private:
639 T1* const ptr_;
640 const T2 value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000641
642 GTEST_DISALLOW_ASSIGN_(AssignAction);
shiqiane35fdd92008-12-10 05:08:54 +0000643};
644
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000645#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000646
shiqiane35fdd92008-12-10 05:08:54 +0000647// Implements the SetErrnoAndReturn action to simulate return from
648// various system calls and libc functions.
649template <typename T>
650class SetErrnoAndReturnAction {
651 public:
652 SetErrnoAndReturnAction(int errno_value, T result)
653 : errno_(errno_value),
654 result_(result) {}
655 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000656 Result Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000657 errno = errno_;
658 return result_;
659 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000660
shiqiane35fdd92008-12-10 05:08:54 +0000661 private:
662 const int errno_;
663 const T result_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000664
665 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
shiqiane35fdd92008-12-10 05:08:54 +0000666};
667
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000668#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000669
shiqiane35fdd92008-12-10 05:08:54 +0000670// 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.
674template <size_t N, typename A, bool kIsProto>
675class SetArgumentPointeeAction {
676 public:
677 // Constructs an action that sets the variable pointed to by the
678 // N-th function argument to 'value'.
679 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
680
681 template <typename Result, typename ArgumentTuple>
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_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000689
690 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
shiqiane35fdd92008-12-10 05:08:54 +0000691};
692
693template <size_t N, typename Proto>
694class 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.
700 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
701 proto_->CopyFrom(proto);
702 }
703
704 template <typename Result, typename ArgumentTuple>
705 void Perform(const ArgumentTuple& args) const {
706 CompileAssertTypesEqual<void, Result>();
707 ::std::tr1::get<N>(args)->CopyFrom(*proto_);
708 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000709
shiqiane35fdd92008-12-10 05:08:54 +0000710 private:
711 const internal::linked_ptr<Proto> proto_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000712
713 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
shiqiane35fdd92008-12-10 05:08:54 +0000714};
715
shiqiane35fdd92008-12-10 05:08:54 +0000716// 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>).
721template <typename FunctionImpl>
722class InvokeWithoutArgsAction {
723 public:
724 // The c'tor makes a copy of function_impl (either a function
725 // pointer or a functor).
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>
732 Result Perform(const ArgumentTuple&) { return function_impl_(); }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000733
shiqiane35fdd92008-12-10 05:08:54 +0000734 private:
735 FunctionImpl function_impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000736
737 GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
shiqiane35fdd92008-12-10 05:08:54 +0000738};
739
740// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
741template <class Class, typename MethodPtr>
742class InvokeMethodWithoutArgsAction {
743 public:
744 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
745 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
746
747 template <typename Result, typename ArgumentTuple>
748 Result Perform(const ArgumentTuple&) const {
749 return (obj_ptr_->*method_ptr_)();
750 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000751
shiqiane35fdd92008-12-10 05:08:54 +0000752 private:
753 Class* const obj_ptr_;
754 const MethodPtr method_ptr_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000755
756 GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
shiqiane35fdd92008-12-10 05:08:54 +0000757};
758
759// Implements the IgnoreResult(action) action.
760template <typename A>
761class IgnoreResultAction {
762 public:
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 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000782
shiqiane35fdd92008-12-10 05:08:54 +0000783 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
790 explicit Impl(const A& action) : action_(action) {}
791
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_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000804
805 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000806 };
807
808 const A action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000809
810 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
shiqiane35fdd92008-12-10 05:08:54 +0000811};
812
zhanyong.wana18423e2009-07-22 23:58:19 +0000813// 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.
820template <typename T>
821class ReferenceWrapper {
822 public:
823 // Constructs a ReferenceWrapper<T> object from a T&.
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.
834template <typename T>
835void 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.
842template <typename Action1, typename Action2>
843class DoBothAction {
844 public:
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
864 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
865 : action1_(action1), action2_(action2) {}
866
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_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000875
876 GTEST_DISALLOW_ASSIGN_(Impl);
zhanyong.wana18423e2009-07-22 23:58:19 +0000877 };
878
879 Action1 action1_;
880 Action2 action2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000881
882 GTEST_DISALLOW_ASSIGN_(DoBothAction);
zhanyong.wana18423e2009-07-22 23:58:19 +0000883};
884
shiqiane35fdd92008-12-10 05:08:54 +0000885} // 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));
917typedef 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.
923template <typename To>
924template <typename From>
925Action<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.
931template <typename R>
932internal::ReturnAction<R> Return(R value) {
933 return internal::ReturnAction<R>(value);
934}
935
936// Creates an action that returns NULL.
937inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
938 return MakePolymorphicAction(internal::ReturnNullAction());
939}
940
941// Creates an action that returns from a void function.
942inline PolymorphicAction<internal::ReturnVoidAction> Return() {
943 return MakePolymorphicAction(internal::ReturnVoidAction());
944}
945
946// Creates an action that returns the reference to a variable.
947template <typename R>
948inline 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.
953inline 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'.
959template <size_t N, typename T>
960PolymorphicAction<
961 internal::SetArgumentPointeeAction<
962 N, T, internal::IsAProtocolMessage<T>::value> >
963SetArgumentPointee(const T& x) {
964 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
965 N, T, internal::IsAProtocolMessage<T>::value>(x));
966}
967
shiqiane35fdd92008-12-10 05:08:54 +0000968// Creates an action that sets a pointer referent to a given value.
969template <typename T1, typename T2>
970PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
971 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
972}
973
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000974#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000975
shiqiane35fdd92008-12-10 05:08:54 +0000976// Creates an action that sets errno and returns the appropriate error.
977template <typename T>
978PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
979SetErrnoAndReturn(int errval, T result) {
980 return MakePolymorphicAction(
981 internal::SetErrnoAndReturnAction<T>(errval, result));
982}
983
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000984#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000985
shiqiane35fdd92008-12-10 05:08:54 +0000986// Various overloads for InvokeWithoutArgs().
987
988// Creates an action that invokes 'function_impl' with no argument.
989template <typename FunctionImpl>
990PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
991InvokeWithoutArgs(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.
998template <class Class, typename MethodPtr>
999PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
1000InvokeWithoutArgs(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.
1009template <typename A>
1010inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1011 return internal::IgnoreResultAction<A>(an_action);
1012}
1013
zhanyong.wana18423e2009-07-22 23:58:19 +00001014// 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)
1021template <typename T>
1022inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
1023 return internal::ReferenceWrapper<T>(l_value);
1024}
1025
shiqiane35fdd92008-12-10 05:08:54 +00001026} // namespace testing
1027
1028#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_