Path: blob/main/contrib/googletest/googlemock/test/gmock-actions_test.cc
48254 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// This file tests the built-in actions.3233#include "gmock/gmock-actions.h"3435#include <algorithm>36#include <functional>37#include <iterator>38#include <memory>39#include <sstream>40#include <string>41#include <tuple>42#include <type_traits>43#include <utility>44#include <vector>4546#include "gmock/gmock.h"47#include "gmock/internal/gmock-port.h"48#include "gtest/gtest-spi.h"49#include "gtest/gtest.h"50#include "gtest/internal/gtest-port.h"5152// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name53// length exceeded) for MSVC.54GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)55#if defined(_MSC_VER) && (_MSC_VER == 1900)56// and silence C4800 (C4800: 'int *const ': forcing value57// to bool 'true' or 'false') for MSVC 1558GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)59#endif6061namespace testing {62namespace {6364using ::testing::internal::BuiltInDefaultValue;6566TEST(TypeTraits, Negation) {67// Direct use with std types.68static_assert(std::is_base_of<std::false_type,69internal::negation<std::true_type>>::value,70"");7172static_assert(std::is_base_of<std::true_type,73internal::negation<std::false_type>>::value,74"");7576// With other types that fit the requirement of a value member that is77// convertible to bool.78static_assert(std::is_base_of<79std::true_type,80internal::negation<std::integral_constant<int, 0>>>::value,81"");8283static_assert(std::is_base_of<84std::false_type,85internal::negation<std::integral_constant<int, 1>>>::value,86"");8788static_assert(std::is_base_of<89std::false_type,90internal::negation<std::integral_constant<int, -1>>>::value,91"");92}9394// Weird false/true types that aren't actually bool constants (but should still95// be legal according to [meta.logical] because `bool(T::value)` is valid), are96// distinct from std::false_type and std::true_type, and are distinct from other97// instantiations of the same template.98//99// These let us check finicky details mandated by the standard like100// "std::conjunction should evaluate to a type that inherits from the first101// false-y input".102template <int>103struct MyFalse : std::integral_constant<int, 0> {};104105template <int>106struct MyTrue : std::integral_constant<int, -1> {};107108TEST(TypeTraits, Conjunction) {109// Base case: always true.110static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value,111"");112113// One predicate: inherits from that predicate, regardless of value.114static_assert(115std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value,116"");117118static_assert(119std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, "");120121// Multiple predicates, with at least one false: inherits from that one.122static_assert(123std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,124MyTrue<2>>>::value,125"");126127static_assert(128std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,129MyFalse<2>>>::value,130"");131132// Short circuiting: in the case above, additional predicates need not even133// define a value member.134struct Empty {};135static_assert(136std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,137Empty>>::value,138"");139140// All predicates true: inherits from the last.141static_assert(142std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>,143MyTrue<2>>>::value,144"");145}146147TEST(TypeTraits, Disjunction) {148// Base case: always false.149static_assert(150std::is_base_of<std::false_type, internal::disjunction<>>::value, "");151152// One predicate: inherits from that predicate, regardless of value.153static_assert(154std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value,155"");156157static_assert(158std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, "");159160// Multiple predicates, with at least one true: inherits from that one.161static_assert(162std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,163MyFalse<2>>>::value,164"");165166static_assert(167std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,168MyTrue<2>>>::value,169"");170171// Short circuiting: in the case above, additional predicates need not even172// define a value member.173struct Empty {};174static_assert(175std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,176Empty>>::value,177"");178179// All predicates false: inherits from the last.180static_assert(181std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>,182MyFalse<2>>>::value,183"");184}185186TEST(TypeTraits, IsInvocableRV) {187struct C {188int operator()() const { return 0; }189void operator()(int) & {}190std::string operator()(int) && { return ""; };191};192193// The first overload is callable for const and non-const rvalues and lvalues.194// It can be used to obtain an int, cv void, or anything int is convertible195// to.196static_assert(internal::is_callable_r<int, C>::value, "");197static_assert(internal::is_callable_r<int, C&>::value, "");198static_assert(internal::is_callable_r<int, const C>::value, "");199static_assert(internal::is_callable_r<int, const C&>::value, "");200201static_assert(internal::is_callable_r<void, C>::value, "");202static_assert(internal::is_callable_r<const volatile void, C>::value, "");203static_assert(internal::is_callable_r<char, C>::value, "");204205// It's possible to provide an int. If it's given to an lvalue, the result is206// void. Otherwise it is std::string (which is also treated as allowed for a207// void result type).208static_assert(internal::is_callable_r<void, C&, int>::value, "");209static_assert(!internal::is_callable_r<int, C&, int>::value, "");210static_assert(!internal::is_callable_r<std::string, C&, int>::value, "");211static_assert(!internal::is_callable_r<void, const C&, int>::value, "");212213static_assert(internal::is_callable_r<std::string, C, int>::value, "");214static_assert(internal::is_callable_r<void, C, int>::value, "");215static_assert(!internal::is_callable_r<int, C, int>::value, "");216217// It's not possible to provide other arguments.218static_assert(!internal::is_callable_r<void, C, std::string>::value, "");219static_assert(!internal::is_callable_r<void, C, int, int>::value, "");220221// In C++17 and above, where it's guaranteed that functions can return222// non-moveable objects, everything should work fine for non-moveable rsult223// types too.224#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \225GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L226{227struct NonMoveable {228NonMoveable() = default;229NonMoveable(NonMoveable&&) = delete;230};231232static_assert(!std::is_move_constructible_v<NonMoveable>);233234struct Callable {235NonMoveable operator()() { return NonMoveable(); }236};237238static_assert(internal::is_callable_r<NonMoveable, Callable>::value);239static_assert(internal::is_callable_r<void, Callable>::value);240static_assert(241internal::is_callable_r<const volatile void, Callable>::value);242243static_assert(!internal::is_callable_r<int, Callable>::value);244static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);245}246#endif // C++17 and above247248// Nothing should choke when we try to call other arguments besides directly249// callable objects, but they should not show up as callable.250static_assert(!internal::is_callable_r<void, int>::value, "");251static_assert(!internal::is_callable_r<void, void (C::*)()>::value, "");252static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, "");253}254255// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.256TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {257EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr);258EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr);259EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr);260}261262// Tests that BuiltInDefaultValue<T*>::Exists() return true.263TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {264EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());265EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());266EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());267}268269// Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a270// built-in numeric type.271TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {272EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());273EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());274EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());275#if GMOCK_WCHAR_T_IS_NATIVE_276#if !defined(__WCHAR_UNSIGNED__)277EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());278#else279EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());280#endif281#endif282EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT283EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT284EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT285EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());286EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());287EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());288EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT289EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT290EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT291EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get()); // NOLINT292EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get()); // NOLINT293EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); // NOLINT294EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());295EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());296}297298// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a299// built-in numeric type.300TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {301EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());302EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());303EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());304#if GMOCK_WCHAR_T_IS_NATIVE_305EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());306#endif307EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT308EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT309EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT310EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());311EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());312EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());313EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT314EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT315EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT316EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); // NOLINT317EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); // NOLINT318EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); // NOLINT319EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());320EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());321}322323// Tests that BuiltInDefaultValue<bool>::Get() returns false.324TEST(BuiltInDefaultValueTest, IsFalseForBool) {325EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());326}327328// Tests that BuiltInDefaultValue<bool>::Exists() returns true.329TEST(BuiltInDefaultValueTest, BoolExists) {330EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());331}332333// Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a334// string type.335TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {336EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get());337}338339// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a340// string type.341TEST(BuiltInDefaultValueTest, ExistsForString) {342EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists());343}344345// Tests that BuiltInDefaultValue<const T>::Get() returns the same346// value as BuiltInDefaultValue<T>::Get() does.347TEST(BuiltInDefaultValueTest, WorksForConstTypes) {348EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());349EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());350EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);351EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());352}353354// A type that's default constructible.355class MyDefaultConstructible {356public:357MyDefaultConstructible() : value_(42) {}358359int value() const { return value_; }360361private:362int value_;363};364365// A type that's not default constructible.366class MyNonDefaultConstructible {367public:368// Does not have a default ctor.369explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}370371int value() const { return value_; }372373private:374int value_;375};376377TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {378EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());379}380381TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {382EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());383}384385TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {386EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());387}388389// Tests that BuiltInDefaultValue<T&>::Get() aborts the program.390TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {391EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, "");392EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, "");393}394395TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {396EXPECT_DEATH_IF_SUPPORTED(397{ BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, "");398}399400// Tests that DefaultValue<T>::IsSet() is false initially.401TEST(DefaultValueTest, IsInitiallyUnset) {402EXPECT_FALSE(DefaultValue<int>::IsSet());403EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());404EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());405}406407// Tests that DefaultValue<T> can be set and then unset.408TEST(DefaultValueTest, CanBeSetAndUnset) {409EXPECT_TRUE(DefaultValue<int>::Exists());410EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());411412DefaultValue<int>::Set(1);413DefaultValue<const MyNonDefaultConstructible>::Set(414MyNonDefaultConstructible(42));415416EXPECT_EQ(1, DefaultValue<int>::Get());417EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());418419EXPECT_TRUE(DefaultValue<int>::Exists());420EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());421422DefaultValue<int>::Clear();423DefaultValue<const MyNonDefaultConstructible>::Clear();424425EXPECT_FALSE(DefaultValue<int>::IsSet());426EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());427428EXPECT_TRUE(DefaultValue<int>::Exists());429EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());430}431432// Tests that DefaultValue<T>::Get() returns the433// BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is434// false.435TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {436EXPECT_FALSE(DefaultValue<int>::IsSet());437EXPECT_TRUE(DefaultValue<int>::Exists());438EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());439EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());440441EXPECT_EQ(0, DefaultValue<int>::Get());442443EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },444"");445}446447TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {448EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());449EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);450DefaultValue<std::unique_ptr<int>>::SetFactory(451[] { return std::make_unique<int>(42); });452EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());453std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();454EXPECT_EQ(42, *i);455}456457// Tests that DefaultValue<void>::Get() returns void.458TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); }459460// Tests using DefaultValue with a reference type.461462// Tests that DefaultValue<T&>::IsSet() is false initially.463TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {464EXPECT_FALSE(DefaultValue<int&>::IsSet());465EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());466EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());467}468469// Tests that DefaultValue<T&>::Exists is false initially.470TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {471EXPECT_FALSE(DefaultValue<int&>::Exists());472EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());473EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());474}475476// Tests that DefaultValue<T&> can be set and then unset.477TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {478int n = 1;479DefaultValue<const int&>::Set(n);480MyNonDefaultConstructible x(42);481DefaultValue<MyNonDefaultConstructible&>::Set(x);482483EXPECT_TRUE(DefaultValue<const int&>::Exists());484EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());485486EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));487EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));488489DefaultValue<const int&>::Clear();490DefaultValue<MyNonDefaultConstructible&>::Clear();491492EXPECT_FALSE(DefaultValue<const int&>::Exists());493EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());494495EXPECT_FALSE(DefaultValue<const int&>::IsSet());496EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());497}498499// Tests that DefaultValue<T&>::Get() returns the500// BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is501// false.502TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {503EXPECT_FALSE(DefaultValue<int&>::IsSet());504EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());505506EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");507EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },508"");509}510511// Tests that ActionInterface can be implemented by defining the512// Perform method.513514typedef int MyGlobalFunction(bool, int);515516class MyActionImpl : public ActionInterface<MyGlobalFunction> {517public:518int Perform(const std::tuple<bool, int>& args) override {519return std::get<0>(args) ? std::get<1>(args) : 0;520}521};522523TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {524MyActionImpl my_action_impl;525(void)my_action_impl;526}527528TEST(ActionInterfaceTest, MakeAction) {529Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);530531// When exercising the Perform() method of Action<F>, we must pass532// it a tuple whose size and type are compatible with F's argument533// types. For example, if F is int(), then Perform() takes a534// 0-tuple; if F is void(bool, int), then Perform() takes a535// std::tuple<bool, int>, and so on.536EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));537}538539// Tests that Action<F> can be constructed from a pointer to540// ActionInterface<F>.541TEST(ActionTest, CanBeConstructedFromActionInterface) {542Action<MyGlobalFunction> action(new MyActionImpl);543}544545// Tests that Action<F> delegates actual work to ActionInterface<F>.546TEST(ActionTest, DelegatesWorkToActionInterface) {547const Action<MyGlobalFunction> action(new MyActionImpl);548549EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));550EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1)));551}552553// Tests that Action<F> can be copied.554TEST(ActionTest, IsCopyable) {555Action<MyGlobalFunction> a1(new MyActionImpl);556Action<MyGlobalFunction> a2(a1); // Tests the copy constructor.557558// a1 should continue to work after being copied from.559EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));560EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));561562// a2 should work like the action it was copied from.563EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));564EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));565566a2 = a1; // Tests the assignment operator.567568// a1 should continue to work after being copied from.569EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));570EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));571572// a2 should work like the action it was copied from.573EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));574EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));575}576577// Tests that an Action<From> object can be converted to a578// compatible Action<To> object.579580class IsNotZero : public ActionInterface<bool(int)> { // NOLINT581public:582bool Perform(const std::tuple<int>& arg) override {583return std::get<0>(arg) != 0;584}585};586587TEST(ActionTest, CanBeConvertedToOtherActionType) {588const Action<bool(int)> a1(new IsNotZero); // NOLINT589const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT590EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));591EXPECT_EQ(0, a2.Perform(std::make_tuple('\0')));592}593594// The following two classes are for testing MakePolymorphicAction().595596// Implements a polymorphic action that returns the second of the597// arguments it receives.598class ReturnSecondArgumentAction {599public:600// We want to verify that MakePolymorphicAction() can work with a601// polymorphic action whose Perform() method template is either602// const or not. This lets us verify the non-const case.603template <typename Result, typename ArgumentTuple>604Result Perform(const ArgumentTuple& args) {605return std::get<1>(args);606}607};608609// Implements a polymorphic action that can be used in a nullary610// function to return 0.611class ReturnZeroFromNullaryFunctionAction {612public:613// For testing that MakePolymorphicAction() works when the614// implementation class' Perform() method template takes only one615// template parameter.616//617// We want to verify that MakePolymorphicAction() can work with a618// polymorphic action whose Perform() method template is either619// const or not. This lets us verify the const case.620template <typename Result>621Result Perform(const std::tuple<>&) const {622return 0;623}624};625626// These functions verify that MakePolymorphicAction() returns a627// PolymorphicAction<T> where T is the argument's type.628629PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {630return MakePolymorphicAction(ReturnSecondArgumentAction());631}632633PolymorphicAction<ReturnZeroFromNullaryFunctionAction>634ReturnZeroFromNullaryFunction() {635return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());636}637638// Tests that MakePolymorphicAction() turns a polymorphic action639// implementation class into a polymorphic action.640TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {641Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT642EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0)));643}644645// Tests that MakePolymorphicAction() works when the implementation646// class' Perform() method template has only one template parameter.647TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {648Action<int()> a1 = ReturnZeroFromNullaryFunction();649EXPECT_EQ(0, a1.Perform(std::make_tuple()));650651Action<void*()> a2 = ReturnZeroFromNullaryFunction();652EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr);653}654655// Tests that Return() works as an action for void-returning656// functions.657TEST(ReturnTest, WorksForVoid) {658const Action<void(int)> ret = Return(); // NOLINT659return ret.Perform(std::make_tuple(1));660}661662// Tests that Return(v) returns v.663TEST(ReturnTest, ReturnsGivenValue) {664Action<int()> ret = Return(1); // NOLINT665EXPECT_EQ(1, ret.Perform(std::make_tuple()));666667ret = Return(-5);668EXPECT_EQ(-5, ret.Perform(std::make_tuple()));669}670671// Tests that Return("string literal") works.672TEST(ReturnTest, AcceptsStringLiteral) {673Action<const char*()> a1 = Return("Hello");674EXPECT_STREQ("Hello", a1.Perform(std::make_tuple()));675676Action<std::string()> a2 = Return("world");677EXPECT_EQ("world", a2.Perform(std::make_tuple()));678}679680// Return(x) should work fine when the mock function's return type is a681// reference-like wrapper for decltype(x), as when x is a std::string and the682// mock function returns std::string_view.683TEST(ReturnTest, SupportsReferenceLikeReturnType) {684// A reference wrapper for std::vector<int>, implicitly convertible from it.685struct Result {686const std::vector<int>* v;687Result(const std::vector<int>& vec) : v(&vec) {} // NOLINT688};689690// Set up an action for a mock function that returns the reference wrapper691// type, initializing it with an actual vector.692//693// The returned wrapper should be initialized with a copy of that vector694// that's embedded within the action itself (which should stay alive as long695// as the mock object is alive), rather than e.g. a reference to the temporary696// we feed to Return. This should work fine both for WillOnce and697// WillRepeatedly.698MockFunction<Result()> mock;699EXPECT_CALL(mock, Call)700.WillOnce(Return(std::vector<int>{17, 19, 23}))701.WillRepeatedly(Return(std::vector<int>{29, 31, 37}));702703EXPECT_THAT(mock.AsStdFunction()(),704Field(&Result::v, Pointee(ElementsAre(17, 19, 23))));705706EXPECT_THAT(mock.AsStdFunction()(),707Field(&Result::v, Pointee(ElementsAre(29, 31, 37))));708}709710TEST(ReturnTest, PrefersConversionOperator) {711// Define types In and Out such that:712//713// * In is implicitly convertible to Out.714// * Out also has an explicit constructor from In.715//716struct In;717struct Out {718int x;719720explicit Out(const int val) : x(val) {}721explicit Out(const In&) : x(0) {}722};723724struct In {725operator Out() const { return Out{19}; } // NOLINT726};727728// Assumption check: the C++ language rules are such that a function that729// returns Out which uses In a return statement will use the implicit730// conversion path rather than the explicit constructor.731EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19));732733// Return should work the same way: if the mock function's return type is Out734// and we feed Return an In value, then the Out should be created through the735// implicit conversion path rather than the explicit constructor.736MockFunction<Out()> mock;737EXPECT_CALL(mock, Call).WillOnce(Return(In()));738EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19));739}740741// It should be possible to use Return(R) with a mock function result type U742// that is convertible from const R& but *not* R (such as743// std::reference_wrapper). This should work for both WillOnce and744// WillRepeatedly.745TEST(ReturnTest, ConversionRequiresConstLvalueReference) {746using R = int;747using U = std::reference_wrapper<const int>;748749static_assert(std::is_convertible<const R&, U>::value, "");750static_assert(!std::is_convertible<R, U>::value, "");751752MockFunction<U()> mock;753EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19));754755EXPECT_EQ(17, mock.AsStdFunction()());756EXPECT_EQ(19, mock.AsStdFunction()());757}758759// Return(x) should not be usable with a mock function result type that's760// implicitly convertible from decltype(x) but requires a non-const lvalue761// reference to the input. It doesn't make sense for the conversion operator to762// modify the input.763TEST(ReturnTest, ConversionRequiresMutableLvalueReference) {764// Set up a type that is implicitly convertible from std::string&, but not765// std::string&& or `const std::string&`.766//767// Avoid asserting about conversion from std::string on MSVC, which seems to768// implement std::is_convertible incorrectly in this case.769struct S {770S(std::string&) {} // NOLINT771};772773static_assert(std::is_convertible<std::string&, S>::value, "");774#ifndef _MSC_VER775static_assert(!std::is_convertible<std::string&&, S>::value, "");776#endif777static_assert(!std::is_convertible<const std::string&, S>::value, "");778779// It shouldn't be possible to use the result of Return(std::string) in a780// context where an S is needed.781//782// Here too we disable the assertion for MSVC, since its incorrect783// implementation of is_convertible causes our SFINAE to be wrong.784using RA = decltype(Return(std::string()));785786static_assert(!std::is_convertible<RA, Action<S()>>::value, "");787#ifndef _MSC_VER788static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, "");789#endif790}791792TEST(ReturnTest, MoveOnlyResultType) {793// Return should support move-only result types when used with WillOnce.794{795MockFunction<std::unique_ptr<int>()> mock;796EXPECT_CALL(mock, Call)797// NOLINTNEXTLINE798.WillOnce(Return(std::unique_ptr<int>(new int(17))));799800EXPECT_THAT(mock.AsStdFunction()(), Pointee(17));801}802803// The result of Return should not be convertible to Action (so it can't be804// used with WillRepeatedly).805static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())),806Action<std::unique_ptr<int>()>>::value,807"");808}809810// Tests that Return(v) is covariant.811812struct Base {813bool operator==(const Base&) { return true; }814};815816struct Derived : public Base {817bool operator==(const Derived&) { return true; }818};819820TEST(ReturnTest, IsCovariant) {821Base base;822Derived derived;823Action<Base*()> ret = Return(&base);824EXPECT_EQ(&base, ret.Perform(std::make_tuple()));825826ret = Return(&derived);827EXPECT_EQ(&derived, ret.Perform(std::make_tuple()));828}829830// Tests that the type of the value passed into Return is converted into T831// when the action is cast to Action<T(...)> rather than when the action is832// performed. See comments on testing::internal::ReturnAction in833// gmock-actions.h for more information.834class FromType {835public:836explicit FromType(bool* is_converted) : converted_(is_converted) {}837bool* converted() const { return converted_; }838839private:840bool* const converted_;841};842843class ToType {844public:845// Must allow implicit conversion due to use in ImplicitCast_<T>.846ToType(const FromType& x) { *x.converted() = true; } // NOLINT847};848849TEST(ReturnTest, ConvertsArgumentWhenConverted) {850bool converted = false;851FromType x(&converted);852Action<ToType()> action(Return(x));853EXPECT_TRUE(converted) << "Return must convert its argument in its own "854<< "conversion operator.";855converted = false;856action.Perform(std::tuple<>());857EXPECT_FALSE(converted) << "Action must NOT convert its argument "858<< "when performed.";859}860861// Tests that ReturnNull() returns NULL in a pointer-returning function.862TEST(ReturnNullTest, WorksInPointerReturningFunction) {863const Action<int*()> a1 = ReturnNull();864EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);865866const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT867EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr);868}869870// Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning871// functions.872TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {873const Action<std::unique_ptr<const int>()> a1 = ReturnNull();874EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);875876const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();877EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr);878}879880// Tests that ReturnRef(v) works for reference types.881TEST(ReturnRefTest, WorksForReference) {882const int n = 0;883const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT884885EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true)));886}887888// Tests that ReturnRef(v) is covariant.889TEST(ReturnRefTest, IsCovariant) {890Base base;891Derived derived;892Action<Base&()> a = ReturnRef(base);893EXPECT_EQ(&base, &a.Perform(std::make_tuple()));894895a = ReturnRef(derived);896EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));897}898899template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>900bool CanCallReturnRef(T&&) {901return true;902}903bool CanCallReturnRef(Unused) { return false; }904905// Tests that ReturnRef(v) is working with non-temporaries (T&)906TEST(ReturnRefTest, WorksForNonTemporary) {907int scalar_value = 123;908EXPECT_TRUE(CanCallReturnRef(scalar_value));909910std::string non_scalar_value("ABC");911EXPECT_TRUE(CanCallReturnRef(non_scalar_value));912913const int const_scalar_value{321};914EXPECT_TRUE(CanCallReturnRef(const_scalar_value));915916const std::string const_non_scalar_value("CBA");917EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value));918}919920// Tests that ReturnRef(v) is not working with temporaries (T&&)921TEST(ReturnRefTest, DoesNotWorkForTemporary) {922auto scalar_value = []() -> int { return 123; };923EXPECT_FALSE(CanCallReturnRef(scalar_value()));924925auto non_scalar_value = []() -> std::string { return "ABC"; };926EXPECT_FALSE(CanCallReturnRef(non_scalar_value()));927928// cannot use here callable returning "const scalar type",929// because such const for scalar return type is ignored930EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321)));931932auto const_non_scalar_value = []() -> const std::string { return "CBA"; };933EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value()));934}935936// Tests that ReturnRefOfCopy(v) works for reference types.937TEST(ReturnRefOfCopyTest, WorksForReference) {938int n = 42;939const Action<const int&()> ret = ReturnRefOfCopy(n);940941EXPECT_NE(&n, &ret.Perform(std::make_tuple()));942EXPECT_EQ(42, ret.Perform(std::make_tuple()));943944n = 43;945EXPECT_NE(&n, &ret.Perform(std::make_tuple()));946EXPECT_EQ(42, ret.Perform(std::make_tuple()));947}948949// Tests that ReturnRefOfCopy(v) is covariant.950TEST(ReturnRefOfCopyTest, IsCovariant) {951Base base;952Derived derived;953Action<Base&()> a = ReturnRefOfCopy(base);954EXPECT_NE(&base, &a.Perform(std::make_tuple()));955956a = ReturnRefOfCopy(derived);957EXPECT_NE(&derived, &a.Perform(std::make_tuple()));958}959960// Tests that ReturnRoundRobin(v) works with initializer lists961TEST(ReturnRoundRobinTest, WorksForInitList) {962Action<int()> ret = ReturnRoundRobin({1, 2, 3});963964EXPECT_EQ(1, ret.Perform(std::make_tuple()));965EXPECT_EQ(2, ret.Perform(std::make_tuple()));966EXPECT_EQ(3, ret.Perform(std::make_tuple()));967EXPECT_EQ(1, ret.Perform(std::make_tuple()));968EXPECT_EQ(2, ret.Perform(std::make_tuple()));969EXPECT_EQ(3, ret.Perform(std::make_tuple()));970}971972// Tests that ReturnRoundRobin(v) works with vectors973TEST(ReturnRoundRobinTest, WorksForVector) {974std::vector<double> v = {4.4, 5.5, 6.6};975Action<double()> ret = ReturnRoundRobin(v);976977EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));978EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));979EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));980EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));981EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));982EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));983}984985// Tests that DoDefault() does the default action for the mock method.986987class MockClass {988public:989MockClass() = default;990991MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT992MOCK_METHOD0(Foo, MyNonDefaultConstructible());993MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());994MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());995MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());996MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));997MOCK_METHOD2(TakeUnique,998int(const std::unique_ptr<int>&, std::unique_ptr<int>));9991000private:1001MockClass(const MockClass&) = delete;1002MockClass& operator=(const MockClass&) = delete;1003};10041005// Tests that DoDefault() returns the built-in default value for the1006// return type by default.1007TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {1008MockClass mock;1009EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());1010EXPECT_EQ(0, mock.IntFunc(true));1011}10121013// Tests that DoDefault() throws (when exceptions are enabled) or aborts1014// the process when there is no built-in default value for the return type.1015TEST(DoDefaultDeathTest, DiesForUnknowType) {1016MockClass mock;1017EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault());1018#if GTEST_HAS_EXCEPTIONS1019EXPECT_ANY_THROW(mock.Foo());1020#else1021EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, "");1022#endif1023}10241025// Tests that using DoDefault() inside a composite action leads to a1026// run-time error.10271028void VoidFunc(bool /* flag */) {}10291030TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {1031MockClass mock;1032EXPECT_CALL(mock, IntFunc(_))1033.WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));10341035// Ideally we should verify the error message as well. Sadly,1036// EXPECT_DEATH() can only capture stderr, while Google Mock's1037// errors are printed on stdout. Therefore we have to settle for1038// not verifying the message.1039EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, "");1040}10411042// Tests that DoDefault() returns the default value set by1043// DefaultValue<T>::Set() when it's not overridden by an ON_CALL().1044TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {1045DefaultValue<int>::Set(1);1046MockClass mock;1047EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());1048EXPECT_EQ(1, mock.IntFunc(false));1049DefaultValue<int>::Clear();1050}10511052// Tests that DoDefault() does the action specified by ON_CALL().1053TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {1054MockClass mock;1055ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2));1056EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());1057EXPECT_EQ(2, mock.IntFunc(false));1058}10591060// Tests that using DoDefault() in ON_CALL() leads to a run-time failure.1061TEST(DoDefaultTest, CannotBeUsedInOnCall) {1062MockClass mock;1063EXPECT_NONFATAL_FAILURE(1064{ // NOLINT1065ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault());1066},1067"DoDefault() cannot be used in ON_CALL()");1068}10691070// Tests that SetArgPointee<N>(v) sets the variable pointed to by1071// the N-th (0-based) argument to v.1072TEST(SetArgPointeeTest, SetsTheNthPointee) {1073typedef void MyFunction(bool, int*, char*);1074Action<MyFunction> a = SetArgPointee<1>(2);10751076int n = 0;1077char ch = '\0';1078a.Perform(std::make_tuple(true, &n, &ch));1079EXPECT_EQ(2, n);1080EXPECT_EQ('\0', ch);10811082a = SetArgPointee<2>('a');1083n = 0;1084ch = '\0';1085a.Perform(std::make_tuple(true, &n, &ch));1086EXPECT_EQ(0, n);1087EXPECT_EQ('a', ch);1088}10891090// Tests that SetArgPointee<N>() accepts a string literal.1091TEST(SetArgPointeeTest, AcceptsStringLiteral) {1092typedef void MyFunction(std::string*, const char**);1093Action<MyFunction> a = SetArgPointee<0>("hi");1094std::string str;1095const char* ptr = nullptr;1096a.Perform(std::make_tuple(&str, &ptr));1097EXPECT_EQ("hi", str);1098EXPECT_TRUE(ptr == nullptr);10991100a = SetArgPointee<1>("world");1101str = "";1102a.Perform(std::make_tuple(&str, &ptr));1103EXPECT_EQ("", str);1104EXPECT_STREQ("world", ptr);1105}11061107TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {1108typedef void MyFunction(const wchar_t**);1109Action<MyFunction> a = SetArgPointee<0>(L"world");1110const wchar_t* ptr = nullptr;1111a.Perform(std::make_tuple(&ptr));1112EXPECT_STREQ(L"world", ptr);11131114#if GTEST_HAS_STD_WSTRING11151116typedef void MyStringFunction(std::wstring*);1117Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");1118std::wstring str = L"";1119a2.Perform(std::make_tuple(&str));1120EXPECT_EQ(L"world", str);11211122#endif1123}11241125// Tests that SetArgPointee<N>() accepts a char pointer.1126TEST(SetArgPointeeTest, AcceptsCharPointer) {1127typedef void MyFunction(bool, std::string*, const char**);1128const char* const hi = "hi";1129Action<MyFunction> a = SetArgPointee<1>(hi);1130std::string str;1131const char* ptr = nullptr;1132a.Perform(std::make_tuple(true, &str, &ptr));1133EXPECT_EQ("hi", str);1134EXPECT_TRUE(ptr == nullptr);11351136char world_array[] = "world";1137char* const world = world_array;1138a = SetArgPointee<2>(world);1139str = "";1140a.Perform(std::make_tuple(true, &str, &ptr));1141EXPECT_EQ("", str);1142EXPECT_EQ(world, ptr);1143}11441145TEST(SetArgPointeeTest, AcceptsWideCharPointer) {1146typedef void MyFunction(bool, const wchar_t**);1147const wchar_t* const hi = L"hi";1148Action<MyFunction> a = SetArgPointee<1>(hi);1149const wchar_t* ptr = nullptr;1150a.Perform(std::make_tuple(true, &ptr));1151EXPECT_EQ(hi, ptr);11521153#if GTEST_HAS_STD_WSTRING11541155typedef void MyStringFunction(bool, std::wstring*);1156wchar_t world_array[] = L"world";1157wchar_t* const world = world_array;1158Action<MyStringFunction> a2 = SetArgPointee<1>(world);1159std::wstring str;1160a2.Perform(std::make_tuple(true, &str));1161EXPECT_EQ(world_array, str);1162#endif1163}11641165// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by1166// the N-th (0-based) argument to v.1167TEST(SetArgumentPointeeTest, SetsTheNthPointee) {1168typedef void MyFunction(bool, int*, char*);1169Action<MyFunction> a = SetArgumentPointee<1>(2);11701171int n = 0;1172char ch = '\0';1173a.Perform(std::make_tuple(true, &n, &ch));1174EXPECT_EQ(2, n);1175EXPECT_EQ('\0', ch);11761177a = SetArgumentPointee<2>('a');1178n = 0;1179ch = '\0';1180a.Perform(std::make_tuple(true, &n, &ch));1181EXPECT_EQ(0, n);1182EXPECT_EQ('a', ch);1183}11841185// Sample functions and functors for testing Invoke() and etc.1186int Nullary() { return 1; }11871188class NullaryFunctor {1189public:1190int operator()() { return 2; }1191};11921193bool g_done = false;1194void VoidNullary() { g_done = true; }11951196class VoidNullaryFunctor {1197public:1198void operator()() { g_done = true; }1199};12001201short Short(short n) { return n; } // NOLINT1202char Char(char ch) { return ch; }12031204const char* CharPtr(const char* s) { return s; }12051206bool Unary(int x) { return x < 0; }12071208const char* Binary(const char* input, short n) { return input + n; } // NOLINT12091210void VoidBinary(int, char) { g_done = true; }12111212int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT12131214int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }12151216class Foo {1217public:1218Foo() : value_(123) {}12191220int Nullary() const { return value_; }12211222private:1223int value_;1224};12251226// Tests InvokeWithoutArgs(function).1227TEST(InvokeWithoutArgsTest, Function) {1228// As an action that takes one argument.1229Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT1230EXPECT_EQ(1, a.Perform(std::make_tuple(2)));12311232// As an action that takes two arguments.1233Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT1234EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5)));12351236// As an action that returns void.1237Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT1238g_done = false;1239a3.Perform(std::make_tuple(1));1240EXPECT_TRUE(g_done);1241}12421243// Tests InvokeWithoutArgs(functor).1244TEST(InvokeWithoutArgsTest, Functor) {1245// As an action that takes no argument.1246Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT1247EXPECT_EQ(2, a.Perform(std::make_tuple()));12481249// As an action that takes three arguments.1250Action<int(int, double, char)> a2 = // NOLINT1251InvokeWithoutArgs(NullaryFunctor());1252EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a')));12531254// As an action that returns void.1255Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());1256g_done = false;1257a3.Perform(std::make_tuple());1258EXPECT_TRUE(g_done);1259}12601261// Tests InvokeWithoutArgs(obj_ptr, method).1262TEST(InvokeWithoutArgsTest, Method) {1263Foo foo;1264Action<int(bool, char)> a = // NOLINT1265InvokeWithoutArgs(&foo, &Foo::Nullary);1266EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));1267}12681269// Tests using IgnoreResult() on a polymorphic action.1270TEST(IgnoreResultTest, PolymorphicAction) {1271Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT1272a.Perform(std::make_tuple(1));1273}12741275// Tests using IgnoreResult() on a monomorphic action.12761277int ReturnOne() {1278g_done = true;1279return 1;1280}12811282TEST(IgnoreResultTest, MonomorphicAction) {1283g_done = false;1284Action<void()> a = IgnoreResult(Invoke(ReturnOne));1285a.Perform(std::make_tuple());1286EXPECT_TRUE(g_done);1287}12881289// Tests using IgnoreResult() on an action that returns a class type.12901291MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {1292g_done = true;1293return MyNonDefaultConstructible(42);1294}12951296TEST(IgnoreResultTest, ActionReturningClass) {1297g_done = false;1298Action<void(int)> a =1299IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT1300a.Perform(std::make_tuple(2));1301EXPECT_TRUE(g_done);1302}13031304TEST(AssignTest, Int) {1305int x = 0;1306Action<void(int)> a = Assign(&x, 5);1307a.Perform(std::make_tuple(0));1308EXPECT_EQ(5, x);1309}13101311TEST(AssignTest, String) {1312::std::string x;1313Action<void(void)> a = Assign(&x, "Hello, world");1314a.Perform(std::make_tuple());1315EXPECT_EQ("Hello, world", x);1316}13171318TEST(AssignTest, CompatibleTypes) {1319double x = 0;1320Action<void(int)> a = Assign(&x, 5);1321a.Perform(std::make_tuple(0));1322EXPECT_DOUBLE_EQ(5, x);1323}13241325// DoAll should support &&-qualified actions when used with WillOnce.1326TEST(DoAll, SupportsRefQualifiedActions) {1327struct InitialAction {1328void operator()(const int arg) && { EXPECT_EQ(17, arg); }1329};13301331struct FinalAction {1332int operator()() && { return 19; }1333};13341335MockFunction<int(int)> mock;1336EXPECT_CALL(mock, Call).WillOnce(DoAll(InitialAction{}, FinalAction{}));1337EXPECT_EQ(19, mock.AsStdFunction()(17));1338}13391340// DoAll should never provide rvalue references to the initial actions. If the1341// mock action itself accepts an rvalue reference or a non-scalar object by1342// value then the final action should receive an rvalue reference, but initial1343// actions should receive only lvalue references.1344TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {1345struct Obj {};13461347// Mock action accepts by value: the initial action should be fed a const1348// lvalue reference, and the final action an rvalue reference.1349{1350struct InitialAction {1351void operator()(Obj&) const { FAIL() << "Unexpected call"; }1352void operator()(const Obj&) const {}1353void operator()(Obj&&) const { FAIL() << "Unexpected call"; }1354void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }1355};13561357MockFunction<void(Obj)> mock;1358EXPECT_CALL(mock, Call)1359.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))1360.WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));13611362mock.AsStdFunction()(Obj{});1363mock.AsStdFunction()(Obj{});1364}13651366// Mock action accepts by const lvalue reference: both actions should receive1367// a const lvalue reference.1368{1369struct InitialAction {1370void operator()(Obj&) const { FAIL() << "Unexpected call"; }1371void operator()(const Obj&) const {}1372void operator()(Obj&&) const { FAIL() << "Unexpected call"; }1373void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }1374};13751376MockFunction<void(const Obj&)> mock;1377EXPECT_CALL(mock, Call)1378.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}))1379.WillRepeatedly(1380DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}));13811382mock.AsStdFunction()(Obj{});1383mock.AsStdFunction()(Obj{});1384}13851386// Mock action accepts by non-const lvalue reference: both actions should get1387// a non-const lvalue reference if they want them.1388{1389struct InitialAction {1390void operator()(Obj&) const {}1391void operator()(Obj&&) const { FAIL() << "Unexpected call"; }1392};13931394MockFunction<void(Obj&)> mock;1395EXPECT_CALL(mock, Call)1396.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}))1397.WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));13981399Obj obj;1400mock.AsStdFunction()(obj);1401mock.AsStdFunction()(obj);1402}14031404// Mock action accepts by rvalue reference: the initial actions should receive1405// a non-const lvalue reference if it wants it, and the final action an rvalue1406// reference.1407{1408struct InitialAction {1409void operator()(Obj&) const {}1410void operator()(Obj&&) const { FAIL() << "Unexpected call"; }1411};14121413MockFunction<void(Obj&&)> mock;1414EXPECT_CALL(mock, Call)1415.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))1416.WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));14171418mock.AsStdFunction()(Obj{});1419mock.AsStdFunction()(Obj{});1420}14211422// &&-qualified initial actions should also be allowed with WillOnce.1423{1424struct InitialAction {1425void operator()(Obj&) && {}1426};14271428MockFunction<void(Obj&)> mock;1429EXPECT_CALL(mock, Call)1430.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));14311432Obj obj;1433mock.AsStdFunction()(obj);1434}14351436{1437struct InitialAction {1438void operator()(Obj&) && {}1439};14401441MockFunction<void(Obj&&)> mock;1442EXPECT_CALL(mock, Call)1443.WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));14441445mock.AsStdFunction()(Obj{});1446}1447}14481449// DoAll should support being used with type-erased Action objects, both through1450// WillOnce and WillRepeatedly.1451TEST(DoAll, SupportsTypeErasedActions) {1452// With only type-erased actions.1453const Action<void()> initial_action = [] {};1454const Action<int()> final_action = [] { return 17; };14551456MockFunction<int()> mock;1457EXPECT_CALL(mock, Call)1458.WillOnce(DoAll(initial_action, initial_action, final_action))1459.WillRepeatedly(DoAll(initial_action, initial_action, final_action));14601461EXPECT_EQ(17, mock.AsStdFunction()());14621463// With &&-qualified and move-only final action.1464{1465struct FinalAction {1466FinalAction() = default;1467FinalAction(FinalAction&&) = default;14681469int operator()() && { return 17; }1470};14711472EXPECT_CALL(mock, Call)1473.WillOnce(DoAll(initial_action, initial_action, FinalAction{}));14741475EXPECT_EQ(17, mock.AsStdFunction()());1476}1477}14781479// Tests using WithArgs and with an action that takes 1 argument.1480TEST(WithArgsTest, OneArg) {1481Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT1482EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));1483EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));1484}14851486// Tests using WithArgs with an action that takes 2 arguments.1487TEST(WithArgsTest, TwoArgs) {1488Action<const char*(const char* s, double x, short n)> a = // NOLINT1489WithArgs<0, 2>(Invoke(Binary));1490const char s[] = "Hello";1491EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));1492}14931494struct ConcatAll {1495std::string operator()() const { return {}; }1496template <typename... I>1497std::string operator()(const char* a, I... i) const {1498return a + ConcatAll()(i...);1499}1500};15011502// Tests using WithArgs with an action that takes 10 arguments.1503TEST(WithArgsTest, TenArgs) {1504Action<std::string(const char*, const char*, const char*, const char*)> a =1505WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));1506EXPECT_EQ("0123210123",1507a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),1508CharPtr("3"))));1509}15101511// Tests using WithArgs with an action that is not Invoke().1512class SubtractAction : public ActionInterface<int(int, int)> {1513public:1514int Perform(const std::tuple<int, int>& args) override {1515return std::get<0>(args) - std::get<1>(args);1516}1517};15181519TEST(WithArgsTest, NonInvokeAction) {1520Action<int(const std::string&, int, int)> a =1521WithArgs<2, 1>(MakeAction(new SubtractAction));1522std::tuple<std::string, int, int> dummy =1523std::make_tuple(std::string("hi"), 2, 10);1524EXPECT_EQ(8, a.Perform(dummy));1525}15261527// Tests using WithArgs to pass all original arguments in the original order.1528TEST(WithArgsTest, Identity) {1529Action<int(int x, char y, short z)> a = // NOLINT1530WithArgs<0, 1, 2>(Invoke(Ternary));1531EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));1532}15331534// Tests using WithArgs with repeated arguments.1535TEST(WithArgsTest, RepeatedArguments) {1536Action<int(bool, int m, int n)> a = // NOLINT1537WithArgs<1, 1, 1, 1>(Invoke(SumOf4));1538EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));1539}15401541// Tests using WithArgs with reversed argument order.1542TEST(WithArgsTest, ReversedArgumentOrder) {1543Action<const char*(short n, const char* input)> a = // NOLINT1544WithArgs<1, 0>(Invoke(Binary));1545const char s[] = "Hello";1546EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));1547}15481549// Tests using WithArgs with compatible, but not identical, argument types.1550TEST(WithArgsTest, ArgsOfCompatibleTypes) {1551Action<long(short x, char y, double z, char c)> a = // NOLINT1552WithArgs<0, 1, 3>(Invoke(Ternary));1553EXPECT_EQ(123,1554a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));1555}15561557// Tests using WithArgs with an action that returns void.1558TEST(WithArgsTest, VoidAction) {1559Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));1560g_done = false;1561a.Perform(std::make_tuple(1.5, 'a', 3));1562EXPECT_TRUE(g_done);1563}15641565TEST(WithArgsTest, ReturnReference) {1566Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });1567int i = 0;1568const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));1569EXPECT_EQ(&i, &res);1570}15711572TEST(WithArgsTest, InnerActionWithConversion) {1573Action<Derived*()> inner = [] { return nullptr; };15741575MockFunction<Base*(double)> mock;1576EXPECT_CALL(mock, Call)1577.WillOnce(WithoutArgs(inner))1578.WillRepeatedly(WithoutArgs(inner));15791580EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));1581EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));1582}15831584// It should be possible to use an &&-qualified inner action as long as the1585// whole shebang is used as an rvalue with WillOnce.1586TEST(WithArgsTest, RefQualifiedInnerAction) {1587struct SomeAction {1588int operator()(const int arg) && {1589EXPECT_EQ(17, arg);1590return 19;1591}1592};15931594MockFunction<int(int, int)> mock;1595EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{}));1596EXPECT_EQ(19, mock.AsStdFunction()(0, 17));1597}15981599#ifndef GTEST_OS_WINDOWS_MOBILE16001601class SetErrnoAndReturnTest : public testing::Test {1602protected:1603void SetUp() override { errno = 0; }1604void TearDown() override { errno = 0; }1605};16061607TEST_F(SetErrnoAndReturnTest, Int) {1608Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);1609EXPECT_EQ(-5, a.Perform(std::make_tuple()));1610EXPECT_EQ(ENOTTY, errno);1611}16121613TEST_F(SetErrnoAndReturnTest, Ptr) {1614int x;1615Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);1616EXPECT_EQ(&x, a.Perform(std::make_tuple()));1617EXPECT_EQ(ENOTTY, errno);1618}16191620TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {1621Action<double()> a = SetErrnoAndReturn(EINVAL, 5);1622EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));1623EXPECT_EQ(EINVAL, errno);1624}16251626#endif // !GTEST_OS_WINDOWS_MOBILE16271628// Tests ByRef().16291630// Tests that the result of ByRef() is copyable.1631TEST(ByRefTest, IsCopyable) {1632const std::string s1 = "Hi";1633const std::string s2 = "Hello";16341635auto ref_wrapper = ByRef(s1);1636const std::string& r1 = ref_wrapper;1637EXPECT_EQ(&s1, &r1);16381639// Assigns a new value to ref_wrapper.1640ref_wrapper = ByRef(s2);1641const std::string& r2 = ref_wrapper;1642EXPECT_EQ(&s2, &r2);16431644auto ref_wrapper1 = ByRef(s1);1645// Copies ref_wrapper1 to ref_wrapper.1646ref_wrapper = ref_wrapper1;1647const std::string& r3 = ref_wrapper;1648EXPECT_EQ(&s1, &r3);1649}16501651// Tests using ByRef() on a const value.1652TEST(ByRefTest, ConstValue) {1653const int n = 0;1654// int& ref = ByRef(n); // This shouldn't compile - we have a1655// negative compilation test to catch it.1656const int& const_ref = ByRef(n);1657EXPECT_EQ(&n, &const_ref);1658}16591660// Tests using ByRef() on a non-const value.1661TEST(ByRefTest, NonConstValue) {1662int n = 0;16631664// ByRef(n) can be used as either an int&,1665int& ref = ByRef(n);1666EXPECT_EQ(&n, &ref);16671668// or a const int&.1669const int& const_ref = ByRef(n);1670EXPECT_EQ(&n, &const_ref);1671}16721673// Tests explicitly specifying the type when using ByRef().1674TEST(ByRefTest, ExplicitType) {1675int n = 0;1676const int& r1 = ByRef<const int>(n);1677EXPECT_EQ(&n, &r1);16781679// ByRef<char>(n); // This shouldn't compile - we have a negative1680// compilation test to catch it.16811682Derived d;1683Derived& r2 = ByRef<Derived>(d);1684EXPECT_EQ(&d, &r2);16851686const Derived& r3 = ByRef<const Derived>(d);1687EXPECT_EQ(&d, &r3);16881689Base& r4 = ByRef<Base>(d);1690EXPECT_EQ(&d, &r4);16911692const Base& r5 = ByRef<const Base>(d);1693EXPECT_EQ(&d, &r5);16941695// The following shouldn't compile - we have a negative compilation1696// test for it.1697//1698// Base b;1699// ByRef<Derived>(b);1700}17011702// Tests that Google Mock prints expression ByRef(x) as a reference to x.1703TEST(ByRefTest, PrintsCorrectly) {1704int n = 42;1705::std::stringstream expected, actual;1706testing::internal::UniversalPrinter<const int&>::Print(n, &expected);1707testing::internal::UniversalPrint(ByRef(n), &actual);1708EXPECT_EQ(expected.str(), actual.str());1709}17101711struct UnaryConstructorClass {1712explicit UnaryConstructorClass(int v) : value(v) {}1713int value;1714};17151716// Tests using ReturnNew() with a unary constructor.1717TEST(ReturnNewTest, Unary) {1718Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);1719UnaryConstructorClass* c = a.Perform(std::make_tuple());1720EXPECT_EQ(4000, c->value);1721delete c;1722}17231724TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {1725Action<UnaryConstructorClass*(bool, int)> a =1726ReturnNew<UnaryConstructorClass>(4000);1727UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));1728EXPECT_EQ(4000, c->value);1729delete c;1730}17311732TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {1733Action<const UnaryConstructorClass*()> a =1734ReturnNew<UnaryConstructorClass>(4000);1735const UnaryConstructorClass* c = a.Perform(std::make_tuple());1736EXPECT_EQ(4000, c->value);1737delete c;1738}17391740class TenArgConstructorClass {1741public:1742TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,1743int a8, int a9, int a10)1744: value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}1745int value_;1746};17471748// Tests using ReturnNew() with a 10-argument constructor.1749TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {1750Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(17511000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,17520);1753TenArgConstructorClass* c = a.Perform(std::make_tuple());1754EXPECT_EQ(1234567890, c->value_);1755delete c;1756}17571758std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); }17591760std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {1761std::vector<std::unique_ptr<int>> out;1762out.emplace_back(new int(7));1763return out;1764}17651766TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {1767MockClass mock;1768std::unique_ptr<int> i(new int(19));1769EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));1770EXPECT_CALL(mock, MakeVectorUnique())1771.WillOnce(Return(ByMove(VectorUniquePtrSource())));1772Derived* d = new Derived;1773EXPECT_CALL(mock, MakeUniqueBase())1774.WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));17751776std::unique_ptr<int> result1 = mock.MakeUnique();1777EXPECT_EQ(19, *result1);17781779std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();1780EXPECT_EQ(1u, vresult.size());1781EXPECT_NE(nullptr, vresult[0]);1782EXPECT_EQ(7, *vresult[0]);17831784std::unique_ptr<Base> result2 = mock.MakeUniqueBase();1785EXPECT_EQ(d, result2.get());1786}17871788TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {1789testing::MockFunction<void()> mock_function;1790MockClass mock;1791std::unique_ptr<int> i(new int(19));1792EXPECT_CALL(mock_function, Call());1793EXPECT_CALL(mock, MakeUnique())1794.WillOnce(DoAll(InvokeWithoutArgs(&mock_function,1795&testing::MockFunction<void()>::Call),1796Return(ByMove(std::move(i)))));17971798std::unique_ptr<int> result1 = mock.MakeUnique();1799EXPECT_EQ(19, *result1);1800}18011802TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {1803MockClass mock;18041805// Check default value1806DefaultValue<std::unique_ptr<int>>::SetFactory(1807[] { return std::make_unique<int>(42); });1808EXPECT_EQ(42, *mock.MakeUnique());18091810EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));1811EXPECT_CALL(mock, MakeVectorUnique())1812.WillRepeatedly(Invoke(VectorUniquePtrSource));1813std::unique_ptr<int> result1 = mock.MakeUnique();1814EXPECT_EQ(19, *result1);1815std::unique_ptr<int> result2 = mock.MakeUnique();1816EXPECT_EQ(19, *result2);1817EXPECT_NE(result1, result2);18181819std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();1820EXPECT_EQ(1u, vresult.size());1821EXPECT_NE(nullptr, vresult[0]);1822EXPECT_EQ(7, *vresult[0]);1823}18241825TEST(MockMethodTest, CanTakeMoveOnlyValue) {1826MockClass mock;1827auto make = [](int i) { return std::make_unique<int>(i); };18281829EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {1830return *i;1831});1832// DoAll() does not compile, since it would move from its arguments twice.1833// EXPECT_CALL(mock, TakeUnique(_, _))1834// .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),1835// Return(1)));1836EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))1837.WillOnce(Return(-7))1838.RetiresOnSaturation();1839EXPECT_CALL(mock, TakeUnique(testing::IsNull()))1840.WillOnce(Return(-1))1841.RetiresOnSaturation();18421843EXPECT_EQ(5, mock.TakeUnique(make(5)));1844EXPECT_EQ(-7, mock.TakeUnique(make(7)));1845EXPECT_EQ(7, mock.TakeUnique(make(7)));1846EXPECT_EQ(7, mock.TakeUnique(make(7)));1847EXPECT_EQ(-1, mock.TakeUnique({}));18481849// Some arguments are moved, some passed by reference.1850auto lvalue = make(6);1851EXPECT_CALL(mock, TakeUnique(_, _))1852.WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {1853return *i * *j;1854});1855EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));18561857// The unique_ptr can be saved by the action.1858std::unique_ptr<int> saved;1859EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {1860saved = std::move(i);1861return 0;1862});1863EXPECT_EQ(0, mock.TakeUnique(make(42)));1864EXPECT_EQ(42, *saved);1865}18661867// It should be possible to use callables with an &&-qualified call operator1868// with WillOnce, since they will be called only once. This allows actions to1869// contain and manipulate move-only types.1870TEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) {1871struct Return17 {1872int operator()() && { return 17; }1873};18741875// Action is directly compatible with mocked function type.1876{1877MockFunction<int()> mock;1878EXPECT_CALL(mock, Call).WillOnce(Return17());18791880EXPECT_EQ(17, mock.AsStdFunction()());1881}18821883// Action doesn't want mocked function arguments.1884{1885MockFunction<int(int)> mock;1886EXPECT_CALL(mock, Call).WillOnce(Return17());18871888EXPECT_EQ(17, mock.AsStdFunction()(0));1889}1890}18911892// Edge case: if an action has both a const-qualified and an &&-qualified call1893// operator, there should be no "ambiguous call" errors. The &&-qualified1894// operator should be used by WillOnce (since it doesn't need to retain the1895// action beyond one call), and the const-qualified one by WillRepeatedly.1896TEST(MockMethodTest, ActionHasMultipleCallOperators) {1897struct ReturnInt {1898int operator()() && { return 17; }1899int operator()() const& { return 19; }1900};19011902// Directly compatible with mocked function type.1903{1904MockFunction<int()> mock;1905EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());19061907EXPECT_EQ(17, mock.AsStdFunction()());1908EXPECT_EQ(19, mock.AsStdFunction()());1909EXPECT_EQ(19, mock.AsStdFunction()());1910}19111912// Ignores function arguments.1913{1914MockFunction<int(int)> mock;1915EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());19161917EXPECT_EQ(17, mock.AsStdFunction()(0));1918EXPECT_EQ(19, mock.AsStdFunction()(0));1919EXPECT_EQ(19, mock.AsStdFunction()(0));1920}1921}19221923// WillOnce should have no problem coping with a move-only action, whether it is1924// &&-qualified or not.1925TEST(MockMethodTest, MoveOnlyAction) {1926// &&-qualified1927{1928struct Return17 {1929Return17() = default;1930Return17(Return17&&) = default;19311932Return17(const Return17&) = delete;1933Return17 operator=(const Return17&) = delete;19341935int operator()() && { return 17; }1936};19371938MockFunction<int()> mock;1939EXPECT_CALL(mock, Call).WillOnce(Return17());1940EXPECT_EQ(17, mock.AsStdFunction()());1941}19421943// Not &&-qualified1944{1945struct Return17 {1946Return17() = default;1947Return17(Return17&&) = default;19481949Return17(const Return17&) = delete;1950Return17 operator=(const Return17&) = delete;19511952int operator()() const { return 17; }1953};19541955MockFunction<int()> mock;1956EXPECT_CALL(mock, Call).WillOnce(Return17());1957EXPECT_EQ(17, mock.AsStdFunction()());1958}1959}19601961// It should be possible to use an action that returns a value with a mock1962// function that doesn't, both through WillOnce and WillRepeatedly.1963TEST(MockMethodTest, ActionReturnsIgnoredValue) {1964struct ReturnInt {1965int operator()() const { return 0; }1966};19671968MockFunction<void()> mock;1969EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());19701971mock.AsStdFunction()();1972mock.AsStdFunction()();1973}19741975// Despite the fanciness around move-only actions and so on, it should still be1976// possible to hand an lvalue reference to a copyable action to WillOnce.1977TEST(MockMethodTest, WillOnceCanAcceptLvalueReference) {1978MockFunction<int()> mock;19791980const auto action = [] { return 17; };1981EXPECT_CALL(mock, Call).WillOnce(action);19821983EXPECT_EQ(17, mock.AsStdFunction()());1984}19851986// A callable that doesn't use SFINAE to restrict its call operator's overload1987// set, but is still picky about which arguments it will accept.1988struct StaticAssertSingleArgument {1989template <typename... Args>1990static constexpr bool CheckArgs() {1991static_assert(sizeof...(Args) == 1, "");1992return true;1993}19941995template <typename... Args, bool = CheckArgs<Args...>()>1996int operator()(Args...) const {1997return 17;1998}1999};20002001// WillOnce and WillRepeatedly should both work fine with naïve implementations2002// of actions that don't use SFINAE to limit the overload set for their call2003// operator. If they are compatible with the actual mocked signature, we2004// shouldn't probe them with no arguments and trip a static_assert.2005TEST(MockMethodTest, ActionSwallowsAllArguments) {2006MockFunction<int(int)> mock;2007EXPECT_CALL(mock, Call)2008.WillOnce(StaticAssertSingleArgument{})2009.WillRepeatedly(StaticAssertSingleArgument{});20102011EXPECT_EQ(17, mock.AsStdFunction()(0));2012EXPECT_EQ(17, mock.AsStdFunction()(0));2013}20142015struct ActionWithTemplatedConversionOperators {2016template <typename... Args>2017operator OnceAction<int(Args...)>() && { // NOLINT2018return [] { return 17; };2019}20202021template <typename... Args>2022operator Action<int(Args...)>() const { // NOLINT2023return [] { return 19; };2024}2025};20262027// It should be fine to hand both WillOnce and WillRepeatedly a function that2028// defines templated conversion operators to OnceAction and Action. WillOnce2029// should prefer the OnceAction version.2030TEST(MockMethodTest, ActionHasTemplatedConversionOperators) {2031MockFunction<int()> mock;2032EXPECT_CALL(mock, Call)2033.WillOnce(ActionWithTemplatedConversionOperators{})2034.WillRepeatedly(ActionWithTemplatedConversionOperators{});20352036EXPECT_EQ(17, mock.AsStdFunction()());2037EXPECT_EQ(19, mock.AsStdFunction()());2038}20392040// Tests for std::function based action.20412042int Add(int val, int& ref, int* ptr) { // NOLINT2043int result = val + ref + *ptr;2044ref = 42;2045*ptr = 43;2046return result;2047}20482049int Deref(std::unique_ptr<int> ptr) { return *ptr; }20502051struct Double {2052template <typename T>2053T operator()(T t) {2054return 2 * t;2055}2056};20572058std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); }20592060TEST(FunctorActionTest, ActionFromFunction) {2061Action<int(int, int&, int*)> a = &Add;2062int x = 1, y = 2, z = 3;2063EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));2064EXPECT_EQ(42, y);2065EXPECT_EQ(43, z);20662067Action<int(std::unique_ptr<int>)> a1 = &Deref;2068EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));2069}20702071TEST(FunctorActionTest, ActionFromLambda) {2072Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };2073EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));2074EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5)));20752076std::unique_ptr<int> saved;2077Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {2078saved = std::move(p);2079};2080a2.Perform(std::make_tuple(UniqueInt(5)));2081EXPECT_EQ(5, *saved);2082}20832084TEST(FunctorActionTest, PolymorphicFunctor) {2085Action<int(int)> ai = Double();2086EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));2087Action<double(double)> ad = Double(); // Double? Double double!2088EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5)));2089}20902091TEST(FunctorActionTest, TypeConversion) {2092// Numeric promotions are allowed.2093const Action<bool(int)> a1 = [](int i) { return i > 1; };2094const Action<int(bool)> a2 = Action<int(bool)>(a1);2095EXPECT_EQ(1, a1.Perform(std::make_tuple(42)));2096EXPECT_EQ(0, a2.Perform(std::make_tuple(42)));20972098// Implicit constructors are allowed.2099const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };2100const Action<int(const char*)> s2 = Action<int(const char*)>(s1);2101EXPECT_EQ(0, s2.Perform(std::make_tuple("")));2102EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));21032104// Also between the lambda and the action itself.2105const Action<bool(std::string)> x1 = [](Unused) { return 42; };2106const Action<bool(std::string)> x2 = [] { return 42; };2107EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));2108EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));21092110// Ensure decay occurs where required.2111std::function<int()> f = [] { return 7; };2112Action<int(int)> d = f;2113f = nullptr;2114EXPECT_EQ(7, d.Perform(std::make_tuple(1)));21152116// Ensure creation of an empty action succeeds.2117Action<void(int)>(nullptr);2118}21192120TEST(FunctorActionTest, UnusedArguments) {2121// Verify that users can ignore uninteresting arguments.2122Action<int(int, double y, double z)> a = [](int i, Unused, Unused) {2123return 2 * i;2124};2125std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);2126EXPECT_EQ(6, a.Perform(dummy));2127}21282129// Test that basic built-in actions work with move-only arguments.2130TEST(MoveOnlyArgumentsTest, ReturningActions) {2131Action<int(std::unique_ptr<int>)> a = Return(1);2132EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));21332134a = testing::WithoutArgs([]() { return 7; });2135EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr)));21362137Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);2138int x = 0;2139a2.Perform(std::make_tuple(nullptr, &x));2140EXPECT_EQ(x, 3);2141}21422143ACTION(ReturnArity) { return std::tuple_size<args_type>::value; }21442145TEST(ActionMacro, LargeArity) {2146EXPECT_EQ(21471, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));2148EXPECT_EQ(214910,2150testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(2151ReturnArity())2152.Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));2153EXPECT_EQ(215420,2155testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,2156int, int, int, int, int, int, int, int, int)>(2157ReturnArity())2158.Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,215914, 15, 16, 17, 18, 19)));2160}21612162} // namespace2163} // namespace testing21642165#if defined(_MSC_VER) && (_MSC_VER == 1900)2166GTEST_DISABLE_MSC_WARNINGS_POP_() // 48002167#endif2168GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503216921702171