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