gmock-actions_test.cc 71.1 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
// 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.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
29

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

34
#include "gmock/gmock-actions.h"
35

36
#include <algorithm>
37
#include <functional>
38
#include <iterator>
39
#include <memory>
Tom Hughes's avatar
Tom Hughes committed
40
#include <sstream>
41
#include <string>
Tom Hughes's avatar
Tom Hughes committed
42
#include <tuple>
43
#include <type_traits>
Tom Hughes's avatar
Tom Hughes committed
44
#include <utility>
45
#include <vector>
46

47
48
49
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest-spi.h"
50
#include "gtest/gtest.h"
51

52
53
54
55
56
57
58
59
60
// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
// length exceeded) for MSVC.
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
#if defined(_MSC_VER) && (_MSC_VER == 1900)
// and silence C4800 (C4800: 'int *const ': forcing value
// to bool 'true' or 'false') for MSVC 15
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
#endif

61
namespace testing {
62
63
namespace {

Abseil Team's avatar
Abseil Team committed
64
using ::testing::internal::BuiltInDefaultValue;
65

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
TEST(TypeTraits, Negation) {
  // Direct use with std types.
  static_assert(std::is_base_of<std::false_type,
                                internal::negation<std::true_type>>::value,
                "");

  static_assert(std::is_base_of<std::true_type,
                                internal::negation<std::false_type>>::value,
                "");

  // With other types that fit the requirement of a value member that is
  // convertible to bool.
  static_assert(std::is_base_of<
                    std::true_type,
                    internal::negation<std::integral_constant<int, 0>>>::value,
                "");

  static_assert(std::is_base_of<
                    std::false_type,
                    internal::negation<std::integral_constant<int, 1>>>::value,
                "");

  static_assert(std::is_base_of<
                    std::false_type,
                    internal::negation<std::integral_constant<int, -1>>>::value,
                "");
}

// Weird false/true types that aren't actually bool constants (but should still
// be legal according to [meta.logical] because `bool(T::value)` is valid), are
// distinct from std::false_type and std::true_type, and are distinct from other
// instantiations of the same template.
//
// These let us check finicky details mandated by the standard like
// "std::conjunction should evaluate to a type that inherits from the first
// false-y input".
template <int>
struct MyFalse : std::integral_constant<int, 0> {};

template <int>
struct MyTrue : std::integral_constant<int, -1> {};

TEST(TypeTraits, Conjunction) {
  // Base case: always true.
  static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value,
                "");

  // One predicate: inherits from that predicate, regardless of value.
  static_assert(
      std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value,
      "");

  static_assert(
      std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, "");

  // Multiple predicates, with at least one false: inherits from that one.
  static_assert(
      std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
                                                        MyTrue<2>>>::value,
      "");

  static_assert(
      std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
                                                        MyFalse<2>>>::value,
      "");

  // Short circuiting: in the case above, additional predicates need not even
  // define a value member.
  struct Empty {};
  static_assert(
      std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
                                                        Empty>>::value,
      "");

  // All predicates true: inherits from the last.
  static_assert(
      std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>,
                                                       MyTrue<2>>>::value,
      "");
}

TEST(TypeTraits, Disjunction) {
  // Base case: always false.
  static_assert(
      std::is_base_of<std::false_type, internal::disjunction<>>::value, "");

  // One predicate: inherits from that predicate, regardless of value.
  static_assert(
      std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value,
      "");

  static_assert(
      std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, "");

  // Multiple predicates, with at least one true: inherits from that one.
  static_assert(
      std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
                                                       MyFalse<2>>>::value,
      "");

  static_assert(
      std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
                                                       MyTrue<2>>>::value,
      "");

  // Short circuiting: in the case above, additional predicates need not even
  // define a value member.
  struct Empty {};
  static_assert(
      std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
                                                       Empty>>::value,
      "");

  // All predicates false: inherits from the last.
  static_assert(
      std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>,
                                                        MyFalse<2>>>::value,
      "");
}

TEST(TypeTraits, IsInvocableRV) {
  struct C {
    int operator()() const { return 0; }
    void operator()(int) & {}
    std::string operator()(int) && { return ""; };
  };

  // The first overload is callable for const and non-const rvalues and lvalues.
194
195
  // It can be used to obtain an int, cv void, or anything int is convertible
  // to.
196
197
198
199
200
201
  static_assert(internal::is_callable_r<int, C>::value, "");
  static_assert(internal::is_callable_r<int, C&>::value, "");
  static_assert(internal::is_callable_r<int, const C>::value, "");
  static_assert(internal::is_callable_r<int, const C&>::value, "");

  static_assert(internal::is_callable_r<void, C>::value, "");
202
  static_assert(internal::is_callable_r<const volatile void, C>::value, "");
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
  static_assert(internal::is_callable_r<char, C>::value, "");

  // It's possible to provide an int. If it's given to an lvalue, the result is
  // void. Otherwise it is std::string (which is also treated as allowed for a
  // void result type).
  static_assert(internal::is_callable_r<void, C&, int>::value, "");
  static_assert(!internal::is_callable_r<int, C&, int>::value, "");
  static_assert(!internal::is_callable_r<std::string, C&, int>::value, "");
  static_assert(!internal::is_callable_r<void, const C&, int>::value, "");

  static_assert(internal::is_callable_r<std::string, C, int>::value, "");
  static_assert(internal::is_callable_r<void, C, int>::value, "");
  static_assert(!internal::is_callable_r<int, C, int>::value, "");

  // It's not possible to provide other arguments.
  static_assert(!internal::is_callable_r<void, C, std::string>::value, "");
  static_assert(!internal::is_callable_r<void, C, int, int>::value, "");

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
  // In C++17 and above, where it's guaranteed that functions can return
  // non-moveable objects, everything should work fine for non-moveable rsult
  // types too.
#if defined(__cplusplus) && __cplusplus >= 201703L
  {
    struct NonMoveable {
      NonMoveable() = default;
      NonMoveable(NonMoveable&&) = delete;
    };

    static_assert(!std::is_move_constructible_v<NonMoveable>);

    struct Callable {
      NonMoveable operator()() { return NonMoveable(); }
    };

    static_assert(internal::is_callable_r<NonMoveable, Callable>::value);
    static_assert(internal::is_callable_r<void, Callable>::value);
    static_assert(
        internal::is_callable_r<const volatile void, Callable>::value);

    static_assert(!internal::is_callable_r<int, Callable>::value);
    static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);
  }
#endif  // C++17 and above

247
248
249
250
251
252
  // Nothing should choke when we try to call other arguments besides directly
  // callable objects, but they should not show up as callable.
  static_assert(!internal::is_callable_r<void, int>::value, "");
  static_assert(!internal::is_callable_r<void, void (C::*)()>::value, "");
  static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, "");
}
253
254
255

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

261
262
263
264
265
266
267
// 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());
}

268
269
270
// Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
// built-in numeric type.
TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
271
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
272
273
  EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
  EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
274
#if GMOCK_WCHAR_T_IS_NATIVE_
275
#if !defined(__WCHAR_UNSIGNED__)
276
  EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
277
278
279
#else
  EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
#endif
280
#endif
281
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get());  // NOLINT
282
283
  EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get());     // NOLINT
  EXPECT_EQ(0, BuiltInDefaultValue<short>::Get());            // NOLINT
284
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
285
286
  EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
  EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
287
288
289
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get());       // NOLINT
  EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get());          // NOLINT
  EXPECT_EQ(0, BuiltInDefaultValue<long>::Get());                 // NOLINT
Abseil Team's avatar
Abseil Team committed
290
  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get());  // NOLINT
291
292
  EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get());     // NOLINT
  EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get());            // NOLINT
293
294
295
296
  EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
  EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
}

297
298
299
300
301
302
// 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());
303
#if GMOCK_WCHAR_T_IS_NATIVE_
304
  EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
305
#endif
306
  EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists());  // NOLINT
307
308
  EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists());    // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<short>::Exists());           // NOLINT
309
310
311
  EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
312
313
314
  EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists());       // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists());         // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<long>::Exists());                // NOLINT
Abseil Team's avatar
Abseil Team committed
315
  EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists());  // NOLINT
316
317
  EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists());    // NOLINT
  EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists());           // NOLINT
318
319
320
321
  EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
  EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
}

322
323
324
325
326
// Tests that BuiltInDefaultValue<bool>::Get() returns false.
TEST(BuiltInDefaultValueTest, IsFalseForBool) {
  EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
}

327
328
329
330
331
// Tests that BuiltInDefaultValue<bool>::Exists() returns true.
TEST(BuiltInDefaultValueTest, BoolExists) {
  EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
}

332
333
334
// Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
// string type.
TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
335
  EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get());
336
337
}

338
339
340
// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
// string type.
TEST(BuiltInDefaultValueTest, ExistsForString) {
341
  EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists());
342
343
}

344
345
346
347
348
// 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());
349
  EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);
350
351
352
  EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
}

353
354
355
356
357
358
// A type that's default constructible.
class MyDefaultConstructible {
 public:
  MyDefaultConstructible() : value_(42) {}

  int value() const { return value_; }
359

360
361
 private:
  int value_;
362
363
};

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// 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_;
};

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

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

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

388
389
// Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
390
391
  EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, "");
  EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, "");
392
393
}

394
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
395
396
  EXPECT_DEATH_IF_SUPPORTED(
      { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, "");
397
398
399
400
401
}

// Tests that DefaultValue<T>::IsSet() is false initially.
TEST(DefaultValueTest, IsInitiallyUnset) {
  EXPECT_FALSE(DefaultValue<int>::IsSet());
402
403
  EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
404
405
406
407
}

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

411
  DefaultValue<int>::Set(1);
412
413
  DefaultValue<const MyNonDefaultConstructible>::Set(
      MyNonDefaultConstructible(42));
414
415

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

418
  EXPECT_TRUE(DefaultValue<int>::Exists());
419
  EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
420

421
  DefaultValue<int>::Clear();
422
  DefaultValue<const MyNonDefaultConstructible>::Clear();
423
424

  EXPECT_FALSE(DefaultValue<int>::IsSet());
425
  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
426
427

  EXPECT_TRUE(DefaultValue<int>::Exists());
428
  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
429
430
431
432
433
434
435
}

// Tests that DefaultValue<T>::Get() returns the
// BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
// false.
TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
  EXPECT_FALSE(DefaultValue<int>::IsSet());
436
  EXPECT_TRUE(DefaultValue<int>::Exists());
437
438
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
439
440
441

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

442
443
  EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
                            "");
444
445
}

446
447
TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
448
  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
449
  DefaultValue<std::unique_ptr<int>>::SetFactory(
450
      [] { return std::make_unique<int>(42); });
451
452
453
454
455
  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
  std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
  EXPECT_EQ(42, *i);
}

456
// Tests that DefaultValue<void>::Get() returns void.
457
TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); }
458
459
460
461
462
463

// Tests using DefaultValue with a reference type.

// Tests that DefaultValue<T&>::IsSet() is false initially.
TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
  EXPECT_FALSE(DefaultValue<int&>::IsSet());
464
465
  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
466
467
}

yutotnh's avatar
yutotnh committed
468
// Tests that DefaultValue<T&>::Exists is false initially.
469
470
TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
  EXPECT_FALSE(DefaultValue<int&>::Exists());
471
472
  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
473
474
}

475
476
477
478
// Tests that DefaultValue<T&> can be set and then unset.
TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
  int n = 1;
  DefaultValue<const int&>::Set(n);
479
480
  MyNonDefaultConstructible x(42);
  DefaultValue<MyNonDefaultConstructible&>::Set(x);
481

482
  EXPECT_TRUE(DefaultValue<const int&>::Exists());
483
  EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
484

485
  EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
486
  EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
487
488

  DefaultValue<const int&>::Clear();
489
  DefaultValue<MyNonDefaultConstructible&>::Clear();
490

491
  EXPECT_FALSE(DefaultValue<const int&>::Exists());
492
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
493

494
  EXPECT_FALSE(DefaultValue<const int&>::IsSet());
495
  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
496
497
498
499
500
501
502
}

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

505
506
507
  EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
  EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
                            "");
508
509
510
511
512
}

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

513
typedef int MyGlobalFunction(bool, int);
514

515
class MyActionImpl : public ActionInterface<MyGlobalFunction> {
516
 public:
Abseil Team's avatar
Abseil Team committed
517
  int Perform(const std::tuple<bool, int>& args) override {
Abseil Team's avatar
Abseil Team committed
518
    return std::get<0>(args) ? std::get<1>(args) : 0;
519
520
521
522
523
  }
};

TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
  MyActionImpl my_action_impl;
524
  (void)my_action_impl;
525
526
527
}

TEST(ActionInterfaceTest, MakeAction) {
528
  Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
529
530
531
532
533

  // 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
Abseil Team's avatar
Abseil Team committed
534
535
  // std::tuple<bool, int>, and so on.
  EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
536
537
}

slowy07's avatar
slowy07 committed
538
// Tests that Action<F> can be constructed from a pointer to
539
540
// ActionInterface<F>.
TEST(ActionTest, CanBeConstructedFromActionInterface) {
541
  Action<MyGlobalFunction> action(new MyActionImpl);
542
543
544
545
}

// Tests that Action<F> delegates actual work to ActionInterface<F>.
TEST(ActionTest, DelegatesWorkToActionInterface) {
546
  const Action<MyGlobalFunction> action(new MyActionImpl);
547

Abseil Team's avatar
Abseil Team committed
548
549
  EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
  EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1)));
550
551
552
553
}

// Tests that Action<F> can be copied.
TEST(ActionTest, IsCopyable) {
554
555
  Action<MyGlobalFunction> a1(new MyActionImpl);
  Action<MyGlobalFunction> a2(a1);  // Tests the copy constructor.
556
557

  // a1 should continue to work after being copied from.
Abseil Team's avatar
Abseil Team committed
558
559
  EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
  EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
560
561

  // a2 should work like the action it was copied from.
Abseil Team's avatar
Abseil Team committed
562
563
  EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
  EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
564
565
566
567

  a2 = a1;  // Tests the assignment operator.

  // a1 should continue to work after being copied from.
Abseil Team's avatar
Abseil Team committed
568
569
  EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
  EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
570
571

  // a2 should work like the action it was copied from.
Abseil Team's avatar
Abseil Team committed
572
573
  EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
  EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
574
575
576
577
578
579
580
}

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

class IsNotZero : public ActionInterface<bool(int)> {  // NOLINT
 public:
Abseil Team's avatar
Abseil Team committed
581
  bool Perform(const std::tuple<int>& arg) override {
Abseil Team's avatar
Abseil Team committed
582
    return std::get<0>(arg) != 0;
583
584
585
586
  }
};

TEST(ActionTest, CanBeConvertedToOtherActionType) {
587
  const Action<bool(int)> a1(new IsNotZero);           // NOLINT
588
  const Action<int(char)> a2 = Action<int(char)>(a1);  // NOLINT
Abseil Team's avatar
Abseil Team committed
589
590
  EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));
  EXPECT_EQ(0, a2.Perform(std::make_tuple('\0')));
591
592
593
594
595
596
597
598
599
600
601
602
}

// 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>
Abseil Team's avatar
Abseil Team committed
603
604
605
  Result Perform(const ArgumentTuple& args) {
    return std::get<1>(args);
  }
606
607
608
609
610
611
612
613
614
615
616
617
618
619
};

// 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>
Abseil Team's avatar
Abseil Team committed
620
621
622
  Result Perform(const std::tuple<>&) const {
    return 0;
  }
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
};

// 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
Abseil Team's avatar
Abseil Team committed
641
  EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0)));
642
643
644
645
646
647
}

// Tests that MakePolymorphicAction() works when the implementation
// class' Perform() method template has only one template parameter.
TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
  Action<int()> a1 = ReturnZeroFromNullaryFunction();
Abseil Team's avatar
Abseil Team committed
648
  EXPECT_EQ(0, a1.Perform(std::make_tuple()));
649
650

  Action<void*()> a2 = ReturnZeroFromNullaryFunction();
Abseil Team's avatar
Abseil Team committed
651
  EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr);
652
653
654
655
656
657
}

// Tests that Return() works as an action for void-returning
// functions.
TEST(ReturnTest, WorksForVoid) {
  const Action<void(int)> ret = Return();  // NOLINT
Abseil Team's avatar
Abseil Team committed
658
  return ret.Perform(std::make_tuple(1));
659
660
661
662
663
}

// Tests that Return(v) returns v.
TEST(ReturnTest, ReturnsGivenValue) {
  Action<int()> ret = Return(1);  // NOLINT
Abseil Team's avatar
Abseil Team committed
664
  EXPECT_EQ(1, ret.Perform(std::make_tuple()));
665
666

  ret = Return(-5);
Abseil Team's avatar
Abseil Team committed
667
  EXPECT_EQ(-5, ret.Perform(std::make_tuple()));
668
669
670
671
672
}

// Tests that Return("string literal") works.
TEST(ReturnTest, AcceptsStringLiteral) {
  Action<const char*()> a1 = Return("Hello");
Abseil Team's avatar
Abseil Team committed
673
  EXPECT_STREQ("Hello", a1.Perform(std::make_tuple()));
674
675

  Action<std::string()> a2 = Return("world");
Abseil Team's avatar
Abseil Team committed
676
  EXPECT_EQ("world", a2.Perform(std::make_tuple()));
677
678
}

679
680
681
682
683
684
// Return(x) should work fine when the mock function's return type is a
// reference-like wrapper for decltype(x), as when x is a std::string and the
// mock function returns std::string_view.
TEST(ReturnTest, SupportsReferenceLikeReturnType) {
  // A reference wrapper for std::vector<int>, implicitly convertible from it.
  struct Result {
685
    const std::vector<int>* v;
Tom Hughes's avatar
Tom Hughes committed
686
    Result(const std::vector<int>& vec) : v(&vec) {}  // NOLINT
687
  };
688

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
  // Set up an action for a mock function that returns the reference wrapper
  // type, initializing it with an actual vector.
  //
  // The returned wrapper should be initialized with a copy of that vector
  // that's embedded within the action itself (which should stay alive as long
  // as the mock object is alive), rather than e.g. a reference to the temporary
  // we feed to Return. This should work fine both for WillOnce and
  // WillRepeatedly.
  MockFunction<Result()> mock;
  EXPECT_CALL(mock, Call)
      .WillOnce(Return(std::vector<int>{17, 19, 23}))
      .WillRepeatedly(Return(std::vector<int>{29, 31, 37}));

  EXPECT_THAT(mock.AsStdFunction()(),
              Field(&Result::v, Pointee(ElementsAre(17, 19, 23))));

  EXPECT_THAT(mock.AsStdFunction()(),
              Field(&Result::v, Pointee(ElementsAre(29, 31, 37))));
707
708
}

709
710
711
712
713
714
715
716
717
718
TEST(ReturnTest, PrefersConversionOperator) {
  // Define types In and Out such that:
  //
  //  *  In is implicitly convertible to Out.
  //  *  Out also has an explicit constructor from In.
  //
  struct In;
  struct Out {
    int x;

Tom Hughes's avatar
Tom Hughes committed
719
    explicit Out(const int val) : x(val) {}
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
    explicit Out(const In&) : x(0) {}
  };

  struct In {
    operator Out() const { return Out{19}; }  // NOLINT
  };

  // Assumption check: the C++ language rules are such that a function that
  // returns Out which uses In a return statement will use the implicit
  // conversion path rather than the explicit constructor.
  EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19));

  // Return should work the same way: if the mock function's return type is Out
  // and we feed Return an In value, then the Out should be created through the
  // implicit conversion path rather than the explicit constructor.
  MockFunction<Out()> mock;
  EXPECT_CALL(mock, Call).WillOnce(Return(In()));
  EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19));
}

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
// It should be possible to use Return(R) with a mock function result type U
// that is convertible from const R& but *not* R (such as
// std::reference_wrapper). This should work for both WillOnce and
// WillRepeatedly.
TEST(ReturnTest, ConversionRequiresConstLvalueReference) {
  using R = int;
  using U = std::reference_wrapper<const int>;

  static_assert(std::is_convertible<const R&, U>::value, "");
  static_assert(!std::is_convertible<R, U>::value, "");

  MockFunction<U()> mock;
  EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19));

  EXPECT_EQ(17, mock.AsStdFunction()());
  EXPECT_EQ(19, mock.AsStdFunction()());
}

758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
// Return(x) should not be usable with a mock function result type that's
// implicitly convertible from decltype(x) but requires a non-const lvalue
// reference to the input. It doesn't make sense for the conversion operator to
// modify the input.
TEST(ReturnTest, ConversionRequiresMutableLvalueReference) {
  // Set up a type that is implicitly convertible from std::string&, but not
  // std::string&& or `const std::string&`.
  //
  // Avoid asserting about conversion from std::string on MSVC, which seems to
  // implement std::is_convertible incorrectly in this case.
  struct S {
    S(std::string&) {}  // NOLINT
  };

  static_assert(std::is_convertible<std::string&, S>::value, "");
#ifndef _MSC_VER
  static_assert(!std::is_convertible<std::string&&, S>::value, "");
#endif
  static_assert(!std::is_convertible<const std::string&, S>::value, "");

  // It shouldn't be possible to use the result of Return(std::string) in a
  // context where an S is needed.
780
781
782
  //
  // Here too we disable the assertion for MSVC, since its incorrect
  // implementation of is_convertible causes our SFINAE to be wrong.
783
784
785
  using RA = decltype(Return(std::string()));

  static_assert(!std::is_convertible<RA, Action<S()>>::value, "");
786
#ifndef _MSC_VER
787
  static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, "");
788
#endif
789
790
}

791
792
793
794
795
796
797
TEST(ReturnTest, MoveOnlyResultType) {
  // Return should support move-only result types when used with WillOnce.
  {
    MockFunction<std::unique_ptr<int>()> mock;
    EXPECT_CALL(mock, Call)
        // NOLINTNEXTLINE
        .WillOnce(Return(std::unique_ptr<int>(new int(17))));
798

799
800
    EXPECT_THAT(mock.AsStdFunction()(), Pointee(17));
  }
801

802
803
804
805
806
  // The result of Return should not be convertible to Action (so it can't be
  // used with WillRepeatedly).
  static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())),
                                     Action<std::unique_ptr<int>()>>::value,
                "");
807
808
}

yutotnh's avatar
yutotnh committed
809
// Tests that Return(v) is covariant.
810
811
812
813
814
815
816
817
818
819
820
821
822

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);
Abseil Team's avatar
Abseil Team committed
823
  EXPECT_EQ(&base, ret.Perform(std::make_tuple()));
824
825

  ret = Return(&derived);
Abseil Team's avatar
Abseil Team committed
826
  EXPECT_EQ(&derived, ret.Perform(std::make_tuple()));
827
828
}

829
830
831
832
833
834
// 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:
835
  explicit FromType(bool* is_converted) : converted_(is_converted) {}
836
837
838
839
840
841
842
843
  bool* converted() const { return converted_; }

 private:
  bool* const converted_;
};

class ToType {
 public:
844
845
  // Must allow implicit conversion due to use in ImplicitCast_<T>.
  ToType(const FromType& x) { *x.converted() = true; }  // NOLINT
846
847
848
849
850
851
852
853
854
};

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;
Abseil Team's avatar
Abseil Team committed
855
  action.Perform(std::tuple<>());
856
  EXPECT_FALSE(converted) << "Action must NOT convert its argument "
857
                          << "when performed.";
858
859
}

860
861
862
// Tests that ReturnNull() returns NULL in a pointer-returning function.
TEST(ReturnNullTest, WorksInPointerReturningFunction) {
  const Action<int*()> a1 = ReturnNull();
Abseil Team's avatar
Abseil Team committed
863
  EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
864
865

  const Action<const char*(bool)> a2 = ReturnNull();  // NOLINT
Abseil Team's avatar
Abseil Team committed
866
  EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr);
867
868
}

869
870
871
872
// 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();
Abseil Team's avatar
Abseil Team committed
873
  EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
874
875

  const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
Abseil Team's avatar
Abseil Team committed
876
  EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr);
877
878
}

879
880
881
882
883
// Tests that ReturnRef(v) works for reference types.
TEST(ReturnRefTest, WorksForReference) {
  const int n = 0;
  const Action<const int&(bool)> ret = ReturnRef(n);  // NOLINT

Abseil Team's avatar
Abseil Team committed
884
  EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true)));
885
886
887
888
889
890
891
}

// Tests that ReturnRef(v) is covariant.
TEST(ReturnRefTest, IsCovariant) {
  Base base;
  Derived derived;
  Action<Base&()> a = ReturnRef(base);
Abseil Team's avatar
Abseil Team committed
892
  EXPECT_EQ(&base, &a.Perform(std::make_tuple()));
893
894

  a = ReturnRef(derived);
Abseil Team's avatar
Abseil Team committed
895
  EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));
896
897
}

898
template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
899
900
901
bool CanCallReturnRef(T&&) {
  return true;
}
902
bool CanCallReturnRef(Unused) { return false; }
903
904

// Tests that ReturnRef(v) is working with non-temporaries (T&)
905
TEST(ReturnRefTest, WorksForNonTemporary) {
906
907
  int scalar_value = 123;
  EXPECT_TRUE(CanCallReturnRef(scalar_value));
908

909
910
  std::string non_scalar_value("ABC");
  EXPECT_TRUE(CanCallReturnRef(non_scalar_value));
911

912
913
  const int const_scalar_value{321};
  EXPECT_TRUE(CanCallReturnRef(const_scalar_value));
914

915
916
  const std::string const_non_scalar_value("CBA");
  EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value));
917
918
919
}

// Tests that ReturnRef(v) is not working with temporaries (T&&)
920
TEST(ReturnRefTest, DoesNotWorkForTemporary) {
921
  auto scalar_value = []() -> int { return 123; };
922
  EXPECT_FALSE(CanCallReturnRef(scalar_value()));
923

924
925
  auto non_scalar_value = []() -> std::string { return "ABC"; };
  EXPECT_FALSE(CanCallReturnRef(non_scalar_value()));
926

Piotr Nycz's avatar
Piotr Nycz committed
927
928
  // cannot use here callable returning "const scalar type",
  // because such const for scalar return type is ignored
929
  EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321)));
930

931
932
  auto const_non_scalar_value = []() -> const std::string { return "CBA"; };
  EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value()));
933
}
934

935
936
937
938
939
// Tests that ReturnRefOfCopy(v) works for reference types.
TEST(ReturnRefOfCopyTest, WorksForReference) {
  int n = 42;
  const Action<const int&()> ret = ReturnRefOfCopy(n);

Abseil Team's avatar
Abseil Team committed
940
941
  EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
  EXPECT_EQ(42, ret.Perform(std::make_tuple()));
942
943

  n = 43;
Abseil Team's avatar
Abseil Team committed
944
945
  EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
  EXPECT_EQ(42, ret.Perform(std::make_tuple()));
946
947
948
949
950
951
952
}

// Tests that ReturnRefOfCopy(v) is covariant.
TEST(ReturnRefOfCopyTest, IsCovariant) {
  Base base;
  Derived derived;
  Action<Base&()> a = ReturnRefOfCopy(base);
Abseil Team's avatar
Abseil Team committed
953
  EXPECT_NE(&base, &a.Perform(std::make_tuple()));
954
955

  a = ReturnRefOfCopy(derived);
Abseil Team's avatar
Abseil Team committed
956
  EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
957
958
}

Abseil Team's avatar
Abseil Team committed
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
// Tests that ReturnRoundRobin(v) works with initializer lists
TEST(ReturnRoundRobinTest, WorksForInitList) {
  Action<int()> ret = ReturnRoundRobin({1, 2, 3});

  EXPECT_EQ(1, ret.Perform(std::make_tuple()));
  EXPECT_EQ(2, ret.Perform(std::make_tuple()));
  EXPECT_EQ(3, ret.Perform(std::make_tuple()));
  EXPECT_EQ(1, ret.Perform(std::make_tuple()));
  EXPECT_EQ(2, ret.Perform(std::make_tuple()));
  EXPECT_EQ(3, ret.Perform(std::make_tuple()));
}

// Tests that ReturnRoundRobin(v) works with vectors
TEST(ReturnRoundRobinTest, WorksForVector) {
  std::vector<double> v = {4.4, 5.5, 6.6};
  Action<double()> ret = ReturnRoundRobin(v);

  EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
  EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
  EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
  EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
  EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
  EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
}

984
985
986
987
// Tests that DoDefault() does the default action for the mock method.

class MockClass {
 public:
988
989
  MockClass() {}

990
  MOCK_METHOD1(IntFunc, int(bool flag));  // NOLINT
991
  MOCK_METHOD0(Foo, MyNonDefaultConstructible());
992
  MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
993
  MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
994
  MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
Gennadiy Civil's avatar
Gennadiy Civil committed
995
  MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
996
997
  MOCK_METHOD2(TakeUnique,
               int(const std::unique_ptr<int>&, std::unique_ptr<int>));
998
999

 private:
1000
1001
  MockClass(const MockClass&) = delete;
  MockClass& operator=(const MockClass&) = delete;
1002
1003
1004
1005
1006
1007
};

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

1012
1013
// Tests that DoDefault() throws (when exceptions are enabled) or aborts
// the process when there is no built-in default value for the return type.
1014
1015
TEST(DoDefaultDeathTest, DiesForUnknowType) {
  MockClass mock;
1016
  EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault());
1017
1018
1019
#if GTEST_HAS_EXCEPTIONS
  EXPECT_ANY_THROW(mock.Foo());
#else
1020
  EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, "");
1021
#endif
1022
1023
1024
1025
1026
}

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

1027
void VoidFunc(bool /* flag */) {}
1028
1029
1030
1031

TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
  MockClass mock;
  EXPECT_CALL(mock, IntFunc(_))
1032
      .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));
1033
1034
1035
1036
1037

  // 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.
1038
  EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, "");
1039
1040
1041
}

// Tests that DoDefault() returns the default value set by
John Bampton's avatar
John Bampton committed
1042
// DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
1043
1044
1045
TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
  DefaultValue<int>::Set(1);
  MockClass mock;
1046
  EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
1047
1048
1049
1050
1051
1052
1053
  EXPECT_EQ(1, mock.IntFunc(false));
  DefaultValue<int>::Clear();
}

// Tests that DoDefault() does the action specified by ON_CALL().
TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
  MockClass mock;
1054
1055
  ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2));
  EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
1056
1057
1058
1059
1060
1061
  EXPECT_EQ(2, mock.IntFunc(false));
}

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

1069
1070
1071
1072
1073
1074
1075
1076
// 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';
Abseil Team's avatar
Abseil Team committed
1077
  a.Perform(std::make_tuple(true, &n, &ch));
1078
1079
1080
1081
1082
1083
  EXPECT_EQ(2, n);
  EXPECT_EQ('\0', ch);

  a = SetArgPointee<2>('a');
  n = 0;
  ch = '\0';
Abseil Team's avatar
Abseil Team committed
1084
  a.Perform(std::make_tuple(true, &n, &ch));
1085
1086
1087
1088
  EXPECT_EQ(0, n);
  EXPECT_EQ('a', ch);
}

1089
1090
// Tests that SetArgPointee<N>() accepts a string literal.
TEST(SetArgPointeeTest, AcceptsStringLiteral) {
1091
1092
  typedef void MyFunction(std::string*, const char**);
  Action<MyFunction> a = SetArgPointee<0>("hi");
1093
  std::string str;
1094
  const char* ptr = nullptr;
Abseil Team's avatar
Abseil Team committed
1095
  a.Perform(std::make_tuple(&str, &ptr));
1096
  EXPECT_EQ("hi", str);
1097
  EXPECT_TRUE(ptr == nullptr);
1098

1099
  a = SetArgPointee<1>("world");
1100
  str = "";
Abseil Team's avatar
Abseil Team committed
1101
  a.Perform(std::make_tuple(&str, &ptr));
1102
1103
1104
1105
  EXPECT_EQ("", str);
  EXPECT_STREQ("world", ptr);
}

1106
1107
1108
TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
  typedef void MyFunction(const wchar_t**);
  Action<MyFunction> a = SetArgPointee<0>(L"world");
1109
  const wchar_t* ptr = nullptr;
Abseil Team's avatar
Abseil Team committed
1110
  a.Perform(std::make_tuple(&ptr));
1111
1112
  EXPECT_STREQ(L"world", ptr);

1113
#if GTEST_HAS_STD_WSTRING
1114
1115
1116
1117

  typedef void MyStringFunction(std::wstring*);
  Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
  std::wstring str = L"";
Abseil Team's avatar
Abseil Team committed
1118
  a2.Perform(std::make_tuple(&str));
1119
1120
  EXPECT_EQ(L"world", str);

1121
#endif
1122
1123
}

1124
1125
1126
1127
1128
1129
// 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;
1130
  const char* ptr = nullptr;
Abseil Team's avatar
Abseil Team committed
1131
  a.Perform(std::make_tuple(true, &str, &ptr));
1132
  EXPECT_EQ("hi", str);
1133
  EXPECT_TRUE(ptr == nullptr);
1134
1135
1136
1137
1138

  char world_array[] = "world";
  char* const world = world_array;
  a = SetArgPointee<2>(world);
  str = "";
Abseil Team's avatar
Abseil Team committed
1139
  a.Perform(std::make_tuple(true, &str, &ptr));
1140
1141
1142
1143
  EXPECT_EQ("", str);
  EXPECT_EQ(world, ptr);
}

1144
1145
1146
1147
TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
  typedef void MyFunction(bool, const wchar_t**);
  const wchar_t* const hi = L"hi";
  Action<MyFunction> a = SetArgPointee<1>(hi);
1148
  const wchar_t* ptr = nullptr;
Abseil Team's avatar
Abseil Team committed
1149
  a.Perform(std::make_tuple(true, &ptr));
1150
1151
  EXPECT_EQ(hi, ptr);

1152
#if GTEST_HAS_STD_WSTRING
1153
1154
1155
1156
1157
1158

  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;
Abseil Team's avatar
Abseil Team committed
1159
  a2.Perform(std::make_tuple(true, &str));
1160
  EXPECT_EQ(world_array, str);
1161
#endif
1162
1163
}

1164
1165
1166
1167
1168
1169
1170
1171
// 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';
Abseil Team's avatar
Abseil Team committed
1172
  a.Perform(std::make_tuple(true, &n, &ch));
1173
1174
1175
1176
1177
1178
  EXPECT_EQ(2, n);
  EXPECT_EQ('\0', ch);

  a = SetArgumentPointee<2>('a');
  n = 0;
  ch = '\0';
Abseil Team's avatar
Abseil Team committed
1179
  a.Perform(std::make_tuple(true, &n, &ch));
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
  EXPECT_EQ(0, n);
  EXPECT_EQ('a', ch);
}

// 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; }
};

Abseil Team's avatar
Abseil Team committed
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
short Short(short n) { return n; }  // NOLINT
char Char(char ch) { return ch; }

const char* CharPtr(const char* s) { return s; }

bool Unary(int x) { return x < 0; }

const char* Binary(const char* input, short n) { return input + n; }  // NOLINT

void VoidBinary(int, char) { g_done = true; }

int Ternary(int x, char y, short z) { return x + y + z; }  // NOLINT

int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }

1215
1216
1217
1218
1219
class Foo {
 public:
  Foo() : value_(123) {}

  int Nullary() const { return value_; }
1220

1221
1222
1223
1224
1225
1226
1227
1228
 private:
  int value_;
};

// Tests InvokeWithoutArgs(function).
TEST(InvokeWithoutArgsTest, Function) {
  // As an action that takes one argument.
  Action<int(int)> a = InvokeWithoutArgs(Nullary);  // NOLINT
Abseil Team's avatar
Abseil Team committed
1229
  EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
1230
1231

  // As an action that takes two arguments.
1232
  Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary);  // NOLINT
Abseil Team's avatar
Abseil Team committed
1233
  EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5)));
1234
1235
1236
1237

  // As an action that returns void.
  Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary);  // NOLINT
  g_done = false;
Abseil Team's avatar
Abseil Team committed
1238
  a3.Perform(std::make_tuple(1));
1239
1240
1241
1242
1243
1244
1245
  EXPECT_TRUE(g_done);
}

// Tests InvokeWithoutArgs(functor).
TEST(InvokeWithoutArgsTest, Functor) {
  // As an action that takes no argument.
  Action<int()> a = InvokeWithoutArgs(NullaryFunctor());  // NOLINT
Abseil Team's avatar
Abseil Team committed
1246
  EXPECT_EQ(2, a.Perform(std::make_tuple()));
1247
1248

  // As an action that takes three arguments.
1249
  Action<int(int, double, char)> a2 =  // NOLINT
1250
      InvokeWithoutArgs(NullaryFunctor());
Abseil Team's avatar
Abseil Team committed
1251
  EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a')));
1252
1253
1254
1255

  // As an action that returns void.
  Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
  g_done = false;
Abseil Team's avatar
Abseil Team committed
1256
  a3.Perform(std::make_tuple());
1257
1258
1259
1260
1261
1262
1263
1264
  EXPECT_TRUE(g_done);
}

// Tests InvokeWithoutArgs(obj_ptr, method).
TEST(InvokeWithoutArgsTest, Method) {
  Foo foo;
  Action<int(bool, char)> a =  // NOLINT
      InvokeWithoutArgs(&foo, &Foo::Nullary);
Abseil Team's avatar
Abseil Team committed
1265
  EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));
1266
1267
1268
1269
1270
}

// Tests using IgnoreResult() on a polymorphic action.
TEST(IgnoreResultTest, PolymorphicAction) {
  Action<void(int)> a = IgnoreResult(Return(5));  // NOLINT
Abseil Team's avatar
Abseil Team committed
1271
  a.Perform(std::make_tuple(1));
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
}

// 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));
Abseil Team's avatar
Abseil Team committed
1284
  a.Perform(std::make_tuple());
1285
1286
1287
1288
1289
  EXPECT_TRUE(g_done);
}

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

1290
MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1291
  g_done = true;
1292
  return MyNonDefaultConstructible(42);
1293
1294
1295
1296
}

TEST(IgnoreResultTest, ActionReturningClass) {
  g_done = false;
1297
1298
  Action<void(int)> a =
      IgnoreResult(Invoke(ReturnMyNonDefaultConstructible));  // NOLINT
Abseil Team's avatar
Abseil Team committed
1299
  a.Perform(std::make_tuple(2));
1300
1301
1302
1303
1304
1305
  EXPECT_TRUE(g_done);
}

TEST(AssignTest, Int) {
  int x = 0;
  Action<void(int)> a = Assign(&x, 5);
Abseil Team's avatar
Abseil Team committed
1306
  a.Perform(std::make_tuple(0));
1307
1308
1309
1310
1311
1312
  EXPECT_EQ(5, x);
}

TEST(AssignTest, String) {
  ::std::string x;
  Action<void(void)> a = Assign(&x, "Hello, world");
Abseil Team's avatar
Abseil Team committed
1313
  a.Perform(std::make_tuple());
1314
1315
1316
1317
1318
1319
  EXPECT_EQ("Hello, world", x);
}

TEST(AssignTest, CompatibleTypes) {
  double x = 0;
  Action<void(int)> a = Assign(&x, 5);
Abseil Team's avatar
Abseil Team committed
1320
  a.Perform(std::make_tuple(0));
1321
1322
1323
  EXPECT_DOUBLE_EQ(5, x);
}

1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
// DoAll should support &&-qualified actions when used with WillOnce.
TEST(DoAll, SupportsRefQualifiedActions) {
  struct InitialAction {
    void operator()(const int arg) && { EXPECT_EQ(17, arg); }
  };

  struct FinalAction {
    int operator()() && { return 19; }
  };

  MockFunction<int(int)> mock;
  EXPECT_CALL(mock, Call).WillOnce(DoAll(InitialAction{}, FinalAction{}));
  EXPECT_EQ(19, mock.AsStdFunction()(17));
}

1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
// DoAll should never provide rvalue references to the initial actions. If the
// mock action itself accepts an rvalue reference or a non-scalar object by
// value then the final action should receive an rvalue reference, but initial
// actions should receive only lvalue references.
TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {
  struct Obj {};

  // Mock action accepts by value: the initial action should be fed a const
  // lvalue reference, and the final action an rvalue reference.
  {
    struct InitialAction {
      void operator()(Obj&) const { FAIL() << "Unexpected call"; }
      void operator()(const Obj&) const {}
      void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
      void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
    };

    MockFunction<void(Obj)> mock;
    EXPECT_CALL(mock, Call)
        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
        .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));

    mock.AsStdFunction()(Obj{});
    mock.AsStdFunction()(Obj{});
  }

  // Mock action accepts by const lvalue reference: both actions should receive
  // a const lvalue reference.
  {
    struct InitialAction {
      void operator()(Obj&) const { FAIL() << "Unexpected call"; }
      void operator()(const Obj&) const {}
      void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
      void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
    };

    MockFunction<void(const Obj&)> mock;
    EXPECT_CALL(mock, Call)
        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}))
        .WillRepeatedly(
            DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}));

    mock.AsStdFunction()(Obj{});
    mock.AsStdFunction()(Obj{});
  }

  // Mock action accepts by non-const lvalue reference: both actions should get
  // a non-const lvalue reference if they want them.
  {
    struct InitialAction {
      void operator()(Obj&) const {}
      void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
    };

    MockFunction<void(Obj&)> mock;
    EXPECT_CALL(mock, Call)
        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}))
        .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));

    Obj obj;
    mock.AsStdFunction()(obj);
    mock.AsStdFunction()(obj);
  }

  // Mock action accepts by rvalue reference: the initial actions should receive
  // a non-const lvalue reference if it wants it, and the final action an rvalue
  // reference.
  {
    struct InitialAction {
      void operator()(Obj&) const {}
      void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
    };

Tom Hughes's avatar
Tom Hughes committed
1412
    MockFunction<void(Obj&&)> mock;
1413
1414
1415
1416
1417
1418
1419
    EXPECT_CALL(mock, Call)
        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
        .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));

    mock.AsStdFunction()(Obj{});
    mock.AsStdFunction()(Obj{});
  }
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439

  // &&-qualified initial actions should also be allowed with WillOnce.
  {
    struct InitialAction {
      void operator()(Obj&) && {}
    };

    MockFunction<void(Obj&)> mock;
    EXPECT_CALL(mock, Call)
        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));

    Obj obj;
    mock.AsStdFunction()(obj);
  }

  {
    struct InitialAction {
      void operator()(Obj&) && {}
    };

Tom Hughes's avatar
Tom Hughes committed
1440
    MockFunction<void(Obj&&)> mock;
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
    EXPECT_CALL(mock, Call)
        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));

    mock.AsStdFunction()(Obj{});
  }
}

// DoAll should support being used with type-erased Action objects, both through
// WillOnce and WillRepeatedly.
TEST(DoAll, SupportsTypeErasedActions) {
  // With only type-erased actions.
  const Action<void()> initial_action = [] {};
  const Action<int()> final_action = [] { return 17; };

  MockFunction<int()> mock;
  EXPECT_CALL(mock, Call)
      .WillOnce(DoAll(initial_action, initial_action, final_action))
      .WillRepeatedly(DoAll(initial_action, initial_action, final_action));

  EXPECT_EQ(17, mock.AsStdFunction()());

  // With &&-qualified and move-only final action.
  {
    struct FinalAction {
      FinalAction() = default;
      FinalAction(FinalAction&&) = default;

      int operator()() && { return 17; }
    };

    EXPECT_CALL(mock, Call)
        .WillOnce(DoAll(initial_action, initial_action, FinalAction{}));

    EXPECT_EQ(17, mock.AsStdFunction()());
  }
1476
1477
}

Abseil Team's avatar
Abseil Team committed
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
// Tests using WithArgs and with an action that takes 1 argument.
TEST(WithArgsTest, OneArg) {
  Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary));  // NOLINT
  EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));
  EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));
}

// Tests using WithArgs with an action that takes 2 arguments.
TEST(WithArgsTest, TwoArgs) {
  Action<const char*(const char* s, double x, short n)> a =  // NOLINT
      WithArgs<0, 2>(Invoke(Binary));
  const char s[] = "Hello";
  EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
}

struct ConcatAll {
  std::string operator()() const { return {}; }
  template <typename... I>
  std::string operator()(const char* a, I... i) const {
    return a + ConcatAll()(i...);
  }
};

// Tests using WithArgs with an action that takes 10 arguments.
TEST(WithArgsTest, TenArgs) {
  Action<std::string(const char*, const char*, const char*, const char*)> a =
      WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
  EXPECT_EQ("0123210123",
            a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
                                      CharPtr("3"))));
}

// Tests using WithArgs with an action that is not Invoke().
class SubtractAction : public ActionInterface<int(int, int)> {
 public:
Abseil Team's avatar
Abseil Team committed
1513
  int Perform(const std::tuple<int, int>& args) override {
Abseil Team's avatar
Abseil Team committed
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
    return std::get<0>(args) - std::get<1>(args);
  }
};

TEST(WithArgsTest, NonInvokeAction) {
  Action<int(const std::string&, int, int)> a =
      WithArgs<2, 1>(MakeAction(new SubtractAction));
  std::tuple<std::string, int, int> dummy =
      std::make_tuple(std::string("hi"), 2, 10);
  EXPECT_EQ(8, a.Perform(dummy));
}

// Tests using WithArgs to pass all original arguments in the original order.
TEST(WithArgsTest, Identity) {
  Action<int(int x, char y, short z)> a =  // NOLINT
      WithArgs<0, 1, 2>(Invoke(Ternary));
  EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));
}

// Tests using WithArgs with repeated arguments.
TEST(WithArgsTest, RepeatedArguments) {
  Action<int(bool, int m, int n)> a =  // NOLINT
      WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
  EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));
}

// Tests using WithArgs with reversed argument order.
TEST(WithArgsTest, ReversedArgumentOrder) {
  Action<const char*(short n, const char* input)> a =  // NOLINT
      WithArgs<1, 0>(Invoke(Binary));
  const char s[] = "Hello";
  EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));
}

// Tests using WithArgs with compatible, but not identical, argument types.
TEST(WithArgsTest, ArgsOfCompatibleTypes) {
  Action<long(short x, char y, double z, char c)> a =  // NOLINT
      WithArgs<0, 1, 3>(Invoke(Ternary));
  EXPECT_EQ(123,
            a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));
}

// Tests using WithArgs with an action that returns void.
TEST(WithArgsTest, VoidAction) {
  Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
  g_done = false;
  a.Perform(std::make_tuple(1.5, 'a', 3));
  EXPECT_TRUE(g_done);
}

TEST(WithArgsTest, ReturnReference) {
misterg's avatar
misterg committed
1565
  Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });
Abseil Team's avatar
Abseil Team committed
1566
  int i = 0;
misterg's avatar
misterg committed
1567
  const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));
Abseil Team's avatar
Abseil Team committed
1568
1569
1570
1571
1572
  EXPECT_EQ(&i, &res);
}

TEST(WithArgsTest, InnerActionWithConversion) {
  Action<Derived*()> inner = [] { return nullptr; };
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595

  MockFunction<Base*(double)> mock;
  EXPECT_CALL(mock, Call)
      .WillOnce(WithoutArgs(inner))
      .WillRepeatedly(WithoutArgs(inner));

  EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
  EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
}

// It should be possible to use an &&-qualified inner action as long as the
// whole shebang is used as an rvalue with WillOnce.
TEST(WithArgsTest, RefQualifiedInnerAction) {
  struct SomeAction {
    int operator()(const int arg) && {
      EXPECT_EQ(17, arg);
      return 19;
    }
  };

  MockFunction<int(int, int)> mock;
  EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{}));
  EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
Abseil Team's avatar
Abseil Team committed
1596
1597
}

1598
#ifndef GTEST_OS_WINDOWS_MOBILE
1599

1600
1601
class SetErrnoAndReturnTest : public testing::Test {
 protected:
Abseil Team's avatar
Abseil Team committed
1602
1603
  void SetUp() override { errno = 0; }
  void TearDown() override { errno = 0; }
1604
1605
1606
1607
};

TEST_F(SetErrnoAndReturnTest, Int) {
  Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
Abseil Team's avatar
Abseil Team committed
1608
  EXPECT_EQ(-5, a.Perform(std::make_tuple()));
1609
1610
1611
1612
1613
1614
  EXPECT_EQ(ENOTTY, errno);
}

TEST_F(SetErrnoAndReturnTest, Ptr) {
  int x;
  Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
Abseil Team's avatar
Abseil Team committed
1615
  EXPECT_EQ(&x, a.Perform(std::make_tuple()));
1616
1617
1618
1619
1620
  EXPECT_EQ(ENOTTY, errno);
}

TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
  Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
Abseil Team's avatar
Abseil Team committed
1621
  EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));
1622
1623
1624
  EXPECT_EQ(EINVAL, errno);
}

1625
#endif  // !GTEST_OS_WINDOWS_MOBILE
1626

1627
1628
// Tests ByRef().

Abseil Team's avatar
Abseil Team committed
1629
// Tests that the result of ByRef() is copyable.
1630
1631
1632
1633
TEST(ByRefTest, IsCopyable) {
  const std::string s1 = "Hi";
  const std::string s2 = "Hello";

Abseil Team's avatar
Abseil Team committed
1634
  auto ref_wrapper = ByRef(s1);
1635
1636
1637
1638
1639
1640
1641
1642
  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);

Abseil Team's avatar
Abseil Team committed
1643
  auto ref_wrapper1 = ByRef(s1);
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
  // 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
1654
  // negative compilation test to catch it.
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
  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
1679
  // compilation test to catch it.
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709

  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());
}

Abseil Team's avatar
Abseil Team committed
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
struct UnaryConstructorClass {
  explicit UnaryConstructorClass(int v) : value(v) {}
  int value;
};

// Tests using ReturnNew() with a unary constructor.
TEST(ReturnNewTest, Unary) {
  Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
  UnaryConstructorClass* c = a.Perform(std::make_tuple());
  EXPECT_EQ(4000, c->value);
  delete c;
}

TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
  Action<UnaryConstructorClass*(bool, int)> a =
      ReturnNew<UnaryConstructorClass>(4000);
  UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
  EXPECT_EQ(4000, c->value);
  delete c;
}

TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
  Action<const UnaryConstructorClass*()> a =
      ReturnNew<UnaryConstructorClass>(4000);
  const UnaryConstructorClass* c = a.Perform(std::make_tuple());
  EXPECT_EQ(4000, c->value);
  delete c;
}

class TenArgConstructorClass {
 public:
  TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
                         int a8, int a9, int a10)
      : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
  int value_;
};

// Tests using ReturnNew() with a 10-argument constructor.
TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
  Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(
      1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,
      0);
  TenArgConstructorClass* c = a.Perform(std::make_tuple());
  EXPECT_EQ(1234567890, c->value_);
  delete c;
}
1756

1757
std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); }
1758
1759
1760
1761
1762
1763
1764

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

1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
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();
1779
  EXPECT_EQ(1u, vresult.size());
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
  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());
1792
1793
1794
1795
  EXPECT_CALL(mock, MakeUnique())
      .WillOnce(DoAll(InvokeWithoutArgs(&mock_function,
                                        &testing::MockFunction<void()>::Call),
                      Return(ByMove(std::move(i)))));
1796
1797
1798
1799
1800
1801

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

TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1802
1803
1804
  MockClass mock;

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

1809
  EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
1810
1811
1812
1813
1814
1815
1816
1817
1818
  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();
1819
  EXPECT_EQ(1u, vresult.size());
1820
1821
1822
1823
  EXPECT_NE(nullptr, vresult[0]);
  EXPECT_EQ(7, *vresult[0]);
}

Gennadiy Civil's avatar
 
Gennadiy Civil committed
1824
1825
TEST(MockMethodTest, CanTakeMoveOnlyValue) {
  MockClass mock;
1826
  auto make = [](int i) { return std::make_unique<int>(i); };
Gennadiy Civil's avatar
 
Gennadiy Civil committed
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865

  EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
    return *i;
  });
  // DoAll() does not compile, since it would move from its arguments twice.
  // EXPECT_CALL(mock, TakeUnique(_, _))
  //     .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
  //     Return(1)));
  EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
      .WillOnce(Return(-7))
      .RetiresOnSaturation();
  EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
      .WillOnce(Return(-1))
      .RetiresOnSaturation();

  EXPECT_EQ(5, mock.TakeUnique(make(5)));
  EXPECT_EQ(-7, mock.TakeUnique(make(7)));
  EXPECT_EQ(7, mock.TakeUnique(make(7)));
  EXPECT_EQ(7, mock.TakeUnique(make(7)));
  EXPECT_EQ(-1, mock.TakeUnique({}));

  // Some arguments are moved, some passed by reference.
  auto lvalue = make(6);
  EXPECT_CALL(mock, TakeUnique(_, _))
      .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
        return *i * *j;
      });
  EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));

  // The unique_ptr can be saved by the action.
  std::unique_ptr<int> saved;
  EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
    saved = std::move(i);
    return 0;
  });
  EXPECT_EQ(0, mock.TakeUnique(make(42)));
  EXPECT_EQ(42, *saved);
}

1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
// It should be possible to use callables with an &&-qualified call operator
// with WillOnce, since they will be called only once. This allows actions to
// contain and manipulate move-only types.
TEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) {
  struct Return17 {
    int operator()() && { return 17; }
  };

  // Action is directly compatible with mocked function type.
  {
    MockFunction<int()> mock;
    EXPECT_CALL(mock, Call).WillOnce(Return17());

    EXPECT_EQ(17, mock.AsStdFunction()());
  }

  // Action doesn't want mocked function arguments.
  {
    MockFunction<int(int)> mock;
    EXPECT_CALL(mock, Call).WillOnce(Return17());

    EXPECT_EQ(17, mock.AsStdFunction()(0));
  }
}

// Edge case: if an action has both a const-qualified and an &&-qualified call
// operator, there should be no "ambiguous call" errors. The &&-qualified
// operator should be used by WillOnce (since it doesn't need to retain the
// action beyond one call), and the const-qualified one by WillRepeatedly.
TEST(MockMethodTest, ActionHasMultipleCallOperators) {
  struct ReturnInt {
    int operator()() && { return 17; }
    int operator()() const& { return 19; }
  };

  // Directly compatible with mocked function type.
  {
    MockFunction<int()> mock;
    EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());

    EXPECT_EQ(17, mock.AsStdFunction()());
    EXPECT_EQ(19, mock.AsStdFunction()());
    EXPECT_EQ(19, mock.AsStdFunction()());
  }

  // Ignores function arguments.
  {
    MockFunction<int(int)> mock;
    EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());

    EXPECT_EQ(17, mock.AsStdFunction()(0));
    EXPECT_EQ(19, mock.AsStdFunction()(0));
    EXPECT_EQ(19, mock.AsStdFunction()(0));
  }
}

// WillOnce should have no problem coping with a move-only action, whether it is
// &&-qualified or not.
TEST(MockMethodTest, MoveOnlyAction) {
  // &&-qualified
  {
    struct Return17 {
      Return17() = default;
      Return17(Return17&&) = default;

      Return17(const Return17&) = delete;
      Return17 operator=(const Return17&) = delete;

      int operator()() && { return 17; }
    };

    MockFunction<int()> mock;
    EXPECT_CALL(mock, Call).WillOnce(Return17());
    EXPECT_EQ(17, mock.AsStdFunction()());
  }

  // Not &&-qualified
  {
    struct Return17 {
      Return17() = default;
      Return17(Return17&&) = default;

      Return17(const Return17&) = delete;
      Return17 operator=(const Return17&) = delete;

      int operator()() const { return 17; }
    };

    MockFunction<int()> mock;
    EXPECT_CALL(mock, Call).WillOnce(Return17());
    EXPECT_EQ(17, mock.AsStdFunction()());
  }
}

// It should be possible to use an action that returns a value with a mock
// function that doesn't, both through WillOnce and WillRepeatedly.
TEST(MockMethodTest, ActionReturnsIgnoredValue) {
  struct ReturnInt {
    int operator()() const { return 0; }
  };

  MockFunction<void()> mock;
  EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());

  mock.AsStdFunction()();
  mock.AsStdFunction()();
}

// Despite the fanciness around move-only actions and so on, it should still be
// possible to hand an lvalue reference to a copyable action to WillOnce.
TEST(MockMethodTest, WillOnceCanAcceptLvalueReference) {
  MockFunction<int()> mock;

  const auto action = [] { return 17; };
  EXPECT_CALL(mock, Call).WillOnce(action);

  EXPECT_EQ(17, mock.AsStdFunction()());
}

// A callable that doesn't use SFINAE to restrict its call operator's overload
// set, but is still picky about which arguments it will accept.
struct StaticAssertSingleArgument {
  template <typename... Args>
  static constexpr bool CheckArgs() {
    static_assert(sizeof...(Args) == 1, "");
    return true;
  }

  template <typename... Args, bool = CheckArgs<Args...>()>
  int operator()(Args...) const {
    return 17;
  }
};

// WillOnce and WillRepeatedly should both work fine with naïve implementations
// of actions that don't use SFINAE to limit the overload set for their call
// operator. If they are compatible with the actual mocked signature, we
// shouldn't probe them with no arguments and trip a static_assert.
TEST(MockMethodTest, ActionSwallowsAllArguments) {
  MockFunction<int(int)> mock;
  EXPECT_CALL(mock, Call)
      .WillOnce(StaticAssertSingleArgument{})
      .WillRepeatedly(StaticAssertSingleArgument{});

  EXPECT_EQ(17, mock.AsStdFunction()(0));
  EXPECT_EQ(17, mock.AsStdFunction()(0));
}

2014
2015
struct ActionWithTemplatedConversionOperators {
  template <typename... Args>
2016
  operator OnceAction<int(Args...)>() && {  // NOLINT
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
    return [] { return 17; };
  }

  template <typename... Args>
  operator Action<int(Args...)>() const {  // NOLINT
    return [] { return 19; };
  }
};

// It should be fine to hand both WillOnce and WillRepeatedly a function that
// defines templated conversion operators to OnceAction and Action. WillOnce
// should prefer the OnceAction version.
TEST(MockMethodTest, ActionHasTemplatedConversionOperators) {
  MockFunction<int()> mock;
  EXPECT_CALL(mock, Call)
      .WillOnce(ActionWithTemplatedConversionOperators{})
      .WillRepeatedly(ActionWithTemplatedConversionOperators{});

  EXPECT_EQ(17, mock.AsStdFunction()());
  EXPECT_EQ(19, mock.AsStdFunction()());
}

Gennadiy Civil's avatar
 
Gennadiy Civil committed
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
// Tests for std::function based action.

int Add(int val, int& ref, int* ptr) {  // NOLINT
  int result = val + ref + *ptr;
  ref = 42;
  *ptr = 43;
  return result;
}

int Deref(std::unique_ptr<int> ptr) { return *ptr; }

struct Double {
  template <typename T>
2052
2053
2054
  T operator()(T t) {
    return 2 * t;
  }
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2055
2056
};

2057
std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); }
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071

TEST(FunctorActionTest, ActionFromFunction) {
  Action<int(int, int&, int*)> a = &Add;
  int x = 1, y = 2, z = 3;
  EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
  EXPECT_EQ(42, y);
  EXPECT_EQ(43, z);

  Action<int(std::unique_ptr<int>)> a1 = &Deref;
  EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
}

TEST(FunctorActionTest, ActionFromLambda) {
  Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
Abseil Team's avatar
Abseil Team committed
2072
2073
  EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
  EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5)));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2074
2075
2076
2077
2078

  std::unique_ptr<int> saved;
  Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {
    saved = std::move(p);
  };
Abseil Team's avatar
Abseil Team committed
2079
  a2.Perform(std::make_tuple(UniqueInt(5)));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2080
2081
2082
2083
2084
  EXPECT_EQ(5, *saved);
}

TEST(FunctorActionTest, PolymorphicFunctor) {
  Action<int(int)> ai = Double();
Abseil Team's avatar
Abseil Team committed
2085
  EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2086
  Action<double(double)> ad = Double();  // Double? Double double!
Abseil Team's avatar
Abseil Team committed
2087
  EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5)));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2088
2089
2090
2091
2092
2093
}

TEST(FunctorActionTest, TypeConversion) {
  // Numeric promotions are allowed.
  const Action<bool(int)> a1 = [](int i) { return i > 1; };
  const Action<int(bool)> a2 = Action<int(bool)>(a1);
Abseil Team's avatar
Abseil Team committed
2094
2095
  EXPECT_EQ(1, a1.Perform(std::make_tuple(42)));
  EXPECT_EQ(0, a2.Perform(std::make_tuple(42)));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2096
2097
2098
2099

  // Implicit constructors are allowed.
  const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };
  const Action<int(const char*)> s2 = Action<int(const char*)>(s1);
Abseil Team's avatar
Abseil Team committed
2100
2101
  EXPECT_EQ(0, s2.Perform(std::make_tuple("")));
  EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2102
2103

  // Also between the lambda and the action itself.
Abseil Team's avatar
Abseil Team committed
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
  const Action<bool(std::string)> x1 = [](Unused) { return 42; };
  const Action<bool(std::string)> x2 = [] { return 42; };
  EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));
  EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));

  // Ensure decay occurs where required.
  std::function<int()> f = [] { return 7; };
  Action<int(int)> d = f;
  f = nullptr;
  EXPECT_EQ(7, d.Perform(std::make_tuple(1)));

  // Ensure creation of an empty action succeeds.
  Action<void(int)>(nullptr);
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2117
2118
2119
2120
}

TEST(FunctorActionTest, UnusedArguments) {
  // Verify that users can ignore uninteresting arguments.
2121
2122
2123
  Action<int(int, double y, double z)> a = [](int i, Unused, Unused) {
    return 2 * i;
  };
Abseil Team's avatar
Abseil Team committed
2124
  std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2125
  EXPECT_EQ(6, a.Perform(dummy));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2126
2127
2128
2129
2130
}

// Test that basic built-in actions work with move-only arguments.
TEST(MoveOnlyArgumentsTest, ReturningActions) {
  Action<int(std::unique_ptr<int>)> a = Return(1);
Abseil Team's avatar
Abseil Team committed
2131
  EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2132
2133

  a = testing::WithoutArgs([]() { return 7; });
Abseil Team's avatar
Abseil Team committed
2134
  EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr)));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2135
2136
2137

  Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
  int x = 0;
Abseil Team's avatar
Abseil Team committed
2138
  a2.Perform(std::make_tuple(nullptr, &x));
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2139
2140
2141
  EXPECT_EQ(x, 3);
}

2142
ACTION(ReturnArity) { return std::tuple_size<args_type>::value; }
Abseil Team's avatar
Abseil Team committed
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159

TEST(ActionMacro, LargeArity) {
  EXPECT_EQ(
      1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));
  EXPECT_EQ(
      10,
      testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(
          ReturnArity())
          .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));
  EXPECT_EQ(
      20,
      testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,
                          int, int, int, int, int, int, int, int, int)>(
          ReturnArity())
          .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
                                   14, 15, 16, 17, 18, 19)));
}
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2160

2161
2162
}  // namespace
}  // namespace testing
2163
2164
2165
2166
2167

#if defined(_MSC_VER) && (_MSC_VER == 1900)
GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4800
#endif
GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4100 4503