blob: 42648ada2f06177059926d7b85f19bf457503d47 [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
Gennadiy Civil984cba32018-07-27 11:15:08 -040036// GOOGLETEST_CM0002 DO NOT DELETE
37
shiqiane35fdd92008-12-10 05:08:54 +000038#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
40
zhanyong.wan5b5d62f2009-03-11 23:37:56 +000041#ifndef _WIN32_WCE
zhanyong.wan658ac0b2011-02-24 07:29:13 +000042# include <errno.h>
zhanyong.wan5b5d62f2009-03-11 23:37:56 +000043#endif
44
jgm79a367e2012-04-10 16:02:11 +000045#include <algorithm>
46#include <string>
47
zhanyong.wan53e08c42010-09-14 05:38:21 +000048#include "gmock/internal/gmock-internal-utils.h"
49#include "gmock/internal/gmock-port.h"
shiqiane35fdd92008-12-10 05:08:54 +000050
Gennadiy Civilaf463c42018-03-13 11:13:37 -040051#if GTEST_LANG_CXX11 // Defined by gtest-port.h via gmock-port.h.
52#include <functional>
kosakd478a1f2015-02-14 02:45:40 +000053#include <type_traits>
Gennadiy Civilaf463c42018-03-13 11:13:37 -040054#endif // GTEST_LANG_CXX11
kosakd478a1f2015-02-14 02:45:40 +000055
shiqiane35fdd92008-12-10 05:08:54 +000056namespace testing {
57
58// To implement an action Foo, define:
59// 1. a class FooAction that implements the ActionInterface interface, and
60// 2. a factory function that creates an Action object from a
61// const FooAction*.
62//
63// The two-level delegation design follows that of Matcher, providing
64// consistency for extension developers. It also eases ownership
65// management as Action objects can now be copied like plain values.
66
67namespace internal {
68
shiqiane35fdd92008-12-10 05:08:54 +000069template <typename F1, typename F2>
70class ActionAdaptor;
71
kosakd478a1f2015-02-14 02:45:40 +000072// BuiltInDefaultValueGetter<T, true>::Get() returns a
73// default-constructed T value. BuiltInDefaultValueGetter<T,
74// false>::Get() crashes with an error.
75//
76// This primary template is used when kDefaultConstructible is true.
77template <typename T, bool kDefaultConstructible>
78struct BuiltInDefaultValueGetter {
79 static T Get() { return T(); }
80};
shiqiane35fdd92008-12-10 05:08:54 +000081template <typename T>
kosakd478a1f2015-02-14 02:45:40 +000082struct BuiltInDefaultValueGetter<T, false> {
shiqiane35fdd92008-12-10 05:08:54 +000083 static T Get() {
84 Assert(false, __FILE__, __LINE__,
85 "Default action undefined for the function return type.");
86 return internal::Invalid<T>();
87 // The above statement will never be reached, but is required in
88 // order for this function to compile.
89 }
90};
91
kosakd478a1f2015-02-14 02:45:40 +000092// BuiltInDefaultValue<T>::Get() returns the "built-in" default value
93// for type T, which is NULL when T is a raw pointer type, 0 when T is
94// a numeric type, false when T is bool, or "" when T is string or
95// std::string. In addition, in C++11 and above, it turns a
96// default-constructed T value if T is default constructible. For any
97// other type T, the built-in default T value is undefined, and the
98// function will abort the process.
99template <typename T>
100class BuiltInDefaultValue {
101 public:
Gennadiy Civilaf463c42018-03-13 11:13:37 -0400102#if GTEST_LANG_CXX11
kosakd478a1f2015-02-14 02:45:40 +0000103 // This function returns true iff type T has a built-in default value.
104 static bool Exists() {
105 return ::std::is_default_constructible<T>::value;
106 }
107
108 static T Get() {
109 return BuiltInDefaultValueGetter<
110 T, ::std::is_default_constructible<T>::value>::Get();
111 }
112
Gennadiy Civilaf463c42018-03-13 11:13:37 -0400113#else // GTEST_LANG_CXX11
kosakd478a1f2015-02-14 02:45:40 +0000114 // This function returns true iff type T has a built-in default value.
115 static bool Exists() {
116 return false;
117 }
118
119 static T Get() {
120 return BuiltInDefaultValueGetter<T, false>::Get();
121 }
122
Gennadiy Civilaf463c42018-03-13 11:13:37 -0400123#endif // GTEST_LANG_CXX11
kosakd478a1f2015-02-14 02:45:40 +0000124};
125
shiqiane35fdd92008-12-10 05:08:54 +0000126// This partial specialization says that we use the same built-in
127// default value for T and const T.
128template <typename T>
129class BuiltInDefaultValue<const T> {
130 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000131 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
shiqiane35fdd92008-12-10 05:08:54 +0000132 static T Get() { return BuiltInDefaultValue<T>::Get(); }
133};
134
135// This partial specialization defines the default values for pointer
136// types.
137template <typename T>
138class BuiltInDefaultValue<T*> {
139 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000140 static bool Exists() { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000141 static T* Get() { return NULL; }
142};
143
144// The following specializations define the default values for
145// specific types we care about.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000146#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
shiqiane35fdd92008-12-10 05:08:54 +0000147 template <> \
148 class BuiltInDefaultValue<type> { \
149 public: \
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000150 static bool Exists() { return true; } \
shiqiane35fdd92008-12-10 05:08:54 +0000151 static type Get() { return value; } \
152 }
153
zhanyong.wane0d051e2009-02-19 00:33:37 +0000154GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000155#if GTEST_HAS_GLOBAL_STRING
zhanyong.wane0d051e2009-02-19 00:33:37 +0000156GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
shiqiane35fdd92008-12-10 05:08:54 +0000157#endif // GTEST_HAS_GLOBAL_STRING
zhanyong.wane0d051e2009-02-19 00:33:37 +0000158GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
zhanyong.wane0d051e2009-02-19 00:33:37 +0000159GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
160GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
161GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
162GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
shiqiane35fdd92008-12-10 05:08:54 +0000163
shiqiane35fdd92008-12-10 05:08:54 +0000164// There's no need for a default action for signed wchar_t, as that
165// type is the same as wchar_t for gcc, and invalid for MSVC.
166//
167// There's also no need for a default action for unsigned wchar_t, as
168// that type is the same as unsigned int for gcc, and invalid for
169// MSVC.
zhanyong.wan95b12332009-09-25 18:55:50 +0000170#if GMOCK_WCHAR_T_IS_NATIVE_
zhanyong.wane0d051e2009-02-19 00:33:37 +0000171GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000172#endif
173
zhanyong.wane0d051e2009-02-19 00:33:37 +0000174GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
175GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
176GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
177GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
178GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
179GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
180GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
181GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
182GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
183GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
shiqiane35fdd92008-12-10 05:08:54 +0000184
zhanyong.wane0d051e2009-02-19 00:33:37 +0000185#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
shiqiane35fdd92008-12-10 05:08:54 +0000186
187} // namespace internal
188
189// When an unexpected function call is encountered, Google Mock will
190// let it return a default value if the user has specified one for its
191// return type, or if the return type has a built-in default value;
192// otherwise Google Mock won't know what value to return and will have
193// to abort the process.
194//
195// The DefaultValue<T> class allows a user to specify the
196// default value for a type T that is both copyable and publicly
197// destructible (i.e. anything that can be used as a function return
198// type). The usage is:
199//
200// // Sets the default value for type T to be foo.
201// DefaultValue<T>::Set(foo);
202template <typename T>
203class DefaultValue {
204 public:
205 // Sets the default value for type T; requires T to be
206 // copy-constructable and have a public destructor.
207 static void Set(T x) {
kosakb5c81092014-01-29 06:41:44 +0000208 delete producer_;
209 producer_ = new FixedValueProducer(x);
210 }
211
212 // Provides a factory function to be called to generate the default value.
213 // This method can be used even if T is only move-constructible, but it is not
214 // limited to that case.
215 typedef T (*FactoryFunction)();
216 static void SetFactory(FactoryFunction factory) {
217 delete producer_;
218 producer_ = new FactoryValueProducer(factory);
shiqiane35fdd92008-12-10 05:08:54 +0000219 }
220
221 // Unsets the default value for type T.
222 static void Clear() {
kosakb5c81092014-01-29 06:41:44 +0000223 delete producer_;
224 producer_ = NULL;
shiqiane35fdd92008-12-10 05:08:54 +0000225 }
226
227 // Returns true iff the user has set the default value for type T.
kosakb5c81092014-01-29 06:41:44 +0000228 static bool IsSet() { return producer_ != NULL; }
shiqiane35fdd92008-12-10 05:08:54 +0000229
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000230 // Returns true if T has a default return value set by the user or there
231 // exists a built-in default value.
232 static bool Exists() {
233 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
234 }
235
shiqiane35fdd92008-12-10 05:08:54 +0000236 // Returns the default value for type T if the user has set one;
kosakb5c81092014-01-29 06:41:44 +0000237 // otherwise returns the built-in default value. Requires that Exists()
238 // is true, which ensures that the return value is well-defined.
shiqiane35fdd92008-12-10 05:08:54 +0000239 static T Get() {
kosakb5c81092014-01-29 06:41:44 +0000240 return producer_ == NULL ?
241 internal::BuiltInDefaultValue<T>::Get() : producer_->Produce();
shiqiane35fdd92008-12-10 05:08:54 +0000242 }
jgm79a367e2012-04-10 16:02:11 +0000243
shiqiane35fdd92008-12-10 05:08:54 +0000244 private:
kosakb5c81092014-01-29 06:41:44 +0000245 class ValueProducer {
246 public:
247 virtual ~ValueProducer() {}
248 virtual T Produce() = 0;
249 };
250
251 class FixedValueProducer : public ValueProducer {
252 public:
253 explicit FixedValueProducer(T value) : value_(value) {}
254 virtual T Produce() { return value_; }
255
256 private:
257 const T value_;
258 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
259 };
260
261 class FactoryValueProducer : public ValueProducer {
262 public:
263 explicit FactoryValueProducer(FactoryFunction factory)
264 : factory_(factory) {}
265 virtual T Produce() { return factory_(); }
266
267 private:
268 const FactoryFunction factory_;
269 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
270 };
271
272 static ValueProducer* producer_;
shiqiane35fdd92008-12-10 05:08:54 +0000273};
274
275// This partial specialization allows a user to set default values for
276// reference types.
277template <typename T>
278class DefaultValue<T&> {
279 public:
280 // Sets the default value for type T&.
281 static void Set(T& x) { // NOLINT
282 address_ = &x;
283 }
284
285 // Unsets the default value for type T&.
286 static void Clear() {
287 address_ = NULL;
288 }
289
290 // Returns true iff the user has set the default value for type T&.
291 static bool IsSet() { return address_ != NULL; }
292
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000293 // Returns true if T has a default return value set by the user or there
294 // exists a built-in default value.
295 static bool Exists() {
296 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
297 }
298
shiqiane35fdd92008-12-10 05:08:54 +0000299 // Returns the default value for type T& if the user has set one;
300 // otherwise returns the built-in default value if there is one;
301 // otherwise aborts the process.
302 static T& Get() {
303 return address_ == NULL ?
304 internal::BuiltInDefaultValue<T&>::Get() : *address_;
305 }
jgm79a367e2012-04-10 16:02:11 +0000306
shiqiane35fdd92008-12-10 05:08:54 +0000307 private:
308 static T* address_;
309};
310
311// This specialization allows DefaultValue<void>::Get() to
312// compile.
313template <>
314class DefaultValue<void> {
315 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000316 static bool Exists() { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000317 static void Get() {}
318};
319
320// Points to the user-set default value for type T.
321template <typename T>
kosakb5c81092014-01-29 06:41:44 +0000322typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL;
shiqiane35fdd92008-12-10 05:08:54 +0000323
324// Points to the user-set default value for type T&.
325template <typename T>
326T* DefaultValue<T&>::address_ = NULL;
327
328// Implement this interface to define an action for function type F.
329template <typename F>
330class ActionInterface {
331 public:
332 typedef typename internal::Function<F>::Result Result;
333 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
334
zhanyong.waned6c9272011-02-23 19:39:27 +0000335 ActionInterface() {}
shiqiane35fdd92008-12-10 05:08:54 +0000336 virtual ~ActionInterface() {}
337
338 // Performs the action. This method is not const, as in general an
339 // action can have side effects and be stateful. For example, a
340 // get-the-next-element-from-the-collection action will need to
341 // remember the current element.
342 virtual Result Perform(const ArgumentTuple& args) = 0;
343
shiqiane35fdd92008-12-10 05:08:54 +0000344 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000345 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
shiqiane35fdd92008-12-10 05:08:54 +0000346};
347
348// An Action<F> is a copyable and IMMUTABLE (except by assignment)
349// object that represents an action to be taken when a mock function
350// of type F is called. The implementation of Action<T> is just a
351// linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
352// Don't inherit from Action!
353//
354// You can view an object implementing ActionInterface<F> as a
355// concrete action (including its current state), and an Action<F>
356// object as a handle to it.
357template <typename F>
358class Action {
359 public:
360 typedef typename internal::Function<F>::Result Result;
361 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
362
363 // Constructs a null Action. Needed for storing Action objects in
364 // STL containers.
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400365 Action() {}
shiqiane35fdd92008-12-10 05:08:54 +0000366
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400367#if GTEST_LANG_CXX11
368 // Construct an Action from a specified callable.
369 // This cannot take std::function directly, because then Action would not be
370 // directly constructible from lambda (it would require two conversions).
371 template <typename G,
372 typename = typename ::std::enable_if<
373 ::std::is_constructible<::std::function<F>, G>::value>::type>
374 Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
375#endif
376
377 // Constructs an Action from its implementation.
shiqiane35fdd92008-12-10 05:08:54 +0000378 explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
379
shiqiane35fdd92008-12-10 05:08:54 +0000380 // This constructor allows us to turn an Action<Func> object into an
381 // Action<F>, as long as F's arguments can be implicitly converted
vladloseva070cbd2009-11-18 00:09:28 +0000382 // to Func's and Func's return type can be implicitly converted to
shiqiane35fdd92008-12-10 05:08:54 +0000383 // F's.
384 template <typename Func>
385 explicit Action(const Action<Func>& action);
386
387 // Returns true iff this is the DoDefault() action.
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400388 bool IsDoDefault() const {
389#if GTEST_LANG_CXX11
390 return impl_ == nullptr && fun_ == nullptr;
391#else
392 return impl_ == NULL;
393#endif
394 }
shiqiane35fdd92008-12-10 05:08:54 +0000395
396 // Performs the action. Note that this method is const even though
397 // the corresponding method in ActionInterface is not. The reason
398 // is that a const Action<F> means that it cannot be re-bound to
399 // another concrete action, not that the concrete action it binds to
400 // cannot change state. (Think of the difference between a const
401 // pointer and a pointer to const.)
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400402 Result Perform(ArgumentTuple args) const {
403 if (IsDoDefault()) {
404 internal::IllegalDoDefault(__FILE__, __LINE__);
405 }
406#if GTEST_LANG_CXX11
407 if (fun_ != nullptr) {
408 return internal::Apply(fun_, ::std::move(args));
409 }
410#endif
shiqiane35fdd92008-12-10 05:08:54 +0000411 return impl_->Perform(args);
412 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000413
shiqiane35fdd92008-12-10 05:08:54 +0000414 private:
415 template <typename F1, typename F2>
416 friend class internal::ActionAdaptor;
417
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400418 template <typename G>
419 friend class Action;
420
421 // In C++11, Action can be implemented either as a generic functor (through
422 // std::function), or legacy ActionInterface. In C++98, only ActionInterface
423 // is available. The invariants are as follows:
424 // * in C++98, impl_ is null iff this is the default action
425 // * in C++11, at most one of fun_ & impl_ may be nonnull; both are null iff
426 // this is the default action
427#if GTEST_LANG_CXX11
428 ::std::function<F> fun_;
429#endif
shiqiane35fdd92008-12-10 05:08:54 +0000430 internal::linked_ptr<ActionInterface<F> > impl_;
431};
432
433// The PolymorphicAction class template makes it easy to implement a
434// polymorphic action (i.e. an action that can be used in mock
435// functions of than one type, e.g. Return()).
436//
437// To define a polymorphic action, a user first provides a COPYABLE
438// implementation class that has a Perform() method template:
439//
440// class FooAction {
441// public:
442// template <typename Result, typename ArgumentTuple>
443// Result Perform(const ArgumentTuple& args) const {
444// // Processes the arguments and returns a result, using
445// // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
446// }
447// ...
448// };
449//
450// Then the user creates the polymorphic action using
451// MakePolymorphicAction(object) where object has type FooAction. See
452// the definition of Return(void) and SetArgumentPointee<N>(value) for
453// complete examples.
454template <typename Impl>
455class PolymorphicAction {
456 public:
457 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
458
459 template <typename F>
460 operator Action<F>() const {
461 return Action<F>(new MonomorphicImpl<F>(impl_));
462 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000463
shiqiane35fdd92008-12-10 05:08:54 +0000464 private:
465 template <typename F>
466 class MonomorphicImpl : public ActionInterface<F> {
467 public:
468 typedef typename internal::Function<F>::Result Result;
469 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
470
471 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
472
473 virtual Result Perform(const ArgumentTuple& args) {
474 return impl_.template Perform<Result>(args);
475 }
476
477 private:
478 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000479
480 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000481 };
482
483 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000484
485 GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
shiqiane35fdd92008-12-10 05:08:54 +0000486};
487
488// Creates an Action from its implementation and returns it. The
489// created Action object owns the implementation.
490template <typename F>
491Action<F> MakeAction(ActionInterface<F>* impl) {
492 return Action<F>(impl);
493}
494
495// Creates a polymorphic action from its implementation. This is
496// easier to use than the PolymorphicAction<Impl> constructor as it
497// doesn't require you to explicitly write the template argument, e.g.
498//
499// MakePolymorphicAction(foo);
500// vs
501// PolymorphicAction<TypeOfFoo>(foo);
502template <typename Impl>
503inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
504 return PolymorphicAction<Impl>(impl);
505}
506
507namespace internal {
508
509// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
510// and F1 are compatible.
511template <typename F1, typename F2>
512class ActionAdaptor : public ActionInterface<F1> {
513 public:
514 typedef typename internal::Function<F1>::Result Result;
515 typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
516
517 explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
518
519 virtual Result Perform(const ArgumentTuple& args) {
520 return impl_->Perform(args);
521 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000522
shiqiane35fdd92008-12-10 05:08:54 +0000523 private:
524 const internal::linked_ptr<ActionInterface<F2> > impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000525
526 GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
shiqiane35fdd92008-12-10 05:08:54 +0000527};
528
kosak3d1c78b2014-11-17 00:56:52 +0000529// Helper struct to specialize ReturnAction to execute a move instead of a copy
530// on return. Useful for move-only types, but could be used on any type.
531template <typename T>
532struct ByMoveWrapper {
kosakd370f852014-11-17 01:14:16 +0000533 explicit ByMoveWrapper(T value) : payload(internal::move(value)) {}
kosak3d1c78b2014-11-17 00:56:52 +0000534 T payload;
535};
536
shiqiane35fdd92008-12-10 05:08:54 +0000537// Implements the polymorphic Return(x) action, which can be used in
538// any function that returns the type of x, regardless of the argument
539// types.
vladloseva070cbd2009-11-18 00:09:28 +0000540//
541// Note: The value passed into Return must be converted into
542// Function<F>::Result when this action is cast to Action<F> rather than
543// when that action is performed. This is important in scenarios like
544//
545// MOCK_METHOD1(Method, T(U));
546// ...
547// {
548// Foo foo;
549// X x(&foo);
550// EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
551// }
552//
553// In the example above the variable x holds reference to foo which leaves
554// scope and gets destroyed. If copying X just copies a reference to foo,
555// that copy will be left with a hanging reference. If conversion to T
556// makes a copy of foo, the above code is safe. To support that scenario, we
557// need to make sure that the type conversion happens inside the EXPECT_CALL
558// statement, and conversion of the result of Return to Action<T(U)> is a
559// good place for that.
560//
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400561// The real life example of the above scenario happens when an invocation
562// of gtl::Container() is passed into Return.
563//
shiqiane35fdd92008-12-10 05:08:54 +0000564template <typename R>
565class ReturnAction {
566 public:
567 // Constructs a ReturnAction object from the value to be returned.
568 // 'value' is passed by value instead of by const reference in order
569 // to allow Return("string literal") to compile.
kosakd370f852014-11-17 01:14:16 +0000570 explicit ReturnAction(R value) : value_(new R(internal::move(value))) {}
shiqiane35fdd92008-12-10 05:08:54 +0000571
572 // This template type conversion operator allows Return(x) to be
573 // used in ANY function that returns x's type.
574 template <typename F>
575 operator Action<F>() const {
576 // Assert statement belongs here because this is the best place to verify
577 // conditions on F. It produces the clearest error messages
578 // in most compilers.
579 // Impl really belongs in this scope as a local class but can't
580 // because MSVC produces duplicate symbols in different translation units
581 // in this case. Until MS fixes that bug we put Impl into the class scope
582 // and put the typedef both here (for use in assert statement) and
583 // in the Impl class. But both definitions must be the same.
584 typedef typename Function<F>::Result Result;
zhanyong.wan02f71062010-05-10 17:14:29 +0000585 GTEST_COMPILE_ASSERT_(
kosak3d1c78b2014-11-17 00:56:52 +0000586 !is_reference<Result>::value,
zhanyong.wane0d051e2009-02-19 00:33:37 +0000587 use_ReturnRef_instead_of_Return_to_return_a_reference);
kosak3d1c78b2014-11-17 00:56:52 +0000588 return Action<F>(new Impl<R, F>(value_));
shiqiane35fdd92008-12-10 05:08:54 +0000589 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000590
shiqiane35fdd92008-12-10 05:08:54 +0000591 private:
592 // Implements the Return(x) action for a particular function type F.
kosak3d1c78b2014-11-17 00:56:52 +0000593 template <typename R_, typename F>
shiqiane35fdd92008-12-10 05:08:54 +0000594 class Impl : public ActionInterface<F> {
595 public:
596 typedef typename Function<F>::Result Result;
597 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
598
vladloseva070cbd2009-11-18 00:09:28 +0000599 // The implicit cast is necessary when Result has more than one
600 // single-argument constructor (e.g. Result is std::vector<int>) and R
601 // has a type conversion operator template. In that case, value_(value)
602 // won't compile as the compiler doesn't known which constructor of
zhanyong.wan5b61ce32011-02-01 00:00:03 +0000603 // Result to call. ImplicitCast_ forces the compiler to convert R to
vladloseva070cbd2009-11-18 00:09:28 +0000604 // Result without considering explicit constructors, thus resolving the
605 // ambiguity. value_ is then initialized using its copy constructor.
kosak3d1c78b2014-11-17 00:56:52 +0000606 explicit Impl(const linked_ptr<R>& value)
kosak7123d832014-11-17 02:04:46 +0000607 : value_before_cast_(*value),
608 value_(ImplicitCast_<Result>(value_before_cast_)) {}
shiqiane35fdd92008-12-10 05:08:54 +0000609
610 virtual Result Perform(const ArgumentTuple&) { return value_; }
611
612 private:
kosak3d1c78b2014-11-17 00:56:52 +0000613 GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
vladloseva070cbd2009-11-18 00:09:28 +0000614 Result_cannot_be_a_reference_type);
kosak7123d832014-11-17 02:04:46 +0000615 // We save the value before casting just in case it is being cast to a
616 // wrapper type.
617 R value_before_cast_;
vladloseva070cbd2009-11-18 00:09:28 +0000618 Result value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000619
kosak7123d832014-11-17 02:04:46 +0000620 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000621 };
622
kosak3d1c78b2014-11-17 00:56:52 +0000623 // Partially specialize for ByMoveWrapper. This version of ReturnAction will
624 // move its contents instead.
625 template <typename R_, typename F>
626 class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
627 public:
628 typedef typename Function<F>::Result Result;
629 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
630
631 explicit Impl(const linked_ptr<R>& wrapper)
632 : performed_(false), wrapper_(wrapper) {}
633
634 virtual Result Perform(const ArgumentTuple&) {
635 GTEST_CHECK_(!performed_)
636 << "A ByMove() action should only be performed once.";
637 performed_ = true;
kosakd370f852014-11-17 01:14:16 +0000638 return internal::move(wrapper_->payload);
kosak3d1c78b2014-11-17 00:56:52 +0000639 }
640
641 private:
642 bool performed_;
643 const linked_ptr<R> wrapper_;
644
645 GTEST_DISALLOW_ASSIGN_(Impl);
646 };
647
648 const linked_ptr<R> value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000649
650 GTEST_DISALLOW_ASSIGN_(ReturnAction);
shiqiane35fdd92008-12-10 05:08:54 +0000651};
652
653// Implements the ReturnNull() action.
654class ReturnNullAction {
655 public:
kosak53d49dc2015-01-08 03:03:09 +0000656 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
657 // this is enforced by returning nullptr, and in non-C++11 by asserting a
658 // pointer type on compile time.
shiqiane35fdd92008-12-10 05:08:54 +0000659 template <typename Result, typename ArgumentTuple>
660 static Result Perform(const ArgumentTuple&) {
kosak53d49dc2015-01-08 03:03:09 +0000661#if GTEST_LANG_CXX11
662 return nullptr;
663#else
zhanyong.wan02f71062010-05-10 17:14:29 +0000664 GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
zhanyong.wane0d051e2009-02-19 00:33:37 +0000665 ReturnNull_can_be_used_to_return_a_pointer_only);
shiqiane35fdd92008-12-10 05:08:54 +0000666 return NULL;
kosak53d49dc2015-01-08 03:03:09 +0000667#endif // GTEST_LANG_CXX11
shiqiane35fdd92008-12-10 05:08:54 +0000668 }
669};
670
671// Implements the Return() action.
672class ReturnVoidAction {
673 public:
674 // Allows Return() to be used in any void-returning function.
675 template <typename Result, typename ArgumentTuple>
676 static void Perform(const ArgumentTuple&) {
677 CompileAssertTypesEqual<void, Result>();
678 }
679};
680
681// Implements the polymorphic ReturnRef(x) action, which can be used
682// in any function that returns a reference to the type of x,
683// regardless of the argument types.
684template <typename T>
685class ReturnRefAction {
686 public:
687 // Constructs a ReturnRefAction object from the reference to be returned.
688 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
689
690 // This template type conversion operator allows ReturnRef(x) to be
691 // used in ANY function that returns a reference to x's type.
692 template <typename F>
693 operator Action<F>() const {
694 typedef typename Function<F>::Result Result;
695 // Asserts that the function return type is a reference. This
696 // catches the user error of using ReturnRef(x) when Return(x)
697 // should be used, and generates some helpful error message.
zhanyong.wan02f71062010-05-10 17:14:29 +0000698 GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
zhanyong.wane0d051e2009-02-19 00:33:37 +0000699 use_Return_instead_of_ReturnRef_to_return_a_value);
shiqiane35fdd92008-12-10 05:08:54 +0000700 return Action<F>(new Impl<F>(ref_));
701 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000702
shiqiane35fdd92008-12-10 05:08:54 +0000703 private:
704 // Implements the ReturnRef(x) action for a particular function type F.
705 template <typename F>
706 class Impl : public ActionInterface<F> {
707 public:
708 typedef typename Function<F>::Result Result;
709 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
710
711 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
712
713 virtual Result Perform(const ArgumentTuple&) {
714 return ref_;
715 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000716
shiqiane35fdd92008-12-10 05:08:54 +0000717 private:
718 T& ref_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000719
720 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000721 };
722
723 T& ref_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000724
725 GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
shiqiane35fdd92008-12-10 05:08:54 +0000726};
727
zhanyong.wane3bd0982010-07-03 00:16:42 +0000728// Implements the polymorphic ReturnRefOfCopy(x) action, which can be
729// used in any function that returns a reference to the type of x,
730// regardless of the argument types.
731template <typename T>
732class ReturnRefOfCopyAction {
733 public:
734 // Constructs a ReturnRefOfCopyAction object from the reference to
735 // be returned.
736 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
737
738 // This template type conversion operator allows ReturnRefOfCopy(x) to be
739 // used in ANY function that returns a reference to x's type.
740 template <typename F>
741 operator Action<F>() const {
742 typedef typename Function<F>::Result Result;
743 // Asserts that the function return type is a reference. This
744 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
745 // should be used, and generates some helpful error message.
746 GTEST_COMPILE_ASSERT_(
747 internal::is_reference<Result>::value,
748 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
749 return Action<F>(new Impl<F>(value_));
750 }
751
752 private:
753 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
754 template <typename F>
755 class Impl : public ActionInterface<F> {
756 public:
757 typedef typename Function<F>::Result Result;
758 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
759
760 explicit Impl(const T& value) : value_(value) {} // NOLINT
761
762 virtual Result Perform(const ArgumentTuple&) {
763 return value_;
764 }
765
766 private:
767 T value_;
768
769 GTEST_DISALLOW_ASSIGN_(Impl);
770 };
771
772 const T value_;
773
774 GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
775};
776
shiqiane35fdd92008-12-10 05:08:54 +0000777// Implements the polymorphic DoDefault() action.
778class DoDefaultAction {
779 public:
780 // This template type conversion operator allows DoDefault() to be
781 // used in any function.
782 template <typename F>
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400783 operator Action<F>() const { return Action<F>(); } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000784};
785
786// Implements the Assign action to set a given pointer referent to a
787// particular value.
788template <typename T1, typename T2>
789class AssignAction {
790 public:
791 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
792
793 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000794 void Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000795 *ptr_ = value_;
796 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000797
shiqiane35fdd92008-12-10 05:08:54 +0000798 private:
799 T1* const ptr_;
800 const T2 value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000801
802 GTEST_DISALLOW_ASSIGN_(AssignAction);
shiqiane35fdd92008-12-10 05:08:54 +0000803};
804
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000805#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000806
shiqiane35fdd92008-12-10 05:08:54 +0000807// Implements the SetErrnoAndReturn action to simulate return from
808// various system calls and libc functions.
809template <typename T>
810class SetErrnoAndReturnAction {
811 public:
812 SetErrnoAndReturnAction(int errno_value, T result)
813 : errno_(errno_value),
814 result_(result) {}
815 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000816 Result Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000817 errno = errno_;
818 return result_;
819 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000820
shiqiane35fdd92008-12-10 05:08:54 +0000821 private:
822 const int errno_;
823 const T result_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000824
825 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
shiqiane35fdd92008-12-10 05:08:54 +0000826};
827
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000828#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000829
shiqiane35fdd92008-12-10 05:08:54 +0000830// Implements the SetArgumentPointee<N>(x) action for any function
831// whose N-th argument (0-based) is a pointer to x's type. The
832// template parameter kIsProto is true iff type A is ProtocolMessage,
833// proto2::Message, or a sub-class of those.
834template <size_t N, typename A, bool kIsProto>
835class SetArgumentPointeeAction {
836 public:
837 // Constructs an action that sets the variable pointed to by the
838 // N-th function argument to 'value'.
839 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
840
841 template <typename Result, typename ArgumentTuple>
842 void Perform(const ArgumentTuple& args) const {
843 CompileAssertTypesEqual<void, Result>();
kosakbd018832014-04-02 20:30:00 +0000844 *::testing::get<N>(args) = value_;
shiqiane35fdd92008-12-10 05:08:54 +0000845 }
846
847 private:
848 const A value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000849
850 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
shiqiane35fdd92008-12-10 05:08:54 +0000851};
852
853template <size_t N, typename Proto>
854class SetArgumentPointeeAction<N, Proto, true> {
855 public:
856 // Constructs an action that sets the variable pointed to by the
857 // N-th function argument to 'proto'. Both ProtocolMessage and
858 // proto2::Message have the CopyFrom() method, so the same
859 // implementation works for both.
860 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
861 proto_->CopyFrom(proto);
862 }
863
864 template <typename Result, typename ArgumentTuple>
865 void Perform(const ArgumentTuple& args) const {
866 CompileAssertTypesEqual<void, Result>();
kosakbd018832014-04-02 20:30:00 +0000867 ::testing::get<N>(args)->CopyFrom(*proto_);
shiqiane35fdd92008-12-10 05:08:54 +0000868 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000869
shiqiane35fdd92008-12-10 05:08:54 +0000870 private:
871 const internal::linked_ptr<Proto> proto_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000872
873 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
shiqiane35fdd92008-12-10 05:08:54 +0000874};
875
shiqiane35fdd92008-12-10 05:08:54 +0000876// Implements the InvokeWithoutArgs(f) action. The template argument
877// FunctionImpl is the implementation type of f, which can be either a
878// function pointer or a functor. InvokeWithoutArgs(f) can be used as an
879// Action<F> as long as f's type is compatible with F (i.e. f can be
880// assigned to a tr1::function<F>).
881template <typename FunctionImpl>
882class InvokeWithoutArgsAction {
883 public:
884 // The c'tor makes a copy of function_impl (either a function
885 // pointer or a functor).
886 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
887 : function_impl_(function_impl) {}
888
889 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
890 // compatible with f.
891 template <typename Result, typename ArgumentTuple>
892 Result Perform(const ArgumentTuple&) { return function_impl_(); }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000893
shiqiane35fdd92008-12-10 05:08:54 +0000894 private:
895 FunctionImpl function_impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000896
897 GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
shiqiane35fdd92008-12-10 05:08:54 +0000898};
899
900// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
901template <class Class, typename MethodPtr>
902class InvokeMethodWithoutArgsAction {
903 public:
904 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
905 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
906
907 template <typename Result, typename ArgumentTuple>
908 Result Perform(const ArgumentTuple&) const {
909 return (obj_ptr_->*method_ptr_)();
910 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000911
shiqiane35fdd92008-12-10 05:08:54 +0000912 private:
913 Class* const obj_ptr_;
914 const MethodPtr method_ptr_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000915
916 GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
shiqiane35fdd92008-12-10 05:08:54 +0000917};
918
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400919// Implements the InvokeWithoutArgs(callback) action.
920template <typename CallbackType>
921class InvokeCallbackWithoutArgsAction {
922 public:
923 // The c'tor takes ownership of the callback.
924 explicit InvokeCallbackWithoutArgsAction(CallbackType* callback)
925 : callback_(callback) {
926 callback->CheckIsRepeatable(); // Makes sure the callback is permanent.
927 }
928
929 // This type conversion operator template allows Invoke(callback) to
930 // be used wherever the callback's return type can be implicitly
931 // converted to that of the mock function.
932 template <typename Result, typename ArgumentTuple>
933 Result Perform(const ArgumentTuple&) const { return callback_->Run(); }
934
935 private:
936 const internal::linked_ptr<CallbackType> callback_;
937
938 GTEST_DISALLOW_ASSIGN_(InvokeCallbackWithoutArgsAction);
939};
940
shiqiane35fdd92008-12-10 05:08:54 +0000941// Implements the IgnoreResult(action) action.
942template <typename A>
943class IgnoreResultAction {
944 public:
945 explicit IgnoreResultAction(const A& action) : action_(action) {}
946
947 template <typename F>
948 operator Action<F>() const {
949 // Assert statement belongs here because this is the best place to verify
950 // conditions on F. It produces the clearest error messages
951 // in most compilers.
952 // Impl really belongs in this scope as a local class but can't
953 // because MSVC produces duplicate symbols in different translation units
954 // in this case. Until MS fixes that bug we put Impl into the class scope
955 // and put the typedef both here (for use in assert statement) and
956 // in the Impl class. But both definitions must be the same.
957 typedef typename internal::Function<F>::Result Result;
958
959 // Asserts at compile time that F returns void.
960 CompileAssertTypesEqual<void, Result>();
961
962 return Action<F>(new Impl<F>(action_));
963 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000964
shiqiane35fdd92008-12-10 05:08:54 +0000965 private:
966 template <typename F>
967 class Impl : public ActionInterface<F> {
968 public:
969 typedef typename internal::Function<F>::Result Result;
970 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
971
972 explicit Impl(const A& action) : action_(action) {}
973
974 virtual void Perform(const ArgumentTuple& args) {
975 // Performs the action and ignores its result.
976 action_.Perform(args);
977 }
978
979 private:
980 // Type OriginalFunction is the same as F except that its return
981 // type is IgnoredValue.
982 typedef typename internal::Function<F>::MakeResultIgnoredValue
983 OriginalFunction;
984
985 const Action<OriginalFunction> action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000986
987 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000988 };
989
990 const A action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000991
992 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
shiqiane35fdd92008-12-10 05:08:54 +0000993};
994
zhanyong.wana18423e2009-07-22 23:58:19 +0000995// A ReferenceWrapper<T> object represents a reference to type T,
996// which can be either const or not. It can be explicitly converted
997// from, and implicitly converted to, a T&. Unlike a reference,
998// ReferenceWrapper<T> can be copied and can survive template type
999// inference. This is used to support by-reference arguments in the
1000// InvokeArgument<N>(...) action. The idea was from "reference
1001// wrappers" in tr1, which we don't have in our source tree yet.
1002template <typename T>
1003class ReferenceWrapper {
1004 public:
1005 // Constructs a ReferenceWrapper<T> object from a T&.
1006 explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
1007
1008 // Allows a ReferenceWrapper<T> object to be implicitly converted to
1009 // a T&.
1010 operator T&() const { return *pointer_; }
1011 private:
1012 T* pointer_;
1013};
1014
1015// Allows the expression ByRef(x) to be printed as a reference to x.
1016template <typename T>
1017void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
1018 T& value = ref;
1019 UniversalPrinter<T&>::Print(value, os);
1020}
1021
1022// Does two actions sequentially. Used for implementing the DoAll(a1,
1023// a2, ...) action.
1024template <typename Action1, typename Action2>
1025class DoBothAction {
1026 public:
1027 DoBothAction(Action1 action1, Action2 action2)
1028 : action1_(action1), action2_(action2) {}
1029
1030 // This template type conversion operator allows DoAll(a1, ..., a_n)
1031 // to be used in ANY function of compatible type.
1032 template <typename F>
1033 operator Action<F>() const {
1034 return Action<F>(new Impl<F>(action1_, action2_));
1035 }
1036
1037 private:
1038 // Implements the DoAll(...) action for a particular function type F.
1039 template <typename F>
1040 class Impl : public ActionInterface<F> {
1041 public:
1042 typedef typename Function<F>::Result Result;
1043 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1044 typedef typename Function<F>::MakeResultVoid VoidResult;
1045
1046 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
1047 : action1_(action1), action2_(action2) {}
1048
1049 virtual Result Perform(const ArgumentTuple& args) {
1050 action1_.Perform(args);
1051 return action2_.Perform(args);
1052 }
1053
1054 private:
1055 const Action<VoidResult> action1_;
1056 const Action<F> action2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001057
1058 GTEST_DISALLOW_ASSIGN_(Impl);
zhanyong.wana18423e2009-07-22 23:58:19 +00001059 };
1060
1061 Action1 action1_;
1062 Action2 action2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001063
1064 GTEST_DISALLOW_ASSIGN_(DoBothAction);
zhanyong.wana18423e2009-07-22 23:58:19 +00001065};
1066
shiqiane35fdd92008-12-10 05:08:54 +00001067} // namespace internal
1068
1069// An Unused object can be implicitly constructed from ANY value.
1070// This is handy when defining actions that ignore some or all of the
1071// mock function arguments. For example, given
1072//
1073// MOCK_METHOD3(Foo, double(const string& label, double x, double y));
1074// MOCK_METHOD3(Bar, double(int index, double x, double y));
1075//
1076// instead of
1077//
1078// double DistanceToOriginWithLabel(const string& label, double x, double y) {
1079// return sqrt(x*x + y*y);
1080// }
1081// double DistanceToOriginWithIndex(int index, double x, double y) {
1082// return sqrt(x*x + y*y);
1083// }
1084// ...
Hector Dearman41ad2432017-06-19 18:43:55 +01001085// EXPECT_CALL(mock, Foo("abc", _, _))
shiqiane35fdd92008-12-10 05:08:54 +00001086// .WillOnce(Invoke(DistanceToOriginWithLabel));
Hector Dearman41ad2432017-06-19 18:43:55 +01001087// EXPECT_CALL(mock, Bar(5, _, _))
shiqiane35fdd92008-12-10 05:08:54 +00001088// .WillOnce(Invoke(DistanceToOriginWithIndex));
1089//
1090// you could write
1091//
1092// // We can declare any uninteresting argument as Unused.
1093// double DistanceToOrigin(Unused, double x, double y) {
1094// return sqrt(x*x + y*y);
1095// }
1096// ...
Hector Dearman41ad2432017-06-19 18:43:55 +01001097// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
1098// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
shiqiane35fdd92008-12-10 05:08:54 +00001099typedef internal::IgnoredValue Unused;
1100
1101// This constructor allows us to turn an Action<From> object into an
1102// Action<To>, as long as To's arguments can be implicitly converted
1103// to From's and From's return type cann be implicitly converted to
1104// To's.
1105template <typename To>
1106template <typename From>
1107Action<To>::Action(const Action<From>& from)
Gennadiy Civil8654c1c2018-04-11 15:33:31 -04001108 :
1109#if GTEST_LANG_CXX11
1110 fun_(from.fun_),
1111#endif
1112 impl_(from.impl_ == NULL ? NULL
1113 : new internal::ActionAdaptor<To, From>(from)) {
1114}
shiqiane35fdd92008-12-10 05:08:54 +00001115
1116// Creates an action that returns 'value'. 'value' is passed by value
1117// instead of const reference - otherwise Return("string literal")
1118// will trigger a compiler error about using array as initializer.
1119template <typename R>
1120internal::ReturnAction<R> Return(R value) {
kosak3d1c78b2014-11-17 00:56:52 +00001121 return internal::ReturnAction<R>(internal::move(value));
shiqiane35fdd92008-12-10 05:08:54 +00001122}
1123
1124// Creates an action that returns NULL.
1125inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1126 return MakePolymorphicAction(internal::ReturnNullAction());
1127}
1128
1129// Creates an action that returns from a void function.
1130inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1131 return MakePolymorphicAction(internal::ReturnVoidAction());
1132}
1133
1134// Creates an action that returns the reference to a variable.
1135template <typename R>
1136inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
1137 return internal::ReturnRefAction<R>(x);
1138}
1139
zhanyong.wane3bd0982010-07-03 00:16:42 +00001140// Creates an action that returns the reference to a copy of the
1141// argument. The copy is created when the action is constructed and
1142// lives as long as the action.
1143template <typename R>
1144inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1145 return internal::ReturnRefOfCopyAction<R>(x);
1146}
1147
kosak3d1c78b2014-11-17 00:56:52 +00001148// Modifies the parent action (a Return() action) to perform a move of the
1149// argument instead of a copy.
1150// Return(ByMove()) actions can only be executed once and will assert this
1151// invariant.
1152template <typename R>
1153internal::ByMoveWrapper<R> ByMove(R x) {
1154 return internal::ByMoveWrapper<R>(internal::move(x));
1155}
1156
shiqiane35fdd92008-12-10 05:08:54 +00001157// Creates an action that does the default action for the give mock function.
1158inline internal::DoDefaultAction DoDefault() {
1159 return internal::DoDefaultAction();
1160}
1161
1162// Creates an action that sets the variable pointed by the N-th
1163// (0-based) function argument to 'value'.
1164template <size_t N, typename T>
1165PolymorphicAction<
1166 internal::SetArgumentPointeeAction<
1167 N, T, internal::IsAProtocolMessage<T>::value> >
zhanyong.wan59214832010-10-05 05:58:51 +00001168SetArgPointee(const T& x) {
1169 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1170 N, T, internal::IsAProtocolMessage<T>::value>(x));
1171}
zhanyong.wanfc8c6c42011-03-09 01:18:08 +00001172
1173#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
zhanyong.wana684b5a2010-12-02 23:30:50 +00001174// This overload allows SetArgPointee() to accept a string literal.
zhanyong.wanfc8c6c42011-03-09 01:18:08 +00001175// GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish
1176// this overload from the templated version and emit a compile error.
zhanyong.wana684b5a2010-12-02 23:30:50 +00001177template <size_t N>
1178PolymorphicAction<
1179 internal::SetArgumentPointeeAction<N, const char*, false> >
1180SetArgPointee(const char* p) {
1181 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1182 N, const char*, false>(p));
1183}
zhanyong.wanfc8c6c42011-03-09 01:18:08 +00001184
1185template <size_t N>
1186PolymorphicAction<
1187 internal::SetArgumentPointeeAction<N, const wchar_t*, false> >
1188SetArgPointee(const wchar_t* p) {
1189 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1190 N, const wchar_t*, false>(p));
1191}
1192#endif
1193
zhanyong.wan59214832010-10-05 05:58:51 +00001194// The following version is DEPRECATED.
1195template <size_t N, typename T>
1196PolymorphicAction<
1197 internal::SetArgumentPointeeAction<
1198 N, T, internal::IsAProtocolMessage<T>::value> >
shiqiane35fdd92008-12-10 05:08:54 +00001199SetArgumentPointee(const T& x) {
1200 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1201 N, T, internal::IsAProtocolMessage<T>::value>(x));
1202}
1203
shiqiane35fdd92008-12-10 05:08:54 +00001204// Creates an action that sets a pointer referent to a given value.
1205template <typename T1, typename T2>
1206PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
1207 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1208}
1209
zhanyong.wanf7af24c2009-09-24 21:17:24 +00001210#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +00001211
shiqiane35fdd92008-12-10 05:08:54 +00001212// Creates an action that sets errno and returns the appropriate error.
1213template <typename T>
1214PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
1215SetErrnoAndReturn(int errval, T result) {
1216 return MakePolymorphicAction(
1217 internal::SetErrnoAndReturnAction<T>(errval, result));
1218}
1219
zhanyong.wanf7af24c2009-09-24 21:17:24 +00001220#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +00001221
shiqiane35fdd92008-12-10 05:08:54 +00001222// Various overloads for InvokeWithoutArgs().
1223
1224// Creates an action that invokes 'function_impl' with no argument.
1225template <typename FunctionImpl>
1226PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
1227InvokeWithoutArgs(FunctionImpl function_impl) {
1228 return MakePolymorphicAction(
1229 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
1230}
1231
1232// Creates an action that invokes the given method on the given object
1233// with no argument.
1234template <class Class, typename MethodPtr>
1235PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
1236InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
1237 return MakePolymorphicAction(
1238 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
1239 obj_ptr, method_ptr));
1240}
1241
1242// Creates an action that performs an_action and throws away its
1243// result. In other words, it changes the return type of an_action to
1244// void. an_action MUST NOT return void, or the code won't compile.
1245template <typename A>
1246inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1247 return internal::IgnoreResultAction<A>(an_action);
1248}
1249
zhanyong.wana18423e2009-07-22 23:58:19 +00001250// Creates a reference wrapper for the given L-value. If necessary,
1251// you can explicitly specify the type of the reference. For example,
1252// suppose 'derived' is an object of type Derived, ByRef(derived)
1253// would wrap a Derived&. If you want to wrap a const Base& instead,
1254// where Base is a base class of Derived, just write:
1255//
1256// ByRef<const Base>(derived)
1257template <typename T>
1258inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
1259 return internal::ReferenceWrapper<T>(l_value);
1260}
1261
shiqiane35fdd92008-12-10 05:08:54 +00001262} // namespace testing
1263
1264#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_