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