1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file tests the built-in actions.
34
35 // Silence C4800 (C4800: 'int *const ': forcing value
36 // to bool 'true' or 'false') for MSVC 15
37 #ifdef _MSC_VER
38 #if _MSC_VER == 1900
39 # pragma warning(push)
40 # pragma warning(disable:4800)
41 #endif
42 #endif
43
44 #include "gmock/gmock-actions.h"
45 #include <algorithm>
46 #include <iterator>
47 #include <memory>
48 #include <string>
49 #include "gmock/gmock.h"
50 #include "gmock/internal/gmock-port.h"
51 #include "gtest/gtest.h"
52 #include "gtest/gtest-spi.h"
53
54 namespace {
55
56 // This list should be kept sorted.
57 using testing::_;
58 using testing::Action;
59 using testing::ActionInterface;
60 using testing::Assign;
61 using testing::ByMove;
62 using testing::ByRef;
63 using testing::DefaultValue;
64 using testing::DoAll;
65 using testing::DoDefault;
66 using testing::IgnoreResult;
67 using testing::Invoke;
68 using testing::InvokeWithoutArgs;
69 using testing::MakePolymorphicAction;
70 using testing::Ne;
71 using testing::PolymorphicAction;
72 using testing::Return;
73 using testing::ReturnNull;
74 using testing::ReturnRef;
75 using testing::ReturnRefOfCopy;
76 using testing::SetArgPointee;
77 using testing::SetArgumentPointee;
78 using testing::Unused;
79 using testing::WithArgs;
80 using testing::internal::BuiltInDefaultValue;
81 using testing::internal::Int64;
82 using testing::internal::UInt64;
83
84 #if !GTEST_OS_WINDOWS_MOBILE
85 using testing::SetErrnoAndReturn;
86 #endif
87
88 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
TEST(BuiltInDefaultValueTest,IsNullForPointerTypes)89 TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
90 EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr);
91 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr);
92 EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr);
93 }
94
95 // Tests that BuiltInDefaultValue<T*>::Exists() return true.
TEST(BuiltInDefaultValueTest,ExistsForPointerTypes)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.
TEST(BuiltInDefaultValueTest,IsZeroForNumericTypes)104 TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
105 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
106 EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
107 EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
108 #if GMOCK_HAS_SIGNED_WCHAR_T_
109 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get());
110 EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get());
111 #endif
112 #if GMOCK_WCHAR_T_IS_NATIVE_
113 #if !defined(__WCHAR_UNSIGNED__)
114 EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
115 #else
116 EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
117 #endif
118 #endif
119 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
120 EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
121 EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT
122 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
123 EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
124 EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
125 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
126 EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
127 EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
128 EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get());
129 EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get());
130 EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
131 EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
132 }
133
134 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
135 // built-in numeric type.
TEST(BuiltInDefaultValueTest,ExistsForNumericTypes)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.
TEST(BuiltInDefaultValueTest,IsFalseForBool)163 TEST(BuiltInDefaultValueTest, IsFalseForBool) {
164 EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
165 }
166
167 // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
TEST(BuiltInDefaultValueTest,BoolExists)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.
TEST(BuiltInDefaultValueTest,IsEmptyStringForString)174 TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
175 #if GTEST_HAS_GLOBAL_STRING
176 EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get());
177 #endif // GTEST_HAS_GLOBAL_STRING
178
179 EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
180 }
181
182 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
183 // string type.
TEST(BuiltInDefaultValueTest,ExistsForString)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.
TEST(BuiltInDefaultValueTest,WorksForConstTypes)194 TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
195 EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
196 EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
197 EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);
198 EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
199 }
200
201 // A type that's default constructible.
202 class MyDefaultConstructible {
203 public:
MyDefaultConstructible()204 MyDefaultConstructible() : value_(42) {}
205
value() const206 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.
MyNonDefaultConstructible(int a_value)216 explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
217
value() const218 int value() const { return value_; }
219
220 private:
221 int value_;
222 };
223
224
TEST(BuiltInDefaultValueTest,ExistsForDefaultConstructibleType)225 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
226 EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
227 }
228
TEST(BuiltInDefaultValueTest,IsDefaultConstructedForDefaultConstructibleType)229 TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
230 EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
231 }
232
233
TEST(BuiltInDefaultValueTest,DoesNotExistForNonDefaultConstructibleType)234 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
235 EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
236 }
237
238 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
TEST(BuiltInDefaultValueDeathTest,IsUndefinedForReferences)239 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
240 EXPECT_DEATH_IF_SUPPORTED({
241 BuiltInDefaultValue<int&>::Get();
242 }, "");
243 EXPECT_DEATH_IF_SUPPORTED({
244 BuiltInDefaultValue<const char&>::Get();
245 }, "");
246 }
247
TEST(BuiltInDefaultValueDeathTest,IsUndefinedForNonDefaultConstructibleType)248 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
249 EXPECT_DEATH_IF_SUPPORTED({
250 BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
251 }, "");
252 }
253
254 // Tests that DefaultValue<T>::IsSet() is false initially.
TEST(DefaultValueTest,IsInitiallyUnset)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.
TEST(DefaultValueTest,CanBeSetAndUnset)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
270 EXPECT_EQ(1, DefaultValue<int>::Get());
271 EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
272
273 EXPECT_TRUE(DefaultValue<int>::Exists());
274 EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
275
276 DefaultValue<int>::Clear();
277 DefaultValue<const MyNonDefaultConstructible>::Clear();
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.
TEST(DefaultValueDeathTest,GetReturnsBuiltInDefaultValueWhenUnset)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
295 EXPECT_EQ(0, DefaultValue<int>::Get());
296
297 EXPECT_DEATH_IF_SUPPORTED({
298 DefaultValue<MyNonDefaultConstructible>::Get();
299 }, "");
300 }
301
TEST(DefaultValueTest,GetWorksForMoveOnlyIfSet)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.
TEST(DefaultValueTest,GetWorksForVoid)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.
TEST(DefaultValueOfReferenceTest,IsInitiallyUnset)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.
TEST(DefaultValueOfReferenceTest,IsInitiallyNotExisting)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.
TEST(DefaultValueOfReferenceTest,CanBeSetAndUnset)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
344 EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
345 EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
346
347 DefaultValue<const int&>::Clear();
348 DefaultValue<MyNonDefaultConstructible&>::Clear();
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.
TEST(DefaultValueOfReferenceDeathTest,GetReturnsBuiltInDefaultValueWhenUnset)360 TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
361 EXPECT_FALSE(DefaultValue<int&>::IsSet());
362 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
363
364 EXPECT_DEATH_IF_SUPPORTED({
365 DefaultValue<int&>::Get();
366 }, "");
367 EXPECT_DEATH_IF_SUPPORTED({
368 DefaultValue<MyNonDefaultConstructible>::Get();
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:
Perform(const std::tuple<bool,int> & args)379 int Perform(const std::tuple<bool, int>& args) override {
380 return std::get<0>(args) ? std::get<1>(args) : 0;
381 }
382 };
383
TEST(ActionInterfaceTest,CanBeImplementedByDefiningPerform)384 TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
385 MyActionImpl my_action_impl;
386 (void)my_action_impl;
387 }
388
TEST(ActionInterfaceTest,MakeAction)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>.
TEST(ActionTest,CanBeConstructedFromActionInterface)402 TEST(ActionTest, CanBeConstructedFromActionInterface) {
403 Action<MyGlobalFunction> action(new MyActionImpl);
404 }
405
406 // Tests that Action<F> delegates actual work to ActionInterface<F>.
TEST(ActionTest,DelegatesWorkToActionInterface)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.
TEST(ActionTest,IsCopyable)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:
Perform(const std::tuple<int> & arg)443 bool Perform(const std::tuple<int>& arg) override {
444 return std::get<0>(arg) != 0;
445 }
446 };
447
TEST(ActionTest,CanBeConvertedToOtherActionType)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>
Perform(const ArgumentTuple & args)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>
Perform(const std::tuple<> &) const482 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
ReturnSecondArgument()490 PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
491 return MakePolymorphicAction(ReturnSecondArgumentAction());
492 }
493
494 PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
ReturnZeroFromNullaryFunction()495 ReturnZeroFromNullaryFunction() {
496 return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
497 }
498
499 // Tests that MakePolymorphicAction() turns a polymorphic action
500 // implementation class into a polymorphic action.
TEST(MakePolymorphicActionTest,ConstructsActionFromImpl)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.
TEST(MakePolymorphicActionTest,WorksWhenPerformHasOneTemplateParameter)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.
TEST(ReturnTest,WorksForVoid)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.
TEST(ReturnTest,ReturnsGivenValue)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.
TEST(ReturnTest,AcceptsStringLiteral)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;
IntegerVectorWrapper__anonf784654d0111::IntegerVectorWrapper545 IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT
546 };
547
548 // Tests that Return() works when return type is a wrapper type.
TEST(ReturnTest,SupportsWrapperReturnType)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 {
operator ==__anonf784654d0111::Base564 bool operator==(const Base&) { return true; }
565 };
566
567 struct Derived : public Base {
operator ==__anonf784654d0111::Derived568 bool operator==(const Derived&) { return true; }
569 };
570
TEST(ReturnTest,IsCovariant)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:
FromType(bool * is_converted)587 explicit FromType(bool* is_converted) : converted_(is_converted) {}
converted() const588 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>.
ToType(const FromType & x)599 ToType(const FromType& x) { *x.converted() = true; } // NOLINT
600 };
601
TEST(ReturnTest,ConvertsArgumentWhenConverted)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.
operator DestinationType()619 operator DestinationType() { return DestinationType(); }
620 };
621
TEST(ReturnTest,CanConvertArgumentUsingNonConstTypeCastOperator)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.
TEST(ReturnNullTest,WorksInPointerReturningFunction)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.
TEST(ReturnNullTest,WorksInSmartPointerReturningFunction)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.
TEST(ReturnRefTest,WorksForReference)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.
TEST(ReturnRefTest,IsCovariant)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.
TEST(ReturnRefOfCopyTest,WorksForReference)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.
TEST(ReturnRefOfCopyTest,IsCovariant)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:
MockClass()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:
705 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
706 };
707
708 // Tests that DoDefault() returns the built-in default value for the
709 // return type by default.
TEST(DoDefaultTest,ReturnsBuiltInDefaultValueByDefault)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.
TEST(DoDefaultDeathTest,DiesForUnknowType)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
726 EXPECT_DEATH_IF_SUPPORTED({
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
VoidFunc(bool)735 void VoidFunc(bool /* flag */) {}
736
TEST(DoDefaultDeathTest,DiesIfUsedInCompositeAction)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.
747 EXPECT_DEATH_IF_SUPPORTED({
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().
TEST(DoDefaultTest,ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne)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));
760 DefaultValue<int>::Clear();
761 }
762
763 // Tests that DoDefault() does the action specified by ON_CALL().
TEST(DoDefaultTest,DoesWhatOnCallSpecifies)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.
TEST(DoDefaultTest,CannotBeUsedInOnCall)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.
TEST(SetArgPointeeTest,SetsTheNthPointee)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.
TEST(SetArgPointeeTest,AcceptsStringLiteral)803 TEST(SetArgPointeeTest, AcceptsStringLiteral) {
804 typedef void MyFunction(std::string*, const char**);
805 Action<MyFunction> a = SetArgPointee<0>("hi");
806 std::string str;
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
TEST(SetArgPointeeTest,AcceptsWideStringLiteral)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.
TEST(SetArgPointeeTest,AcceptsCharPointer)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);
842 std::string str;
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
TEST(SetArgPointeeTest,AcceptsWideCharPointer)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);
871 std::wstring str;
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.
TEST(SetArgumentPointeeTest,SetsTheNthPointee)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.
Nullary()898 int Nullary() { return 1; }
899
900 class NullaryFunctor {
901 public:
operator ()()902 int operator()() { return 2; }
903 };
904
905 bool g_done = false;
VoidNullary()906 void VoidNullary() { g_done = true; }
907
908 class VoidNullaryFunctor {
909 public:
operator ()()910 void operator()() { g_done = true; }
911 };
912
Short(short n)913 short Short(short n) { return n; } // NOLINT
Char(char ch)914 char Char(char ch) { return ch; }
915
CharPtr(const char * s)916 const char* CharPtr(const char* s) { return s; }
917
Unary(int x)918 bool Unary(int x) { return x < 0; }
919
Binary(const char * input,short n)920 const char* Binary(const char* input, short n) { return input + n; } // NOLINT
921
VoidBinary(int,char)922 void VoidBinary(int, char) { g_done = true; }
923
Ternary(int x,char y,short z)924 int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
925
SumOf4(int a,int b,int c,int d)926 int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
927
928 class Foo {
929 public:
Foo()930 Foo() : value_(123) {}
931
Nullary() const932 int Nullary() const { return value_; }
933
934 private:
935 int value_;
936 };
937
938 // Tests InvokeWithoutArgs(function).
TEST(InvokeWithoutArgsTest,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));
952 EXPECT_TRUE(g_done);
953 }
954
955 // Tests InvokeWithoutArgs(functor).
TEST(InvokeWithoutArgsTest,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());
970 EXPECT_TRUE(g_done);
971 }
972
973 // Tests InvokeWithoutArgs(obj_ptr, method).
TEST(InvokeWithoutArgsTest,Method)974 TEST(InvokeWithoutArgsTest, Method) {
975 Foo foo;
976 Action<int(bool, char)> a = // NOLINT
977 InvokeWithoutArgs(&foo, &Foo::Nullary);
978 EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));
979 }
980
981 // Tests using IgnoreResult() on a polymorphic action.
TEST(IgnoreResultTest,PolymorphicAction)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
ReturnOne()989 int ReturnOne() {
990 g_done = true;
991 return 1;
992 }
993
TEST(IgnoreResultTest,MonomorphicAction)994 TEST(IgnoreResultTest, MonomorphicAction) {
995 g_done = false;
996 Action<void()> a = IgnoreResult(Invoke(ReturnOne));
997 a.Perform(std::make_tuple());
998 EXPECT_TRUE(g_done);
999 }
1000
1001 // Tests using IgnoreResult() on an action that returns a class type.
1002
ReturnMyNonDefaultConstructible(double)1003 MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1004 g_done = true;
1005 return MyNonDefaultConstructible(42);
1006 }
1007
TEST(IgnoreResultTest,ActionReturningClass)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));
1013 EXPECT_TRUE(g_done);
1014 }
1015
TEST(AssignTest,Int)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
TEST(AssignTest,String)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
TEST(AssignTest,CompatibleTypes)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.
TEST(WithArgsTest,OneArg)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.
TEST(WithArgsTest,TwoArgs)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 {
operator ()__anonf784654d0111::ConcatAll1054 std::string operator()() const { return {}; }
1055 template <typename... I>
operator ()__anonf784654d0111::ConcatAll1056 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.
TEST(WithArgsTest,TenArgs)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:
Perform(const std::tuple<int,int> & args)1073 int Perform(const std::tuple<int, int>& args) override {
1074 return std::get<0>(args) - std::get<1>(args);
1075 }
1076 };
1077
TEST(WithArgsTest,NonInvokeAction)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.
TEST(WithArgsTest,Identity)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.
TEST(WithArgsTest,RepeatedArguments)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.
TEST(WithArgsTest,ReversedArgumentOrder)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.
TEST(WithArgsTest,ArgsOfCompatibleTypes)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.
TEST(WithArgsTest,VoidAction)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));
1121 EXPECT_TRUE(g_done);
1122 }
1123
TEST(WithArgsTest,ReturnReference)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
TEST(WithArgsTest,InnerActionWithConversion)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:
SetUp()1141 void SetUp() override { errno = 0; }
TearDown()1142 void TearDown() override { errno = 0; }
1143 };
1144
TEST_F(SetErrnoAndReturnTest,Int)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
TEST_F(SetErrnoAndReturnTest,Ptr)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
TEST_F(SetErrnoAndReturnTest,CompatibleTypes)1158 TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
1159 Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
1160 EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));
1161 EXPECT_EQ(EINVAL, errno);
1162 }
1163
1164 #endif // !GTEST_OS_WINDOWS_MOBILE
1165
1166 // Tests ByRef().
1167
1168 // Tests that the result of ByRef() is copyable.
TEST(ByRefTest,IsCopyable)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.
TEST(ByRefTest,ConstValue)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.
TEST(ByRefTest,NonConstValue)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().
TEST(ByRefTest,ExplicitType)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.
TEST(ByRefTest,PrintsCorrectly)1241 TEST(ByRefTest, PrintsCorrectly) {
1242 int n = 42;
1243 ::std::stringstream expected, actual;
1244 testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
1245 testing::internal::UniversalPrint(ByRef(n), &actual);
1246 EXPECT_EQ(expected.str(), actual.str());
1247 }
1248
1249
UniquePtrSource()1250 std::unique_ptr<int> UniquePtrSource() {
1251 return std::unique_ptr<int>(new int(19));
1252 }
1253
VectorUniquePtrSource()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
TEST(MockMethodTest,CanReturnMoveOnlyValue_Return)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
TEST(MockMethodTest,CanReturnMoveOnlyValue_DoAllReturn)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
TEST(MockMethodTest,CanReturnMoveOnlyValue_Invoke)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
TEST(MockMethodTest,CanTakeMoveOnlyValue)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
Add(int val,int & ref,int * ptr)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
Deref(std::unique_ptr<int> ptr)1371 int Deref(std::unique_ptr<int> ptr) { return *ptr; }
1372
1373 struct Double {
1374 template <typename T>
operator ()__anonf784654d0111::Double1375 T operator()(T t) { return 2 * t; }
1376 };
1377
UniqueInt(int i)1378 std::unique_ptr<int> UniqueInt(int i) {
1379 return std::unique_ptr<int>(new int(i));
1380 }
1381
TEST(FunctorActionTest,ActionFromFunction)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
TEST(FunctorActionTest,ActionFromLambda)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
TEST(FunctorActionTest,PolymorphicFunctor)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
TEST(FunctorActionTest,TypeConversion)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
TEST(FunctorActionTest,UnusedArguments)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.
TEST(MoveOnlyArgumentsTest,ReturningActions)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
1462