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