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


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:52