• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file tests the built-in actions.
34 
35 // Silence C4100 (unreferenced formal parameter) for MSVC
36 #ifdef _MSC_VER
37 #  pragma warning(push)
38 #  pragma warning(disable:4100)
39 #if _MSC_VER == 1900
40 // and silence C4800 (C4800: 'int *const ': forcing value
41 // to bool 'true' or 'false') for MSVC 15
42 #  pragma warning(disable:4800)
43 #endif
44 #endif
45 
46 #include "gmock/gmock-actions.h"
47 #include <algorithm>
48 #include <iterator>
49 #include <memory>
50 #include <string>
51 #include <type_traits>
52 #include "gmock/gmock.h"
53 #include "gmock/internal/gmock-port.h"
54 #include "gtest/gtest.h"
55 #include "gtest/gtest-spi.h"
56 
57 namespace {
58 
59 using ::testing::_;
60 using ::testing::Action;
61 using ::testing::ActionInterface;
62 using ::testing::Assign;
63 using ::testing::ByMove;
64 using ::testing::ByRef;
65 using ::testing::DefaultValue;
66 using ::testing::DoAll;
67 using ::testing::DoDefault;
68 using ::testing::IgnoreResult;
69 using ::testing::Invoke;
70 using ::testing::InvokeWithoutArgs;
71 using ::testing::MakePolymorphicAction;
72 using ::testing::PolymorphicAction;
73 using ::testing::Return;
74 using ::testing::ReturnNew;
75 using ::testing::ReturnNull;
76 using ::testing::ReturnRef;
77 using ::testing::ReturnRefOfCopy;
78 using ::testing::ReturnRoundRobin;
79 using ::testing::SetArgPointee;
80 using ::testing::SetArgumentPointee;
81 using ::testing::Unused;
82 using ::testing::WithArgs;
83 using ::testing::internal::BuiltInDefaultValue;
84 
85 #if !GTEST_OS_WINDOWS_MOBILE
86 using ::testing::SetErrnoAndReturn;
87 #endif
88 
89 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
TEST(BuiltInDefaultValueTest,IsNullForPointerTypes)90 TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
91   EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr);
92   EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr);
93   EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr);
94 }
95 
96 // Tests that BuiltInDefaultValue<T*>::Exists() return true.
TEST(BuiltInDefaultValueTest,ExistsForPointerTypes)97 TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
98   EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
99   EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
100   EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
101 }
102 
103 // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
104 // built-in numeric type.
TEST(BuiltInDefaultValueTest,IsZeroForNumericTypes)105 TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
106   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
107   EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
108   EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
109 #if GMOCK_WCHAR_T_IS_NATIVE_
110 #if !defined(__WCHAR_UNSIGNED__)
111   EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
112 #else
113   EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
114 #endif
115 #endif
116   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get());  // NOLINT
117   EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get());  // NOLINT
118   EXPECT_EQ(0, BuiltInDefaultValue<short>::Get());  // NOLINT
119   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
120   EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
121   EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
122   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get());  // NOLINT
123   EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get());  // NOLINT
124   EXPECT_EQ(0, BuiltInDefaultValue<long>::Get());  // NOLINT
125   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get());  // NOLINT
126   EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get());  // NOLINT
127   EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get());  // NOLINT
128   EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
129   EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
130 }
131 
132 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
133 // built-in numeric type.
TEST(BuiltInDefaultValueTest,ExistsForNumericTypes)134 TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
135   EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
136   EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
137   EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
138 #if GMOCK_WCHAR_T_IS_NATIVE_
139   EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
140 #endif
141   EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists());  // NOLINT
142   EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists());  // NOLINT
143   EXPECT_TRUE(BuiltInDefaultValue<short>::Exists());  // NOLINT
144   EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
145   EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
146   EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
147   EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists());  // NOLINT
148   EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists());  // NOLINT
149   EXPECT_TRUE(BuiltInDefaultValue<long>::Exists());  // NOLINT
150   EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists());  // NOLINT
151   EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists());  // NOLINT
152   EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists());  // NOLINT
153   EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
154   EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
155 }
156 
157 // Tests that BuiltInDefaultValue<bool>::Get() returns false.
TEST(BuiltInDefaultValueTest,IsFalseForBool)158 TEST(BuiltInDefaultValueTest, IsFalseForBool) {
159   EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
160 }
161 
162 // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
TEST(BuiltInDefaultValueTest,BoolExists)163 TEST(BuiltInDefaultValueTest, BoolExists) {
164   EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
165 }
166 
167 // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
168 // string type.
TEST(BuiltInDefaultValueTest,IsEmptyStringForString)169 TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
170   EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
171 }
172 
173 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
174 // string type.
TEST(BuiltInDefaultValueTest,ExistsForString)175 TEST(BuiltInDefaultValueTest, ExistsForString) {
176   EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
177 }
178 
179 // Tests that BuiltInDefaultValue<const T>::Get() returns the same
180 // value as BuiltInDefaultValue<T>::Get() does.
TEST(BuiltInDefaultValueTest,WorksForConstTypes)181 TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
182   EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
183   EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
184   EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);
185   EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
186 }
187 
188 // A type that's default constructible.
189 class MyDefaultConstructible {
190  public:
MyDefaultConstructible()191   MyDefaultConstructible() : value_(42) {}
192 
value() const193   int value() const { return value_; }
194 
195  private:
196   int value_;
197 };
198 
199 // A type that's not default constructible.
200 class MyNonDefaultConstructible {
201  public:
202   // Does not have a default ctor.
MyNonDefaultConstructible(int a_value)203   explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
204 
value() const205   int value() const { return value_; }
206 
207  private:
208   int value_;
209 };
210 
211 
TEST(BuiltInDefaultValueTest,ExistsForDefaultConstructibleType)212 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
213   EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
214 }
215 
TEST(BuiltInDefaultValueTest,IsDefaultConstructedForDefaultConstructibleType)216 TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
217   EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
218 }
219 
220 
TEST(BuiltInDefaultValueTest,DoesNotExistForNonDefaultConstructibleType)221 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
222   EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
223 }
224 
225 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
TEST(BuiltInDefaultValueDeathTest,IsUndefinedForReferences)226 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
227   EXPECT_DEATH_IF_SUPPORTED({
228     BuiltInDefaultValue<int&>::Get();
229   }, "");
230   EXPECT_DEATH_IF_SUPPORTED({
231     BuiltInDefaultValue<const char&>::Get();
232   }, "");
233 }
234 
TEST(BuiltInDefaultValueDeathTest,IsUndefinedForNonDefaultConstructibleType)235 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
236   EXPECT_DEATH_IF_SUPPORTED({
237     BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
238   }, "");
239 }
240 
241 // Tests that DefaultValue<T>::IsSet() is false initially.
TEST(DefaultValueTest,IsInitiallyUnset)242 TEST(DefaultValueTest, IsInitiallyUnset) {
243   EXPECT_FALSE(DefaultValue<int>::IsSet());
244   EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
245   EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
246 }
247 
248 // Tests that DefaultValue<T> can be set and then unset.
TEST(DefaultValueTest,CanBeSetAndUnset)249 TEST(DefaultValueTest, CanBeSetAndUnset) {
250   EXPECT_TRUE(DefaultValue<int>::Exists());
251   EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
252 
253   DefaultValue<int>::Set(1);
254   DefaultValue<const MyNonDefaultConstructible>::Set(
255       MyNonDefaultConstructible(42));
256 
257   EXPECT_EQ(1, DefaultValue<int>::Get());
258   EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
259 
260   EXPECT_TRUE(DefaultValue<int>::Exists());
261   EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
262 
263   DefaultValue<int>::Clear();
264   DefaultValue<const MyNonDefaultConstructible>::Clear();
265 
266   EXPECT_FALSE(DefaultValue<int>::IsSet());
267   EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
268 
269   EXPECT_TRUE(DefaultValue<int>::Exists());
270   EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
271 }
272 
273 // Tests that DefaultValue<T>::Get() returns the
274 // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
275 // false.
TEST(DefaultValueDeathTest,GetReturnsBuiltInDefaultValueWhenUnset)276 TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
277   EXPECT_FALSE(DefaultValue<int>::IsSet());
278   EXPECT_TRUE(DefaultValue<int>::Exists());
279   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
280   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
281 
282   EXPECT_EQ(0, DefaultValue<int>::Get());
283 
284   EXPECT_DEATH_IF_SUPPORTED({
285     DefaultValue<MyNonDefaultConstructible>::Get();
286   }, "");
287 }
288 
TEST(DefaultValueTest,GetWorksForMoveOnlyIfSet)289 TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
290   EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
291   EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
292   DefaultValue<std::unique_ptr<int>>::SetFactory([] {
293     return std::unique_ptr<int>(new int(42));
294   });
295   EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
296   std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
297   EXPECT_EQ(42, *i);
298 }
299 
300 // Tests that DefaultValue<void>::Get() returns void.
TEST(DefaultValueTest,GetWorksForVoid)301 TEST(DefaultValueTest, GetWorksForVoid) {
302   return DefaultValue<void>::Get();
303 }
304 
305 // Tests using DefaultValue with a reference type.
306 
307 // Tests that DefaultValue<T&>::IsSet() is false initially.
TEST(DefaultValueOfReferenceTest,IsInitiallyUnset)308 TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
309   EXPECT_FALSE(DefaultValue<int&>::IsSet());
310   EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
311   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
312 }
313 
314 // Tests that DefaultValue<T&>::Exists is false initiallly.
TEST(DefaultValueOfReferenceTest,IsInitiallyNotExisting)315 TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
316   EXPECT_FALSE(DefaultValue<int&>::Exists());
317   EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
318   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
319 }
320 
321 // Tests that DefaultValue<T&> can be set and then unset.
TEST(DefaultValueOfReferenceTest,CanBeSetAndUnset)322 TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
323   int n = 1;
324   DefaultValue<const int&>::Set(n);
325   MyNonDefaultConstructible x(42);
326   DefaultValue<MyNonDefaultConstructible&>::Set(x);
327 
328   EXPECT_TRUE(DefaultValue<const int&>::Exists());
329   EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
330 
331   EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
332   EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
333 
334   DefaultValue<const int&>::Clear();
335   DefaultValue<MyNonDefaultConstructible&>::Clear();
336 
337   EXPECT_FALSE(DefaultValue<const int&>::Exists());
338   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
339 
340   EXPECT_FALSE(DefaultValue<const int&>::IsSet());
341   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
342 }
343 
344 // Tests that DefaultValue<T&>::Get() returns the
345 // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
346 // false.
TEST(DefaultValueOfReferenceDeathTest,GetReturnsBuiltInDefaultValueWhenUnset)347 TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
348   EXPECT_FALSE(DefaultValue<int&>::IsSet());
349   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
350 
351   EXPECT_DEATH_IF_SUPPORTED({
352     DefaultValue<int&>::Get();
353   }, "");
354   EXPECT_DEATH_IF_SUPPORTED({
355     DefaultValue<MyNonDefaultConstructible>::Get();
356   }, "");
357 }
358 
359 // Tests that ActionInterface can be implemented by defining the
360 // Perform method.
361 
362 typedef int MyGlobalFunction(bool, int);
363 
364 class MyActionImpl : public ActionInterface<MyGlobalFunction> {
365  public:
Perform(const std::tuple<bool,int> & args)366   int Perform(const std::tuple<bool, int>& args) override {
367     return std::get<0>(args) ? std::get<1>(args) : 0;
368   }
369 };
370 
TEST(ActionInterfaceTest,CanBeImplementedByDefiningPerform)371 TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
372   MyActionImpl my_action_impl;
373   (void)my_action_impl;
374 }
375 
TEST(ActionInterfaceTest,MakeAction)376 TEST(ActionInterfaceTest, MakeAction) {
377   Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
378 
379   // When exercising the Perform() method of Action<F>, we must pass
380   // it a tuple whose size and type are compatible with F's argument
381   // types.  For example, if F is int(), then Perform() takes a
382   // 0-tuple; if F is void(bool, int), then Perform() takes a
383   // std::tuple<bool, int>, and so on.
384   EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
385 }
386 
387 // Tests that Action<F> can be contructed from a pointer to
388 // ActionInterface<F>.
TEST(ActionTest,CanBeConstructedFromActionInterface)389 TEST(ActionTest, CanBeConstructedFromActionInterface) {
390   Action<MyGlobalFunction> action(new MyActionImpl);
391 }
392 
393 // Tests that Action<F> delegates actual work to ActionInterface<F>.
TEST(ActionTest,DelegatesWorkToActionInterface)394 TEST(ActionTest, DelegatesWorkToActionInterface) {
395   const Action<MyGlobalFunction> action(new MyActionImpl);
396 
397   EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
398   EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1)));
399 }
400 
401 // Tests that Action<F> can be copied.
TEST(ActionTest,IsCopyable)402 TEST(ActionTest, IsCopyable) {
403   Action<MyGlobalFunction> a1(new MyActionImpl);
404   Action<MyGlobalFunction> a2(a1);  // Tests the copy constructor.
405 
406   // a1 should continue to work after being copied from.
407   EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
408   EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
409 
410   // a2 should work like the action it was copied from.
411   EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
412   EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
413 
414   a2 = a1;  // Tests the assignment operator.
415 
416   // a1 should continue to work after being copied from.
417   EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
418   EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
419 
420   // a2 should work like the action it was copied from.
421   EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
422   EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
423 }
424 
425 // Tests that an Action<From> object can be converted to a
426 // compatible Action<To> object.
427 
428 class IsNotZero : public ActionInterface<bool(int)> {  // NOLINT
429  public:
Perform(const std::tuple<int> & arg)430   bool Perform(const std::tuple<int>& arg) override {
431     return std::get<0>(arg) != 0;
432   }
433 };
434 
TEST(ActionTest,CanBeConvertedToOtherActionType)435 TEST(ActionTest, CanBeConvertedToOtherActionType) {
436   const Action<bool(int)> a1(new IsNotZero);  // NOLINT
437   const Action<int(char)> a2 = Action<int(char)>(a1);  // NOLINT
438   EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));
439   EXPECT_EQ(0, a2.Perform(std::make_tuple('\0')));
440 }
441 
442 // The following two classes are for testing MakePolymorphicAction().
443 
444 // Implements a polymorphic action that returns the second of the
445 // arguments it receives.
446 class ReturnSecondArgumentAction {
447  public:
448   // We want to verify that MakePolymorphicAction() can work with a
449   // polymorphic action whose Perform() method template is either
450   // const or not.  This lets us verify the non-const case.
451   template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple & args)452   Result Perform(const ArgumentTuple& args) {
453     return std::get<1>(args);
454   }
455 };
456 
457 // Implements a polymorphic action that can be used in a nullary
458 // function to return 0.
459 class ReturnZeroFromNullaryFunctionAction {
460  public:
461   // For testing that MakePolymorphicAction() works when the
462   // implementation class' Perform() method template takes only one
463   // template parameter.
464   //
465   // We want to verify that MakePolymorphicAction() can work with a
466   // polymorphic action whose Perform() method template is either
467   // const or not.  This lets us verify the const case.
468   template <typename Result>
Perform(const std::tuple<> &) const469   Result Perform(const std::tuple<>&) const {
470     return 0;
471   }
472 };
473 
474 // These functions verify that MakePolymorphicAction() returns a
475 // PolymorphicAction<T> where T is the argument's type.
476 
ReturnSecondArgument()477 PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
478   return MakePolymorphicAction(ReturnSecondArgumentAction());
479 }
480 
481 PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
ReturnZeroFromNullaryFunction()482 ReturnZeroFromNullaryFunction() {
483   return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
484 }
485 
486 // Tests that MakePolymorphicAction() turns a polymorphic action
487 // implementation class into a polymorphic action.
TEST(MakePolymorphicActionTest,ConstructsActionFromImpl)488 TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
489   Action<int(bool, int, double)> a1 = ReturnSecondArgument();  // NOLINT
490   EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0)));
491 }
492 
493 // Tests that MakePolymorphicAction() works when the implementation
494 // class' Perform() method template has only one template parameter.
TEST(MakePolymorphicActionTest,WorksWhenPerformHasOneTemplateParameter)495 TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
496   Action<int()> a1 = ReturnZeroFromNullaryFunction();
497   EXPECT_EQ(0, a1.Perform(std::make_tuple()));
498 
499   Action<void*()> a2 = ReturnZeroFromNullaryFunction();
500   EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr);
501 }
502 
503 // Tests that Return() works as an action for void-returning
504 // functions.
TEST(ReturnTest,WorksForVoid)505 TEST(ReturnTest, WorksForVoid) {
506   const Action<void(int)> ret = Return();  // NOLINT
507   return ret.Perform(std::make_tuple(1));
508 }
509 
510 // Tests that Return(v) returns v.
TEST(ReturnTest,ReturnsGivenValue)511 TEST(ReturnTest, ReturnsGivenValue) {
512   Action<int()> ret = Return(1);  // NOLINT
513   EXPECT_EQ(1, ret.Perform(std::make_tuple()));
514 
515   ret = Return(-5);
516   EXPECT_EQ(-5, ret.Perform(std::make_tuple()));
517 }
518 
519 // Tests that Return("string literal") works.
TEST(ReturnTest,AcceptsStringLiteral)520 TEST(ReturnTest, AcceptsStringLiteral) {
521   Action<const char*()> a1 = Return("Hello");
522   EXPECT_STREQ("Hello", a1.Perform(std::make_tuple()));
523 
524   Action<std::string()> a2 = Return("world");
525   EXPECT_EQ("world", a2.Perform(std::make_tuple()));
526 }
527 
528 // Test struct which wraps a vector of integers. Used in
529 // 'SupportsWrapperReturnType' test.
530 struct IntegerVectorWrapper {
531   std::vector<int> * v;
IntegerVectorWrapper__anon87d4a8ab0111::IntegerVectorWrapper532   IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {}  // NOLINT
533 };
534 
535 // Tests that Return() works when return type is a wrapper type.
TEST(ReturnTest,SupportsWrapperReturnType)536 TEST(ReturnTest, SupportsWrapperReturnType) {
537   // Initialize vector of integers.
538   std::vector<int> v;
539   for (int i = 0; i < 5; ++i) v.push_back(i);
540 
541   // Return() called with 'v' as argument. The Action will return the same data
542   // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
543   Action<IntegerVectorWrapper()> a = Return(v);
544   const std::vector<int>& result = *(a.Perform(std::make_tuple()).v);
545   EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4));
546 }
547 
548 // Tests that Return(v) is covaraint.
549 
550 struct Base {
operator ==__anon87d4a8ab0111::Base551   bool operator==(const Base&) { return true; }
552 };
553 
554 struct Derived : public Base {
operator ==__anon87d4a8ab0111::Derived555   bool operator==(const Derived&) { return true; }
556 };
557 
TEST(ReturnTest,IsCovariant)558 TEST(ReturnTest, IsCovariant) {
559   Base base;
560   Derived derived;
561   Action<Base*()> ret = Return(&base);
562   EXPECT_EQ(&base, ret.Perform(std::make_tuple()));
563 
564   ret = Return(&derived);
565   EXPECT_EQ(&derived, ret.Perform(std::make_tuple()));
566 }
567 
568 // Tests that the type of the value passed into Return is converted into T
569 // when the action is cast to Action<T(...)> rather than when the action is
570 // performed. See comments on testing::internal::ReturnAction in
571 // gmock-actions.h for more information.
572 class FromType {
573  public:
FromType(bool * is_converted)574   explicit FromType(bool* is_converted) : converted_(is_converted) {}
converted() const575   bool* converted() const { return converted_; }
576 
577  private:
578   bool* const converted_;
579 };
580 
581 class ToType {
582  public:
583   // Must allow implicit conversion due to use in ImplicitCast_<T>.
ToType(const FromType & x)584   ToType(const FromType& x) { *x.converted() = true; }  // NOLINT
585 };
586 
TEST(ReturnTest,ConvertsArgumentWhenConverted)587 TEST(ReturnTest, ConvertsArgumentWhenConverted) {
588   bool converted = false;
589   FromType x(&converted);
590   Action<ToType()> action(Return(x));
591   EXPECT_TRUE(converted) << "Return must convert its argument in its own "
592                          << "conversion operator.";
593   converted = false;
594   action.Perform(std::tuple<>());
595   EXPECT_FALSE(converted) << "Action must NOT convert its argument "
596                           << "when performed.";
597 }
598 
599 class DestinationType {};
600 
601 class SourceType {
602  public:
603   // Note: a non-const typecast operator.
operator DestinationType()604   operator DestinationType() { return DestinationType(); }
605 };
606 
TEST(ReturnTest,CanConvertArgumentUsingNonConstTypeCastOperator)607 TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
608   SourceType s;
609   Action<DestinationType()> action(Return(s));
610 }
611 
612 // Tests that ReturnNull() returns NULL in a pointer-returning function.
TEST(ReturnNullTest,WorksInPointerReturningFunction)613 TEST(ReturnNullTest, WorksInPointerReturningFunction) {
614   const Action<int*()> a1 = ReturnNull();
615   EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
616 
617   const Action<const char*(bool)> a2 = ReturnNull();  // NOLINT
618   EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr);
619 }
620 
621 // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
622 // functions.
TEST(ReturnNullTest,WorksInSmartPointerReturningFunction)623 TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
624   const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
625   EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
626 
627   const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
628   EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr);
629 }
630 
631 // Tests that ReturnRef(v) works for reference types.
TEST(ReturnRefTest,WorksForReference)632 TEST(ReturnRefTest, WorksForReference) {
633   const int n = 0;
634   const Action<const int&(bool)> ret = ReturnRef(n);  // NOLINT
635 
636   EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true)));
637 }
638 
639 // Tests that ReturnRef(v) is covariant.
TEST(ReturnRefTest,IsCovariant)640 TEST(ReturnRefTest, IsCovariant) {
641   Base base;
642   Derived derived;
643   Action<Base&()> a = ReturnRef(base);
644   EXPECT_EQ(&base, &a.Perform(std::make_tuple()));
645 
646   a = ReturnRef(derived);
647   EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));
648 }
649 
650 template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
CanCallReturnRef(T &&)651 bool CanCallReturnRef(T&&) { return true; }
CanCallReturnRef(Unused)652 bool CanCallReturnRef(Unused) { return false; }
653 
654 // Tests that ReturnRef(v) is working with non-temporaries (T&)
TEST(ReturnRefTest,WorksForNonTemporary)655 TEST(ReturnRefTest, WorksForNonTemporary) {
656   int scalar_value = 123;
657   EXPECT_TRUE(CanCallReturnRef(scalar_value));
658 
659   std::string non_scalar_value("ABC");
660   EXPECT_TRUE(CanCallReturnRef(non_scalar_value));
661 
662   const int const_scalar_value{321};
663   EXPECT_TRUE(CanCallReturnRef(const_scalar_value));
664 
665   const std::string const_non_scalar_value("CBA");
666   EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value));
667 }
668 
669 // Tests that ReturnRef(v) is not working with temporaries (T&&)
TEST(ReturnRefTest,DoesNotWorkForTemporary)670 TEST(ReturnRefTest, DoesNotWorkForTemporary) {
671   auto scalar_value = []()  -> int { return 123; };
672   EXPECT_FALSE(CanCallReturnRef(scalar_value()));
673 
674   auto non_scalar_value = []() -> std::string { return "ABC"; };
675   EXPECT_FALSE(CanCallReturnRef(non_scalar_value()));
676 
677   // cannot use here callable returning "const scalar type",
678   // because such const for scalar return type is ignored
679   EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321)));
680 
681   auto const_non_scalar_value = []() -> const std::string { return "CBA"; };
682   EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value()));
683 }
684 
685 // Tests that ReturnRefOfCopy(v) works for reference types.
TEST(ReturnRefOfCopyTest,WorksForReference)686 TEST(ReturnRefOfCopyTest, WorksForReference) {
687   int n = 42;
688   const Action<const int&()> ret = ReturnRefOfCopy(n);
689 
690   EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
691   EXPECT_EQ(42, ret.Perform(std::make_tuple()));
692 
693   n = 43;
694   EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
695   EXPECT_EQ(42, ret.Perform(std::make_tuple()));
696 }
697 
698 // Tests that ReturnRefOfCopy(v) is covariant.
TEST(ReturnRefOfCopyTest,IsCovariant)699 TEST(ReturnRefOfCopyTest, IsCovariant) {
700   Base base;
701   Derived derived;
702   Action<Base&()> a = ReturnRefOfCopy(base);
703   EXPECT_NE(&base, &a.Perform(std::make_tuple()));
704 
705   a = ReturnRefOfCopy(derived);
706   EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
707 }
708 
709 // Tests that ReturnRoundRobin(v) works with initializer lists
TEST(ReturnRoundRobinTest,WorksForInitList)710 TEST(ReturnRoundRobinTest, WorksForInitList) {
711   Action<int()> ret = ReturnRoundRobin({1, 2, 3});
712 
713   EXPECT_EQ(1, ret.Perform(std::make_tuple()));
714   EXPECT_EQ(2, ret.Perform(std::make_tuple()));
715   EXPECT_EQ(3, ret.Perform(std::make_tuple()));
716   EXPECT_EQ(1, ret.Perform(std::make_tuple()));
717   EXPECT_EQ(2, ret.Perform(std::make_tuple()));
718   EXPECT_EQ(3, ret.Perform(std::make_tuple()));
719 }
720 
721 // Tests that ReturnRoundRobin(v) works with vectors
TEST(ReturnRoundRobinTest,WorksForVector)722 TEST(ReturnRoundRobinTest, WorksForVector) {
723   std::vector<double> v = {4.4, 5.5, 6.6};
724   Action<double()> ret = ReturnRoundRobin(v);
725 
726   EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
727   EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
728   EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
729   EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
730   EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
731   EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
732 }
733 
734 // Tests that DoDefault() does the default action for the mock method.
735 
736 class MockClass {
737  public:
MockClass()738   MockClass() {}
739 
740   MOCK_METHOD1(IntFunc, int(bool flag));  // NOLINT
741   MOCK_METHOD0(Foo, MyNonDefaultConstructible());
742   MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
743   MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
744   MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
745   MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
746   MOCK_METHOD2(TakeUnique,
747                int(const std::unique_ptr<int>&, std::unique_ptr<int>));
748 
749  private:
750   GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
751 };
752 
753 // Tests that DoDefault() returns the built-in default value for the
754 // return type by default.
TEST(DoDefaultTest,ReturnsBuiltInDefaultValueByDefault)755 TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
756   MockClass mock;
757   EXPECT_CALL(mock, IntFunc(_))
758       .WillOnce(DoDefault());
759   EXPECT_EQ(0, mock.IntFunc(true));
760 }
761 
762 // Tests that DoDefault() throws (when exceptions are enabled) or aborts
763 // the process when there is no built-in default value for the return type.
TEST(DoDefaultDeathTest,DiesForUnknowType)764 TEST(DoDefaultDeathTest, DiesForUnknowType) {
765   MockClass mock;
766   EXPECT_CALL(mock, Foo())
767       .WillRepeatedly(DoDefault());
768 #if GTEST_HAS_EXCEPTIONS
769   EXPECT_ANY_THROW(mock.Foo());
770 #else
771   EXPECT_DEATH_IF_SUPPORTED({
772     mock.Foo();
773   }, "");
774 #endif
775 }
776 
777 // Tests that using DoDefault() inside a composite action leads to a
778 // run-time error.
779 
VoidFunc(bool)780 void VoidFunc(bool /* flag */) {}
781 
TEST(DoDefaultDeathTest,DiesIfUsedInCompositeAction)782 TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
783   MockClass mock;
784   EXPECT_CALL(mock, IntFunc(_))
785       .WillRepeatedly(DoAll(Invoke(VoidFunc),
786                             DoDefault()));
787 
788   // Ideally we should verify the error message as well.  Sadly,
789   // EXPECT_DEATH() can only capture stderr, while Google Mock's
790   // errors are printed on stdout.  Therefore we have to settle for
791   // not verifying the message.
792   EXPECT_DEATH_IF_SUPPORTED({
793     mock.IntFunc(true);
794   }, "");
795 }
796 
797 // Tests that DoDefault() returns the default value set by
798 // DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
TEST(DoDefaultTest,ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne)799 TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
800   DefaultValue<int>::Set(1);
801   MockClass mock;
802   EXPECT_CALL(mock, IntFunc(_))
803       .WillOnce(DoDefault());
804   EXPECT_EQ(1, mock.IntFunc(false));
805   DefaultValue<int>::Clear();
806 }
807 
808 // Tests that DoDefault() does the action specified by ON_CALL().
TEST(DoDefaultTest,DoesWhatOnCallSpecifies)809 TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
810   MockClass mock;
811   ON_CALL(mock, IntFunc(_))
812       .WillByDefault(Return(2));
813   EXPECT_CALL(mock, IntFunc(_))
814       .WillOnce(DoDefault());
815   EXPECT_EQ(2, mock.IntFunc(false));
816 }
817 
818 // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
TEST(DoDefaultTest,CannotBeUsedInOnCall)819 TEST(DoDefaultTest, CannotBeUsedInOnCall) {
820   MockClass mock;
821   EXPECT_NONFATAL_FAILURE({  // NOLINT
822     ON_CALL(mock, IntFunc(_))
823       .WillByDefault(DoDefault());
824   }, "DoDefault() cannot be used in ON_CALL()");
825 }
826 
827 // Tests that SetArgPointee<N>(v) sets the variable pointed to by
828 // the N-th (0-based) argument to v.
TEST(SetArgPointeeTest,SetsTheNthPointee)829 TEST(SetArgPointeeTest, SetsTheNthPointee) {
830   typedef void MyFunction(bool, int*, char*);
831   Action<MyFunction> a = SetArgPointee<1>(2);
832 
833   int n = 0;
834   char ch = '\0';
835   a.Perform(std::make_tuple(true, &n, &ch));
836   EXPECT_EQ(2, n);
837   EXPECT_EQ('\0', ch);
838 
839   a = SetArgPointee<2>('a');
840   n = 0;
841   ch = '\0';
842   a.Perform(std::make_tuple(true, &n, &ch));
843   EXPECT_EQ(0, n);
844   EXPECT_EQ('a', ch);
845 }
846 
847 // Tests that SetArgPointee<N>() accepts a string literal.
TEST(SetArgPointeeTest,AcceptsStringLiteral)848 TEST(SetArgPointeeTest, AcceptsStringLiteral) {
849   typedef void MyFunction(std::string*, const char**);
850   Action<MyFunction> a = SetArgPointee<0>("hi");
851   std::string str;
852   const char* ptr = nullptr;
853   a.Perform(std::make_tuple(&str, &ptr));
854   EXPECT_EQ("hi", str);
855   EXPECT_TRUE(ptr == nullptr);
856 
857   a = SetArgPointee<1>("world");
858   str = "";
859   a.Perform(std::make_tuple(&str, &ptr));
860   EXPECT_EQ("", str);
861   EXPECT_STREQ("world", ptr);
862 }
863 
TEST(SetArgPointeeTest,AcceptsWideStringLiteral)864 TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
865   typedef void MyFunction(const wchar_t**);
866   Action<MyFunction> a = SetArgPointee<0>(L"world");
867   const wchar_t* ptr = nullptr;
868   a.Perform(std::make_tuple(&ptr));
869   EXPECT_STREQ(L"world", ptr);
870 
871 # if GTEST_HAS_STD_WSTRING
872 
873   typedef void MyStringFunction(std::wstring*);
874   Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
875   std::wstring str = L"";
876   a2.Perform(std::make_tuple(&str));
877   EXPECT_EQ(L"world", str);
878 
879 # endif
880 }
881 
882 // Tests that SetArgPointee<N>() accepts a char pointer.
TEST(SetArgPointeeTest,AcceptsCharPointer)883 TEST(SetArgPointeeTest, AcceptsCharPointer) {
884   typedef void MyFunction(bool, std::string*, const char**);
885   const char* const hi = "hi";
886   Action<MyFunction> a = SetArgPointee<1>(hi);
887   std::string str;
888   const char* ptr = nullptr;
889   a.Perform(std::make_tuple(true, &str, &ptr));
890   EXPECT_EQ("hi", str);
891   EXPECT_TRUE(ptr == nullptr);
892 
893   char world_array[] = "world";
894   char* const world = world_array;
895   a = SetArgPointee<2>(world);
896   str = "";
897   a.Perform(std::make_tuple(true, &str, &ptr));
898   EXPECT_EQ("", str);
899   EXPECT_EQ(world, ptr);
900 }
901 
TEST(SetArgPointeeTest,AcceptsWideCharPointer)902 TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
903   typedef void MyFunction(bool, const wchar_t**);
904   const wchar_t* const hi = L"hi";
905   Action<MyFunction> a = SetArgPointee<1>(hi);
906   const wchar_t* ptr = nullptr;
907   a.Perform(std::make_tuple(true, &ptr));
908   EXPECT_EQ(hi, ptr);
909 
910 # if GTEST_HAS_STD_WSTRING
911 
912   typedef void MyStringFunction(bool, std::wstring*);
913   wchar_t world_array[] = L"world";
914   wchar_t* const world = world_array;
915   Action<MyStringFunction> a2 = SetArgPointee<1>(world);
916   std::wstring str;
917   a2.Perform(std::make_tuple(true, &str));
918   EXPECT_EQ(world_array, str);
919 # endif
920 }
921 
922 // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
923 // the N-th (0-based) argument to v.
TEST(SetArgumentPointeeTest,SetsTheNthPointee)924 TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
925   typedef void MyFunction(bool, int*, char*);
926   Action<MyFunction> a = SetArgumentPointee<1>(2);
927 
928   int n = 0;
929   char ch = '\0';
930   a.Perform(std::make_tuple(true, &n, &ch));
931   EXPECT_EQ(2, n);
932   EXPECT_EQ('\0', ch);
933 
934   a = SetArgumentPointee<2>('a');
935   n = 0;
936   ch = '\0';
937   a.Perform(std::make_tuple(true, &n, &ch));
938   EXPECT_EQ(0, n);
939   EXPECT_EQ('a', ch);
940 }
941 
942 // Sample functions and functors for testing Invoke() and etc.
Nullary()943 int Nullary() { return 1; }
944 
945 class NullaryFunctor {
946  public:
operator ()()947   int operator()() { return 2; }
948 };
949 
950 bool g_done = false;
VoidNullary()951 void VoidNullary() { g_done = true; }
952 
953 class VoidNullaryFunctor {
954  public:
operator ()()955   void operator()() { g_done = true; }
956 };
957 
Short(short n)958 short Short(short n) { return n; }  // NOLINT
Char(char ch)959 char Char(char ch) { return ch; }
960 
CharPtr(const char * s)961 const char* CharPtr(const char* s) { return s; }
962 
Unary(int x)963 bool Unary(int x) { return x < 0; }
964 
Binary(const char * input,short n)965 const char* Binary(const char* input, short n) { return input + n; }  // NOLINT
966 
VoidBinary(int,char)967 void VoidBinary(int, char) { g_done = true; }
968 
Ternary(int x,char y,short z)969 int Ternary(int x, char y, short z) { return x + y + z; }  // NOLINT
970 
SumOf4(int a,int b,int c,int d)971 int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
972 
973 class Foo {
974  public:
Foo()975   Foo() : value_(123) {}
976 
Nullary() const977   int Nullary() const { return value_; }
978 
979  private:
980   int value_;
981 };
982 
983 // Tests InvokeWithoutArgs(function).
TEST(InvokeWithoutArgsTest,Function)984 TEST(InvokeWithoutArgsTest, Function) {
985   // As an action that takes one argument.
986   Action<int(int)> a = InvokeWithoutArgs(Nullary);  // NOLINT
987   EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
988 
989   // As an action that takes two arguments.
990   Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary);  // NOLINT
991   EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5)));
992 
993   // As an action that returns void.
994   Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary);  // NOLINT
995   g_done = false;
996   a3.Perform(std::make_tuple(1));
997   EXPECT_TRUE(g_done);
998 }
999 
1000 // Tests InvokeWithoutArgs(functor).
TEST(InvokeWithoutArgsTest,Functor)1001 TEST(InvokeWithoutArgsTest, Functor) {
1002   // As an action that takes no argument.
1003   Action<int()> a = InvokeWithoutArgs(NullaryFunctor());  // NOLINT
1004   EXPECT_EQ(2, a.Perform(std::make_tuple()));
1005 
1006   // As an action that takes three arguments.
1007   Action<int(int, double, char)> a2 =  // NOLINT
1008       InvokeWithoutArgs(NullaryFunctor());
1009   EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a')));
1010 
1011   // As an action that returns void.
1012   Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
1013   g_done = false;
1014   a3.Perform(std::make_tuple());
1015   EXPECT_TRUE(g_done);
1016 }
1017 
1018 // Tests InvokeWithoutArgs(obj_ptr, method).
TEST(InvokeWithoutArgsTest,Method)1019 TEST(InvokeWithoutArgsTest, Method) {
1020   Foo foo;
1021   Action<int(bool, char)> a =  // NOLINT
1022       InvokeWithoutArgs(&foo, &Foo::Nullary);
1023   EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));
1024 }
1025 
1026 // Tests using IgnoreResult() on a polymorphic action.
TEST(IgnoreResultTest,PolymorphicAction)1027 TEST(IgnoreResultTest, PolymorphicAction) {
1028   Action<void(int)> a = IgnoreResult(Return(5));  // NOLINT
1029   a.Perform(std::make_tuple(1));
1030 }
1031 
1032 // Tests using IgnoreResult() on a monomorphic action.
1033 
ReturnOne()1034 int ReturnOne() {
1035   g_done = true;
1036   return 1;
1037 }
1038 
TEST(IgnoreResultTest,MonomorphicAction)1039 TEST(IgnoreResultTest, MonomorphicAction) {
1040   g_done = false;
1041   Action<void()> a = IgnoreResult(Invoke(ReturnOne));
1042   a.Perform(std::make_tuple());
1043   EXPECT_TRUE(g_done);
1044 }
1045 
1046 // Tests using IgnoreResult() on an action that returns a class type.
1047 
ReturnMyNonDefaultConstructible(double)1048 MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1049   g_done = true;
1050   return MyNonDefaultConstructible(42);
1051 }
1052 
TEST(IgnoreResultTest,ActionReturningClass)1053 TEST(IgnoreResultTest, ActionReturningClass) {
1054   g_done = false;
1055   Action<void(int)> a =
1056       IgnoreResult(Invoke(ReturnMyNonDefaultConstructible));  // NOLINT
1057   a.Perform(std::make_tuple(2));
1058   EXPECT_TRUE(g_done);
1059 }
1060 
TEST(AssignTest,Int)1061 TEST(AssignTest, Int) {
1062   int x = 0;
1063   Action<void(int)> a = Assign(&x, 5);
1064   a.Perform(std::make_tuple(0));
1065   EXPECT_EQ(5, x);
1066 }
1067 
TEST(AssignTest,String)1068 TEST(AssignTest, String) {
1069   ::std::string x;
1070   Action<void(void)> a = Assign(&x, "Hello, world");
1071   a.Perform(std::make_tuple());
1072   EXPECT_EQ("Hello, world", x);
1073 }
1074 
TEST(AssignTest,CompatibleTypes)1075 TEST(AssignTest, CompatibleTypes) {
1076   double x = 0;
1077   Action<void(int)> a = Assign(&x, 5);
1078   a.Perform(std::make_tuple(0));
1079   EXPECT_DOUBLE_EQ(5, x);
1080 }
1081 
1082 
1083 // Tests using WithArgs and with an action that takes 1 argument.
TEST(WithArgsTest,OneArg)1084 TEST(WithArgsTest, OneArg) {
1085   Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary));  // NOLINT
1086   EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));
1087   EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));
1088 }
1089 
1090 // Tests using WithArgs with an action that takes 2 arguments.
TEST(WithArgsTest,TwoArgs)1091 TEST(WithArgsTest, TwoArgs) {
1092   Action<const char*(const char* s, double x, short n)> a =  // NOLINT
1093       WithArgs<0, 2>(Invoke(Binary));
1094   const char s[] = "Hello";
1095   EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
1096 }
1097 
1098 struct ConcatAll {
operator ()__anon87d4a8ab0111::ConcatAll1099   std::string operator()() const { return {}; }
1100   template <typename... I>
operator ()__anon87d4a8ab0111::ConcatAll1101   std::string operator()(const char* a, I... i) const {
1102     return a + ConcatAll()(i...);
1103   }
1104 };
1105 
1106 // Tests using WithArgs with an action that takes 10 arguments.
TEST(WithArgsTest,TenArgs)1107 TEST(WithArgsTest, TenArgs) {
1108   Action<std::string(const char*, const char*, const char*, const char*)> a =
1109       WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
1110   EXPECT_EQ("0123210123",
1111             a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
1112                                       CharPtr("3"))));
1113 }
1114 
1115 // Tests using WithArgs with an action that is not Invoke().
1116 class SubtractAction : public ActionInterface<int(int, int)> {
1117  public:
Perform(const std::tuple<int,int> & args)1118   int Perform(const std::tuple<int, int>& args) override {
1119     return std::get<0>(args) - std::get<1>(args);
1120   }
1121 };
1122 
TEST(WithArgsTest,NonInvokeAction)1123 TEST(WithArgsTest, NonInvokeAction) {
1124   Action<int(const std::string&, int, int)> a =
1125       WithArgs<2, 1>(MakeAction(new SubtractAction));
1126   std::tuple<std::string, int, int> dummy =
1127       std::make_tuple(std::string("hi"), 2, 10);
1128   EXPECT_EQ(8, a.Perform(dummy));
1129 }
1130 
1131 // Tests using WithArgs to pass all original arguments in the original order.
TEST(WithArgsTest,Identity)1132 TEST(WithArgsTest, Identity) {
1133   Action<int(int x, char y, short z)> a =  // NOLINT
1134       WithArgs<0, 1, 2>(Invoke(Ternary));
1135   EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));
1136 }
1137 
1138 // Tests using WithArgs with repeated arguments.
TEST(WithArgsTest,RepeatedArguments)1139 TEST(WithArgsTest, RepeatedArguments) {
1140   Action<int(bool, int m, int n)> a =  // NOLINT
1141       WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
1142   EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));
1143 }
1144 
1145 // Tests using WithArgs with reversed argument order.
TEST(WithArgsTest,ReversedArgumentOrder)1146 TEST(WithArgsTest, ReversedArgumentOrder) {
1147   Action<const char*(short n, const char* input)> a =  // NOLINT
1148       WithArgs<1, 0>(Invoke(Binary));
1149   const char s[] = "Hello";
1150   EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));
1151 }
1152 
1153 // Tests using WithArgs with compatible, but not identical, argument types.
TEST(WithArgsTest,ArgsOfCompatibleTypes)1154 TEST(WithArgsTest, ArgsOfCompatibleTypes) {
1155   Action<long(short x, char y, double z, char c)> a =  // NOLINT
1156       WithArgs<0, 1, 3>(Invoke(Ternary));
1157   EXPECT_EQ(123,
1158             a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));
1159 }
1160 
1161 // Tests using WithArgs with an action that returns void.
TEST(WithArgsTest,VoidAction)1162 TEST(WithArgsTest, VoidAction) {
1163   Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
1164   g_done = false;
1165   a.Perform(std::make_tuple(1.5, 'a', 3));
1166   EXPECT_TRUE(g_done);
1167 }
1168 
TEST(WithArgsTest,ReturnReference)1169 TEST(WithArgsTest, ReturnReference) {
1170   Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });
1171   int i = 0;
1172   const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));
1173   EXPECT_EQ(&i, &res);
1174 }
1175 
TEST(WithArgsTest,InnerActionWithConversion)1176 TEST(WithArgsTest, InnerActionWithConversion) {
1177   Action<Derived*()> inner = [] { return nullptr; };
1178   Action<Base*(double)> a = testing::WithoutArgs(inner);
1179   EXPECT_EQ(nullptr, a.Perform(std::make_tuple(1.1)));
1180 }
1181 
1182 #if !GTEST_OS_WINDOWS_MOBILE
1183 
1184 class SetErrnoAndReturnTest : public testing::Test {
1185  protected:
SetUp()1186   void SetUp() override { errno = 0; }
TearDown()1187   void TearDown() override { errno = 0; }
1188 };
1189 
TEST_F(SetErrnoAndReturnTest,Int)1190 TEST_F(SetErrnoAndReturnTest, Int) {
1191   Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
1192   EXPECT_EQ(-5, a.Perform(std::make_tuple()));
1193   EXPECT_EQ(ENOTTY, errno);
1194 }
1195 
TEST_F(SetErrnoAndReturnTest,Ptr)1196 TEST_F(SetErrnoAndReturnTest, Ptr) {
1197   int x;
1198   Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
1199   EXPECT_EQ(&x, a.Perform(std::make_tuple()));
1200   EXPECT_EQ(ENOTTY, errno);
1201 }
1202 
TEST_F(SetErrnoAndReturnTest,CompatibleTypes)1203 TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
1204   Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
1205   EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));
1206   EXPECT_EQ(EINVAL, errno);
1207 }
1208 
1209 #endif  // !GTEST_OS_WINDOWS_MOBILE
1210 
1211 // Tests ByRef().
1212 
1213 // Tests that the result of ByRef() is copyable.
TEST(ByRefTest,IsCopyable)1214 TEST(ByRefTest, IsCopyable) {
1215   const std::string s1 = "Hi";
1216   const std::string s2 = "Hello";
1217 
1218   auto ref_wrapper = ByRef(s1);
1219   const std::string& r1 = ref_wrapper;
1220   EXPECT_EQ(&s1, &r1);
1221 
1222   // Assigns a new value to ref_wrapper.
1223   ref_wrapper = ByRef(s2);
1224   const std::string& r2 = ref_wrapper;
1225   EXPECT_EQ(&s2, &r2);
1226 
1227   auto ref_wrapper1 = ByRef(s1);
1228   // Copies ref_wrapper1 to ref_wrapper.
1229   ref_wrapper = ref_wrapper1;
1230   const std::string& r3 = ref_wrapper;
1231   EXPECT_EQ(&s1, &r3);
1232 }
1233 
1234 // Tests using ByRef() on a const value.
TEST(ByRefTest,ConstValue)1235 TEST(ByRefTest, ConstValue) {
1236   const int n = 0;
1237   // int& ref = ByRef(n);  // This shouldn't compile - we have a
1238                            // negative compilation test to catch it.
1239   const int& const_ref = ByRef(n);
1240   EXPECT_EQ(&n, &const_ref);
1241 }
1242 
1243 // Tests using ByRef() on a non-const value.
TEST(ByRefTest,NonConstValue)1244 TEST(ByRefTest, NonConstValue) {
1245   int n = 0;
1246 
1247   // ByRef(n) can be used as either an int&,
1248   int& ref = ByRef(n);
1249   EXPECT_EQ(&n, &ref);
1250 
1251   // or a const int&.
1252   const int& const_ref = ByRef(n);
1253   EXPECT_EQ(&n, &const_ref);
1254 }
1255 
1256 // Tests explicitly specifying the type when using ByRef().
TEST(ByRefTest,ExplicitType)1257 TEST(ByRefTest, ExplicitType) {
1258   int n = 0;
1259   const int& r1 = ByRef<const int>(n);
1260   EXPECT_EQ(&n, &r1);
1261 
1262   // ByRef<char>(n);  // This shouldn't compile - we have a negative
1263                       // compilation test to catch it.
1264 
1265   Derived d;
1266   Derived& r2 = ByRef<Derived>(d);
1267   EXPECT_EQ(&d, &r2);
1268 
1269   const Derived& r3 = ByRef<const Derived>(d);
1270   EXPECT_EQ(&d, &r3);
1271 
1272   Base& r4 = ByRef<Base>(d);
1273   EXPECT_EQ(&d, &r4);
1274 
1275   const Base& r5 = ByRef<const Base>(d);
1276   EXPECT_EQ(&d, &r5);
1277 
1278   // The following shouldn't compile - we have a negative compilation
1279   // test for it.
1280   //
1281   // Base b;
1282   // ByRef<Derived>(b);
1283 }
1284 
1285 // Tests that Google Mock prints expression ByRef(x) as a reference to x.
TEST(ByRefTest,PrintsCorrectly)1286 TEST(ByRefTest, PrintsCorrectly) {
1287   int n = 42;
1288   ::std::stringstream expected, actual;
1289   testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
1290   testing::internal::UniversalPrint(ByRef(n), &actual);
1291   EXPECT_EQ(expected.str(), actual.str());
1292 }
1293 
1294 struct UnaryConstructorClass {
UnaryConstructorClass__anon87d4a8ab0111::UnaryConstructorClass1295   explicit UnaryConstructorClass(int v) : value(v) {}
1296   int value;
1297 };
1298 
1299 // Tests using ReturnNew() with a unary constructor.
TEST(ReturnNewTest,Unary)1300 TEST(ReturnNewTest, Unary) {
1301   Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
1302   UnaryConstructorClass* c = a.Perform(std::make_tuple());
1303   EXPECT_EQ(4000, c->value);
1304   delete c;
1305 }
1306 
TEST(ReturnNewTest,UnaryWorksWhenMockMethodHasArgs)1307 TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
1308   Action<UnaryConstructorClass*(bool, int)> a =
1309       ReturnNew<UnaryConstructorClass>(4000);
1310   UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
1311   EXPECT_EQ(4000, c->value);
1312   delete c;
1313 }
1314 
TEST(ReturnNewTest,UnaryWorksWhenMockMethodReturnsPointerToConst)1315 TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
1316   Action<const UnaryConstructorClass*()> a =
1317       ReturnNew<UnaryConstructorClass>(4000);
1318   const UnaryConstructorClass* c = a.Perform(std::make_tuple());
1319   EXPECT_EQ(4000, c->value);
1320   delete c;
1321 }
1322 
1323 class TenArgConstructorClass {
1324  public:
TenArgConstructorClass(int a1,int a2,int a3,int a4,int a5,int a6,int a7,int a8,int a9,int a10)1325   TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
1326                          int a8, int a9, int a10)
1327       : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
1328   int value_;
1329 };
1330 
1331 // Tests using ReturnNew() with a 10-argument constructor.
TEST(ReturnNewTest,ConstructorThatTakes10Arguments)1332 TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
1333   Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(
1334       1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,
1335       0);
1336   TenArgConstructorClass* c = a.Perform(std::make_tuple());
1337   EXPECT_EQ(1234567890, c->value_);
1338   delete c;
1339 }
1340 
UniquePtrSource()1341 std::unique_ptr<int> UniquePtrSource() {
1342   return std::unique_ptr<int>(new int(19));
1343 }
1344 
VectorUniquePtrSource()1345 std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
1346   std::vector<std::unique_ptr<int>> out;
1347   out.emplace_back(new int(7));
1348   return out;
1349 }
1350 
TEST(MockMethodTest,CanReturnMoveOnlyValue_Return)1351 TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
1352   MockClass mock;
1353   std::unique_ptr<int> i(new int(19));
1354   EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
1355   EXPECT_CALL(mock, MakeVectorUnique())
1356       .WillOnce(Return(ByMove(VectorUniquePtrSource())));
1357   Derived* d = new Derived;
1358   EXPECT_CALL(mock, MakeUniqueBase())
1359       .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
1360 
1361   std::unique_ptr<int> result1 = mock.MakeUnique();
1362   EXPECT_EQ(19, *result1);
1363 
1364   std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1365   EXPECT_EQ(1u, vresult.size());
1366   EXPECT_NE(nullptr, vresult[0]);
1367   EXPECT_EQ(7, *vresult[0]);
1368 
1369   std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
1370   EXPECT_EQ(d, result2.get());
1371 }
1372 
TEST(MockMethodTest,CanReturnMoveOnlyValue_DoAllReturn)1373 TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
1374   testing::MockFunction<void()> mock_function;
1375   MockClass mock;
1376   std::unique_ptr<int> i(new int(19));
1377   EXPECT_CALL(mock_function, Call());
1378   EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
1379       InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
1380       Return(ByMove(std::move(i)))));
1381 
1382   std::unique_ptr<int> result1 = mock.MakeUnique();
1383   EXPECT_EQ(19, *result1);
1384 }
1385 
TEST(MockMethodTest,CanReturnMoveOnlyValue_Invoke)1386 TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1387   MockClass mock;
1388 
1389   // Check default value
1390   DefaultValue<std::unique_ptr<int>>::SetFactory([] {
1391     return std::unique_ptr<int>(new int(42));
1392   });
1393   EXPECT_EQ(42, *mock.MakeUnique());
1394 
1395   EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
1396   EXPECT_CALL(mock, MakeVectorUnique())
1397       .WillRepeatedly(Invoke(VectorUniquePtrSource));
1398   std::unique_ptr<int> result1 = mock.MakeUnique();
1399   EXPECT_EQ(19, *result1);
1400   std::unique_ptr<int> result2 = mock.MakeUnique();
1401   EXPECT_EQ(19, *result2);
1402   EXPECT_NE(result1, result2);
1403 
1404   std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1405   EXPECT_EQ(1u, vresult.size());
1406   EXPECT_NE(nullptr, vresult[0]);
1407   EXPECT_EQ(7, *vresult[0]);
1408 }
1409 
TEST(MockMethodTest,CanTakeMoveOnlyValue)1410 TEST(MockMethodTest, CanTakeMoveOnlyValue) {
1411   MockClass mock;
1412   auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
1413 
1414   EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
1415     return *i;
1416   });
1417   // DoAll() does not compile, since it would move from its arguments twice.
1418   // EXPECT_CALL(mock, TakeUnique(_, _))
1419   //     .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
1420   //     Return(1)));
1421   EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
1422       .WillOnce(Return(-7))
1423       .RetiresOnSaturation();
1424   EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
1425       .WillOnce(Return(-1))
1426       .RetiresOnSaturation();
1427 
1428   EXPECT_EQ(5, mock.TakeUnique(make(5)));
1429   EXPECT_EQ(-7, mock.TakeUnique(make(7)));
1430   EXPECT_EQ(7, mock.TakeUnique(make(7)));
1431   EXPECT_EQ(7, mock.TakeUnique(make(7)));
1432   EXPECT_EQ(-1, mock.TakeUnique({}));
1433 
1434   // Some arguments are moved, some passed by reference.
1435   auto lvalue = make(6);
1436   EXPECT_CALL(mock, TakeUnique(_, _))
1437       .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
1438         return *i * *j;
1439       });
1440   EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
1441 
1442   // The unique_ptr can be saved by the action.
1443   std::unique_ptr<int> saved;
1444   EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
1445     saved = std::move(i);
1446     return 0;
1447   });
1448   EXPECT_EQ(0, mock.TakeUnique(make(42)));
1449   EXPECT_EQ(42, *saved);
1450 }
1451 
1452 
1453 // Tests for std::function based action.
1454 
Add(int val,int & ref,int * ptr)1455 int Add(int val, int& ref, int* ptr) {  // NOLINT
1456   int result = val + ref + *ptr;
1457   ref = 42;
1458   *ptr = 43;
1459   return result;
1460 }
1461 
Deref(std::unique_ptr<int> ptr)1462 int Deref(std::unique_ptr<int> ptr) { return *ptr; }
1463 
1464 struct Double {
1465   template <typename T>
operator ()__anon87d4a8ab0111::Double1466   T operator()(T t) { return 2 * t; }
1467 };
1468 
UniqueInt(int i)1469 std::unique_ptr<int> UniqueInt(int i) {
1470   return std::unique_ptr<int>(new int(i));
1471 }
1472 
TEST(FunctorActionTest,ActionFromFunction)1473 TEST(FunctorActionTest, ActionFromFunction) {
1474   Action<int(int, int&, int*)> a = &Add;
1475   int x = 1, y = 2, z = 3;
1476   EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
1477   EXPECT_EQ(42, y);
1478   EXPECT_EQ(43, z);
1479 
1480   Action<int(std::unique_ptr<int>)> a1 = &Deref;
1481   EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
1482 }
1483 
TEST(FunctorActionTest,ActionFromLambda)1484 TEST(FunctorActionTest, ActionFromLambda) {
1485   Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
1486   EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
1487   EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5)));
1488 
1489   std::unique_ptr<int> saved;
1490   Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {
1491     saved = std::move(p);
1492   };
1493   a2.Perform(std::make_tuple(UniqueInt(5)));
1494   EXPECT_EQ(5, *saved);
1495 }
1496 
TEST(FunctorActionTest,PolymorphicFunctor)1497 TEST(FunctorActionTest, PolymorphicFunctor) {
1498   Action<int(int)> ai = Double();
1499   EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));
1500   Action<double(double)> ad = Double();  // Double? Double double!
1501   EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5)));
1502 }
1503 
TEST(FunctorActionTest,TypeConversion)1504 TEST(FunctorActionTest, TypeConversion) {
1505   // Numeric promotions are allowed.
1506   const Action<bool(int)> a1 = [](int i) { return i > 1; };
1507   const Action<int(bool)> a2 = Action<int(bool)>(a1);
1508   EXPECT_EQ(1, a1.Perform(std::make_tuple(42)));
1509   EXPECT_EQ(0, a2.Perform(std::make_tuple(42)));
1510 
1511   // Implicit constructors are allowed.
1512   const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };
1513   const Action<int(const char*)> s2 = Action<int(const char*)>(s1);
1514   EXPECT_EQ(0, s2.Perform(std::make_tuple("")));
1515   EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
1516 
1517   // Also between the lambda and the action itself.
1518   const Action<bool(std::string)> x1 = [](Unused) { return 42; };
1519   const Action<bool(std::string)> x2 = [] { return 42; };
1520   EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));
1521   EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));
1522 
1523   // Ensure decay occurs where required.
1524   std::function<int()> f = [] { return 7; };
1525   Action<int(int)> d = f;
1526   f = nullptr;
1527   EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
1528 
1529   // Ensure creation of an empty action succeeds.
1530   Action<void(int)>(nullptr);
1531 }
1532 
TEST(FunctorActionTest,UnusedArguments)1533 TEST(FunctorActionTest, UnusedArguments) {
1534   // Verify that users can ignore uninteresting arguments.
1535   Action<int(int, double y, double z)> a =
1536       [](int i, Unused, Unused) { return 2 * i; };
1537   std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
1538   EXPECT_EQ(6, a.Perform(dummy));
1539 }
1540 
1541 // Test that basic built-in actions work with move-only arguments.
TEST(MoveOnlyArgumentsTest,ReturningActions)1542 TEST(MoveOnlyArgumentsTest, ReturningActions) {
1543   Action<int(std::unique_ptr<int>)> a = Return(1);
1544   EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));
1545 
1546   a = testing::WithoutArgs([]() { return 7; });
1547   EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr)));
1548 
1549   Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
1550   int x = 0;
1551   a2.Perform(std::make_tuple(nullptr, &x));
1552   EXPECT_EQ(x, 3);
1553 }
1554 
ACTION(ReturnArity)1555 ACTION(ReturnArity) {
1556   return std::tuple_size<args_type>::value;
1557 }
1558 
TEST(ActionMacro,LargeArity)1559 TEST(ActionMacro, LargeArity) {
1560   EXPECT_EQ(
1561       1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));
1562   EXPECT_EQ(
1563       10,
1564       testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(
1565           ReturnArity())
1566           .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));
1567   EXPECT_EQ(
1568       20,
1569       testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,
1570                           int, int, int, int, int, int, int, int, int)>(
1571           ReturnArity())
1572           .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
1573                                    14, 15, 16, 17, 18, 19)));
1574 }
1575 
1576 }  // Unnamed namespace
1577 
1578 #ifdef _MSC_VER
1579 #if _MSC_VER == 1900
1580 #  pragma warning(pop)
1581 #endif
1582 #endif
1583 
1584