blob: f7daf82619937a9b67eb4ab4f1b5a19be6c909ba [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
128// signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
129// Using them is a bad practice and not portable. So don't use them.
130//
131// Still, Google Mock is designed to work even if the user uses signed
132// wchar_t or unsigned wchar_t (obviously, assuming the compiler
133// supports them).
134//
135// To gcc,
136//
137// wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
138//
139// MSVC does not recognize signed wchar_t or unsigned wchar_t. It
140// treats wchar_t as a native type usually, but treats it as the same
141// as unsigned short when the compiler option /Zc:wchar_t- is
142// specified.
143//
144// Therefore we provide a default action for wchar_t when compiled
145// with gcc or _NATIVE_WCHAR_T_DEFINED is defined.
146//
147// There's no need for a default action for signed wchar_t, as that
148// type is the same as wchar_t for gcc, and invalid for MSVC.
149//
150// There's also no need for a default action for unsigned wchar_t, as
151// that type is the same as unsigned int for gcc, and invalid for
152// MSVC.
153#if defined(__GNUC__) || defined(_NATIVE_WCHAR_T_DEFINED)
zhanyong.wane0d051e2009-02-19 00:33:37 +0000154GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000155#endif
156
zhanyong.wane0d051e2009-02-19 00:33:37 +0000157GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
158GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
159GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
160GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
161GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
162GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
163GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
164GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
165GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
166GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
shiqiane35fdd92008-12-10 05:08:54 +0000167
zhanyong.wane0d051e2009-02-19 00:33:37 +0000168#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
shiqiane35fdd92008-12-10 05:08:54 +0000169
170} // namespace internal
171
172// When an unexpected function call is encountered, Google Mock will
173// let it return a default value if the user has specified one for its
174// return type, or if the return type has a built-in default value;
175// otherwise Google Mock won't know what value to return and will have
176// to abort the process.
177//
178// The DefaultValue<T> class allows a user to specify the
179// default value for a type T that is both copyable and publicly
180// destructible (i.e. anything that can be used as a function return
181// type). The usage is:
182//
183// // Sets the default value for type T to be foo.
184// DefaultValue<T>::Set(foo);
185template <typename T>
186class DefaultValue {
187 public:
188 // Sets the default value for type T; requires T to be
189 // copy-constructable and have a public destructor.
190 static void Set(T x) {
191 delete value_;
192 value_ = new T(x);
193 }
194
195 // Unsets the default value for type T.
196 static void Clear() {
197 delete value_;
198 value_ = NULL;
199 }
200
201 // Returns true iff the user has set the default value for type T.
202 static bool IsSet() { return value_ != NULL; }
203
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000204 // Returns true if T has a default return value set by the user or there
205 // exists a built-in default value.
206 static bool Exists() {
207 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
208 }
209
shiqiane35fdd92008-12-10 05:08:54 +0000210 // Returns the default value for type T if the user has set one;
211 // otherwise returns the built-in default value if there is one;
212 // otherwise aborts the process.
213 static T Get() {
214 return value_ == NULL ?
215 internal::BuiltInDefaultValue<T>::Get() : *value_;
216 }
217 private:
218 static const T* value_;
219};
220
221// This partial specialization allows a user to set default values for
222// reference types.
223template <typename T>
224class DefaultValue<T&> {
225 public:
226 // Sets the default value for type T&.
227 static void Set(T& x) { // NOLINT
228 address_ = &x;
229 }
230
231 // Unsets the default value for type T&.
232 static void Clear() {
233 address_ = NULL;
234 }
235
236 // Returns true iff the user has set the default value for type T&.
237 static bool IsSet() { return address_ != NULL; }
238
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000239 // Returns true if T has a default return value set by the user or there
240 // exists a built-in default value.
241 static bool Exists() {
242 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
243 }
244
shiqiane35fdd92008-12-10 05:08:54 +0000245 // Returns the default value for type T& if the user has set one;
246 // otherwise returns the built-in default value if there is one;
247 // otherwise aborts the process.
248 static T& Get() {
249 return address_ == NULL ?
250 internal::BuiltInDefaultValue<T&>::Get() : *address_;
251 }
252 private:
253 static T* address_;
254};
255
256// This specialization allows DefaultValue<void>::Get() to
257// compile.
258template <>
259class DefaultValue<void> {
260 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000261 static bool Exists() { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000262 static void Get() {}
263};
264
265// Points to the user-set default value for type T.
266template <typename T>
267const T* DefaultValue<T>::value_ = NULL;
268
269// Points to the user-set default value for type T&.
270template <typename T>
271T* DefaultValue<T&>::address_ = NULL;
272
273// Implement this interface to define an action for function type F.
274template <typename F>
275class ActionInterface {
276 public:
277 typedef typename internal::Function<F>::Result Result;
278 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
279
280 ActionInterface() : is_do_default_(false) {}
281
282 virtual ~ActionInterface() {}
283
284 // Performs the action. This method is not const, as in general an
285 // action can have side effects and be stateful. For example, a
286 // get-the-next-element-from-the-collection action will need to
287 // remember the current element.
288 virtual Result Perform(const ArgumentTuple& args) = 0;
289
290 // Returns true iff this is the DoDefault() action.
291 bool IsDoDefault() const { return is_do_default_; }
292 private:
293 template <typename Function>
294 friend class internal::MonomorphicDoDefaultActionImpl;
295
296 // This private constructor is reserved for implementing
297 // DoDefault(), the default action for a given mock function.
298 explicit ActionInterface(bool is_do_default)
299 : is_do_default_(is_do_default) {}
300
301 // True iff this action is DoDefault().
302 const bool is_do_default_;
303};
304
305// An Action<F> is a copyable and IMMUTABLE (except by assignment)
306// object that represents an action to be taken when a mock function
307// of type F is called. The implementation of Action<T> is just a
308// linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
309// Don't inherit from Action!
310//
311// You can view an object implementing ActionInterface<F> as a
312// concrete action (including its current state), and an Action<F>
313// object as a handle to it.
314template <typename F>
315class Action {
316 public:
317 typedef typename internal::Function<F>::Result Result;
318 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
319
320 // Constructs a null Action. Needed for storing Action objects in
321 // STL containers.
322 Action() : impl_(NULL) {}
323
324 // Constructs an Action from its implementation.
325 explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
326
327 // Copy constructor.
328 Action(const Action& action) : impl_(action.impl_) {}
329
330 // This constructor allows us to turn an Action<Func> object into an
331 // Action<F>, as long as F's arguments can be implicitly converted
332 // to Func's and Func's return type cann be implicitly converted to
333 // F's.
334 template <typename Func>
335 explicit Action(const Action<Func>& action);
336
337 // Returns true iff this is the DoDefault() action.
338 bool IsDoDefault() const { return impl_->IsDoDefault(); }
339
340 // Performs the action. Note that this method is const even though
341 // the corresponding method in ActionInterface is not. The reason
342 // is that a const Action<F> means that it cannot be re-bound to
343 // another concrete action, not that the concrete action it binds to
344 // cannot change state. (Think of the difference between a const
345 // pointer and a pointer to const.)
346 Result Perform(const ArgumentTuple& args) const {
347 return impl_->Perform(args);
348 }
349 private:
350 template <typename F1, typename F2>
351 friend class internal::ActionAdaptor;
352
353 internal::linked_ptr<ActionInterface<F> > impl_;
354};
355
356// The PolymorphicAction class template makes it easy to implement a
357// polymorphic action (i.e. an action that can be used in mock
358// functions of than one type, e.g. Return()).
359//
360// To define a polymorphic action, a user first provides a COPYABLE
361// implementation class that has a Perform() method template:
362//
363// class FooAction {
364// public:
365// template <typename Result, typename ArgumentTuple>
366// Result Perform(const ArgumentTuple& args) const {
367// // Processes the arguments and returns a result, using
368// // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
369// }
370// ...
371// };
372//
373// Then the user creates the polymorphic action using
374// MakePolymorphicAction(object) where object has type FooAction. See
375// the definition of Return(void) and SetArgumentPointee<N>(value) for
376// complete examples.
377template <typename Impl>
378class PolymorphicAction {
379 public:
380 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
381
382 template <typename F>
383 operator Action<F>() const {
384 return Action<F>(new MonomorphicImpl<F>(impl_));
385 }
386 private:
387 template <typename F>
388 class MonomorphicImpl : public ActionInterface<F> {
389 public:
390 typedef typename internal::Function<F>::Result Result;
391 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
392
393 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
394
395 virtual Result Perform(const ArgumentTuple& args) {
396 return impl_.template Perform<Result>(args);
397 }
398
399 private:
400 Impl impl_;
401 };
402
403 Impl impl_;
404};
405
406// Creates an Action from its implementation and returns it. The
407// created Action object owns the implementation.
408template <typename F>
409Action<F> MakeAction(ActionInterface<F>* impl) {
410 return Action<F>(impl);
411}
412
413// Creates a polymorphic action from its implementation. This is
414// easier to use than the PolymorphicAction<Impl> constructor as it
415// doesn't require you to explicitly write the template argument, e.g.
416//
417// MakePolymorphicAction(foo);
418// vs
419// PolymorphicAction<TypeOfFoo>(foo);
420template <typename Impl>
421inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
422 return PolymorphicAction<Impl>(impl);
423}
424
425namespace internal {
426
427// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
428// and F1 are compatible.
429template <typename F1, typename F2>
430class ActionAdaptor : public ActionInterface<F1> {
431 public:
432 typedef typename internal::Function<F1>::Result Result;
433 typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
434
435 explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
436
437 virtual Result Perform(const ArgumentTuple& args) {
438 return impl_->Perform(args);
439 }
440 private:
441 const internal::linked_ptr<ActionInterface<F2> > impl_;
442};
443
444// Implements the polymorphic Return(x) action, which can be used in
445// any function that returns the type of x, regardless of the argument
446// types.
447template <typename R>
448class ReturnAction {
449 public:
450 // Constructs a ReturnAction object from the value to be returned.
451 // 'value' is passed by value instead of by const reference in order
452 // to allow Return("string literal") to compile.
453 explicit ReturnAction(R value) : value_(value) {}
454
455 // This template type conversion operator allows Return(x) to be
456 // used in ANY function that returns x's type.
457 template <typename F>
458 operator Action<F>() const {
459 // Assert statement belongs here because this is the best place to verify
460 // conditions on F. It produces the clearest error messages
461 // in most compilers.
462 // Impl really belongs in this scope as a local class but can't
463 // because MSVC produces duplicate symbols in different translation units
464 // in this case. Until MS fixes that bug we put Impl into the class scope
465 // and put the typedef both here (for use in assert statement) and
466 // in the Impl class. But both definitions must be the same.
467 typedef typename Function<F>::Result Result;
zhanyong.wane0d051e2009-02-19 00:33:37 +0000468 GMOCK_COMPILE_ASSERT_(
469 !internal::is_reference<Result>::value,
470 use_ReturnRef_instead_of_Return_to_return_a_reference);
shiqiane35fdd92008-12-10 05:08:54 +0000471 return Action<F>(new Impl<F>(value_));
472 }
473 private:
474 // Implements the Return(x) action for a particular function type F.
475 template <typename F>
476 class Impl : public ActionInterface<F> {
477 public:
478 typedef typename Function<F>::Result Result;
479 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
480
481 explicit Impl(R value) : value_(value) {}
482
483 virtual Result Perform(const ArgumentTuple&) { return value_; }
484
485 private:
486 R value_;
487 };
488
489 R value_;
490};
491
492// Implements the ReturnNull() action.
493class ReturnNullAction {
494 public:
495 // Allows ReturnNull() to be used in any pointer-returning function.
496 template <typename Result, typename ArgumentTuple>
497 static Result Perform(const ArgumentTuple&) {
zhanyong.wane0d051e2009-02-19 00:33:37 +0000498 GMOCK_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
499 ReturnNull_can_be_used_to_return_a_pointer_only);
shiqiane35fdd92008-12-10 05:08:54 +0000500 return NULL;
501 }
502};
503
504// Implements the Return() action.
505class ReturnVoidAction {
506 public:
507 // Allows Return() to be used in any void-returning function.
508 template <typename Result, typename ArgumentTuple>
509 static void Perform(const ArgumentTuple&) {
510 CompileAssertTypesEqual<void, Result>();
511 }
512};
513
514// Implements the polymorphic ReturnRef(x) action, which can be used
515// in any function that returns a reference to the type of x,
516// regardless of the argument types.
517template <typename T>
518class ReturnRefAction {
519 public:
520 // Constructs a ReturnRefAction object from the reference to be returned.
521 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
522
523 // This template type conversion operator allows ReturnRef(x) to be
524 // used in ANY function that returns a reference to x's type.
525 template <typename F>
526 operator Action<F>() const {
527 typedef typename Function<F>::Result Result;
528 // Asserts that the function return type is a reference. This
529 // catches the user error of using ReturnRef(x) when Return(x)
530 // should be used, and generates some helpful error message.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000531 GMOCK_COMPILE_ASSERT_(internal::is_reference<Result>::value,
532 use_Return_instead_of_ReturnRef_to_return_a_value);
shiqiane35fdd92008-12-10 05:08:54 +0000533 return Action<F>(new Impl<F>(ref_));
534 }
535 private:
536 // Implements the ReturnRef(x) action for a particular function type F.
537 template <typename F>
538 class Impl : public ActionInterface<F> {
539 public:
540 typedef typename Function<F>::Result Result;
541 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
542
543 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
544
545 virtual Result Perform(const ArgumentTuple&) {
546 return ref_;
547 }
548 private:
549 T& ref_;
550 };
551
552 T& ref_;
553};
554
555// Implements the DoDefault() action for a particular function type F.
556template <typename F>
557class MonomorphicDoDefaultActionImpl : public ActionInterface<F> {
558 public:
559 typedef typename Function<F>::Result Result;
560 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
561
562 MonomorphicDoDefaultActionImpl() : ActionInterface<F>(true) {}
563
564 // For technical reasons, DoDefault() cannot be used inside a
565 // composite action (e.g. DoAll(...)). It can only be used at the
566 // top level in an EXPECT_CALL(). If this function is called, the
567 // user must be using DoDefault() inside a composite action, and we
568 // have to generate a run-time error.
569 virtual Result Perform(const ArgumentTuple&) {
570 Assert(false, __FILE__, __LINE__,
571 "You are using DoDefault() inside a composite action like "
572 "DoAll() or WithArgs(). This is not supported for technical "
573 "reasons. Please instead spell out the default action, or "
574 "assign the default action to an Action variable and use "
575 "the variable in various places.");
576 return internal::Invalid<Result>();
577 // The above statement will never be reached, but is required in
578 // order for this function to compile.
579 }
580};
581
582// Implements the polymorphic DoDefault() action.
583class DoDefaultAction {
584 public:
585 // This template type conversion operator allows DoDefault() to be
586 // used in any function.
587 template <typename F>
588 operator Action<F>() const {
589 return Action<F>(new MonomorphicDoDefaultActionImpl<F>);
590 }
591};
592
593// Implements the Assign action to set a given pointer referent to a
594// particular value.
595template <typename T1, typename T2>
596class AssignAction {
597 public:
598 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
599
600 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000601 void Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000602 *ptr_ = value_;
603 }
604 private:
605 T1* const ptr_;
606 const T2 value_;
607};
608
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000609#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000610
shiqiane35fdd92008-12-10 05:08:54 +0000611// Implements the SetErrnoAndReturn action to simulate return from
612// various system calls and libc functions.
613template <typename T>
614class SetErrnoAndReturnAction {
615 public:
616 SetErrnoAndReturnAction(int errno_value, T result)
617 : errno_(errno_value),
618 result_(result) {}
619 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000620 Result Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000621 errno = errno_;
622 return result_;
623 }
624 private:
625 const int errno_;
626 const T result_;
627};
628
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000629#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000630
shiqiane35fdd92008-12-10 05:08:54 +0000631// Implements the SetArgumentPointee<N>(x) action for any function
632// whose N-th argument (0-based) is a pointer to x's type. The
633// template parameter kIsProto is true iff type A is ProtocolMessage,
634// proto2::Message, or a sub-class of those.
635template <size_t N, typename A, bool kIsProto>
636class SetArgumentPointeeAction {
637 public:
638 // Constructs an action that sets the variable pointed to by the
639 // N-th function argument to 'value'.
640 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
641
642 template <typename Result, typename ArgumentTuple>
643 void Perform(const ArgumentTuple& args) const {
644 CompileAssertTypesEqual<void, Result>();
645 *::std::tr1::get<N>(args) = value_;
646 }
647
648 private:
649 const A value_;
650};
651
652template <size_t N, typename Proto>
653class SetArgumentPointeeAction<N, Proto, true> {
654 public:
655 // Constructs an action that sets the variable pointed to by the
656 // N-th function argument to 'proto'. Both ProtocolMessage and
657 // proto2::Message have the CopyFrom() method, so the same
658 // implementation works for both.
659 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
660 proto_->CopyFrom(proto);
661 }
662
663 template <typename Result, typename ArgumentTuple>
664 void Perform(const ArgumentTuple& args) const {
665 CompileAssertTypesEqual<void, Result>();
666 ::std::tr1::get<N>(args)->CopyFrom(*proto_);
667 }
668 private:
669 const internal::linked_ptr<Proto> proto_;
670};
671
shiqiane35fdd92008-12-10 05:08:54 +0000672// Implements the InvokeWithoutArgs(f) action. The template argument
673// FunctionImpl is the implementation type of f, which can be either a
674// function pointer or a functor. InvokeWithoutArgs(f) can be used as an
675// Action<F> as long as f's type is compatible with F (i.e. f can be
676// assigned to a tr1::function<F>).
677template <typename FunctionImpl>
678class InvokeWithoutArgsAction {
679 public:
680 // The c'tor makes a copy of function_impl (either a function
681 // pointer or a functor).
682 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
683 : function_impl_(function_impl) {}
684
685 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
686 // compatible with f.
687 template <typename Result, typename ArgumentTuple>
688 Result Perform(const ArgumentTuple&) { return function_impl_(); }
689 private:
690 FunctionImpl function_impl_;
691};
692
693// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
694template <class Class, typename MethodPtr>
695class InvokeMethodWithoutArgsAction {
696 public:
697 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
698 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
699
700 template <typename Result, typename ArgumentTuple>
701 Result Perform(const ArgumentTuple&) const {
702 return (obj_ptr_->*method_ptr_)();
703 }
704 private:
705 Class* const obj_ptr_;
706 const MethodPtr method_ptr_;
707};
708
709// Implements the IgnoreResult(action) action.
710template <typename A>
711class IgnoreResultAction {
712 public:
713 explicit IgnoreResultAction(const A& action) : action_(action) {}
714
715 template <typename F>
716 operator Action<F>() const {
717 // Assert statement belongs here because this is the best place to verify
718 // conditions on F. It produces the clearest error messages
719 // in most compilers.
720 // Impl really belongs in this scope as a local class but can't
721 // because MSVC produces duplicate symbols in different translation units
722 // in this case. Until MS fixes that bug we put Impl into the class scope
723 // and put the typedef both here (for use in assert statement) and
724 // in the Impl class. But both definitions must be the same.
725 typedef typename internal::Function<F>::Result Result;
726
727 // Asserts at compile time that F returns void.
728 CompileAssertTypesEqual<void, Result>();
729
730 return Action<F>(new Impl<F>(action_));
731 }
732 private:
733 template <typename F>
734 class Impl : public ActionInterface<F> {
735 public:
736 typedef typename internal::Function<F>::Result Result;
737 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
738
739 explicit Impl(const A& action) : action_(action) {}
740
741 virtual void Perform(const ArgumentTuple& args) {
742 // Performs the action and ignores its result.
743 action_.Perform(args);
744 }
745
746 private:
747 // Type OriginalFunction is the same as F except that its return
748 // type is IgnoredValue.
749 typedef typename internal::Function<F>::MakeResultIgnoredValue
750 OriginalFunction;
751
752 const Action<OriginalFunction> action_;
753 };
754
755 const A action_;
756};
757
zhanyong.wana18423e2009-07-22 23:58:19 +0000758// A ReferenceWrapper<T> object represents a reference to type T,
759// which can be either const or not. It can be explicitly converted
760// from, and implicitly converted to, a T&. Unlike a reference,
761// ReferenceWrapper<T> can be copied and can survive template type
762// inference. This is used to support by-reference arguments in the
763// InvokeArgument<N>(...) action. The idea was from "reference
764// wrappers" in tr1, which we don't have in our source tree yet.
765template <typename T>
766class ReferenceWrapper {
767 public:
768 // Constructs a ReferenceWrapper<T> object from a T&.
769 explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
770
771 // Allows a ReferenceWrapper<T> object to be implicitly converted to
772 // a T&.
773 operator T&() const { return *pointer_; }
774 private:
775 T* pointer_;
776};
777
778// Allows the expression ByRef(x) to be printed as a reference to x.
779template <typename T>
780void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
781 T& value = ref;
782 UniversalPrinter<T&>::Print(value, os);
783}
784
785// Does two actions sequentially. Used for implementing the DoAll(a1,
786// a2, ...) action.
787template <typename Action1, typename Action2>
788class DoBothAction {
789 public:
790 DoBothAction(Action1 action1, Action2 action2)
791 : action1_(action1), action2_(action2) {}
792
793 // This template type conversion operator allows DoAll(a1, ..., a_n)
794 // to be used in ANY function of compatible type.
795 template <typename F>
796 operator Action<F>() const {
797 return Action<F>(new Impl<F>(action1_, action2_));
798 }
799
800 private:
801 // Implements the DoAll(...) action for a particular function type F.
802 template <typename F>
803 class Impl : public ActionInterface<F> {
804 public:
805 typedef typename Function<F>::Result Result;
806 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
807 typedef typename Function<F>::MakeResultVoid VoidResult;
808
809 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
810 : action1_(action1), action2_(action2) {}
811
812 virtual Result Perform(const ArgumentTuple& args) {
813 action1_.Perform(args);
814 return action2_.Perform(args);
815 }
816
817 private:
818 const Action<VoidResult> action1_;
819 const Action<F> action2_;
820 };
821
822 Action1 action1_;
823 Action2 action2_;
824};
825
shiqiane35fdd92008-12-10 05:08:54 +0000826} // namespace internal
827
828// An Unused object can be implicitly constructed from ANY value.
829// This is handy when defining actions that ignore some or all of the
830// mock function arguments. For example, given
831//
832// MOCK_METHOD3(Foo, double(const string& label, double x, double y));
833// MOCK_METHOD3(Bar, double(int index, double x, double y));
834//
835// instead of
836//
837// double DistanceToOriginWithLabel(const string& label, double x, double y) {
838// return sqrt(x*x + y*y);
839// }
840// double DistanceToOriginWithIndex(int index, double x, double y) {
841// return sqrt(x*x + y*y);
842// }
843// ...
844// EXEPCT_CALL(mock, Foo("abc", _, _))
845// .WillOnce(Invoke(DistanceToOriginWithLabel));
846// EXEPCT_CALL(mock, Bar(5, _, _))
847// .WillOnce(Invoke(DistanceToOriginWithIndex));
848//
849// you could write
850//
851// // We can declare any uninteresting argument as Unused.
852// double DistanceToOrigin(Unused, double x, double y) {
853// return sqrt(x*x + y*y);
854// }
855// ...
856// EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
857// EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
858typedef internal::IgnoredValue Unused;
859
860// This constructor allows us to turn an Action<From> object into an
861// Action<To>, as long as To's arguments can be implicitly converted
862// to From's and From's return type cann be implicitly converted to
863// To's.
864template <typename To>
865template <typename From>
866Action<To>::Action(const Action<From>& from)
867 : impl_(new internal::ActionAdaptor<To, From>(from)) {}
868
869// Creates an action that returns 'value'. 'value' is passed by value
870// instead of const reference - otherwise Return("string literal")
871// will trigger a compiler error about using array as initializer.
872template <typename R>
873internal::ReturnAction<R> Return(R value) {
874 return internal::ReturnAction<R>(value);
875}
876
877// Creates an action that returns NULL.
878inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
879 return MakePolymorphicAction(internal::ReturnNullAction());
880}
881
882// Creates an action that returns from a void function.
883inline PolymorphicAction<internal::ReturnVoidAction> Return() {
884 return MakePolymorphicAction(internal::ReturnVoidAction());
885}
886
887// Creates an action that returns the reference to a variable.
888template <typename R>
889inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
890 return internal::ReturnRefAction<R>(x);
891}
892
893// Creates an action that does the default action for the give mock function.
894inline internal::DoDefaultAction DoDefault() {
895 return internal::DoDefaultAction();
896}
897
898// Creates an action that sets the variable pointed by the N-th
899// (0-based) function argument to 'value'.
900template <size_t N, typename T>
901PolymorphicAction<
902 internal::SetArgumentPointeeAction<
903 N, T, internal::IsAProtocolMessage<T>::value> >
904SetArgumentPointee(const T& x) {
905 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
906 N, T, internal::IsAProtocolMessage<T>::value>(x));
907}
908
shiqiane35fdd92008-12-10 05:08:54 +0000909// Creates an action that sets a pointer referent to a given value.
910template <typename T1, typename T2>
911PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
912 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
913}
914
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000915#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000916
shiqiane35fdd92008-12-10 05:08:54 +0000917// Creates an action that sets errno and returns the appropriate error.
918template <typename T>
919PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
920SetErrnoAndReturn(int errval, T result) {
921 return MakePolymorphicAction(
922 internal::SetErrnoAndReturnAction<T>(errval, result));
923}
924
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000925#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000926
shiqiane35fdd92008-12-10 05:08:54 +0000927// Various overloads for InvokeWithoutArgs().
928
929// Creates an action that invokes 'function_impl' with no argument.
930template <typename FunctionImpl>
931PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
932InvokeWithoutArgs(FunctionImpl function_impl) {
933 return MakePolymorphicAction(
934 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
935}
936
937// Creates an action that invokes the given method on the given object
938// with no argument.
939template <class Class, typename MethodPtr>
940PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
941InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
942 return MakePolymorphicAction(
943 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
944 obj_ptr, method_ptr));
945}
946
947// Creates an action that performs an_action and throws away its
948// result. In other words, it changes the return type of an_action to
949// void. an_action MUST NOT return void, or the code won't compile.
950template <typename A>
951inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
952 return internal::IgnoreResultAction<A>(an_action);
953}
954
zhanyong.wana18423e2009-07-22 23:58:19 +0000955// Creates a reference wrapper for the given L-value. If necessary,
956// you can explicitly specify the type of the reference. For example,
957// suppose 'derived' is an object of type Derived, ByRef(derived)
958// would wrap a Derived&. If you want to wrap a const Base& instead,
959// where Base is a base class of Derived, just write:
960//
961// ByRef<const Base>(derived)
962template <typename T>
963inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
964 return internal::ReferenceWrapper<T>(l_value);
965}
966
shiqiane35fdd92008-12-10 05:08:54 +0000967} // namespace testing
968
969#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_