proxygen
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 // Author: wan@google.com (Zhanyong Wan)
31 
32 // Google Mock - a framework for writing C++ mock classes.
33 //
34 // This file tests the built-in actions.
35 
36 #include "gmock/gmock-actions.h"
37 #include <algorithm>
38 #include <iterator>
39 #include <memory>
40 #include <string>
41 #include "gmock/gmock.h"
42 #include "gmock/internal/gmock-port.h"
43 #include "gtest/gtest.h"
44 #include "gtest/gtest-spi.h"
45 
46 namespace {
47 
48 // This list should be kept sorted.
49 using testing::Action;
51 using testing::Assign;
52 using testing::ByMove;
53 using testing::ByRef;
55 using testing::DoDefault;
57 using testing::Invoke;
60 using testing::Ne;
62 using testing::Return;
64 using testing::ReturnRef;
68 using testing::_;
69 using testing::get;
74 using testing::tuple;
75 using testing::tuple_element;
76 
77 #if !GTEST_OS_WINDOWS_MOBILE
79 #endif
80 
81 #if GTEST_HAS_PROTOBUF_
82 using testing::internal::TestMessage;
83 #endif // GTEST_HAS_PROTOBUF_
84 
85 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
86 TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
87  EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL);
88  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL);
89  EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL);
90 }
91 
92 // Tests that BuiltInDefaultValue<T*>::Exists() return true.
93 TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
94  EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
95  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
96  EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
97 }
98 
99 // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
100 // built-in numeric type.
101 TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
102  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
103  EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
104  EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
105 #if GMOCK_HAS_SIGNED_WCHAR_T_
106  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get());
107  EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get());
108 #endif
109 #if GMOCK_WCHAR_T_IS_NATIVE_
110  EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
111 #endif
112  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
113  EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
114  EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT
115  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
116  EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
117  EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
118  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
119  EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
120  EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
121  EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get());
122  EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get());
123  EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
124  EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
125 }
126 
127 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
128 // built-in numeric type.
129 TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
130  EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
131  EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
132  EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
133 #if GMOCK_HAS_SIGNED_WCHAR_T_
134  EXPECT_TRUE(BuiltInDefaultValue<unsigned wchar_t>::Exists());
135  EXPECT_TRUE(BuiltInDefaultValue<signed wchar_t>::Exists());
136 #endif
137 #if GMOCK_WCHAR_T_IS_NATIVE_
138  EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
139 #endif
140  EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT
141  EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT
142  EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT
143  EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
144  EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
145  EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
146  EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT
147  EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT
148  EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT
149  EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists());
150  EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists());
151  EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
152  EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
153 }
154 
155 // Tests that BuiltInDefaultValue<bool>::Get() returns false.
156 TEST(BuiltInDefaultValueTest, IsFalseForBool) {
157  EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
158 }
159 
160 // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
161 TEST(BuiltInDefaultValueTest, BoolExists) {
162  EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
163 }
164 
165 // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
166 // string type.
167 TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
168 #if GTEST_HAS_GLOBAL_STRING
169  EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get());
170 #endif // GTEST_HAS_GLOBAL_STRING
171 
172  EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
173 }
174 
175 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
176 // string type.
177 TEST(BuiltInDefaultValueTest, ExistsForString) {
178 #if GTEST_HAS_GLOBAL_STRING
179  EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists());
180 #endif // GTEST_HAS_GLOBAL_STRING
181 
182  EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
183 }
184 
185 // Tests that BuiltInDefaultValue<const T>::Get() returns the same
186 // value as BuiltInDefaultValue<T>::Get() does.
187 TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
188  EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
189  EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
190  EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL);
191  EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
192 }
193 
194 // A type that's default constructible.
195 class MyDefaultConstructible {
196  public:
197  MyDefaultConstructible() : value_(42) {}
198 
199  int value() const { return value_; }
200 
201  private:
202  int value_;
203 };
204 
205 // A type that's not default constructible.
206 class MyNonDefaultConstructible {
207  public:
208  // Does not have a default ctor.
209  explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
210 
211  int value() const { return value_; }
212 
213  private:
214  int value_;
215 };
216 
217 #if GTEST_HAS_STD_TYPE_TRAITS_
218 
219 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
220  EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
221 }
222 
223 TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
224  EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
225 }
226 
227 #endif // GTEST_HAS_STD_TYPE_TRAITS_
228 
229 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
230  EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
231 }
232 
233 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
234 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
236  BuiltInDefaultValue<int&>::Get();
237  }, "");
239  BuiltInDefaultValue<const char&>::Get();
240  }, "");
241 }
242 
243 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
245  BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
246  }, "");
247 }
248 
249 // Tests that DefaultValue<T>::IsSet() is false initially.
250 TEST(DefaultValueTest, IsInitiallyUnset) {
251  EXPECT_FALSE(DefaultValue<int>::IsSet());
252  EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
253  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
254 }
255 
256 // Tests that DefaultValue<T> can be set and then unset.
257 TEST(DefaultValueTest, CanBeSetAndUnset) {
258  EXPECT_TRUE(DefaultValue<int>::Exists());
259  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
260 
261  DefaultValue<int>::Set(1);
262  DefaultValue<const MyNonDefaultConstructible>::Set(
263  MyNonDefaultConstructible(42));
264 
265  EXPECT_EQ(1, DefaultValue<int>::Get());
266  EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
267 
268  EXPECT_TRUE(DefaultValue<int>::Exists());
269  EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
270 
271  DefaultValue<int>::Clear();
272  DefaultValue<const MyNonDefaultConstructible>::Clear();
273 
274  EXPECT_FALSE(DefaultValue<int>::IsSet());
275  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
276 
277  EXPECT_TRUE(DefaultValue<int>::Exists());
278  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
279 }
280 
281 // Tests that DefaultValue<T>::Get() returns the
282 // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
283 // false.
284 TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
285  EXPECT_FALSE(DefaultValue<int>::IsSet());
286  EXPECT_TRUE(DefaultValue<int>::Exists());
287  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
288  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
289 
290  EXPECT_EQ(0, DefaultValue<int>::Get());
291 
293  DefaultValue<MyNonDefaultConstructible>::Get();
294  }, "");
295 }
296 
297 #if GTEST_HAS_STD_UNIQUE_PTR_
298 TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
299  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
300  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == NULL);
301  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
302  return std::unique_ptr<int>(new int(42));
303  });
304  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
305  std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
306  EXPECT_EQ(42, *i);
307 }
308 #endif // GTEST_HAS_STD_UNIQUE_PTR_
309 
310 // Tests that DefaultValue<void>::Get() returns void.
311 TEST(DefaultValueTest, GetWorksForVoid) {
312  return DefaultValue<void>::Get();
313 }
314 
315 // Tests using DefaultValue with a reference type.
316 
317 // Tests that DefaultValue<T&>::IsSet() is false initially.
318 TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
319  EXPECT_FALSE(DefaultValue<int&>::IsSet());
320  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
321  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
322 }
323 
324 // Tests that DefaultValue<T&>::Exists is false initiallly.
325 TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
326  EXPECT_FALSE(DefaultValue<int&>::Exists());
327  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
328  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
329 }
330 
331 // Tests that DefaultValue<T&> can be set and then unset.
332 TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
333  int n = 1;
334  DefaultValue<const int&>::Set(n);
335  MyNonDefaultConstructible x(42);
336  DefaultValue<MyNonDefaultConstructible&>::Set(x);
337 
338  EXPECT_TRUE(DefaultValue<const int&>::Exists());
339  EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
340 
341  EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
342  EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
343 
344  DefaultValue<const int&>::Clear();
345  DefaultValue<MyNonDefaultConstructible&>::Clear();
346 
347  EXPECT_FALSE(DefaultValue<const int&>::Exists());
348  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
349 
350  EXPECT_FALSE(DefaultValue<const int&>::IsSet());
351  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
352 }
353 
354 // Tests that DefaultValue<T&>::Get() returns the
355 // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
356 // false.
357 TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
358  EXPECT_FALSE(DefaultValue<int&>::IsSet());
359  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
360 
362  DefaultValue<int&>::Get();
363  }, "");
365  DefaultValue<MyNonDefaultConstructible>::Get();
366  }, "");
367 }
368 
369 // Tests that ActionInterface can be implemented by defining the
370 // Perform method.
371 
372 typedef int MyGlobalFunction(bool, int);
373 
374 class MyActionImpl : public ActionInterface<MyGlobalFunction> {
375  public:
376  virtual int Perform(const tuple<bool, int>& args) {
377  return get<0>(args) ? get<1>(args) : 0;
378  }
379 };
380 
381 TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
382  MyActionImpl my_action_impl;
383  (void)my_action_impl;
384 }
385 
386 TEST(ActionInterfaceTest, MakeAction) {
387  Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
388 
389  // When exercising the Perform() method of Action<F>, we must pass
390  // it a tuple whose size and type are compatible with F's argument
391  // types. For example, if F is int(), then Perform() takes a
392  // 0-tuple; if F is void(bool, int), then Perform() takes a
393  // tuple<bool, int>, and so on.
394  EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
395 }
396 
397 // Tests that Action<F> can be contructed from a pointer to
398 // ActionInterface<F>.
399 TEST(ActionTest, CanBeConstructedFromActionInterface) {
400  Action<MyGlobalFunction> action(new MyActionImpl);
401 }
402 
403 // Tests that Action<F> delegates actual work to ActionInterface<F>.
404 TEST(ActionTest, DelegatesWorkToActionInterface) {
405  const Action<MyGlobalFunction> action(new MyActionImpl);
406 
407  EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
408  EXPECT_EQ(0, action.Perform(make_tuple(false, 1)));
409 }
410 
411 // Tests that Action<F> can be copied.
412 TEST(ActionTest, IsCopyable) {
413  Action<MyGlobalFunction> a1(new MyActionImpl);
414  Action<MyGlobalFunction> a2(a1); // Tests the copy constructor.
415 
416  // a1 should continue to work after being copied from.
417  EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
418  EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
419 
420  // a2 should work like the action it was copied from.
421  EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
422  EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
423 
424  a2 = a1; // Tests the assignment operator.
425 
426  // a1 should continue to work after being copied from.
427  EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
428  EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
429 
430  // a2 should work like the action it was copied from.
431  EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
432  EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
433 }
434 
435 // Tests that an Action<From> object can be converted to a
436 // compatible Action<To> object.
437 
438 class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
439  public:
440  virtual bool Perform(const tuple<int>& arg) {
441  return get<0>(arg) != 0;
442  }
443 };
444 
445 #if !GTEST_OS_SYMBIAN
446 // Compiling this test on Nokia's Symbian compiler fails with:
447 // 'Result' is not a member of class 'testing::internal::Function<int>'
448 // (point of instantiation: '@unnamed@gmock_actions_test_cc@::
449 // ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()')
450 // with no obvious fix.
451 TEST(ActionTest, CanBeConvertedToOtherActionType) {
452  const Action<bool(int)> a1(new IsNotZero); // NOLINT
453  const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT
454  EXPECT_EQ(1, a2.Perform(make_tuple('a')));
455  EXPECT_EQ(0, a2.Perform(make_tuple('\0')));
456 }
457 #endif // !GTEST_OS_SYMBIAN
458 
459 // The following two classes are for testing MakePolymorphicAction().
460 
461 // Implements a polymorphic action that returns the second of the
462 // arguments it receives.
463 class ReturnSecondArgumentAction {
464  public:
465  // We want to verify that MakePolymorphicAction() can work with a
466  // polymorphic action whose Perform() method template is either
467  // const or not. This lets us verify the non-const case.
468  template <typename Result, typename ArgumentTuple>
469  Result Perform(const ArgumentTuple& args) { return get<1>(args); }
470 };
471 
472 // Implements a polymorphic action that can be used in a nullary
473 // function to return 0.
474 class ReturnZeroFromNullaryFunctionAction {
475  public:
476  // For testing that MakePolymorphicAction() works when the
477  // implementation class' Perform() method template takes only one
478  // template parameter.
479  //
480  // We want to verify that MakePolymorphicAction() can work with a
481  // polymorphic action whose Perform() method template is either
482  // const or not. This lets us verify the const case.
483  template <typename Result>
484  Result Perform(const tuple<>&) const { return 0; }
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(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(make_tuple()));
511 
512  Action<void*()> a2 = ReturnZeroFromNullaryFunction();
513  EXPECT_TRUE(a2.Perform(make_tuple()) == NULL);
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(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(make_tuple()));
527 
528  ret = Return(-5);
529  EXPECT_EQ(-5, ret.Perform(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(make_tuple()));
536 
537  Action<std::string()> a2 = Return("world");
538  EXPECT_EQ("world", a2.Perform(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(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(make_tuple()));
576 
577  ret = Return(&derived);
578  EXPECT_EQ(&derived, ret.Perform(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(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(make_tuple()) == NULL);
631 
632  const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT
633  EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL);
634 }
635 
636 #if GTEST_HAS_STD_UNIQUE_PTR_
637 // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
638 // functions.
639 TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
640  const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
641  EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr);
642 
643  const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
644  EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr);
645 }
646 #endif // GTEST_HAS_STD_UNIQUE_PTR_
647 
648 // Tests that ReturnRef(v) works for reference types.
649 TEST(ReturnRefTest, WorksForReference) {
650  const int n = 0;
651  const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT
652 
653  EXPECT_EQ(&n, &ret.Perform(make_tuple(true)));
654 }
655 
656 // Tests that ReturnRef(v) is covariant.
657 TEST(ReturnRefTest, IsCovariant) {
658  Base base;
659  Derived derived;
660  Action<Base&()> a = ReturnRef(base);
661  EXPECT_EQ(&base, &a.Perform(make_tuple()));
662 
663  a = ReturnRef(derived);
664  EXPECT_EQ(&derived, &a.Perform(make_tuple()));
665 }
666 
667 // Tests that ReturnRefOfCopy(v) works for reference types.
668 TEST(ReturnRefOfCopyTest, WorksForReference) {
669  int n = 42;
670  const Action<const int&()> ret = ReturnRefOfCopy(n);
671 
672  EXPECT_NE(&n, &ret.Perform(make_tuple()));
673  EXPECT_EQ(42, ret.Perform(make_tuple()));
674 
675  n = 43;
676  EXPECT_NE(&n, &ret.Perform(make_tuple()));
677  EXPECT_EQ(42, ret.Perform(make_tuple()));
678 }
679 
680 // Tests that ReturnRefOfCopy(v) is covariant.
681 TEST(ReturnRefOfCopyTest, IsCovariant) {
682  Base base;
683  Derived derived;
684  Action<Base&()> a = ReturnRefOfCopy(base);
685  EXPECT_NE(&base, &a.Perform(make_tuple()));
686 
687  a = ReturnRefOfCopy(derived);
688  EXPECT_NE(&derived, &a.Perform(make_tuple()));
689 }
690 
691 // Tests that DoDefault() does the default action for the mock method.
692 
693 class MockClass {
694  public:
695  MockClass() {}
696 
697  MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
698  MOCK_METHOD0(Foo, MyNonDefaultConstructible());
699 #if GTEST_HAS_STD_UNIQUE_PTR_
700  MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
701  MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
702  MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
703 #endif
704 
705  private:
707 };
708 
709 // Tests that DoDefault() returns the built-in default value for the
710 // return type by default.
711 TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
712  MockClass mock;
713  EXPECT_CALL(mock, IntFunc(_))
714  .WillOnce(DoDefault());
715  EXPECT_EQ(0, mock.IntFunc(true));
716 }
717 
718 // Tests that DoDefault() throws (when exceptions are enabled) or aborts
719 // the process when there is no built-in default value for the return type.
720 TEST(DoDefaultDeathTest, DiesForUnknowType) {
721  MockClass mock;
722  EXPECT_CALL(mock, Foo())
723  .WillRepeatedly(DoDefault());
724 #if GTEST_HAS_EXCEPTIONS
725  EXPECT_ANY_THROW(mock.Foo());
726 #else
728  mock.Foo();
729  }, "");
730 #endif
731 }
732 
733 // Tests that using DoDefault() inside a composite action leads to a
734 // run-time error.
735 
736 void VoidFunc(bool /* flag */) {}
737 
738 TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
739  MockClass mock;
740  EXPECT_CALL(mock, IntFunc(_))
741  .WillRepeatedly(DoAll(Invoke(VoidFunc),
742  DoDefault()));
743 
744  // Ideally we should verify the error message as well. Sadly,
745  // EXPECT_DEATH() can only capture stderr, while Google Mock's
746  // errors are printed on stdout. Therefore we have to settle for
747  // not verifying the message.
749  mock.IntFunc(true);
750  }, "");
751 }
752 
753 // Tests that DoDefault() returns the default value set by
754 // DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
755 TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
756  DefaultValue<int>::Set(1);
757  MockClass mock;
758  EXPECT_CALL(mock, IntFunc(_))
759  .WillOnce(DoDefault());
760  EXPECT_EQ(1, mock.IntFunc(false));
761  DefaultValue<int>::Clear();
762 }
763 
764 // Tests that DoDefault() does the action specified by ON_CALL().
765 TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
766  MockClass mock;
767  ON_CALL(mock, IntFunc(_))
768  .WillByDefault(Return(2));
769  EXPECT_CALL(mock, IntFunc(_))
770  .WillOnce(DoDefault());
771  EXPECT_EQ(2, mock.IntFunc(false));
772 }
773 
774 // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
775 TEST(DoDefaultTest, CannotBeUsedInOnCall) {
776  MockClass mock;
777  EXPECT_NONFATAL_FAILURE({ // NOLINT
778  ON_CALL(mock, IntFunc(_))
779  .WillByDefault(DoDefault());
780  }, "DoDefault() cannot be used in ON_CALL()");
781 }
782 
783 // Tests that SetArgPointee<N>(v) sets the variable pointed to by
784 // the N-th (0-based) argument to v.
785 TEST(SetArgPointeeTest, SetsTheNthPointee) {
786  typedef void MyFunction(bool, int*, char*);
787  Action<MyFunction> a = SetArgPointee<1>(2);
788 
789  int n = 0;
790  char ch = '\0';
791  a.Perform(make_tuple(true, &n, &ch));
792  EXPECT_EQ(2, n);
793  EXPECT_EQ('\0', ch);
794 
795  a = SetArgPointee<2>('a');
796  n = 0;
797  ch = '\0';
798  a.Perform(make_tuple(true, &n, &ch));
799  EXPECT_EQ(0, n);
800  EXPECT_EQ('a', ch);
801 }
802 
803 #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
804 // Tests that SetArgPointee<N>() accepts a string literal.
805 // GCC prior to v4.0 and the Symbian compiler do not support this.
806 TEST(SetArgPointeeTest, AcceptsStringLiteral) {
807  typedef void MyFunction(std::string*, const char**);
808  Action<MyFunction> a = SetArgPointee<0>("hi");
809  std::string str;
810  const char* ptr = NULL;
811  a.Perform(make_tuple(&str, &ptr));
812  EXPECT_EQ("hi", str);
813  EXPECT_TRUE(ptr == NULL);
814 
815  a = SetArgPointee<1>("world");
816  str = "";
817  a.Perform(make_tuple(&str, &ptr));
818  EXPECT_EQ("", str);
819  EXPECT_STREQ("world", ptr);
820 }
821 
822 TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
823  typedef void MyFunction(const wchar_t**);
824  Action<MyFunction> a = SetArgPointee<0>(L"world");
825  const wchar_t* ptr = NULL;
826  a.Perform(make_tuple(&ptr));
827  EXPECT_STREQ(L"world", ptr);
828 
829 # if GTEST_HAS_STD_WSTRING
830 
831  typedef void MyStringFunction(std::wstring*);
832  Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
833  std::wstring str = L"";
834  a2.Perform(make_tuple(&str));
835  EXPECT_EQ(L"world", str);
836 
837 # endif
838 }
839 #endif
840 
841 // Tests that SetArgPointee<N>() accepts a char pointer.
842 TEST(SetArgPointeeTest, AcceptsCharPointer) {
843  typedef void MyFunction(bool, std::string*, const char**);
844  const char* const hi = "hi";
845  Action<MyFunction> a = SetArgPointee<1>(hi);
846  std::string str;
847  const char* ptr = NULL;
848  a.Perform(make_tuple(true, &str, &ptr));
849  EXPECT_EQ("hi", str);
850  EXPECT_TRUE(ptr == NULL);
851 
852  char world_array[] = "world";
853  char* const world = world_array;
854  a = SetArgPointee<2>(world);
855  str = "";
856  a.Perform(make_tuple(true, &str, &ptr));
857  EXPECT_EQ("", str);
858  EXPECT_EQ(world, ptr);
859 }
860 
861 TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
862  typedef void MyFunction(bool, const wchar_t**);
863  const wchar_t* const hi = L"hi";
864  Action<MyFunction> a = SetArgPointee<1>(hi);
865  const wchar_t* ptr = NULL;
866  a.Perform(make_tuple(true, &ptr));
867  EXPECT_EQ(hi, ptr);
868 
869 # if GTEST_HAS_STD_WSTRING
870 
871  typedef void MyStringFunction(bool, std::wstring*);
872  wchar_t world_array[] = L"world";
873  wchar_t* const world = world_array;
874  Action<MyStringFunction> a2 = SetArgPointee<1>(world);
875  std::wstring str;
876  a2.Perform(make_tuple(true, &str));
877  EXPECT_EQ(world_array, str);
878 # endif
879 }
880 
881 #if GTEST_HAS_PROTOBUF_
882 
883 // Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf
884 // variable pointed to by the N-th (0-based) argument to proto_buffer.
885 TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
886  TestMessage* const msg = new TestMessage;
887  msg->set_member("yes");
888  TestMessage orig_msg;
889  orig_msg.CopyFrom(*msg);
890 
891  Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg);
892  // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
893  // s.t. the action works even when the original proto_buffer has
894  // died. We ensure this behavior by deleting msg before using the
895  // action.
896  delete msg;
897 
898  TestMessage dest;
899  EXPECT_FALSE(orig_msg.Equals(dest));
900  a.Perform(make_tuple(true, &dest));
901  EXPECT_TRUE(orig_msg.Equals(dest));
902 }
903 
904 // Tests that SetArgPointee<N>(proto_buffer) sets the
905 // ::ProtocolMessage variable pointed to by the N-th (0-based)
906 // argument to proto_buffer.
907 TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
908  TestMessage* const msg = new TestMessage;
909  msg->set_member("yes");
910  TestMessage orig_msg;
911  orig_msg.CopyFrom(*msg);
912 
913  Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg);
914  // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
915  // s.t. the action works even when the original proto_buffer has
916  // died. We ensure this behavior by deleting msg before using the
917  // action.
918  delete msg;
919 
920  TestMessage dest;
921  ::ProtocolMessage* const dest_base = &dest;
922  EXPECT_FALSE(orig_msg.Equals(dest));
923  a.Perform(make_tuple(true, dest_base));
924  EXPECT_TRUE(orig_msg.Equals(dest));
925 }
926 
927 // Tests that SetArgPointee<N>(proto2_buffer) sets the v2
928 // protobuf variable pointed to by the N-th (0-based) argument to
929 // proto2_buffer.
930 TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
931  using testing::internal::FooMessage;
932  FooMessage* const msg = new FooMessage;
933  msg->set_int_field(2);
934  msg->set_string_field("hi");
935  FooMessage orig_msg;
936  orig_msg.CopyFrom(*msg);
937 
938  Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg);
939  // SetArgPointee<N>(proto2_buffer) makes a copy of
940  // proto2_buffer s.t. the action works even when the original
941  // proto2_buffer has died. We ensure this behavior by deleting msg
942  // before using the action.
943  delete msg;
944 
945  FooMessage dest;
946  dest.set_int_field(0);
947  a.Perform(make_tuple(true, &dest));
948  EXPECT_EQ(2, dest.int_field());
949  EXPECT_EQ("hi", dest.string_field());
950 }
951 
952 // Tests that SetArgPointee<N>(proto2_buffer) sets the
953 // proto2::Message variable pointed to by the N-th (0-based) argument
954 // to proto2_buffer.
955 TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
956  using testing::internal::FooMessage;
957  FooMessage* const msg = new FooMessage;
958  msg->set_int_field(2);
959  msg->set_string_field("hi");
960  FooMessage orig_msg;
961  orig_msg.CopyFrom(*msg);
962 
963  Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg);
964  // SetArgPointee<N>(proto2_buffer) makes a copy of
965  // proto2_buffer s.t. the action works even when the original
966  // proto2_buffer has died. We ensure this behavior by deleting msg
967  // before using the action.
968  delete msg;
969 
970  FooMessage dest;
971  dest.set_int_field(0);
972  ::proto2::Message* const dest_base = &dest;
973  a.Perform(make_tuple(true, dest_base));
974  EXPECT_EQ(2, dest.int_field());
975  EXPECT_EQ("hi", dest.string_field());
976 }
977 
978 #endif // GTEST_HAS_PROTOBUF_
979 
980 // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
981 // the N-th (0-based) argument to v.
982 TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
983  typedef void MyFunction(bool, int*, char*);
984  Action<MyFunction> a = SetArgumentPointee<1>(2);
985 
986  int n = 0;
987  char ch = '\0';
988  a.Perform(make_tuple(true, &n, &ch));
989  EXPECT_EQ(2, n);
990  EXPECT_EQ('\0', ch);
991 
992  a = SetArgumentPointee<2>('a');
993  n = 0;
994  ch = '\0';
995  a.Perform(make_tuple(true, &n, &ch));
996  EXPECT_EQ(0, n);
997  EXPECT_EQ('a', ch);
998 }
999 
1000 #if GTEST_HAS_PROTOBUF_
1001 
1002 // Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf
1003 // variable pointed to by the N-th (0-based) argument to proto_buffer.
1004 TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
1005  TestMessage* const msg = new TestMessage;
1006  msg->set_member("yes");
1007  TestMessage orig_msg;
1008  orig_msg.CopyFrom(*msg);
1009 
1010  Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg);
1011  // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
1012  // s.t. the action works even when the original proto_buffer has
1013  // died. We ensure this behavior by deleting msg before using the
1014  // action.
1015  delete msg;
1016 
1017  TestMessage dest;
1018  EXPECT_FALSE(orig_msg.Equals(dest));
1019  a.Perform(make_tuple(true, &dest));
1020  EXPECT_TRUE(orig_msg.Equals(dest));
1021 }
1022 
1023 // Tests that SetArgumentPointee<N>(proto_buffer) sets the
1024 // ::ProtocolMessage variable pointed to by the N-th (0-based)
1025 // argument to proto_buffer.
1026 TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
1027  TestMessage* const msg = new TestMessage;
1028  msg->set_member("yes");
1029  TestMessage orig_msg;
1030  orig_msg.CopyFrom(*msg);
1031 
1032  Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg);
1033  // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
1034  // s.t. the action works even when the original proto_buffer has
1035  // died. We ensure this behavior by deleting msg before using the
1036  // action.
1037  delete msg;
1038 
1039  TestMessage dest;
1040  ::ProtocolMessage* const dest_base = &dest;
1041  EXPECT_FALSE(orig_msg.Equals(dest));
1042  a.Perform(make_tuple(true, dest_base));
1043  EXPECT_TRUE(orig_msg.Equals(dest));
1044 }
1045 
1046 // Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2
1047 // protobuf variable pointed to by the N-th (0-based) argument to
1048 // proto2_buffer.
1049 TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
1050  using testing::internal::FooMessage;
1051  FooMessage* const msg = new FooMessage;
1052  msg->set_int_field(2);
1053  msg->set_string_field("hi");
1054  FooMessage orig_msg;
1055  orig_msg.CopyFrom(*msg);
1056 
1057  Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg);
1058  // SetArgumentPointee<N>(proto2_buffer) makes a copy of
1059  // proto2_buffer s.t. the action works even when the original
1060  // proto2_buffer has died. We ensure this behavior by deleting msg
1061  // before using the action.
1062  delete msg;
1063 
1064  FooMessage dest;
1065  dest.set_int_field(0);
1066  a.Perform(make_tuple(true, &dest));
1067  EXPECT_EQ(2, dest.int_field());
1068  EXPECT_EQ("hi", dest.string_field());
1069 }
1070 
1071 // Tests that SetArgumentPointee<N>(proto2_buffer) sets the
1072 // proto2::Message variable pointed to by the N-th (0-based) argument
1073 // to proto2_buffer.
1074 TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
1075  using testing::internal::FooMessage;
1076  FooMessage* const msg = new FooMessage;
1077  msg->set_int_field(2);
1078  msg->set_string_field("hi");
1079  FooMessage orig_msg;
1080  orig_msg.CopyFrom(*msg);
1081 
1082  Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg);
1083  // SetArgumentPointee<N>(proto2_buffer) makes a copy of
1084  // proto2_buffer s.t. the action works even when the original
1085  // proto2_buffer has died. We ensure this behavior by deleting msg
1086  // before using the action.
1087  delete msg;
1088 
1089  FooMessage dest;
1090  dest.set_int_field(0);
1091  ::proto2::Message* const dest_base = &dest;
1092  a.Perform(make_tuple(true, dest_base));
1093  EXPECT_EQ(2, dest.int_field());
1094  EXPECT_EQ("hi", dest.string_field());
1095 }
1096 
1097 #endif // GTEST_HAS_PROTOBUF_
1098 
1099 // Sample functions and functors for testing Invoke() and etc.
1100 int Nullary() { return 1; }
1101 
1102 class NullaryFunctor {
1103  public:
1104  int operator()() { return 2; }
1105 };
1106 
1107 bool g_done = false;
1108 void VoidNullary() { g_done = true; }
1109 
1110 class VoidNullaryFunctor {
1111  public:
1112  void operator()() { g_done = true; }
1113 };
1114 
1115 class Foo {
1116  public:
1117  Foo() : value_(123) {}
1118 
1119  int Nullary() const { return value_; }
1120 
1121  private:
1122  int value_;
1123 };
1124 
1125 // Tests InvokeWithoutArgs(function).
1126 TEST(InvokeWithoutArgsTest, Function) {
1127  // As an action that takes one argument.
1128  Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT
1129  EXPECT_EQ(1, a.Perform(make_tuple(2)));
1130 
1131  // As an action that takes two arguments.
1132  Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT
1133  EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5)));
1134 
1135  // As an action that returns void.
1136  Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT
1137  g_done = false;
1138  a3.Perform(make_tuple(1));
1139  EXPECT_TRUE(g_done);
1140 }
1141 
1142 // Tests InvokeWithoutArgs(functor).
1143 TEST(InvokeWithoutArgsTest, Functor) {
1144  // As an action that takes no argument.
1145  Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT
1146  EXPECT_EQ(2, a.Perform(make_tuple()));
1147 
1148  // As an action that takes three arguments.
1149  Action<int(int, double, char)> a2 = // NOLINT
1150  InvokeWithoutArgs(NullaryFunctor());
1151  EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a')));
1152 
1153  // As an action that returns void.
1154  Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
1155  g_done = false;
1156  a3.Perform(make_tuple());
1157  EXPECT_TRUE(g_done);
1158 }
1159 
1160 // Tests InvokeWithoutArgs(obj_ptr, method).
1161 TEST(InvokeWithoutArgsTest, Method) {
1162  Foo foo;
1163  Action<int(bool, char)> a = // NOLINT
1165  EXPECT_EQ(123, a.Perform(make_tuple(true, 'a')));
1166 }
1167 
1168 // Tests using IgnoreResult() on a polymorphic action.
1169 TEST(IgnoreResultTest, PolymorphicAction) {
1170  Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT
1171  a.Perform(make_tuple(1));
1172 }
1173 
1174 // Tests using IgnoreResult() on a monomorphic action.
1175 
1176 int ReturnOne() {
1177  g_done = true;
1178  return 1;
1179 }
1180 
1181 TEST(IgnoreResultTest, MonomorphicAction) {
1182  g_done = false;
1183  Action<void()> a = IgnoreResult(Invoke(ReturnOne));
1184  a.Perform(make_tuple());
1185  EXPECT_TRUE(g_done);
1186 }
1187 
1188 // Tests using IgnoreResult() on an action that returns a class type.
1189 
1190 MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1191  g_done = true;
1192  return MyNonDefaultConstructible(42);
1193 }
1194 
1195 TEST(IgnoreResultTest, ActionReturningClass) {
1196  g_done = false;
1197  Action<void(int)> a =
1198  IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
1199  a.Perform(make_tuple(2));
1200  EXPECT_TRUE(g_done);
1201 }
1202 
1203 TEST(AssignTest, Int) {
1204  int x = 0;
1205  Action<void(int)> a = Assign(&x, 5);
1206  a.Perform(make_tuple(0));
1207  EXPECT_EQ(5, x);
1208 }
1209 
1210 TEST(AssignTest, String) {
1211  ::std::string x;
1212  Action<void(void)> a = Assign(&x, "Hello, world");
1213  a.Perform(make_tuple());
1214  EXPECT_EQ("Hello, world", x);
1215 }
1216 
1217 TEST(AssignTest, CompatibleTypes) {
1218  double x = 0;
1219  Action<void(int)> a = Assign(&x, 5);
1220  a.Perform(make_tuple(0));
1221  EXPECT_DOUBLE_EQ(5, x);
1222 }
1223 
1224 #if !GTEST_OS_WINDOWS_MOBILE
1225 
1226 class SetErrnoAndReturnTest : public testing::Test {
1227  protected:
1228  virtual void SetUp() { errno = 0; }
1229  virtual void TearDown() { errno = 0; }
1230 };
1231 
1232 TEST_F(SetErrnoAndReturnTest, Int) {
1233  Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
1234  EXPECT_EQ(-5, a.Perform(make_tuple()));
1235  EXPECT_EQ(ENOTTY, errno);
1236 }
1237 
1238 TEST_F(SetErrnoAndReturnTest, Ptr) {
1239  int x;
1240  Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
1241  EXPECT_EQ(&x, a.Perform(make_tuple()));
1242  EXPECT_EQ(ENOTTY, errno);
1243 }
1244 
1245 TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
1246  Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
1247  EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple()));
1248  EXPECT_EQ(EINVAL, errno);
1249 }
1250 
1251 #endif // !GTEST_OS_WINDOWS_MOBILE
1252 
1253 // Tests ByRef().
1254 
1255 // Tests that ReferenceWrapper<T> is copyable.
1256 TEST(ByRefTest, IsCopyable) {
1257  const std::string s1 = "Hi";
1258  const std::string s2 = "Hello";
1259 
1261  ByRef(s1);
1262  const std::string& r1 = ref_wrapper;
1263  EXPECT_EQ(&s1, &r1);
1264 
1265  // Assigns a new value to ref_wrapper.
1266  ref_wrapper = ByRef(s2);
1267  const std::string& r2 = ref_wrapper;
1268  EXPECT_EQ(&s2, &r2);
1269 
1271  ByRef(s1);
1272  // Copies ref_wrapper1 to ref_wrapper.
1273  ref_wrapper = ref_wrapper1;
1274  const std::string& r3 = ref_wrapper;
1275  EXPECT_EQ(&s1, &r3);
1276 }
1277 
1278 // Tests using ByRef() on a const value.
1279 TEST(ByRefTest, ConstValue) {
1280  const int n = 0;
1281  // int& ref = ByRef(n); // This shouldn't compile - we have a
1282  // negative compilation test to catch it.
1283  const int& const_ref = ByRef(n);
1284  EXPECT_EQ(&n, &const_ref);
1285 }
1286 
1287 // Tests using ByRef() on a non-const value.
1288 TEST(ByRefTest, NonConstValue) {
1289  int n = 0;
1290 
1291  // ByRef(n) can be used as either an int&,
1292  int& ref = ByRef(n);
1293  EXPECT_EQ(&n, &ref);
1294 
1295  // or a const int&.
1296  const int& const_ref = ByRef(n);
1297  EXPECT_EQ(&n, &const_ref);
1298 }
1299 
1300 // Tests explicitly specifying the type when using ByRef().
1301 TEST(ByRefTest, ExplicitType) {
1302  int n = 0;
1303  const int& r1 = ByRef<const int>(n);
1304  EXPECT_EQ(&n, &r1);
1305 
1306  // ByRef<char>(n); // This shouldn't compile - we have a negative
1307  // compilation test to catch it.
1308 
1309  Derived d;
1310  Derived& r2 = ByRef<Derived>(d);
1311  EXPECT_EQ(&d, &r2);
1312 
1313  const Derived& r3 = ByRef<const Derived>(d);
1314  EXPECT_EQ(&d, &r3);
1315 
1316  Base& r4 = ByRef<Base>(d);
1317  EXPECT_EQ(&d, &r4);
1318 
1319  const Base& r5 = ByRef<const Base>(d);
1320  EXPECT_EQ(&d, &r5);
1321 
1322  // The following shouldn't compile - we have a negative compilation
1323  // test for it.
1324  //
1325  // Base b;
1326  // ByRef<Derived>(b);
1327 }
1328 
1329 // Tests that Google Mock prints expression ByRef(x) as a reference to x.
1330 TEST(ByRefTest, PrintsCorrectly) {
1331  int n = 42;
1332  ::std::stringstream expected, actual;
1335  EXPECT_EQ(expected.str(), actual.str());
1336 }
1337 
1338 #if GTEST_HAS_STD_UNIQUE_PTR_
1339 
1340 std::unique_ptr<int> UniquePtrSource() {
1341  return std::unique_ptr<int>(new int(19));
1342 }
1343 
1344 std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
1345  std::vector<std::unique_ptr<int>> out;
1346  out.emplace_back(new int(7));
1347  return out;
1348 }
1349 
1350 TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
1351  MockClass mock;
1352  std::unique_ptr<int> i(new int(19));
1353  EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
1354  EXPECT_CALL(mock, MakeVectorUnique())
1355  .WillOnce(Return(ByMove(VectorUniquePtrSource())));
1356  Derived* d = new Derived;
1357  EXPECT_CALL(mock, MakeUniqueBase())
1358  .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
1359 
1360  std::unique_ptr<int> result1 = mock.MakeUnique();
1361  EXPECT_EQ(19, *result1);
1362 
1363  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1364  EXPECT_EQ(1u, vresult.size());
1365  EXPECT_NE(nullptr, vresult[0]);
1366  EXPECT_EQ(7, *vresult[0]);
1367 
1368  std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
1369  EXPECT_EQ(d, result2.get());
1370 }
1371 
1372 TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
1373  testing::MockFunction<void()> mock_function;
1374  MockClass mock;
1375  std::unique_ptr<int> i(new int(19));
1376  EXPECT_CALL(mock_function, Call());
1377  EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
1378  InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
1379  Return(ByMove(std::move(i)))));
1380 
1381  std::unique_ptr<int> result1 = mock.MakeUnique();
1382  EXPECT_EQ(19, *result1);
1383 }
1384 
1385 TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1386  MockClass mock;
1387 
1388  // Check default value
1389  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
1390  return std::unique_ptr<int>(new int(42));
1391  });
1392  EXPECT_EQ(42, *mock.MakeUnique());
1393 
1394  EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
1395  EXPECT_CALL(mock, MakeVectorUnique())
1396  .WillRepeatedly(Invoke(VectorUniquePtrSource));
1397  std::unique_ptr<int> result1 = mock.MakeUnique();
1398  EXPECT_EQ(19, *result1);
1399  std::unique_ptr<int> result2 = mock.MakeUnique();
1400  EXPECT_EQ(19, *result2);
1401  EXPECT_NE(result1, result2);
1402 
1403  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1404  EXPECT_EQ(1u, vresult.size());
1405  EXPECT_NE(nullptr, vresult[0]);
1406  EXPECT_EQ(7, *vresult[0]);
1407 }
1408 
1409 #endif // GTEST_HAS_STD_UNIQUE_PTR_
1410 
1411 } // Unnamed namespace
Definition: InvokeTest.cpp:58
void * ptr
#define EXPECT_ANY_THROW(statement)
Definition: gtest.h:1847
TypeWithSize< 8 >::Int Int64
Definition: gtest-port.h:2496
bool operator==(const char *c, CStringRange::Sentinel)
A polymorphic function wrapper that is not copyable and does not require the wrapped function to be c...
#define TEST(test_case_name, test_name)
Definition: gtest.h:2187
internal::NeMatcher< Rhs > Ne(Rhs x)
auto v
PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage< T >::value > > SetArgumentPointee(const T &x)
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< Impl > MakePolymorphicAction(const Impl &impl)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const int x
dest
Definition: upload.py:394
TypeWithSize< 8 >::UInt UInt64
Definition: gtest-port.h:2497
static once_flag flag
Definition: Random.cpp:75
tuple make_tuple()
Definition: gtest-tuple.h:675
PolymorphicAction< internal::InvokeWithoutArgsAction< FunctionImpl > > InvokeWithoutArgs(FunctionImpl function_impl)
internal::ReturnRefAction< R > ReturnRef(R &x)
internal::ByMoveWrapper< R > ByMove(R x)
auto ch
#define GTEST_DISALLOW_ASSIGN_(type)
Definition: gtest-port.h:869
boost::variant< DeliverAppData, WriteToSocket, ReportHandshakeSuccess, ReportEarlyHandshakeSuccess, ReportEarlyWriteFailed, ReportError, MutateState, WaitForData, NewCachedPsk > Action
Definition: Actions.h:79
Action< F > MakeAction(ActionInterface< F > *impl)
#define EXPECT_STREQ(s1, s2)
Definition: gtest.h:1995
::std::wstring wstring
Definition: gtest-port.h:1103
PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage< T >::value > > SetArgPointee(const T &x)
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
ConvertibleToBool IsNotZero(int number)
void UniversalPrint(const T &value,::std::ostream *os)
AtomicCounter< T, DeterministicAtomic > Base
char a
static const char *const value
Definition: Conv.cpp:50
PolymorphicAction< internal::ReturnNullAction > ReturnNull()
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex)
#define EXPECT_THAT(value, matcher)
internal::DoDefaultAction DoDefault()
#define ON_CALL(obj, call)
#define EXPECT_DOUBLE_EQ(val1, val2)
Definition: gtest.h:2031
#define MOCK_METHOD1(m,...)
const char * string
Definition: Conv.cpp:212
#define Method
internal::ReferenceWrapper< T > ByRef(T &l_value)
#define EXPECT_NE(val1, val2)
Definition: gtest.h:1926
static set< string > s
StrictConjunction< std::is_copy_constructible< T >, std::is_copy_assignable< T >> IsCopyable
Definition: Expected.h:117
#define EXPECT_NONFATAL_FAILURE(statement, substr)
Definition: gtest-spi.h:204
PolymorphicAction< internal::AssignAction< T1, T2 > > Assign(T1 *ptr, T2 val)
internal::DoBothAction< Action1, Action2 > DoAll(Action1 a1, Action2 a2)
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
Definition: gtest-port.h:874
internal::IgnoreResultAction< A > IgnoreResult(const A &an_action)
PolymorphicAction< internal::SetErrnoAndReturnAction< T > > SetErrnoAndReturn(int errval, T result)
static void Print(const T &value,::std::ostream *os)
PUSHMI_INLINE_VAR constexpr detail::get_fn< T > get
Definition: submit.h:391
internal::ElementsAreMatcher< ::testing::tuple<> > ElementsAre()
internal::ReturnRefOfCopyAction< R > ReturnRefOfCopy(const R &x)
internal::ReturnAction< R > Return(R value)
#define TEST_F(test_fixture, test_name)
Definition: gtest.h:2216
#define MOCK_METHOD0(m,...)
action
Definition: upload.py:393