blob: 7f21a7d449d2eb1d2f9c874b630a847f834fb7a5 [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
313 // to Func's and Func's return type cann be implicitly converted to
314 // 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.
428template <typename R>
429class ReturnAction {
430 public:
431 // Constructs a ReturnAction object from the value to be returned.
432 // 'value' is passed by value instead of by const reference in order
433 // to allow Return("string literal") to compile.
434 explicit ReturnAction(R value) : value_(value) {}
435
436 // This template type conversion operator allows Return(x) to be
437 // used in ANY function that returns x's type.
438 template <typename F>
439 operator Action<F>() const {
440 // Assert statement belongs here because this is the best place to verify
441 // conditions on F. It produces the clearest error messages
442 // in most compilers.
443 // Impl really belongs in this scope as a local class but can't
444 // because MSVC produces duplicate symbols in different translation units
445 // in this case. Until MS fixes that bug we put Impl into the class scope
446 // and put the typedef both here (for use in assert statement) and
447 // in the Impl class. But both definitions must be the same.
448 typedef typename Function<F>::Result Result;
zhanyong.wane0d051e2009-02-19 00:33:37 +0000449 GMOCK_COMPILE_ASSERT_(
450 !internal::is_reference<Result>::value,
451 use_ReturnRef_instead_of_Return_to_return_a_reference);
shiqiane35fdd92008-12-10 05:08:54 +0000452 return Action<F>(new Impl<F>(value_));
453 }
454 private:
455 // Implements the Return(x) action for a particular function type F.
456 template <typename F>
457 class Impl : public ActionInterface<F> {
458 public:
459 typedef typename Function<F>::Result Result;
460 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
461
462 explicit Impl(R value) : value_(value) {}
463
464 virtual Result Perform(const ArgumentTuple&) { return value_; }
465
466 private:
467 R value_;
468 };
469
470 R value_;
471};
472
473// Implements the ReturnNull() action.
474class ReturnNullAction {
475 public:
476 // Allows ReturnNull() to be used in any pointer-returning function.
477 template <typename Result, typename ArgumentTuple>
478 static Result Perform(const ArgumentTuple&) {
zhanyong.wane0d051e2009-02-19 00:33:37 +0000479 GMOCK_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
480 ReturnNull_can_be_used_to_return_a_pointer_only);
shiqiane35fdd92008-12-10 05:08:54 +0000481 return NULL;
482 }
483};
484
485// Implements the Return() action.
486class ReturnVoidAction {
487 public:
488 // Allows Return() to be used in any void-returning function.
489 template <typename Result, typename ArgumentTuple>
490 static void Perform(const ArgumentTuple&) {
491 CompileAssertTypesEqual<void, Result>();
492 }
493};
494
495// Implements the polymorphic ReturnRef(x) action, which can be used
496// in any function that returns a reference to the type of x,
497// regardless of the argument types.
498template <typename T>
499class ReturnRefAction {
500 public:
501 // Constructs a ReturnRefAction object from the reference to be returned.
502 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
503
504 // This template type conversion operator allows ReturnRef(x) to be
505 // used in ANY function that returns a reference to x's type.
506 template <typename F>
507 operator Action<F>() const {
508 typedef typename Function<F>::Result Result;
509 // Asserts that the function return type is a reference. This
510 // catches the user error of using ReturnRef(x) when Return(x)
511 // should be used, and generates some helpful error message.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000512 GMOCK_COMPILE_ASSERT_(internal::is_reference<Result>::value,
513 use_Return_instead_of_ReturnRef_to_return_a_value);
shiqiane35fdd92008-12-10 05:08:54 +0000514 return Action<F>(new Impl<F>(ref_));
515 }
516 private:
517 // Implements the ReturnRef(x) action for a particular function type F.
518 template <typename F>
519 class Impl : public ActionInterface<F> {
520 public:
521 typedef typename Function<F>::Result Result;
522 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
523
524 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
525
526 virtual Result Perform(const ArgumentTuple&) {
527 return ref_;
528 }
529 private:
530 T& ref_;
531 };
532
533 T& ref_;
534};
535
536// Implements the DoDefault() action for a particular function type F.
537template <typename F>
538class MonomorphicDoDefaultActionImpl : public ActionInterface<F> {
539 public:
540 typedef typename Function<F>::Result Result;
541 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
542
543 MonomorphicDoDefaultActionImpl() : ActionInterface<F>(true) {}
544
545 // For technical reasons, DoDefault() cannot be used inside a
546 // composite action (e.g. DoAll(...)). It can only be used at the
547 // top level in an EXPECT_CALL(). If this function is called, the
548 // user must be using DoDefault() inside a composite action, and we
549 // have to generate a run-time error.
550 virtual Result Perform(const ArgumentTuple&) {
551 Assert(false, __FILE__, __LINE__,
552 "You are using DoDefault() inside a composite action like "
553 "DoAll() or WithArgs(). This is not supported for technical "
554 "reasons. Please instead spell out the default action, or "
555 "assign the default action to an Action variable and use "
556 "the variable in various places.");
557 return internal::Invalid<Result>();
558 // The above statement will never be reached, but is required in
559 // order for this function to compile.
560 }
561};
562
563// Implements the polymorphic DoDefault() action.
564class DoDefaultAction {
565 public:
566 // This template type conversion operator allows DoDefault() to be
567 // used in any function.
568 template <typename F>
569 operator Action<F>() const {
570 return Action<F>(new MonomorphicDoDefaultActionImpl<F>);
571 }
572};
573
574// Implements the Assign action to set a given pointer referent to a
575// particular value.
576template <typename T1, typename T2>
577class AssignAction {
578 public:
579 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
580
581 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000582 void Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000583 *ptr_ = value_;
584 }
585 private:
586 T1* const ptr_;
587 const T2 value_;
588};
589
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000590#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000591
shiqiane35fdd92008-12-10 05:08:54 +0000592// Implements the SetErrnoAndReturn action to simulate return from
593// various system calls and libc functions.
594template <typename T>
595class SetErrnoAndReturnAction {
596 public:
597 SetErrnoAndReturnAction(int errno_value, T result)
598 : errno_(errno_value),
599 result_(result) {}
600 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000601 Result Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000602 errno = errno_;
603 return result_;
604 }
605 private:
606 const int errno_;
607 const T result_;
608};
609
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000610#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000611
shiqiane35fdd92008-12-10 05:08:54 +0000612// Implements the SetArgumentPointee<N>(x) action for any function
613// whose N-th argument (0-based) is a pointer to x's type. The
614// template parameter kIsProto is true iff type A is ProtocolMessage,
615// proto2::Message, or a sub-class of those.
616template <size_t N, typename A, bool kIsProto>
617class SetArgumentPointeeAction {
618 public:
619 // Constructs an action that sets the variable pointed to by the
620 // N-th function argument to 'value'.
621 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
622
623 template <typename Result, typename ArgumentTuple>
624 void Perform(const ArgumentTuple& args) const {
625 CompileAssertTypesEqual<void, Result>();
626 *::std::tr1::get<N>(args) = value_;
627 }
628
629 private:
630 const A value_;
631};
632
633template <size_t N, typename Proto>
634class SetArgumentPointeeAction<N, Proto, true> {
635 public:
636 // Constructs an action that sets the variable pointed to by the
637 // N-th function argument to 'proto'. Both ProtocolMessage and
638 // proto2::Message have the CopyFrom() method, so the same
639 // implementation works for both.
640 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
641 proto_->CopyFrom(proto);
642 }
643
644 template <typename Result, typename ArgumentTuple>
645 void Perform(const ArgumentTuple& args) const {
646 CompileAssertTypesEqual<void, Result>();
647 ::std::tr1::get<N>(args)->CopyFrom(*proto_);
648 }
649 private:
650 const internal::linked_ptr<Proto> proto_;
651};
652
shiqiane35fdd92008-12-10 05:08:54 +0000653// Implements the InvokeWithoutArgs(f) action. The template argument
654// FunctionImpl is the implementation type of f, which can be either a
655// function pointer or a functor. InvokeWithoutArgs(f) can be used as an
656// Action<F> as long as f's type is compatible with F (i.e. f can be
657// assigned to a tr1::function<F>).
658template <typename FunctionImpl>
659class InvokeWithoutArgsAction {
660 public:
661 // The c'tor makes a copy of function_impl (either a function
662 // pointer or a functor).
663 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
664 : function_impl_(function_impl) {}
665
666 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
667 // compatible with f.
668 template <typename Result, typename ArgumentTuple>
669 Result Perform(const ArgumentTuple&) { return function_impl_(); }
670 private:
671 FunctionImpl function_impl_;
672};
673
674// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
675template <class Class, typename MethodPtr>
676class InvokeMethodWithoutArgsAction {
677 public:
678 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
679 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
680
681 template <typename Result, typename ArgumentTuple>
682 Result Perform(const ArgumentTuple&) const {
683 return (obj_ptr_->*method_ptr_)();
684 }
685 private:
686 Class* const obj_ptr_;
687 const MethodPtr method_ptr_;
688};
689
690// Implements the IgnoreResult(action) action.
691template <typename A>
692class IgnoreResultAction {
693 public:
694 explicit IgnoreResultAction(const A& action) : action_(action) {}
695
696 template <typename F>
697 operator Action<F>() const {
698 // Assert statement belongs here because this is the best place to verify
699 // conditions on F. It produces the clearest error messages
700 // in most compilers.
701 // Impl really belongs in this scope as a local class but can't
702 // because MSVC produces duplicate symbols in different translation units
703 // in this case. Until MS fixes that bug we put Impl into the class scope
704 // and put the typedef both here (for use in assert statement) and
705 // in the Impl class. But both definitions must be the same.
706 typedef typename internal::Function<F>::Result Result;
707
708 // Asserts at compile time that F returns void.
709 CompileAssertTypesEqual<void, Result>();
710
711 return Action<F>(new Impl<F>(action_));
712 }
713 private:
714 template <typename F>
715 class Impl : public ActionInterface<F> {
716 public:
717 typedef typename internal::Function<F>::Result Result;
718 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
719
720 explicit Impl(const A& action) : action_(action) {}
721
722 virtual void Perform(const ArgumentTuple& args) {
723 // Performs the action and ignores its result.
724 action_.Perform(args);
725 }
726
727 private:
728 // Type OriginalFunction is the same as F except that its return
729 // type is IgnoredValue.
730 typedef typename internal::Function<F>::MakeResultIgnoredValue
731 OriginalFunction;
732
733 const Action<OriginalFunction> action_;
734 };
735
736 const A action_;
737};
738
zhanyong.wana18423e2009-07-22 23:58:19 +0000739// A ReferenceWrapper<T> object represents a reference to type T,
740// which can be either const or not. It can be explicitly converted
741// from, and implicitly converted to, a T&. Unlike a reference,
742// ReferenceWrapper<T> can be copied and can survive template type
743// inference. This is used to support by-reference arguments in the
744// InvokeArgument<N>(...) action. The idea was from "reference
745// wrappers" in tr1, which we don't have in our source tree yet.
746template <typename T>
747class ReferenceWrapper {
748 public:
749 // Constructs a ReferenceWrapper<T> object from a T&.
750 explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
751
752 // Allows a ReferenceWrapper<T> object to be implicitly converted to
753 // a T&.
754 operator T&() const { return *pointer_; }
755 private:
756 T* pointer_;
757};
758
759// Allows the expression ByRef(x) to be printed as a reference to x.
760template <typename T>
761void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
762 T& value = ref;
763 UniversalPrinter<T&>::Print(value, os);
764}
765
766// Does two actions sequentially. Used for implementing the DoAll(a1,
767// a2, ...) action.
768template <typename Action1, typename Action2>
769class DoBothAction {
770 public:
771 DoBothAction(Action1 action1, Action2 action2)
772 : action1_(action1), action2_(action2) {}
773
774 // This template type conversion operator allows DoAll(a1, ..., a_n)
775 // to be used in ANY function of compatible type.
776 template <typename F>
777 operator Action<F>() const {
778 return Action<F>(new Impl<F>(action1_, action2_));
779 }
780
781 private:
782 // Implements the DoAll(...) action for a particular function type F.
783 template <typename F>
784 class Impl : public ActionInterface<F> {
785 public:
786 typedef typename Function<F>::Result Result;
787 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
788 typedef typename Function<F>::MakeResultVoid VoidResult;
789
790 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
791 : action1_(action1), action2_(action2) {}
792
793 virtual Result Perform(const ArgumentTuple& args) {
794 action1_.Perform(args);
795 return action2_.Perform(args);
796 }
797
798 private:
799 const Action<VoidResult> action1_;
800 const Action<F> action2_;
801 };
802
803 Action1 action1_;
804 Action2 action2_;
805};
806
shiqiane35fdd92008-12-10 05:08:54 +0000807} // namespace internal
808
809// An Unused object can be implicitly constructed from ANY value.
810// This is handy when defining actions that ignore some or all of the
811// mock function arguments. For example, given
812//
813// MOCK_METHOD3(Foo, double(const string& label, double x, double y));
814// MOCK_METHOD3(Bar, double(int index, double x, double y));
815//
816// instead of
817//
818// double DistanceToOriginWithLabel(const string& label, double x, double y) {
819// return sqrt(x*x + y*y);
820// }
821// double DistanceToOriginWithIndex(int index, double x, double y) {
822// return sqrt(x*x + y*y);
823// }
824// ...
825// EXEPCT_CALL(mock, Foo("abc", _, _))
826// .WillOnce(Invoke(DistanceToOriginWithLabel));
827// EXEPCT_CALL(mock, Bar(5, _, _))
828// .WillOnce(Invoke(DistanceToOriginWithIndex));
829//
830// you could write
831//
832// // We can declare any uninteresting argument as Unused.
833// double DistanceToOrigin(Unused, double x, double y) {
834// return sqrt(x*x + y*y);
835// }
836// ...
837// EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
838// EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
839typedef internal::IgnoredValue Unused;
840
841// This constructor allows us to turn an Action<From> object into an
842// Action<To>, as long as To's arguments can be implicitly converted
843// to From's and From's return type cann be implicitly converted to
844// To's.
845template <typename To>
846template <typename From>
847Action<To>::Action(const Action<From>& from)
848 : impl_(new internal::ActionAdaptor<To, From>(from)) {}
849
850// Creates an action that returns 'value'. 'value' is passed by value
851// instead of const reference - otherwise Return("string literal")
852// will trigger a compiler error about using array as initializer.
853template <typename R>
854internal::ReturnAction<R> Return(R value) {
855 return internal::ReturnAction<R>(value);
856}
857
858// Creates an action that returns NULL.
859inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
860 return MakePolymorphicAction(internal::ReturnNullAction());
861}
862
863// Creates an action that returns from a void function.
864inline PolymorphicAction<internal::ReturnVoidAction> Return() {
865 return MakePolymorphicAction(internal::ReturnVoidAction());
866}
867
868// Creates an action that returns the reference to a variable.
869template <typename R>
870inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
871 return internal::ReturnRefAction<R>(x);
872}
873
874// Creates an action that does the default action for the give mock function.
875inline internal::DoDefaultAction DoDefault() {
876 return internal::DoDefaultAction();
877}
878
879// Creates an action that sets the variable pointed by the N-th
880// (0-based) function argument to 'value'.
881template <size_t N, typename T>
882PolymorphicAction<
883 internal::SetArgumentPointeeAction<
884 N, T, internal::IsAProtocolMessage<T>::value> >
885SetArgumentPointee(const T& x) {
886 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
887 N, T, internal::IsAProtocolMessage<T>::value>(x));
888}
889
shiqiane35fdd92008-12-10 05:08:54 +0000890// Creates an action that sets a pointer referent to a given value.
891template <typename T1, typename T2>
892PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
893 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
894}
895
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000896#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000897
shiqiane35fdd92008-12-10 05:08:54 +0000898// Creates an action that sets errno and returns the appropriate error.
899template <typename T>
900PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
901SetErrnoAndReturn(int errval, T result) {
902 return MakePolymorphicAction(
903 internal::SetErrnoAndReturnAction<T>(errval, result));
904}
905
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000906#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000907
shiqiane35fdd92008-12-10 05:08:54 +0000908// Various overloads for InvokeWithoutArgs().
909
910// Creates an action that invokes 'function_impl' with no argument.
911template <typename FunctionImpl>
912PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
913InvokeWithoutArgs(FunctionImpl function_impl) {
914 return MakePolymorphicAction(
915 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
916}
917
918// Creates an action that invokes the given method on the given object
919// with no argument.
920template <class Class, typename MethodPtr>
921PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
922InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
923 return MakePolymorphicAction(
924 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
925 obj_ptr, method_ptr));
926}
927
928// Creates an action that performs an_action and throws away its
929// result. In other words, it changes the return type of an_action to
930// void. an_action MUST NOT return void, or the code won't compile.
931template <typename A>
932inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
933 return internal::IgnoreResultAction<A>(an_action);
934}
935
zhanyong.wana18423e2009-07-22 23:58:19 +0000936// Creates a reference wrapper for the given L-value. If necessary,
937// you can explicitly specify the type of the reference. For example,
938// suppose 'derived' is an object of type Derived, ByRef(derived)
939// would wrap a Derived&. If you want to wrap a const Base& instead,
940// where Base is a base class of Derived, just write:
941//
942// ByRef<const Base>(derived)
943template <typename T>
944inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
945 return internal::ReferenceWrapper<T>(l_value);
946}
947
shiqiane35fdd92008-12-10 05:08:54 +0000948} // namespace testing
949
950#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_