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