blob: 214b2912c2f8d40f0270fcebd7f371d08ec4e946 [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
120#if GTEST_HAS_STD_STRING
zhanyong.wane0d051e2009-02-19 00:33:37 +0000121GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
shiqiane35fdd92008-12-10 05:08:54 +0000122#endif // GTEST_HAS_STD_STRING
zhanyong.wane0d051e2009-02-19 00:33:37 +0000123GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
124GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
125GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
126GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
shiqiane35fdd92008-12-10 05:08:54 +0000127
shiqiane35fdd92008-12-10 05:08:54 +0000128// There's no need for a default action for signed wchar_t, as that
129// type is the same as wchar_t for gcc, and invalid for MSVC.
130//
131// There's also no need for a default action for unsigned wchar_t, as
132// that type is the same as unsigned int for gcc, and invalid for
133// MSVC.
zhanyong.wan95b12332009-09-25 18:55:50 +0000134#if GMOCK_WCHAR_T_IS_NATIVE_
zhanyong.wane0d051e2009-02-19 00:33:37 +0000135GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000136#endif
137
zhanyong.wane0d051e2009-02-19 00:33:37 +0000138GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
139GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
140GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
141GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
142GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
143GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
144GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
145GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
146GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
147GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
shiqiane35fdd92008-12-10 05:08:54 +0000148
zhanyong.wane0d051e2009-02-19 00:33:37 +0000149#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
shiqiane35fdd92008-12-10 05:08:54 +0000150
151} // namespace internal
152
153// When an unexpected function call is encountered, Google Mock will
154// let it return a default value if the user has specified one for its
155// return type, or if the return type has a built-in default value;
156// otherwise Google Mock won't know what value to return and will have
157// to abort the process.
158//
159// The DefaultValue<T> class allows a user to specify the
160// default value for a type T that is both copyable and publicly
161// destructible (i.e. anything that can be used as a function return
162// type). The usage is:
163//
164// // Sets the default value for type T to be foo.
165// DefaultValue<T>::Set(foo);
166template <typename T>
167class DefaultValue {
168 public:
169 // Sets the default value for type T; requires T to be
170 // copy-constructable and have a public destructor.
171 static void Set(T x) {
172 delete value_;
173 value_ = new T(x);
174 }
175
176 // Unsets the default value for type T.
177 static void Clear() {
178 delete value_;
179 value_ = NULL;
180 }
181
182 // Returns true iff the user has set the default value for type T.
183 static bool IsSet() { return value_ != NULL; }
184
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000185 // Returns true if T has a default return value set by the user or there
186 // exists a built-in default value.
187 static bool Exists() {
188 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
189 }
190
shiqiane35fdd92008-12-10 05:08:54 +0000191 // Returns the default value for type T if the user has set one;
192 // otherwise returns the built-in default value if there is one;
193 // otherwise aborts the process.
194 static T Get() {
195 return value_ == NULL ?
196 internal::BuiltInDefaultValue<T>::Get() : *value_;
197 }
198 private:
199 static const T* value_;
200};
201
202// This partial specialization allows a user to set default values for
203// reference types.
204template <typename T>
205class DefaultValue<T&> {
206 public:
207 // Sets the default value for type T&.
208 static void Set(T& x) { // NOLINT
209 address_ = &x;
210 }
211
212 // Unsets the default value for type T&.
213 static void Clear() {
214 address_ = NULL;
215 }
216
217 // Returns true iff the user has set the default value for type T&.
218 static bool IsSet() { return address_ != NULL; }
219
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000220 // Returns true if T has a default return value set by the user or there
221 // exists a built-in default value.
222 static bool Exists() {
223 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
224 }
225
shiqiane35fdd92008-12-10 05:08:54 +0000226 // Returns the default value for type T& if the user has set one;
227 // otherwise returns the built-in default value if there is one;
228 // otherwise aborts the process.
229 static T& Get() {
230 return address_ == NULL ?
231 internal::BuiltInDefaultValue<T&>::Get() : *address_;
232 }
233 private:
234 static T* address_;
235};
236
237// This specialization allows DefaultValue<void>::Get() to
238// compile.
239template <>
240class DefaultValue<void> {
241 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000242 static bool Exists() { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000243 static void Get() {}
244};
245
246// Points to the user-set default value for type T.
247template <typename T>
248const T* DefaultValue<T>::value_ = NULL;
249
250// Points to the user-set default value for type T&.
251template <typename T>
252T* DefaultValue<T&>::address_ = NULL;
253
254// Implement this interface to define an action for function type F.
255template <typename F>
256class ActionInterface {
257 public:
258 typedef typename internal::Function<F>::Result Result;
259 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
260
261 ActionInterface() : is_do_default_(false) {}
262
263 virtual ~ActionInterface() {}
264
265 // Performs the action. This method is not const, as in general an
266 // action can have side effects and be stateful. For example, a
267 // get-the-next-element-from-the-collection action will need to
268 // remember the current element.
269 virtual Result Perform(const ArgumentTuple& args) = 0;
270
271 // Returns true iff this is the DoDefault() action.
272 bool IsDoDefault() const { return is_do_default_; }
273 private:
274 template <typename Function>
275 friend class internal::MonomorphicDoDefaultActionImpl;
276
277 // This private constructor is reserved for implementing
278 // DoDefault(), the default action for a given mock function.
279 explicit ActionInterface(bool is_do_default)
280 : is_do_default_(is_do_default) {}
281
282 // True iff this action is DoDefault().
283 const bool is_do_default_;
284};
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 }
330 private:
331 template <typename F1, typename F2>
332 friend class internal::ActionAdaptor;
333
334 internal::linked_ptr<ActionInterface<F> > impl_;
335};
336
337// The PolymorphicAction class template makes it easy to implement a
338// polymorphic action (i.e. an action that can be used in mock
339// functions of than one type, e.g. Return()).
340//
341// To define a polymorphic action, a user first provides a COPYABLE
342// implementation class that has a Perform() method template:
343//
344// class FooAction {
345// public:
346// template <typename Result, typename ArgumentTuple>
347// Result Perform(const ArgumentTuple& args) const {
348// // Processes the arguments and returns a result, using
349// // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
350// }
351// ...
352// };
353//
354// Then the user creates the polymorphic action using
355// MakePolymorphicAction(object) where object has type FooAction. See
356// the definition of Return(void) and SetArgumentPointee<N>(value) for
357// complete examples.
358template <typename Impl>
359class PolymorphicAction {
360 public:
361 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
362
363 template <typename F>
364 operator Action<F>() const {
365 return Action<F>(new MonomorphicImpl<F>(impl_));
366 }
367 private:
368 template <typename F>
369 class MonomorphicImpl : public ActionInterface<F> {
370 public:
371 typedef typename internal::Function<F>::Result Result;
372 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
373
374 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
375
376 virtual Result Perform(const ArgumentTuple& args) {
377 return impl_.template Perform<Result>(args);
378 }
379
380 private:
381 Impl impl_;
382 };
383
384 Impl impl_;
385};
386
387// Creates an Action from its implementation and returns it. The
388// created Action object owns the implementation.
389template <typename F>
390Action<F> MakeAction(ActionInterface<F>* impl) {
391 return Action<F>(impl);
392}
393
394// Creates a polymorphic action from its implementation. This is
395// easier to use than the PolymorphicAction<Impl> constructor as it
396// doesn't require you to explicitly write the template argument, e.g.
397//
398// MakePolymorphicAction(foo);
399// vs
400// PolymorphicAction<TypeOfFoo>(foo);
401template <typename Impl>
402inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
403 return PolymorphicAction<Impl>(impl);
404}
405
406namespace internal {
407
408// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
409// and F1 are compatible.
410template <typename F1, typename F2>
411class ActionAdaptor : public ActionInterface<F1> {
412 public:
413 typedef typename internal::Function<F1>::Result Result;
414 typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
415
416 explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
417
418 virtual Result Perform(const ArgumentTuple& args) {
419 return impl_->Perform(args);
420 }
421 private:
422 const internal::linked_ptr<ActionInterface<F2> > impl_;
423};
424
425// Implements the polymorphic Return(x) action, which can be used in
426// any function that returns the type of x, regardless of the argument
427// types.
vladloseva070cbd2009-11-18 00:09:28 +0000428//
429// Note: The value passed into Return must be converted into
430// Function<F>::Result when this action is cast to Action<F> rather than
431// when that action is performed. This is important in scenarios like
432//
433// MOCK_METHOD1(Method, T(U));
434// ...
435// {
436// Foo foo;
437// X x(&foo);
438// EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
439// }
440//
441// In the example above the variable x holds reference to foo which leaves
442// scope and gets destroyed. If copying X just copies a reference to foo,
443// that copy will be left with a hanging reference. If conversion to T
444// makes a copy of foo, the above code is safe. To support that scenario, we
445// need to make sure that the type conversion happens inside the EXPECT_CALL
446// statement, and conversion of the result of Return to Action<T(U)> is a
447// good place for that.
448//
shiqiane35fdd92008-12-10 05:08:54 +0000449template <typename R>
450class ReturnAction {
451 public:
452 // Constructs a ReturnAction object from the value to be returned.
453 // 'value' is passed by value instead of by const reference in order
454 // to allow Return("string literal") to compile.
455 explicit ReturnAction(R value) : value_(value) {}
456
457 // This template type conversion operator allows Return(x) to be
458 // used in ANY function that returns x's type.
459 template <typename F>
460 operator Action<F>() const {
461 // Assert statement belongs here because this is the best place to verify
462 // conditions on F. It produces the clearest error messages
463 // in most compilers.
464 // Impl really belongs in this scope as a local class but can't
465 // because MSVC produces duplicate symbols in different translation units
466 // in this case. Until MS fixes that bug we put Impl into the class scope
467 // and put the typedef both here (for use in assert statement) and
468 // in the Impl class. But both definitions must be the same.
469 typedef typename Function<F>::Result Result;
zhanyong.wane0d051e2009-02-19 00:33:37 +0000470 GMOCK_COMPILE_ASSERT_(
471 !internal::is_reference<Result>::value,
472 use_ReturnRef_instead_of_Return_to_return_a_reference);
shiqiane35fdd92008-12-10 05:08:54 +0000473 return Action<F>(new Impl<F>(value_));
474 }
475 private:
476 // Implements the Return(x) action for a particular function type F.
477 template <typename F>
478 class Impl : public ActionInterface<F> {
479 public:
480 typedef typename Function<F>::Result Result;
481 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
482
vladloseva070cbd2009-11-18 00:09:28 +0000483 // The implicit cast is necessary when Result has more than one
484 // single-argument constructor (e.g. Result is std::vector<int>) and R
485 // has a type conversion operator template. In that case, value_(value)
486 // won't compile as the compiler doesn't known which constructor of
487 // Result to call. implicit_cast forces the compiler to convert R to
488 // Result without considering explicit constructors, thus resolving the
489 // ambiguity. value_ is then initialized using its copy constructor.
490 explicit Impl(R value)
491 : value_(::testing::internal::implicit_cast<Result>(value)) {}
shiqiane35fdd92008-12-10 05:08:54 +0000492
493 virtual Result Perform(const ArgumentTuple&) { return value_; }
494
495 private:
vladloseva070cbd2009-11-18 00:09:28 +0000496 GMOCK_COMPILE_ASSERT_(!internal::is_reference<Result>::value,
497 Result_cannot_be_a_reference_type);
498 Result value_;
shiqiane35fdd92008-12-10 05:08:54 +0000499 };
500
501 R value_;
502};
503
504// Implements the ReturnNull() action.
505class ReturnNullAction {
506 public:
507 // Allows ReturnNull() to be used in any pointer-returning function.
508 template <typename Result, typename ArgumentTuple>
509 static Result Perform(const ArgumentTuple&) {
zhanyong.wane0d051e2009-02-19 00:33:37 +0000510 GMOCK_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
511 ReturnNull_can_be_used_to_return_a_pointer_only);
shiqiane35fdd92008-12-10 05:08:54 +0000512 return NULL;
513 }
514};
515
516// Implements the Return() action.
517class ReturnVoidAction {
518 public:
519 // Allows Return() to be used in any void-returning function.
520 template <typename Result, typename ArgumentTuple>
521 static void Perform(const ArgumentTuple&) {
522 CompileAssertTypesEqual<void, Result>();
523 }
524};
525
526// Implements the polymorphic ReturnRef(x) action, which can be used
527// in any function that returns a reference to the type of x,
528// regardless of the argument types.
529template <typename T>
530class ReturnRefAction {
531 public:
532 // Constructs a ReturnRefAction object from the reference to be returned.
533 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
534
535 // This template type conversion operator allows ReturnRef(x) to be
536 // used in ANY function that returns a reference to x's type.
537 template <typename F>
538 operator Action<F>() const {
539 typedef typename Function<F>::Result Result;
540 // Asserts that the function return type is a reference. This
541 // catches the user error of using ReturnRef(x) when Return(x)
542 // should be used, and generates some helpful error message.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000543 GMOCK_COMPILE_ASSERT_(internal::is_reference<Result>::value,
544 use_Return_instead_of_ReturnRef_to_return_a_value);
shiqiane35fdd92008-12-10 05:08:54 +0000545 return Action<F>(new Impl<F>(ref_));
546 }
547 private:
548 // Implements the ReturnRef(x) action for a particular function type F.
549 template <typename F>
550 class Impl : public ActionInterface<F> {
551 public:
552 typedef typename Function<F>::Result Result;
553 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
554
555 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
556
557 virtual Result Perform(const ArgumentTuple&) {
558 return ref_;
559 }
560 private:
561 T& ref_;
562 };
563
564 T& ref_;
565};
566
567// Implements the DoDefault() action for a particular function type F.
568template <typename F>
569class MonomorphicDoDefaultActionImpl : public ActionInterface<F> {
570 public:
571 typedef typename Function<F>::Result Result;
572 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
573
574 MonomorphicDoDefaultActionImpl() : ActionInterface<F>(true) {}
575
576 // For technical reasons, DoDefault() cannot be used inside a
577 // composite action (e.g. DoAll(...)). It can only be used at the
578 // top level in an EXPECT_CALL(). If this function is called, the
579 // user must be using DoDefault() inside a composite action, and we
580 // have to generate a run-time error.
581 virtual Result Perform(const ArgumentTuple&) {
582 Assert(false, __FILE__, __LINE__,
583 "You are using DoDefault() inside a composite action like "
584 "DoAll() or WithArgs(). This is not supported for technical "
585 "reasons. Please instead spell out the default action, or "
586 "assign the default action to an Action variable and use "
587 "the variable in various places.");
588 return internal::Invalid<Result>();
589 // The above statement will never be reached, but is required in
590 // order for this function to compile.
591 }
592};
593
594// Implements the polymorphic DoDefault() action.
595class DoDefaultAction {
596 public:
597 // This template type conversion operator allows DoDefault() to be
598 // used in any function.
599 template <typename F>
600 operator Action<F>() const {
601 return Action<F>(new MonomorphicDoDefaultActionImpl<F>);
602 }
603};
604
605// Implements the Assign action to set a given pointer referent to a
606// particular value.
607template <typename T1, typename T2>
608class AssignAction {
609 public:
610 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
611
612 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000613 void Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000614 *ptr_ = value_;
615 }
616 private:
617 T1* const ptr_;
618 const T2 value_;
619};
620
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000621#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000622
shiqiane35fdd92008-12-10 05:08:54 +0000623// Implements the SetErrnoAndReturn action to simulate return from
624// various system calls and libc functions.
625template <typename T>
626class SetErrnoAndReturnAction {
627 public:
628 SetErrnoAndReturnAction(int errno_value, T result)
629 : errno_(errno_value),
630 result_(result) {}
631 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000632 Result Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000633 errno = errno_;
634 return result_;
635 }
636 private:
637 const int errno_;
638 const T result_;
639};
640
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000641#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000642
shiqiane35fdd92008-12-10 05:08:54 +0000643// Implements the SetArgumentPointee<N>(x) action for any function
644// whose N-th argument (0-based) is a pointer to x's type. The
645// template parameter kIsProto is true iff type A is ProtocolMessage,
646// proto2::Message, or a sub-class of those.
647template <size_t N, typename A, bool kIsProto>
648class SetArgumentPointeeAction {
649 public:
650 // Constructs an action that sets the variable pointed to by the
651 // N-th function argument to 'value'.
652 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
653
654 template <typename Result, typename ArgumentTuple>
655 void Perform(const ArgumentTuple& args) const {
656 CompileAssertTypesEqual<void, Result>();
657 *::std::tr1::get<N>(args) = value_;
658 }
659
660 private:
661 const A value_;
662};
663
664template <size_t N, typename Proto>
665class SetArgumentPointeeAction<N, Proto, true> {
666 public:
667 // Constructs an action that sets the variable pointed to by the
668 // N-th function argument to 'proto'. Both ProtocolMessage and
669 // proto2::Message have the CopyFrom() method, so the same
670 // implementation works for both.
671 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
672 proto_->CopyFrom(proto);
673 }
674
675 template <typename Result, typename ArgumentTuple>
676 void Perform(const ArgumentTuple& args) const {
677 CompileAssertTypesEqual<void, Result>();
678 ::std::tr1::get<N>(args)->CopyFrom(*proto_);
679 }
680 private:
681 const internal::linked_ptr<Proto> proto_;
682};
683
shiqiane35fdd92008-12-10 05:08:54 +0000684// Implements the InvokeWithoutArgs(f) action. The template argument
685// FunctionImpl is the implementation type of f, which can be either a
686// function pointer or a functor. InvokeWithoutArgs(f) can be used as an
687// Action<F> as long as f's type is compatible with F (i.e. f can be
688// assigned to a tr1::function<F>).
689template <typename FunctionImpl>
690class InvokeWithoutArgsAction {
691 public:
692 // The c'tor makes a copy of function_impl (either a function
693 // pointer or a functor).
694 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
695 : function_impl_(function_impl) {}
696
697 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
698 // compatible with f.
699 template <typename Result, typename ArgumentTuple>
700 Result Perform(const ArgumentTuple&) { return function_impl_(); }
701 private:
702 FunctionImpl function_impl_;
703};
704
705// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
706template <class Class, typename MethodPtr>
707class InvokeMethodWithoutArgsAction {
708 public:
709 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
710 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
711
712 template <typename Result, typename ArgumentTuple>
713 Result Perform(const ArgumentTuple&) const {
714 return (obj_ptr_->*method_ptr_)();
715 }
716 private:
717 Class* const obj_ptr_;
718 const MethodPtr method_ptr_;
719};
720
721// Implements the IgnoreResult(action) action.
722template <typename A>
723class IgnoreResultAction {
724 public:
725 explicit IgnoreResultAction(const A& action) : action_(action) {}
726
727 template <typename F>
728 operator Action<F>() const {
729 // Assert statement belongs here because this is the best place to verify
730 // conditions on F. It produces the clearest error messages
731 // in most compilers.
732 // Impl really belongs in this scope as a local class but can't
733 // because MSVC produces duplicate symbols in different translation units
734 // in this case. Until MS fixes that bug we put Impl into the class scope
735 // and put the typedef both here (for use in assert statement) and
736 // in the Impl class. But both definitions must be the same.
737 typedef typename internal::Function<F>::Result Result;
738
739 // Asserts at compile time that F returns void.
740 CompileAssertTypesEqual<void, Result>();
741
742 return Action<F>(new Impl<F>(action_));
743 }
744 private:
745 template <typename F>
746 class Impl : public ActionInterface<F> {
747 public:
748 typedef typename internal::Function<F>::Result Result;
749 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
750
751 explicit Impl(const A& action) : action_(action) {}
752
753 virtual void Perform(const ArgumentTuple& args) {
754 // Performs the action and ignores its result.
755 action_.Perform(args);
756 }
757
758 private:
759 // Type OriginalFunction is the same as F except that its return
760 // type is IgnoredValue.
761 typedef typename internal::Function<F>::MakeResultIgnoredValue
762 OriginalFunction;
763
764 const Action<OriginalFunction> action_;
765 };
766
767 const A action_;
768};
769
zhanyong.wana18423e2009-07-22 23:58:19 +0000770// A ReferenceWrapper<T> object represents a reference to type T,
771// which can be either const or not. It can be explicitly converted
772// from, and implicitly converted to, a T&. Unlike a reference,
773// ReferenceWrapper<T> can be copied and can survive template type
774// inference. This is used to support by-reference arguments in the
775// InvokeArgument<N>(...) action. The idea was from "reference
776// wrappers" in tr1, which we don't have in our source tree yet.
777template <typename T>
778class ReferenceWrapper {
779 public:
780 // Constructs a ReferenceWrapper<T> object from a T&.
781 explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
782
783 // Allows a ReferenceWrapper<T> object to be implicitly converted to
784 // a T&.
785 operator T&() const { return *pointer_; }
786 private:
787 T* pointer_;
788};
789
790// Allows the expression ByRef(x) to be printed as a reference to x.
791template <typename T>
792void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
793 T& value = ref;
794 UniversalPrinter<T&>::Print(value, os);
795}
796
797// Does two actions sequentially. Used for implementing the DoAll(a1,
798// a2, ...) action.
799template <typename Action1, typename Action2>
800class DoBothAction {
801 public:
802 DoBothAction(Action1 action1, Action2 action2)
803 : action1_(action1), action2_(action2) {}
804
805 // This template type conversion operator allows DoAll(a1, ..., a_n)
806 // to be used in ANY function of compatible type.
807 template <typename F>
808 operator Action<F>() const {
809 return Action<F>(new Impl<F>(action1_, action2_));
810 }
811
812 private:
813 // Implements the DoAll(...) action for a particular function type F.
814 template <typename F>
815 class Impl : public ActionInterface<F> {
816 public:
817 typedef typename Function<F>::Result Result;
818 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
819 typedef typename Function<F>::MakeResultVoid VoidResult;
820
821 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
822 : action1_(action1), action2_(action2) {}
823
824 virtual Result Perform(const ArgumentTuple& args) {
825 action1_.Perform(args);
826 return action2_.Perform(args);
827 }
828
829 private:
830 const Action<VoidResult> action1_;
831 const Action<F> action2_;
832 };
833
834 Action1 action1_;
835 Action2 action2_;
836};
837
shiqiane35fdd92008-12-10 05:08:54 +0000838} // namespace internal
839
840// An Unused object can be implicitly constructed from ANY value.
841// This is handy when defining actions that ignore some or all of the
842// mock function arguments. For example, given
843//
844// MOCK_METHOD3(Foo, double(const string& label, double x, double y));
845// MOCK_METHOD3(Bar, double(int index, double x, double y));
846//
847// instead of
848//
849// double DistanceToOriginWithLabel(const string& label, double x, double y) {
850// return sqrt(x*x + y*y);
851// }
852// double DistanceToOriginWithIndex(int index, double x, double y) {
853// return sqrt(x*x + y*y);
854// }
855// ...
856// EXEPCT_CALL(mock, Foo("abc", _, _))
857// .WillOnce(Invoke(DistanceToOriginWithLabel));
858// EXEPCT_CALL(mock, Bar(5, _, _))
859// .WillOnce(Invoke(DistanceToOriginWithIndex));
860//
861// you could write
862//
863// // We can declare any uninteresting argument as Unused.
864// double DistanceToOrigin(Unused, double x, double y) {
865// return sqrt(x*x + y*y);
866// }
867// ...
868// EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
869// EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
870typedef internal::IgnoredValue Unused;
871
872// This constructor allows us to turn an Action<From> object into an
873// Action<To>, as long as To's arguments can be implicitly converted
874// to From's and From's return type cann be implicitly converted to
875// To's.
876template <typename To>
877template <typename From>
878Action<To>::Action(const Action<From>& from)
879 : impl_(new internal::ActionAdaptor<To, From>(from)) {}
880
881// Creates an action that returns 'value'. 'value' is passed by value
882// instead of const reference - otherwise Return("string literal")
883// will trigger a compiler error about using array as initializer.
884template <typename R>
885internal::ReturnAction<R> Return(R value) {
886 return internal::ReturnAction<R>(value);
887}
888
889// Creates an action that returns NULL.
890inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
891 return MakePolymorphicAction(internal::ReturnNullAction());
892}
893
894// Creates an action that returns from a void function.
895inline PolymorphicAction<internal::ReturnVoidAction> Return() {
896 return MakePolymorphicAction(internal::ReturnVoidAction());
897}
898
899// Creates an action that returns the reference to a variable.
900template <typename R>
901inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
902 return internal::ReturnRefAction<R>(x);
903}
904
905// Creates an action that does the default action for the give mock function.
906inline internal::DoDefaultAction DoDefault() {
907 return internal::DoDefaultAction();
908}
909
910// Creates an action that sets the variable pointed by the N-th
911// (0-based) function argument to 'value'.
912template <size_t N, typename T>
913PolymorphicAction<
914 internal::SetArgumentPointeeAction<
915 N, T, internal::IsAProtocolMessage<T>::value> >
916SetArgumentPointee(const T& x) {
917 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
918 N, T, internal::IsAProtocolMessage<T>::value>(x));
919}
920
shiqiane35fdd92008-12-10 05:08:54 +0000921// Creates an action that sets a pointer referent to a given value.
922template <typename T1, typename T2>
923PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
924 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
925}
926
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000927#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000928
shiqiane35fdd92008-12-10 05:08:54 +0000929// Creates an action that sets errno and returns the appropriate error.
930template <typename T>
931PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
932SetErrnoAndReturn(int errval, T result) {
933 return MakePolymorphicAction(
934 internal::SetErrnoAndReturnAction<T>(errval, result));
935}
936
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000937#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000938
shiqiane35fdd92008-12-10 05:08:54 +0000939// Various overloads for InvokeWithoutArgs().
940
941// Creates an action that invokes 'function_impl' with no argument.
942template <typename FunctionImpl>
943PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
944InvokeWithoutArgs(FunctionImpl function_impl) {
945 return MakePolymorphicAction(
946 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
947}
948
949// Creates an action that invokes the given method on the given object
950// with no argument.
951template <class Class, typename MethodPtr>
952PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
953InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
954 return MakePolymorphicAction(
955 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
956 obj_ptr, method_ptr));
957}
958
959// Creates an action that performs an_action and throws away its
960// result. In other words, it changes the return type of an_action to
961// void. an_action MUST NOT return void, or the code won't compile.
962template <typename A>
963inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
964 return internal::IgnoreResultAction<A>(an_action);
965}
966
zhanyong.wana18423e2009-07-22 23:58:19 +0000967// Creates a reference wrapper for the given L-value. If necessary,
968// you can explicitly specify the type of the reference. For example,
969// suppose 'derived' is an object of type Derived, ByRef(derived)
970// would wrap a Derived&. If you want to wrap a const Base& instead,
971// where Base is a base class of Derived, just write:
972//
973// ByRef<const Base>(derived)
974template <typename T>
975inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
976 return internal::ReferenceWrapper<T>(l_value);
977}
978
shiqiane35fdd92008-12-10 05:08:54 +0000979} // namespace testing
980
981#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_