blob: b82313d5b05c94e3c0e2dd82b36d1462e38b2439 [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.
Gennadiy Civila3c0dd02018-08-14 14:04:07 -040029
shiqiane35fdd92008-12-10 05:08:54 +000030
31// Google Mock - a framework for writing C++ mock classes.
32//
33// This file implements some commonly used actions.
34
Gennadiy Civil984cba32018-07-27 11:15:08 -040035// GOOGLETEST_CM0002 DO NOT DELETE
36
shiqiane35fdd92008-12-10 05:08:54 +000037#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
38#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
39
zhanyong.wan5b5d62f2009-03-11 23:37:56 +000040#ifndef _WIN32_WCE
zhanyong.wan658ac0b2011-02-24 07:29:13 +000041# include <errno.h>
zhanyong.wan5b5d62f2009-03-11 23:37:56 +000042#endif
43
jgm79a367e2012-04-10 16:02:11 +000044#include <algorithm>
45#include <string>
46
zhanyong.wan53e08c42010-09-14 05:38:21 +000047#include "gmock/internal/gmock-internal-utils.h"
48#include "gmock/internal/gmock-port.h"
shiqiane35fdd92008-12-10 05:08:54 +000049
Gennadiy Civilaf463c42018-03-13 11:13:37 -040050#if GTEST_LANG_CXX11 // Defined by gtest-port.h via gmock-port.h.
51#include <functional>
kosakd478a1f2015-02-14 02:45:40 +000052#include <type_traits>
Gennadiy Civilaf463c42018-03-13 11:13:37 -040053#endif // GTEST_LANG_CXX11
kosakd478a1f2015-02-14 02:45:40 +000054
shiqiane35fdd92008-12-10 05:08:54 +000055namespace testing {
56
57// To implement an action Foo, define:
58// 1. a class FooAction that implements the ActionInterface interface, and
59// 2. a factory function that creates an Action object from a
60// const FooAction*.
61//
62// The two-level delegation design follows that of Matcher, providing
63// consistency for extension developers. It also eases ownership
64// management as Action objects can now be copied like plain values.
65
66namespace internal {
67
shiqiane35fdd92008-12-10 05:08:54 +000068template <typename F1, typename F2>
69class ActionAdaptor;
70
kosakd478a1f2015-02-14 02:45:40 +000071// BuiltInDefaultValueGetter<T, true>::Get() returns a
72// default-constructed T value. BuiltInDefaultValueGetter<T,
73// false>::Get() crashes with an error.
74//
75// This primary template is used when kDefaultConstructible is true.
76template <typename T, bool kDefaultConstructible>
77struct BuiltInDefaultValueGetter {
78 static T Get() { return T(); }
79};
shiqiane35fdd92008-12-10 05:08:54 +000080template <typename T>
kosakd478a1f2015-02-14 02:45:40 +000081struct BuiltInDefaultValueGetter<T, false> {
shiqiane35fdd92008-12-10 05:08:54 +000082 static T Get() {
83 Assert(false, __FILE__, __LINE__,
84 "Default action undefined for the function return type.");
85 return internal::Invalid<T>();
86 // The above statement will never be reached, but is required in
87 // order for this function to compile.
88 }
89};
90
kosakd478a1f2015-02-14 02:45:40 +000091// BuiltInDefaultValue<T>::Get() returns the "built-in" default value
92// for type T, which is NULL when T is a raw pointer type, 0 when T is
93// a numeric type, false when T is bool, or "" when T is string or
94// std::string. In addition, in C++11 and above, it turns a
95// default-constructed T value if T is default constructible. For any
96// other type T, the built-in default T value is undefined, and the
97// function will abort the process.
98template <typename T>
99class BuiltInDefaultValue {
100 public:
Gennadiy Civilaf463c42018-03-13 11:13:37 -0400101#if GTEST_LANG_CXX11
kosakd478a1f2015-02-14 02:45:40 +0000102 // This function returns true iff type T has a built-in default value.
103 static bool Exists() {
104 return ::std::is_default_constructible<T>::value;
105 }
106
107 static T Get() {
108 return BuiltInDefaultValueGetter<
109 T, ::std::is_default_constructible<T>::value>::Get();
110 }
111
Gennadiy Civilaf463c42018-03-13 11:13:37 -0400112#else // GTEST_LANG_CXX11
kosakd478a1f2015-02-14 02:45:40 +0000113 // This function returns true iff type T has a built-in default value.
114 static bool Exists() {
115 return false;
116 }
117
118 static T Get() {
119 return BuiltInDefaultValueGetter<T, false>::Get();
120 }
121
Gennadiy Civilaf463c42018-03-13 11:13:37 -0400122#endif // GTEST_LANG_CXX11
kosakd478a1f2015-02-14 02:45:40 +0000123};
124
shiqiane35fdd92008-12-10 05:08:54 +0000125// This partial specialization says that we use the same built-in
126// default value for T and const T.
127template <typename T>
128class BuiltInDefaultValue<const T> {
129 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000130 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
shiqiane35fdd92008-12-10 05:08:54 +0000131 static T Get() { return BuiltInDefaultValue<T>::Get(); }
132};
133
134// This partial specialization defines the default values for pointer
135// types.
136template <typename T>
137class BuiltInDefaultValue<T*> {
138 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000139 static bool Exists() { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000140 static T* Get() { return NULL; }
141};
142
143// The following specializations define the default values for
144// specific types we care about.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000145#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
shiqiane35fdd92008-12-10 05:08:54 +0000146 template <> \
147 class BuiltInDefaultValue<type> { \
148 public: \
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000149 static bool Exists() { return true; } \
shiqiane35fdd92008-12-10 05:08:54 +0000150 static type Get() { return value; } \
151 }
152
zhanyong.wane0d051e2009-02-19 00:33:37 +0000153GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000154#if GTEST_HAS_GLOBAL_STRING
zhanyong.wane0d051e2009-02-19 00:33:37 +0000155GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
shiqiane35fdd92008-12-10 05:08:54 +0000156#endif // GTEST_HAS_GLOBAL_STRING
zhanyong.wane0d051e2009-02-19 00:33:37 +0000157GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
zhanyong.wane0d051e2009-02-19 00:33:37 +0000158GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
159GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
160GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
161GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
shiqiane35fdd92008-12-10 05:08:54 +0000162
shiqiane35fdd92008-12-10 05:08:54 +0000163// There's no need for a default action for signed wchar_t, as that
164// type is the same as wchar_t for gcc, and invalid for MSVC.
165//
166// There's also no need for a default action for unsigned wchar_t, as
167// that type is the same as unsigned int for gcc, and invalid for
168// MSVC.
zhanyong.wan95b12332009-09-25 18:55:50 +0000169#if GMOCK_WCHAR_T_IS_NATIVE_
zhanyong.wane0d051e2009-02-19 00:33:37 +0000170GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000171#endif
172
zhanyong.wane0d051e2009-02-19 00:33:37 +0000173GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
174GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
175GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
176GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
177GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
178GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
179GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
180GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
181GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
182GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
shiqiane35fdd92008-12-10 05:08:54 +0000183
zhanyong.wane0d051e2009-02-19 00:33:37 +0000184#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
shiqiane35fdd92008-12-10 05:08:54 +0000185
186} // namespace internal
187
188// When an unexpected function call is encountered, Google Mock will
189// let it return a default value if the user has specified one for its
190// return type, or if the return type has a built-in default value;
191// otherwise Google Mock won't know what value to return and will have
192// to abort the process.
193//
194// The DefaultValue<T> class allows a user to specify the
195// default value for a type T that is both copyable and publicly
196// destructible (i.e. anything that can be used as a function return
197// type). The usage is:
198//
199// // Sets the default value for type T to be foo.
200// DefaultValue<T>::Set(foo);
201template <typename T>
202class DefaultValue {
203 public:
204 // Sets the default value for type T; requires T to be
205 // copy-constructable and have a public destructor.
206 static void Set(T x) {
kosakb5c81092014-01-29 06:41:44 +0000207 delete producer_;
208 producer_ = new FixedValueProducer(x);
209 }
210
211 // Provides a factory function to be called to generate the default value.
212 // This method can be used even if T is only move-constructible, but it is not
213 // limited to that case.
214 typedef T (*FactoryFunction)();
215 static void SetFactory(FactoryFunction factory) {
216 delete producer_;
217 producer_ = new FactoryValueProducer(factory);
shiqiane35fdd92008-12-10 05:08:54 +0000218 }
219
220 // Unsets the default value for type T.
221 static void Clear() {
kosakb5c81092014-01-29 06:41:44 +0000222 delete producer_;
223 producer_ = NULL;
shiqiane35fdd92008-12-10 05:08:54 +0000224 }
225
226 // Returns true iff the user has set the default value for type T.
kosakb5c81092014-01-29 06:41:44 +0000227 static bool IsSet() { return producer_ != NULL; }
shiqiane35fdd92008-12-10 05:08:54 +0000228
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000229 // Returns true if T has a default return value set by the user or there
230 // exists a built-in default value.
231 static bool Exists() {
232 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
233 }
234
shiqiane35fdd92008-12-10 05:08:54 +0000235 // Returns the default value for type T if the user has set one;
kosakb5c81092014-01-29 06:41:44 +0000236 // otherwise returns the built-in default value. Requires that Exists()
237 // is true, which ensures that the return value is well-defined.
shiqiane35fdd92008-12-10 05:08:54 +0000238 static T Get() {
kosakb5c81092014-01-29 06:41:44 +0000239 return producer_ == NULL ?
240 internal::BuiltInDefaultValue<T>::Get() : producer_->Produce();
shiqiane35fdd92008-12-10 05:08:54 +0000241 }
jgm79a367e2012-04-10 16:02:11 +0000242
shiqiane35fdd92008-12-10 05:08:54 +0000243 private:
kosakb5c81092014-01-29 06:41:44 +0000244 class ValueProducer {
245 public:
246 virtual ~ValueProducer() {}
247 virtual T Produce() = 0;
248 };
249
250 class FixedValueProducer : public ValueProducer {
251 public:
252 explicit FixedValueProducer(T value) : value_(value) {}
253 virtual T Produce() { return value_; }
254
255 private:
256 const T value_;
257 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
258 };
259
260 class FactoryValueProducer : public ValueProducer {
261 public:
262 explicit FactoryValueProducer(FactoryFunction factory)
263 : factory_(factory) {}
264 virtual T Produce() { return factory_(); }
265
266 private:
267 const FactoryFunction factory_;
268 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
269 };
270
271 static ValueProducer* producer_;
shiqiane35fdd92008-12-10 05:08:54 +0000272};
273
274// This partial specialization allows a user to set default values for
275// reference types.
276template <typename T>
277class DefaultValue<T&> {
278 public:
279 // Sets the default value for type T&.
280 static void Set(T& x) { // NOLINT
281 address_ = &x;
282 }
283
284 // Unsets the default value for type T&.
285 static void Clear() {
286 address_ = NULL;
287 }
288
289 // Returns true iff the user has set the default value for type T&.
290 static bool IsSet() { return address_ != NULL; }
291
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000292 // Returns true if T has a default return value set by the user or there
293 // exists a built-in default value.
294 static bool Exists() {
295 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
296 }
297
shiqiane35fdd92008-12-10 05:08:54 +0000298 // Returns the default value for type T& if the user has set one;
299 // otherwise returns the built-in default value if there is one;
300 // otherwise aborts the process.
301 static T& Get() {
302 return address_ == NULL ?
303 internal::BuiltInDefaultValue<T&>::Get() : *address_;
304 }
jgm79a367e2012-04-10 16:02:11 +0000305
shiqiane35fdd92008-12-10 05:08:54 +0000306 private:
307 static T* address_;
308};
309
310// This specialization allows DefaultValue<void>::Get() to
311// compile.
312template <>
313class DefaultValue<void> {
314 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000315 static bool Exists() { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000316 static void Get() {}
317};
318
319// Points to the user-set default value for type T.
320template <typename T>
kosakb5c81092014-01-29 06:41:44 +0000321typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL;
shiqiane35fdd92008-12-10 05:08:54 +0000322
323// Points to the user-set default value for type T&.
324template <typename T>
325T* DefaultValue<T&>::address_ = NULL;
326
327// Implement this interface to define an action for function type F.
328template <typename F>
329class ActionInterface {
330 public:
331 typedef typename internal::Function<F>::Result Result;
332 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
333
zhanyong.waned6c9272011-02-23 19:39:27 +0000334 ActionInterface() {}
shiqiane35fdd92008-12-10 05:08:54 +0000335 virtual ~ActionInterface() {}
336
337 // Performs the action. This method is not const, as in general an
338 // action can have side effects and be stateful. For example, a
339 // get-the-next-element-from-the-collection action will need to
340 // remember the current element.
341 virtual Result Perform(const ArgumentTuple& args) = 0;
342
shiqiane35fdd92008-12-10 05:08:54 +0000343 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000344 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
shiqiane35fdd92008-12-10 05:08:54 +0000345};
346
347// An Action<F> is a copyable and IMMUTABLE (except by assignment)
348// object that represents an action to be taken when a mock function
349// of type F is called. The implementation of Action<T> is just a
350// linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
351// Don't inherit from Action!
352//
353// You can view an object implementing ActionInterface<F> as a
354// concrete action (including its current state), and an Action<F>
355// object as a handle to it.
356template <typename F>
357class Action {
358 public:
359 typedef typename internal::Function<F>::Result Result;
360 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
361
362 // Constructs a null Action. Needed for storing Action objects in
363 // STL containers.
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400364 Action() {}
shiqiane35fdd92008-12-10 05:08:54 +0000365
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400366#if GTEST_LANG_CXX11
367 // Construct an Action from a specified callable.
368 // This cannot take std::function directly, because then Action would not be
369 // directly constructible from lambda (it would require two conversions).
370 template <typename G,
371 typename = typename ::std::enable_if<
372 ::std::is_constructible<::std::function<F>, G>::value>::type>
373 Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
374#endif
375
376 // Constructs an Action from its implementation.
shiqiane35fdd92008-12-10 05:08:54 +0000377 explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
378
shiqiane35fdd92008-12-10 05:08:54 +0000379 // This constructor allows us to turn an Action<Func> object into an
380 // Action<F>, as long as F's arguments can be implicitly converted
vladloseva070cbd2009-11-18 00:09:28 +0000381 // to Func's and Func's return type can be implicitly converted to
shiqiane35fdd92008-12-10 05:08:54 +0000382 // F's.
383 template <typename Func>
384 explicit Action(const Action<Func>& action);
385
386 // Returns true iff this is the DoDefault() action.
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400387 bool IsDoDefault() const {
388#if GTEST_LANG_CXX11
389 return impl_ == nullptr && fun_ == nullptr;
390#else
391 return impl_ == NULL;
392#endif
393 }
shiqiane35fdd92008-12-10 05:08:54 +0000394
395 // Performs the action. Note that this method is const even though
396 // the corresponding method in ActionInterface is not. The reason
397 // is that a const Action<F> means that it cannot be re-bound to
398 // another concrete action, not that the concrete action it binds to
399 // cannot change state. (Think of the difference between a const
400 // pointer and a pointer to const.)
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400401 Result Perform(ArgumentTuple args) const {
402 if (IsDoDefault()) {
403 internal::IllegalDoDefault(__FILE__, __LINE__);
404 }
405#if GTEST_LANG_CXX11
406 if (fun_ != nullptr) {
407 return internal::Apply(fun_, ::std::move(args));
408 }
409#endif
shiqiane35fdd92008-12-10 05:08:54 +0000410 return impl_->Perform(args);
411 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000412
shiqiane35fdd92008-12-10 05:08:54 +0000413 private:
414 template <typename F1, typename F2>
415 friend class internal::ActionAdaptor;
416
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400417 template <typename G>
418 friend class Action;
419
420 // In C++11, Action can be implemented either as a generic functor (through
421 // std::function), or legacy ActionInterface. In C++98, only ActionInterface
422 // is available. The invariants are as follows:
423 // * in C++98, impl_ is null iff this is the default action
424 // * in C++11, at most one of fun_ & impl_ may be nonnull; both are null iff
425 // this is the default action
426#if GTEST_LANG_CXX11
427 ::std::function<F> fun_;
428#endif
shiqiane35fdd92008-12-10 05:08:54 +0000429 internal::linked_ptr<ActionInterface<F> > impl_;
430};
431
432// The PolymorphicAction class template makes it easy to implement a
433// polymorphic action (i.e. an action that can be used in mock
434// functions of than one type, e.g. Return()).
435//
436// To define a polymorphic action, a user first provides a COPYABLE
437// implementation class that has a Perform() method template:
438//
439// class FooAction {
440// public:
441// template <typename Result, typename ArgumentTuple>
442// Result Perform(const ArgumentTuple& args) const {
443// // Processes the arguments and returns a result, using
444// // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
445// }
446// ...
447// };
448//
449// Then the user creates the polymorphic action using
450// MakePolymorphicAction(object) where object has type FooAction. See
451// the definition of Return(void) and SetArgumentPointee<N>(value) for
452// complete examples.
453template <typename Impl>
454class PolymorphicAction {
455 public:
456 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
457
458 template <typename F>
459 operator Action<F>() const {
460 return Action<F>(new MonomorphicImpl<F>(impl_));
461 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000462
shiqiane35fdd92008-12-10 05:08:54 +0000463 private:
464 template <typename F>
465 class MonomorphicImpl : public ActionInterface<F> {
466 public:
467 typedef typename internal::Function<F>::Result Result;
468 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
469
470 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
471
472 virtual Result Perform(const ArgumentTuple& args) {
473 return impl_.template Perform<Result>(args);
474 }
475
476 private:
477 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000478
479 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000480 };
481
482 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000483
484 GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
shiqiane35fdd92008-12-10 05:08:54 +0000485};
486
487// Creates an Action from its implementation and returns it. The
488// created Action object owns the implementation.
489template <typename F>
490Action<F> MakeAction(ActionInterface<F>* impl) {
491 return Action<F>(impl);
492}
493
494// Creates a polymorphic action from its implementation. This is
495// easier to use than the PolymorphicAction<Impl> constructor as it
496// doesn't require you to explicitly write the template argument, e.g.
497//
498// MakePolymorphicAction(foo);
499// vs
500// PolymorphicAction<TypeOfFoo>(foo);
501template <typename Impl>
502inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
503 return PolymorphicAction<Impl>(impl);
504}
505
506namespace internal {
507
508// Allows an Action<F2> object to pose as an Action<F1>, as long as F2
509// and F1 are compatible.
510template <typename F1, typename F2>
511class ActionAdaptor : public ActionInterface<F1> {
512 public:
513 typedef typename internal::Function<F1>::Result Result;
514 typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
515
516 explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
517
518 virtual Result Perform(const ArgumentTuple& args) {
519 return impl_->Perform(args);
520 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000521
shiqiane35fdd92008-12-10 05:08:54 +0000522 private:
523 const internal::linked_ptr<ActionInterface<F2> > impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000524
525 GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
shiqiane35fdd92008-12-10 05:08:54 +0000526};
527
kosak3d1c78b2014-11-17 00:56:52 +0000528// Helper struct to specialize ReturnAction to execute a move instead of a copy
529// on return. Useful for move-only types, but could be used on any type.
530template <typename T>
531struct ByMoveWrapper {
kosakd370f852014-11-17 01:14:16 +0000532 explicit ByMoveWrapper(T value) : payload(internal::move(value)) {}
kosak3d1c78b2014-11-17 00:56:52 +0000533 T payload;
534};
535
shiqiane35fdd92008-12-10 05:08:54 +0000536// Implements the polymorphic Return(x) action, which can be used in
537// any function that returns the type of x, regardless of the argument
538// types.
vladloseva070cbd2009-11-18 00:09:28 +0000539//
540// Note: The value passed into Return must be converted into
541// Function<F>::Result when this action is cast to Action<F> rather than
542// when that action is performed. This is important in scenarios like
543//
544// MOCK_METHOD1(Method, T(U));
545// ...
546// {
547// Foo foo;
548// X x(&foo);
549// EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
550// }
551//
552// In the example above the variable x holds reference to foo which leaves
553// scope and gets destroyed. If copying X just copies a reference to foo,
554// that copy will be left with a hanging reference. If conversion to T
555// makes a copy of foo, the above code is safe. To support that scenario, we
556// need to make sure that the type conversion happens inside the EXPECT_CALL
557// statement, and conversion of the result of Return to Action<T(U)> is a
558// good place for that.
559//
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400560// The real life example of the above scenario happens when an invocation
561// of gtl::Container() is passed into Return.
562//
shiqiane35fdd92008-12-10 05:08:54 +0000563template <typename R>
564class ReturnAction {
565 public:
566 // Constructs a ReturnAction object from the value to be returned.
567 // 'value' is passed by value instead of by const reference in order
568 // to allow Return("string literal") to compile.
kosakd370f852014-11-17 01:14:16 +0000569 explicit ReturnAction(R value) : value_(new R(internal::move(value))) {}
shiqiane35fdd92008-12-10 05:08:54 +0000570
571 // This template type conversion operator allows Return(x) to be
572 // used in ANY function that returns x's type.
573 template <typename F>
574 operator Action<F>() const {
575 // Assert statement belongs here because this is the best place to verify
576 // conditions on F. It produces the clearest error messages
577 // in most compilers.
578 // Impl really belongs in this scope as a local class but can't
579 // because MSVC produces duplicate symbols in different translation units
580 // in this case. Until MS fixes that bug we put Impl into the class scope
581 // and put the typedef both here (for use in assert statement) and
582 // in the Impl class. But both definitions must be the same.
583 typedef typename Function<F>::Result Result;
zhanyong.wan02f71062010-05-10 17:14:29 +0000584 GTEST_COMPILE_ASSERT_(
kosak3d1c78b2014-11-17 00:56:52 +0000585 !is_reference<Result>::value,
zhanyong.wane0d051e2009-02-19 00:33:37 +0000586 use_ReturnRef_instead_of_Return_to_return_a_reference);
kosak3d1c78b2014-11-17 00:56:52 +0000587 return Action<F>(new Impl<R, F>(value_));
shiqiane35fdd92008-12-10 05:08:54 +0000588 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000589
shiqiane35fdd92008-12-10 05:08:54 +0000590 private:
591 // Implements the Return(x) action for a particular function type F.
kosak3d1c78b2014-11-17 00:56:52 +0000592 template <typename R_, typename F>
shiqiane35fdd92008-12-10 05:08:54 +0000593 class Impl : public ActionInterface<F> {
594 public:
595 typedef typename Function<F>::Result Result;
596 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
597
vladloseva070cbd2009-11-18 00:09:28 +0000598 // The implicit cast is necessary when Result has more than one
599 // single-argument constructor (e.g. Result is std::vector<int>) and R
600 // has a type conversion operator template. In that case, value_(value)
601 // won't compile as the compiler doesn't known which constructor of
zhanyong.wan5b61ce32011-02-01 00:00:03 +0000602 // Result to call. ImplicitCast_ forces the compiler to convert R to
vladloseva070cbd2009-11-18 00:09:28 +0000603 // Result without considering explicit constructors, thus resolving the
604 // ambiguity. value_ is then initialized using its copy constructor.
kosak3d1c78b2014-11-17 00:56:52 +0000605 explicit Impl(const linked_ptr<R>& value)
kosak7123d832014-11-17 02:04:46 +0000606 : value_before_cast_(*value),
607 value_(ImplicitCast_<Result>(value_before_cast_)) {}
shiqiane35fdd92008-12-10 05:08:54 +0000608
609 virtual Result Perform(const ArgumentTuple&) { return value_; }
610
611 private:
kosak3d1c78b2014-11-17 00:56:52 +0000612 GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
vladloseva070cbd2009-11-18 00:09:28 +0000613 Result_cannot_be_a_reference_type);
kosak7123d832014-11-17 02:04:46 +0000614 // We save the value before casting just in case it is being cast to a
615 // wrapper type.
616 R value_before_cast_;
vladloseva070cbd2009-11-18 00:09:28 +0000617 Result value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000618
kosak7123d832014-11-17 02:04:46 +0000619 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000620 };
621
kosak3d1c78b2014-11-17 00:56:52 +0000622 // Partially specialize for ByMoveWrapper. This version of ReturnAction will
623 // move its contents instead.
624 template <typename R_, typename F>
625 class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
626 public:
627 typedef typename Function<F>::Result Result;
628 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
629
630 explicit Impl(const linked_ptr<R>& wrapper)
631 : performed_(false), wrapper_(wrapper) {}
632
633 virtual Result Perform(const ArgumentTuple&) {
634 GTEST_CHECK_(!performed_)
635 << "A ByMove() action should only be performed once.";
636 performed_ = true;
kosakd370f852014-11-17 01:14:16 +0000637 return internal::move(wrapper_->payload);
kosak3d1c78b2014-11-17 00:56:52 +0000638 }
639
640 private:
641 bool performed_;
642 const linked_ptr<R> wrapper_;
643
644 GTEST_DISALLOW_ASSIGN_(Impl);
645 };
646
647 const linked_ptr<R> value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000648
649 GTEST_DISALLOW_ASSIGN_(ReturnAction);
shiqiane35fdd92008-12-10 05:08:54 +0000650};
651
652// Implements the ReturnNull() action.
653class ReturnNullAction {
654 public:
kosak53d49dc2015-01-08 03:03:09 +0000655 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
656 // this is enforced by returning nullptr, and in non-C++11 by asserting a
657 // pointer type on compile time.
shiqiane35fdd92008-12-10 05:08:54 +0000658 template <typename Result, typename ArgumentTuple>
659 static Result Perform(const ArgumentTuple&) {
kosak53d49dc2015-01-08 03:03:09 +0000660#if GTEST_LANG_CXX11
661 return nullptr;
662#else
zhanyong.wan02f71062010-05-10 17:14:29 +0000663 GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
zhanyong.wane0d051e2009-02-19 00:33:37 +0000664 ReturnNull_can_be_used_to_return_a_pointer_only);
shiqiane35fdd92008-12-10 05:08:54 +0000665 return NULL;
kosak53d49dc2015-01-08 03:03:09 +0000666#endif // GTEST_LANG_CXX11
shiqiane35fdd92008-12-10 05:08:54 +0000667 }
668};
669
670// Implements the Return() action.
671class ReturnVoidAction {
672 public:
673 // Allows Return() to be used in any void-returning function.
674 template <typename Result, typename ArgumentTuple>
675 static void Perform(const ArgumentTuple&) {
676 CompileAssertTypesEqual<void, Result>();
677 }
678};
679
680// Implements the polymorphic ReturnRef(x) action, which can be used
681// in any function that returns a reference to the type of x,
682// regardless of the argument types.
683template <typename T>
684class ReturnRefAction {
685 public:
686 // Constructs a ReturnRefAction object from the reference to be returned.
687 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
688
689 // This template type conversion operator allows ReturnRef(x) to be
690 // used in ANY function that returns a reference to x's type.
691 template <typename F>
692 operator Action<F>() const {
693 typedef typename Function<F>::Result Result;
694 // Asserts that the function return type is a reference. This
695 // catches the user error of using ReturnRef(x) when Return(x)
696 // should be used, and generates some helpful error message.
zhanyong.wan02f71062010-05-10 17:14:29 +0000697 GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
zhanyong.wane0d051e2009-02-19 00:33:37 +0000698 use_Return_instead_of_ReturnRef_to_return_a_value);
shiqiane35fdd92008-12-10 05:08:54 +0000699 return Action<F>(new Impl<F>(ref_));
700 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000701
shiqiane35fdd92008-12-10 05:08:54 +0000702 private:
703 // Implements the ReturnRef(x) action for a particular function type F.
704 template <typename F>
705 class Impl : public ActionInterface<F> {
706 public:
707 typedef typename Function<F>::Result Result;
708 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
709
710 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
711
712 virtual Result Perform(const ArgumentTuple&) {
713 return ref_;
714 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000715
shiqiane35fdd92008-12-10 05:08:54 +0000716 private:
717 T& ref_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000718
719 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000720 };
721
722 T& ref_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000723
724 GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
shiqiane35fdd92008-12-10 05:08:54 +0000725};
726
zhanyong.wane3bd0982010-07-03 00:16:42 +0000727// Implements the polymorphic ReturnRefOfCopy(x) action, which can be
728// used in any function that returns a reference to the type of x,
729// regardless of the argument types.
730template <typename T>
731class ReturnRefOfCopyAction {
732 public:
733 // Constructs a ReturnRefOfCopyAction object from the reference to
734 // be returned.
735 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
736
737 // This template type conversion operator allows ReturnRefOfCopy(x) to be
738 // used in ANY function that returns a reference to x's type.
739 template <typename F>
740 operator Action<F>() const {
741 typedef typename Function<F>::Result Result;
742 // Asserts that the function return type is a reference. This
743 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
744 // should be used, and generates some helpful error message.
745 GTEST_COMPILE_ASSERT_(
746 internal::is_reference<Result>::value,
747 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
748 return Action<F>(new Impl<F>(value_));
749 }
750
751 private:
752 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
753 template <typename F>
754 class Impl : public ActionInterface<F> {
755 public:
756 typedef typename Function<F>::Result Result;
757 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
758
759 explicit Impl(const T& value) : value_(value) {} // NOLINT
760
761 virtual Result Perform(const ArgumentTuple&) {
762 return value_;
763 }
764
765 private:
766 T value_;
767
768 GTEST_DISALLOW_ASSIGN_(Impl);
769 };
770
771 const T value_;
772
773 GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
774};
775
shiqiane35fdd92008-12-10 05:08:54 +0000776// Implements the polymorphic DoDefault() action.
777class DoDefaultAction {
778 public:
779 // This template type conversion operator allows DoDefault() to be
780 // used in any function.
781 template <typename F>
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400782 operator Action<F>() const { return Action<F>(); } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000783};
784
785// Implements the Assign action to set a given pointer referent to a
786// particular value.
787template <typename T1, typename T2>
788class AssignAction {
789 public:
790 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
791
792 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000793 void Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000794 *ptr_ = value_;
795 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000796
shiqiane35fdd92008-12-10 05:08:54 +0000797 private:
798 T1* const ptr_;
799 const T2 value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000800
801 GTEST_DISALLOW_ASSIGN_(AssignAction);
shiqiane35fdd92008-12-10 05:08:54 +0000802};
803
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000804#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000805
shiqiane35fdd92008-12-10 05:08:54 +0000806// Implements the SetErrnoAndReturn action to simulate return from
807// various system calls and libc functions.
808template <typename T>
809class SetErrnoAndReturnAction {
810 public:
811 SetErrnoAndReturnAction(int errno_value, T result)
812 : errno_(errno_value),
813 result_(result) {}
814 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000815 Result Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000816 errno = errno_;
817 return result_;
818 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000819
shiqiane35fdd92008-12-10 05:08:54 +0000820 private:
821 const int errno_;
822 const T result_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000823
824 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
shiqiane35fdd92008-12-10 05:08:54 +0000825};
826
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000827#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000828
shiqiane35fdd92008-12-10 05:08:54 +0000829// Implements the SetArgumentPointee<N>(x) action for any function
830// whose N-th argument (0-based) is a pointer to x's type. The
831// template parameter kIsProto is true iff type A is ProtocolMessage,
832// proto2::Message, or a sub-class of those.
833template <size_t N, typename A, bool kIsProto>
834class SetArgumentPointeeAction {
835 public:
836 // Constructs an action that sets the variable pointed to by the
837 // N-th function argument to 'value'.
838 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
839
840 template <typename Result, typename ArgumentTuple>
841 void Perform(const ArgumentTuple& args) const {
842 CompileAssertTypesEqual<void, Result>();
kosakbd018832014-04-02 20:30:00 +0000843 *::testing::get<N>(args) = value_;
shiqiane35fdd92008-12-10 05:08:54 +0000844 }
845
846 private:
847 const A value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000848
849 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
shiqiane35fdd92008-12-10 05:08:54 +0000850};
851
852template <size_t N, typename Proto>
853class SetArgumentPointeeAction<N, Proto, true> {
854 public:
855 // Constructs an action that sets the variable pointed to by the
856 // N-th function argument to 'proto'. Both ProtocolMessage and
857 // proto2::Message have the CopyFrom() method, so the same
858 // implementation works for both.
859 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
860 proto_->CopyFrom(proto);
861 }
862
863 template <typename Result, typename ArgumentTuple>
864 void Perform(const ArgumentTuple& args) const {
865 CompileAssertTypesEqual<void, Result>();
kosakbd018832014-04-02 20:30:00 +0000866 ::testing::get<N>(args)->CopyFrom(*proto_);
shiqiane35fdd92008-12-10 05:08:54 +0000867 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000868
shiqiane35fdd92008-12-10 05:08:54 +0000869 private:
870 const internal::linked_ptr<Proto> proto_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000871
872 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
shiqiane35fdd92008-12-10 05:08:54 +0000873};
874
shiqiane35fdd92008-12-10 05:08:54 +0000875// Implements the InvokeWithoutArgs(f) action. The template argument
876// FunctionImpl is the implementation type of f, which can be either a
877// function pointer or a functor. InvokeWithoutArgs(f) can be used as an
878// Action<F> as long as f's type is compatible with F (i.e. f can be
879// assigned to a tr1::function<F>).
880template <typename FunctionImpl>
881class InvokeWithoutArgsAction {
882 public:
883 // The c'tor makes a copy of function_impl (either a function
884 // pointer or a functor).
885 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
886 : function_impl_(function_impl) {}
887
888 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
889 // compatible with f.
890 template <typename Result, typename ArgumentTuple>
891 Result Perform(const ArgumentTuple&) { return function_impl_(); }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000892
shiqiane35fdd92008-12-10 05:08:54 +0000893 private:
894 FunctionImpl function_impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000895
896 GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
shiqiane35fdd92008-12-10 05:08:54 +0000897};
898
899// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
900template <class Class, typename MethodPtr>
901class InvokeMethodWithoutArgsAction {
902 public:
903 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
904 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
905
906 template <typename Result, typename ArgumentTuple>
907 Result Perform(const ArgumentTuple&) const {
908 return (obj_ptr_->*method_ptr_)();
909 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000910
shiqiane35fdd92008-12-10 05:08:54 +0000911 private:
912 Class* const obj_ptr_;
913 const MethodPtr method_ptr_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000914
915 GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
shiqiane35fdd92008-12-10 05:08:54 +0000916};
917
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400918// Implements the InvokeWithoutArgs(callback) action.
919template <typename CallbackType>
920class InvokeCallbackWithoutArgsAction {
921 public:
922 // The c'tor takes ownership of the callback.
923 explicit InvokeCallbackWithoutArgsAction(CallbackType* callback)
924 : callback_(callback) {
925 callback->CheckIsRepeatable(); // Makes sure the callback is permanent.
926 }
927
928 // This type conversion operator template allows Invoke(callback) to
929 // be used wherever the callback's return type can be implicitly
930 // converted to that of the mock function.
931 template <typename Result, typename ArgumentTuple>
932 Result Perform(const ArgumentTuple&) const { return callback_->Run(); }
933
934 private:
935 const internal::linked_ptr<CallbackType> callback_;
936
937 GTEST_DISALLOW_ASSIGN_(InvokeCallbackWithoutArgsAction);
938};
939
shiqiane35fdd92008-12-10 05:08:54 +0000940// Implements the IgnoreResult(action) action.
941template <typename A>
942class IgnoreResultAction {
943 public:
944 explicit IgnoreResultAction(const A& action) : action_(action) {}
945
946 template <typename F>
947 operator Action<F>() const {
948 // Assert statement belongs here because this is the best place to verify
949 // conditions on F. It produces the clearest error messages
950 // in most compilers.
951 // Impl really belongs in this scope as a local class but can't
952 // because MSVC produces duplicate symbols in different translation units
953 // in this case. Until MS fixes that bug we put Impl into the class scope
954 // and put the typedef both here (for use in assert statement) and
955 // in the Impl class. But both definitions must be the same.
956 typedef typename internal::Function<F>::Result Result;
957
958 // Asserts at compile time that F returns void.
959 CompileAssertTypesEqual<void, Result>();
960
961 return Action<F>(new Impl<F>(action_));
962 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000963
shiqiane35fdd92008-12-10 05:08:54 +0000964 private:
965 template <typename F>
966 class Impl : public ActionInterface<F> {
967 public:
968 typedef typename internal::Function<F>::Result Result;
969 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
970
971 explicit Impl(const A& action) : action_(action) {}
972
973 virtual void Perform(const ArgumentTuple& args) {
974 // Performs the action and ignores its result.
975 action_.Perform(args);
976 }
977
978 private:
979 // Type OriginalFunction is the same as F except that its return
980 // type is IgnoredValue.
981 typedef typename internal::Function<F>::MakeResultIgnoredValue
982 OriginalFunction;
983
984 const Action<OriginalFunction> action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000985
986 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000987 };
988
989 const A action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000990
991 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
shiqiane35fdd92008-12-10 05:08:54 +0000992};
993
zhanyong.wana18423e2009-07-22 23:58:19 +0000994// A ReferenceWrapper<T> object represents a reference to type T,
995// which can be either const or not. It can be explicitly converted
996// from, and implicitly converted to, a T&. Unlike a reference,
997// ReferenceWrapper<T> can be copied and can survive template type
998// inference. This is used to support by-reference arguments in the
999// InvokeArgument<N>(...) action. The idea was from "reference
1000// wrappers" in tr1, which we don't have in our source tree yet.
1001template <typename T>
1002class ReferenceWrapper {
1003 public:
1004 // Constructs a ReferenceWrapper<T> object from a T&.
1005 explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
1006
1007 // Allows a ReferenceWrapper<T> object to be implicitly converted to
1008 // a T&.
1009 operator T&() const { return *pointer_; }
1010 private:
1011 T* pointer_;
1012};
1013
1014// Allows the expression ByRef(x) to be printed as a reference to x.
1015template <typename T>
1016void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
1017 T& value = ref;
1018 UniversalPrinter<T&>::Print(value, os);
1019}
1020
1021// Does two actions sequentially. Used for implementing the DoAll(a1,
1022// a2, ...) action.
1023template <typename Action1, typename Action2>
1024class DoBothAction {
1025 public:
1026 DoBothAction(Action1 action1, Action2 action2)
1027 : action1_(action1), action2_(action2) {}
1028
1029 // This template type conversion operator allows DoAll(a1, ..., a_n)
1030 // to be used in ANY function of compatible type.
1031 template <typename F>
1032 operator Action<F>() const {
1033 return Action<F>(new Impl<F>(action1_, action2_));
1034 }
1035
1036 private:
1037 // Implements the DoAll(...) action for a particular function type F.
1038 template <typename F>
1039 class Impl : public ActionInterface<F> {
1040 public:
1041 typedef typename Function<F>::Result Result;
1042 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1043 typedef typename Function<F>::MakeResultVoid VoidResult;
1044
1045 Impl(const Action<VoidResult>& action1, const Action<F>& action2)
1046 : action1_(action1), action2_(action2) {}
1047
1048 virtual Result Perform(const ArgumentTuple& args) {
1049 action1_.Perform(args);
1050 return action2_.Perform(args);
1051 }
1052
1053 private:
1054 const Action<VoidResult> action1_;
1055 const Action<F> action2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001056
1057 GTEST_DISALLOW_ASSIGN_(Impl);
zhanyong.wana18423e2009-07-22 23:58:19 +00001058 };
1059
1060 Action1 action1_;
1061 Action2 action2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001062
1063 GTEST_DISALLOW_ASSIGN_(DoBothAction);
zhanyong.wana18423e2009-07-22 23:58:19 +00001064};
1065
shiqiane35fdd92008-12-10 05:08:54 +00001066} // namespace internal
1067
1068// An Unused object can be implicitly constructed from ANY value.
1069// This is handy when defining actions that ignore some or all of the
1070// mock function arguments. For example, given
1071//
1072// MOCK_METHOD3(Foo, double(const string& label, double x, double y));
1073// MOCK_METHOD3(Bar, double(int index, double x, double y));
1074//
1075// instead of
1076//
1077// double DistanceToOriginWithLabel(const string& label, double x, double y) {
1078// return sqrt(x*x + y*y);
1079// }
1080// double DistanceToOriginWithIndex(int index, double x, double y) {
1081// return sqrt(x*x + y*y);
1082// }
1083// ...
Hector Dearman41ad2432017-06-19 18:43:55 +01001084// EXPECT_CALL(mock, Foo("abc", _, _))
shiqiane35fdd92008-12-10 05:08:54 +00001085// .WillOnce(Invoke(DistanceToOriginWithLabel));
Hector Dearman41ad2432017-06-19 18:43:55 +01001086// EXPECT_CALL(mock, Bar(5, _, _))
shiqiane35fdd92008-12-10 05:08:54 +00001087// .WillOnce(Invoke(DistanceToOriginWithIndex));
1088//
1089// you could write
1090//
1091// // We can declare any uninteresting argument as Unused.
1092// double DistanceToOrigin(Unused, double x, double y) {
1093// return sqrt(x*x + y*y);
1094// }
1095// ...
Hector Dearman41ad2432017-06-19 18:43:55 +01001096// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
1097// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
shiqiane35fdd92008-12-10 05:08:54 +00001098typedef internal::IgnoredValue Unused;
1099
1100// This constructor allows us to turn an Action<From> object into an
1101// Action<To>, as long as To's arguments can be implicitly converted
1102// to From's and From's return type cann be implicitly converted to
1103// To's.
1104template <typename To>
1105template <typename From>
1106Action<To>::Action(const Action<From>& from)
Gennadiy Civil8654c1c2018-04-11 15:33:31 -04001107 :
1108#if GTEST_LANG_CXX11
1109 fun_(from.fun_),
1110#endif
1111 impl_(from.impl_ == NULL ? NULL
1112 : new internal::ActionAdaptor<To, From>(from)) {
1113}
shiqiane35fdd92008-12-10 05:08:54 +00001114
1115// Creates an action that returns 'value'. 'value' is passed by value
1116// instead of const reference - otherwise Return("string literal")
1117// will trigger a compiler error about using array as initializer.
1118template <typename R>
1119internal::ReturnAction<R> Return(R value) {
kosak3d1c78b2014-11-17 00:56:52 +00001120 return internal::ReturnAction<R>(internal::move(value));
shiqiane35fdd92008-12-10 05:08:54 +00001121}
1122
1123// Creates an action that returns NULL.
1124inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1125 return MakePolymorphicAction(internal::ReturnNullAction());
1126}
1127
1128// Creates an action that returns from a void function.
1129inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1130 return MakePolymorphicAction(internal::ReturnVoidAction());
1131}
1132
1133// Creates an action that returns the reference to a variable.
1134template <typename R>
1135inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
1136 return internal::ReturnRefAction<R>(x);
1137}
1138
zhanyong.wane3bd0982010-07-03 00:16:42 +00001139// Creates an action that returns the reference to a copy of the
1140// argument. The copy is created when the action is constructed and
1141// lives as long as the action.
1142template <typename R>
1143inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1144 return internal::ReturnRefOfCopyAction<R>(x);
1145}
1146
kosak3d1c78b2014-11-17 00:56:52 +00001147// Modifies the parent action (a Return() action) to perform a move of the
1148// argument instead of a copy.
1149// Return(ByMove()) actions can only be executed once and will assert this
1150// invariant.
1151template <typename R>
1152internal::ByMoveWrapper<R> ByMove(R x) {
1153 return internal::ByMoveWrapper<R>(internal::move(x));
1154}
1155
shiqiane35fdd92008-12-10 05:08:54 +00001156// Creates an action that does the default action for the give mock function.
1157inline internal::DoDefaultAction DoDefault() {
1158 return internal::DoDefaultAction();
1159}
1160
1161// Creates an action that sets the variable pointed by the N-th
1162// (0-based) function argument to 'value'.
1163template <size_t N, typename T>
1164PolymorphicAction<
1165 internal::SetArgumentPointeeAction<
1166 N, T, internal::IsAProtocolMessage<T>::value> >
zhanyong.wan59214832010-10-05 05:58:51 +00001167SetArgPointee(const T& x) {
1168 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1169 N, T, internal::IsAProtocolMessage<T>::value>(x));
1170}
zhanyong.wanfc8c6c42011-03-09 01:18:08 +00001171
1172#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
zhanyong.wana684b5a2010-12-02 23:30:50 +00001173// This overload allows SetArgPointee() to accept a string literal.
zhanyong.wanfc8c6c42011-03-09 01:18:08 +00001174// GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish
1175// this overload from the templated version and emit a compile error.
zhanyong.wana684b5a2010-12-02 23:30:50 +00001176template <size_t N>
1177PolymorphicAction<
1178 internal::SetArgumentPointeeAction<N, const char*, false> >
1179SetArgPointee(const char* p) {
1180 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1181 N, const char*, false>(p));
1182}
zhanyong.wanfc8c6c42011-03-09 01:18:08 +00001183
1184template <size_t N>
1185PolymorphicAction<
1186 internal::SetArgumentPointeeAction<N, const wchar_t*, false> >
1187SetArgPointee(const wchar_t* p) {
1188 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1189 N, const wchar_t*, false>(p));
1190}
1191#endif
1192
zhanyong.wan59214832010-10-05 05:58:51 +00001193// The following version is DEPRECATED.
1194template <size_t N, typename T>
1195PolymorphicAction<
1196 internal::SetArgumentPointeeAction<
1197 N, T, internal::IsAProtocolMessage<T>::value> >
shiqiane35fdd92008-12-10 05:08:54 +00001198SetArgumentPointee(const T& x) {
1199 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
1200 N, T, internal::IsAProtocolMessage<T>::value>(x));
1201}
1202
shiqiane35fdd92008-12-10 05:08:54 +00001203// Creates an action that sets a pointer referent to a given value.
1204template <typename T1, typename T2>
1205PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
1206 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1207}
1208
zhanyong.wanf7af24c2009-09-24 21:17:24 +00001209#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +00001210
shiqiane35fdd92008-12-10 05:08:54 +00001211// Creates an action that sets errno and returns the appropriate error.
1212template <typename T>
1213PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
1214SetErrnoAndReturn(int errval, T result) {
1215 return MakePolymorphicAction(
1216 internal::SetErrnoAndReturnAction<T>(errval, result));
1217}
1218
zhanyong.wanf7af24c2009-09-24 21:17:24 +00001219#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +00001220
shiqiane35fdd92008-12-10 05:08:54 +00001221// Various overloads for InvokeWithoutArgs().
1222
1223// Creates an action that invokes 'function_impl' with no argument.
1224template <typename FunctionImpl>
1225PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
1226InvokeWithoutArgs(FunctionImpl function_impl) {
1227 return MakePolymorphicAction(
1228 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
1229}
1230
1231// Creates an action that invokes the given method on the given object
1232// with no argument.
1233template <class Class, typename MethodPtr>
1234PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
1235InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
1236 return MakePolymorphicAction(
1237 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
1238 obj_ptr, method_ptr));
1239}
1240
1241// Creates an action that performs an_action and throws away its
1242// result. In other words, it changes the return type of an_action to
1243// void. an_action MUST NOT return void, or the code won't compile.
1244template <typename A>
1245inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1246 return internal::IgnoreResultAction<A>(an_action);
1247}
1248
zhanyong.wana18423e2009-07-22 23:58:19 +00001249// Creates a reference wrapper for the given L-value. If necessary,
1250// you can explicitly specify the type of the reference. For example,
1251// suppose 'derived' is an object of type Derived, ByRef(derived)
1252// would wrap a Derived&. If you want to wrap a const Base& instead,
1253// where Base is a base class of Derived, just write:
1254//
1255// ByRef<const Base>(derived)
1256template <typename T>
1257inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
1258 return internal::ReferenceWrapper<T>(l_value);
1259}
1260
shiqiane35fdd92008-12-10 05:08:54 +00001261} // namespace testing
1262
1263#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_