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