blob: 49d5532d549478c50f7190e137bec5cdc2710cf9 [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.wan5b5d62f2009-03-11 23:37:56 +0000609#ifndef _WIN32_WCE
610
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.wan5b5d62f2009-03-11 23:37:56 +0000629#endif // _WIN32_WCE
630
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
672// Implements the SetArrayArgument<N>(first, last) action for any function
673// whose N-th argument (0-based) is a pointer or iterator to a type that can be
674// implicitly converted from *first.
675template <size_t N, typename InputIterator>
676class SetArrayArgumentAction {
677 public:
678 // Constructs an action that sets the variable pointed to by the
679 // N-th function argument to 'value'.
680 explicit SetArrayArgumentAction(InputIterator first, InputIterator last)
681 : first_(first), last_(last) {
682 }
683
684 template <typename Result, typename ArgumentTuple>
685 void Perform(const ArgumentTuple& args) const {
686 CompileAssertTypesEqual<void, Result>();
687
688 // Microsoft compiler deprecates ::std::copy, so we want to suppress warning
689 // 4996 (Function call with parameters that may be unsafe) there.
zhanyong.wan652540a2009-02-23 23:37:29 +0000690#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +0000691#pragma warning(push) // Saves the current warning state.
692#pragma warning(disable:4996) // Temporarily disables warning 4996.
693#endif // GTEST_OS_WINDOWS
694 ::std::copy(first_, last_, ::std::tr1::get<N>(args));
zhanyong.wan652540a2009-02-23 23:37:29 +0000695#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +0000696#pragma warning(pop) // Restores the warning state.
697#endif // GTEST_OS_WINDOWS
698 }
699
700 private:
701 const InputIterator first_;
702 const InputIterator last_;
703};
704
705// Implements the InvokeWithoutArgs(f) action. The template argument
706// FunctionImpl is the implementation type of f, which can be either a
707// function pointer or a functor. InvokeWithoutArgs(f) can be used as an
708// Action<F> as long as f's type is compatible with F (i.e. f can be
709// assigned to a tr1::function<F>).
710template <typename FunctionImpl>
711class InvokeWithoutArgsAction {
712 public:
713 // The c'tor makes a copy of function_impl (either a function
714 // pointer or a functor).
715 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
716 : function_impl_(function_impl) {}
717
718 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
719 // compatible with f.
720 template <typename Result, typename ArgumentTuple>
721 Result Perform(const ArgumentTuple&) { return function_impl_(); }
722 private:
723 FunctionImpl function_impl_;
724};
725
726// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
727template <class Class, typename MethodPtr>
728class InvokeMethodWithoutArgsAction {
729 public:
730 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
731 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
732
733 template <typename Result, typename ArgumentTuple>
734 Result Perform(const ArgumentTuple&) const {
735 return (obj_ptr_->*method_ptr_)();
736 }
737 private:
738 Class* const obj_ptr_;
739 const MethodPtr method_ptr_;
740};
741
742// Implements the IgnoreResult(action) action.
743template <typename A>
744class IgnoreResultAction {
745 public:
746 explicit IgnoreResultAction(const A& action) : action_(action) {}
747
748 template <typename F>
749 operator Action<F>() const {
750 // Assert statement belongs here because this is the best place to verify
751 // conditions on F. It produces the clearest error messages
752 // in most compilers.
753 // Impl really belongs in this scope as a local class but can't
754 // because MSVC produces duplicate symbols in different translation units
755 // in this case. Until MS fixes that bug we put Impl into the class scope
756 // and put the typedef both here (for use in assert statement) and
757 // in the Impl class. But both definitions must be the same.
758 typedef typename internal::Function<F>::Result Result;
759
760 // Asserts at compile time that F returns void.
761 CompileAssertTypesEqual<void, Result>();
762
763 return Action<F>(new Impl<F>(action_));
764 }
765 private:
766 template <typename F>
767 class Impl : public ActionInterface<F> {
768 public:
769 typedef typename internal::Function<F>::Result Result;
770 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
771
772 explicit Impl(const A& action) : action_(action) {}
773
774 virtual void Perform(const ArgumentTuple& args) {
775 // Performs the action and ignores its result.
776 action_.Perform(args);
777 }
778
779 private:
780 // Type OriginalFunction is the same as F except that its return
781 // type is IgnoredValue.
782 typedef typename internal::Function<F>::MakeResultIgnoredValue
783 OriginalFunction;
784
785 const Action<OriginalFunction> action_;
786 };
787
788 const A action_;
789};
790
zhanyong.wana18423e2009-07-22 23:58:19 +0000791// A ReferenceWrapper<T> object represents a reference to type T,
792// which can be either const or not. It can be explicitly converted
793// from, and implicitly converted to, a T&. Unlike a reference,
794// ReferenceWrapper<T> can be copied and can survive template type
795// inference. This is used to support by-reference arguments in the
796// InvokeArgument<N>(...) action. The idea was from "reference
797// wrappers" in tr1, which we don't have in our source tree yet.
798template <typename T>
799class ReferenceWrapper {
800 public:
801 // Constructs a ReferenceWrapper<T> object from a T&.
802 explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
803
804 // Allows a ReferenceWrapper<T> object to be implicitly converted to
805 // a T&.
806 operator T&() const { return *pointer_; }
807 private:
808 T* pointer_;
809};
810
811// Allows the expression ByRef(x) to be printed as a reference to x.
812template <typename T>
813void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
814 T& value = ref;
815 UniversalPrinter<T&>::Print(value, os);
816}
817
818// Does two actions sequentially. Used for implementing the DoAll(a1,
819// a2, ...) action.
820template <typename Action1, typename Action2>
821class DoBothAction {
822 public:
823 DoBothAction(Action1 action1, Action2 action2)
824 : action1_(action1), action2_(action2) {}
825
826 // This template type conversion operator allows DoAll(a1, ..., a_n)
827 // to be used in ANY function of compatible type.
828 template <typename F>
829 operator Action<F>() const {
830 return Action<F>(new Impl<F>(action1_, action2_));
831 }
832
833 private:
834 // Implements the DoAll(...) action for a particular function type F.
835 template <typename F>
836 class Impl : public ActionInterface<F> {
837 public:
838 typedef typename Function<F>::Result Result;
839 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
840 typedef typename Function<F>::MakeResultVoid VoidResult;
841
842 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
843 : action1_(action1), action2_(action2) {}
844
845 virtual Result Perform(const ArgumentTuple& args) {
846 action1_.Perform(args);
847 return action2_.Perform(args);
848 }
849
850 private:
851 const Action<VoidResult> action1_;
852 const Action<F> action2_;
853 };
854
855 Action1 action1_;
856 Action2 action2_;
857};
858
shiqiane35fdd92008-12-10 05:08:54 +0000859} // namespace internal
860
861// An Unused object can be implicitly constructed from ANY value.
862// This is handy when defining actions that ignore some or all of the
863// mock function arguments. For example, given
864//
865// MOCK_METHOD3(Foo, double(const string& label, double x, double y));
866// MOCK_METHOD3(Bar, double(int index, double x, double y));
867//
868// instead of
869//
870// double DistanceToOriginWithLabel(const string& label, double x, double y) {
871// return sqrt(x*x + y*y);
872// }
873// double DistanceToOriginWithIndex(int index, double x, double y) {
874// return sqrt(x*x + y*y);
875// }
876// ...
877// EXEPCT_CALL(mock, Foo("abc", _, _))
878// .WillOnce(Invoke(DistanceToOriginWithLabel));
879// EXEPCT_CALL(mock, Bar(5, _, _))
880// .WillOnce(Invoke(DistanceToOriginWithIndex));
881//
882// you could write
883//
884// // We can declare any uninteresting argument as Unused.
885// double DistanceToOrigin(Unused, double x, double y) {
886// return sqrt(x*x + y*y);
887// }
888// ...
889// EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
890// EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
891typedef internal::IgnoredValue Unused;
892
893// This constructor allows us to turn an Action<From> object into an
894// Action<To>, as long as To's arguments can be implicitly converted
895// to From's and From's return type cann be implicitly converted to
896// To's.
897template <typename To>
898template <typename From>
899Action<To>::Action(const Action<From>& from)
900 : impl_(new internal::ActionAdaptor<To, From>(from)) {}
901
902// Creates an action that returns 'value'. 'value' is passed by value
903// instead of const reference - otherwise Return("string literal")
904// will trigger a compiler error about using array as initializer.
905template <typename R>
906internal::ReturnAction<R> Return(R value) {
907 return internal::ReturnAction<R>(value);
908}
909
910// Creates an action that returns NULL.
911inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
912 return MakePolymorphicAction(internal::ReturnNullAction());
913}
914
915// Creates an action that returns from a void function.
916inline PolymorphicAction<internal::ReturnVoidAction> Return() {
917 return MakePolymorphicAction(internal::ReturnVoidAction());
918}
919
920// Creates an action that returns the reference to a variable.
921template <typename R>
922inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
923 return internal::ReturnRefAction<R>(x);
924}
925
926// Creates an action that does the default action for the give mock function.
927inline internal::DoDefaultAction DoDefault() {
928 return internal::DoDefaultAction();
929}
930
931// Creates an action that sets the variable pointed by the N-th
932// (0-based) function argument to 'value'.
933template <size_t N, typename T>
934PolymorphicAction<
935 internal::SetArgumentPointeeAction<
936 N, T, internal::IsAProtocolMessage<T>::value> >
937SetArgumentPointee(const T& x) {
938 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
939 N, T, internal::IsAProtocolMessage<T>::value>(x));
940}
941
942// Creates an action that sets the elements of the array pointed to by the N-th
943// (0-based) function argument, which can be either a pointer or an iterator,
944// to the values of the elements in the source range [first, last).
945template <size_t N, typename InputIterator>
946PolymorphicAction<internal::SetArrayArgumentAction<N, InputIterator> >
947SetArrayArgument(InputIterator first, InputIterator last) {
948 return MakePolymorphicAction(internal::SetArrayArgumentAction<
949 N, InputIterator>(first, last));
950}
951
952// Creates an action that sets a pointer referent to a given value.
953template <typename T1, typename T2>
954PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
955 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
956}
957
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000958#ifndef _WIN32_WCE
959
shiqiane35fdd92008-12-10 05:08:54 +0000960// Creates an action that sets errno and returns the appropriate error.
961template <typename T>
962PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
963SetErrnoAndReturn(int errval, T result) {
964 return MakePolymorphicAction(
965 internal::SetErrnoAndReturnAction<T>(errval, result));
966}
967
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000968#endif // _WIN32_WCE
969
shiqiane35fdd92008-12-10 05:08:54 +0000970// Various overloads for InvokeWithoutArgs().
971
972// Creates an action that invokes 'function_impl' with no argument.
973template <typename FunctionImpl>
974PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
975InvokeWithoutArgs(FunctionImpl function_impl) {
976 return MakePolymorphicAction(
977 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
978}
979
980// Creates an action that invokes the given method on the given object
981// with no argument.
982template <class Class, typename MethodPtr>
983PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
984InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
985 return MakePolymorphicAction(
986 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
987 obj_ptr, method_ptr));
988}
989
990// Creates an action that performs an_action and throws away its
991// result. In other words, it changes the return type of an_action to
992// void. an_action MUST NOT return void, or the code won't compile.
993template <typename A>
994inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
995 return internal::IgnoreResultAction<A>(an_action);
996}
997
zhanyong.wana18423e2009-07-22 23:58:19 +0000998// Creates a reference wrapper for the given L-value. If necessary,
999// you can explicitly specify the type of the reference. For example,
1000// suppose 'derived' is an object of type Derived, ByRef(derived)
1001// would wrap a Derived&. If you want to wrap a const Base& instead,
1002// where Base is a base class of Derived, just write:
1003//
1004// ByRef<const Base>(derived)
1005template <typename T>
1006inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
1007 return internal::ReferenceWrapper<T>(l_value);
1008}
1009
shiqiane35fdd92008-12-10 05:08:54 +00001010} // namespace testing
1011
1012#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_