gmock-actions_test.cc 44.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)

// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the built-in actions.

36
#include "gmock/gmock-actions.h"
37
38
#include <algorithm>
#include <iterator>
39
#include <memory>
40
#include <string>
41
42
43
44
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
45
46
47
48
49
50
51

namespace {

// This list should be kept sorted.
using testing::Action;
using testing::ActionInterface;
using testing::Assign;
52
using testing::ByMove;
53
using testing::ByRef;
54
55
56
57
58
59
60
61
62
63
64
using testing::DefaultValue;
using testing::DoDefault;
using testing::IgnoreResult;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::MakePolymorphicAction;
using testing::Ne;
using testing::PolymorphicAction;
using testing::Return;
using testing::ReturnNull;
using testing::ReturnRef;
65
using testing::ReturnRefOfCopy;
66
using testing::SetArgPointee;
67
using testing::SetArgumentPointee;
68
69
70
71
72
73
74
75
using testing::_;
using testing::get;
using testing::internal::BuiltInDefaultValue;
using testing::internal::Int64;
using testing::internal::UInt64;
using testing::make_tuple;
using testing::tuple;
using testing::tuple_element;
76

77
#if !GTEST_OS_WINDOWS_MOBILE
78
using testing::SetErrnoAndReturn;
79
#endif
80

81
#if GTEST_HAS_PROTOBUF_
82
using testing::internal::TestMessage;
83
#endif  // GTEST_HAS_PROTOBUF_
84
85
86
87
88
89
90
91

// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
  EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL);
  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL);
  EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL);
}

92
93
94
95
96
97
98
// Tests that BuiltInDefaultValue<T*>::Exists() return true.
TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
  EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
}

99
100
101
// Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
// built-in numeric type.
TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
102
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
103
104
  EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
  EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
105
#if GMOCK_HAS_SIGNED_WCHAR_T_
106
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get());
107
  EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get());
108
109
#endif
#if GMOCK_WCHAR_T_IS_NATIVE_
110
#if !defined(__WCHAR_UNSIGNED__)
111
  EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
112
113
114
#else
  EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
#endif
115
#endif
116
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get());  // NOLINT
117
118
  EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get());  // NOLINT
  EXPECT_EQ(0, BuiltInDefaultValue<short>::Get());  // NOLINT
119
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
120
121
  EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
  EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
122
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get());  // NOLINT
123
124
  EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get());  // NOLINT
  EXPECT_EQ(0, BuiltInDefaultValue<long>::Get());  // NOLINT
125
  EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get());
126
127
128
129
130
  EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get());
  EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
  EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
}

131
132
133
134
135
136
// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
// built-in numeric type.
TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
  EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
137
#if GMOCK_HAS_SIGNED_WCHAR_T_
138
139
  EXPECT_TRUE(BuiltInDefaultValue<unsigned wchar_t>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<signed wchar_t>::Exists());
140
141
#endif
#if GMOCK_WCHAR_T_IS_NATIVE_
142
  EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
143
#endif
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
  EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists());  // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists());  // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<short>::Exists());  // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists());  // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists());  // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<long>::Exists());  // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
}

159
160
161
162
163
// Tests that BuiltInDefaultValue<bool>::Get() returns false.
TEST(BuiltInDefaultValueTest, IsFalseForBool) {
  EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
}

164
165
166
167
168
// Tests that BuiltInDefaultValue<bool>::Exists() returns true.
TEST(BuiltInDefaultValueTest, BoolExists) {
  EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
}

169
170
171
172
173
174
175
176
177
178
// Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
// string type.
TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
#if GTEST_HAS_GLOBAL_STRING
  EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get());
#endif  // GTEST_HAS_GLOBAL_STRING

  EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
}

179
180
181
182
183
184
185
186
187
188
// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
// string type.
TEST(BuiltInDefaultValueTest, ExistsForString) {
#if GTEST_HAS_GLOBAL_STRING
  EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists());
#endif  // GTEST_HAS_GLOBAL_STRING

  EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
}

189
190
191
192
193
194
195
196
197
// Tests that BuiltInDefaultValue<const T>::Get() returns the same
// value as BuiltInDefaultValue<T>::Get() does.
TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
  EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
  EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
  EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL);
  EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
}

198
199
200
201
202
203
// A type that's default constructible.
class MyDefaultConstructible {
 public:
  MyDefaultConstructible() : value_(42) {}

  int value() const { return value_; }
204

205
206
 private:
  int value_;
207
208
};

209
210
211
212
213
214
215
216
217
218
219
220
// A type that's not default constructible.
class MyNonDefaultConstructible {
 public:
  // Does not have a default ctor.
  explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}

  int value() const { return value_; }

 private:
  int value_;
};

221
#if GTEST_LANG_CXX11
222
223
224
225
226
227
228
229
230

TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
  EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
}

TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
  EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
}

231
#endif  // GTEST_LANG_CXX11
232
233
234

TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
  EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
235
236
}

237
238
// Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
239
  EXPECT_DEATH_IF_SUPPORTED({
240
241
    BuiltInDefaultValue<int&>::Get();
  }, "");
242
  EXPECT_DEATH_IF_SUPPORTED({
243
244
245
246
    BuiltInDefaultValue<const char&>::Get();
  }, "");
}

247
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
248
  EXPECT_DEATH_IF_SUPPORTED({
249
    BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
250
251
252
253
254
255
  }, "");
}

// Tests that DefaultValue<T>::IsSet() is false initially.
TEST(DefaultValueTest, IsInitiallyUnset) {
  EXPECT_FALSE(DefaultValue<int>::IsSet());
256
257
  EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
258
259
260
261
}

// Tests that DefaultValue<T> can be set and then unset.
TEST(DefaultValueTest, CanBeSetAndUnset) {
262
  EXPECT_TRUE(DefaultValue<int>::Exists());
263
  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
264

265
  DefaultValue<int>::Set(1);
266
267
  DefaultValue<const MyNonDefaultConstructible>::Set(
      MyNonDefaultConstructible(42));
268
269

  EXPECT_EQ(1, DefaultValue<int>::Get());
270
  EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
271

272
  EXPECT_TRUE(DefaultValue<int>::Exists());
273
  EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
274

275
  DefaultValue<int>::Clear();
276
  DefaultValue<const MyNonDefaultConstructible>::Clear();
277
278

  EXPECT_FALSE(DefaultValue<int>::IsSet());
279
  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
280
281

  EXPECT_TRUE(DefaultValue<int>::Exists());
282
  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
283
284
285
286
287
288
289
}

// Tests that DefaultValue<T>::Get() returns the
// BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
// false.
TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
  EXPECT_FALSE(DefaultValue<int>::IsSet());
290
  EXPECT_TRUE(DefaultValue<int>::Exists());
291
292
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
293
294
295

  EXPECT_EQ(0, DefaultValue<int>::Get());

296
  EXPECT_DEATH_IF_SUPPORTED({
297
    DefaultValue<MyNonDefaultConstructible>::Get();
298
299
300
  }, "");
}

301
#if GTEST_HAS_STD_UNIQUE_PTR_
302
303
304
TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == NULL);
305
306
307
308
309
310
311
  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
    return std::unique_ptr<int>(new int(42));
  });
  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
  std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
  EXPECT_EQ(42, *i);
}
312
#endif  // GTEST_HAS_STD_UNIQUE_PTR_
313

314
315
316
317
318
319
320
321
322
323
// Tests that DefaultValue<void>::Get() returns void.
TEST(DefaultValueTest, GetWorksForVoid) {
  return DefaultValue<void>::Get();
}

// Tests using DefaultValue with a reference type.

// Tests that DefaultValue<T&>::IsSet() is false initially.
TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
  EXPECT_FALSE(DefaultValue<int&>::IsSet());
324
325
  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
326
327
}

328
329
330
// Tests that DefaultValue<T&>::Exists is false initiallly.
TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
  EXPECT_FALSE(DefaultValue<int&>::Exists());
331
332
  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
333
334
}

335
336
337
338
// Tests that DefaultValue<T&> can be set and then unset.
TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
  int n = 1;
  DefaultValue<const int&>::Set(n);
339
340
  MyNonDefaultConstructible x(42);
  DefaultValue<MyNonDefaultConstructible&>::Set(x);
341

342
  EXPECT_TRUE(DefaultValue<const int&>::Exists());
343
  EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
344

345
  EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
346
  EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
347
348

  DefaultValue<const int&>::Clear();
349
  DefaultValue<MyNonDefaultConstructible&>::Clear();
350

351
  EXPECT_FALSE(DefaultValue<const int&>::Exists());
352
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
353

354
  EXPECT_FALSE(DefaultValue<const int&>::IsSet());
355
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
356
357
358
359
360
361
362
}

// Tests that DefaultValue<T&>::Get() returns the
// BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
// false.
TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
  EXPECT_FALSE(DefaultValue<int&>::IsSet());
363
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
364

365
  EXPECT_DEATH_IF_SUPPORTED({
366
367
    DefaultValue<int&>::Get();
  }, "");
368
  EXPECT_DEATH_IF_SUPPORTED({
369
    DefaultValue<MyNonDefaultConstructible>::Get();
370
371
372
373
374
375
  }, "");
}

// Tests that ActionInterface can be implemented by defining the
// Perform method.

376
typedef int MyGlobalFunction(bool, int);
377

378
class MyActionImpl : public ActionInterface<MyGlobalFunction> {
379
380
381
382
383
384
385
386
 public:
  virtual int Perform(const tuple<bool, int>& args) {
    return get<0>(args) ? get<1>(args) : 0;
  }
};

TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
  MyActionImpl my_action_impl;
387
  (void)my_action_impl;
388
389
390
}

TEST(ActionInterfaceTest, MakeAction) {
391
  Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
392
393
394
395
396
397
398
399
400
401
402
403

  // When exercising the Perform() method of Action<F>, we must pass
  // it a tuple whose size and type are compatible with F's argument
  // types.  For example, if F is int(), then Perform() takes a
  // 0-tuple; if F is void(bool, int), then Perform() takes a
  // tuple<bool, int>, and so on.
  EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
}

// Tests that Action<F> can be contructed from a pointer to
// ActionInterface<F>.
TEST(ActionTest, CanBeConstructedFromActionInterface) {
404
  Action<MyGlobalFunction> action(new MyActionImpl);
405
406
407
408
}

// Tests that Action<F> delegates actual work to ActionInterface<F>.
TEST(ActionTest, DelegatesWorkToActionInterface) {
409
  const Action<MyGlobalFunction> action(new MyActionImpl);
410
411
412
413
414
415
416

  EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
  EXPECT_EQ(0, action.Perform(make_tuple(false, 1)));
}

// Tests that Action<F> can be copied.
TEST(ActionTest, IsCopyable) {
417
418
  Action<MyGlobalFunction> a1(new MyActionImpl);
  Action<MyGlobalFunction> a2(a1);  // Tests the copy constructor.
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448

  // a1 should continue to work after being copied from.
  EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
  EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));

  // a2 should work like the action it was copied from.
  EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
  EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));

  a2 = a1;  // Tests the assignment operator.

  // a1 should continue to work after being copied from.
  EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
  EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));

  // a2 should work like the action it was copied from.
  EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
  EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
}

// Tests that an Action<From> object can be converted to a
// compatible Action<To> object.

class IsNotZero : public ActionInterface<bool(int)> {  // NOLINT
 public:
  virtual bool Perform(const tuple<int>& arg) {
    return get<0>(arg) != 0;
  }
};

449
450
451
452
453
454
#if !GTEST_OS_SYMBIAN
// Compiling this test on Nokia's Symbian compiler fails with:
//  'Result' is not a member of class 'testing::internal::Function<int>'
//  (point of instantiation: '@unnamed@gmock_actions_test_cc@::
//      ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()')
// with no obvious fix.
455
456
457
458
459
460
TEST(ActionTest, CanBeConvertedToOtherActionType) {
  const Action<bool(int)> a1(new IsNotZero);  // NOLINT
  const Action<int(char)> a2 = Action<int(char)>(a1);  // NOLINT
  EXPECT_EQ(1, a2.Perform(make_tuple('a')));
  EXPECT_EQ(0, a2.Perform(make_tuple('\0')));
}
461
#endif  // !GTEST_OS_SYMBIAN
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544

// The following two classes are for testing MakePolymorphicAction().

// Implements a polymorphic action that returns the second of the
// arguments it receives.
class ReturnSecondArgumentAction {
 public:
  // We want to verify that MakePolymorphicAction() can work with a
  // polymorphic action whose Perform() method template is either
  // const or not.  This lets us verify the non-const case.
  template <typename Result, typename ArgumentTuple>
  Result Perform(const ArgumentTuple& args) { return get<1>(args); }
};

// Implements a polymorphic action that can be used in a nullary
// function to return 0.
class ReturnZeroFromNullaryFunctionAction {
 public:
  // For testing that MakePolymorphicAction() works when the
  // implementation class' Perform() method template takes only one
  // template parameter.
  //
  // We want to verify that MakePolymorphicAction() can work with a
  // polymorphic action whose Perform() method template is either
  // const or not.  This lets us verify the const case.
  template <typename Result>
  Result Perform(const tuple<>&) const { return 0; }
};

// These functions verify that MakePolymorphicAction() returns a
// PolymorphicAction<T> where T is the argument's type.

PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
  return MakePolymorphicAction(ReturnSecondArgumentAction());
}

PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
ReturnZeroFromNullaryFunction() {
  return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
}

// Tests that MakePolymorphicAction() turns a polymorphic action
// implementation class into a polymorphic action.
TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
  Action<int(bool, int, double)> a1 = ReturnSecondArgument();  // NOLINT
  EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0)));
}

// Tests that MakePolymorphicAction() works when the implementation
// class' Perform() method template has only one template parameter.
TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
  Action<int()> a1 = ReturnZeroFromNullaryFunction();
  EXPECT_EQ(0, a1.Perform(make_tuple()));

  Action<void*()> a2 = ReturnZeroFromNullaryFunction();
  EXPECT_TRUE(a2.Perform(make_tuple()) == NULL);
}

// Tests that Return() works as an action for void-returning
// functions.
TEST(ReturnTest, WorksForVoid) {
  const Action<void(int)> ret = Return();  // NOLINT
  return ret.Perform(make_tuple(1));
}

// Tests that Return(v) returns v.
TEST(ReturnTest, ReturnsGivenValue) {
  Action<int()> ret = Return(1);  // NOLINT
  EXPECT_EQ(1, ret.Perform(make_tuple()));

  ret = Return(-5);
  EXPECT_EQ(-5, ret.Perform(make_tuple()));
}

// Tests that Return("string literal") works.
TEST(ReturnTest, AcceptsStringLiteral) {
  Action<const char*()> a1 = Return("Hello");
  EXPECT_STREQ("Hello", a1.Perform(make_tuple()));

  Action<std::string()> a2 = Return("world");
  EXPECT_EQ("world", a2.Perform(make_tuple()));
}

545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// Test struct which wraps a vector of integers. Used in
// 'SupportsWrapperReturnType' test.
struct IntegerVectorWrapper {
  std::vector<int> * v;
  IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {}  // NOLINT
};

// Tests that Return() works when return type is a wrapper type.
TEST(ReturnTest, SupportsWrapperReturnType) {
  // Initialize vector of integers.
  std::vector<int> v;
  for (int i = 0; i < 5; ++i) v.push_back(i);

  // Return() called with 'v' as argument. The Action will return the same data
  // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
  Action<IntegerVectorWrapper()> a = Return(v);
  const std::vector<int>& result = *(a.Perform(make_tuple()).v);
  EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4));
}

565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// Tests that Return(v) is covaraint.

struct Base {
  bool operator==(const Base&) { return true; }
};

struct Derived : public Base {
  bool operator==(const Derived&) { return true; }
};

TEST(ReturnTest, IsCovariant) {
  Base base;
  Derived derived;
  Action<Base*()> ret = Return(&base);
  EXPECT_EQ(&base, ret.Perform(make_tuple()));

  ret = Return(&derived);
  EXPECT_EQ(&derived, ret.Perform(make_tuple()));
}

585
586
587
588
589
590
// Tests that the type of the value passed into Return is converted into T
// when the action is cast to Action<T(...)> rather than when the action is
// performed. See comments on testing::internal::ReturnAction in
// gmock-actions.h for more information.
class FromType {
 public:
591
  explicit FromType(bool* is_converted) : converted_(is_converted) {}
592
593
594
595
  bool* converted() const { return converted_; }

 private:
  bool* const converted_;
596
597

  GTEST_DISALLOW_ASSIGN_(FromType);
598
599
600
601
};

class ToType {
 public:
602
603
  // Must allow implicit conversion due to use in ImplicitCast_<T>.
  ToType(const FromType& x) { *x.converted() = true; }  // NOLINT
604
605
606
607
608
609
610
611
612
613
614
};

TEST(ReturnTest, ConvertsArgumentWhenConverted) {
  bool converted = false;
  FromType x(&converted);
  Action<ToType()> action(Return(x));
  EXPECT_TRUE(converted) << "Return must convert its argument in its own "
                         << "conversion operator.";
  converted = false;
  action.Perform(tuple<>());
  EXPECT_FALSE(converted) << "Action must NOT convert its argument "
615
                          << "when performed.";
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
}

class DestinationType {};

class SourceType {
 public:
  // Note: a non-const typecast operator.
  operator DestinationType() { return DestinationType(); }
};

TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
  SourceType s;
  Action<DestinationType()> action(Return(s));
}

631
632
633
634
635
636
637
638
639
// Tests that ReturnNull() returns NULL in a pointer-returning function.
TEST(ReturnNullTest, WorksInPointerReturningFunction) {
  const Action<int*()> a1 = ReturnNull();
  EXPECT_TRUE(a1.Perform(make_tuple()) == NULL);

  const Action<const char*(bool)> a2 = ReturnNull();  // NOLINT
  EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL);
}

640
641
642
643
644
645
646
647
648
649
650
651
#if GTEST_HAS_STD_UNIQUE_PTR_
// Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
// functions.
TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
  const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
  EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr);

  const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
  EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr);
}
#endif  // GTEST_HAS_STD_UNIQUE_PTR_

652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
// Tests that ReturnRef(v) works for reference types.
TEST(ReturnRefTest, WorksForReference) {
  const int n = 0;
  const Action<const int&(bool)> ret = ReturnRef(n);  // NOLINT

  EXPECT_EQ(&n, &ret.Perform(make_tuple(true)));
}

// Tests that ReturnRef(v) is covariant.
TEST(ReturnRefTest, IsCovariant) {
  Base base;
  Derived derived;
  Action<Base&()> a = ReturnRef(base);
  EXPECT_EQ(&base, &a.Perform(make_tuple()));

  a = ReturnRef(derived);
  EXPECT_EQ(&derived, &a.Perform(make_tuple()));
}

671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
// Tests that ReturnRefOfCopy(v) works for reference types.
TEST(ReturnRefOfCopyTest, WorksForReference) {
  int n = 42;
  const Action<const int&()> ret = ReturnRefOfCopy(n);

  EXPECT_NE(&n, &ret.Perform(make_tuple()));
  EXPECT_EQ(42, ret.Perform(make_tuple()));

  n = 43;
  EXPECT_NE(&n, &ret.Perform(make_tuple()));
  EXPECT_EQ(42, ret.Perform(make_tuple()));
}

// Tests that ReturnRefOfCopy(v) is covariant.
TEST(ReturnRefOfCopyTest, IsCovariant) {
  Base base;
  Derived derived;
  Action<Base&()> a = ReturnRefOfCopy(base);
  EXPECT_NE(&base, &a.Perform(make_tuple()));

  a = ReturnRefOfCopy(derived);
  EXPECT_NE(&derived, &a.Perform(make_tuple()));
}

695
696
697
698
// Tests that DoDefault() does the default action for the mock method.

class MockClass {
 public:
699
700
  MockClass() {}

701
  MOCK_METHOD1(IntFunc, int(bool flag));  // NOLINT
702
  MOCK_METHOD0(Foo, MyNonDefaultConstructible());
703
#if GTEST_HAS_STD_UNIQUE_PTR_
704
  MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
705
  MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
706
  MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
Gennadiy Civil's avatar
Gennadiy Civil committed
707
  MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
708
#endif
709
710
711

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
712
713
714
715
716
717
718
719
720
721
722
};

// Tests that DoDefault() returns the built-in default value for the
// return type by default.
TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
  MockClass mock;
  EXPECT_CALL(mock, IntFunc(_))
      .WillOnce(DoDefault());
  EXPECT_EQ(0, mock.IntFunc(true));
}

723
724
// Tests that DoDefault() throws (when exceptions are enabled) or aborts
// the process when there is no built-in default value for the return type.
725
726
727
728
TEST(DoDefaultDeathTest, DiesForUnknowType) {
  MockClass mock;
  EXPECT_CALL(mock, Foo())
      .WillRepeatedly(DoDefault());
729
730
731
#if GTEST_HAS_EXCEPTIONS
  EXPECT_ANY_THROW(mock.Foo());
#else
732
  EXPECT_DEATH_IF_SUPPORTED({
733
734
    mock.Foo();
  }, "");
735
#endif
736
737
738
739
740
}

// Tests that using DoDefault() inside a composite action leads to a
// run-time error.

741
void VoidFunc(bool /* flag */) {}
742
743
744
745
746
747
748
749
750
751
752

TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
  MockClass mock;
  EXPECT_CALL(mock, IntFunc(_))
      .WillRepeatedly(DoAll(Invoke(VoidFunc),
                            DoDefault()));

  // Ideally we should verify the error message as well.  Sadly,
  // EXPECT_DEATH() can only capture stderr, while Google Mock's
  // errors are printed on stdout.  Therefore we have to settle for
  // not verifying the message.
753
  EXPECT_DEATH_IF_SUPPORTED({
754
755
756
757
758
    mock.IntFunc(true);
  }, "");
}

// Tests that DoDefault() returns the default value set by
Troy Holsapple's avatar
Troy Holsapple committed
759
// DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
  DefaultValue<int>::Set(1);
  MockClass mock;
  EXPECT_CALL(mock, IntFunc(_))
      .WillOnce(DoDefault());
  EXPECT_EQ(1, mock.IntFunc(false));
  DefaultValue<int>::Clear();
}

// Tests that DoDefault() does the action specified by ON_CALL().
TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
  MockClass mock;
  ON_CALL(mock, IntFunc(_))
      .WillByDefault(Return(2));
  EXPECT_CALL(mock, IntFunc(_))
      .WillOnce(DoDefault());
  EXPECT_EQ(2, mock.IntFunc(false));
}

// Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
TEST(DoDefaultTest, CannotBeUsedInOnCall) {
  MockClass mock;
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    ON_CALL(mock, IntFunc(_))
      .WillByDefault(DoDefault());
  }, "DoDefault() cannot be used in ON_CALL()");
}

788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// Tests that SetArgPointee<N>(v) sets the variable pointed to by
// the N-th (0-based) argument to v.
TEST(SetArgPointeeTest, SetsTheNthPointee) {
  typedef void MyFunction(bool, int*, char*);
  Action<MyFunction> a = SetArgPointee<1>(2);

  int n = 0;
  char ch = '\0';
  a.Perform(make_tuple(true, &n, &ch));
  EXPECT_EQ(2, n);
  EXPECT_EQ('\0', ch);

  a = SetArgPointee<2>('a');
  n = 0;
  ch = '\0';
  a.Perform(make_tuple(true, &n, &ch));
  EXPECT_EQ(0, n);
  EXPECT_EQ('a', ch);
}

808
#if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
809
// Tests that SetArgPointee<N>() accepts a string literal.
810
// GCC prior to v4.0 and the Symbian compiler do not support this.
811
TEST(SetArgPointeeTest, AcceptsStringLiteral) {
812
813
  typedef void MyFunction(std::string*, const char**);
  Action<MyFunction> a = SetArgPointee<0>("hi");
814
815
  std::string str;
  const char* ptr = NULL;
816
  a.Perform(make_tuple(&str, &ptr));
817
818
819
  EXPECT_EQ("hi", str);
  EXPECT_TRUE(ptr == NULL);

820
  a = SetArgPointee<1>("world");
821
  str = "";
822
  a.Perform(make_tuple(&str, &ptr));
823
824
825
826
  EXPECT_EQ("", str);
  EXPECT_STREQ("world", ptr);
}

827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
  typedef void MyFunction(const wchar_t**);
  Action<MyFunction> a = SetArgPointee<0>(L"world");
  const wchar_t* ptr = NULL;
  a.Perform(make_tuple(&ptr));
  EXPECT_STREQ(L"world", ptr);

# if GTEST_HAS_STD_WSTRING

  typedef void MyStringFunction(std::wstring*);
  Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
  std::wstring str = L"";
  a2.Perform(make_tuple(&str));
  EXPECT_EQ(L"world", str);

# endif
}
#endif

846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
// Tests that SetArgPointee<N>() accepts a char pointer.
TEST(SetArgPointeeTest, AcceptsCharPointer) {
  typedef void MyFunction(bool, std::string*, const char**);
  const char* const hi = "hi";
  Action<MyFunction> a = SetArgPointee<1>(hi);
  std::string str;
  const char* ptr = NULL;
  a.Perform(make_tuple(true, &str, &ptr));
  EXPECT_EQ("hi", str);
  EXPECT_TRUE(ptr == NULL);

  char world_array[] = "world";
  char* const world = world_array;
  a = SetArgPointee<2>(world);
  str = "";
  a.Perform(make_tuple(true, &str, &ptr));
  EXPECT_EQ("", str);
  EXPECT_EQ(world, ptr);
}

866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
  typedef void MyFunction(bool, const wchar_t**);
  const wchar_t* const hi = L"hi";
  Action<MyFunction> a = SetArgPointee<1>(hi);
  const wchar_t* ptr = NULL;
  a.Perform(make_tuple(true, &ptr));
  EXPECT_EQ(hi, ptr);

# if GTEST_HAS_STD_WSTRING

  typedef void MyStringFunction(bool, std::wstring*);
  wchar_t world_array[] = L"world";
  wchar_t* const world = world_array;
  Action<MyStringFunction> a2 = SetArgPointee<1>(world);
  std::wstring str;
  a2.Perform(make_tuple(true, &str));
  EXPECT_EQ(world_array, str);
# endif
}

886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
#if GTEST_HAS_PROTOBUF_

// Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf
// variable pointed to by the N-th (0-based) argument to proto_buffer.
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
  TestMessage* const msg = new TestMessage;
  msg->set_member("yes");
  TestMessage orig_msg;
  orig_msg.CopyFrom(*msg);

  Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg);
  // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
  // s.t. the action works even when the original proto_buffer has
  // died.  We ensure this behavior by deleting msg before using the
  // action.
  delete msg;

  TestMessage dest;
  EXPECT_FALSE(orig_msg.Equals(dest));
  a.Perform(make_tuple(true, &dest));
  EXPECT_TRUE(orig_msg.Equals(dest));
}

// Tests that SetArgPointee<N>(proto_buffer) sets the
// ::ProtocolMessage variable pointed to by the N-th (0-based)
// argument to proto_buffer.
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
  TestMessage* const msg = new TestMessage;
  msg->set_member("yes");
  TestMessage orig_msg;
  orig_msg.CopyFrom(*msg);

  Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg);
  // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
  // s.t. the action works even when the original proto_buffer has
  // died.  We ensure this behavior by deleting msg before using the
  // action.
  delete msg;

  TestMessage dest;
  ::ProtocolMessage* const dest_base = &dest;
  EXPECT_FALSE(orig_msg.Equals(dest));
  a.Perform(make_tuple(true, dest_base));
  EXPECT_TRUE(orig_msg.Equals(dest));
}

// Tests that SetArgPointee<N>(proto2_buffer) sets the v2
// protobuf variable pointed to by the N-th (0-based) argument to
// proto2_buffer.
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
  using testing::internal::FooMessage;
  FooMessage* const msg = new FooMessage;
  msg->set_int_field(2);
  msg->set_string_field("hi");
  FooMessage orig_msg;
  orig_msg.CopyFrom(*msg);

  Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg);
  // SetArgPointee<N>(proto2_buffer) makes a copy of
  // proto2_buffer s.t. the action works even when the original
  // proto2_buffer has died.  We ensure this behavior by deleting msg
  // before using the action.
  delete msg;

  FooMessage dest;
  dest.set_int_field(0);
  a.Perform(make_tuple(true, &dest));
  EXPECT_EQ(2, dest.int_field());
  EXPECT_EQ("hi", dest.string_field());
}

// Tests that SetArgPointee<N>(proto2_buffer) sets the
// proto2::Message variable pointed to by the N-th (0-based) argument
// to proto2_buffer.
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
  using testing::internal::FooMessage;
  FooMessage* const msg = new FooMessage;
  msg->set_int_field(2);
  msg->set_string_field("hi");
  FooMessage orig_msg;
  orig_msg.CopyFrom(*msg);

  Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg);
  // SetArgPointee<N>(proto2_buffer) makes a copy of
  // proto2_buffer s.t. the action works even when the original
  // proto2_buffer has died.  We ensure this behavior by deleting msg
  // before using the action.
  delete msg;

  FooMessage dest;
  dest.set_int_field(0);
  ::proto2::Message* const dest_base = &dest;
  a.Perform(make_tuple(true, dest_base));
  EXPECT_EQ(2, dest.int_field());
  EXPECT_EQ("hi", dest.string_field());
}

#endif  // GTEST_HAS_PROTOBUF_

985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
// the N-th (0-based) argument to v.
TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
  typedef void MyFunction(bool, int*, char*);
  Action<MyFunction> a = SetArgumentPointee<1>(2);

  int n = 0;
  char ch = '\0';
  a.Perform(make_tuple(true, &n, &ch));
  EXPECT_EQ(2, n);
  EXPECT_EQ('\0', ch);

  a = SetArgumentPointee<2>('a');
  n = 0;
  ch = '\0';
  a.Perform(make_tuple(true, &n, &ch));
  EXPECT_EQ(0, n);
  EXPECT_EQ('a', ch);
}

1005
#if GTEST_HAS_PROTOBUF_
1006

1007
1008
// Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf
// variable pointed to by the N-th (0-based) argument to proto_buffer.
1009
1010
1011
1012
1013
1014
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
  TestMessage* const msg = new TestMessage;
  msg->set_member("yes");
  TestMessage orig_msg;
  orig_msg.CopyFrom(*msg);

1015
  Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg);
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
  // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
  // s.t. the action works even when the original proto_buffer has
  // died.  We ensure this behavior by deleting msg before using the
  // action.
  delete msg;

  TestMessage dest;
  EXPECT_FALSE(orig_msg.Equals(dest));
  a.Perform(make_tuple(true, &dest));
  EXPECT_TRUE(orig_msg.Equals(dest));
}

1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
// Tests that SetArgumentPointee<N>(proto_buffer) sets the
// ::ProtocolMessage variable pointed to by the N-th (0-based)
// argument to proto_buffer.
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
  TestMessage* const msg = new TestMessage;
  msg->set_member("yes");
  TestMessage orig_msg;
  orig_msg.CopyFrom(*msg);

  Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg);
  // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
  // s.t. the action works even when the original proto_buffer has
  // died.  We ensure this behavior by deleting msg before using the
  // action.
  delete msg;

  TestMessage dest;
  ::ProtocolMessage* const dest_base = &dest;
  EXPECT_FALSE(orig_msg.Equals(dest));
  a.Perform(make_tuple(true, dest_base));
  EXPECT_TRUE(orig_msg.Equals(dest));
}

// Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2
// protobuf variable pointed to by the N-th (0-based) argument to
// proto2_buffer.
1054
1055
1056
1057
1058
1059
1060
1061
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
  using testing::internal::FooMessage;
  FooMessage* const msg = new FooMessage;
  msg->set_int_field(2);
  msg->set_string_field("hi");
  FooMessage orig_msg;
  orig_msg.CopyFrom(*msg);

1062
  Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg);
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
  // SetArgumentPointee<N>(proto2_buffer) makes a copy of
  // proto2_buffer s.t. the action works even when the original
  // proto2_buffer has died.  We ensure this behavior by deleting msg
  // before using the action.
  delete msg;

  FooMessage dest;
  dest.set_int_field(0);
  a.Perform(make_tuple(true, &dest));
  EXPECT_EQ(2, dest.int_field());
  EXPECT_EQ("hi", dest.string_field());
}

1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
// Tests that SetArgumentPointee<N>(proto2_buffer) sets the
// proto2::Message variable pointed to by the N-th (0-based) argument
// to proto2_buffer.
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
  using testing::internal::FooMessage;
  FooMessage* const msg = new FooMessage;
  msg->set_int_field(2);
  msg->set_string_field("hi");
  FooMessage orig_msg;
  orig_msg.CopyFrom(*msg);

  Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg);
  // SetArgumentPointee<N>(proto2_buffer) makes a copy of
  // proto2_buffer s.t. the action works even when the original
  // proto2_buffer has died.  We ensure this behavior by deleting msg
  // before using the action.
  delete msg;

  FooMessage dest;
  dest.set_int_field(0);
  ::proto2::Message* const dest_base = &dest;
  a.Perform(make_tuple(true, dest_base));
  EXPECT_EQ(2, dest.int_field());
  EXPECT_EQ("hi", dest.string_field());
}

1102
#endif  // GTEST_HAS_PROTOBUF_
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124

// Sample functions and functors for testing Invoke() and etc.
int Nullary() { return 1; }

class NullaryFunctor {
 public:
  int operator()() { return 2; }
};

bool g_done = false;
void VoidNullary() { g_done = true; }

class VoidNullaryFunctor {
 public:
  void operator()() { g_done = true; }
};

class Foo {
 public:
  Foo() : value_(123) {}

  int Nullary() const { return value_; }
1125

1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
 private:
  int value_;
};

// Tests InvokeWithoutArgs(function).
TEST(InvokeWithoutArgsTest, Function) {
  // As an action that takes one argument.
  Action<int(int)> a = InvokeWithoutArgs(Nullary);  // NOLINT
  EXPECT_EQ(1, a.Perform(make_tuple(2)));

  // As an action that takes two arguments.
1137
  Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary);  // NOLINT
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
  EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5)));

  // As an action that returns void.
  Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary);  // NOLINT
  g_done = false;
  a3.Perform(make_tuple(1));
  EXPECT_TRUE(g_done);
}

// Tests InvokeWithoutArgs(functor).
TEST(InvokeWithoutArgsTest, Functor) {
  // As an action that takes no argument.
  Action<int()> a = InvokeWithoutArgs(NullaryFunctor());  // NOLINT
  EXPECT_EQ(2, a.Perform(make_tuple()));

  // As an action that takes three arguments.
1154
  Action<int(int, double, char)> a2 =  // NOLINT
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
      InvokeWithoutArgs(NullaryFunctor());
  EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a')));

  // As an action that returns void.
  Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
  g_done = false;
  a3.Perform(make_tuple());
  EXPECT_TRUE(g_done);
}

// Tests InvokeWithoutArgs(obj_ptr, method).
TEST(InvokeWithoutArgsTest, Method) {
  Foo foo;
  Action<int(bool, char)> a =  // NOLINT
      InvokeWithoutArgs(&foo, &Foo::Nullary);
  EXPECT_EQ(123, a.Perform(make_tuple(true, 'a')));
}

// Tests using IgnoreResult() on a polymorphic action.
TEST(IgnoreResultTest, PolymorphicAction) {
  Action<void(int)> a = IgnoreResult(Return(5));  // NOLINT
  a.Perform(make_tuple(1));
}

// Tests using IgnoreResult() on a monomorphic action.

int ReturnOne() {
  g_done = true;
  return 1;
}

TEST(IgnoreResultTest, MonomorphicAction) {
  g_done = false;
  Action<void()> a = IgnoreResult(Invoke(ReturnOne));
  a.Perform(make_tuple());
  EXPECT_TRUE(g_done);
}

// Tests using IgnoreResult() on an action that returns a class type.

1195
MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1196
  g_done = true;
1197
  return MyNonDefaultConstructible(42);
1198
1199
1200
1201
}

TEST(IgnoreResultTest, ActionReturningClass) {
  g_done = false;
1202
1203
  Action<void(int)> a =
      IgnoreResult(Invoke(ReturnMyNonDefaultConstructible));  // NOLINT
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
  a.Perform(make_tuple(2));
  EXPECT_TRUE(g_done);
}

TEST(AssignTest, Int) {
  int x = 0;
  Action<void(int)> a = Assign(&x, 5);
  a.Perform(make_tuple(0));
  EXPECT_EQ(5, x);
}

TEST(AssignTest, String) {
  ::std::string x;
  Action<void(void)> a = Assign(&x, "Hello, world");
  a.Perform(make_tuple());
  EXPECT_EQ("Hello, world", x);
}

TEST(AssignTest, CompatibleTypes) {
  double x = 0;
  Action<void(int)> a = Assign(&x, 5);
  a.Perform(make_tuple(0));
  EXPECT_DOUBLE_EQ(5, x);
}

1229
#if !GTEST_OS_WINDOWS_MOBILE
1230

1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
class SetErrnoAndReturnTest : public testing::Test {
 protected:
  virtual void SetUp() { errno = 0; }
  virtual void TearDown() { errno = 0; }
};

TEST_F(SetErrnoAndReturnTest, Int) {
  Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
  EXPECT_EQ(-5, a.Perform(make_tuple()));
  EXPECT_EQ(ENOTTY, errno);
}

TEST_F(SetErrnoAndReturnTest, Ptr) {
  int x;
  Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
  EXPECT_EQ(&x, a.Perform(make_tuple()));
  EXPECT_EQ(ENOTTY, errno);
}

TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
  Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
  EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple()));
  EXPECT_EQ(EINVAL, errno);
}

1256
#endif  // !GTEST_OS_WINDOWS_MOBILE
1257

1258
1259
1260
1261
1262
1263
1264
// Tests ByRef().

// Tests that ReferenceWrapper<T> is copyable.
TEST(ByRefTest, IsCopyable) {
  const std::string s1 = "Hi";
  const std::string s2 = "Hello";

1265
1266
  ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper =
      ByRef(s1);
1267
1268
1269
1270
1271
1272
1273
1274
  const std::string& r1 = ref_wrapper;
  EXPECT_EQ(&s1, &r1);

  // Assigns a new value to ref_wrapper.
  ref_wrapper = ByRef(s2);
  const std::string& r2 = ref_wrapper;
  EXPECT_EQ(&s2, &r2);

1275
1276
  ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 =
      ByRef(s1);
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
  // Copies ref_wrapper1 to ref_wrapper.
  ref_wrapper = ref_wrapper1;
  const std::string& r3 = ref_wrapper;
  EXPECT_EQ(&s1, &r3);
}

// Tests using ByRef() on a const value.
TEST(ByRefTest, ConstValue) {
  const int n = 0;
  // int& ref = ByRef(n);  // This shouldn't compile - we have a
                           // negative compilation test to catch it.
  const int& const_ref = ByRef(n);
  EXPECT_EQ(&n, &const_ref);
}

// Tests using ByRef() on a non-const value.
TEST(ByRefTest, NonConstValue) {
  int n = 0;

  // ByRef(n) can be used as either an int&,
  int& ref = ByRef(n);
  EXPECT_EQ(&n, &ref);

  // or a const int&.
  const int& const_ref = ByRef(n);
  EXPECT_EQ(&n, &const_ref);
}

// Tests explicitly specifying the type when using ByRef().
TEST(ByRefTest, ExplicitType) {
  int n = 0;
  const int& r1 = ByRef<const int>(n);
  EXPECT_EQ(&n, &r1);

  // ByRef<char>(n);  // This shouldn't compile - we have a negative
                      // compilation test to catch it.

  Derived d;
  Derived& r2 = ByRef<Derived>(d);
  EXPECT_EQ(&d, &r2);

  const Derived& r3 = ByRef<const Derived>(d);
  EXPECT_EQ(&d, &r3);

  Base& r4 = ByRef<Base>(d);
  EXPECT_EQ(&d, &r4);

  const Base& r5 = ByRef<const Base>(d);
  EXPECT_EQ(&d, &r5);

  // The following shouldn't compile - we have a negative compilation
  // test for it.
  //
  // Base b;
  // ByRef<Derived>(b);
}

// Tests that Google Mock prints expression ByRef(x) as a reference to x.
TEST(ByRefTest, PrintsCorrectly) {
  int n = 42;
  ::std::stringstream expected, actual;
  testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
  testing::internal::UniversalPrint(ByRef(n), &actual);
  EXPECT_EQ(expected.str(), actual.str());
}

1343
#if GTEST_HAS_STD_UNIQUE_PTR_
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354

std::unique_ptr<int> UniquePtrSource() {
  return std::unique_ptr<int>(new int(19));
}

std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
  std::vector<std::unique_ptr<int>> out;
  out.emplace_back(new int(7));
  return out;
}

1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
  MockClass mock;
  std::unique_ptr<int> i(new int(19));
  EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
  EXPECT_CALL(mock, MakeVectorUnique())
      .WillOnce(Return(ByMove(VectorUniquePtrSource())));
  Derived* d = new Derived;
  EXPECT_CALL(mock, MakeUniqueBase())
      .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));

  std::unique_ptr<int> result1 = mock.MakeUnique();
  EXPECT_EQ(19, *result1);

  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1369
  EXPECT_EQ(1u, vresult.size());
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
  EXPECT_NE(nullptr, vresult[0]);
  EXPECT_EQ(7, *vresult[0]);

  std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
  EXPECT_EQ(d, result2.get());
}

TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
  testing::MockFunction<void()> mock_function;
  MockClass mock;
  std::unique_ptr<int> i(new int(19));
  EXPECT_CALL(mock_function, Call());
  EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
      InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
      Return(ByMove(std::move(i)))));

  std::unique_ptr<int> result1 = mock.MakeUnique();
  EXPECT_EQ(19, *result1);
}

TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1391
1392
1393
1394
1395
1396
1397
1398
  MockClass mock;

  // Check default value
  DefaultValue<std::unique_ptr<int>>::SetFactory([] {
    return std::unique_ptr<int>(new int(42));
  });
  EXPECT_EQ(42, *mock.MakeUnique());

1399
  EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
1400
1401
1402
1403
1404
1405
1406
1407
1408
  EXPECT_CALL(mock, MakeVectorUnique())
      .WillRepeatedly(Invoke(VectorUniquePtrSource));
  std::unique_ptr<int> result1 = mock.MakeUnique();
  EXPECT_EQ(19, *result1);
  std::unique_ptr<int> result2 = mock.MakeUnique();
  EXPECT_EQ(19, *result2);
  EXPECT_NE(result1, result2);

  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1409
  EXPECT_EQ(1u, vresult.size());
1410
1411
1412
1413
  EXPECT_NE(nullptr, vresult[0]);
  EXPECT_EQ(7, *vresult[0]);
}

1414
#endif  // GTEST_HAS_STD_UNIQUE_PTR_
1415

1416
}  // Unnamed namespace