Path: blob/main/contrib/googletest/googlemock/include/gmock/gmock-actions.h
48375 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Mock - a framework for writing C++ mock classes.30//31// The ACTION* family of macros can be used in a namespace scope to32// define custom actions easily. The syntax:33//34// ACTION(name) { statements; }35//36// will define an action with the given name that executes the37// statements. The value returned by the statements will be used as38// the return value of the action. Inside the statements, you can39// refer to the K-th (0-based) argument of the mock function by40// 'argK', and refer to its type by 'argK_type'. For example:41//42// ACTION(IncrementArg1) {43// arg1_type temp = arg1;44// return ++(*temp);45// }46//47// allows you to write48//49// ...WillOnce(IncrementArg1());50//51// You can also refer to the entire argument tuple and its type by52// 'args' and 'args_type', and refer to the mock function type and its53// return type by 'function_type' and 'return_type'.54//55// Note that you don't need to specify the types of the mock function56// arguments. However rest assured that your code is still type-safe:57// you'll get a compiler error if *arg1 doesn't support the ++58// operator, or if the type of ++(*arg1) isn't compatible with the59// mock function's return type, for example.60//61// Sometimes you'll want to parameterize the action. For that you can use62// another macro:63//64// ACTION_P(name, param_name) { statements; }65//66// For example:67//68// ACTION_P(Add, n) { return arg0 + n; }69//70// will allow you to write:71//72// ...WillOnce(Add(5));73//74// Note that you don't need to provide the type of the parameter75// either. If you need to reference the type of a parameter named76// 'foo', you can write 'foo_type'. For example, in the body of77// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type78// of 'n'.79//80// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support81// multi-parameter actions.82//83// For the purpose of typing, you can view84//85// ACTION_Pk(Foo, p1, ..., pk) { ... }86//87// as shorthand for88//89// template <typename p1_type, ..., typename pk_type>90// FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }91//92// In particular, you can provide the template type arguments93// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);94// although usually you can rely on the compiler to infer the types95// for you automatically. You can assign the result of expression96// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,97// pk_type>. This can be useful when composing actions.98//99// You can also overload actions with different numbers of parameters:100//101// ACTION_P(Plus, a) { ... }102// ACTION_P2(Plus, a, b) { ... }103//104// While it's tempting to always use the ACTION* macros when defining105// a new action, you should also consider implementing ActionInterface106// or using MakePolymorphicAction() instead, especially if you need to107// use the action a lot. While these approaches require more work,108// they give you more control on the types of the mock function109// arguments and the action parameters, which in general leads to110// better compiler error messages that pay off in the long run. They111// also allow overloading actions based on parameter types (as opposed112// to just based on the number of parameters).113//114// CAVEAT:115//116// ACTION*() can only be used in a namespace scope as templates cannot be117// declared inside of a local class.118// Users can, however, define any local functors (e.g. a lambda) that119// can be used as actions.120//121// MORE INFORMATION:122//123// To learn more about using these macros, please search for 'ACTION' on124// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md125126// IWYU pragma: private, include "gmock/gmock.h"127// IWYU pragma: friend gmock/.*128129#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_130#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_131132#ifndef _WIN32_WCE133#include <errno.h>134#endif135136#include <algorithm>137#include <exception>138#include <functional>139#include <memory>140#include <string>141#include <tuple>142#include <type_traits>143#include <utility>144145#include "gmock/internal/gmock-internal-utils.h"146#include "gmock/internal/gmock-port.h"147#include "gmock/internal/gmock-pp.h"148149GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)150151namespace testing {152153// To implement an action Foo, define:154// 1. a class FooAction that implements the ActionInterface interface, and155// 2. a factory function that creates an Action object from a156// const FooAction*.157//158// The two-level delegation design follows that of Matcher, providing159// consistency for extension developers. It also eases ownership160// management as Action objects can now be copied like plain values.161162namespace internal {163164// BuiltInDefaultValueGetter<T, true>::Get() returns a165// default-constructed T value. BuiltInDefaultValueGetter<T,166// false>::Get() crashes with an error.167//168// This primary template is used when kDefaultConstructible is true.169template <typename T, bool kDefaultConstructible>170struct BuiltInDefaultValueGetter {171static T Get() { return T(); }172};173template <typename T>174struct BuiltInDefaultValueGetter<T, false> {175static T Get() {176Assert(false, __FILE__, __LINE__,177"Default action undefined for the function return type.");178#if defined(__GNUC__) || defined(__clang__)179__builtin_unreachable();180#elif defined(_MSC_VER)181__assume(0);182#else183return Invalid<T>();184// The above statement will never be reached, but is required in185// order for this function to compile.186#endif187}188};189190// BuiltInDefaultValue<T>::Get() returns the "built-in" default value191// for type T, which is NULL when T is a raw pointer type, 0 when T is192// a numeric type, false when T is bool, or "" when T is string or193// std::string. In addition, in C++11 and above, it turns a194// default-constructed T value if T is default constructible. For any195// other type T, the built-in default T value is undefined, and the196// function will abort the process.197template <typename T>198class BuiltInDefaultValue {199public:200// This function returns true if and only if type T has a built-in default201// value.202static bool Exists() { return ::std::is_default_constructible<T>::value; }203204static T Get() {205return BuiltInDefaultValueGetter<206T, ::std::is_default_constructible<T>::value>::Get();207}208};209210// This partial specialization says that we use the same built-in211// default value for T and const T.212template <typename T>213class BuiltInDefaultValue<const T> {214public:215static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }216static T Get() { return BuiltInDefaultValue<T>::Get(); }217};218219// This partial specialization defines the default values for pointer220// types.221template <typename T>222class BuiltInDefaultValue<T*> {223public:224static bool Exists() { return true; }225static T* Get() { return nullptr; }226};227228// The following specializations define the default values for229// specific types we care about.230#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \231template <> \232class BuiltInDefaultValue<type> { \233public: \234static bool Exists() { return true; } \235static type Get() { return value; } \236}237238GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT239GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");240GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);241GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');242GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');243GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');244245// There's no need for a default action for signed wchar_t, as that246// type is the same as wchar_t for gcc, and invalid for MSVC.247//248// There's also no need for a default action for unsigned wchar_t, as249// that type is the same as unsigned int for gcc, and invalid for250// MSVC.251#if GMOCK_WCHAR_T_IS_NATIVE_252GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT253#endif254255GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT256GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT257GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);258GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);259GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT260GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT261GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT262GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT263GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);264GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);265266#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_267268// Partial implementations of metaprogramming types from the standard library269// not available in C++11.270271template <typename P>272struct negation273// NOLINTNEXTLINE274: std::integral_constant<bool, bool(!P::value)> {};275276// Base case: with zero predicates the answer is always true.277template <typename...>278struct conjunction : std::true_type {};279280// With a single predicate, the answer is that predicate.281template <typename P1>282struct conjunction<P1> : P1 {};283284// With multiple predicates the answer is the first predicate if that is false,285// and we recurse otherwise.286template <typename P1, typename... Ps>287struct conjunction<P1, Ps...>288: std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {};289290template <typename...>291struct disjunction : std::false_type {};292293template <typename P1>294struct disjunction<P1> : P1 {};295296template <typename P1, typename... Ps>297struct disjunction<P1, Ps...>298// NOLINTNEXTLINE299: std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {};300301template <typename...>302using void_t = void;303304// Detects whether an expression of type `From` can be implicitly converted to305// `To` according to [conv]. In C++17, [conv]/3 defines this as follows:306//307// An expression e can be implicitly converted to a type T if and only if308// the declaration T t=e; is well-formed, for some invented temporary309// variable t ([dcl.init]).310//311// [conv]/2 implies we can use function argument passing to detect whether this312// initialization is valid.313//314// Note that this is distinct from is_convertible, which requires this be valid:315//316// To test() {317// return declval<From>();318// }319//320// In particular, is_convertible doesn't give the correct answer when `To` and321// `From` are the same non-moveable type since `declval<From>` will be an rvalue322// reference, defeating the guaranteed copy elision that would otherwise make323// this function work.324//325// REQUIRES: `From` is not cv void.326template <typename From, typename To>327struct is_implicitly_convertible {328private:329// A function that accepts a parameter of type T. This can be called with type330// U successfully only if U is implicitly convertible to T.331template <typename T>332static void Accept(T);333334// A function that creates a value of type T.335template <typename T>336static T Make();337338// An overload be selected when implicit conversion from T to To is possible.339template <typename T, typename = decltype(Accept<To>(Make<T>()))>340static std::true_type TestImplicitConversion(int);341342// A fallback overload selected in all other cases.343template <typename T>344static std::false_type TestImplicitConversion(...);345346public:347using type = decltype(TestImplicitConversion<From>(0));348static constexpr bool value = type::value;349};350351// Like std::invoke_result_t from C++17, but works only for objects with call352// operators (not e.g. member function pointers, which we don't need specific353// support for in OnceAction because std::function deals with them).354template <typename F, typename... Args>355using call_result_t = decltype(std::declval<F>()(std::declval<Args>()...));356357template <typename Void, typename R, typename F, typename... Args>358struct is_callable_r_impl : std::false_type {};359360// Specialize the struct for those template arguments where call_result_t is361// well-formed. When it's not, the generic template above is chosen, resulting362// in std::false_type.363template <typename R, typename F, typename... Args>364struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...>365: std::conditional<366std::is_void<R>::value, //367std::true_type, //368is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {};369370// Like std::is_invocable_r from C++17, but works only for objects with call371// operators. See the note on call_result_t.372template <typename R, typename F, typename... Args>373using is_callable_r = is_callable_r_impl<void, R, F, Args...>;374375// Like std::as_const from C++17.376template <typename T>377typename std::add_const<T>::type& as_const(T& t) {378return t;379}380381} // namespace internal382383// Specialized for function types below.384template <typename F>385class OnceAction;386387// An action that can only be used once.388//389// This is accepted by WillOnce, which doesn't require the underlying action to390// be copy-constructible (only move-constructible), and promises to invoke it as391// an rvalue reference. This allows the action to work with move-only types like392// std::move_only_function in a type-safe manner.393//394// For example:395//396// // Assume we have some API that needs to accept a unique pointer to some397// // non-copyable object Foo.398// void AcceptUniquePointer(std::unique_ptr<Foo> foo);399//400// // We can define an action that provides a Foo to that API. Because It401// // has to give away its unique pointer, it must not be called more than402// // once, so its call operator is &&-qualified.403// struct ProvideFoo {404// std::unique_ptr<Foo> foo;405//406// void operator()() && {407// AcceptUniquePointer(std::move(Foo));408// }409// };410//411// // This action can be used with WillOnce.412// EXPECT_CALL(mock, Call)413// .WillOnce(ProvideFoo{std::make_unique<Foo>(...)});414//415// // But a call to WillRepeatedly will fail to compile. This is correct,416// // since the action cannot correctly be used repeatedly.417// EXPECT_CALL(mock, Call)418// .WillRepeatedly(ProvideFoo{std::make_unique<Foo>(...)});419//420// A less-contrived example would be an action that returns an arbitrary type,421// whose &&-qualified call operator is capable of dealing with move-only types.422template <typename Result, typename... Args>423class OnceAction<Result(Args...)> final {424private:425// True iff we can use the given callable type (or lvalue reference) directly426// via StdFunctionAdaptor.427template <typename Callable>428using IsDirectlyCompatible = internal::conjunction<429// It must be possible to capture the callable in StdFunctionAdaptor.430std::is_constructible<typename std::decay<Callable>::type, Callable>,431// The callable must be compatible with our signature.432internal::is_callable_r<Result, typename std::decay<Callable>::type,433Args...>>;434435// True iff we can use the given callable type via StdFunctionAdaptor once we436// ignore incoming arguments.437template <typename Callable>438using IsCompatibleAfterIgnoringArguments = internal::conjunction<439// It must be possible to capture the callable in a lambda.440std::is_constructible<typename std::decay<Callable>::type, Callable>,441// The callable must be invocable with zero arguments, returning something442// convertible to Result.443internal::is_callable_r<Result, typename std::decay<Callable>::type>>;444445public:446// Construct from a callable that is directly compatible with our mocked447// signature: it accepts our function type's arguments and returns something448// convertible to our result type.449template <typename Callable,450typename std::enable_if<451internal::conjunction<452// Teach clang on macOS that we're not talking about a453// copy/move constructor here. Otherwise it gets confused454// when checking the is_constructible requirement of our455// traits above.456internal::negation<std::is_same<457OnceAction, typename std::decay<Callable>::type>>,458IsDirectlyCompatible<Callable>> //459::value,460int>::type = 0>461OnceAction(Callable&& callable) // NOLINT462: function_(StdFunctionAdaptor<typename std::decay<Callable>::type>(463{}, std::forward<Callable>(callable))) {}464465// As above, but for a callable that ignores the mocked function's arguments.466template <typename Callable,467typename std::enable_if<468internal::conjunction<469// Teach clang on macOS that we're not talking about a470// copy/move constructor here. Otherwise it gets confused471// when checking the is_constructible requirement of our472// traits above.473internal::negation<std::is_same<474OnceAction, typename std::decay<Callable>::type>>,475// Exclude callables for which the overload above works.476// We'd rather provide the arguments if possible.477internal::negation<IsDirectlyCompatible<Callable>>,478IsCompatibleAfterIgnoringArguments<Callable>>::value,479int>::type = 0>480OnceAction(Callable&& callable) // NOLINT481// Call the constructor above with a callable482// that ignores the input arguments.483: OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{484std::forward<Callable>(callable)}) {}485486// We are naturally copyable because we store only an std::function, but487// semantically we should not be copyable.488OnceAction(const OnceAction&) = delete;489OnceAction& operator=(const OnceAction&) = delete;490OnceAction(OnceAction&&) = default;491492// Invoke the underlying action callable with which we were constructed,493// handing it the supplied arguments.494Result Call(Args... args) && {495return function_(std::forward<Args>(args)...);496}497498private:499// An adaptor that wraps a callable that is compatible with our signature and500// being invoked as an rvalue reference so that it can be used as an501// StdFunctionAdaptor. This throws away type safety, but that's fine because502// this is only used by WillOnce, which we know calls at most once.503//504// Once we have something like std::move_only_function from C++23, we can do505// away with this.506template <typename Callable>507class StdFunctionAdaptor final {508public:509// A tag indicating that the (otherwise universal) constructor is accepting510// the callable itself, instead of e.g. stealing calls for the move511// constructor.512struct CallableTag final {};513514template <typename F>515explicit StdFunctionAdaptor(CallableTag, F&& callable)516: callable_(std::make_shared<Callable>(std::forward<F>(callable))) {}517518// Rather than explicitly returning Result, we return whatever the wrapped519// callable returns. This allows for compatibility with existing uses like520// the following, when the mocked function returns void:521//522// EXPECT_CALL(mock_fn_, Call)523// .WillOnce([&] {524// [...]525// return 0;526// });527//528// Such a callable can be turned into std::function<void()>. If we use an529// explicit return type of Result here then it *doesn't* work with530// std::function, because we'll get a "void function should not return a531// value" error.532//533// We need not worry about incompatible result types because the SFINAE on534// OnceAction already checks this for us. std::is_invocable_r_v itself makes535// the same allowance for void result types.536template <typename... ArgRefs>537internal::call_result_t<Callable, ArgRefs...> operator()(538ArgRefs&&... args) const {539return std::move(*callable_)(std::forward<ArgRefs>(args)...);540}541542private:543// We must put the callable on the heap so that we are copyable, which544// std::function needs.545std::shared_ptr<Callable> callable_;546};547548// An adaptor that makes a callable that accepts zero arguments callable with549// our mocked arguments.550template <typename Callable>551struct IgnoreIncomingArguments {552internal::call_result_t<Callable> operator()(Args&&...) {553return std::move(callable)();554}555556Callable callable;557};558559std::function<Result(Args...)> function_;560};561562// When an unexpected function call is encountered, Google Mock will563// let it return a default value if the user has specified one for its564// return type, or if the return type has a built-in default value;565// otherwise Google Mock won't know what value to return and will have566// to abort the process.567//568// The DefaultValue<T> class allows a user to specify the569// default value for a type T that is both copyable and publicly570// destructible (i.e. anything that can be used as a function return571// type). The usage is:572//573// // Sets the default value for type T to be foo.574// DefaultValue<T>::Set(foo);575template <typename T>576class DefaultValue {577public:578// Sets the default value for type T; requires T to be579// copy-constructable and have a public destructor.580static void Set(T x) {581delete producer_;582producer_ = new FixedValueProducer(x);583}584585// Provides a factory function to be called to generate the default value.586// This method can be used even if T is only move-constructible, but it is not587// limited to that case.588typedef T (*FactoryFunction)();589static void SetFactory(FactoryFunction factory) {590delete producer_;591producer_ = new FactoryValueProducer(factory);592}593594// Unsets the default value for type T.595static void Clear() {596delete producer_;597producer_ = nullptr;598}599600// Returns true if and only if the user has set the default value for type T.601static bool IsSet() { return producer_ != nullptr; }602603// Returns true if T has a default return value set by the user or there604// exists a built-in default value.605static bool Exists() {606return IsSet() || internal::BuiltInDefaultValue<T>::Exists();607}608609// Returns the default value for type T if the user has set one;610// otherwise returns the built-in default value. Requires that Exists()611// is true, which ensures that the return value is well-defined.612static T Get() {613return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()614: producer_->Produce();615}616617private:618class ValueProducer {619public:620virtual ~ValueProducer() = default;621virtual T Produce() = 0;622};623624class FixedValueProducer : public ValueProducer {625public:626explicit FixedValueProducer(T value) : value_(value) {}627T Produce() override { return value_; }628629private:630const T value_;631FixedValueProducer(const FixedValueProducer&) = delete;632FixedValueProducer& operator=(const FixedValueProducer&) = delete;633};634635class FactoryValueProducer : public ValueProducer {636public:637explicit FactoryValueProducer(FactoryFunction factory)638: factory_(factory) {}639T Produce() override { return factory_(); }640641private:642const FactoryFunction factory_;643FactoryValueProducer(const FactoryValueProducer&) = delete;644FactoryValueProducer& operator=(const FactoryValueProducer&) = delete;645};646647static ValueProducer* producer_;648};649650// This partial specialization allows a user to set default values for651// reference types.652template <typename T>653class DefaultValue<T&> {654public:655// Sets the default value for type T&.656static void Set(T& x) { // NOLINT657address_ = &x;658}659660// Unsets the default value for type T&.661static void Clear() { address_ = nullptr; }662663// Returns true if and only if the user has set the default value for type T&.664static bool IsSet() { return address_ != nullptr; }665666// Returns true if T has a default return value set by the user or there667// exists a built-in default value.668static bool Exists() {669return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();670}671672// Returns the default value for type T& if the user has set one;673// otherwise returns the built-in default value if there is one;674// otherwise aborts the process.675static T& Get() {676return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()677: *address_;678}679680private:681static T* address_;682};683684// This specialization allows DefaultValue<void>::Get() to685// compile.686template <>687class DefaultValue<void> {688public:689static bool Exists() { return true; }690static void Get() {}691};692693// Points to the user-set default value for type T.694template <typename T>695typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;696697// Points to the user-set default value for type T&.698template <typename T>699T* DefaultValue<T&>::address_ = nullptr;700701// Implement this interface to define an action for function type F.702template <typename F>703class ActionInterface {704public:705typedef typename internal::Function<F>::Result Result;706typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;707708ActionInterface() = default;709virtual ~ActionInterface() = default;710711// Performs the action. This method is not const, as in general an712// action can have side effects and be stateful. For example, a713// get-the-next-element-from-the-collection action will need to714// remember the current element.715virtual Result Perform(const ArgumentTuple& args) = 0;716717private:718ActionInterface(const ActionInterface&) = delete;719ActionInterface& operator=(const ActionInterface&) = delete;720};721722template <typename F>723class Action;724725// An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment)726// object that represents an action to be taken when a mock function of type727// R(Args...) is called. The implementation of Action<T> is just a728// std::shared_ptr to const ActionInterface<T>. Don't inherit from Action! You729// can view an object implementing ActionInterface<F> as a concrete action730// (including its current state), and an Action<F> object as a handle to it.731template <typename R, typename... Args>732class Action<R(Args...)> {733private:734using F = R(Args...);735736// Adapter class to allow constructing Action from a legacy ActionInterface.737// New code should create Actions from functors instead.738struct ActionAdapter {739// Adapter must be copyable to satisfy std::function requirements.740::std::shared_ptr<ActionInterface<F>> impl_;741742template <typename... InArgs>743typename internal::Function<F>::Result operator()(InArgs&&... args) {744return impl_->Perform(745::std::forward_as_tuple(::std::forward<InArgs>(args)...));746}747};748749template <typename G>750using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;751752public:753typedef typename internal::Function<F>::Result Result;754typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;755756// Constructs a null Action. Needed for storing Action objects in757// STL containers.758Action() = default;759760// Construct an Action from a specified callable.761// This cannot take std::function directly, because then Action would not be762// directly constructible from lambda (it would require two conversions).763template <764typename G,765typename = typename std::enable_if<internal::disjunction<766IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,767G>>::value>::type>768Action(G&& fun) { // NOLINT769Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());770}771772// Constructs an Action from its implementation.773explicit Action(ActionInterface<F>* impl)774: fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}775776// This constructor allows us to turn an Action<Func> object into an777// Action<F>, as long as F's arguments can be implicitly converted778// to Func's and Func's return type can be implicitly converted to F's.779template <typename Func>780Action(const Action<Func>& action) // NOLINT781: fun_(action.fun_) {}782783// Returns true if and only if this is the DoDefault() action.784bool IsDoDefault() const { return fun_ == nullptr; }785786// Performs the action. Note that this method is const even though787// the corresponding method in ActionInterface is not. The reason788// is that a const Action<F> means that it cannot be re-bound to789// another concrete action, not that the concrete action it binds to790// cannot change state. (Think of the difference between a const791// pointer and a pointer to const.)792Result Perform(ArgumentTuple args) const {793if (IsDoDefault()) {794internal::IllegalDoDefault(__FILE__, __LINE__);795}796return internal::Apply(fun_, ::std::move(args));797}798799// An action can be used as a OnceAction, since it's obviously safe to call it800// once.801operator OnceAction<F>() const { // NOLINT802// Return a OnceAction-compatible callable that calls Perform with the803// arguments it is provided. We could instead just return fun_, but then804// we'd need to handle the IsDoDefault() case separately.805struct OA {806Action<F> action;807808R operator()(Args... args) && {809return action.Perform(810std::forward_as_tuple(std::forward<Args>(args)...));811}812};813814return OA{*this};815}816817private:818template <typename G>819friend class Action;820821template <typename G>822void Init(G&& g, ::std::true_type) {823fun_ = ::std::forward<G>(g);824}825826template <typename G>827void Init(G&& g, ::std::false_type) {828fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};829}830831template <typename FunctionImpl>832struct IgnoreArgs {833template <typename... InArgs>834Result operator()(const InArgs&...) const {835return function_impl();836}837838FunctionImpl function_impl;839};840841// fun_ is an empty function if and only if this is the DoDefault() action.842::std::function<F> fun_;843};844845// The PolymorphicAction class template makes it easy to implement a846// polymorphic action (i.e. an action that can be used in mock847// functions of than one type, e.g. Return()).848//849// To define a polymorphic action, a user first provides a COPYABLE850// implementation class that has a Perform() method template:851//852// class FooAction {853// public:854// template <typename Result, typename ArgumentTuple>855// Result Perform(const ArgumentTuple& args) const {856// // Processes the arguments and returns a result, using857// // std::get<N>(args) to get the N-th (0-based) argument in the tuple.858// }859// ...860// };861//862// Then the user creates the polymorphic action using863// MakePolymorphicAction(object) where object has type FooAction. See864// the definition of Return(void) and SetArgumentPointee<N>(value) for865// complete examples.866template <typename Impl>867class PolymorphicAction {868public:869explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}870871template <typename F>872operator Action<F>() const {873return Action<F>(new MonomorphicImpl<F>(impl_));874}875876private:877template <typename F>878class MonomorphicImpl : public ActionInterface<F> {879public:880typedef typename internal::Function<F>::Result Result;881typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;882883explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}884885Result Perform(const ArgumentTuple& args) override {886return impl_.template Perform<Result>(args);887}888889private:890Impl impl_;891};892893Impl impl_;894};895896// Creates an Action from its implementation and returns it. The897// created Action object owns the implementation.898template <typename F>899Action<F> MakeAction(ActionInterface<F>* impl) {900return Action<F>(impl);901}902903// Creates a polymorphic action from its implementation. This is904// easier to use than the PolymorphicAction<Impl> constructor as it905// doesn't require you to explicitly write the template argument, e.g.906//907// MakePolymorphicAction(foo);908// vs909// PolymorphicAction<TypeOfFoo>(foo);910template <typename Impl>911inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {912return PolymorphicAction<Impl>(impl);913}914915namespace internal {916917// Helper struct to specialize ReturnAction to execute a move instead of a copy918// on return. Useful for move-only types, but could be used on any type.919template <typename T>920struct ByMoveWrapper {921explicit ByMoveWrapper(T value) : payload(std::move(value)) {}922T payload;923};924925// The general implementation of Return(R). Specializations follow below.926template <typename R>927class ReturnAction final {928public:929explicit ReturnAction(R value) : value_(std::move(value)) {}930931template <typename U, typename... Args,932typename = typename std::enable_if<conjunction<933// See the requirements documented on Return.934negation<std::is_same<void, U>>, //935negation<std::is_reference<U>>, //936std::is_convertible<R, U>, //937std::is_move_constructible<U>>::value>::type>938operator OnceAction<U(Args...)>() && { // NOLINT939return Impl<U>(std::move(value_));940}941942template <typename U, typename... Args,943typename = typename std::enable_if<conjunction<944// See the requirements documented on Return.945negation<std::is_same<void, U>>, //946negation<std::is_reference<U>>, //947std::is_convertible<const R&, U>, //948std::is_copy_constructible<U>>::value>::type>949operator Action<U(Args...)>() const { // NOLINT950return Impl<U>(value_);951}952953private:954// Implements the Return(x) action for a mock function that returns type U.955template <typename U>956class Impl final {957public:958// The constructor used when the return value is allowed to move from the959// input value (i.e. we are converting to OnceAction).960explicit Impl(R&& input_value)961: state_(new State(std::move(input_value))) {}962963// The constructor used when the return value is not allowed to move from964// the input value (i.e. we are converting to Action).965explicit Impl(const R& input_value) : state_(new State(input_value)) {}966967U operator()() && { return std::move(state_->value); }968U operator()() const& { return state_->value; }969970private:971// We put our state on the heap so that the compiler-generated copy/move972// constructors work correctly even when U is a reference-like type. This is973// necessary only because we eagerly create State::value (see the note on974// that symbol for details). If we instead had only the input value as a975// member then the default constructors would work fine.976//977// For example, when R is std::string and U is std::string_view, value is a978// reference to the string backed by input_value. The copy constructor would979// copy both, so that we wind up with a new input_value object (with the980// same contents) and a reference to the *old* input_value object rather981// than the new one.982struct State {983explicit State(const R& input_value_in)984: input_value(input_value_in),985// Make an implicit conversion to Result before initializing the U986// object we store, avoiding calling any explicit constructor of U987// from R.988//989// This simulates the language rules: a function with return type U990// that does `return R()` requires R to be implicitly convertible to991// U, and uses that path for the conversion, even U Result has an992// explicit constructor from R.993value(ImplicitCast_<U>(internal::as_const(input_value))) {}994995// As above, but for the case where we're moving from the ReturnAction996// object because it's being used as a OnceAction.997explicit State(R&& input_value_in)998: input_value(std::move(input_value_in)),999// For the same reason as above we make an implicit conversion to U1000// before initializing the value.1001//1002// Unlike above we provide the input value as an rvalue to the1003// implicit conversion because this is a OnceAction: it's fine if it1004// wants to consume the input value.1005value(ImplicitCast_<U>(std::move(input_value))) {}10061007// A copy of the value originally provided by the user. We retain this in1008// addition to the value of the mock function's result type below in case1009// the latter is a reference-like type. See the std::string_view example1010// in the documentation on Return.1011R input_value;10121013// The value we actually return, as the type returned by the mock function1014// itself.1015//1016// We eagerly initialize this here, rather than lazily doing the implicit1017// conversion automatically each time Perform is called, for historical1018// reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126)1019// made the Action<U()> conversion operator eagerly convert the R value to1020// U, but without keeping the R alive. This broke the use case discussed1021// in the documentation for Return, making reference-like types such as1022// std::string_view not safe to use as U where the input type R is a1023// value-like type such as std::string.1024//1025// The example the commit gave was not very clear, nor was the issue1026// thread (https://github.com/google/googlemock/issues/86), but it seems1027// the worry was about reference-like input types R that flatten to a1028// value-like type U when being implicitly converted. An example of this1029// is std::vector<bool>::reference, which is often a proxy type with an1030// reference to the underlying vector:1031//1032// // Helper method: have the mock function return bools according1033// // to the supplied script.1034// void SetActions(MockFunction<bool(size_t)>& mock,1035// const std::vector<bool>& script) {1036// for (size_t i = 0; i < script.size(); ++i) {1037// EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i]));1038// }1039// }1040//1041// TEST(Foo, Bar) {1042// // Set actions using a temporary vector, whose operator[]1043// // returns proxy objects that references that will be1044// // dangling once the call to SetActions finishes and the1045// // vector is destroyed.1046// MockFunction<bool(size_t)> mock;1047// SetActions(mock, {false, true});1048//1049// EXPECT_FALSE(mock.AsStdFunction()(0));1050// EXPECT_TRUE(mock.AsStdFunction()(1));1051// }1052//1053// This eager conversion helps with a simple case like this, but doesn't1054// fully make these types work in general. For example the following still1055// uses a dangling reference:1056//1057// TEST(Foo, Baz) {1058// MockFunction<std::vector<std::string>()> mock;1059//1060// // Return the same vector twice, and then the empty vector1061// // thereafter.1062// auto action = Return(std::initializer_list<std::string>{1063// "taco", "burrito",1064// });1065//1066// EXPECT_CALL(mock, Call)1067// .WillOnce(action)1068// .WillOnce(action)1069// .WillRepeatedly(Return(std::vector<std::string>{}));1070//1071// EXPECT_THAT(mock.AsStdFunction()(),1072// ElementsAre("taco", "burrito"));1073// EXPECT_THAT(mock.AsStdFunction()(),1074// ElementsAre("taco", "burrito"));1075// EXPECT_THAT(mock.AsStdFunction()(), IsEmpty());1076// }1077//1078U value;1079};10801081const std::shared_ptr<State> state_;1082};10831084R value_;1085};10861087// A specialization of ReturnAction<R> when R is ByMoveWrapper<T> for some T.1088//1089// This version applies the type system-defeating hack of moving from T even in1090// the const call operator, checking at runtime that it isn't called more than1091// once, since the user has declared their intent to do so by using ByMove.1092template <typename T>1093class ReturnAction<ByMoveWrapper<T>> final {1094public:1095explicit ReturnAction(ByMoveWrapper<T> wrapper)1096: state_(new State(std::move(wrapper.payload))) {}10971098T operator()() const {1099GTEST_CHECK_(!state_->called)1100<< "A ByMove() action must be performed at most once.";11011102state_->called = true;1103return std::move(state_->value);1104}11051106private:1107// We store our state on the heap so that we are copyable as required by1108// Action, despite the fact that we are stateful and T may not be copyable.1109struct State {1110explicit State(T&& value_in) : value(std::move(value_in)) {}11111112T value;1113bool called = false;1114};11151116const std::shared_ptr<State> state_;1117};11181119// Implements the ReturnNull() action.1120class ReturnNullAction {1121public:1122// Allows ReturnNull() to be used in any pointer-returning function. In C++111123// this is enforced by returning nullptr, and in non-C++11 by asserting a1124// pointer type on compile time.1125template <typename Result, typename ArgumentTuple>1126static Result Perform(const ArgumentTuple&) {1127return nullptr;1128}1129};11301131// Implements the Return() action.1132class ReturnVoidAction {1133public:1134// Allows Return() to be used in any void-returning function.1135template <typename Result, typename ArgumentTuple>1136static void Perform(const ArgumentTuple&) {1137static_assert(std::is_void<Result>::value, "Result should be void.");1138}1139};11401141// Implements the polymorphic ReturnRef(x) action, which can be used1142// in any function that returns a reference to the type of x,1143// regardless of the argument types.1144template <typename T>1145class ReturnRefAction {1146public:1147// Constructs a ReturnRefAction object from the reference to be returned.1148explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT11491150// This template type conversion operator allows ReturnRef(x) to be1151// used in ANY function that returns a reference to x's type.1152template <typename F>1153operator Action<F>() const {1154typedef typename Function<F>::Result Result;1155// Asserts that the function return type is a reference. This1156// catches the user error of using ReturnRef(x) when Return(x)1157// should be used, and generates some helpful error message.1158static_assert(std::is_reference<Result>::value,1159"use Return instead of ReturnRef to return a value");1160return Action<F>(new Impl<F>(ref_));1161}11621163private:1164// Implements the ReturnRef(x) action for a particular function type F.1165template <typename F>1166class Impl : public ActionInterface<F> {1167public:1168typedef typename Function<F>::Result Result;1169typedef typename Function<F>::ArgumentTuple ArgumentTuple;11701171explicit Impl(T& ref) : ref_(ref) {} // NOLINT11721173Result Perform(const ArgumentTuple&) override { return ref_; }11741175private:1176T& ref_;1177};11781179T& ref_;1180};11811182// Implements the polymorphic ReturnRefOfCopy(x) action, which can be1183// used in any function that returns a reference to the type of x,1184// regardless of the argument types.1185template <typename T>1186class ReturnRefOfCopyAction {1187public:1188// Constructs a ReturnRefOfCopyAction object from the reference to1189// be returned.1190explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT11911192// This template type conversion operator allows ReturnRefOfCopy(x) to be1193// used in ANY function that returns a reference to x's type.1194template <typename F>1195operator Action<F>() const {1196typedef typename Function<F>::Result Result;1197// Asserts that the function return type is a reference. This1198// catches the user error of using ReturnRefOfCopy(x) when Return(x)1199// should be used, and generates some helpful error message.1200static_assert(std::is_reference<Result>::value,1201"use Return instead of ReturnRefOfCopy to return a value");1202return Action<F>(new Impl<F>(value_));1203}12041205private:1206// Implements the ReturnRefOfCopy(x) action for a particular function type F.1207template <typename F>1208class Impl : public ActionInterface<F> {1209public:1210typedef typename Function<F>::Result Result;1211typedef typename Function<F>::ArgumentTuple ArgumentTuple;12121213explicit Impl(const T& value) : value_(value) {} // NOLINT12141215Result Perform(const ArgumentTuple&) override { return value_; }12161217private:1218T value_;1219};12201221const T value_;1222};12231224// Implements the polymorphic ReturnRoundRobin(v) action, which can be1225// used in any function that returns the element_type of v.1226template <typename T>1227class ReturnRoundRobinAction {1228public:1229explicit ReturnRoundRobinAction(std::vector<T> values) {1230GTEST_CHECK_(!values.empty())1231<< "ReturnRoundRobin requires at least one element.";1232state_->values = std::move(values);1233}12341235template <typename... Args>1236T operator()(Args&&...) const {1237return state_->Next();1238}12391240private:1241struct State {1242T Next() {1243T ret_val = values[i++];1244if (i == values.size()) i = 0;1245return ret_val;1246}12471248std::vector<T> values;1249size_t i = 0;1250};1251std::shared_ptr<State> state_ = std::make_shared<State>();1252};12531254// Implements the polymorphic DoDefault() action.1255class DoDefaultAction {1256public:1257// This template type conversion operator allows DoDefault() to be1258// used in any function.1259template <typename F>1260operator Action<F>() const {1261return Action<F>();1262} // NOLINT1263};12641265// Implements the Assign action to set a given pointer referent to a1266// particular value.1267template <typename T1, typename T2>1268class AssignAction {1269public:1270AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}12711272template <typename Result, typename ArgumentTuple>1273void Perform(const ArgumentTuple& /* args */) const {1274*ptr_ = value_;1275}12761277private:1278T1* const ptr_;1279const T2 value_;1280};12811282#ifndef GTEST_OS_WINDOWS_MOBILE12831284// Implements the SetErrnoAndReturn action to simulate return from1285// various system calls and libc functions.1286template <typename T>1287class SetErrnoAndReturnAction {1288public:1289SetErrnoAndReturnAction(int errno_value, T result)1290: errno_(errno_value), result_(result) {}1291template <typename Result, typename ArgumentTuple>1292Result Perform(const ArgumentTuple& /* args */) const {1293errno = errno_;1294return result_;1295}12961297private:1298const int errno_;1299const T result_;1300};13011302#endif // !GTEST_OS_WINDOWS_MOBILE13031304// Implements the SetArgumentPointee<N>(x) action for any function1305// whose N-th argument (0-based) is a pointer to x's type.1306template <size_t N, typename A, typename = void>1307struct SetArgumentPointeeAction {1308A value;13091310template <typename... Args>1311void operator()(const Args&... args) const {1312*::std::get<N>(std::tie(args...)) = value;1313}1314};13151316// Implements the Invoke(object_ptr, &Class::Method) action.1317template <class Class, typename MethodPtr>1318struct InvokeMethodAction {1319Class* const obj_ptr;1320const MethodPtr method_ptr;13211322template <typename... Args>1323auto operator()(Args&&... args) const1324-> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {1325return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);1326}1327};13281329// Implements the InvokeWithoutArgs(f) action. The template argument1330// FunctionImpl is the implementation type of f, which can be either a1331// function pointer or a functor. InvokeWithoutArgs(f) can be used as an1332// Action<F> as long as f's type is compatible with F.1333template <typename FunctionImpl>1334struct InvokeWithoutArgsAction {1335FunctionImpl function_impl;13361337// Allows InvokeWithoutArgs(f) to be used as any action whose type is1338// compatible with f.1339template <typename... Args>1340auto operator()(const Args&...) -> decltype(function_impl()) {1341return function_impl();1342}1343};13441345// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.1346template <class Class, typename MethodPtr>1347struct InvokeMethodWithoutArgsAction {1348Class* const obj_ptr;1349const MethodPtr method_ptr;13501351using ReturnType =1352decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());13531354template <typename... Args>1355ReturnType operator()(const Args&...) const {1356return (obj_ptr->*method_ptr)();1357}1358};13591360// Implements the IgnoreResult(action) action.1361template <typename A>1362class IgnoreResultAction {1363public:1364explicit IgnoreResultAction(const A& action) : action_(action) {}13651366template <typename F>1367operator Action<F>() const {1368// Assert statement belongs here because this is the best place to verify1369// conditions on F. It produces the clearest error messages1370// in most compilers.1371// Impl really belongs in this scope as a local class but can't1372// because MSVC produces duplicate symbols in different translation units1373// in this case. Until MS fixes that bug we put Impl into the class scope1374// and put the typedef both here (for use in assert statement) and1375// in the Impl class. But both definitions must be the same.1376typedef typename internal::Function<F>::Result Result;13771378// Asserts at compile time that F returns void.1379static_assert(std::is_void<Result>::value, "Result type should be void.");13801381return Action<F>(new Impl<F>(action_));1382}13831384private:1385template <typename F>1386class Impl : public ActionInterface<F> {1387public:1388typedef typename internal::Function<F>::Result Result;1389typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;13901391explicit Impl(const A& action) : action_(action) {}13921393void Perform(const ArgumentTuple& args) override {1394// Performs the action and ignores its result.1395action_.Perform(args);1396}13971398private:1399// Type OriginalFunction is the same as F except that its return1400// type is IgnoredValue.1401typedef1402typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction;14031404const Action<OriginalFunction> action_;1405};14061407const A action_;1408};14091410template <typename InnerAction, size_t... I>1411struct WithArgsAction {1412InnerAction inner_action;14131414// The signature of the function as seen by the inner action, given an out1415// action with the given result and argument types.1416template <typename R, typename... Args>1417using InnerSignature =1418R(typename std::tuple_element<I, std::tuple<Args...>>::type...);14191420// Rather than a call operator, we must define conversion operators to1421// particular action types. This is necessary for embedded actions like1422// DoDefault(), which rely on an action conversion operators rather than1423// providing a call operator because even with a particular set of arguments1424// they don't have a fixed return type.14251426template <1427typename R, typename... Args,1428typename std::enable_if<1429std::is_convertible<InnerAction,1430// Unfortunately we can't use the InnerSignature1431// alias here; MSVC complains about the I1432// parameter pack not being expanded (error C3520)1433// despite it being expanded in the type alias.1434// TupleElement is also an MSVC workaround.1435// See its definition for details.1436OnceAction<R(internal::TupleElement<1437I, std::tuple<Args...>>...)>>::value,1438int>::type = 0>1439operator OnceAction<R(Args...)>() && { // NOLINT1440struct OA {1441OnceAction<InnerSignature<R, Args...>> inner_action;14421443R operator()(Args&&... args) && {1444return std::move(inner_action)1445.Call(std::get<I>(1446std::forward_as_tuple(std::forward<Args>(args)...))...);1447}1448};14491450return OA{std::move(inner_action)};1451}14521453template <1454typename R, typename... Args,1455typename std::enable_if<1456std::is_convertible<const InnerAction&,1457// Unfortunately we can't use the InnerSignature1458// alias here; MSVC complains about the I1459// parameter pack not being expanded (error C3520)1460// despite it being expanded in the type alias.1461// TupleElement is also an MSVC workaround.1462// See its definition for details.1463Action<R(internal::TupleElement<1464I, std::tuple<Args...>>...)>>::value,1465int>::type = 0>1466operator Action<R(Args...)>() const { // NOLINT1467Action<InnerSignature<R, Args...>> converted(inner_action);14681469return [converted](Args&&... args) -> R {1470return converted.Perform(std::forward_as_tuple(1471std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));1472};1473}1474};14751476template <typename... Actions>1477class DoAllAction;14781479// Base case: only a single action.1480template <typename FinalAction>1481class DoAllAction<FinalAction> {1482public:1483struct UserConstructorTag {};14841485template <typename T>1486explicit DoAllAction(UserConstructorTag, T&& action)1487: final_action_(std::forward<T>(action)) {}14881489// Rather than a call operator, we must define conversion operators to1490// particular action types. This is necessary for embedded actions like1491// DoDefault(), which rely on an action conversion operators rather than1492// providing a call operator because even with a particular set of arguments1493// they don't have a fixed return type.14941495template <typename R, typename... Args,1496typename std::enable_if<1497std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,1498int>::type = 0>1499operator OnceAction<R(Args...)>() && { // NOLINT1500return std::move(final_action_);1501}15021503template <1504typename R, typename... Args,1505typename std::enable_if<1506std::is_convertible<const FinalAction&, Action<R(Args...)>>::value,1507int>::type = 0>1508operator Action<R(Args...)>() const { // NOLINT1509return final_action_;1510}15111512private:1513FinalAction final_action_;1514};15151516// Recursive case: support N actions by calling the initial action and then1517// calling through to the base class containing N-1 actions.1518template <typename InitialAction, typename... OtherActions>1519class DoAllAction<InitialAction, OtherActions...>1520: private DoAllAction<OtherActions...> {1521private:1522using Base = DoAllAction<OtherActions...>;15231524// The type of reference that should be provided to an initial action for a1525// mocked function parameter of type T.1526//1527// There are two quirks here:1528//1529// * Unlike most forwarding functions, we pass scalars through by value.1530// This isn't strictly necessary because an lvalue reference would work1531// fine too and be consistent with other non-reference types, but it's1532// perhaps less surprising.1533//1534// For example if the mocked function has signature void(int), then it1535// might seem surprising for the user's initial action to need to be1536// convertible to Action<void(const int&)>. This is perhaps less1537// surprising for a non-scalar type where there may be a performance1538// impact, or it might even be impossible, to pass by value.1539//1540// * More surprisingly, `const T&` is often not a const reference type.1541// By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to1542// U& or U&& for some non-scalar type U, then InitialActionArgType<T> is1543// U&. In other words, we may hand over a non-const reference.1544//1545// So for example, given some non-scalar type Obj we have the following1546// mappings:1547//1548// T InitialActionArgType<T>1549// ------- -----------------------1550// Obj const Obj&1551// Obj& Obj&1552// Obj&& Obj&1553// const Obj const Obj&1554// const Obj& const Obj&1555// const Obj&& const Obj&1556//1557// In other words, the initial actions get a mutable view of an non-scalar1558// argument if and only if the mock function itself accepts a non-const1559// reference type. They are never given an rvalue reference to an1560// non-scalar type.1561//1562// This situation makes sense if you imagine use with a matcher that is1563// designed to write through a reference. For example, if the caller wants1564// to fill in a reference argument and then return a canned value:1565//1566// EXPECT_CALL(mock, Call)1567// .WillOnce(DoAll(SetArgReferee<0>(17), Return(19)));1568//1569template <typename T>1570using InitialActionArgType =1571typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;15721573public:1574struct UserConstructorTag {};15751576template <typename T, typename... U>1577explicit DoAllAction(UserConstructorTag, T&& initial_action,1578U&&... other_actions)1579: Base({}, std::forward<U>(other_actions)...),1580initial_action_(std::forward<T>(initial_action)) {}15811582template <typename R, typename... Args,1583typename std::enable_if<1584conjunction<1585// Both the initial action and the rest must support1586// conversion to OnceAction.1587std::is_convertible<1588InitialAction,1589OnceAction<void(InitialActionArgType<Args>...)>>,1590std::is_convertible<Base, OnceAction<R(Args...)>>>::value,1591int>::type = 0>1592operator OnceAction<R(Args...)>() && { // NOLINT1593// Return an action that first calls the initial action with arguments1594// filtered through InitialActionArgType, then forwards arguments directly1595// to the base class to deal with the remaining actions.1596struct OA {1597OnceAction<void(InitialActionArgType<Args>...)> initial_action;1598OnceAction<R(Args...)> remaining_actions;15991600R operator()(Args... args) && {1601std::move(initial_action)1602.Call(static_cast<InitialActionArgType<Args>>(args)...);16031604return std::move(remaining_actions).Call(std::forward<Args>(args)...);1605}1606};16071608return OA{1609std::move(initial_action_),1610std::move(static_cast<Base&>(*this)),1611};1612}16131614template <1615typename R, typename... Args,1616typename std::enable_if<1617conjunction<1618// Both the initial action and the rest must support conversion to1619// Action.1620std::is_convertible<const InitialAction&,1621Action<void(InitialActionArgType<Args>...)>>,1622std::is_convertible<const Base&, Action<R(Args...)>>>::value,1623int>::type = 0>1624operator Action<R(Args...)>() const { // NOLINT1625// Return an action that first calls the initial action with arguments1626// filtered through InitialActionArgType, then forwards arguments directly1627// to the base class to deal with the remaining actions.1628struct OA {1629Action<void(InitialActionArgType<Args>...)> initial_action;1630Action<R(Args...)> remaining_actions;16311632R operator()(Args... args) const {1633initial_action.Perform(std::forward_as_tuple(1634static_cast<InitialActionArgType<Args>>(args)...));16351636return remaining_actions.Perform(1637std::forward_as_tuple(std::forward<Args>(args)...));1638}1639};16401641return OA{1642initial_action_,1643static_cast<const Base&>(*this),1644};1645}16461647private:1648InitialAction initial_action_;1649};16501651template <typename T, typename... Params>1652struct ReturnNewAction {1653T* operator()() const {1654return internal::Apply(1655[](const Params&... unpacked_params) {1656return new T(unpacked_params...);1657},1658params);1659}1660std::tuple<Params...> params;1661};16621663template <size_t k>1664struct ReturnArgAction {1665template <typename... Args,1666typename = typename std::enable_if<(k < sizeof...(Args))>::type>1667auto operator()(Args&&... args) const -> decltype(std::get<k>(1668std::forward_as_tuple(std::forward<Args>(args)...))) {1669return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...));1670}1671};16721673template <size_t k, typename Ptr>1674struct SaveArgAction {1675Ptr pointer;16761677template <typename... Args>1678void operator()(const Args&... args) const {1679*pointer = std::get<k>(std::tie(args...));1680}1681};16821683template <size_t k, typename Ptr>1684struct SaveArgPointeeAction {1685Ptr pointer;16861687template <typename... Args>1688void operator()(const Args&... args) const {1689*pointer = *std::get<k>(std::tie(args...));1690}1691};16921693template <size_t k, typename T>1694struct SetArgRefereeAction {1695T value;16961697template <typename... Args>1698void operator()(Args&&... args) const {1699using argk_type =1700typename ::std::tuple_element<k, std::tuple<Args...>>::type;1701static_assert(std::is_lvalue_reference<argk_type>::value,1702"Argument must be a reference type.");1703std::get<k>(std::tie(args...)) = value;1704}1705};17061707template <size_t k, typename I1, typename I2>1708struct SetArrayArgumentAction {1709I1 first;1710I2 last;17111712template <typename... Args>1713void operator()(const Args&... args) const {1714auto value = std::get<k>(std::tie(args...));1715for (auto it = first; it != last; ++it, (void)++value) {1716*value = *it;1717}1718}1719};17201721template <size_t k>1722struct DeleteArgAction {1723template <typename... Args>1724void operator()(const Args&... args) const {1725delete std::get<k>(std::tie(args...));1726}1727};17281729template <typename Ptr>1730struct ReturnPointeeAction {1731Ptr pointer;1732template <typename... Args>1733auto operator()(const Args&...) const -> decltype(*pointer) {1734return *pointer;1735}1736};17371738#if GTEST_HAS_EXCEPTIONS1739template <typename T>1740struct ThrowAction {1741T exception;1742// We use a conversion operator to adapt to any return type.1743template <typename R, typename... Args>1744operator Action<R(Args...)>() const { // NOLINT1745T copy = exception;1746return [copy](Args...) -> R { throw copy; };1747}1748};1749struct RethrowAction {1750std::exception_ptr exception;1751template <typename R, typename... Args>1752operator Action<R(Args...)>() const { // NOLINT1753return [ex = exception](Args...) -> R { std::rethrow_exception(ex); };1754}1755};1756#endif // GTEST_HAS_EXCEPTIONS17571758} // namespace internal17591760// An Unused object can be implicitly constructed from ANY value.1761// This is handy when defining actions that ignore some or all of the1762// mock function arguments. For example, given1763//1764// MOCK_METHOD3(Foo, double(const string& label, double x, double y));1765// MOCK_METHOD3(Bar, double(int index, double x, double y));1766//1767// instead of1768//1769// double DistanceToOriginWithLabel(const string& label, double x, double y) {1770// return sqrt(x*x + y*y);1771// }1772// double DistanceToOriginWithIndex(int index, double x, double y) {1773// return sqrt(x*x + y*y);1774// }1775// ...1776// EXPECT_CALL(mock, Foo("abc", _, _))1777// .WillOnce(Invoke(DistanceToOriginWithLabel));1778// EXPECT_CALL(mock, Bar(5, _, _))1779// .WillOnce(Invoke(DistanceToOriginWithIndex));1780//1781// you could write1782//1783// // We can declare any uninteresting argument as Unused.1784// double DistanceToOrigin(Unused, double x, double y) {1785// return sqrt(x*x + y*y);1786// }1787// ...1788// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));1789// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));1790typedef internal::IgnoredValue Unused;17911792// Creates an action that does actions a1, a2, ..., sequentially in1793// each invocation. All but the last action will have a readonly view of the1794// arguments.1795template <typename... Action>1796internal::DoAllAction<typename std::decay<Action>::type...> DoAll(1797Action&&... action) {1798return internal::DoAllAction<typename std::decay<Action>::type...>(1799{}, std::forward<Action>(action)...);1800}18011802// WithArg<k>(an_action) creates an action that passes the k-th1803// (0-based) argument of the mock function to an_action and performs1804// it. It adapts an action accepting one argument to one that accepts1805// multiple arguments. For convenience, we also provide1806// WithArgs<k>(an_action) (defined below) as a synonym.1807template <size_t k, typename InnerAction>1808internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg(1809InnerAction&& action) {1810return {std::forward<InnerAction>(action)};1811}18121813// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes1814// the selected arguments of the mock function to an_action and1815// performs it. It serves as an adaptor between actions with1816// different argument lists.1817template <size_t k, size_t... ks, typename InnerAction>1818internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>1819WithArgs(InnerAction&& action) {1820return {std::forward<InnerAction>(action)};1821}18221823// WithoutArgs(inner_action) can be used in a mock function with a1824// non-empty argument list to perform inner_action, which takes no1825// argument. In other words, it adapts an action accepting no1826// argument to one that accepts (and ignores) arguments.1827template <typename InnerAction>1828internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs(1829InnerAction&& action) {1830return {std::forward<InnerAction>(action)};1831}18321833// Creates an action that returns a value.1834//1835// The returned type can be used with a mock function returning a non-void,1836// non-reference type U as follows:1837//1838// * If R is convertible to U and U is move-constructible, then the action can1839// be used with WillOnce.1840//1841// * If const R& is convertible to U and U is copy-constructible, then the1842// action can be used with both WillOnce and WillRepeatedly.1843//1844// The mock expectation contains the R value from which the U return value is1845// constructed (a move/copy of the argument to Return). This means that the R1846// value will survive at least until the mock object's expectations are cleared1847// or the mock object is destroyed, meaning that U can safely be a1848// reference-like type such as std::string_view:1849//1850// // The mock function returns a view of a copy of the string fed to1851// // Return. The view is valid even after the action is performed.1852// MockFunction<std::string_view()> mock;1853// EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco")));1854// const std::string_view result = mock.AsStdFunction()();1855// EXPECT_EQ("taco", result);1856//1857template <typename R>1858internal::ReturnAction<R> Return(R value) {1859return internal::ReturnAction<R>(std::move(value));1860}18611862// Creates an action that returns NULL.1863inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {1864return MakePolymorphicAction(internal::ReturnNullAction());1865}18661867// Creates an action that returns from a void function.1868inline PolymorphicAction<internal::ReturnVoidAction> Return() {1869return MakePolymorphicAction(internal::ReturnVoidAction());1870}18711872// Creates an action that returns the reference to a variable.1873template <typename R>1874inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT1875return internal::ReturnRefAction<R>(x);1876}18771878// Prevent using ReturnRef on reference to temporary.1879template <typename R, R* = nullptr>1880internal::ReturnRefAction<R> ReturnRef(R&&) = delete;18811882// Creates an action that returns the reference to a copy of the1883// argument. The copy is created when the action is constructed and1884// lives as long as the action.1885template <typename R>1886inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {1887return internal::ReturnRefOfCopyAction<R>(x);1888}18891890// DEPRECATED: use Return(x) directly with WillOnce.1891//1892// Modifies the parent action (a Return() action) to perform a move of the1893// argument instead of a copy.1894// Return(ByMove()) actions can only be executed once and will assert this1895// invariant.1896template <typename R>1897internal::ByMoveWrapper<R> ByMove(R x) {1898return internal::ByMoveWrapper<R>(std::move(x));1899}19001901// Creates an action that returns an element of `vals`. Calling this action will1902// repeatedly return the next value from `vals` until it reaches the end and1903// will restart from the beginning.1904template <typename T>1905internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {1906return internal::ReturnRoundRobinAction<T>(std::move(vals));1907}19081909// Creates an action that returns an element of `vals`. Calling this action will1910// repeatedly return the next value from `vals` until it reaches the end and1911// will restart from the beginning.1912template <typename T>1913internal::ReturnRoundRobinAction<T> ReturnRoundRobin(1914std::initializer_list<T> vals) {1915return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));1916}19171918// Creates an action that does the default action for the give mock function.1919inline internal::DoDefaultAction DoDefault() {1920return internal::DoDefaultAction();1921}19221923// Creates an action that sets the variable pointed by the N-th1924// (0-based) function argument to 'value'.1925template <size_t N, typename T>1926internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {1927return {std::move(value)};1928}19291930// The following version is DEPRECATED.1931template <size_t N, typename T>1932internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {1933return {std::move(value)};1934}19351936// Creates an action that sets a pointer referent to a given value.1937template <typename T1, typename T2>1938PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {1939return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));1940}19411942#ifndef GTEST_OS_WINDOWS_MOBILE19431944// Creates an action that sets errno and returns the appropriate error.1945template <typename T>1946PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(1947int errval, T result) {1948return MakePolymorphicAction(1949internal::SetErrnoAndReturnAction<T>(errval, result));1950}19511952#endif // !GTEST_OS_WINDOWS_MOBILE19531954// Various overloads for Invoke().19551956// Legacy function.1957// Actions can now be implicitly constructed from callables. No need to create1958// wrapper objects.1959// This function exists for backwards compatibility.1960template <typename FunctionImpl>1961typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {1962return std::forward<FunctionImpl>(function_impl);1963}19641965// Creates an action that invokes the given method on the given object1966// with the mock function's arguments.1967template <class Class, typename MethodPtr>1968internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,1969MethodPtr method_ptr) {1970return {obj_ptr, method_ptr};1971}19721973// Creates an action that invokes 'function_impl' with no argument.1974template <typename FunctionImpl>1975internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>1976InvokeWithoutArgs(FunctionImpl function_impl) {1977return {std::move(function_impl)};1978}19791980// Creates an action that invokes the given method on the given object1981// with no argument.1982template <class Class, typename MethodPtr>1983internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(1984Class* obj_ptr, MethodPtr method_ptr) {1985return {obj_ptr, method_ptr};1986}19871988// Creates an action that performs an_action and throws away its1989// result. In other words, it changes the return type of an_action to1990// void. an_action MUST NOT return void, or the code won't compile.1991template <typename A>1992inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {1993return internal::IgnoreResultAction<A>(an_action);1994}19951996// Creates a reference wrapper for the given L-value. If necessary,1997// you can explicitly specify the type of the reference. For example,1998// suppose 'derived' is an object of type Derived, ByRef(derived)1999// would wrap a Derived&. If you want to wrap a const Base& instead,2000// where Base is a base class of Derived, just write:2001//2002// ByRef<const Base>(derived)2003//2004// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.2005// However, it may still be used for consistency with ByMove().2006template <typename T>2007inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT2008return ::std::reference_wrapper<T>(l_value);2009}20102011// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new2012// instance of type T, constructed on the heap with constructor arguments2013// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.2014template <typename T, typename... Params>2015internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(2016Params&&... params) {2017return {std::forward_as_tuple(std::forward<Params>(params)...)};2018}20192020// Action ReturnArg<k>() returns the k-th argument of the mock function.2021template <size_t k>2022internal::ReturnArgAction<k> ReturnArg() {2023return {};2024}20252026// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the2027// mock function to *pointer.2028template <size_t k, typename Ptr>2029internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {2030return {pointer};2031}20322033// Action SaveArgPointee<k>(pointer) saves the value pointed to2034// by the k-th (0-based) argument of the mock function to *pointer.2035template <size_t k, typename Ptr>2036internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {2037return {pointer};2038}20392040// Action SetArgReferee<k>(value) assigns 'value' to the variable2041// referenced by the k-th (0-based) argument of the mock function.2042template <size_t k, typename T>2043internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(2044T&& value) {2045return {std::forward<T>(value)};2046}20472048// Action SetArrayArgument<k>(first, last) copies the elements in2049// source range [first, last) to the array pointed to by the k-th2050// (0-based) argument, which can be either a pointer or an2051// iterator. The action does not take ownership of the elements in the2052// source range.2053template <size_t k, typename I1, typename I2>2054internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,2055I2 last) {2056return {first, last};2057}20582059// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock2060// function.2061template <size_t k>2062internal::DeleteArgAction<k> DeleteArg() {2063return {};2064}20652066// This action returns the value pointed to by 'pointer'.2067template <typename Ptr>2068internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {2069return {pointer};2070}20712072#if GTEST_HAS_EXCEPTIONS2073// Action Throw(exception) can be used in a mock function of any type2074// to throw the given exception. Any copyable value can be thrown,2075// except for std::exception_ptr, which is likely a mistake if2076// thrown directly.2077template <typename T>2078typename std::enable_if<2079!std::is_base_of<std::exception_ptr, typename std::decay<T>::type>::value,2080internal::ThrowAction<typename std::decay<T>::type>>::type2081Throw(T&& exception) {2082return {std::forward<T>(exception)};2083}2084// Action Rethrow(exception_ptr) can be used in a mock function of any type2085// to rethrow any exception_ptr. Note that the same object is thrown each time.2086inline internal::RethrowAction Rethrow(std::exception_ptr exception) {2087return {std::move(exception)};2088}2089#endif // GTEST_HAS_EXCEPTIONS20902091namespace internal {20922093// A macro from the ACTION* family (defined later in gmock-generated-actions.h)2094// defines an action that can be used in a mock function. Typically,2095// these actions only care about a subset of the arguments of the mock2096// function. For example, if such an action only uses the second2097// argument, it can be used in any mock function that takes >= 22098// arguments where the type of the second argument is compatible.2099//2100// Therefore, the action implementation must be prepared to take more2101// arguments than it needs. The ExcessiveArg type is used to2102// represent those excessive arguments. In order to keep the compiler2103// error messages tractable, we define it in the testing namespace2104// instead of testing::internal. However, this is an INTERNAL TYPE2105// and subject to change without notice, so a user MUST NOT USE THIS2106// TYPE DIRECTLY.2107struct ExcessiveArg {};21082109// Builds an implementation of an Action<> for some particular signature, using2110// a class defined by an ACTION* macro.2111template <typename F, typename Impl>2112struct ActionImpl;21132114template <typename Impl>2115struct ImplBase {2116struct Holder {2117// Allows each copy of the Action<> to get to the Impl.2118explicit operator const Impl&() const { return *ptr; }2119std::shared_ptr<Impl> ptr;2120};2121using type = typename std::conditional<std::is_constructible<Impl>::value,2122Impl, Holder>::type;2123};21242125template <typename R, typename... Args, typename Impl>2126struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {2127using Base = typename ImplBase<Impl>::type;2128using function_type = R(Args...);2129using args_type = std::tuple<Args...>;21302131ActionImpl() = default; // Only defined if appropriate for Base.2132explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {}21332134R operator()(Args&&... arg) const {2135static constexpr size_t kMaxArgs =2136sizeof...(Args) <= 10 ? sizeof...(Args) : 10;2137return Apply(std::make_index_sequence<kMaxArgs>{},2138std::make_index_sequence<10 - kMaxArgs>{},2139args_type{std::forward<Args>(arg)...});2140}21412142template <std::size_t... arg_id, std::size_t... excess_id>2143R Apply(std::index_sequence<arg_id...>, std::index_sequence<excess_id...>,2144const args_type& args) const {2145// Impl need not be specific to the signature of action being implemented;2146// only the implementing function body needs to have all of the specific2147// types instantiated. Up to 10 of the args that are provided by the2148// args_type get passed, followed by a dummy of unspecified type for the2149// remainder up to 10 explicit args.2150static constexpr ExcessiveArg kExcessArg{};2151return static_cast<const Impl&>(*this)2152.template gmock_PerformImpl<2153/*function_type=*/function_type, /*return_type=*/R,2154/*args_type=*/args_type,2155/*argN_type=*/2156typename std::tuple_element<arg_id, args_type>::type...>(2157/*args=*/args, std::get<arg_id>(args)...,2158((void)excess_id, kExcessArg)...);2159}2160};21612162// Stores a default-constructed Impl as part of the Action<>'s2163// std::function<>. The Impl should be trivial to copy.2164template <typename F, typename Impl>2165::testing::Action<F> MakeAction() {2166return ::testing::Action<F>(ActionImpl<F, Impl>());2167}21682169// Stores just the one given instance of Impl.2170template <typename F, typename Impl>2171::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {2172return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));2173}21742175#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \2176, GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const arg##i##_type& arg##i2177#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \2178GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const args_type& args GMOCK_PP_REPEAT( \2179GMOCK_INTERNAL_ARG_UNUSED, , 10)21802181#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i2182#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \2183const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)21842185#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type2186#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \2187GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))21882189#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type2190#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \2191GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))21922193#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type2194#define GMOCK_ACTION_TYPE_PARAMS_(params) \2195GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))21962197#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \2198, param##_type gmock_p##i2199#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \2200GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))22012202#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \2203, std::forward<param##_type>(gmock_p##i)2204#define GMOCK_ACTION_GVALUE_PARAMS_(params) \2205GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))22062207#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \2208, param(::std::forward<param##_type>(gmock_p##i))2209#define GMOCK_ACTION_INIT_PARAMS_(params) \2210GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))22112212#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;2213#define GMOCK_ACTION_FIELD_PARAMS_(params) \2214GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)22152216#define GMOCK_INTERNAL_ACTION(name, full_name, params) \2217template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \2218class full_name { \2219public: \2220explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \2221: impl_(std::make_shared<gmock_Impl>( \2222GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \2223full_name(const full_name&) = default; \2224full_name(full_name&&) noexcept = default; \2225template <typename F> \2226operator ::testing::Action<F>() const { \2227return ::testing::internal::MakeAction<F>(impl_); \2228} \2229\2230private: \2231class gmock_Impl { \2232public: \2233explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \2234: GMOCK_ACTION_INIT_PARAMS_(params) {} \2235template <typename function_type, typename return_type, \2236typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \2237return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \2238GMOCK_ACTION_FIELD_PARAMS_(params) \2239}; \2240std::shared_ptr<const gmock_Impl> impl_; \2241}; \2242template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \2243inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \2244GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \2245template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \2246inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \2247GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \2248return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \2249GMOCK_ACTION_GVALUE_PARAMS_(params)); \2250} \2251template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \2252template <typename function_type, typename return_type, typename args_type, \2253GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \2254return_type \2255full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \2256GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const22572258} // namespace internal22592260// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.2261#define ACTION(name) \2262class name##Action { \2263public: \2264explicit name##Action() noexcept {} \2265name##Action(const name##Action&) noexcept {} \2266template <typename F> \2267operator ::testing::Action<F>() const { \2268return ::testing::internal::MakeAction<F, gmock_Impl>(); \2269} \2270\2271private: \2272class gmock_Impl { \2273public: \2274template <typename function_type, typename return_type, \2275typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \2276return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \2277}; \2278}; \2279inline name##Action name() GTEST_MUST_USE_RESULT_; \2280inline name##Action name() { return name##Action(); } \2281template <typename function_type, typename return_type, typename args_type, \2282GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \2283return_type name##Action::gmock_Impl::gmock_PerformImpl( \2284GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const22852286#define ACTION_P(name, ...) \2287GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))22882289#define ACTION_P2(name, ...) \2290GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))22912292#define ACTION_P3(name, ...) \2293GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))22942295#define ACTION_P4(name, ...) \2296GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))22972298#define ACTION_P5(name, ...) \2299GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))23002301#define ACTION_P6(name, ...) \2302GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))23032304#define ACTION_P7(name, ...) \2305GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))23062307#define ACTION_P8(name, ...) \2308GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))23092310#define ACTION_P9(name, ...) \2311GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))23122313#define ACTION_P10(name, ...) \2314GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))23152316} // namespace testing23172318GTEST_DISABLE_MSC_WARNINGS_POP_() // 410023192320#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_232123222323