Upload upstream chromium 69.0.3497
[platform/framework/web/chromium-efl.git] / base / bind_unittest.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/bind.h"
6
7 #include <memory>
8 #include <utility>
9 #include <vector>
10
11 #include "base/callback.h"
12 #include "base/macros.h"
13 #include "base/memory/ptr_util.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/test/bind_test_util.h"
17 #include "base/test/gtest_util.h"
18 #include "build/build_config.h"
19 #include "testing/gmock/include/gmock/gmock.h"
20 #include "testing/gtest/include/gtest/gtest.h"
21
22 using ::testing::_;
23 using ::testing::Mock;
24 using ::testing::ByMove;
25 using ::testing::Return;
26 using ::testing::StrictMock;
27
28 namespace base {
29 namespace {
30
31 class IncompleteType;
32
33 class NoRef {
34  public:
35   NoRef() = default;
36
37   MOCK_METHOD0(VoidMethod0, void());
38   MOCK_CONST_METHOD0(VoidConstMethod0, void());
39
40   MOCK_METHOD0(IntMethod0, int());
41   MOCK_CONST_METHOD0(IntConstMethod0, int());
42
43   MOCK_METHOD1(VoidMethodWithIntArg, void(int));
44   MOCK_METHOD0(UniquePtrMethod0, std::unique_ptr<int>());
45
46  private:
47   // Particularly important in this test to ensure no copies are made.
48   DISALLOW_COPY_AND_ASSIGN(NoRef);
49 };
50
51 class HasRef : public NoRef {
52  public:
53   HasRef() = default;
54
55   MOCK_CONST_METHOD0(AddRef, void());
56   MOCK_CONST_METHOD0(Release, bool());
57
58  private:
59   // Particularly important in this test to ensure no copies are made.
60   DISALLOW_COPY_AND_ASSIGN(HasRef);
61 };
62
63 class HasRefPrivateDtor : public HasRef {
64  private:
65   ~HasRefPrivateDtor() = default;
66 };
67
68 static const int kParentValue = 1;
69 static const int kChildValue = 2;
70
71 class Parent {
72  public:
73   void AddRef() const {}
74   void Release() const {}
75   virtual void VirtualSet() { value = kParentValue; }
76   void NonVirtualSet() { value = kParentValue; }
77   int value;
78 };
79
80 class Child : public Parent {
81  public:
82   void VirtualSet() override { value = kChildValue; }
83   void NonVirtualSet() { value = kChildValue; }
84 };
85
86 class NoRefParent {
87  public:
88   virtual void VirtualSet() { value = kParentValue; }
89   void NonVirtualSet() { value = kParentValue; }
90   int value;
91 };
92
93 class NoRefChild : public NoRefParent {
94   void VirtualSet() override { value = kChildValue; }
95   void NonVirtualSet() { value = kChildValue; }
96 };
97
98 // Used for probing the number of copies and moves that occur if a type must be
99 // coerced during argument forwarding in the Run() methods.
100 struct DerivedCopyMoveCounter {
101   DerivedCopyMoveCounter(int* copies,
102                          int* assigns,
103                          int* move_constructs,
104                          int* move_assigns)
105       : copies_(copies),
106         assigns_(assigns),
107         move_constructs_(move_constructs),
108         move_assigns_(move_assigns) {}
109   int* copies_;
110   int* assigns_;
111   int* move_constructs_;
112   int* move_assigns_;
113 };
114
115 // Used for probing the number of copies and moves in an argument.
116 class CopyMoveCounter {
117  public:
118   CopyMoveCounter(int* copies,
119                   int* assigns,
120                   int* move_constructs,
121                   int* move_assigns)
122       : copies_(copies),
123         assigns_(assigns),
124         move_constructs_(move_constructs),
125         move_assigns_(move_assigns) {}
126
127   CopyMoveCounter(const CopyMoveCounter& other)
128       : copies_(other.copies_),
129         assigns_(other.assigns_),
130         move_constructs_(other.move_constructs_),
131         move_assigns_(other.move_assigns_) {
132     (*copies_)++;
133   }
134
135   CopyMoveCounter(CopyMoveCounter&& other)
136       : copies_(other.copies_),
137         assigns_(other.assigns_),
138         move_constructs_(other.move_constructs_),
139         move_assigns_(other.move_assigns_) {
140     (*move_constructs_)++;
141   }
142
143   // Probing for copies from coercion.
144   explicit CopyMoveCounter(const DerivedCopyMoveCounter& other)
145       : copies_(other.copies_),
146         assigns_(other.assigns_),
147         move_constructs_(other.move_constructs_),
148         move_assigns_(other.move_assigns_) {
149     (*copies_)++;
150   }
151
152   // Probing for moves from coercion.
153   explicit CopyMoveCounter(DerivedCopyMoveCounter&& other)
154       : copies_(other.copies_),
155         assigns_(other.assigns_),
156         move_constructs_(other.move_constructs_),
157         move_assigns_(other.move_assigns_) {
158     (*move_constructs_)++;
159   }
160
161   const CopyMoveCounter& operator=(const CopyMoveCounter& rhs) {
162     copies_ = rhs.copies_;
163     assigns_ = rhs.assigns_;
164     move_constructs_ = rhs.move_constructs_;
165     move_assigns_ = rhs.move_assigns_;
166
167     (*assigns_)++;
168
169     return *this;
170   }
171
172   const CopyMoveCounter& operator=(CopyMoveCounter&& rhs) {
173     copies_ = rhs.copies_;
174     assigns_ = rhs.assigns_;
175     move_constructs_ = rhs.move_constructs_;
176     move_assigns_ = rhs.move_assigns_;
177
178     (*move_assigns_)++;
179
180     return *this;
181   }
182
183   int copies() const {
184     return *copies_;
185   }
186
187  private:
188   int* copies_;
189   int* assigns_;
190   int* move_constructs_;
191   int* move_assigns_;
192 };
193
194 // Used for probing the number of copies in an argument. The instance is a
195 // copyable and non-movable type.
196 class CopyCounter {
197  public:
198   CopyCounter(int* copies, int* assigns)
199       : counter_(copies, assigns, nullptr, nullptr) {}
200   CopyCounter(const CopyCounter& other) = default;
201   CopyCounter& operator=(const CopyCounter& other) = default;
202
203   explicit CopyCounter(const DerivedCopyMoveCounter& other) : counter_(other) {}
204
205   int copies() const { return counter_.copies(); }
206
207  private:
208   CopyMoveCounter counter_;
209 };
210
211 // Used for probing the number of moves in an argument. The instance is a
212 // non-copyable and movable type.
213 class MoveCounter {
214  public:
215   MoveCounter(int* move_constructs, int* move_assigns)
216       : counter_(nullptr, nullptr, move_constructs, move_assigns) {}
217   MoveCounter(MoveCounter&& other) : counter_(std::move(other.counter_)) {}
218   MoveCounter& operator=(MoveCounter&& other) {
219     counter_ = std::move(other.counter_);
220     return *this;
221   }
222
223   explicit MoveCounter(DerivedCopyMoveCounter&& other)
224       : counter_(std::move(other)) {}
225
226  private:
227   CopyMoveCounter counter_;
228 };
229
230 class DeleteCounter {
231  public:
232   explicit DeleteCounter(int* deletes)
233       : deletes_(deletes) {
234   }
235
236   ~DeleteCounter() {
237     (*deletes_)++;
238   }
239
240   void VoidMethod0() {}
241
242  private:
243   int* deletes_;
244 };
245
246 template <typename T>
247 T PassThru(T scoper) {
248   return scoper;
249 }
250
251 // Some test functions that we can Bind to.
252 template <typename T>
253 T PolymorphicIdentity(T t) {
254   return t;
255 }
256
257 template <typename... Ts>
258 struct VoidPolymorphic {
259   static void Run(Ts... t) {}
260 };
261
262 int Identity(int n) {
263   return n;
264 }
265
266 int ArrayGet(const int array[], int n) {
267   return array[n];
268 }
269
270 int Sum(int a, int b, int c, int d, int e, int f) {
271   return a + b + c + d + e + f;
272 }
273
274 const char* CStringIdentity(const char* s) {
275   return s;
276 }
277
278 int GetCopies(const CopyMoveCounter& counter) {
279   return counter.copies();
280 }
281
282 int UnwrapNoRefParent(NoRefParent p) {
283   return p.value;
284 }
285
286 int UnwrapNoRefParentPtr(NoRefParent* p) {
287   return p->value;
288 }
289
290 int UnwrapNoRefParentConstRef(const NoRefParent& p) {
291   return p.value;
292 }
293
294 void RefArgSet(int &n) {
295   n = 2;
296 }
297
298 void PtrArgSet(int *n) {
299   *n = 2;
300 }
301
302 int FunctionWithWeakFirstParam(WeakPtr<NoRef> o, int n) {
303   return n;
304 }
305
306 int FunctionWithScopedRefptrFirstParam(const scoped_refptr<HasRef>& o, int n) {
307   return n;
308 }
309
310 void TakesACallback(const Closure& callback) {
311   callback.Run();
312 }
313
314 int Noexcept() noexcept {
315   return 42;
316 }
317
318 class BindTest : public ::testing::Test {
319  public:
320   BindTest() {
321     const_has_ref_ptr_ = &has_ref_;
322     const_no_ref_ptr_ = &no_ref_;
323     static_func_mock_ptr = &static_func_mock_;
324   }
325
326   ~BindTest() override = default;
327
328   static void VoidFunc0() {
329     static_func_mock_ptr->VoidMethod0();
330   }
331
332   static int IntFunc0() { return static_func_mock_ptr->IntMethod0(); }
333   int NoexceptMethod() noexcept { return 42; }
334   int ConstNoexceptMethod() const noexcept { return 42; }
335
336  protected:
337   StrictMock<NoRef> no_ref_;
338   StrictMock<HasRef> has_ref_;
339   const HasRef* const_has_ref_ptr_;
340   const NoRef* const_no_ref_ptr_;
341   StrictMock<NoRef> static_func_mock_;
342
343   // Used by the static functions to perform expectations.
344   static StrictMock<NoRef>* static_func_mock_ptr;
345
346  private:
347   DISALLOW_COPY_AND_ASSIGN(BindTest);
348 };
349
350 StrictMock<NoRef>* BindTest::static_func_mock_ptr;
351 StrictMock<NoRef>* g_func_mock_ptr;
352
353 void VoidFunc0() {
354   g_func_mock_ptr->VoidMethod0();
355 }
356
357 int IntFunc0() {
358   return g_func_mock_ptr->IntMethod0();
359 }
360
361 TEST_F(BindTest, BasicTest) {
362   Callback<int(int, int, int)> cb = Bind(&Sum, 32, 16, 8);
363   EXPECT_EQ(92, cb.Run(13, 12, 11));
364
365   Callback<int(int, int, int, int, int, int)> c1 = Bind(&Sum);
366   EXPECT_EQ(69, c1.Run(14, 13, 12, 11, 10, 9));
367
368   Callback<int(int, int, int)> c2 = Bind(c1, 32, 16, 8);
369   EXPECT_EQ(86, c2.Run(11, 10, 9));
370
371   Callback<int()> c3 = Bind(c2, 4, 2, 1);
372   EXPECT_EQ(63, c3.Run());
373 }
374
375 // Test that currying the rvalue result of another Bind() works correctly.
376 //   - rvalue should be usable as argument to Bind().
377 //   - multiple runs of resulting Callback remain valid.
378 TEST_F(BindTest, CurryingRvalueResultOfBind) {
379   int n = 0;
380   RepeatingClosure cb = BindRepeating(&TakesACallback,
381                                       BindRepeating(&PtrArgSet, &n));
382
383   // If we implement Bind() such that the return value has auto_ptr-like
384   // semantics, the second call here will fail because ownership of
385   // the internal BindState<> would have been transfered to a *temporary*
386   // constructon of a Callback object on the first call.
387   cb.Run();
388   EXPECT_EQ(2, n);
389
390   n = 0;
391   cb.Run();
392   EXPECT_EQ(2, n);
393 }
394
395 TEST_F(BindTest, RepeatingCallbackBasicTest) {
396   RepeatingCallback<int(int)> c0 = BindRepeating(&Sum, 1, 2, 4, 8, 16);
397
398   // RepeatingCallback can run via a lvalue-reference.
399   EXPECT_EQ(63, c0.Run(32));
400
401   // It is valid to call a RepeatingCallback more than once.
402   EXPECT_EQ(54, c0.Run(23));
403
404   // BindRepeating can handle a RepeatingCallback as the target functor.
405   RepeatingCallback<int()> c1 = BindRepeating(c0, 11);
406
407   // RepeatingCallback can run via a rvalue-reference.
408   EXPECT_EQ(42, std::move(c1).Run());
409
410   // BindRepeating can handle a rvalue-reference of RepeatingCallback.
411   EXPECT_EQ(32, BindRepeating(std::move(c0), 1).Run());
412 }
413
414 TEST_F(BindTest, OnceCallbackBasicTest) {
415   OnceCallback<int(int)> c0 = BindOnce(&Sum, 1, 2, 4, 8, 16);
416
417   // OnceCallback can run via a rvalue-reference.
418   EXPECT_EQ(63, std::move(c0).Run(32));
419
420   // After running via the rvalue-reference, the value of the OnceCallback
421   // is undefined. The implementation simply clears the instance after the
422   // invocation.
423   EXPECT_TRUE(c0.is_null());
424
425   c0 = BindOnce(&Sum, 2, 3, 5, 7, 11);
426
427   // BindOnce can handle a rvalue-reference of OnceCallback as the target
428   // functor.
429   OnceCallback<int()> c1 = BindOnce(std::move(c0), 13);
430   EXPECT_EQ(41, std::move(c1).Run());
431
432   RepeatingCallback<int(int)> c2 = BindRepeating(&Sum, 2, 3, 5, 7, 11);
433   EXPECT_EQ(41, BindOnce(c2, 13).Run());
434 }
435
436 // IgnoreResult adapter test.
437 //   - Function with return value.
438 //   - Method with return value.
439 //   - Const Method with return.
440 //   - Method with return value bound to WeakPtr<>.
441 //   - Const Method with return bound to WeakPtr<>.
442 TEST_F(BindTest, IgnoreResultForRepeating) {
443   EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
444   EXPECT_CALL(has_ref_, AddRef()).Times(2);
445   EXPECT_CALL(has_ref_, Release()).Times(2);
446   EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
447   EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
448   EXPECT_CALL(no_ref_, IntMethod0()).WillOnce(Return(12));
449   EXPECT_CALL(no_ref_, IntConstMethod0()).WillOnce(Return(13));
450
451   RepeatingClosure normal_func_cb = BindRepeating(IgnoreResult(&IntFunc0));
452   normal_func_cb.Run();
453
454   RepeatingClosure non_void_method_cb =
455       BindRepeating(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
456   non_void_method_cb.Run();
457
458   RepeatingClosure non_void_const_method_cb =
459       BindRepeating(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
460   non_void_const_method_cb.Run();
461
462   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
463   WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
464
465   RepeatingClosure non_void_weak_method_cb  =
466       BindRepeating(IgnoreResult(&NoRef::IntMethod0),
467                     weak_factory.GetWeakPtr());
468   non_void_weak_method_cb.Run();
469
470   RepeatingClosure non_void_weak_const_method_cb =
471       BindRepeating(IgnoreResult(&NoRef::IntConstMethod0),
472                     weak_factory.GetWeakPtr());
473   non_void_weak_const_method_cb.Run();
474
475   weak_factory.InvalidateWeakPtrs();
476   non_void_weak_const_method_cb.Run();
477   non_void_weak_method_cb.Run();
478 }
479
480 TEST_F(BindTest, IgnoreResultForOnce) {
481   EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
482   EXPECT_CALL(has_ref_, AddRef()).Times(2);
483   EXPECT_CALL(has_ref_, Release()).Times(2);
484   EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
485   EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
486
487   OnceClosure normal_func_cb = BindOnce(IgnoreResult(&IntFunc0));
488   std::move(normal_func_cb).Run();
489
490   OnceClosure non_void_method_cb =
491       BindOnce(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
492   std::move(non_void_method_cb).Run();
493
494   OnceClosure non_void_const_method_cb =
495       BindOnce(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
496   std::move(non_void_const_method_cb).Run();
497
498   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
499   WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
500
501   OnceClosure non_void_weak_method_cb  =
502       BindOnce(IgnoreResult(&NoRef::IntMethod0),
503                   weak_factory.GetWeakPtr());
504   OnceClosure non_void_weak_const_method_cb =
505       BindOnce(IgnoreResult(&NoRef::IntConstMethod0),
506                   weak_factory.GetWeakPtr());
507
508   weak_factory.InvalidateWeakPtrs();
509   std::move(non_void_weak_const_method_cb).Run();
510   std::move(non_void_weak_method_cb).Run();
511 }
512
513 // Functions that take reference parameters.
514 //  - Forced reference parameter type still stores a copy.
515 //  - Forced const reference parameter type still stores a copy.
516 TEST_F(BindTest, ReferenceArgumentBindingForRepeating) {
517   int n = 1;
518   int& ref_n = n;
519   const int& const_ref_n = n;
520
521   RepeatingCallback<int()> ref_copies_cb = BindRepeating(&Identity, ref_n);
522   EXPECT_EQ(n, ref_copies_cb.Run());
523   n++;
524   EXPECT_EQ(n - 1, ref_copies_cb.Run());
525
526   RepeatingCallback<int()> const_ref_copies_cb =
527       BindRepeating(&Identity, const_ref_n);
528   EXPECT_EQ(n, const_ref_copies_cb.Run());
529   n++;
530   EXPECT_EQ(n - 1, const_ref_copies_cb.Run());
531 }
532
533 TEST_F(BindTest, ReferenceArgumentBindingForOnce) {
534   int n = 1;
535   int& ref_n = n;
536   const int& const_ref_n = n;
537
538   OnceCallback<int()> ref_copies_cb = BindOnce(&Identity, ref_n);
539   n++;
540   EXPECT_EQ(n - 1, std::move(ref_copies_cb).Run());
541
542   OnceCallback<int()> const_ref_copies_cb =
543       BindOnce(&Identity, const_ref_n);
544   n++;
545   EXPECT_EQ(n - 1, std::move(const_ref_copies_cb).Run());
546 }
547
548 // Check that we can pass in arrays and have them be stored as a pointer.
549 //  - Array of values stores a pointer.
550 //  - Array of const values stores a pointer.
551 TEST_F(BindTest, ArrayArgumentBindingForRepeating) {
552   int array[4] = {1, 1, 1, 1};
553   const int (*const_array_ptr)[4] = &array;
554
555   RepeatingCallback<int()> array_cb = BindRepeating(&ArrayGet, array, 1);
556   EXPECT_EQ(1, array_cb.Run());
557
558   RepeatingCallback<int()> const_array_cb =
559       BindRepeating(&ArrayGet, *const_array_ptr, 1);
560   EXPECT_EQ(1, const_array_cb.Run());
561
562   array[1] = 3;
563   EXPECT_EQ(3, array_cb.Run());
564   EXPECT_EQ(3, const_array_cb.Run());
565 }
566
567 TEST_F(BindTest, ArrayArgumentBindingForOnce) {
568   int array[4] = {1, 1, 1, 1};
569   const int (*const_array_ptr)[4] = &array;
570
571   OnceCallback<int()> array_cb = BindOnce(&ArrayGet, array, 1);
572   OnceCallback<int()> const_array_cb =
573       BindOnce(&ArrayGet, *const_array_ptr, 1);
574
575   array[1] = 3;
576   EXPECT_EQ(3, std::move(array_cb).Run());
577   EXPECT_EQ(3, std::move(const_array_cb).Run());
578 }
579
580 // WeakPtr() support.
581 //   - Method bound to WeakPtr<> to non-const object.
582 //   - Const method bound to WeakPtr<> to non-const object.
583 //   - Const method bound to WeakPtr<> to const object.
584 //   - Normal Function with WeakPtr<> as P1 can have return type and is
585 //     not canceled.
586 TEST_F(BindTest, WeakPtrForRepeating) {
587   EXPECT_CALL(no_ref_, VoidMethod0());
588   EXPECT_CALL(no_ref_, VoidConstMethod0()).Times(2);
589
590   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
591   WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
592
593   RepeatingClosure method_cb =
594       BindRepeating(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
595   method_cb.Run();
596
597   RepeatingClosure const_method_cb =
598       BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
599   const_method_cb.Run();
600
601   RepeatingClosure const_method_const_ptr_cb =
602       BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
603   const_method_const_ptr_cb.Run();
604
605   RepeatingCallback<int(int)> normal_func_cb =
606       BindRepeating(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
607   EXPECT_EQ(1, normal_func_cb.Run(1));
608
609   weak_factory.InvalidateWeakPtrs();
610   const_weak_factory.InvalidateWeakPtrs();
611
612   method_cb.Run();
613   const_method_cb.Run();
614   const_method_const_ptr_cb.Run();
615
616   // Still runs even after the pointers are invalidated.
617   EXPECT_EQ(2, normal_func_cb.Run(2));
618 }
619
620 TEST_F(BindTest, WeakPtrForOnce) {
621   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
622   WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
623
624   OnceClosure method_cb =
625       BindOnce(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
626   OnceClosure const_method_cb =
627       BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
628   OnceClosure const_method_const_ptr_cb =
629       BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
630   Callback<int(int)> normal_func_cb =
631       Bind(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
632
633   weak_factory.InvalidateWeakPtrs();
634   const_weak_factory.InvalidateWeakPtrs();
635
636   std::move(method_cb).Run();
637   std::move(const_method_cb).Run();
638   std::move(const_method_const_ptr_cb).Run();
639
640   // Still runs even after the pointers are invalidated.
641   EXPECT_EQ(2, std::move(normal_func_cb).Run(2));
642 }
643
644 // ConstRef() wrapper support.
645 //   - Binding w/o ConstRef takes a copy.
646 //   - Binding a ConstRef takes a reference.
647 //   - Binding ConstRef to a function ConstRef does not copy on invoke.
648 TEST_F(BindTest, ConstRefForRepeating) {
649   int n = 1;
650
651   RepeatingCallback<int()> copy_cb = BindRepeating(&Identity, n);
652   RepeatingCallback<int()> const_ref_cb = BindRepeating(&Identity, ConstRef(n));
653   EXPECT_EQ(n, copy_cb.Run());
654   EXPECT_EQ(n, const_ref_cb.Run());
655   n++;
656   EXPECT_EQ(n - 1, copy_cb.Run());
657   EXPECT_EQ(n, const_ref_cb.Run());
658
659   int copies = 0;
660   int assigns = 0;
661   int move_constructs = 0;
662   int move_assigns = 0;
663   CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
664   RepeatingCallback<int()> all_const_ref_cb =
665       BindRepeating(&GetCopies, ConstRef(counter));
666   EXPECT_EQ(0, all_const_ref_cb.Run());
667   EXPECT_EQ(0, copies);
668   EXPECT_EQ(0, assigns);
669   EXPECT_EQ(0, move_constructs);
670   EXPECT_EQ(0, move_assigns);
671 }
672
673 TEST_F(BindTest, ConstRefForOnce) {
674   int n = 1;
675
676   OnceCallback<int()> copy_cb = BindOnce(&Identity, n);
677   OnceCallback<int()> const_ref_cb = BindOnce(&Identity, ConstRef(n));
678   n++;
679   EXPECT_EQ(n - 1, std::move(copy_cb).Run());
680   EXPECT_EQ(n, std::move(const_ref_cb).Run());
681
682   int copies = 0;
683   int assigns = 0;
684   int move_constructs = 0;
685   int move_assigns = 0;
686   CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
687   OnceCallback<int()> all_const_ref_cb =
688       BindOnce(&GetCopies, ConstRef(counter));
689   EXPECT_EQ(0, std::move(all_const_ref_cb).Run());
690   EXPECT_EQ(0, copies);
691   EXPECT_EQ(0, assigns);
692   EXPECT_EQ(0, move_constructs);
693   EXPECT_EQ(0, move_assigns);
694 }
695
696 // Test Owned() support.
697 TEST_F(BindTest, OwnedForRepeating) {
698   int deletes = 0;
699   DeleteCounter* counter = new DeleteCounter(&deletes);
700
701   // If we don't capture, delete happens on Callback destruction/reset.
702   // return the same value.
703   RepeatingCallback<DeleteCounter*()> no_capture_cb =
704       BindRepeating(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
705   ASSERT_EQ(counter, no_capture_cb.Run());
706   ASSERT_EQ(counter, no_capture_cb.Run());
707   EXPECT_EQ(0, deletes);
708   no_capture_cb.Reset();  // This should trigger a delete.
709   EXPECT_EQ(1, deletes);
710
711   deletes = 0;
712   counter = new DeleteCounter(&deletes);
713   RepeatingClosure own_object_cb =
714       BindRepeating(&DeleteCounter::VoidMethod0, Owned(counter));
715   own_object_cb.Run();
716   EXPECT_EQ(0, deletes);
717   own_object_cb.Reset();
718   EXPECT_EQ(1, deletes);
719 }
720
721 TEST_F(BindTest, OwnedForOnce) {
722   int deletes = 0;
723   DeleteCounter* counter = new DeleteCounter(&deletes);
724
725   // If we don't capture, delete happens on Callback destruction/reset.
726   // return the same value.
727   OnceCallback<DeleteCounter*()> no_capture_cb =
728       BindOnce(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
729   EXPECT_EQ(0, deletes);
730   no_capture_cb.Reset();  // This should trigger a delete.
731   EXPECT_EQ(1, deletes);
732
733   deletes = 0;
734   counter = new DeleteCounter(&deletes);
735   OnceClosure own_object_cb =
736       BindOnce(&DeleteCounter::VoidMethod0, Owned(counter));
737   EXPECT_EQ(0, deletes);
738   own_object_cb.Reset();
739   EXPECT_EQ(1, deletes);
740 }
741
742 template <typename T>
743 class BindVariantsTest : public ::testing::Test {
744 };
745
746 struct RepeatingTestConfig {
747   template <typename Signature>
748   using CallbackType = RepeatingCallback<Signature>;
749   using ClosureType = RepeatingClosure;
750
751   template <typename F, typename... Args>
752   static CallbackType<MakeUnboundRunType<F, Args...>>
753   Bind(F&& f, Args&&... args) {
754     return BindRepeating(std::forward<F>(f), std::forward<Args>(args)...);
755   }
756 };
757
758 struct OnceTestConfig {
759   template <typename Signature>
760   using CallbackType = OnceCallback<Signature>;
761   using ClosureType = OnceClosure;
762
763   template <typename F, typename... Args>
764   static CallbackType<MakeUnboundRunType<F, Args...>>
765   Bind(F&& f, Args&&... args) {
766     return BindOnce(std::forward<F>(f), std::forward<Args>(args)...);
767   }
768 };
769
770 using BindVariantsTestConfig = ::testing::Types<
771   RepeatingTestConfig, OnceTestConfig>;
772 TYPED_TEST_CASE(BindVariantsTest, BindVariantsTestConfig);
773
774 template <typename TypeParam, typename Signature>
775 using CallbackType = typename TypeParam::template CallbackType<Signature>;
776
777 // Function type support.
778 //   - Normal function.
779 //   - Normal function bound with non-refcounted first argument.
780 //   - Method bound to non-const object.
781 //   - Method bound to scoped_refptr.
782 //   - Const method bound to non-const object.
783 //   - Const method bound to const object.
784 //   - Derived classes can be used with pointers to non-virtual base functions.
785 //   - Derived classes can be used with pointers to virtual base functions (and
786 //     preserve virtual dispatch).
787 TYPED_TEST(BindVariantsTest, FunctionTypeSupport) {
788   using ClosureType = typename TypeParam::ClosureType;
789
790   StrictMock<HasRef> has_ref;
791   StrictMock<NoRef> no_ref;
792   StrictMock<NoRef> static_func_mock;
793   const HasRef* const_has_ref_ptr = &has_ref;
794   g_func_mock_ptr = &static_func_mock;
795
796   EXPECT_CALL(static_func_mock, VoidMethod0());
797   EXPECT_CALL(has_ref, AddRef()).Times(4);
798   EXPECT_CALL(has_ref, Release()).Times(4);
799   EXPECT_CALL(has_ref, VoidMethod0()).Times(2);
800   EXPECT_CALL(has_ref, VoidConstMethod0()).Times(2);
801
802   ClosureType normal_cb = TypeParam::Bind(&VoidFunc0);
803   CallbackType<TypeParam, NoRef*()> normal_non_refcounted_cb =
804       TypeParam::Bind(&PolymorphicIdentity<NoRef*>, &no_ref);
805   std::move(normal_cb).Run();
806   EXPECT_EQ(&no_ref, std::move(normal_non_refcounted_cb).Run());
807
808   ClosureType method_cb = TypeParam::Bind(&HasRef::VoidMethod0, &has_ref);
809   ClosureType method_refptr_cb =
810       TypeParam::Bind(&HasRef::VoidMethod0, WrapRefCounted(&has_ref));
811   ClosureType const_method_nonconst_obj_cb =
812       TypeParam::Bind(&HasRef::VoidConstMethod0, &has_ref);
813   ClosureType const_method_const_obj_cb =
814       TypeParam::Bind(&HasRef::VoidConstMethod0, const_has_ref_ptr);
815   std::move(method_cb).Run();
816   std::move(method_refptr_cb).Run();
817   std::move(const_method_nonconst_obj_cb).Run();
818   std::move(const_method_const_obj_cb).Run();
819
820   Child child;
821   child.value = 0;
822   ClosureType virtual_set_cb = TypeParam::Bind(&Parent::VirtualSet, &child);
823   std::move(virtual_set_cb).Run();
824   EXPECT_EQ(kChildValue, child.value);
825
826   child.value = 0;
827   ClosureType non_virtual_set_cb =
828       TypeParam::Bind(&Parent::NonVirtualSet, &child);
829   std::move(non_virtual_set_cb).Run();
830   EXPECT_EQ(kParentValue, child.value);
831 }
832
833 // Return value support.
834 //   - Function with return value.
835 //   - Method with return value.
836 //   - Const method with return value.
837 //   - Move-only return value.
838 TYPED_TEST(BindVariantsTest, ReturnValues) {
839   StrictMock<NoRef> static_func_mock;
840   StrictMock<HasRef> has_ref;
841   g_func_mock_ptr = &static_func_mock;
842   const HasRef* const_has_ref_ptr = &has_ref;
843
844   EXPECT_CALL(static_func_mock, IntMethod0()).WillOnce(Return(1337));
845   EXPECT_CALL(has_ref, AddRef()).Times(4);
846   EXPECT_CALL(has_ref, Release()).Times(4);
847   EXPECT_CALL(has_ref, IntMethod0()).WillOnce(Return(31337));
848   EXPECT_CALL(has_ref, IntConstMethod0())
849       .WillOnce(Return(41337))
850       .WillOnce(Return(51337));
851   EXPECT_CALL(has_ref, UniquePtrMethod0())
852       .WillOnce(Return(ByMove(std::make_unique<int>(42))));
853
854   CallbackType<TypeParam, int()> normal_cb = TypeParam::Bind(&IntFunc0);
855   CallbackType<TypeParam, int()> method_cb =
856       TypeParam::Bind(&HasRef::IntMethod0, &has_ref);
857   CallbackType<TypeParam, int()> const_method_nonconst_obj_cb =
858       TypeParam::Bind(&HasRef::IntConstMethod0, &has_ref);
859   CallbackType<TypeParam, int()> const_method_const_obj_cb =
860       TypeParam::Bind(&HasRef::IntConstMethod0, const_has_ref_ptr);
861   CallbackType<TypeParam, std::unique_ptr<int>()> move_only_rv_cb =
862       TypeParam::Bind(&HasRef::UniquePtrMethod0, &has_ref);
863   EXPECT_EQ(1337, std::move(normal_cb).Run());
864   EXPECT_EQ(31337, std::move(method_cb).Run());
865   EXPECT_EQ(41337, std::move(const_method_nonconst_obj_cb).Run());
866   EXPECT_EQ(51337, std::move(const_method_const_obj_cb).Run());
867   EXPECT_EQ(42, *std::move(move_only_rv_cb).Run());
868 }
869
870 // Argument binding tests.
871 //   - Argument binding to primitive.
872 //   - Argument binding to primitive pointer.
873 //   - Argument binding to a literal integer.
874 //   - Argument binding to a literal string.
875 //   - Argument binding with template function.
876 //   - Argument binding to an object.
877 //   - Argument binding to pointer to incomplete type.
878 //   - Argument gets type converted.
879 //   - Pointer argument gets converted.
880 //   - Const Reference forces conversion.
881 TYPED_TEST(BindVariantsTest, ArgumentBinding) {
882   int n = 2;
883
884   EXPECT_EQ(n, TypeParam::Bind(&Identity, n).Run());
885   EXPECT_EQ(&n, TypeParam::Bind(&PolymorphicIdentity<int*>, &n).Run());
886   EXPECT_EQ(3, TypeParam::Bind(&Identity, 3).Run());
887   EXPECT_STREQ("hi", TypeParam::Bind(&CStringIdentity, "hi").Run());
888   EXPECT_EQ(4, TypeParam::Bind(&PolymorphicIdentity<int>, 4).Run());
889
890   NoRefParent p;
891   p.value = 5;
892   EXPECT_EQ(5, TypeParam::Bind(&UnwrapNoRefParent, p).Run());
893
894   IncompleteType* incomplete_ptr = reinterpret_cast<IncompleteType*>(123);
895   EXPECT_EQ(incomplete_ptr,
896             TypeParam::Bind(&PolymorphicIdentity<IncompleteType*>,
897                             incomplete_ptr).Run());
898
899   NoRefChild c;
900   c.value = 6;
901   EXPECT_EQ(6, TypeParam::Bind(&UnwrapNoRefParent, c).Run());
902
903   c.value = 7;
904   EXPECT_EQ(7, TypeParam::Bind(&UnwrapNoRefParentPtr, &c).Run());
905
906   c.value = 8;
907   EXPECT_EQ(8, TypeParam::Bind(&UnwrapNoRefParentConstRef, c).Run());
908 }
909
910 // Unbound argument type support tests.
911 //   - Unbound value.
912 //   - Unbound pointer.
913 //   - Unbound reference.
914 //   - Unbound const reference.
915 //   - Unbound unsized array.
916 //   - Unbound sized array.
917 //   - Unbound array-of-arrays.
918 TYPED_TEST(BindVariantsTest, UnboundArgumentTypeSupport) {
919   CallbackType<TypeParam, void(int)> unbound_value_cb =
920       TypeParam::Bind(&VoidPolymorphic<int>::Run);
921   CallbackType<TypeParam, void(int*)> unbound_pointer_cb =
922       TypeParam::Bind(&VoidPolymorphic<int*>::Run);
923   CallbackType<TypeParam, void(int&)> unbound_ref_cb =
924       TypeParam::Bind(&VoidPolymorphic<int&>::Run);
925   CallbackType<TypeParam, void(const int&)> unbound_const_ref_cb =
926       TypeParam::Bind(&VoidPolymorphic<const int&>::Run);
927   CallbackType<TypeParam, void(int[])> unbound_unsized_array_cb =
928       TypeParam::Bind(&VoidPolymorphic<int[]>::Run);
929   CallbackType<TypeParam, void(int[2])> unbound_sized_array_cb =
930       TypeParam::Bind(&VoidPolymorphic<int[2]>::Run);
931   CallbackType<TypeParam, void(int[][2])> unbound_array_of_arrays_cb =
932       TypeParam::Bind(&VoidPolymorphic<int[][2]>::Run);
933   CallbackType<TypeParam, void(int&)> unbound_ref_with_bound_arg =
934       TypeParam::Bind(&VoidPolymorphic<int, int&>::Run, 1);
935 }
936
937 // Function with unbound reference parameter.
938 //   - Original parameter is modified by callback.
939 TYPED_TEST(BindVariantsTest, UnboundReferenceSupport) {
940   int n = 0;
941   CallbackType<TypeParam, void(int&)> unbound_ref_cb =
942       TypeParam::Bind(&RefArgSet);
943   std::move(unbound_ref_cb).Run(n);
944   EXPECT_EQ(2, n);
945 }
946
947 // Unretained() wrapper support.
948 //   - Method bound to Unretained() non-const object.
949 //   - Const method bound to Unretained() non-const object.
950 //   - Const method bound to Unretained() const object.
951 TYPED_TEST(BindVariantsTest, Unretained) {
952   StrictMock<NoRef> no_ref;
953   const NoRef* const_no_ref_ptr = &no_ref;
954
955   EXPECT_CALL(no_ref, VoidMethod0());
956   EXPECT_CALL(no_ref, VoidConstMethod0()).Times(2);
957
958   TypeParam::Bind(&NoRef::VoidMethod0, Unretained(&no_ref)).Run();
959   TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(&no_ref)).Run();
960   TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(const_no_ref_ptr)).Run();
961 }
962
963 TYPED_TEST(BindVariantsTest, ScopedRefptr) {
964   StrictMock<HasRef> has_ref;
965   EXPECT_CALL(has_ref, AddRef()).Times(1);
966   EXPECT_CALL(has_ref, Release()).Times(1);
967
968   const scoped_refptr<HasRef> refptr(&has_ref);
969   CallbackType<TypeParam, int()> scoped_refptr_const_ref_cb =
970       TypeParam::Bind(&FunctionWithScopedRefptrFirstParam,
971                       base::ConstRef(refptr), 1);
972   EXPECT_EQ(1, std::move(scoped_refptr_const_ref_cb).Run());
973 }
974
975 TYPED_TEST(BindVariantsTest, UniquePtrReceiver) {
976   std::unique_ptr<StrictMock<NoRef>> no_ref(new StrictMock<NoRef>);
977   EXPECT_CALL(*no_ref, VoidMethod0()).Times(1);
978   TypeParam::Bind(&NoRef::VoidMethod0, std::move(no_ref)).Run();
979 }
980
981 // Tests for Passed() wrapper support:
982 //   - Passed() can be constructed from a pointer to scoper.
983 //   - Passed() can be constructed from a scoper rvalue.
984 //   - Using Passed() gives Callback Ownership.
985 //   - Ownership is transferred from Callback to callee on the first Run().
986 //   - Callback supports unbound arguments.
987 template <typename T>
988 class BindMoveOnlyTypeTest : public ::testing::Test {
989 };
990
991 struct CustomDeleter {
992   void operator()(DeleteCounter* c) { delete c; }
993 };
994
995 using MoveOnlyTypesToTest =
996     ::testing::Types<std::unique_ptr<DeleteCounter>,
997                      std::unique_ptr<DeleteCounter, CustomDeleter>>;
998 TYPED_TEST_CASE(BindMoveOnlyTypeTest, MoveOnlyTypesToTest);
999
1000 TYPED_TEST(BindMoveOnlyTypeTest, PassedToBoundCallback) {
1001   int deletes = 0;
1002
1003   TypeParam ptr(new DeleteCounter(&deletes));
1004   Callback<TypeParam()> callback = Bind(&PassThru<TypeParam>, Passed(&ptr));
1005   EXPECT_FALSE(ptr.get());
1006   EXPECT_EQ(0, deletes);
1007
1008   // If we never invoke the Callback, it retains ownership and deletes.
1009   callback.Reset();
1010   EXPECT_EQ(1, deletes);
1011 }
1012
1013 TYPED_TEST(BindMoveOnlyTypeTest, PassedWithRvalue) {
1014   int deletes = 0;
1015   Callback<TypeParam()> callback = Bind(
1016       &PassThru<TypeParam>, Passed(TypeParam(new DeleteCounter(&deletes))));
1017   EXPECT_EQ(0, deletes);
1018
1019   // If we never invoke the Callback, it retains ownership and deletes.
1020   callback.Reset();
1021   EXPECT_EQ(1, deletes);
1022 }
1023
1024 // Check that ownership can be transferred back out.
1025 TYPED_TEST(BindMoveOnlyTypeTest, ReturnMoveOnlyType) {
1026   int deletes = 0;
1027   DeleteCounter* counter = new DeleteCounter(&deletes);
1028   Callback<TypeParam()> callback =
1029       Bind(&PassThru<TypeParam>, Passed(TypeParam(counter)));
1030   TypeParam result = callback.Run();
1031   ASSERT_EQ(counter, result.get());
1032   EXPECT_EQ(0, deletes);
1033
1034   // Resetting does not delete since ownership was transferred.
1035   callback.Reset();
1036   EXPECT_EQ(0, deletes);
1037
1038   // Ensure that we actually did get ownership.
1039   result.reset();
1040   EXPECT_EQ(1, deletes);
1041 }
1042
1043 TYPED_TEST(BindMoveOnlyTypeTest, UnboundForwarding) {
1044   int deletes = 0;
1045   TypeParam ptr(new DeleteCounter(&deletes));
1046   // Test unbound argument forwarding.
1047   Callback<TypeParam(TypeParam)> cb_unbound = Bind(&PassThru<TypeParam>);
1048   cb_unbound.Run(std::move(ptr));
1049   EXPECT_EQ(1, deletes);
1050 }
1051
1052 void VerifyVector(const std::vector<std::unique_ptr<int>>& v) {
1053   ASSERT_EQ(1u, v.size());
1054   EXPECT_EQ(12345, *v[0]);
1055 }
1056
1057 std::vector<std::unique_ptr<int>> AcceptAndReturnMoveOnlyVector(
1058     std::vector<std::unique_ptr<int>> v) {
1059   VerifyVector(v);
1060   return v;
1061 }
1062
1063 // Test that a vector containing move-only types can be used with Callback.
1064 TEST_F(BindTest, BindMoveOnlyVector) {
1065   using MoveOnlyVector = std::vector<std::unique_ptr<int>>;
1066
1067   MoveOnlyVector v;
1068   v.push_back(WrapUnique(new int(12345)));
1069
1070   // Early binding should work:
1071   base::Callback<MoveOnlyVector()> bound_cb =
1072       base::Bind(&AcceptAndReturnMoveOnlyVector, Passed(&v));
1073   MoveOnlyVector intermediate_result = bound_cb.Run();
1074   VerifyVector(intermediate_result);
1075
1076   // As should passing it as an argument to Run():
1077   base::Callback<MoveOnlyVector(MoveOnlyVector)> unbound_cb =
1078       base::Bind(&AcceptAndReturnMoveOnlyVector);
1079   MoveOnlyVector final_result = unbound_cb.Run(std::move(intermediate_result));
1080   VerifyVector(final_result);
1081 }
1082
1083 // Argument copy-constructor usage for non-reference copy-only parameters.
1084 //   - Bound arguments are only copied once.
1085 //   - Forwarded arguments are only copied once.
1086 //   - Forwarded arguments with coercions are only copied twice (once for the
1087 //     coercion, and one for the final dispatch).
1088 TEST_F(BindTest, ArgumentCopies) {
1089   int copies = 0;
1090   int assigns = 0;
1091
1092   CopyCounter counter(&copies, &assigns);
1093   Bind(&VoidPolymorphic<CopyCounter>::Run, counter);
1094   EXPECT_EQ(1, copies);
1095   EXPECT_EQ(0, assigns);
1096
1097   copies = 0;
1098   assigns = 0;
1099   Bind(&VoidPolymorphic<CopyCounter>::Run, CopyCounter(&copies, &assigns));
1100   EXPECT_EQ(1, copies);
1101   EXPECT_EQ(0, assigns);
1102
1103   copies = 0;
1104   assigns = 0;
1105   Bind(&VoidPolymorphic<CopyCounter>::Run).Run(counter);
1106   EXPECT_EQ(2, copies);
1107   EXPECT_EQ(0, assigns);
1108
1109   copies = 0;
1110   assigns = 0;
1111   Bind(&VoidPolymorphic<CopyCounter>::Run).Run(CopyCounter(&copies, &assigns));
1112   EXPECT_EQ(1, copies);
1113   EXPECT_EQ(0, assigns);
1114
1115   copies = 0;
1116   assigns = 0;
1117   DerivedCopyMoveCounter derived(&copies, &assigns, nullptr, nullptr);
1118   Bind(&VoidPolymorphic<CopyCounter>::Run).Run(CopyCounter(derived));
1119   EXPECT_EQ(2, copies);
1120   EXPECT_EQ(0, assigns);
1121
1122   copies = 0;
1123   assigns = 0;
1124   Bind(&VoidPolymorphic<CopyCounter>::Run)
1125       .Run(CopyCounter(
1126           DerivedCopyMoveCounter(&copies, &assigns, nullptr, nullptr)));
1127   EXPECT_EQ(2, copies);
1128   EXPECT_EQ(0, assigns);
1129 }
1130
1131 // Argument move-constructor usage for move-only parameters.
1132 //   - Bound arguments passed by move are not copied.
1133 TEST_F(BindTest, ArgumentMoves) {
1134   int move_constructs = 0;
1135   int move_assigns = 0;
1136
1137   Bind(&VoidPolymorphic<const MoveCounter&>::Run,
1138        MoveCounter(&move_constructs, &move_assigns));
1139   EXPECT_EQ(1, move_constructs);
1140   EXPECT_EQ(0, move_assigns);
1141
1142   // TODO(tzik): Support binding move-only type into a non-reference parameter
1143   // of a variant of Callback.
1144
1145   move_constructs = 0;
1146   move_assigns = 0;
1147   Bind(&VoidPolymorphic<MoveCounter>::Run)
1148       .Run(MoveCounter(&move_constructs, &move_assigns));
1149   EXPECT_EQ(1, move_constructs);
1150   EXPECT_EQ(0, move_assigns);
1151
1152   move_constructs = 0;
1153   move_assigns = 0;
1154   Bind(&VoidPolymorphic<MoveCounter>::Run)
1155       .Run(MoveCounter(DerivedCopyMoveCounter(
1156           nullptr, nullptr, &move_constructs, &move_assigns)));
1157   EXPECT_EQ(2, move_constructs);
1158   EXPECT_EQ(0, move_assigns);
1159 }
1160
1161 // Argument constructor usage for non-reference movable-copyable
1162 // parameters.
1163 //   - Bound arguments passed by move are not copied.
1164 //   - Forwarded arguments are only copied once.
1165 //   - Forwarded arguments with coercions are only copied once and moved once.
1166 TEST_F(BindTest, ArgumentCopiesAndMoves) {
1167   int copies = 0;
1168   int assigns = 0;
1169   int move_constructs = 0;
1170   int move_assigns = 0;
1171
1172   CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
1173   Bind(&VoidPolymorphic<CopyMoveCounter>::Run, counter);
1174   EXPECT_EQ(1, copies);
1175   EXPECT_EQ(0, assigns);
1176   EXPECT_EQ(0, move_constructs);
1177   EXPECT_EQ(0, move_assigns);
1178
1179   copies = 0;
1180   assigns = 0;
1181   move_constructs = 0;
1182   move_assigns = 0;
1183   Bind(&VoidPolymorphic<CopyMoveCounter>::Run,
1184        CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
1185   EXPECT_EQ(0, copies);
1186   EXPECT_EQ(0, assigns);
1187   EXPECT_EQ(1, move_constructs);
1188   EXPECT_EQ(0, move_assigns);
1189
1190   copies = 0;
1191   assigns = 0;
1192   move_constructs = 0;
1193   move_assigns = 0;
1194   Bind(&VoidPolymorphic<CopyMoveCounter>::Run).Run(counter);
1195   EXPECT_EQ(1, copies);
1196   EXPECT_EQ(0, assigns);
1197   EXPECT_EQ(1, move_constructs);
1198   EXPECT_EQ(0, move_assigns);
1199
1200   copies = 0;
1201   assigns = 0;
1202   move_constructs = 0;
1203   move_assigns = 0;
1204   Bind(&VoidPolymorphic<CopyMoveCounter>::Run)
1205       .Run(CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
1206   EXPECT_EQ(0, copies);
1207   EXPECT_EQ(0, assigns);
1208   EXPECT_EQ(1, move_constructs);
1209   EXPECT_EQ(0, move_assigns);
1210
1211   DerivedCopyMoveCounter derived_counter(&copies, &assigns, &move_constructs,
1212                                          &move_assigns);
1213   copies = 0;
1214   assigns = 0;
1215   move_constructs = 0;
1216   move_assigns = 0;
1217   Bind(&VoidPolymorphic<CopyMoveCounter>::Run)
1218       .Run(CopyMoveCounter(derived_counter));
1219   EXPECT_EQ(1, copies);
1220   EXPECT_EQ(0, assigns);
1221   EXPECT_EQ(1, move_constructs);
1222   EXPECT_EQ(0, move_assigns);
1223
1224   copies = 0;
1225   assigns = 0;
1226   move_constructs = 0;
1227   move_assigns = 0;
1228   Bind(&VoidPolymorphic<CopyMoveCounter>::Run)
1229       .Run(CopyMoveCounter(DerivedCopyMoveCounter(
1230           &copies, &assigns, &move_constructs, &move_assigns)));
1231   EXPECT_EQ(0, copies);
1232   EXPECT_EQ(0, assigns);
1233   EXPECT_EQ(2, move_constructs);
1234   EXPECT_EQ(0, move_assigns);
1235 }
1236
1237 TEST_F(BindTest, CapturelessLambda) {
1238   EXPECT_FALSE(internal::IsCallableObject<void>::value);
1239   EXPECT_FALSE(internal::IsCallableObject<int>::value);
1240   EXPECT_FALSE(internal::IsCallableObject<void (*)()>::value);
1241   EXPECT_FALSE(internal::IsCallableObject<void (NoRef::*)()>::value);
1242
1243   auto f = []() {};
1244   EXPECT_TRUE(internal::IsCallableObject<decltype(f)>::value);
1245
1246   int i = 0;
1247   auto g = [i]() { (void)i; };
1248   EXPECT_TRUE(internal::IsCallableObject<decltype(g)>::value);
1249
1250   auto h = [](int, double) { return 'k'; };
1251   EXPECT_TRUE((std::is_same<
1252       char(int, double),
1253       internal::ExtractCallableRunType<decltype(h)>>::value));
1254
1255   EXPECT_EQ(42, Bind([] { return 42; }).Run());
1256   EXPECT_EQ(42, Bind([](int i) { return i * 7; }, 6).Run());
1257
1258   int x = 1;
1259   base::Callback<void(int)> cb =
1260       Bind([](int* x, int i) { *x *= i; }, Unretained(&x));
1261   cb.Run(6);
1262   EXPECT_EQ(6, x);
1263   cb.Run(7);
1264   EXPECT_EQ(42, x);
1265 }
1266
1267 TEST_F(BindTest, EmptyFunctor) {
1268   struct NonEmptyFunctor {
1269     int operator()() const { return x; }
1270     int x = 42;
1271   };
1272
1273   struct EmptyFunctor {
1274     int operator()() { return 42; }
1275   };
1276
1277   struct EmptyFunctorConst {
1278     int operator()() const { return 42; }
1279   };
1280
1281   EXPECT_TRUE(internal::IsCallableObject<NonEmptyFunctor>::value);
1282   EXPECT_TRUE(internal::IsCallableObject<EmptyFunctor>::value);
1283   EXPECT_TRUE(internal::IsCallableObject<EmptyFunctorConst>::value);
1284   EXPECT_EQ(42, BindOnce(EmptyFunctor()).Run());
1285   EXPECT_EQ(42, BindOnce(EmptyFunctorConst()).Run());
1286   EXPECT_EQ(42, BindRepeating(EmptyFunctorConst()).Run());
1287 }
1288
1289 TEST_F(BindTest, CapturingLambdaForTesting) {
1290   int x = 6;
1291   EXPECT_EQ(42, BindLambdaForTesting([=](int y) { return x * y; }).Run(7));
1292
1293   auto f = [x](std::unique_ptr<int> y) { return x * *y; };
1294   EXPECT_EQ(42, BindLambdaForTesting(f).Run(std::make_unique<int>(7)));
1295 }
1296
1297 TEST_F(BindTest, Cancellation) {
1298   EXPECT_CALL(no_ref_, VoidMethodWithIntArg(_)).Times(2);
1299
1300   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
1301   RepeatingCallback<void(int)> cb =
1302       BindRepeating(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
1303   RepeatingClosure cb2 = BindRepeating(cb, 8);
1304   OnceClosure cb3 = BindOnce(cb, 8);
1305
1306   OnceCallback<void(int)> cb4 =
1307       BindOnce(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
1308   EXPECT_FALSE(cb4.IsCancelled());
1309
1310   OnceClosure cb5 = BindOnce(std::move(cb4), 8);
1311
1312   EXPECT_FALSE(cb.IsCancelled());
1313   EXPECT_FALSE(cb2.IsCancelled());
1314   EXPECT_FALSE(cb3.IsCancelled());
1315   EXPECT_FALSE(cb5.IsCancelled());
1316
1317   cb.Run(6);
1318   cb2.Run();
1319
1320   weak_factory.InvalidateWeakPtrs();
1321
1322   EXPECT_TRUE(cb.IsCancelled());
1323   EXPECT_TRUE(cb2.IsCancelled());
1324   EXPECT_TRUE(cb3.IsCancelled());
1325   EXPECT_TRUE(cb5.IsCancelled());
1326
1327   cb.Run(6);
1328   cb2.Run();
1329   std::move(cb3).Run();
1330   std::move(cb5).Run();
1331 }
1332
1333 TEST_F(BindTest, OnceCallback) {
1334   // Check if Callback variants have declarations of conversions as expected.
1335   // Copy constructor and assignment of RepeatingCallback.
1336   static_assert(std::is_constructible<
1337       RepeatingClosure, const RepeatingClosure&>::value,
1338       "RepeatingClosure should be copyable.");
1339   static_assert(
1340       std::is_assignable<RepeatingClosure, const RepeatingClosure&>::value,
1341       "RepeatingClosure should be copy-assignable.");
1342
1343   // Move constructor and assignment of RepeatingCallback.
1344   static_assert(std::is_constructible<
1345       RepeatingClosure, RepeatingClosure&&>::value,
1346       "RepeatingClosure should be movable.");
1347   static_assert(std::is_assignable<RepeatingClosure, RepeatingClosure&&>::value,
1348                 "RepeatingClosure should be move-assignable");
1349
1350   // Conversions from OnceCallback to RepeatingCallback.
1351   static_assert(!std::is_constructible<
1352       RepeatingClosure, const OnceClosure&>::value,
1353       "OnceClosure should not be convertible to RepeatingClosure.");
1354   static_assert(
1355       !std::is_assignable<RepeatingClosure, const OnceClosure&>::value,
1356       "OnceClosure should not be convertible to RepeatingClosure.");
1357
1358   // Destructive conversions from OnceCallback to RepeatingCallback.
1359   static_assert(!std::is_constructible<
1360       RepeatingClosure, OnceClosure&&>::value,
1361       "OnceClosure should not be convertible to RepeatingClosure.");
1362   static_assert(!std::is_assignable<RepeatingClosure, OnceClosure&&>::value,
1363                 "OnceClosure should not be convertible to RepeatingClosure.");
1364
1365   // Copy constructor and assignment of OnceCallback.
1366   static_assert(!std::is_constructible<
1367       OnceClosure, const OnceClosure&>::value,
1368       "OnceClosure should not be copyable.");
1369   static_assert(!std::is_assignable<OnceClosure, const OnceClosure&>::value,
1370                 "OnceClosure should not be copy-assignable");
1371
1372   // Move constructor and assignment of OnceCallback.
1373   static_assert(std::is_constructible<
1374       OnceClosure, OnceClosure&&>::value,
1375       "OnceClosure should be movable.");
1376   static_assert(std::is_assignable<OnceClosure, OnceClosure&&>::value,
1377                 "OnceClosure should be move-assignable.");
1378
1379   // Conversions from RepeatingCallback to OnceCallback.
1380   static_assert(std::is_constructible<
1381       OnceClosure, const RepeatingClosure&>::value,
1382       "RepeatingClosure should be convertible to OnceClosure.");
1383   static_assert(std::is_assignable<OnceClosure, const RepeatingClosure&>::value,
1384                 "RepeatingClosure should be convertible to OnceClosure.");
1385
1386   // Destructive conversions from RepeatingCallback to OnceCallback.
1387   static_assert(std::is_constructible<
1388       OnceClosure, RepeatingClosure&&>::value,
1389       "RepeatingClosure should be convertible to OnceClosure.");
1390   static_assert(std::is_assignable<OnceClosure, RepeatingClosure&&>::value,
1391                 "RepeatingClosure should be covretible to OnceClosure.");
1392
1393   OnceClosure cb = BindOnce(&VoidPolymorphic<>::Run);
1394   std::move(cb).Run();
1395
1396   // RepeatingCallback should be convertible to OnceCallback.
1397   OnceClosure cb2 = BindRepeating(&VoidPolymorphic<>::Run);
1398   std::move(cb2).Run();
1399
1400   RepeatingClosure cb3 = BindRepeating(&VoidPolymorphic<>::Run);
1401   cb = cb3;
1402   std::move(cb).Run();
1403
1404   cb = std::move(cb2);
1405
1406   OnceCallback<void(int)> cb4 =
1407       BindOnce(&VoidPolymorphic<std::unique_ptr<int>, int>::Run,
1408                std::make_unique<int>(0));
1409   BindOnce(std::move(cb4), 1).Run();
1410 }
1411
1412 // Callback construction and assignment tests.
1413 //   - Construction from an InvokerStorageHolder should not cause ref/deref.
1414 //   - Assignment from other callback should only cause one ref
1415 //
1416 // TODO(ajwong): Is there actually a way to test this?
1417
1418 #if defined(OS_WIN)
1419 int __fastcall FastCallFunc(int n) {
1420   return n;
1421 }
1422
1423 int __stdcall StdCallFunc(int n) {
1424   return n;
1425 }
1426
1427 // Windows specific calling convention support.
1428 //   - Can bind a __fastcall function.
1429 //   - Can bind a __stdcall function.
1430 TEST_F(BindTest, WindowsCallingConventions) {
1431   Callback<int()> fastcall_cb = Bind(&FastCallFunc, 1);
1432   EXPECT_EQ(1, fastcall_cb.Run());
1433
1434   Callback<int()> stdcall_cb = Bind(&StdCallFunc, 2);
1435   EXPECT_EQ(2, stdcall_cb.Run());
1436 }
1437 #endif
1438
1439 // Test unwrapping the various wrapping functions.
1440
1441 TEST_F(BindTest, UnwrapUnretained) {
1442   int i = 0;
1443   auto unretained = Unretained(&i);
1444   EXPECT_EQ(&i, internal::Unwrap(unretained));
1445   EXPECT_EQ(&i, internal::Unwrap(std::move(unretained)));
1446 }
1447
1448 TEST_F(BindTest, UnwrapConstRef) {
1449   int p = 0;
1450   auto const_ref = ConstRef(p);
1451   EXPECT_EQ(&p, &internal::Unwrap(const_ref));
1452   EXPECT_EQ(&p, &internal::Unwrap(std::move(const_ref)));
1453 }
1454
1455 TEST_F(BindTest, UnwrapRetainedRef) {
1456   auto p = MakeRefCounted<RefCountedData<int>>();
1457   auto retained_ref = RetainedRef(p);
1458   EXPECT_EQ(p.get(), internal::Unwrap(retained_ref));
1459   EXPECT_EQ(p.get(), internal::Unwrap(std::move(retained_ref)));
1460 }
1461
1462 TEST_F(BindTest, UnwrapOwned) {
1463   int* p = new int;
1464   auto owned = Owned(p);
1465   EXPECT_EQ(p, internal::Unwrap(owned));
1466   EXPECT_EQ(p, internal::Unwrap(std::move(owned)));
1467 }
1468
1469 TEST_F(BindTest, UnwrapPassed) {
1470   int* p = new int;
1471   auto passed = Passed(WrapUnique(p));
1472   EXPECT_EQ(p, internal::Unwrap(passed).get());
1473
1474   p = new int;
1475   EXPECT_EQ(p, internal::Unwrap(Passed(WrapUnique(p))).get());
1476 }
1477
1478 TEST_F(BindTest, BindNoexcept) {
1479   EXPECT_EQ(42, base::BindOnce(&Noexcept).Run());
1480   EXPECT_EQ(
1481       42,
1482       base::BindOnce(&BindTest::NoexceptMethod, base::Unretained(this)).Run());
1483   EXPECT_EQ(
1484       42, base::BindOnce(&BindTest::ConstNoexceptMethod, base::Unretained(this))
1485               .Run());
1486 }
1487
1488 // Test null callbacks cause a DCHECK.
1489 TEST(BindDeathTest, NullCallback) {
1490   base::Callback<void(int)> null_cb;
1491   ASSERT_TRUE(null_cb.is_null());
1492   EXPECT_DCHECK_DEATH(base::Bind(null_cb, 42));
1493 }
1494
1495 }  // namespace
1496 }  // namespace base