xref: /freebsd/contrib/googletest/googlemock/test/gmock-actions_test.cc (revision 46333229c6a0187ebf231805682ee0bceed704d1)
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 // Google Mock - a framework for writing C++ mock classes.
31 //
32 // This file tests the built-in actions.
33 
34 #include "gmock/gmock-actions.h"
35 
36 #include <algorithm>
37 #include <functional>
38 #include <iterator>
39 #include <memory>
40 #include <sstream>
41 #include <string>
42 #include <tuple>
43 #include <type_traits>
44 #include <utility>
45 #include <vector>
46 
47 #include "gmock/gmock.h"
48 #include "gmock/internal/gmock-port.h"
49 #include "gtest/gtest-spi.h"
50 #include "gtest/gtest.h"
51 #include "gtest/internal/gtest-port.h"
52 
53 // Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
54 // length exceeded) for MSVC.
55 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
56 #if defined(_MSC_VER) && (_MSC_VER == 1900)
57 // and silence C4800 (C4800: 'int *const ': forcing value
58 // to bool 'true' or 'false') for MSVC 15
59 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
60 #endif
61 
62 namespace testing {
63 namespace {
64 
65 using ::testing::internal::BuiltInDefaultValue;
66 
TEST(TypeTraits,Negation)67 TEST(TypeTraits, Negation) {
68   // Direct use with std types.
69   static_assert(std::is_base_of<std::false_type,
70                                 internal::negation<std::true_type>>::value,
71                 "");
72 
73   static_assert(std::is_base_of<std::true_type,
74                                 internal::negation<std::false_type>>::value,
75                 "");
76 
77   // With other types that fit the requirement of a value member that is
78   // convertible to bool.
79   static_assert(std::is_base_of<
80                     std::true_type,
81                     internal::negation<std::integral_constant<int, 0>>>::value,
82                 "");
83 
84   static_assert(std::is_base_of<
85                     std::false_type,
86                     internal::negation<std::integral_constant<int, 1>>>::value,
87                 "");
88 
89   static_assert(std::is_base_of<
90                     std::false_type,
91                     internal::negation<std::integral_constant<int, -1>>>::value,
92                 "");
93 }
94 
95 // Weird false/true types that aren't actually bool constants (but should still
96 // be legal according to [meta.logical] because `bool(T::value)` is valid), are
97 // distinct from std::false_type and std::true_type, and are distinct from other
98 // instantiations of the same template.
99 //
100 // These let us check finicky details mandated by the standard like
101 // "std::conjunction should evaluate to a type that inherits from the first
102 // false-y input".
103 template <int>
104 struct MyFalse : std::integral_constant<int, 0> {};
105 
106 template <int>
107 struct MyTrue : std::integral_constant<int, -1> {};
108 
TEST(TypeTraits,Conjunction)109 TEST(TypeTraits, Conjunction) {
110   // Base case: always true.
111   static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value,
112                 "");
113 
114   // One predicate: inherits from that predicate, regardless of value.
115   static_assert(
116       std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value,
117       "");
118 
119   static_assert(
120       std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, "");
121 
122   // Multiple predicates, with at least one false: inherits from that one.
123   static_assert(
124       std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
125                                                         MyTrue<2>>>::value,
126       "");
127 
128   static_assert(
129       std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
130                                                         MyFalse<2>>>::value,
131       "");
132 
133   // Short circuiting: in the case above, additional predicates need not even
134   // define a value member.
135   struct Empty {};
136   static_assert(
137       std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
138                                                         Empty>>::value,
139       "");
140 
141   // All predicates true: inherits from the last.
142   static_assert(
143       std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>,
144                                                        MyTrue<2>>>::value,
145       "");
146 }
147 
TEST(TypeTraits,Disjunction)148 TEST(TypeTraits, Disjunction) {
149   // Base case: always false.
150   static_assert(
151       std::is_base_of<std::false_type, internal::disjunction<>>::value, "");
152 
153   // One predicate: inherits from that predicate, regardless of value.
154   static_assert(
155       std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value,
156       "");
157 
158   static_assert(
159       std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, "");
160 
161   // Multiple predicates, with at least one true: inherits from that one.
162   static_assert(
163       std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
164                                                        MyFalse<2>>>::value,
165       "");
166 
167   static_assert(
168       std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
169                                                        MyTrue<2>>>::value,
170       "");
171 
172   // Short circuiting: in the case above, additional predicates need not even
173   // define a value member.
174   struct Empty {};
175   static_assert(
176       std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
177                                                        Empty>>::value,
178       "");
179 
180   // All predicates false: inherits from the last.
181   static_assert(
182       std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>,
183                                                         MyFalse<2>>>::value,
184       "");
185 }
186 
TEST(TypeTraits,IsInvocableRV)187 TEST(TypeTraits, IsInvocableRV) {
188   struct C {
189     int operator()() const { return 0; }
190     void operator()(int) & {}
191     std::string operator()(int) && { return ""; };
192   };
193 
194   // The first overload is callable for const and non-const rvalues and lvalues.
195   // It can be used to obtain an int, cv void, or anything int is convertible
196   // to.
197   static_assert(internal::is_callable_r<int, C>::value, "");
198   static_assert(internal::is_callable_r<int, C&>::value, "");
199   static_assert(internal::is_callable_r<int, const C>::value, "");
200   static_assert(internal::is_callable_r<int, const C&>::value, "");
201 
202   static_assert(internal::is_callable_r<void, C>::value, "");
203   static_assert(internal::is_callable_r<const volatile void, C>::value, "");
204   static_assert(internal::is_callable_r<char, C>::value, "");
205 
206   // It's possible to provide an int. If it's given to an lvalue, the result is
207   // void. Otherwise it is std::string (which is also treated as allowed for a
208   // void result type).
209   static_assert(internal::is_callable_r<void, C&, int>::value, "");
210   static_assert(!internal::is_callable_r<int, C&, int>::value, "");
211   static_assert(!internal::is_callable_r<std::string, C&, int>::value, "");
212   static_assert(!internal::is_callable_r<void, const C&, int>::value, "");
213 
214   static_assert(internal::is_callable_r<std::string, C, int>::value, "");
215   static_assert(internal::is_callable_r<void, C, int>::value, "");
216   static_assert(!internal::is_callable_r<int, C, int>::value, "");
217 
218   // It's not possible to provide other arguments.
219   static_assert(!internal::is_callable_r<void, C, std::string>::value, "");
220   static_assert(!internal::is_callable_r<void, C, int, int>::value, "");
221 
222   // In C++17 and above, where it's guaranteed that functions can return
223   // non-moveable objects, everything should work fine for non-moveable rsult
224   // types too.
225   // TODO(b/396121064) - Fix this test under MSVC
226 #ifndef _MSC_VER
227   {
228     struct NonMoveable {
229       NonMoveable() = default;
230       NonMoveable(NonMoveable&&) = delete;
231     };
232 
233     static_assert(!std::is_move_constructible_v<NonMoveable>);
234 
235     struct Callable {
236       NonMoveable operator()() { return NonMoveable(); }
237     };
238 
239     static_assert(internal::is_callable_r<NonMoveable, Callable>::value);
240     static_assert(internal::is_callable_r<void, Callable>::value);
241     static_assert(
242         internal::is_callable_r<const volatile void, Callable>::value);
243 
244     static_assert(!internal::is_callable_r<int, Callable>::value);
245     static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);
246   }
247 #endif  // _MSC_VER
248 
249   // Nothing should choke when we try to call other arguments besides directly
250   // callable objects, but they should not show up as callable.
251   static_assert(!internal::is_callable_r<void, int>::value, "");
252   static_assert(!internal::is_callable_r<void, void (C::*)()>::value, "");
253   static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, "");
254 }
255 
256 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
TEST(BuiltInDefaultValueTest,IsNullForPointerTypes)257 TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
258   EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr);
259   EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr);
260   EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr);
261 }
262 
263 // Tests that BuiltInDefaultValue<T*>::Exists() return true.
TEST(BuiltInDefaultValueTest,ExistsForPointerTypes)264 TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
265   EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
266   EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
267   EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
268 }
269 
270 // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
271 // built-in numeric type.
TEST(BuiltInDefaultValueTest,IsZeroForNumericTypes)272 TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
273   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
274   EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
275   EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
276 #if GMOCK_WCHAR_T_IS_NATIVE_
277 #if !defined(__WCHAR_UNSIGNED__)
278   EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
279 #else
280   EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
281 #endif
282 #endif
283   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get());  // NOLINT
284   EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get());     // NOLINT
285   EXPECT_EQ(0, BuiltInDefaultValue<short>::Get());            // NOLINT
286   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
287   EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
288   EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
289   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get());       // NOLINT
290   EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get());          // NOLINT
291   EXPECT_EQ(0, BuiltInDefaultValue<long>::Get());                 // NOLINT
292   EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get());  // NOLINT
293   EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get());     // NOLINT
294   EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get());            // NOLINT
295   EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
296   EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
297 }
298 
299 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
300 // built-in numeric type.
TEST(BuiltInDefaultValueTest,ExistsForNumericTypes)301 TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
302   EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
303   EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
304   EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
305 #if GMOCK_WCHAR_T_IS_NATIVE_
306   EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
307 #endif
308   EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists());  // NOLINT
309   EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists());    // NOLINT
310   EXPECT_TRUE(BuiltInDefaultValue<short>::Exists());           // NOLINT
311   EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
312   EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
313   EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
314   EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists());       // NOLINT
315   EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists());         // NOLINT
316   EXPECT_TRUE(BuiltInDefaultValue<long>::Exists());                // NOLINT
317   EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists());  // NOLINT
318   EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists());    // NOLINT
319   EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists());           // NOLINT
320   EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
321   EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
322 }
323 
324 // Tests that BuiltInDefaultValue<bool>::Get() returns false.
TEST(BuiltInDefaultValueTest,IsFalseForBool)325 TEST(BuiltInDefaultValueTest, IsFalseForBool) {
326   EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
327 }
328 
329 // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
TEST(BuiltInDefaultValueTest,BoolExists)330 TEST(BuiltInDefaultValueTest, BoolExists) {
331   EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
332 }
333 
334 // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
335 // string type.
TEST(BuiltInDefaultValueTest,IsEmptyStringForString)336 TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
337   EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get());
338 }
339 
340 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
341 // string type.
TEST(BuiltInDefaultValueTest,ExistsForString)342 TEST(BuiltInDefaultValueTest, ExistsForString) {
343   EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists());
344 }
345 
346 // Tests that BuiltInDefaultValue<const T>::Get() returns the same
347 // value as BuiltInDefaultValue<T>::Get() does.
TEST(BuiltInDefaultValueTest,WorksForConstTypes)348 TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
349   EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
350   EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
351   EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);
352   EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
353 }
354 
355 // A type that's default constructible.
356 class MyDefaultConstructible {
357  public:
MyDefaultConstructible()358   MyDefaultConstructible() : value_(42) {}
359 
value() const360   int value() const { return value_; }
361 
362  private:
363   int value_;
364 };
365 
366 // A type that's not default constructible.
367 class MyNonDefaultConstructible {
368  public:
369   // Does not have a default ctor.
MyNonDefaultConstructible(int a_value)370   explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
371 
value() const372   int value() const { return value_; }
373 
374  private:
375   int value_;
376 };
377 
TEST(BuiltInDefaultValueTest,ExistsForDefaultConstructibleType)378 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
379   EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
380 }
381 
TEST(BuiltInDefaultValueTest,IsDefaultConstructedForDefaultConstructibleType)382 TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
383   EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
384 }
385 
TEST(BuiltInDefaultValueTest,DoesNotExistForNonDefaultConstructibleType)386 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
387   EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
388 }
389 
390 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
TEST(BuiltInDefaultValueDeathTest,IsUndefinedForReferences)391 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
392   EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, "");
393   EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, "");
394 }
395 
TEST(BuiltInDefaultValueDeathTest,IsUndefinedForNonDefaultConstructibleType)396 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
397   EXPECT_DEATH_IF_SUPPORTED(
398       { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, "");
399 }
400 
401 // Tests that DefaultValue<T>::IsSet() is false initially.
TEST(DefaultValueTest,IsInitiallyUnset)402 TEST(DefaultValueTest, IsInitiallyUnset) {
403   EXPECT_FALSE(DefaultValue<int>::IsSet());
404   EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
405   EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
406 }
407 
408 // Tests that DefaultValue<T> can be set and then unset.
TEST(DefaultValueTest,CanBeSetAndUnset)409 TEST(DefaultValueTest, CanBeSetAndUnset) {
410   EXPECT_TRUE(DefaultValue<int>::Exists());
411   EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
412 
413   DefaultValue<int>::Set(1);
414   DefaultValue<const MyNonDefaultConstructible>::Set(
415       MyNonDefaultConstructible(42));
416 
417   EXPECT_EQ(1, DefaultValue<int>::Get());
418   EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
419 
420   EXPECT_TRUE(DefaultValue<int>::Exists());
421   EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
422 
423   DefaultValue<int>::Clear();
424   DefaultValue<const MyNonDefaultConstructible>::Clear();
425 
426   EXPECT_FALSE(DefaultValue<int>::IsSet());
427   EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
428 
429   EXPECT_TRUE(DefaultValue<int>::Exists());
430   EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
431 }
432 
433 // Tests that DefaultValue<T>::Get() returns the
434 // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
435 // false.
TEST(DefaultValueDeathTest,GetReturnsBuiltInDefaultValueWhenUnset)436 TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
437   EXPECT_FALSE(DefaultValue<int>::IsSet());
438   EXPECT_TRUE(DefaultValue<int>::Exists());
439   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
440   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
441 
442   EXPECT_EQ(0, DefaultValue<int>::Get());
443 
444   EXPECT_DEATH_IF_SUPPORTED(
445       { DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
446 }
447 
TEST(DefaultValueTest,GetWorksForMoveOnlyIfSet)448 TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
449   EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
450   EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
451   DefaultValue<std::unique_ptr<int>>::SetFactory(
452       [] { return std::make_unique<int>(42); });
453   EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
454   std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
455   EXPECT_EQ(42, *i);
456 }
457 
458 // Tests that DefaultValue<void>::Get() returns void.
TEST(DefaultValueTest,GetWorksForVoid)459 TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); }
460 
461 // Tests using DefaultValue with a reference type.
462 
463 // Tests that DefaultValue<T&>::IsSet() is false initially.
TEST(DefaultValueOfReferenceTest,IsInitiallyUnset)464 TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
465   EXPECT_FALSE(DefaultValue<int&>::IsSet());
466   EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
467   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
468 }
469 
470 // Tests that DefaultValue<T&>::Exists is false initially.
TEST(DefaultValueOfReferenceTest,IsInitiallyNotExisting)471 TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
472   EXPECT_FALSE(DefaultValue<int&>::Exists());
473   EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
474   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
475 }
476 
477 // Tests that DefaultValue<T&> can be set and then unset.
TEST(DefaultValueOfReferenceTest,CanBeSetAndUnset)478 TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
479   int n = 1;
480   DefaultValue<const int&>::Set(n);
481   MyNonDefaultConstructible x(42);
482   DefaultValue<MyNonDefaultConstructible&>::Set(x);
483 
484   EXPECT_TRUE(DefaultValue<const int&>::Exists());
485   EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
486 
487   EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
488   EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
489 
490   DefaultValue<const int&>::Clear();
491   DefaultValue<MyNonDefaultConstructible&>::Clear();
492 
493   EXPECT_FALSE(DefaultValue<const int&>::Exists());
494   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
495 
496   EXPECT_FALSE(DefaultValue<const int&>::IsSet());
497   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
498 }
499 
500 // Tests that DefaultValue<T&>::Get() returns the
501 // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
502 // false.
TEST(DefaultValueOfReferenceDeathTest,GetReturnsBuiltInDefaultValueWhenUnset)503 TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
504   EXPECT_FALSE(DefaultValue<int&>::IsSet());
505   EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
506 
507   EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
508   EXPECT_DEATH_IF_SUPPORTED(
509       { DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
510 }
511 
512 // Tests that ActionInterface can be implemented by defining the
513 // Perform method.
514 
515 typedef int MyGlobalFunction(bool, int);
516 
517 class MyActionImpl : public ActionInterface<MyGlobalFunction> {
518  public:
Perform(const std::tuple<bool,int> & args)519   int Perform(const std::tuple<bool, int>& args) override {
520     return std::get<0>(args) ? std::get<1>(args) : 0;
521   }
522 };
523 
TEST(ActionInterfaceTest,CanBeImplementedByDefiningPerform)524 TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
525   MyActionImpl my_action_impl;
526   (void)my_action_impl;
527 }
528 
TEST(ActionInterfaceTest,MakeAction)529 TEST(ActionInterfaceTest, MakeAction) {
530   Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
531 
532   // When exercising the Perform() method of Action<F>, we must pass
533   // it a tuple whose size and type are compatible with F's argument
534   // types.  For example, if F is int(), then Perform() takes a
535   // 0-tuple; if F is void(bool, int), then Perform() takes a
536   // std::tuple<bool, int>, and so on.
537   EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
538 }
539 
540 // Tests that Action<F> can be constructed from a pointer to
541 // ActionInterface<F>.
TEST(ActionTest,CanBeConstructedFromActionInterface)542 TEST(ActionTest, CanBeConstructedFromActionInterface) {
543   Action<MyGlobalFunction> action(new MyActionImpl);
544 }
545 
546 // Tests that Action<F> delegates actual work to ActionInterface<F>.
TEST(ActionTest,DelegatesWorkToActionInterface)547 TEST(ActionTest, DelegatesWorkToActionInterface) {
548   const Action<MyGlobalFunction> action(new MyActionImpl);
549 
550   EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
551   EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1)));
552 }
553 
554 // Tests that Action<F> can be copied.
TEST(ActionTest,IsCopyable)555 TEST(ActionTest, IsCopyable) {
556   Action<MyGlobalFunction> a1(new MyActionImpl);
557   Action<MyGlobalFunction> a2(a1);  // Tests the copy constructor.
558 
559   // a1 should continue to work after being copied from.
560   EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
561   EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
562 
563   // a2 should work like the action it was copied from.
564   EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
565   EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
566 
567   a2 = a1;  // Tests the assignment operator.
568 
569   // a1 should continue to work after being copied from.
570   EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
571   EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
572 
573   // a2 should work like the action it was copied from.
574   EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
575   EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
576 }
577 
578 // Tests that an Action<From> object can be converted to a
579 // compatible Action<To> object.
580 
581 class IsNotZero : public ActionInterface<bool(int)> {  // NOLINT
582  public:
Perform(const std::tuple<int> & arg)583   bool Perform(const std::tuple<int>& arg) override {
584     return std::get<0>(arg) != 0;
585   }
586 };
587 
TEST(ActionTest,CanBeConvertedToOtherActionType)588 TEST(ActionTest, CanBeConvertedToOtherActionType) {
589   const Action<bool(int)> a1(new IsNotZero);           // NOLINT
590   const Action<int(char)> a2 = Action<int(char)>(a1);  // NOLINT
591   EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));
592   EXPECT_EQ(0, a2.Perform(std::make_tuple('\0')));
593 }
594 
595 // The following two classes are for testing MakePolymorphicAction().
596 
597 // Implements a polymorphic action that returns the second of the
598 // arguments it receives.
599 class ReturnSecondArgumentAction {
600  public:
601   // We want to verify that MakePolymorphicAction() can work with a
602   // polymorphic action whose Perform() method template is either
603   // const or not.  This lets us verify the non-const case.
604   template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple & args)605   Result Perform(const ArgumentTuple& args) {
606     return std::get<1>(args);
607   }
608 };
609 
610 // Implements a polymorphic action that can be used in a nullary
611 // function to return 0.
612 class ReturnZeroFromNullaryFunctionAction {
613  public:
614   // For testing that MakePolymorphicAction() works when the
615   // implementation class' Perform() method template takes only one
616   // template parameter.
617   //
618   // We want to verify that MakePolymorphicAction() can work with a
619   // polymorphic action whose Perform() method template is either
620   // const or not.  This lets us verify the const case.
621   template <typename Result>
Perform(const std::tuple<> &) const622   Result Perform(const std::tuple<>&) const {
623     return 0;
624   }
625 };
626 
627 // These functions verify that MakePolymorphicAction() returns a
628 // PolymorphicAction<T> where T is the argument's type.
629 
ReturnSecondArgument()630 PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
631   return MakePolymorphicAction(ReturnSecondArgumentAction());
632 }
633 
634 PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
ReturnZeroFromNullaryFunction()635 ReturnZeroFromNullaryFunction() {
636   return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
637 }
638 
639 // Tests that MakePolymorphicAction() turns a polymorphic action
640 // implementation class into a polymorphic action.
TEST(MakePolymorphicActionTest,ConstructsActionFromImpl)641 TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
642   Action<int(bool, int, double)> a1 = ReturnSecondArgument();  // NOLINT
643   EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0)));
644 }
645 
646 // Tests that MakePolymorphicAction() works when the implementation
647 // class' Perform() method template has only one template parameter.
TEST(MakePolymorphicActionTest,WorksWhenPerformHasOneTemplateParameter)648 TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
649   Action<int()> a1 = ReturnZeroFromNullaryFunction();
650   EXPECT_EQ(0, a1.Perform(std::make_tuple()));
651 
652   Action<void*()> a2 = ReturnZeroFromNullaryFunction();
653   EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr);
654 }
655 
656 // Tests that Return() works as an action for void-returning
657 // functions.
TEST(ReturnTest,WorksForVoid)658 TEST(ReturnTest, WorksForVoid) {
659   const Action<void(int)> ret = Return();  // NOLINT
660   return ret.Perform(std::make_tuple(1));
661 }
662 
663 // Tests that Return(v) returns v.
TEST(ReturnTest,ReturnsGivenValue)664 TEST(ReturnTest, ReturnsGivenValue) {
665   Action<int()> ret = Return(1);  // NOLINT
666   EXPECT_EQ(1, ret.Perform(std::make_tuple()));
667 
668   ret = Return(-5);
669   EXPECT_EQ(-5, ret.Perform(std::make_tuple()));
670 }
671 
672 // Tests that Return("string literal") works.
TEST(ReturnTest,AcceptsStringLiteral)673 TEST(ReturnTest, AcceptsStringLiteral) {
674   Action<const char*()> a1 = Return("Hello");
675   EXPECT_STREQ("Hello", a1.Perform(std::make_tuple()));
676 
677   Action<std::string()> a2 = Return("world");
678   EXPECT_EQ("world", a2.Perform(std::make_tuple()));
679 }
680 
681 // Return(x) should work fine when the mock function's return type is a
682 // reference-like wrapper for decltype(x), as when x is a std::string and the
683 // mock function returns std::string_view.
TEST(ReturnTest,SupportsReferenceLikeReturnType)684 TEST(ReturnTest, SupportsReferenceLikeReturnType) {
685   // A reference wrapper for std::vector<int>, implicitly convertible from it.
686   struct Result {
687     const std::vector<int>* v;
688     Result(const std::vector<int>& vec) : v(&vec) {}  // NOLINT
689   };
690 
691   // Set up an action for a mock function that returns the reference wrapper
692   // type, initializing it with an actual vector.
693   //
694   // The returned wrapper should be initialized with a copy of that vector
695   // that's embedded within the action itself (which should stay alive as long
696   // as the mock object is alive), rather than e.g. a reference to the temporary
697   // we feed to Return. This should work fine both for WillOnce and
698   // WillRepeatedly.
699   MockFunction<Result()> mock;
700   EXPECT_CALL(mock, Call)
701       .WillOnce(Return(std::vector<int>{17, 19, 23}))
702       .WillRepeatedly(Return(std::vector<int>{29, 31, 37}));
703 
704   EXPECT_THAT(mock.AsStdFunction()(),
705               Field(&Result::v, Pointee(ElementsAre(17, 19, 23))));
706 
707   EXPECT_THAT(mock.AsStdFunction()(),
708               Field(&Result::v, Pointee(ElementsAre(29, 31, 37))));
709 }
710 
TEST(ReturnTest,PrefersConversionOperator)711 TEST(ReturnTest, PrefersConversionOperator) {
712   // Define types In and Out such that:
713   //
714   //  *  In is implicitly convertible to Out.
715   //  *  Out also has an explicit constructor from In.
716   //
717   struct In;
718   struct Out {
719     int x;
720 
721     explicit Out(const int val) : x(val) {}
722     explicit Out(const In&) : x(0) {}
723   };
724 
725   struct In {
726     operator Out() const { return Out{19}; }  // NOLINT
727   };
728 
729   // Assumption check: the C++ language rules are such that a function that
730   // returns Out which uses In a return statement will use the implicit
731   // conversion path rather than the explicit constructor.
732   EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19));
733 
734   // Return should work the same way: if the mock function's return type is Out
735   // and we feed Return an In value, then the Out should be created through the
736   // implicit conversion path rather than the explicit constructor.
737   MockFunction<Out()> mock;
738   EXPECT_CALL(mock, Call).WillOnce(Return(In()));
739   EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19));
740 }
741 
742 // It should be possible to use Return(R) with a mock function result type U
743 // that is convertible from const R& but *not* R (such as
744 // std::reference_wrapper). This should work for both WillOnce and
745 // WillRepeatedly.
TEST(ReturnTest,ConversionRequiresConstLvalueReference)746 TEST(ReturnTest, ConversionRequiresConstLvalueReference) {
747   using R = int;
748   using U = std::reference_wrapper<const int>;
749 
750   static_assert(std::is_convertible<const R&, U>::value, "");
751   static_assert(!std::is_convertible<R, U>::value, "");
752 
753   MockFunction<U()> mock;
754   EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19));
755 
756   EXPECT_EQ(17, mock.AsStdFunction()());
757   EXPECT_EQ(19, mock.AsStdFunction()());
758 }
759 
760 // Return(x) should not be usable with a mock function result type that's
761 // implicitly convertible from decltype(x) but requires a non-const lvalue
762 // reference to the input. It doesn't make sense for the conversion operator to
763 // modify the input.
TEST(ReturnTest,ConversionRequiresMutableLvalueReference)764 TEST(ReturnTest, ConversionRequiresMutableLvalueReference) {
765   // Set up a type that is implicitly convertible from std::string&, but not
766   // std::string&& or `const std::string&`.
767   //
768   // Avoid asserting about conversion from std::string on MSVC, which seems to
769   // implement std::is_convertible incorrectly in this case.
770   struct S {
771     S(std::string&) {}  // NOLINT
772   };
773 
774   static_assert(std::is_convertible<std::string&, S>::value, "");
775 #ifndef _MSC_VER
776   static_assert(!std::is_convertible<std::string&&, S>::value, "");
777 #endif
778   static_assert(!std::is_convertible<const std::string&, S>::value, "");
779 
780   // It shouldn't be possible to use the result of Return(std::string) in a
781   // context where an S is needed.
782   //
783   // Here too we disable the assertion for MSVC, since its incorrect
784   // implementation of is_convertible causes our SFINAE to be wrong.
785   using RA = decltype(Return(std::string()));
786 
787   static_assert(!std::is_convertible<RA, Action<S()>>::value, "");
788 #ifndef _MSC_VER
789   static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, "");
790 #endif
791 }
792 
TEST(ReturnTest,MoveOnlyResultType)793 TEST(ReturnTest, MoveOnlyResultType) {
794   // Return should support move-only result types when used with WillOnce.
795   {
796     MockFunction<std::unique_ptr<int>()> mock;
797     EXPECT_CALL(mock, Call)
798         // NOLINTNEXTLINE
799         .WillOnce(Return(std::unique_ptr<int>(new int(17))));
800 
801     EXPECT_THAT(mock.AsStdFunction()(), Pointee(17));
802   }
803 
804   // The result of Return should not be convertible to Action (so it can't be
805   // used with WillRepeatedly).
806   static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())),
807                                      Action<std::unique_ptr<int>()>>::value,
808                 "");
809 }
810 
811 // Tests that Return(v) is covariant.
812 
813 struct Base {
operator ==testing::__anon10e2b6f40111::Base814   bool operator==(const Base&) { return true; }
815 };
816 
817 struct Derived : public Base {
operator ==testing::__anon10e2b6f40111::Derived818   bool operator==(const Derived&) { return true; }
819 };
820 
TEST(ReturnTest,IsCovariant)821 TEST(ReturnTest, IsCovariant) {
822   Base base;
823   Derived derived;
824   Action<Base*()> ret = Return(&base);
825   EXPECT_EQ(&base, ret.Perform(std::make_tuple()));
826 
827   ret = Return(&derived);
828   EXPECT_EQ(&derived, ret.Perform(std::make_tuple()));
829 }
830 
831 // Tests that the type of the value passed into Return is converted into T
832 // when the action is cast to Action<T(...)> rather than when the action is
833 // performed. See comments on testing::internal::ReturnAction in
834 // gmock-actions.h for more information.
835 class FromType {
836  public:
FromType(bool * is_converted)837   explicit FromType(bool* is_converted) : converted_(is_converted) {}
converted() const838   bool* converted() const { return converted_; }
839 
840  private:
841   bool* const converted_;
842 };
843 
844 class ToType {
845  public:
846   // Must allow implicit conversion due to use in ImplicitCast_<T>.
ToType(const FromType & x)847   ToType(const FromType& x) { *x.converted() = true; }  // NOLINT
848 };
849 
TEST(ReturnTest,ConvertsArgumentWhenConverted)850 TEST(ReturnTest, ConvertsArgumentWhenConverted) {
851   bool converted = false;
852   FromType x(&converted);
853   Action<ToType()> action(Return(x));
854   EXPECT_TRUE(converted) << "Return must convert its argument in its own "
855                          << "conversion operator.";
856   converted = false;
857   action.Perform(std::tuple<>());
858   EXPECT_FALSE(converted) << "Action must NOT convert its argument "
859                           << "when performed.";
860 }
861 
862 // Tests that ReturnNull() returns NULL in a pointer-returning function.
TEST(ReturnNullTest,WorksInPointerReturningFunction)863 TEST(ReturnNullTest, WorksInPointerReturningFunction) {
864   const Action<int*()> a1 = ReturnNull();
865   EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
866 
867   const Action<const char*(bool)> a2 = ReturnNull();  // NOLINT
868   EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr);
869 }
870 
871 // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
872 // functions.
TEST(ReturnNullTest,WorksInSmartPointerReturningFunction)873 TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
874   const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
875   EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
876 
877   const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
878   EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr);
879 }
880 
881 // Tests that ReturnRef(v) works for reference types.
TEST(ReturnRefTest,WorksForReference)882 TEST(ReturnRefTest, WorksForReference) {
883   const int n = 0;
884   const Action<const int&(bool)> ret = ReturnRef(n);  // NOLINT
885 
886   EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true)));
887 }
888 
889 // Tests that ReturnRef(v) is covariant.
TEST(ReturnRefTest,IsCovariant)890 TEST(ReturnRefTest, IsCovariant) {
891   Base base;
892   Derived derived;
893   Action<Base&()> a = ReturnRef(base);
894   EXPECT_EQ(&base, &a.Perform(std::make_tuple()));
895 
896   a = ReturnRef(derived);
897   EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));
898 }
899 
900 template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
CanCallReturnRef(T &&)901 bool CanCallReturnRef(T&&) {
902   return true;
903 }
CanCallReturnRef(Unused)904 bool CanCallReturnRef(Unused) { return false; }
905 
906 // Tests that ReturnRef(v) is working with non-temporaries (T&)
TEST(ReturnRefTest,WorksForNonTemporary)907 TEST(ReturnRefTest, WorksForNonTemporary) {
908   int scalar_value = 123;
909   EXPECT_TRUE(CanCallReturnRef(scalar_value));
910 
911   std::string non_scalar_value("ABC");
912   EXPECT_TRUE(CanCallReturnRef(non_scalar_value));
913 
914   const int const_scalar_value{321};
915   EXPECT_TRUE(CanCallReturnRef(const_scalar_value));
916 
917   const std::string const_non_scalar_value("CBA");
918   EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value));
919 }
920 
921 // Tests that ReturnRef(v) is not working with temporaries (T&&)
TEST(ReturnRefTest,DoesNotWorkForTemporary)922 TEST(ReturnRefTest, DoesNotWorkForTemporary) {
923   auto scalar_value = []() -> int { return 123; };
924   EXPECT_FALSE(CanCallReturnRef(scalar_value()));
925 
926   auto non_scalar_value = []() -> std::string { return "ABC"; };
927   EXPECT_FALSE(CanCallReturnRef(non_scalar_value()));
928 
929   // cannot use here callable returning "const scalar type",
930   // because such const for scalar return type is ignored
931   EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321)));
932 
933   auto const_non_scalar_value = []() -> const std::string { return "CBA"; };
934   EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value()));
935 }
936 
937 // Tests that ReturnRefOfCopy(v) works for reference types.
TEST(ReturnRefOfCopyTest,WorksForReference)938 TEST(ReturnRefOfCopyTest, WorksForReference) {
939   int n = 42;
940   const Action<const int&()> ret = ReturnRefOfCopy(n);
941 
942   EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
943   EXPECT_EQ(42, ret.Perform(std::make_tuple()));
944 
945   n = 43;
946   EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
947   EXPECT_EQ(42, ret.Perform(std::make_tuple()));
948 }
949 
950 // Tests that ReturnRefOfCopy(v) is covariant.
TEST(ReturnRefOfCopyTest,IsCovariant)951 TEST(ReturnRefOfCopyTest, IsCovariant) {
952   Base base;
953   Derived derived;
954   Action<Base&()> a = ReturnRefOfCopy(base);
955   EXPECT_NE(&base, &a.Perform(std::make_tuple()));
956 
957   a = ReturnRefOfCopy(derived);
958   EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
959 }
960 
961 // Tests that ReturnRoundRobin(v) works with initializer lists
TEST(ReturnRoundRobinTest,WorksForInitList)962 TEST(ReturnRoundRobinTest, WorksForInitList) {
963   Action<int()> ret = ReturnRoundRobin({1, 2, 3});
964 
965   EXPECT_EQ(1, ret.Perform(std::make_tuple()));
966   EXPECT_EQ(2, ret.Perform(std::make_tuple()));
967   EXPECT_EQ(3, ret.Perform(std::make_tuple()));
968   EXPECT_EQ(1, ret.Perform(std::make_tuple()));
969   EXPECT_EQ(2, ret.Perform(std::make_tuple()));
970   EXPECT_EQ(3, ret.Perform(std::make_tuple()));
971 }
972 
973 // Tests that ReturnRoundRobin(v) works with vectors
TEST(ReturnRoundRobinTest,WorksForVector)974 TEST(ReturnRoundRobinTest, WorksForVector) {
975   std::vector<double> v = {4.4, 5.5, 6.6};
976   Action<double()> ret = ReturnRoundRobin(v);
977 
978   EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
979   EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
980   EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
981   EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
982   EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
983   EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
984 }
985 
986 // Tests that DoDefault() does the default action for the mock method.
987 
988 class MockClass {
989  public:
990   MockClass() = default;
991 
992   MOCK_METHOD1(IntFunc, int(bool flag));  // NOLINT
993   MOCK_METHOD0(Foo, MyNonDefaultConstructible());
994   MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
995   MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
996   MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
997   MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
998   MOCK_METHOD2(TakeUnique,
999                int(const std::unique_ptr<int>&, std::unique_ptr<int>));
1000 
1001  private:
1002   MockClass(const MockClass&) = delete;
1003   MockClass& operator=(const MockClass&) = delete;
1004 };
1005 
1006 // Tests that DoDefault() returns the built-in default value for the
1007 // return type by default.
TEST(DoDefaultTest,ReturnsBuiltInDefaultValueByDefault)1008 TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
1009   MockClass mock;
1010   EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
1011   EXPECT_EQ(0, mock.IntFunc(true));
1012 }
1013 
1014 // Tests that DoDefault() throws (when exceptions are enabled) or aborts
1015 // the process when there is no built-in default value for the return type.
TEST(DoDefaultDeathTest,DiesForUnknowType)1016 TEST(DoDefaultDeathTest, DiesForUnknowType) {
1017   MockClass mock;
1018   EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault());
1019 #if GTEST_HAS_EXCEPTIONS
1020   EXPECT_ANY_THROW(mock.Foo());
1021 #else
1022   EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, "");
1023 #endif
1024 }
1025 
1026 // Tests that using DoDefault() inside a composite action leads to a
1027 // run-time error.
1028 
VoidFunc(bool)1029 void VoidFunc(bool /* flag */) {}
1030 
TEST(DoDefaultDeathTest,DiesIfUsedInCompositeAction)1031 TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
1032   MockClass mock;
1033   EXPECT_CALL(mock, IntFunc(_))
1034       .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));
1035 
1036   // Ideally we should verify the error message as well.  Sadly,
1037   // EXPECT_DEATH() can only capture stderr, while Google Mock's
1038   // errors are printed on stdout.  Therefore we have to settle for
1039   // not verifying the message.
1040   EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, "");
1041 }
1042 
1043 // Tests that DoDefault() returns the default value set by
1044 // DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
TEST(DoDefaultTest,ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne)1045 TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
1046   DefaultValue<int>::Set(1);
1047   MockClass mock;
1048   EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
1049   EXPECT_EQ(1, mock.IntFunc(false));
1050   DefaultValue<int>::Clear();
1051 }
1052 
1053 // Tests that DoDefault() does the action specified by ON_CALL().
TEST(DoDefaultTest,DoesWhatOnCallSpecifies)1054 TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
1055   MockClass mock;
1056   ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2));
1057   EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
1058   EXPECT_EQ(2, mock.IntFunc(false));
1059 }
1060 
1061 // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
TEST(DoDefaultTest,CannotBeUsedInOnCall)1062 TEST(DoDefaultTest, CannotBeUsedInOnCall) {
1063   MockClass mock;
1064   EXPECT_NONFATAL_FAILURE(
1065       {  // NOLINT
1066         ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault());
1067       },
1068       "DoDefault() cannot be used in ON_CALL()");
1069 }
1070 
1071 // Tests that SetArgPointee<N>(v) sets the variable pointed to by
1072 // the N-th (0-based) argument to v.
TEST(SetArgPointeeTest,SetsTheNthPointee)1073 TEST(SetArgPointeeTest, SetsTheNthPointee) {
1074   typedef void MyFunction(bool, int*, char*);
1075   Action<MyFunction> a = SetArgPointee<1>(2);
1076 
1077   int n = 0;
1078   char ch = '\0';
1079   a.Perform(std::make_tuple(true, &n, &ch));
1080   EXPECT_EQ(2, n);
1081   EXPECT_EQ('\0', ch);
1082 
1083   a = SetArgPointee<2>('a');
1084   n = 0;
1085   ch = '\0';
1086   a.Perform(std::make_tuple(true, &n, &ch));
1087   EXPECT_EQ(0, n);
1088   EXPECT_EQ('a', ch);
1089 }
1090 
1091 // Tests that SetArgPointee<N>() accepts a string literal.
TEST(SetArgPointeeTest,AcceptsStringLiteral)1092 TEST(SetArgPointeeTest, AcceptsStringLiteral) {
1093   typedef void MyFunction(std::string*, const char**);
1094   Action<MyFunction> a = SetArgPointee<0>("hi");
1095   std::string str;
1096   const char* ptr = nullptr;
1097   a.Perform(std::make_tuple(&str, &ptr));
1098   EXPECT_EQ("hi", str);
1099   EXPECT_TRUE(ptr == nullptr);
1100 
1101   a = SetArgPointee<1>("world");
1102   str = "";
1103   a.Perform(std::make_tuple(&str, &ptr));
1104   EXPECT_EQ("", str);
1105   EXPECT_STREQ("world", ptr);
1106 }
1107 
TEST(SetArgPointeeTest,AcceptsWideStringLiteral)1108 TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
1109   typedef void MyFunction(const wchar_t**);
1110   Action<MyFunction> a = SetArgPointee<0>(L"world");
1111   const wchar_t* ptr = nullptr;
1112   a.Perform(std::make_tuple(&ptr));
1113   EXPECT_STREQ(L"world", ptr);
1114 
1115 #if GTEST_HAS_STD_WSTRING
1116 
1117   typedef void MyStringFunction(std::wstring*);
1118   Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
1119   std::wstring str = L"";
1120   a2.Perform(std::make_tuple(&str));
1121   EXPECT_EQ(L"world", str);
1122 
1123 #endif
1124 }
1125 
1126 // Tests that SetArgPointee<N>() accepts a char pointer.
TEST(SetArgPointeeTest,AcceptsCharPointer)1127 TEST(SetArgPointeeTest, AcceptsCharPointer) {
1128   typedef void MyFunction(bool, std::string*, const char**);
1129   const char* const hi = "hi";
1130   Action<MyFunction> a = SetArgPointee<1>(hi);
1131   std::string str;
1132   const char* ptr = nullptr;
1133   a.Perform(std::make_tuple(true, &str, &ptr));
1134   EXPECT_EQ("hi", str);
1135   EXPECT_TRUE(ptr == nullptr);
1136 
1137   char world_array[] = "world";
1138   char* const world = world_array;
1139   a = SetArgPointee<2>(world);
1140   str = "";
1141   a.Perform(std::make_tuple(true, &str, &ptr));
1142   EXPECT_EQ("", str);
1143   EXPECT_EQ(world, ptr);
1144 }
1145 
TEST(SetArgPointeeTest,AcceptsWideCharPointer)1146 TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
1147   typedef void MyFunction(bool, const wchar_t**);
1148   const wchar_t* const hi = L"hi";
1149   Action<MyFunction> a = SetArgPointee<1>(hi);
1150   const wchar_t* ptr = nullptr;
1151   a.Perform(std::make_tuple(true, &ptr));
1152   EXPECT_EQ(hi, ptr);
1153 
1154 #if GTEST_HAS_STD_WSTRING
1155 
1156   typedef void MyStringFunction(bool, std::wstring*);
1157   wchar_t world_array[] = L"world";
1158   wchar_t* const world = world_array;
1159   Action<MyStringFunction> a2 = SetArgPointee<1>(world);
1160   std::wstring str;
1161   a2.Perform(std::make_tuple(true, &str));
1162   EXPECT_EQ(world_array, str);
1163 #endif
1164 }
1165 
1166 // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
1167 // the N-th (0-based) argument to v.
TEST(SetArgumentPointeeTest,SetsTheNthPointee)1168 TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
1169   typedef void MyFunction(bool, int*, char*);
1170   Action<MyFunction> a = SetArgumentPointee<1>(2);
1171 
1172   int n = 0;
1173   char ch = '\0';
1174   a.Perform(std::make_tuple(true, &n, &ch));
1175   EXPECT_EQ(2, n);
1176   EXPECT_EQ('\0', ch);
1177 
1178   a = SetArgumentPointee<2>('a');
1179   n = 0;
1180   ch = '\0';
1181   a.Perform(std::make_tuple(true, &n, &ch));
1182   EXPECT_EQ(0, n);
1183   EXPECT_EQ('a', ch);
1184 }
1185 
1186 // Sample functions and functors for testing Invoke() and etc.
Nullary()1187 int Nullary() { return 1; }
1188 
1189 class NullaryFunctor {
1190  public:
operator ()()1191   int operator()() { return 2; }
1192 };
1193 
1194 bool g_done = false;
VoidNullary()1195 void VoidNullary() { g_done = true; }
1196 
1197 class VoidNullaryFunctor {
1198  public:
operator ()()1199   void operator()() { g_done = true; }
1200 };
1201 
Short(short n)1202 short Short(short n) { return n; }  // NOLINT
Char(char ch)1203 char Char(char ch) { return ch; }
1204 
CharPtr(const char * s)1205 const char* CharPtr(const char* s) { return s; }
1206 
Unary(int x)1207 bool Unary(int x) { return x < 0; }
1208 
Binary(const char * input,short n)1209 const char* Binary(const char* input, short n) { return input + n; }  // NOLINT
1210 
VoidBinary(int,char)1211 void VoidBinary(int, char) { g_done = true; }
1212 
Ternary(int x,char y,short z)1213 int Ternary(int x, char y, short z) { return x + y + z; }  // NOLINT
1214 
SumOf4(int a,int b,int c,int d)1215 int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
1216 
1217 class Foo {
1218  public:
Foo()1219   Foo() : value_(123) {}
1220 
Nullary() const1221   int Nullary() const { return value_; }
1222 
1223  private:
1224   int value_;
1225 };
1226 
1227 // Tests InvokeWithoutArgs(function).
TEST(InvokeWithoutArgsTest,Function)1228 TEST(InvokeWithoutArgsTest, Function) {
1229   // As an action that takes one argument.
1230   Action<int(int)> a = InvokeWithoutArgs(Nullary);  // NOLINT
1231   EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
1232 
1233   // As an action that takes two arguments.
1234   Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary);  // NOLINT
1235   EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5)));
1236 
1237   // As an action that returns void.
1238   Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary);  // NOLINT
1239   g_done = false;
1240   a3.Perform(std::make_tuple(1));
1241   EXPECT_TRUE(g_done);
1242 }
1243 
1244 // Tests InvokeWithoutArgs(functor).
TEST(InvokeWithoutArgsTest,Functor)1245 TEST(InvokeWithoutArgsTest, Functor) {
1246   // As an action that takes no argument.
1247   Action<int()> a = InvokeWithoutArgs(NullaryFunctor());  // NOLINT
1248   EXPECT_EQ(2, a.Perform(std::make_tuple()));
1249 
1250   // As an action that takes three arguments.
1251   Action<int(int, double, char)> a2 =  // NOLINT
1252       InvokeWithoutArgs(NullaryFunctor());
1253   EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a')));
1254 
1255   // As an action that returns void.
1256   Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
1257   g_done = false;
1258   a3.Perform(std::make_tuple());
1259   EXPECT_TRUE(g_done);
1260 }
1261 
1262 // Tests InvokeWithoutArgs(obj_ptr, method).
TEST(InvokeWithoutArgsTest,Method)1263 TEST(InvokeWithoutArgsTest, Method) {
1264   Foo foo;
1265   Action<int(bool, char)> a =  // NOLINT
1266       InvokeWithoutArgs(&foo, &Foo::Nullary);
1267   EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));
1268 }
1269 
1270 // Tests using IgnoreResult() on a polymorphic action.
TEST(IgnoreResultTest,PolymorphicAction)1271 TEST(IgnoreResultTest, PolymorphicAction) {
1272   Action<void(int)> a = IgnoreResult(Return(5));  // NOLINT
1273   a.Perform(std::make_tuple(1));
1274 }
1275 
1276 // Tests using IgnoreResult() on a monomorphic action.
1277 
ReturnOne()1278 int ReturnOne() {
1279   g_done = true;
1280   return 1;
1281 }
1282 
TEST(IgnoreResultTest,MonomorphicAction)1283 TEST(IgnoreResultTest, MonomorphicAction) {
1284   g_done = false;
1285   Action<void()> a = IgnoreResult(Invoke(ReturnOne));
1286   a.Perform(std::make_tuple());
1287   EXPECT_TRUE(g_done);
1288 }
1289 
1290 // Tests using IgnoreResult() on an action that returns a class type.
1291 
ReturnMyNonDefaultConstructible(double)1292 MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1293   g_done = true;
1294   return MyNonDefaultConstructible(42);
1295 }
1296 
TEST(IgnoreResultTest,ActionReturningClass)1297 TEST(IgnoreResultTest, ActionReturningClass) {
1298   g_done = false;
1299   Action<void(int)> a =
1300       IgnoreResult(Invoke(ReturnMyNonDefaultConstructible));  // NOLINT
1301   a.Perform(std::make_tuple(2));
1302   EXPECT_TRUE(g_done);
1303 }
1304 
TEST(AssignTest,Int)1305 TEST(AssignTest, Int) {
1306   int x = 0;
1307   Action<void(int)> a = Assign(&x, 5);
1308   a.Perform(std::make_tuple(0));
1309   EXPECT_EQ(5, x);
1310 }
1311 
TEST(AssignTest,String)1312 TEST(AssignTest, String) {
1313   ::std::string x;
1314   Action<void(void)> a = Assign(&x, "Hello, world");
1315   a.Perform(std::make_tuple());
1316   EXPECT_EQ("Hello, world", x);
1317 }
1318 
TEST(AssignTest,CompatibleTypes)1319 TEST(AssignTest, CompatibleTypes) {
1320   double x = 0;
1321   Action<void(int)> a = Assign(&x, 5);
1322   a.Perform(std::make_tuple(0));
1323   EXPECT_DOUBLE_EQ(5, x);
1324 }
1325 
1326 // DoAll should support &&-qualified actions when used with WillOnce.
TEST(DoAll,SupportsRefQualifiedActions)1327 TEST(DoAll, SupportsRefQualifiedActions) {
1328   struct InitialAction {
1329     void operator()(const int arg) && { EXPECT_EQ(17, arg); }
1330   };
1331 
1332   struct FinalAction {
1333     int operator()() && { return 19; }
1334   };
1335 
1336   MockFunction<int(int)> mock;
1337   EXPECT_CALL(mock, Call).WillOnce(DoAll(InitialAction{}, FinalAction{}));
1338   EXPECT_EQ(19, mock.AsStdFunction()(17));
1339 }
1340 
1341 // DoAll should never provide rvalue references to the initial actions. If the
1342 // mock action itself accepts an rvalue reference or a non-scalar object by
1343 // value then the final action should receive an rvalue reference, but initial
1344 // actions should receive only lvalue references.
TEST(DoAll,ProvidesLvalueReferencesToInitialActions)1345 TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {
1346   struct Obj {};
1347 
1348   // Mock action accepts by value: the initial action should be fed a const
1349   // lvalue reference, and the final action an rvalue reference.
1350   {
1351     struct InitialAction {
1352       void operator()(Obj&) const { FAIL() << "Unexpected call"; }
1353       void operator()(const Obj&) const {}
1354       void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
1355       void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
1356     };
1357 
1358     MockFunction<void(Obj)> mock;
1359     EXPECT_CALL(mock, Call)
1360         .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
1361         .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
1362 
1363     mock.AsStdFunction()(Obj{});
1364     mock.AsStdFunction()(Obj{});
1365   }
1366 
1367   // Mock action accepts by const lvalue reference: both actions should receive
1368   // a const lvalue reference.
1369   {
1370     struct InitialAction {
1371       void operator()(Obj&) const { FAIL() << "Unexpected call"; }
1372       void operator()(const Obj&) const {}
1373       void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
1374       void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
1375     };
1376 
1377     MockFunction<void(const Obj&)> mock;
1378     EXPECT_CALL(mock, Call)
1379         .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}))
1380         .WillRepeatedly(
1381             DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}));
1382 
1383     mock.AsStdFunction()(Obj{});
1384     mock.AsStdFunction()(Obj{});
1385   }
1386 
1387   // Mock action accepts by non-const lvalue reference: both actions should get
1388   // a non-const lvalue reference if they want them.
1389   {
1390     struct InitialAction {
1391       void operator()(Obj&) const {}
1392       void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
1393     };
1394 
1395     MockFunction<void(Obj&)> mock;
1396     EXPECT_CALL(mock, Call)
1397         .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}))
1398         .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));
1399 
1400     Obj obj;
1401     mock.AsStdFunction()(obj);
1402     mock.AsStdFunction()(obj);
1403   }
1404 
1405   // Mock action accepts by rvalue reference: the initial actions should receive
1406   // a non-const lvalue reference if it wants it, and the final action an rvalue
1407   // reference.
1408   {
1409     struct InitialAction {
1410       void operator()(Obj&) const {}
1411       void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
1412     };
1413 
1414     MockFunction<void(Obj&&)> mock;
1415     EXPECT_CALL(mock, Call)
1416         .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
1417         .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
1418 
1419     mock.AsStdFunction()(Obj{});
1420     mock.AsStdFunction()(Obj{});
1421   }
1422 
1423   // &&-qualified initial actions should also be allowed with WillOnce.
1424   {
1425     struct InitialAction {
1426       void operator()(Obj&) && {}
1427     };
1428 
1429     MockFunction<void(Obj&)> mock;
1430     EXPECT_CALL(mock, Call)
1431         .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));
1432 
1433     Obj obj;
1434     mock.AsStdFunction()(obj);
1435   }
1436 
1437   {
1438     struct InitialAction {
1439       void operator()(Obj&) && {}
1440     };
1441 
1442     MockFunction<void(Obj&&)> mock;
1443     EXPECT_CALL(mock, Call)
1444         .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
1445 
1446     mock.AsStdFunction()(Obj{});
1447   }
1448 }
1449 
1450 // DoAll should support being used with type-erased Action objects, both through
1451 // WillOnce and WillRepeatedly.
TEST(DoAll,SupportsTypeErasedActions)1452 TEST(DoAll, SupportsTypeErasedActions) {
1453   // With only type-erased actions.
1454   const Action<void()> initial_action = [] {};
1455   const Action<int()> final_action = [] { return 17; };
1456 
1457   MockFunction<int()> mock;
1458   EXPECT_CALL(mock, Call)
1459       .WillOnce(DoAll(initial_action, initial_action, final_action))
1460       .WillRepeatedly(DoAll(initial_action, initial_action, final_action));
1461 
1462   EXPECT_EQ(17, mock.AsStdFunction()());
1463 
1464   // With &&-qualified and move-only final action.
1465   {
1466     struct FinalAction {
1467       FinalAction() = default;
1468       FinalAction(FinalAction&&) = default;
1469 
1470       int operator()() && { return 17; }
1471     };
1472 
1473     EXPECT_CALL(mock, Call)
1474         .WillOnce(DoAll(initial_action, initial_action, FinalAction{}));
1475 
1476     EXPECT_EQ(17, mock.AsStdFunction()());
1477   }
1478 }
1479 
1480 // A DoAll action should be convertible to a OnceAction, even when its component
1481 // sub-actions are user-provided types that define only an Action conversion
1482 // operator. If they supposed being called more than once then they also support
1483 // being called at most once.
TEST(DoAll,ConvertibleToOnceActionWithUserProvidedActionConversion)1484 TEST(DoAll, ConvertibleToOnceActionWithUserProvidedActionConversion) {
1485   // Simplest case: only one sub-action.
1486   struct CustomFinal final {
1487     operator Action<int()>() {  // NOLINT
1488       return Return(17);
1489     }
1490 
1491     operator Action<int(int, char)>() {  // NOLINT
1492       return Return(19);
1493     }
1494   };
1495 
1496   {
1497     OnceAction<int()> action = DoAll(CustomFinal{});
1498     EXPECT_EQ(17, std::move(action).Call());
1499   }
1500 
1501   {
1502     OnceAction<int(int, char)> action = DoAll(CustomFinal{});
1503     EXPECT_EQ(19, std::move(action).Call(0, 0));
1504   }
1505 
1506   // It should also work with multiple sub-actions.
1507   struct CustomInitial final {
1508     operator Action<void()>() {  // NOLINT
1509       return [] {};
1510     }
1511 
1512     operator Action<void(int, char)>() {  // NOLINT
1513       return [] {};
1514     }
1515   };
1516 
1517   {
1518     OnceAction<int()> action = DoAll(CustomInitial{}, CustomFinal{});
1519     EXPECT_EQ(17, std::move(action).Call());
1520   }
1521 
1522   {
1523     OnceAction<int(int, char)> action = DoAll(CustomInitial{}, CustomFinal{});
1524     EXPECT_EQ(19, std::move(action).Call(0, 0));
1525   }
1526 }
1527 
1528 // Tests using WithArgs and with an action that takes 1 argument.
TEST(WithArgsTest,OneArg)1529 TEST(WithArgsTest, OneArg) {
1530   Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary));  // NOLINT
1531   EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));
1532   EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));
1533 }
1534 
1535 // Tests using WithArgs with an action that takes 2 arguments.
TEST(WithArgsTest,TwoArgs)1536 TEST(WithArgsTest, TwoArgs) {
1537   Action<const char*(const char* s, double x, short n)> a =  // NOLINT
1538       WithArgs<0, 2>(Invoke(Binary));
1539   const char s[] = "Hello";
1540   EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
1541 }
1542 
1543 struct ConcatAll {
operator ()testing::__anon10e2b6f40111::ConcatAll1544   std::string operator()() const { return {}; }
1545   template <typename... I>
operator ()testing::__anon10e2b6f40111::ConcatAll1546   std::string operator()(const char* a, I... i) const {
1547     return a + ConcatAll()(i...);
1548   }
1549 };
1550 
1551 // Tests using WithArgs with an action that takes 10 arguments.
TEST(WithArgsTest,TenArgs)1552 TEST(WithArgsTest, TenArgs) {
1553   Action<std::string(const char*, const char*, const char*, const char*)> a =
1554       WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
1555   EXPECT_EQ("0123210123",
1556             a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
1557                                       CharPtr("3"))));
1558 }
1559 
1560 // Tests using WithArgs with an action that is not Invoke().
1561 class SubtractAction : public ActionInterface<int(int, int)> {
1562  public:
Perform(const std::tuple<int,int> & args)1563   int Perform(const std::tuple<int, int>& args) override {
1564     return std::get<0>(args) - std::get<1>(args);
1565   }
1566 };
1567 
TEST(WithArgsTest,NonInvokeAction)1568 TEST(WithArgsTest, NonInvokeAction) {
1569   Action<int(const std::string&, int, int)> a =
1570       WithArgs<2, 1>(MakeAction(new SubtractAction));
1571   std::tuple<std::string, int, int> dummy =
1572       std::make_tuple(std::string("hi"), 2, 10);
1573   EXPECT_EQ(8, a.Perform(dummy));
1574 }
1575 
1576 // Tests using WithArgs to pass all original arguments in the original order.
TEST(WithArgsTest,Identity)1577 TEST(WithArgsTest, Identity) {
1578   Action<int(int x, char y, short z)> a =  // NOLINT
1579       WithArgs<0, 1, 2>(Invoke(Ternary));
1580   EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));
1581 }
1582 
1583 // Tests using WithArgs with repeated arguments.
TEST(WithArgsTest,RepeatedArguments)1584 TEST(WithArgsTest, RepeatedArguments) {
1585   Action<int(bool, int m, int n)> a =  // NOLINT
1586       WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
1587   EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));
1588 }
1589 
1590 // Tests using WithArgs with reversed argument order.
TEST(WithArgsTest,ReversedArgumentOrder)1591 TEST(WithArgsTest, ReversedArgumentOrder) {
1592   Action<const char*(short n, const char* input)> a =  // NOLINT
1593       WithArgs<1, 0>(Invoke(Binary));
1594   const char s[] = "Hello";
1595   EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));
1596 }
1597 
1598 // Tests using WithArgs with compatible, but not identical, argument types.
TEST(WithArgsTest,ArgsOfCompatibleTypes)1599 TEST(WithArgsTest, ArgsOfCompatibleTypes) {
1600   Action<long(short x, char y, double z, char c)> a =  // NOLINT
1601       WithArgs<0, 1, 3>(Invoke(Ternary));
1602   EXPECT_EQ(123,
1603             a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));
1604 }
1605 
1606 // Tests using WithArgs with an action that returns void.
TEST(WithArgsTest,VoidAction)1607 TEST(WithArgsTest, VoidAction) {
1608   Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
1609   g_done = false;
1610   a.Perform(std::make_tuple(1.5, 'a', 3));
1611   EXPECT_TRUE(g_done);
1612 }
1613 
TEST(WithArgsTest,ReturnReference)1614 TEST(WithArgsTest, ReturnReference) {
1615   Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });
1616   int i = 0;
1617   const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));
1618   EXPECT_EQ(&i, &res);
1619 }
1620 
TEST(WithArgsTest,InnerActionWithConversion)1621 TEST(WithArgsTest, InnerActionWithConversion) {
1622   Action<Derived*()> inner = [] { return nullptr; };
1623 
1624   MockFunction<Base*(double)> mock;
1625   EXPECT_CALL(mock, Call)
1626       .WillOnce(WithoutArgs(inner))
1627       .WillRepeatedly(WithoutArgs(inner));
1628 
1629   EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
1630   EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
1631 }
1632 
1633 // It should be possible to use an &&-qualified inner action as long as the
1634 // whole shebang is used as an rvalue with WillOnce.
TEST(WithArgsTest,RefQualifiedInnerAction)1635 TEST(WithArgsTest, RefQualifiedInnerAction) {
1636   struct SomeAction {
1637     int operator()(const int arg) && {
1638       EXPECT_EQ(17, arg);
1639       return 19;
1640     }
1641   };
1642 
1643   MockFunction<int(int, int)> mock;
1644   EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{}));
1645   EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
1646 }
1647 
1648 // It should be fine to provide an lvalue WithArgsAction to WillOnce, even when
1649 // the inner action only wants to convert to OnceAction.
TEST(WithArgsTest,ProvideAsLvalueToWillOnce)1650 TEST(WithArgsTest, ProvideAsLvalueToWillOnce) {
1651   struct SomeAction {
1652     operator OnceAction<int(int)>() const {  // NOLINT
1653       return [](const int arg) { return arg + 2; };
1654     }
1655   };
1656 
1657   const auto wa = WithArg<1>(SomeAction{});
1658 
1659   MockFunction<int(int, int)> mock;
1660   EXPECT_CALL(mock, Call).WillOnce(wa);
1661   EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
1662 }
1663 
1664 #ifndef GTEST_OS_WINDOWS_MOBILE
1665 
1666 class SetErrnoAndReturnTest : public testing::Test {
1667  protected:
SetUp()1668   void SetUp() override { errno = 0; }
TearDown()1669   void TearDown() override { errno = 0; }
1670 };
1671 
TEST_F(SetErrnoAndReturnTest,Int)1672 TEST_F(SetErrnoAndReturnTest, Int) {
1673   Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
1674   EXPECT_EQ(-5, a.Perform(std::make_tuple()));
1675   EXPECT_EQ(ENOTTY, errno);
1676 }
1677 
TEST_F(SetErrnoAndReturnTest,Ptr)1678 TEST_F(SetErrnoAndReturnTest, Ptr) {
1679   int x;
1680   Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
1681   EXPECT_EQ(&x, a.Perform(std::make_tuple()));
1682   EXPECT_EQ(ENOTTY, errno);
1683 }
1684 
TEST_F(SetErrnoAndReturnTest,CompatibleTypes)1685 TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
1686   Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
1687   EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));
1688   EXPECT_EQ(EINVAL, errno);
1689 }
1690 
1691 #endif  // !GTEST_OS_WINDOWS_MOBILE
1692 
1693 // Tests ByRef().
1694 
1695 // Tests that the result of ByRef() is copyable.
TEST(ByRefTest,IsCopyable)1696 TEST(ByRefTest, IsCopyable) {
1697   const std::string s1 = "Hi";
1698   const std::string s2 = "Hello";
1699 
1700   auto ref_wrapper = ByRef(s1);
1701   const std::string& r1 = ref_wrapper;
1702   EXPECT_EQ(&s1, &r1);
1703 
1704   // Assigns a new value to ref_wrapper.
1705   ref_wrapper = ByRef(s2);
1706   const std::string& r2 = ref_wrapper;
1707   EXPECT_EQ(&s2, &r2);
1708 
1709   auto ref_wrapper1 = ByRef(s1);
1710   // Copies ref_wrapper1 to ref_wrapper.
1711   ref_wrapper = ref_wrapper1;
1712   const std::string& r3 = ref_wrapper;
1713   EXPECT_EQ(&s1, &r3);
1714 }
1715 
1716 // Tests using ByRef() on a const value.
TEST(ByRefTest,ConstValue)1717 TEST(ByRefTest, ConstValue) {
1718   const int n = 0;
1719   // int& ref = ByRef(n);  // This shouldn't compile - we have a
1720   // negative compilation test to catch it.
1721   const int& const_ref = ByRef(n);
1722   EXPECT_EQ(&n, &const_ref);
1723 }
1724 
1725 // Tests using ByRef() on a non-const value.
TEST(ByRefTest,NonConstValue)1726 TEST(ByRefTest, NonConstValue) {
1727   int n = 0;
1728 
1729   // ByRef(n) can be used as either an int&,
1730   int& ref = ByRef(n);
1731   EXPECT_EQ(&n, &ref);
1732 
1733   // or a const int&.
1734   const int& const_ref = ByRef(n);
1735   EXPECT_EQ(&n, &const_ref);
1736 }
1737 
1738 // Tests explicitly specifying the type when using ByRef().
TEST(ByRefTest,ExplicitType)1739 TEST(ByRefTest, ExplicitType) {
1740   int n = 0;
1741   const int& r1 = ByRef<const int>(n);
1742   EXPECT_EQ(&n, &r1);
1743 
1744   // ByRef<char>(n);  // This shouldn't compile - we have a negative
1745   // compilation test to catch it.
1746 
1747   Derived d;
1748   Derived& r2 = ByRef<Derived>(d);
1749   EXPECT_EQ(&d, &r2);
1750 
1751   const Derived& r3 = ByRef<const Derived>(d);
1752   EXPECT_EQ(&d, &r3);
1753 
1754   Base& r4 = ByRef<Base>(d);
1755   EXPECT_EQ(&d, &r4);
1756 
1757   const Base& r5 = ByRef<const Base>(d);
1758   EXPECT_EQ(&d, &r5);
1759 
1760   // The following shouldn't compile - we have a negative compilation
1761   // test for it.
1762   //
1763   // Base b;
1764   // ByRef<Derived>(b);
1765 }
1766 
1767 // Tests that Google Mock prints expression ByRef(x) as a reference to x.
TEST(ByRefTest,PrintsCorrectly)1768 TEST(ByRefTest, PrintsCorrectly) {
1769   int n = 42;
1770   ::std::stringstream expected, actual;
1771   testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
1772   testing::internal::UniversalPrint(ByRef(n), &actual);
1773   EXPECT_EQ(expected.str(), actual.str());
1774 }
1775 
1776 struct UnaryConstructorClass {
UnaryConstructorClasstesting::__anon10e2b6f40111::UnaryConstructorClass1777   explicit UnaryConstructorClass(int v) : value(v) {}
1778   int value;
1779 };
1780 
1781 // Tests using ReturnNew() with a unary constructor.
TEST(ReturnNewTest,Unary)1782 TEST(ReturnNewTest, Unary) {
1783   Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
1784   UnaryConstructorClass* c = a.Perform(std::make_tuple());
1785   EXPECT_EQ(4000, c->value);
1786   delete c;
1787 }
1788 
TEST(ReturnNewTest,UnaryWorksWhenMockMethodHasArgs)1789 TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
1790   Action<UnaryConstructorClass*(bool, int)> a =
1791       ReturnNew<UnaryConstructorClass>(4000);
1792   UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
1793   EXPECT_EQ(4000, c->value);
1794   delete c;
1795 }
1796 
TEST(ReturnNewTest,UnaryWorksWhenMockMethodReturnsPointerToConst)1797 TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
1798   Action<const UnaryConstructorClass*()> a =
1799       ReturnNew<UnaryConstructorClass>(4000);
1800   const UnaryConstructorClass* c = a.Perform(std::make_tuple());
1801   EXPECT_EQ(4000, c->value);
1802   delete c;
1803 }
1804 
1805 class TenArgConstructorClass {
1806  public:
TenArgConstructorClass(int a1,int a2,int a3,int a4,int a5,int a6,int a7,int a8,int a9,int a10)1807   TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
1808                          int a8, int a9, int a10)
1809       : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
1810   int value_;
1811 };
1812 
1813 // Tests using ReturnNew() with a 10-argument constructor.
TEST(ReturnNewTest,ConstructorThatTakes10Arguments)1814 TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
1815   Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(
1816       1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,
1817       0);
1818   TenArgConstructorClass* c = a.Perform(std::make_tuple());
1819   EXPECT_EQ(1234567890, c->value_);
1820   delete c;
1821 }
1822 
UniquePtrSource()1823 std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); }
1824 
VectorUniquePtrSource()1825 std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
1826   std::vector<std::unique_ptr<int>> out;
1827   out.emplace_back(new int(7));
1828   return out;
1829 }
1830 
TEST(MockMethodTest,CanReturnMoveOnlyValue_Return)1831 TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
1832   MockClass mock;
1833   std::unique_ptr<int> i(new int(19));
1834   EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
1835   EXPECT_CALL(mock, MakeVectorUnique())
1836       .WillOnce(Return(ByMove(VectorUniquePtrSource())));
1837   Derived* d = new Derived;
1838   EXPECT_CALL(mock, MakeUniqueBase())
1839       .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
1840 
1841   std::unique_ptr<int> result1 = mock.MakeUnique();
1842   EXPECT_EQ(19, *result1);
1843 
1844   std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1845   EXPECT_EQ(1u, vresult.size());
1846   EXPECT_NE(nullptr, vresult[0]);
1847   EXPECT_EQ(7, *vresult[0]);
1848 
1849   std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
1850   EXPECT_EQ(d, result2.get());
1851 }
1852 
TEST(MockMethodTest,CanReturnMoveOnlyValue_DoAllReturn)1853 TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
1854   testing::MockFunction<void()> mock_function;
1855   MockClass mock;
1856   std::unique_ptr<int> i(new int(19));
1857   EXPECT_CALL(mock_function, Call());
1858   EXPECT_CALL(mock, MakeUnique())
1859       .WillOnce(DoAll(InvokeWithoutArgs(&mock_function,
1860                                         &testing::MockFunction<void()>::Call),
1861                       Return(ByMove(std::move(i)))));
1862 
1863   std::unique_ptr<int> result1 = mock.MakeUnique();
1864   EXPECT_EQ(19, *result1);
1865 }
1866 
TEST(MockMethodTest,CanReturnMoveOnlyValue_Invoke)1867 TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1868   MockClass mock;
1869 
1870   // Check default value
1871   DefaultValue<std::unique_ptr<int>>::SetFactory(
1872       [] { return std::make_unique<int>(42); });
1873   EXPECT_EQ(42, *mock.MakeUnique());
1874 
1875   EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
1876   EXPECT_CALL(mock, MakeVectorUnique())
1877       .WillRepeatedly(Invoke(VectorUniquePtrSource));
1878   std::unique_ptr<int> result1 = mock.MakeUnique();
1879   EXPECT_EQ(19, *result1);
1880   std::unique_ptr<int> result2 = mock.MakeUnique();
1881   EXPECT_EQ(19, *result2);
1882   EXPECT_NE(result1, result2);
1883 
1884   std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1885   EXPECT_EQ(1u, vresult.size());
1886   EXPECT_NE(nullptr, vresult[0]);
1887   EXPECT_EQ(7, *vresult[0]);
1888 }
1889 
TEST(MockMethodTest,CanTakeMoveOnlyValue)1890 TEST(MockMethodTest, CanTakeMoveOnlyValue) {
1891   MockClass mock;
1892   auto make = [](int i) { return std::make_unique<int>(i); };
1893 
1894   EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
1895     return *i;
1896   });
1897   // DoAll() does not compile, since it would move from its arguments twice.
1898   // EXPECT_CALL(mock, TakeUnique(_, _))
1899   //     .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
1900   //     Return(1)));
1901   EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
1902       .WillOnce(Return(-7))
1903       .RetiresOnSaturation();
1904   EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
1905       .WillOnce(Return(-1))
1906       .RetiresOnSaturation();
1907 
1908   EXPECT_EQ(5, mock.TakeUnique(make(5)));
1909   EXPECT_EQ(-7, mock.TakeUnique(make(7)));
1910   EXPECT_EQ(7, mock.TakeUnique(make(7)));
1911   EXPECT_EQ(7, mock.TakeUnique(make(7)));
1912   EXPECT_EQ(-1, mock.TakeUnique({}));
1913 
1914   // Some arguments are moved, some passed by reference.
1915   auto lvalue = make(6);
1916   EXPECT_CALL(mock, TakeUnique(_, _))
1917       .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
1918         return *i * *j;
1919       });
1920   EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
1921 
1922   // The unique_ptr can be saved by the action.
1923   std::unique_ptr<int> saved;
1924   EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
1925     saved = std::move(i);
1926     return 0;
1927   });
1928   EXPECT_EQ(0, mock.TakeUnique(make(42)));
1929   EXPECT_EQ(42, *saved);
1930 }
1931 
1932 // It should be possible to use callables with an &&-qualified call operator
1933 // with WillOnce, since they will be called only once. This allows actions to
1934 // contain and manipulate move-only types.
TEST(MockMethodTest,ActionHasRvalueRefQualifiedCallOperator)1935 TEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) {
1936   struct Return17 {
1937     int operator()() && { return 17; }
1938   };
1939 
1940   // Action is directly compatible with mocked function type.
1941   {
1942     MockFunction<int()> mock;
1943     EXPECT_CALL(mock, Call).WillOnce(Return17());
1944 
1945     EXPECT_EQ(17, mock.AsStdFunction()());
1946   }
1947 
1948   // Action doesn't want mocked function arguments.
1949   {
1950     MockFunction<int(int)> mock;
1951     EXPECT_CALL(mock, Call).WillOnce(Return17());
1952 
1953     EXPECT_EQ(17, mock.AsStdFunction()(0));
1954   }
1955 }
1956 
1957 // Edge case: if an action has both a const-qualified and an &&-qualified call
1958 // operator, there should be no "ambiguous call" errors. The &&-qualified
1959 // operator should be used by WillOnce (since it doesn't need to retain the
1960 // action beyond one call), and the const-qualified one by WillRepeatedly.
TEST(MockMethodTest,ActionHasMultipleCallOperators)1961 TEST(MockMethodTest, ActionHasMultipleCallOperators) {
1962   struct ReturnInt {
1963     int operator()() && { return 17; }
1964     int operator()() const& { return 19; }
1965   };
1966 
1967   // Directly compatible with mocked function type.
1968   {
1969     MockFunction<int()> mock;
1970     EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
1971 
1972     EXPECT_EQ(17, mock.AsStdFunction()());
1973     EXPECT_EQ(19, mock.AsStdFunction()());
1974     EXPECT_EQ(19, mock.AsStdFunction()());
1975   }
1976 
1977   // Ignores function arguments.
1978   {
1979     MockFunction<int(int)> mock;
1980     EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
1981 
1982     EXPECT_EQ(17, mock.AsStdFunction()(0));
1983     EXPECT_EQ(19, mock.AsStdFunction()(0));
1984     EXPECT_EQ(19, mock.AsStdFunction()(0));
1985   }
1986 }
1987 
1988 // WillOnce should have no problem coping with a move-only action, whether it is
1989 // &&-qualified or not.
TEST(MockMethodTest,MoveOnlyAction)1990 TEST(MockMethodTest, MoveOnlyAction) {
1991   // &&-qualified
1992   {
1993     struct Return17 {
1994       Return17() = default;
1995       Return17(Return17&&) = default;
1996 
1997       Return17(const Return17&) = delete;
1998       Return17 operator=(const Return17&) = delete;
1999 
2000       int operator()() && { return 17; }
2001     };
2002 
2003     MockFunction<int()> mock;
2004     EXPECT_CALL(mock, Call).WillOnce(Return17());
2005     EXPECT_EQ(17, mock.AsStdFunction()());
2006   }
2007 
2008   // Not &&-qualified
2009   {
2010     struct Return17 {
2011       Return17() = default;
2012       Return17(Return17&&) = default;
2013 
2014       Return17(const Return17&) = delete;
2015       Return17 operator=(const Return17&) = delete;
2016 
2017       int operator()() const { return 17; }
2018     };
2019 
2020     MockFunction<int()> mock;
2021     EXPECT_CALL(mock, Call).WillOnce(Return17());
2022     EXPECT_EQ(17, mock.AsStdFunction()());
2023   }
2024 }
2025 
2026 // It should be possible to use an action that returns a value with a mock
2027 // function that doesn't, both through WillOnce and WillRepeatedly.
TEST(MockMethodTest,ActionReturnsIgnoredValue)2028 TEST(MockMethodTest, ActionReturnsIgnoredValue) {
2029   struct ReturnInt {
2030     int operator()() const { return 0; }
2031   };
2032 
2033   MockFunction<void()> mock;
2034   EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
2035 
2036   mock.AsStdFunction()();
2037   mock.AsStdFunction()();
2038 }
2039 
2040 // Despite the fanciness around move-only actions and so on, it should still be
2041 // possible to hand an lvalue reference to a copyable action to WillOnce.
TEST(MockMethodTest,WillOnceCanAcceptLvalueReference)2042 TEST(MockMethodTest, WillOnceCanAcceptLvalueReference) {
2043   MockFunction<int()> mock;
2044 
2045   const auto action = [] { return 17; };
2046   EXPECT_CALL(mock, Call).WillOnce(action);
2047 
2048   EXPECT_EQ(17, mock.AsStdFunction()());
2049 }
2050 
2051 // A callable that doesn't use SFINAE to restrict its call operator's overload
2052 // set, but is still picky about which arguments it will accept.
2053 struct StaticAssertSingleArgument {
2054   template <typename... Args>
CheckArgstesting::__anon10e2b6f40111::StaticAssertSingleArgument2055   static constexpr bool CheckArgs() {
2056     static_assert(sizeof...(Args) == 1, "");
2057     return true;
2058   }
2059 
2060   template <typename... Args, bool = CheckArgs<Args...>()>
operator ()testing::__anon10e2b6f40111::StaticAssertSingleArgument2061   int operator()(Args...) const {
2062     return 17;
2063   }
2064 };
2065 
2066 // WillOnce and WillRepeatedly should both work fine with naïve implementations
2067 // of actions that don't use SFINAE to limit the overload set for their call
2068 // operator. If they are compatible with the actual mocked signature, we
2069 // shouldn't probe them with no arguments and trip a static_assert.
TEST(MockMethodTest,ActionSwallowsAllArguments)2070 TEST(MockMethodTest, ActionSwallowsAllArguments) {
2071   MockFunction<int(int)> mock;
2072   EXPECT_CALL(mock, Call)
2073       .WillOnce(StaticAssertSingleArgument{})
2074       .WillRepeatedly(StaticAssertSingleArgument{});
2075 
2076   EXPECT_EQ(17, mock.AsStdFunction()(0));
2077   EXPECT_EQ(17, mock.AsStdFunction()(0));
2078 }
2079 
2080 struct ActionWithTemplatedConversionOperators {
2081   template <typename... Args>
operator OnceAction<int(Args...)>testing::__anon10e2b6f40111::ActionWithTemplatedConversionOperators2082   operator OnceAction<int(Args...)>() && {  // NOLINT
2083     return [] { return 17; };
2084   }
2085 
2086   template <typename... Args>
operator Action<int(Args...)>testing::__anon10e2b6f40111::ActionWithTemplatedConversionOperators2087   operator Action<int(Args...)>() const {  // NOLINT
2088     return [] { return 19; };
2089   }
2090 };
2091 
2092 // It should be fine to hand both WillOnce and WillRepeatedly a function that
2093 // defines templated conversion operators to OnceAction and Action. WillOnce
2094 // should prefer the OnceAction version.
TEST(MockMethodTest,ActionHasTemplatedConversionOperators)2095 TEST(MockMethodTest, ActionHasTemplatedConversionOperators) {
2096   MockFunction<int()> mock;
2097   EXPECT_CALL(mock, Call)
2098       .WillOnce(ActionWithTemplatedConversionOperators{})
2099       .WillRepeatedly(ActionWithTemplatedConversionOperators{});
2100 
2101   EXPECT_EQ(17, mock.AsStdFunction()());
2102   EXPECT_EQ(19, mock.AsStdFunction()());
2103 }
2104 
2105 // Tests for std::function based action.
2106 
Add(int val,int & ref,int * ptr)2107 int Add(int val, int& ref, int* ptr) {  // NOLINT
2108   int result = val + ref + *ptr;
2109   ref = 42;
2110   *ptr = 43;
2111   return result;
2112 }
2113 
Deref(std::unique_ptr<int> ptr)2114 int Deref(std::unique_ptr<int> ptr) { return *ptr; }
2115 
2116 struct Double {
2117   template <typename T>
operator ()testing::__anon10e2b6f40111::Double2118   T operator()(T t) {
2119     return 2 * t;
2120   }
2121 };
2122 
UniqueInt(int i)2123 std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); }
2124 
TEST(FunctorActionTest,ActionFromFunction)2125 TEST(FunctorActionTest, ActionFromFunction) {
2126   Action<int(int, int&, int*)> a = &Add;
2127   int x = 1, y = 2, z = 3;
2128   EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
2129   EXPECT_EQ(42, y);
2130   EXPECT_EQ(43, z);
2131 
2132   Action<int(std::unique_ptr<int>)> a1 = &Deref;
2133   EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
2134 }
2135 
TEST(FunctorActionTest,ActionFromLambda)2136 TEST(FunctorActionTest, ActionFromLambda) {
2137   Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
2138   EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
2139   EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5)));
2140 
2141   std::unique_ptr<int> saved;
2142   Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {
2143     saved = std::move(p);
2144   };
2145   a2.Perform(std::make_tuple(UniqueInt(5)));
2146   EXPECT_EQ(5, *saved);
2147 }
2148 
TEST(FunctorActionTest,PolymorphicFunctor)2149 TEST(FunctorActionTest, PolymorphicFunctor) {
2150   Action<int(int)> ai = Double();
2151   EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));
2152   Action<double(double)> ad = Double();  // Double? Double double!
2153   EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5)));
2154 }
2155 
TEST(FunctorActionTest,TypeConversion)2156 TEST(FunctorActionTest, TypeConversion) {
2157   // Numeric promotions are allowed.
2158   const Action<bool(int)> a1 = [](int i) { return i > 1; };
2159   const Action<int(bool)> a2 = Action<int(bool)>(a1);
2160   EXPECT_EQ(1, a1.Perform(std::make_tuple(42)));
2161   EXPECT_EQ(0, a2.Perform(std::make_tuple(42)));
2162 
2163   // Implicit constructors are allowed.
2164   const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };
2165   const Action<int(const char*)> s2 = Action<int(const char*)>(s1);
2166   EXPECT_EQ(0, s2.Perform(std::make_tuple("")));
2167   EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
2168 
2169   // Also between the lambda and the action itself.
2170   const Action<bool(std::string)> x1 = [](Unused) { return 42; };
2171   const Action<bool(std::string)> x2 = [] { return 42; };
2172   EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));
2173   EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));
2174 
2175   // Ensure decay occurs where required.
2176   std::function<int()> f = [] { return 7; };
2177   Action<int(int)> d = f;
2178   f = nullptr;
2179   EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
2180 
2181   // Ensure creation of an empty action succeeds.
2182   Action<void(int)>(nullptr);
2183 }
2184 
TEST(FunctorActionTest,UnusedArguments)2185 TEST(FunctorActionTest, UnusedArguments) {
2186   // Verify that users can ignore uninteresting arguments.
2187   Action<int(int, double y, double z)> a = [](int i, Unused, Unused) {
2188     return 2 * i;
2189   };
2190   std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
2191   EXPECT_EQ(6, a.Perform(dummy));
2192 }
2193 
2194 // Test that basic built-in actions work with move-only arguments.
TEST(MoveOnlyArgumentsTest,ReturningActions)2195 TEST(MoveOnlyArgumentsTest, ReturningActions) {
2196   Action<int(std::unique_ptr<int>)> a = Return(1);
2197   EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));
2198 
2199   a = testing::WithoutArgs([]() { return 7; });
2200   EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr)));
2201 
2202   Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
2203   int x = 0;
2204   a2.Perform(std::make_tuple(nullptr, &x));
2205   EXPECT_EQ(x, 3);
2206 }
2207 
ACTION(ReturnArity)2208 ACTION(ReturnArity) { return std::tuple_size<args_type>::value; }
2209 
TEST(ActionMacro,LargeArity)2210 TEST(ActionMacro, LargeArity) {
2211   EXPECT_EQ(
2212       1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));
2213   EXPECT_EQ(
2214       10,
2215       testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(
2216           ReturnArity())
2217           .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));
2218   EXPECT_EQ(
2219       20,
2220       testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,
2221                           int, int, int, int, int, int, int, int, int)>(
2222           ReturnArity())
2223           .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
2224                                    14, 15, 16, 17, 18, 19)));
2225 }
2226 
2227 }  // namespace
2228 }  // namespace testing
2229 
2230 #if defined(_MSC_VER) && (_MSC_VER == 1900)
2231 GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4800
2232 #endif
2233 GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4100 4503
2234