blob: e921cf4af9c70021fba22ab5beeccfbb78c2b8c6 [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>
Abseil Teame26a3fa2018-12-17 18:59:00 -050045#include <functional>
misterg80b43d92018-10-29 11:09:33 -040046#include <memory>
jgm79a367e2012-04-10 16:02:11 +000047#include <string>
Abseil Teame26a3fa2018-12-17 18:59:00 -050048#include <type_traits>
Abseil Team29b47e42018-10-16 15:29:37 -040049#include <utility>
jgm79a367e2012-04-10 16:02:11 +000050
zhanyong.wan53e08c42010-09-14 05:38:21 +000051#include "gmock/internal/gmock-internal-utils.h"
52#include "gmock/internal/gmock-port.h"
shiqiane35fdd92008-12-10 05:08:54 +000053
mistergbb7c0ec2018-11-20 10:26:17 -050054#ifdef _MSC_VER
55# pragma warning(push)
56# pragma warning(disable:4100)
57#endif
58
shiqiane35fdd92008-12-10 05:08:54 +000059namespace testing {
60
61// To implement an action Foo, define:
62// 1. a class FooAction that implements the ActionInterface interface, and
63// 2. a factory function that creates an Action object from a
64// const FooAction*.
65//
66// The two-level delegation design follows that of Matcher, providing
67// consistency for extension developers. It also eases ownership
68// management as Action objects can now be copied like plain values.
69
70namespace internal {
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:
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200102 // This function returns true if type T has a built-in default value.
kosakd478a1f2015-02-14 02:45:40 +0000103 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 }
kosakd478a1f2015-02-14 02:45:40 +0000111};
112
shiqiane35fdd92008-12-10 05:08:54 +0000113// This partial specialization says that we use the same built-in
114// default value for T and const T.
115template <typename T>
116class BuiltInDefaultValue<const T> {
117 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000118 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
shiqiane35fdd92008-12-10 05:08:54 +0000119 static T Get() { return BuiltInDefaultValue<T>::Get(); }
120};
121
122// This partial specialization defines the default values for pointer
123// types.
124template <typename T>
125class BuiltInDefaultValue<T*> {
126 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000127 static bool Exists() { return true; }
Abseil Team4bb49ed2018-10-04 18:28:05 -0400128 static T* Get() { return nullptr; }
shiqiane35fdd92008-12-10 05:08:54 +0000129};
130
131// The following specializations define the default values for
132// specific types we care about.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000133#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
shiqiane35fdd92008-12-10 05:08:54 +0000134 template <> \
135 class BuiltInDefaultValue<type> { \
136 public: \
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000137 static bool Exists() { return true; } \
shiqiane35fdd92008-12-10 05:08:54 +0000138 static type Get() { return value; } \
139 }
140
zhanyong.wane0d051e2009-02-19 00:33:37 +0000141GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
zhanyong.wane0d051e2009-02-19 00:33:37 +0000142GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
zhanyong.wane0d051e2009-02-19 00:33:37 +0000143GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
144GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
145GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
146GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
shiqiane35fdd92008-12-10 05:08:54 +0000147
shiqiane35fdd92008-12-10 05:08:54 +0000148// There's no need for a default action for signed wchar_t, as that
149// type is the same as wchar_t for gcc, and invalid for MSVC.
150//
151// There's also no need for a default action for unsigned wchar_t, as
152// that type is the same as unsigned int for gcc, and invalid for
153// MSVC.
zhanyong.wan95b12332009-09-25 18:55:50 +0000154#if GMOCK_WCHAR_T_IS_NATIVE_
zhanyong.wane0d051e2009-02-19 00:33:37 +0000155GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000156#endif
157
zhanyong.wane0d051e2009-02-19 00:33:37 +0000158GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
159GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
160GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
161GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
162GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
163GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
164GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
165GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
166GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
167GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
shiqiane35fdd92008-12-10 05:08:54 +0000168
zhanyong.wane0d051e2009-02-19 00:33:37 +0000169#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
shiqiane35fdd92008-12-10 05:08:54 +0000170
171} // namespace internal
172
173// When an unexpected function call is encountered, Google Mock will
174// let it return a default value if the user has specified one for its
175// return type, or if the return type has a built-in default value;
176// otherwise Google Mock won't know what value to return and will have
177// to abort the process.
178//
179// The DefaultValue<T> class allows a user to specify the
180// default value for a type T that is both copyable and publicly
181// destructible (i.e. anything that can be used as a function return
182// type). The usage is:
183//
184// // Sets the default value for type T to be foo.
185// DefaultValue<T>::Set(foo);
186template <typename T>
187class DefaultValue {
188 public:
189 // Sets the default value for type T; requires T to be
190 // copy-constructable and have a public destructor.
191 static void Set(T x) {
kosakb5c81092014-01-29 06:41:44 +0000192 delete producer_;
193 producer_ = new FixedValueProducer(x);
194 }
195
196 // Provides a factory function to be called to generate the default value.
197 // This method can be used even if T is only move-constructible, but it is not
198 // limited to that case.
199 typedef T (*FactoryFunction)();
200 static void SetFactory(FactoryFunction factory) {
201 delete producer_;
202 producer_ = new FactoryValueProducer(factory);
shiqiane35fdd92008-12-10 05:08:54 +0000203 }
204
205 // Unsets the default value for type T.
206 static void Clear() {
kosakb5c81092014-01-29 06:41:44 +0000207 delete producer_;
Abseil Team4bb49ed2018-10-04 18:28:05 -0400208 producer_ = nullptr;
shiqiane35fdd92008-12-10 05:08:54 +0000209 }
210
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200211 // Returns true if the user has set the default value for type T.
Abseil Team4bb49ed2018-10-04 18:28:05 -0400212 static bool IsSet() { return producer_ != nullptr; }
shiqiane35fdd92008-12-10 05:08:54 +0000213
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000214 // Returns true if T has a default return value set by the user or there
215 // exists a built-in default value.
216 static bool Exists() {
217 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
218 }
219
shiqiane35fdd92008-12-10 05:08:54 +0000220 // Returns the default value for type T if the user has set one;
kosakb5c81092014-01-29 06:41:44 +0000221 // otherwise returns the built-in default value. Requires that Exists()
222 // is true, which ensures that the return value is well-defined.
shiqiane35fdd92008-12-10 05:08:54 +0000223 static T Get() {
Abseil Team4bb49ed2018-10-04 18:28:05 -0400224 return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
225 : producer_->Produce();
shiqiane35fdd92008-12-10 05:08:54 +0000226 }
jgm79a367e2012-04-10 16:02:11 +0000227
shiqiane35fdd92008-12-10 05:08:54 +0000228 private:
kosakb5c81092014-01-29 06:41:44 +0000229 class ValueProducer {
230 public:
231 virtual ~ValueProducer() {}
232 virtual T Produce() = 0;
233 };
234
235 class FixedValueProducer : public ValueProducer {
236 public:
237 explicit FixedValueProducer(T value) : value_(value) {}
Abseil Team26743362018-12-03 11:30:02 -0500238 T Produce() override { return value_; }
kosakb5c81092014-01-29 06:41:44 +0000239
240 private:
241 const T value_;
242 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
243 };
244
245 class FactoryValueProducer : public ValueProducer {
246 public:
247 explicit FactoryValueProducer(FactoryFunction factory)
248 : factory_(factory) {}
Abseil Team26743362018-12-03 11:30:02 -0500249 T Produce() override { return factory_(); }
kosakb5c81092014-01-29 06:41:44 +0000250
251 private:
252 const FactoryFunction factory_;
253 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
254 };
255
256 static ValueProducer* producer_;
shiqiane35fdd92008-12-10 05:08:54 +0000257};
258
259// This partial specialization allows a user to set default values for
260// reference types.
261template <typename T>
262class DefaultValue<T&> {
263 public:
264 // Sets the default value for type T&.
265 static void Set(T& x) { // NOLINT
266 address_ = &x;
267 }
268
269 // Unsets the default value for type T&.
Abseil Team4bb49ed2018-10-04 18:28:05 -0400270 static void Clear() { address_ = nullptr; }
shiqiane35fdd92008-12-10 05:08:54 +0000271
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200272 // Returns true if the user has set the default value for type T&.
Abseil Team4bb49ed2018-10-04 18:28:05 -0400273 static bool IsSet() { return address_ != nullptr; }
shiqiane35fdd92008-12-10 05:08:54 +0000274
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000275 // Returns true if T has a default return value set by the user or there
276 // exists a built-in default value.
277 static bool Exists() {
278 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
279 }
280
shiqiane35fdd92008-12-10 05:08:54 +0000281 // Returns the default value for type T& if the user has set one;
282 // otherwise returns the built-in default value if there is one;
283 // otherwise aborts the process.
284 static T& Get() {
Abseil Team4bb49ed2018-10-04 18:28:05 -0400285 return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
286 : *address_;
shiqiane35fdd92008-12-10 05:08:54 +0000287 }
jgm79a367e2012-04-10 16:02:11 +0000288
shiqiane35fdd92008-12-10 05:08:54 +0000289 private:
290 static T* address_;
291};
292
293// This specialization allows DefaultValue<void>::Get() to
294// compile.
295template <>
296class DefaultValue<void> {
297 public:
zhanyong.wan5b95fa72009-01-27 22:28:45 +0000298 static bool Exists() { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000299 static void Get() {}
300};
301
302// Points to the user-set default value for type T.
303template <typename T>
Abseil Team4bb49ed2018-10-04 18:28:05 -0400304typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
shiqiane35fdd92008-12-10 05:08:54 +0000305
306// Points to the user-set default value for type T&.
307template <typename T>
Abseil Team4bb49ed2018-10-04 18:28:05 -0400308T* DefaultValue<T&>::address_ = nullptr;
shiqiane35fdd92008-12-10 05:08:54 +0000309
310// Implement this interface to define an action for function type F.
311template <typename F>
312class ActionInterface {
313 public:
314 typedef typename internal::Function<F>::Result Result;
315 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
316
zhanyong.waned6c9272011-02-23 19:39:27 +0000317 ActionInterface() {}
shiqiane35fdd92008-12-10 05:08:54 +0000318 virtual ~ActionInterface() {}
319
320 // Performs the action. This method is not const, as in general an
321 // action can have side effects and be stateful. For example, a
322 // get-the-next-element-from-the-collection action will need to
323 // remember the current element.
324 virtual Result Perform(const ArgumentTuple& args) = 0;
325
shiqiane35fdd92008-12-10 05:08:54 +0000326 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000327 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
shiqiane35fdd92008-12-10 05:08:54 +0000328};
329
330// An Action<F> is a copyable and IMMUTABLE (except by assignment)
331// object that represents an action to be taken when a mock function
332// of type F is called. The implementation of Action<T> is just a
misterg80b43d92018-10-29 11:09:33 -0400333// std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
shiqiane35fdd92008-12-10 05:08:54 +0000334// You can view an object implementing ActionInterface<F> as a
335// concrete action (including its current state), and an Action<F>
336// object as a handle to it.
337template <typename F>
338class Action {
Abseil Team9494c452018-12-19 03:16:02 -0500339 // Adapter class to allow constructing Action from a legacy ActionInterface.
340 // New code should create Actions from functors instead.
341 struct ActionAdapter {
342 // Adapter must be copyable to satisfy std::function requirements.
343 ::std::shared_ptr<ActionInterface<F>> impl_;
344
345 template <typename... Args>
346 typename internal::Function<F>::Result operator()(Args&&... args) {
347 return impl_->Perform(
348 ::std::forward_as_tuple(::std::forward<Args>(args)...));
349 }
350 };
351
shiqiane35fdd92008-12-10 05:08:54 +0000352 public:
353 typedef typename internal::Function<F>::Result Result;
354 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
355
356 // Constructs a null Action. Needed for storing Action objects in
357 // STL containers.
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400358 Action() {}
shiqiane35fdd92008-12-10 05:08:54 +0000359
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400360 // Construct an Action from a specified callable.
361 // This cannot take std::function directly, because then Action would not be
362 // directly constructible from lambda (it would require two conversions).
363 template <typename G,
364 typename = typename ::std::enable_if<
365 ::std::is_constructible<::std::function<F>, G>::value>::type>
366 Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400367
368 // Constructs an Action from its implementation.
Abseil Team9494c452018-12-19 03:16:02 -0500369 explicit Action(ActionInterface<F>* impl)
370 : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
shiqiane35fdd92008-12-10 05:08:54 +0000371
shiqiane35fdd92008-12-10 05:08:54 +0000372 // This constructor allows us to turn an Action<Func> object into an
373 // Action<F>, as long as F's arguments can be implicitly converted
Abseil Team9494c452018-12-19 03:16:02 -0500374 // to Func's and Func's return type can be implicitly converted to F's.
shiqiane35fdd92008-12-10 05:08:54 +0000375 template <typename Func>
Abseil Team9494c452018-12-19 03:16:02 -0500376 explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
shiqiane35fdd92008-12-10 05:08:54 +0000377
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200378 // Returns true if this is the DoDefault() action.
Abseil Team9494c452018-12-19 03:16:02 -0500379 bool IsDoDefault() const { return fun_ == nullptr; }
shiqiane35fdd92008-12-10 05:08:54 +0000380
381 // Performs the action. Note that this method is const even though
382 // the corresponding method in ActionInterface is not. The reason
383 // is that a const Action<F> means that it cannot be re-bound to
384 // another concrete action, not that the concrete action it binds to
385 // cannot change state. (Think of the difference between a const
386 // pointer and a pointer to const.)
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400387 Result Perform(ArgumentTuple args) const {
388 if (IsDoDefault()) {
389 internal::IllegalDoDefault(__FILE__, __LINE__);
390 }
Abseil Team9494c452018-12-19 03:16:02 -0500391 return internal::Apply(fun_, ::std::move(args));
shiqiane35fdd92008-12-10 05:08:54 +0000392 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000393
shiqiane35fdd92008-12-10 05:08:54 +0000394 private:
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400395 template <typename G>
396 friend class Action;
397
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200398 // fun_ is an empty function if this is the DoDefault() action.
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400399 ::std::function<F> fun_;
shiqiane35fdd92008-12-10 05:08:54 +0000400};
401
402// The PolymorphicAction class template makes it easy to implement a
403// polymorphic action (i.e. an action that can be used in mock
404// functions of than one type, e.g. Return()).
405//
406// To define a polymorphic action, a user first provides a COPYABLE
407// implementation class that has a Perform() method template:
408//
409// class FooAction {
410// public:
411// template <typename Result, typename ArgumentTuple>
412// Result Perform(const ArgumentTuple& args) const {
413// // Processes the arguments and returns a result, using
Abseil Team7d3b73c2018-10-09 14:50:26 -0400414// // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
shiqiane35fdd92008-12-10 05:08:54 +0000415// }
416// ...
417// };
418//
419// Then the user creates the polymorphic action using
420// MakePolymorphicAction(object) where object has type FooAction. See
421// the definition of Return(void) and SetArgumentPointee<N>(value) for
422// complete examples.
423template <typename Impl>
424class PolymorphicAction {
425 public:
426 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
427
428 template <typename F>
429 operator Action<F>() const {
430 return Action<F>(new MonomorphicImpl<F>(impl_));
431 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000432
shiqiane35fdd92008-12-10 05:08:54 +0000433 private:
434 template <typename F>
435 class MonomorphicImpl : public ActionInterface<F> {
436 public:
437 typedef typename internal::Function<F>::Result Result;
438 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
439
440 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
441
Abseil Team26743362018-12-03 11:30:02 -0500442 Result Perform(const ArgumentTuple& args) override {
shiqiane35fdd92008-12-10 05:08:54 +0000443 return impl_.template Perform<Result>(args);
444 }
445
446 private:
447 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000448
449 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000450 };
451
452 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000453
454 GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
shiqiane35fdd92008-12-10 05:08:54 +0000455};
456
457// Creates an Action from its implementation and returns it. The
458// created Action object owns the implementation.
459template <typename F>
460Action<F> MakeAction(ActionInterface<F>* impl) {
461 return Action<F>(impl);
462}
463
464// Creates a polymorphic action from its implementation. This is
465// easier to use than the PolymorphicAction<Impl> constructor as it
466// doesn't require you to explicitly write the template argument, e.g.
467//
468// MakePolymorphicAction(foo);
469// vs
470// PolymorphicAction<TypeOfFoo>(foo);
471template <typename Impl>
472inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
473 return PolymorphicAction<Impl>(impl);
474}
475
476namespace internal {
477
kosak3d1c78b2014-11-17 00:56:52 +0000478// Helper struct to specialize ReturnAction to execute a move instead of a copy
479// on return. Useful for move-only types, but could be used on any type.
480template <typename T>
481struct ByMoveWrapper {
Abseil Team29b47e42018-10-16 15:29:37 -0400482 explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
kosak3d1c78b2014-11-17 00:56:52 +0000483 T payload;
484};
485
shiqiane35fdd92008-12-10 05:08:54 +0000486// Implements the polymorphic Return(x) action, which can be used in
487// any function that returns the type of x, regardless of the argument
488// types.
vladloseva070cbd2009-11-18 00:09:28 +0000489//
490// Note: The value passed into Return must be converted into
491// Function<F>::Result when this action is cast to Action<F> rather than
492// when that action is performed. This is important in scenarios like
493//
494// MOCK_METHOD1(Method, T(U));
495// ...
496// {
497// Foo foo;
498// X x(&foo);
499// EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
500// }
501//
502// In the example above the variable x holds reference to foo which leaves
503// scope and gets destroyed. If copying X just copies a reference to foo,
504// that copy will be left with a hanging reference. If conversion to T
505// makes a copy of foo, the above code is safe. To support that scenario, we
506// need to make sure that the type conversion happens inside the EXPECT_CALL
507// statement, and conversion of the result of Return to Action<T(U)> is a
508// good place for that.
509//
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400510// The real life example of the above scenario happens when an invocation
511// of gtl::Container() is passed into Return.
512//
shiqiane35fdd92008-12-10 05:08:54 +0000513template <typename R>
514class ReturnAction {
515 public:
516 // Constructs a ReturnAction object from the value to be returned.
517 // 'value' is passed by value instead of by const reference in order
518 // to allow Return("string literal") to compile.
Abseil Team29b47e42018-10-16 15:29:37 -0400519 explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
shiqiane35fdd92008-12-10 05:08:54 +0000520
521 // This template type conversion operator allows Return(x) to be
522 // used in ANY function that returns x's type.
523 template <typename F>
Abseil Team096fb372018-12-14 15:24:21 -0500524 operator Action<F>() const { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000525 // Assert statement belongs here because this is the best place to verify
526 // conditions on F. It produces the clearest error messages
527 // in most compilers.
528 // Impl really belongs in this scope as a local class but can't
529 // because MSVC produces duplicate symbols in different translation units
530 // in this case. Until MS fixes that bug we put Impl into the class scope
531 // and put the typedef both here (for use in assert statement) and
532 // in the Impl class. But both definitions must be the same.
533 typedef typename Function<F>::Result Result;
zhanyong.wan02f71062010-05-10 17:14:29 +0000534 GTEST_COMPILE_ASSERT_(
kosak3d1c78b2014-11-17 00:56:52 +0000535 !is_reference<Result>::value,
zhanyong.wane0d051e2009-02-19 00:33:37 +0000536 use_ReturnRef_instead_of_Return_to_return_a_reference);
Abseil Team096fb372018-12-14 15:24:21 -0500537 static_assert(!std::is_void<Result>::value,
538 "Can't use Return() on an action expected to return `void`.");
kosak3d1c78b2014-11-17 00:56:52 +0000539 return Action<F>(new Impl<R, F>(value_));
shiqiane35fdd92008-12-10 05:08:54 +0000540 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000541
shiqiane35fdd92008-12-10 05:08:54 +0000542 private:
543 // Implements the Return(x) action for a particular function type F.
kosak3d1c78b2014-11-17 00:56:52 +0000544 template <typename R_, typename F>
shiqiane35fdd92008-12-10 05:08:54 +0000545 class Impl : public ActionInterface<F> {
546 public:
547 typedef typename Function<F>::Result Result;
548 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
549
vladloseva070cbd2009-11-18 00:09:28 +0000550 // The implicit cast is necessary when Result has more than one
551 // single-argument constructor (e.g. Result is std::vector<int>) and R
552 // has a type conversion operator template. In that case, value_(value)
553 // won't compile as the compiler doesn't known which constructor of
zhanyong.wan5b61ce32011-02-01 00:00:03 +0000554 // Result to call. ImplicitCast_ forces the compiler to convert R to
vladloseva070cbd2009-11-18 00:09:28 +0000555 // Result without considering explicit constructors, thus resolving the
556 // ambiguity. value_ is then initialized using its copy constructor.
misterg80b43d92018-10-29 11:09:33 -0400557 explicit Impl(const std::shared_ptr<R>& value)
kosak7123d832014-11-17 02:04:46 +0000558 : value_before_cast_(*value),
559 value_(ImplicitCast_<Result>(value_before_cast_)) {}
shiqiane35fdd92008-12-10 05:08:54 +0000560
Abseil Team26743362018-12-03 11:30:02 -0500561 Result Perform(const ArgumentTuple&) override { return value_; }
shiqiane35fdd92008-12-10 05:08:54 +0000562
563 private:
kosak3d1c78b2014-11-17 00:56:52 +0000564 GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
vladloseva070cbd2009-11-18 00:09:28 +0000565 Result_cannot_be_a_reference_type);
kosak7123d832014-11-17 02:04:46 +0000566 // We save the value before casting just in case it is being cast to a
567 // wrapper type.
568 R value_before_cast_;
vladloseva070cbd2009-11-18 00:09:28 +0000569 Result value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000570
kosak7123d832014-11-17 02:04:46 +0000571 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000572 };
573
kosak3d1c78b2014-11-17 00:56:52 +0000574 // Partially specialize for ByMoveWrapper. This version of ReturnAction will
575 // move its contents instead.
576 template <typename R_, typename F>
577 class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
578 public:
579 typedef typename Function<F>::Result Result;
580 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
581
misterg80b43d92018-10-29 11:09:33 -0400582 explicit Impl(const std::shared_ptr<R>& wrapper)
kosak3d1c78b2014-11-17 00:56:52 +0000583 : performed_(false), wrapper_(wrapper) {}
584
Abseil Team26743362018-12-03 11:30:02 -0500585 Result Perform(const ArgumentTuple&) override {
kosak3d1c78b2014-11-17 00:56:52 +0000586 GTEST_CHECK_(!performed_)
587 << "A ByMove() action should only be performed once.";
588 performed_ = true;
Abseil Team29b47e42018-10-16 15:29:37 -0400589 return std::move(wrapper_->payload);
kosak3d1c78b2014-11-17 00:56:52 +0000590 }
591
592 private:
593 bool performed_;
misterg80b43d92018-10-29 11:09:33 -0400594 const std::shared_ptr<R> wrapper_;
kosak3d1c78b2014-11-17 00:56:52 +0000595
596 GTEST_DISALLOW_ASSIGN_(Impl);
597 };
598
misterg80b43d92018-10-29 11:09:33 -0400599 const std::shared_ptr<R> value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000600
601 GTEST_DISALLOW_ASSIGN_(ReturnAction);
shiqiane35fdd92008-12-10 05:08:54 +0000602};
603
604// Implements the ReturnNull() action.
605class ReturnNullAction {
606 public:
kosak53d49dc2015-01-08 03:03:09 +0000607 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
608 // this is enforced by returning nullptr, and in non-C++11 by asserting a
609 // pointer type on compile time.
shiqiane35fdd92008-12-10 05:08:54 +0000610 template <typename Result, typename ArgumentTuple>
611 static Result Perform(const ArgumentTuple&) {
kosak53d49dc2015-01-08 03:03:09 +0000612 return nullptr;
shiqiane35fdd92008-12-10 05:08:54 +0000613 }
614};
615
616// Implements the Return() action.
617class ReturnVoidAction {
618 public:
619 // Allows Return() to be used in any void-returning function.
620 template <typename Result, typename ArgumentTuple>
621 static void Perform(const ArgumentTuple&) {
622 CompileAssertTypesEqual<void, Result>();
623 }
624};
625
626// Implements the polymorphic ReturnRef(x) action, which can be used
627// in any function that returns a reference to the type of x,
628// regardless of the argument types.
629template <typename T>
630class ReturnRefAction {
631 public:
632 // Constructs a ReturnRefAction object from the reference to be returned.
633 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
634
635 // This template type conversion operator allows ReturnRef(x) to be
636 // used in ANY function that returns a reference to x's type.
637 template <typename F>
638 operator Action<F>() const {
639 typedef typename Function<F>::Result Result;
640 // Asserts that the function return type is a reference. This
641 // catches the user error of using ReturnRef(x) when Return(x)
642 // should be used, and generates some helpful error message.
zhanyong.wan02f71062010-05-10 17:14:29 +0000643 GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
zhanyong.wane0d051e2009-02-19 00:33:37 +0000644 use_Return_instead_of_ReturnRef_to_return_a_value);
shiqiane35fdd92008-12-10 05:08:54 +0000645 return Action<F>(new Impl<F>(ref_));
646 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000647
shiqiane35fdd92008-12-10 05:08:54 +0000648 private:
649 // Implements the ReturnRef(x) action for a particular function type F.
650 template <typename F>
651 class Impl : public ActionInterface<F> {
652 public:
653 typedef typename Function<F>::Result Result;
654 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
655
656 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
657
Abseil Team26743362018-12-03 11:30:02 -0500658 Result Perform(const ArgumentTuple&) override { return ref_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000659
shiqiane35fdd92008-12-10 05:08:54 +0000660 private:
661 T& ref_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000662
663 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000664 };
665
666 T& ref_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000667
668 GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
shiqiane35fdd92008-12-10 05:08:54 +0000669};
670
zhanyong.wane3bd0982010-07-03 00:16:42 +0000671// Implements the polymorphic ReturnRefOfCopy(x) action, which can be
672// used in any function that returns a reference to the type of x,
673// regardless of the argument types.
674template <typename T>
675class ReturnRefOfCopyAction {
676 public:
677 // Constructs a ReturnRefOfCopyAction object from the reference to
678 // be returned.
679 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
680
681 // This template type conversion operator allows ReturnRefOfCopy(x) to be
682 // used in ANY function that returns a reference to x's type.
683 template <typename F>
684 operator Action<F>() const {
685 typedef typename Function<F>::Result Result;
686 // Asserts that the function return type is a reference. This
687 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
688 // should be used, and generates some helpful error message.
689 GTEST_COMPILE_ASSERT_(
690 internal::is_reference<Result>::value,
691 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
692 return Action<F>(new Impl<F>(value_));
693 }
694
695 private:
696 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
697 template <typename F>
698 class Impl : public ActionInterface<F> {
699 public:
700 typedef typename Function<F>::Result Result;
701 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
702
703 explicit Impl(const T& value) : value_(value) {} // NOLINT
704
Abseil Team26743362018-12-03 11:30:02 -0500705 Result Perform(const ArgumentTuple&) override { return value_; }
zhanyong.wane3bd0982010-07-03 00:16:42 +0000706
707 private:
708 T value_;
709
710 GTEST_DISALLOW_ASSIGN_(Impl);
711 };
712
713 const T value_;
714
715 GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
716};
717
shiqiane35fdd92008-12-10 05:08:54 +0000718// Implements the polymorphic DoDefault() action.
719class DoDefaultAction {
720 public:
721 // This template type conversion operator allows DoDefault() to be
722 // used in any function.
723 template <typename F>
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400724 operator Action<F>() const { return Action<F>(); } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +0000725};
726
727// Implements the Assign action to set a given pointer referent to a
728// particular value.
729template <typename T1, typename T2>
730class AssignAction {
731 public:
732 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
733
734 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000735 void Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000736 *ptr_ = value_;
737 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000738
shiqiane35fdd92008-12-10 05:08:54 +0000739 private:
740 T1* const ptr_;
741 const T2 value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000742
743 GTEST_DISALLOW_ASSIGN_(AssignAction);
shiqiane35fdd92008-12-10 05:08:54 +0000744};
745
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000746#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000747
shiqiane35fdd92008-12-10 05:08:54 +0000748// Implements the SetErrnoAndReturn action to simulate return from
749// various system calls and libc functions.
750template <typename T>
751class SetErrnoAndReturnAction {
752 public:
753 SetErrnoAndReturnAction(int errno_value, T result)
754 : errno_(errno_value),
755 result_(result) {}
756 template <typename Result, typename ArgumentTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000757 Result Perform(const ArgumentTuple& /* args */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000758 errno = errno_;
759 return result_;
760 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000761
shiqiane35fdd92008-12-10 05:08:54 +0000762 private:
763 const int errno_;
764 const T result_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000765
766 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
shiqiane35fdd92008-12-10 05:08:54 +0000767};
768
zhanyong.wanf7af24c2009-09-24 21:17:24 +0000769#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +0000770
shiqiane35fdd92008-12-10 05:08:54 +0000771// Implements the SetArgumentPointee<N>(x) action for any function
Abseil Team3f5b5b82019-05-03 15:06:49 -0400772// whose N-th argument (0-based) is a pointer to x's type.
773template <size_t N, typename A, typename = void>
774struct SetArgumentPointeeAction {
775 A value;
shiqiane35fdd92008-12-10 05:08:54 +0000776
Abseil Team3f5b5b82019-05-03 15:06:49 -0400777 template <typename... Args>
778 void operator()(const Args&... args) const {
779 *::std::get<N>(std::tie(args...)) = value;
shiqiane35fdd92008-12-10 05:08:54 +0000780 }
shiqiane35fdd92008-12-10 05:08:54 +0000781};
782
Abseil Team0adeadd2019-01-16 15:23:44 -0500783// Implements the Invoke(object_ptr, &Class::Method) action.
784template <class Class, typename MethodPtr>
785struct InvokeMethodAction {
786 Class* const obj_ptr;
787 const MethodPtr method_ptr;
788
789 template <typename... Args>
790 auto operator()(Args&&... args) const
791 -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
792 return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
793 }
794};
795
shiqiane35fdd92008-12-10 05:08:54 +0000796// Implements the InvokeWithoutArgs(f) action. The template argument
797// FunctionImpl is the implementation type of f, which can be either a
798// function pointer or a functor. InvokeWithoutArgs(f) can be used as an
Abseil Team0adeadd2019-01-16 15:23:44 -0500799// Action<F> as long as f's type is compatible with F.
shiqiane35fdd92008-12-10 05:08:54 +0000800template <typename FunctionImpl>
Abseil Team0adeadd2019-01-16 15:23:44 -0500801struct InvokeWithoutArgsAction {
802 FunctionImpl function_impl;
shiqiane35fdd92008-12-10 05:08:54 +0000803
804 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
805 // compatible with f.
Abseil Team0adeadd2019-01-16 15:23:44 -0500806 template <typename... Args>
807 auto operator()(const Args&...) -> decltype(function_impl()) {
808 return function_impl();
809 }
shiqiane35fdd92008-12-10 05:08:54 +0000810};
811
812// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
813template <class Class, typename MethodPtr>
Abseil Team0adeadd2019-01-16 15:23:44 -0500814struct InvokeMethodWithoutArgsAction {
815 Class* const obj_ptr;
816 const MethodPtr method_ptr;
shiqiane35fdd92008-12-10 05:08:54 +0000817
Abseil Team0adeadd2019-01-16 15:23:44 -0500818 using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
819
820 template <typename... Args>
821 ReturnType operator()(const Args&...) const {
822 return (obj_ptr->*method_ptr)();
shiqiane35fdd92008-12-10 05:08:54 +0000823 }
Gennadiy Civil8654c1c2018-04-11 15:33:31 -0400824};
825
shiqiane35fdd92008-12-10 05:08:54 +0000826// Implements the IgnoreResult(action) action.
827template <typename A>
828class IgnoreResultAction {
829 public:
830 explicit IgnoreResultAction(const A& action) : action_(action) {}
831
832 template <typename F>
833 operator Action<F>() const {
834 // Assert statement belongs here because this is the best place to verify
835 // conditions on F. It produces the clearest error messages
836 // in most compilers.
837 // Impl really belongs in this scope as a local class but can't
838 // because MSVC produces duplicate symbols in different translation units
839 // in this case. Until MS fixes that bug we put Impl into the class scope
840 // and put the typedef both here (for use in assert statement) and
841 // in the Impl class. But both definitions must be the same.
842 typedef typename internal::Function<F>::Result Result;
843
844 // Asserts at compile time that F returns void.
845 CompileAssertTypesEqual<void, Result>();
846
847 return Action<F>(new Impl<F>(action_));
848 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000849
shiqiane35fdd92008-12-10 05:08:54 +0000850 private:
851 template <typename F>
852 class Impl : public ActionInterface<F> {
853 public:
854 typedef typename internal::Function<F>::Result Result;
855 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
856
857 explicit Impl(const A& action) : action_(action) {}
858
Abseil Team26743362018-12-03 11:30:02 -0500859 void Perform(const ArgumentTuple& args) override {
shiqiane35fdd92008-12-10 05:08:54 +0000860 // Performs the action and ignores its result.
861 action_.Perform(args);
862 }
863
864 private:
865 // Type OriginalFunction is the same as F except that its return
866 // type is IgnoredValue.
867 typedef typename internal::Function<F>::MakeResultIgnoredValue
868 OriginalFunction;
869
870 const Action<OriginalFunction> action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000871
872 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000873 };
874
875 const A action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000876
877 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
shiqiane35fdd92008-12-10 05:08:54 +0000878};
879
Abseil Teamaac18182018-11-15 15:43:19 -0500880template <typename InnerAction, size_t... I>
881struct WithArgsAction {
882 InnerAction action;
883
884 // The inner action could be anything convertible to Action<X>.
885 // We use the conversion operator to detect the signature of the inner Action.
886 template <typename R, typename... Args>
887 operator Action<R(Args...)>() const { // NOLINT
888 Action<R(typename std::tuple_element<I, std::tuple<Args...>>::type...)>
889 converted(action);
890
891 return [converted](Args... args) -> R {
892 return converted.Perform(std::forward_as_tuple(
893 std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
894 };
895 }
896};
897
Abseil Team096fb372018-12-14 15:24:21 -0500898template <typename... Actions>
899struct DoAllAction {
900 private:
901 template <typename... Args, size_t... I>
902 std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
903 return {std::get<I>(actions)...};
904 }
905
906 public:
907 std::tuple<Actions...> actions;
908
909 template <typename R, typename... Args>
910 operator Action<R(Args...)>() const { // NOLINT
911 struct Op {
912 std::vector<Action<void(Args...)>> converted;
913 Action<R(Args...)> last;
914 R operator()(Args... args) const {
915 auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
916 for (auto& a : converted) {
917 a.Perform(tuple_args);
918 }
919 return last.Perform(tuple_args);
920 }
921 };
922 return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()),
923 std::get<sizeof...(Actions) - 1>(actions)};
924 }
925};
926
shiqiane35fdd92008-12-10 05:08:54 +0000927} // namespace internal
928
929// An Unused object can be implicitly constructed from ANY value.
930// This is handy when defining actions that ignore some or all of the
931// mock function arguments. For example, given
932//
933// MOCK_METHOD3(Foo, double(const string& label, double x, double y));
934// MOCK_METHOD3(Bar, double(int index, double x, double y));
935//
936// instead of
937//
938// double DistanceToOriginWithLabel(const string& label, double x, double y) {
939// return sqrt(x*x + y*y);
940// }
941// double DistanceToOriginWithIndex(int index, double x, double y) {
942// return sqrt(x*x + y*y);
943// }
944// ...
Hector Dearman41ad2432017-06-19 18:43:55 +0100945// EXPECT_CALL(mock, Foo("abc", _, _))
shiqiane35fdd92008-12-10 05:08:54 +0000946// .WillOnce(Invoke(DistanceToOriginWithLabel));
Hector Dearman41ad2432017-06-19 18:43:55 +0100947// EXPECT_CALL(mock, Bar(5, _, _))
shiqiane35fdd92008-12-10 05:08:54 +0000948// .WillOnce(Invoke(DistanceToOriginWithIndex));
949//
950// you could write
951//
952// // We can declare any uninteresting argument as Unused.
953// double DistanceToOrigin(Unused, double x, double y) {
954// return sqrt(x*x + y*y);
955// }
956// ...
Hector Dearman41ad2432017-06-19 18:43:55 +0100957// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
958// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
shiqiane35fdd92008-12-10 05:08:54 +0000959typedef internal::IgnoredValue Unused;
960
Abseil Team096fb372018-12-14 15:24:21 -0500961// Creates an action that does actions a1, a2, ..., sequentially in
962// each invocation.
963template <typename... Action>
964internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
965 Action&&... action) {
966 return {std::forward_as_tuple(std::forward<Action>(action)...)};
967}
968
Abseil Teamaac18182018-11-15 15:43:19 -0500969// WithArg<k>(an_action) creates an action that passes the k-th
970// (0-based) argument of the mock function to an_action and performs
971// it. It adapts an action accepting one argument to one that accepts
972// multiple arguments. For convenience, we also provide
973// WithArgs<k>(an_action) (defined below) as a synonym.
974template <size_t k, typename InnerAction>
975internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
976WithArg(InnerAction&& action) {
977 return {std::forward<InnerAction>(action)};
978}
979
980// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
981// the selected arguments of the mock function to an_action and
982// performs it. It serves as an adaptor between actions with
983// different argument lists.
984template <size_t k, size_t... ks, typename InnerAction>
985internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
986WithArgs(InnerAction&& action) {
987 return {std::forward<InnerAction>(action)};
988}
989
990// WithoutArgs(inner_action) can be used in a mock function with a
991// non-empty argument list to perform inner_action, which takes no
992// argument. In other words, it adapts an action accepting no
993// argument to one that accepts (and ignores) arguments.
994template <typename InnerAction>
995internal::WithArgsAction<typename std::decay<InnerAction>::type>
996WithoutArgs(InnerAction&& action) {
997 return {std::forward<InnerAction>(action)};
998}
999
shiqiane35fdd92008-12-10 05:08:54 +00001000// Creates an action that returns 'value'. 'value' is passed by value
1001// instead of const reference - otherwise Return("string literal")
1002// will trigger a compiler error about using array as initializer.
1003template <typename R>
1004internal::ReturnAction<R> Return(R value) {
Abseil Team29b47e42018-10-16 15:29:37 -04001005 return internal::ReturnAction<R>(std::move(value));
shiqiane35fdd92008-12-10 05:08:54 +00001006}
1007
1008// Creates an action that returns NULL.
1009inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1010 return MakePolymorphicAction(internal::ReturnNullAction());
1011}
1012
1013// Creates an action that returns from a void function.
1014inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1015 return MakePolymorphicAction(internal::ReturnVoidAction());
1016}
1017
1018// Creates an action that returns the reference to a variable.
1019template <typename R>
1020inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
1021 return internal::ReturnRefAction<R>(x);
1022}
1023
zhanyong.wane3bd0982010-07-03 00:16:42 +00001024// Creates an action that returns the reference to a copy of the
1025// argument. The copy is created when the action is constructed and
1026// lives as long as the action.
1027template <typename R>
1028inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1029 return internal::ReturnRefOfCopyAction<R>(x);
1030}
1031
kosak3d1c78b2014-11-17 00:56:52 +00001032// Modifies the parent action (a Return() action) to perform a move of the
1033// argument instead of a copy.
1034// Return(ByMove()) actions can only be executed once and will assert this
1035// invariant.
1036template <typename R>
1037internal::ByMoveWrapper<R> ByMove(R x) {
Abseil Team29b47e42018-10-16 15:29:37 -04001038 return internal::ByMoveWrapper<R>(std::move(x));
kosak3d1c78b2014-11-17 00:56:52 +00001039}
1040
shiqiane35fdd92008-12-10 05:08:54 +00001041// Creates an action that does the default action for the give mock function.
1042inline internal::DoDefaultAction DoDefault() {
1043 return internal::DoDefaultAction();
1044}
1045
1046// Creates an action that sets the variable pointed by the N-th
1047// (0-based) function argument to 'value'.
1048template <size_t N, typename T>
Abseil Team3f5b5b82019-05-03 15:06:49 -04001049internal::SetArgumentPointeeAction<N, T> SetArgPointee(T x) {
1050 return {std::move(x)};
zhanyong.wanfc8c6c42011-03-09 01:18:08 +00001051}
zhanyong.wanfc8c6c42011-03-09 01:18:08 +00001052
zhanyong.wan59214832010-10-05 05:58:51 +00001053// The following version is DEPRECATED.
1054template <size_t N, typename T>
Abseil Team3f5b5b82019-05-03 15:06:49 -04001055internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T x) {
1056 return {std::move(x)};
shiqiane35fdd92008-12-10 05:08:54 +00001057}
1058
shiqiane35fdd92008-12-10 05:08:54 +00001059// Creates an action that sets a pointer referent to a given value.
1060template <typename T1, typename T2>
1061PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
1062 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1063}
1064
zhanyong.wanf7af24c2009-09-24 21:17:24 +00001065#if !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +00001066
shiqiane35fdd92008-12-10 05:08:54 +00001067// Creates an action that sets errno and returns the appropriate error.
1068template <typename T>
1069PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
1070SetErrnoAndReturn(int errval, T result) {
1071 return MakePolymorphicAction(
1072 internal::SetErrnoAndReturnAction<T>(errval, result));
1073}
1074
zhanyong.wanf7af24c2009-09-24 21:17:24 +00001075#endif // !GTEST_OS_WINDOWS_MOBILE
zhanyong.wan5b5d62f2009-03-11 23:37:56 +00001076
Abseil Team0adeadd2019-01-16 15:23:44 -05001077// Various overloads for Invoke().
1078
1079// Legacy function.
1080// Actions can now be implicitly constructed from callables. No need to create
1081// wrapper objects.
1082// This function exists for backwards compatibility.
1083template <typename FunctionImpl>
1084typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
1085 return std::forward<FunctionImpl>(function_impl);
1086}
1087
1088// Creates an action that invokes the given method on the given object
1089// with the mock function's arguments.
1090template <class Class, typename MethodPtr>
1091internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
1092 MethodPtr method_ptr) {
1093 return {obj_ptr, method_ptr};
1094}
shiqiane35fdd92008-12-10 05:08:54 +00001095
1096// Creates an action that invokes 'function_impl' with no argument.
1097template <typename FunctionImpl>
Abseil Team0adeadd2019-01-16 15:23:44 -05001098internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
shiqiane35fdd92008-12-10 05:08:54 +00001099InvokeWithoutArgs(FunctionImpl function_impl) {
Abseil Team0adeadd2019-01-16 15:23:44 -05001100 return {std::move(function_impl)};
shiqiane35fdd92008-12-10 05:08:54 +00001101}
1102
1103// Creates an action that invokes the given method on the given object
1104// with no argument.
1105template <class Class, typename MethodPtr>
Abseil Team0adeadd2019-01-16 15:23:44 -05001106internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
1107 Class* obj_ptr, MethodPtr method_ptr) {
1108 return {obj_ptr, method_ptr};
shiqiane35fdd92008-12-10 05:08:54 +00001109}
1110
1111// Creates an action that performs an_action and throws away its
1112// result. In other words, it changes the return type of an_action to
1113// void. an_action MUST NOT return void, or the code won't compile.
1114template <typename A>
1115inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1116 return internal::IgnoreResultAction<A>(an_action);
1117}
1118
zhanyong.wana18423e2009-07-22 23:58:19 +00001119// Creates a reference wrapper for the given L-value. If necessary,
1120// you can explicitly specify the type of the reference. For example,
1121// suppose 'derived' is an object of type Derived, ByRef(derived)
1122// would wrap a Derived&. If you want to wrap a const Base& instead,
1123// where Base is a base class of Derived, just write:
1124//
1125// ByRef<const Base>(derived)
Abseil Team097407f2019-01-12 12:26:37 -05001126//
1127// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
1128// However, it may still be used for consistency with ByMove().
zhanyong.wana18423e2009-07-22 23:58:19 +00001129template <typename T>
Abseil Team097407f2019-01-12 12:26:37 -05001130inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
1131 return ::std::reference_wrapper<T>(l_value);
zhanyong.wana18423e2009-07-22 23:58:19 +00001132}
1133
shiqiane35fdd92008-12-10 05:08:54 +00001134} // namespace testing
1135
mistergbb7c0ec2018-11-20 10:26:17 -05001136#ifdef _MSC_VER
1137# pragma warning(pop)
1138#endif
1139
1140
shiqiane35fdd92008-12-10 05:08:54 +00001141#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_