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
10 #include "base/callback.h"
11 #include "base/macros.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/weak_ptr.h"
15 #include "build/build_config.h"
16 #include "testing/gmock/include/gmock/gmock.h"
17 #include "testing/gtest/include/gtest/gtest.h"
18
19 using ::testing::Mock;
20 using ::testing::Return;
21 using ::testing::StrictMock;
22
23 namespace base {
24 namespace {
25
26 class IncompleteType;
27
28 class NoRef {
29 public:
NoRef()30 NoRef() {}
31
32 MOCK_METHOD0(VoidMethod0, void());
33 MOCK_CONST_METHOD0(VoidConstMethod0, void());
34
35 MOCK_METHOD0(IntMethod0, int());
36 MOCK_CONST_METHOD0(IntConstMethod0, int());
37
38 private:
39 // Particularly important in this test to ensure no copies are made.
40 DISALLOW_COPY_AND_ASSIGN(NoRef);
41 };
42
43 class HasRef : public NoRef {
44 public:
HasRef()45 HasRef() {}
46
47 MOCK_CONST_METHOD0(AddRef, void());
48 MOCK_CONST_METHOD0(Release, bool());
49
50 private:
51 // Particularly important in this test to ensure no copies are made.
52 DISALLOW_COPY_AND_ASSIGN(HasRef);
53 };
54
55 class HasRefPrivateDtor : public HasRef {
56 private:
~HasRefPrivateDtor()57 ~HasRefPrivateDtor() {}
58 };
59
60 static const int kParentValue = 1;
61 static const int kChildValue = 2;
62
63 class Parent {
64 public:
65 virtual ~Parent() = default;
AddRef() const66 void AddRef() const {}
Release() const67 void Release() const {}
VirtualSet()68 virtual void VirtualSet() { value = kParentValue; }
NonVirtualSet()69 void NonVirtualSet() { value = kParentValue; }
70 int value;
71 };
72
73 class Child : public Parent {
74 public:
75 ~Child() override = default;
VirtualSet()76 void VirtualSet() override { value = kChildValue; }
NonVirtualSet()77 void NonVirtualSet() { value = kChildValue; }
78 };
79
80 class NoRefParent {
81 public:
82 virtual ~NoRefParent() = default;
VirtualSet()83 virtual void VirtualSet() { value = kParentValue; }
NonVirtualSet()84 void NonVirtualSet() { value = kParentValue; }
85 int value;
86 };
87
88 class NoRefChild : public NoRefParent {
89 public:
90 ~NoRefChild() override = default;
VirtualSet()91 void VirtualSet() override { value = kChildValue; }
NonVirtualSet()92 void NonVirtualSet() { value = kChildValue; }
93 };
94
95 // Used for probing the number of copies that occur if a type must be coerced
96 // during argument forwarding in the Run() methods.
97 struct DerivedCopyCounter {
DerivedCopyCounterbase::__anoncfda50f00111::DerivedCopyCounter98 DerivedCopyCounter(int* copies, int* assigns)
99 : copies_(copies), assigns_(assigns) {
100 }
101 int* copies_;
102 int* assigns_;
103 };
104
105 // Used for probing the number of copies in an argument.
106 class CopyCounter {
107 public:
CopyCounter(int * copies,int * assigns)108 CopyCounter(int* copies, int* assigns)
109 : copies_(copies), assigns_(assigns) {
110 }
111
CopyCounter(const CopyCounter & other)112 CopyCounter(const CopyCounter& other)
113 : copies_(other.copies_),
114 assigns_(other.assigns_) {
115 (*copies_)++;
116 }
117
118 // Probing for copies from coercion.
CopyCounter(const DerivedCopyCounter & other)119 explicit CopyCounter(const DerivedCopyCounter& other)
120 : copies_(other.copies_),
121 assigns_(other.assigns_) {
122 (*copies_)++;
123 }
124
operator =(const CopyCounter & rhs)125 const CopyCounter& operator=(const CopyCounter& rhs) {
126 copies_ = rhs.copies_;
127 assigns_ = rhs.assigns_;
128
129 if (assigns_) {
130 (*assigns_)++;
131 }
132
133 return *this;
134 }
135
copies() const136 int copies() const {
137 return *copies_;
138 }
139
140 private:
141 int* copies_;
142 int* assigns_;
143 };
144
145 class DeleteCounter {
146 public:
DeleteCounter(int * deletes)147 explicit DeleteCounter(int* deletes)
148 : deletes_(deletes) {
149 }
150
~DeleteCounter()151 ~DeleteCounter() {
152 (*deletes_)++;
153 }
154
VoidMethod0()155 void VoidMethod0() {}
156
157 private:
158 int* deletes_;
159 };
160
161 template <typename T>
PassThru(T scoper)162 T PassThru(T scoper) {
163 return scoper;
164 }
165
166 // Some test functions that we can Bind to.
167 template <typename T>
PolymorphicIdentity(T t)168 T PolymorphicIdentity(T t) {
169 return t;
170 }
171
172 template <typename... Ts>
173 struct VoidPolymorphic {
Runbase::__anoncfda50f00111::VoidPolymorphic174 static void Run(Ts... t) {}
175 };
176
Identity(int n)177 int Identity(int n) {
178 return n;
179 }
180
ArrayGet(const int array[],int n)181 int ArrayGet(const int array[], int n) {
182 return array[n];
183 }
184
Sum(int a,int b,int c,int d,int e,int f)185 int Sum(int a, int b, int c, int d, int e, int f) {
186 return a + b + c + d + e + f;
187 }
188
CStringIdentity(const char * s)189 const char* CStringIdentity(const char* s) {
190 return s;
191 }
192
GetCopies(const CopyCounter & counter)193 int GetCopies(const CopyCounter& counter) {
194 return counter.copies();
195 }
196
UnwrapNoRefParent(NoRefParent p)197 int UnwrapNoRefParent(NoRefParent p) {
198 return p.value;
199 }
200
UnwrapNoRefParentPtr(NoRefParent * p)201 int UnwrapNoRefParentPtr(NoRefParent* p) {
202 return p->value;
203 }
204
UnwrapNoRefParentConstRef(const NoRefParent & p)205 int UnwrapNoRefParentConstRef(const NoRefParent& p) {
206 return p.value;
207 }
208
RefArgSet(int & n)209 void RefArgSet(int &n) {
210 n = 2;
211 }
212
PtrArgSet(int * n)213 void PtrArgSet(int *n) {
214 *n = 2;
215 }
216
FunctionWithWeakFirstParam(WeakPtr<NoRef> o,int n)217 int FunctionWithWeakFirstParam(WeakPtr<NoRef> o, int n) {
218 return n;
219 }
220
FunctionWithScopedRefptrFirstParam(const scoped_refptr<HasRef> & o,int n)221 int FunctionWithScopedRefptrFirstParam(const scoped_refptr<HasRef>& o, int n) {
222 return n;
223 }
224
TakesACallback(const Closure & callback)225 void TakesACallback(const Closure& callback) {
226 callback.Run();
227 }
228
229 class BindTest : public ::testing::Test {
230 public:
BindTest()231 BindTest() {
232 const_has_ref_ptr_ = &has_ref_;
233 const_no_ref_ptr_ = &no_ref_;
234 static_func_mock_ptr = &static_func_mock_;
235 }
236
~BindTest()237 virtual ~BindTest() {
238 }
239
VoidFunc0()240 static void VoidFunc0() {
241 static_func_mock_ptr->VoidMethod0();
242 }
243
IntFunc0()244 static int IntFunc0() { return static_func_mock_ptr->IntMethod0(); }
245
246 protected:
247 StrictMock<NoRef> no_ref_;
248 StrictMock<HasRef> has_ref_;
249 const HasRef* const_has_ref_ptr_;
250 const NoRef* const_no_ref_ptr_;
251 StrictMock<NoRef> static_func_mock_;
252
253 // Used by the static functions to perform expectations.
254 static StrictMock<NoRef>* static_func_mock_ptr;
255
256 private:
257 DISALLOW_COPY_AND_ASSIGN(BindTest);
258 };
259
260 StrictMock<NoRef>* BindTest::static_func_mock_ptr;
261
262 // Sanity check that we can instantiate a callback for each arity.
TEST_F(BindTest,ArityTest)263 TEST_F(BindTest, ArityTest) {
264 Callback<int()> c0 = Bind(&Sum, 32, 16, 8, 4, 2, 1);
265 EXPECT_EQ(63, c0.Run());
266
267 Callback<int(int)> c1 = Bind(&Sum, 32, 16, 8, 4, 2);
268 EXPECT_EQ(75, c1.Run(13));
269
270 Callback<int(int,int)> c2 = Bind(&Sum, 32, 16, 8, 4);
271 EXPECT_EQ(85, c2.Run(13, 12));
272
273 Callback<int(int,int,int)> c3 = Bind(&Sum, 32, 16, 8);
274 EXPECT_EQ(92, c3.Run(13, 12, 11));
275
276 Callback<int(int,int,int,int)> c4 = Bind(&Sum, 32, 16);
277 EXPECT_EQ(94, c4.Run(13, 12, 11, 10));
278
279 Callback<int(int,int,int,int,int)> c5 = Bind(&Sum, 32);
280 EXPECT_EQ(87, c5.Run(13, 12, 11, 10, 9));
281
282 Callback<int(int,int,int,int,int,int)> c6 = Bind(&Sum);
283 EXPECT_EQ(69, c6.Run(13, 12, 11, 10, 9, 14));
284 }
285
286 // Test the Currying ability of the Callback system.
TEST_F(BindTest,CurryingTest)287 TEST_F(BindTest, CurryingTest) {
288 Callback<int(int,int,int,int,int,int)> c6 = Bind(&Sum);
289 EXPECT_EQ(69, c6.Run(13, 12, 11, 10, 9, 14));
290
291 Callback<int(int,int,int,int,int)> c5 = Bind(c6, 32);
292 EXPECT_EQ(87, c5.Run(13, 12, 11, 10, 9));
293
294 Callback<int(int,int,int,int)> c4 = Bind(c5, 16);
295 EXPECT_EQ(94, c4.Run(13, 12, 11, 10));
296
297 Callback<int(int,int,int)> c3 = Bind(c4, 8);
298 EXPECT_EQ(92, c3.Run(13, 12, 11));
299
300 Callback<int(int,int)> c2 = Bind(c3, 4);
301 EXPECT_EQ(85, c2.Run(13, 12));
302
303 Callback<int(int)> c1 = Bind(c2, 2);
304 EXPECT_EQ(75, c1.Run(13));
305
306 Callback<int()> c0 = Bind(c1, 1);
307 EXPECT_EQ(63, c0.Run());
308 }
309
310 // Test that currying the rvalue result of another Bind() works correctly.
311 // - rvalue should be usable as argument to Bind().
312 // - multiple runs of resulting Callback remain valid.
TEST_F(BindTest,CurryingRvalueResultOfBind)313 TEST_F(BindTest, CurryingRvalueResultOfBind) {
314 int n = 0;
315 Closure cb = base::Bind(&TakesACallback, base::Bind(&PtrArgSet, &n));
316
317 // If we implement Bind() such that the return value has auto_ptr-like
318 // semantics, the second call here will fail because ownership of
319 // the internal BindState<> would have been transfered to a *temporary*
320 // constructon of a Callback object on the first call.
321 cb.Run();
322 EXPECT_EQ(2, n);
323
324 n = 0;
325 cb.Run();
326 EXPECT_EQ(2, n);
327 }
328
329 // Function type support.
330 // - Normal function.
331 // - Normal function bound with non-refcounted first argument.
332 // - Method bound to non-const object.
333 // - Method bound to scoped_refptr.
334 // - Const method bound to non-const object.
335 // - Const method bound to const object.
336 // - Derived classes can be used with pointers to non-virtual base functions.
337 // - Derived classes can be used with pointers to virtual base functions (and
338 // preserve virtual dispatch).
TEST_F(BindTest,FunctionTypeSupport)339 TEST_F(BindTest, FunctionTypeSupport) {
340 EXPECT_CALL(static_func_mock_, VoidMethod0());
341 EXPECT_CALL(has_ref_, AddRef()).Times(5);
342 EXPECT_CALL(has_ref_, Release()).Times(5);
343 EXPECT_CALL(has_ref_, VoidMethod0()).Times(2);
344 EXPECT_CALL(has_ref_, VoidConstMethod0()).Times(2);
345
346 Closure normal_cb = Bind(&VoidFunc0);
347 Callback<NoRef*()> normal_non_refcounted_cb =
348 Bind(&PolymorphicIdentity<NoRef*>, &no_ref_);
349 normal_cb.Run();
350 EXPECT_EQ(&no_ref_, normal_non_refcounted_cb.Run());
351
352 Closure method_cb = Bind(&HasRef::VoidMethod0, &has_ref_);
353 Closure method_refptr_cb = Bind(&HasRef::VoidMethod0,
354 make_scoped_refptr(&has_ref_));
355 Closure const_method_nonconst_obj_cb = Bind(&HasRef::VoidConstMethod0,
356 &has_ref_);
357 Closure const_method_const_obj_cb = Bind(&HasRef::VoidConstMethod0,
358 const_has_ref_ptr_);
359 method_cb.Run();
360 method_refptr_cb.Run();
361 const_method_nonconst_obj_cb.Run();
362 const_method_const_obj_cb.Run();
363
364 Child child;
365 child.value = 0;
366 Closure virtual_set_cb = Bind(&Parent::VirtualSet, &child);
367 virtual_set_cb.Run();
368 EXPECT_EQ(kChildValue, child.value);
369
370 child.value = 0;
371 Closure non_virtual_set_cb = Bind(&Parent::NonVirtualSet, &child);
372 non_virtual_set_cb.Run();
373 EXPECT_EQ(kParentValue, child.value);
374 }
375
376 // Return value support.
377 // - Function with return value.
378 // - Method with return value.
379 // - Const method with return value.
TEST_F(BindTest,ReturnValues)380 TEST_F(BindTest, ReturnValues) {
381 EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
382 EXPECT_CALL(has_ref_, AddRef()).Times(3);
383 EXPECT_CALL(has_ref_, Release()).Times(3);
384 EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(31337));
385 EXPECT_CALL(has_ref_, IntConstMethod0())
386 .WillOnce(Return(41337))
387 .WillOnce(Return(51337));
388
389 Callback<int()> normal_cb = Bind(&IntFunc0);
390 Callback<int()> method_cb = Bind(&HasRef::IntMethod0, &has_ref_);
391 Callback<int()> const_method_nonconst_obj_cb =
392 Bind(&HasRef::IntConstMethod0, &has_ref_);
393 Callback<int()> const_method_const_obj_cb =
394 Bind(&HasRef::IntConstMethod0, const_has_ref_ptr_);
395 EXPECT_EQ(1337, normal_cb.Run());
396 EXPECT_EQ(31337, method_cb.Run());
397 EXPECT_EQ(41337, const_method_nonconst_obj_cb.Run());
398 EXPECT_EQ(51337, const_method_const_obj_cb.Run());
399 }
400
401 // IgnoreResult adapter test.
402 // - Function with return value.
403 // - Method with return value.
404 // - Const Method with return.
405 // - Method with return value bound to WeakPtr<>.
406 // - Const Method with return bound to WeakPtr<>.
TEST_F(BindTest,IgnoreResult)407 TEST_F(BindTest, IgnoreResult) {
408 EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
409 EXPECT_CALL(has_ref_, AddRef()).Times(2);
410 EXPECT_CALL(has_ref_, Release()).Times(2);
411 EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
412 EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
413 EXPECT_CALL(no_ref_, IntMethod0()).WillOnce(Return(12));
414 EXPECT_CALL(no_ref_, IntConstMethod0()).WillOnce(Return(13));
415
416 Closure normal_func_cb = Bind(IgnoreResult(&IntFunc0));
417 normal_func_cb.Run();
418
419 Closure non_void_method_cb =
420 Bind(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
421 non_void_method_cb.Run();
422
423 Closure non_void_const_method_cb =
424 Bind(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
425 non_void_const_method_cb.Run();
426
427 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
428 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
429
430 Closure non_void_weak_method_cb =
431 Bind(IgnoreResult(&NoRef::IntMethod0), weak_factory.GetWeakPtr());
432 non_void_weak_method_cb.Run();
433
434 Closure non_void_weak_const_method_cb =
435 Bind(IgnoreResult(&NoRef::IntConstMethod0), weak_factory.GetWeakPtr());
436 non_void_weak_const_method_cb.Run();
437
438 weak_factory.InvalidateWeakPtrs();
439 non_void_weak_const_method_cb.Run();
440 non_void_weak_method_cb.Run();
441 }
442
443 // Argument binding tests.
444 // - Argument binding to primitive.
445 // - Argument binding to primitive pointer.
446 // - Argument binding to a literal integer.
447 // - Argument binding to a literal string.
448 // - Argument binding with template function.
449 // - Argument binding to an object.
450 // - Argument binding to pointer to incomplete type.
451 // - Argument gets type converted.
452 // - Pointer argument gets converted.
453 // - Const Reference forces conversion.
TEST_F(BindTest,ArgumentBinding)454 TEST_F(BindTest, ArgumentBinding) {
455 int n = 2;
456
457 Callback<int()> bind_primitive_cb = Bind(&Identity, n);
458 EXPECT_EQ(n, bind_primitive_cb.Run());
459
460 Callback<int*()> bind_primitive_pointer_cb =
461 Bind(&PolymorphicIdentity<int*>, &n);
462 EXPECT_EQ(&n, bind_primitive_pointer_cb.Run());
463
464 Callback<int()> bind_int_literal_cb = Bind(&Identity, 3);
465 EXPECT_EQ(3, bind_int_literal_cb.Run());
466
467 Callback<const char*()> bind_string_literal_cb =
468 Bind(&CStringIdentity, "hi");
469 EXPECT_STREQ("hi", bind_string_literal_cb.Run());
470
471 Callback<int()> bind_template_function_cb =
472 Bind(&PolymorphicIdentity<int>, 4);
473 EXPECT_EQ(4, bind_template_function_cb.Run());
474
475 NoRefParent p;
476 p.value = 5;
477 Callback<int()> bind_object_cb = Bind(&UnwrapNoRefParent, p);
478 EXPECT_EQ(5, bind_object_cb.Run());
479
480 IncompleteType* incomplete_ptr = reinterpret_cast<IncompleteType*>(123);
481 Callback<IncompleteType*()> bind_incomplete_ptr_cb =
482 Bind(&PolymorphicIdentity<IncompleteType*>, incomplete_ptr);
483 EXPECT_EQ(incomplete_ptr, bind_incomplete_ptr_cb.Run());
484
485 NoRefChild c;
486 c.value = 6;
487 Callback<int()> bind_promotes_cb = Bind(&UnwrapNoRefParent, c);
488 EXPECT_EQ(6, bind_promotes_cb.Run());
489
490 c.value = 7;
491 Callback<int()> bind_pointer_promotes_cb =
492 Bind(&UnwrapNoRefParentPtr, &c);
493 EXPECT_EQ(7, bind_pointer_promotes_cb.Run());
494
495 c.value = 8;
496 Callback<int()> bind_const_reference_promotes_cb =
497 Bind(&UnwrapNoRefParentConstRef, c);
498 EXPECT_EQ(8, bind_const_reference_promotes_cb.Run());
499 }
500
501 // Unbound argument type support tests.
502 // - Unbound value.
503 // - Unbound pointer.
504 // - Unbound reference.
505 // - Unbound const reference.
506 // - Unbound unsized array.
507 // - Unbound sized array.
508 // - Unbound array-of-arrays.
TEST_F(BindTest,UnboundArgumentTypeSupport)509 TEST_F(BindTest, UnboundArgumentTypeSupport) {
510 Callback<void(int)> unbound_value_cb = Bind(&VoidPolymorphic<int>::Run);
511 Callback<void(int*)> unbound_pointer_cb = Bind(&VoidPolymorphic<int*>::Run);
512 Callback<void(int&)> unbound_ref_cb = Bind(&VoidPolymorphic<int&>::Run);
513 Callback<void(const int&)> unbound_const_ref_cb =
514 Bind(&VoidPolymorphic<const int&>::Run);
515 Callback<void(int[])> unbound_unsized_array_cb =
516 Bind(&VoidPolymorphic<int[]>::Run);
517 Callback<void(int[2])> unbound_sized_array_cb =
518 Bind(&VoidPolymorphic<int[2]>::Run);
519 Callback<void(int[][2])> unbound_array_of_arrays_cb =
520 Bind(&VoidPolymorphic<int[][2]>::Run);
521
522 Callback<void(int&)> unbound_ref_with_bound_arg =
523 Bind(&VoidPolymorphic<int, int&>::Run, 1);
524 }
525
526 // Function with unbound reference parameter.
527 // - Original parameter is modified by callback.
TEST_F(BindTest,UnboundReferenceSupport)528 TEST_F(BindTest, UnboundReferenceSupport) {
529 int n = 0;
530 Callback<void(int&)> unbound_ref_cb = Bind(&RefArgSet);
531 unbound_ref_cb.Run(n);
532 EXPECT_EQ(2, n);
533 }
534
535 // Functions that take reference parameters.
536 // - Forced reference parameter type still stores a copy.
537 // - Forced const reference parameter type still stores a copy.
TEST_F(BindTest,ReferenceArgumentBinding)538 TEST_F(BindTest, ReferenceArgumentBinding) {
539 int n = 1;
540 int& ref_n = n;
541 const int& const_ref_n = n;
542
543 Callback<int()> ref_copies_cb = Bind(&Identity, ref_n);
544 EXPECT_EQ(n, ref_copies_cb.Run());
545 n++;
546 EXPECT_EQ(n - 1, ref_copies_cb.Run());
547
548 Callback<int()> const_ref_copies_cb = Bind(&Identity, const_ref_n);
549 EXPECT_EQ(n, const_ref_copies_cb.Run());
550 n++;
551 EXPECT_EQ(n - 1, const_ref_copies_cb.Run());
552 }
553
554 // Check that we can pass in arrays and have them be stored as a pointer.
555 // - Array of values stores a pointer.
556 // - Array of const values stores a pointer.
TEST_F(BindTest,ArrayArgumentBinding)557 TEST_F(BindTest, ArrayArgumentBinding) {
558 int array[4] = {1, 1, 1, 1};
559 const int (*const_array_ptr)[4] = &array;
560
561 Callback<int()> array_cb = Bind(&ArrayGet, array, 1);
562 EXPECT_EQ(1, array_cb.Run());
563
564 Callback<int()> const_array_cb = Bind(&ArrayGet, *const_array_ptr, 1);
565 EXPECT_EQ(1, const_array_cb.Run());
566
567 array[1] = 3;
568 EXPECT_EQ(3, array_cb.Run());
569 EXPECT_EQ(3, const_array_cb.Run());
570 }
571
572 // Verify SupportsAddRefAndRelease correctly introspects the class type for
573 // AddRef() and Release().
574 // - Class with AddRef() and Release()
575 // - Class without AddRef() and Release()
576 // - Derived Class with AddRef() and Release()
577 // - Derived Class without AddRef() and Release()
578 // - Derived Class with AddRef() and Release() and a private destructor.
TEST_F(BindTest,SupportsAddRefAndRelease)579 TEST_F(BindTest, SupportsAddRefAndRelease) {
580 EXPECT_TRUE(internal::SupportsAddRefAndRelease<HasRef>::value);
581 EXPECT_FALSE(internal::SupportsAddRefAndRelease<NoRef>::value);
582
583 // StrictMock<T> is a derived class of T. So, we use StrictMock<HasRef> and
584 // StrictMock<NoRef> to test that SupportsAddRefAndRelease works over
585 // inheritance.
586 EXPECT_TRUE(internal::SupportsAddRefAndRelease<StrictMock<HasRef> >::value);
587 EXPECT_FALSE(internal::SupportsAddRefAndRelease<StrictMock<NoRef> >::value);
588
589 // This matters because the implementation creates a dummy class that
590 // inherits from the template type.
591 EXPECT_TRUE(internal::SupportsAddRefAndRelease<HasRefPrivateDtor>::value);
592 }
593
594 // Unretained() wrapper support.
595 // - Method bound to Unretained() non-const object.
596 // - Const method bound to Unretained() non-const object.
597 // - Const method bound to Unretained() const object.
TEST_F(BindTest,Unretained)598 TEST_F(BindTest, Unretained) {
599 EXPECT_CALL(no_ref_, VoidMethod0());
600 EXPECT_CALL(no_ref_, VoidConstMethod0()).Times(2);
601
602 Callback<void()> method_cb =
603 Bind(&NoRef::VoidMethod0, Unretained(&no_ref_));
604 method_cb.Run();
605
606 Callback<void()> const_method_cb =
607 Bind(&NoRef::VoidConstMethod0, Unretained(&no_ref_));
608 const_method_cb.Run();
609
610 Callback<void()> const_method_const_ptr_cb =
611 Bind(&NoRef::VoidConstMethod0, Unretained(const_no_ref_ptr_));
612 const_method_const_ptr_cb.Run();
613 }
614
615 // WeakPtr() support.
616 // - Method bound to WeakPtr<> to non-const object.
617 // - Const method bound to WeakPtr<> to non-const object.
618 // - Const method bound to WeakPtr<> to const object.
619 // - Normal Function with WeakPtr<> as P1 can have return type and is
620 // not canceled.
TEST_F(BindTest,WeakPtr)621 TEST_F(BindTest, WeakPtr) {
622 EXPECT_CALL(no_ref_, VoidMethod0());
623 EXPECT_CALL(no_ref_, VoidConstMethod0()).Times(2);
624
625 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
626 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
627
628 Closure method_cb =
629 Bind(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
630 method_cb.Run();
631
632 Closure const_method_cb =
633 Bind(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
634 const_method_cb.Run();
635
636 Closure const_method_const_ptr_cb =
637 Bind(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
638 const_method_const_ptr_cb.Run();
639
640 Callback<int(int)> normal_func_cb =
641 Bind(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
642 EXPECT_EQ(1, normal_func_cb.Run(1));
643
644 weak_factory.InvalidateWeakPtrs();
645 const_weak_factory.InvalidateWeakPtrs();
646
647 method_cb.Run();
648 const_method_cb.Run();
649 const_method_const_ptr_cb.Run();
650
651 // Still runs even after the pointers are invalidated.
652 EXPECT_EQ(2, normal_func_cb.Run(2));
653 }
654
655 // ConstRef() wrapper support.
656 // - Binding w/o ConstRef takes a copy.
657 // - Binding a ConstRef takes a reference.
658 // - Binding ConstRef to a function ConstRef does not copy on invoke.
TEST_F(BindTest,ConstRef)659 TEST_F(BindTest, ConstRef) {
660 int n = 1;
661
662 Callback<int()> copy_cb = Bind(&Identity, n);
663 Callback<int()> const_ref_cb = Bind(&Identity, ConstRef(n));
664 EXPECT_EQ(n, copy_cb.Run());
665 EXPECT_EQ(n, const_ref_cb.Run());
666 n++;
667 EXPECT_EQ(n - 1, copy_cb.Run());
668 EXPECT_EQ(n, const_ref_cb.Run());
669
670 int copies = 0;
671 int assigns = 0;
672 CopyCounter counter(&copies, &assigns);
673 Callback<int()> all_const_ref_cb =
674 Bind(&GetCopies, ConstRef(counter));
675 EXPECT_EQ(0, all_const_ref_cb.Run());
676 EXPECT_EQ(0, copies);
677 EXPECT_EQ(0, assigns);
678 }
679
TEST_F(BindTest,ScopedRefptr)680 TEST_F(BindTest, ScopedRefptr) {
681 // BUG: The scoped_refptr should cause the only AddRef()/Release() pair. But
682 // due to a bug in base::Bind(), there's an extra call when invoking the
683 // callback.
684 // https://code.google.com/p/chromium/issues/detail?id=251937
685 EXPECT_CALL(has_ref_, AddRef()).Times(2);
686 EXPECT_CALL(has_ref_, Release()).Times(2);
687
688 const scoped_refptr<StrictMock<HasRef> > refptr(&has_ref_);
689
690 Callback<int()> scoped_refptr_const_ref_cb =
691 Bind(&FunctionWithScopedRefptrFirstParam, base::ConstRef(refptr), 1);
692 EXPECT_EQ(1, scoped_refptr_const_ref_cb.Run());
693 }
694
695 // Test Owned() support.
TEST_F(BindTest,Owned)696 TEST_F(BindTest, Owned) {
697 int deletes = 0;
698 DeleteCounter* counter = new DeleteCounter(&deletes);
699
700 // If we don't capture, delete happens on Callback destruction/reset.
701 // return the same value.
702 Callback<DeleteCounter*()> no_capture_cb =
703 Bind(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
704 ASSERT_EQ(counter, no_capture_cb.Run());
705 ASSERT_EQ(counter, no_capture_cb.Run());
706 EXPECT_EQ(0, deletes);
707 no_capture_cb.Reset(); // This should trigger a delete.
708 EXPECT_EQ(1, deletes);
709
710 deletes = 0;
711 counter = new DeleteCounter(&deletes);
712 base::Closure own_object_cb =
713 Bind(&DeleteCounter::VoidMethod0, Owned(counter));
714 own_object_cb.Run();
715 EXPECT_EQ(0, deletes);
716 own_object_cb.Reset();
717 EXPECT_EQ(1, deletes);
718 }
719
720 // Passed() wrapper support.
721 // - Passed() can be constructed from a pointer to scoper.
722 // - Passed() can be constructed from a scoper rvalue.
723 // - Using Passed() gives Callback Ownership.
724 // - Ownership is transferred from Callback to callee on the first Run().
725 // - Callback supports unbound arguments.
TEST_F(BindTest,ScopedPtr)726 TEST_F(BindTest, ScopedPtr) {
727 int deletes = 0;
728
729 // Tests the Passed() function's support for pointers.
730 scoped_ptr<DeleteCounter> ptr(new DeleteCounter(&deletes));
731 Callback<scoped_ptr<DeleteCounter>()> unused_callback =
732 Bind(&PassThru<scoped_ptr<DeleteCounter> >, Passed(&ptr));
733 EXPECT_FALSE(ptr.get());
734 EXPECT_EQ(0, deletes);
735
736 // If we never invoke the Callback, it retains ownership and deletes.
737 unused_callback.Reset();
738 EXPECT_EQ(1, deletes);
739
740 // Tests the Passed() function's support for rvalues.
741 deletes = 0;
742 DeleteCounter* counter = new DeleteCounter(&deletes);
743 Callback<scoped_ptr<DeleteCounter>()> callback =
744 Bind(&PassThru<scoped_ptr<DeleteCounter> >,
745 Passed(scoped_ptr<DeleteCounter>(counter)));
746 EXPECT_FALSE(ptr.get());
747 EXPECT_EQ(0, deletes);
748
749 // Check that ownership can be transferred back out.
750 scoped_ptr<DeleteCounter> result = callback.Run();
751 ASSERT_EQ(counter, result.get());
752 EXPECT_EQ(0, deletes);
753
754 // Resetting does not delete since ownership was transferred.
755 callback.Reset();
756 EXPECT_EQ(0, deletes);
757
758 // Ensure that we actually did get ownership.
759 result.reset();
760 EXPECT_EQ(1, deletes);
761
762 // Test unbound argument forwarding.
763 Callback<scoped_ptr<DeleteCounter>(scoped_ptr<DeleteCounter>)> cb_unbound =
764 Bind(&PassThru<scoped_ptr<DeleteCounter> >);
765 ptr.reset(new DeleteCounter(&deletes));
766 cb_unbound.Run(std::move(ptr));
767 }
768
TEST_F(BindTest,UniquePtr)769 TEST_F(BindTest, UniquePtr) {
770 int deletes = 0;
771
772 // Tests the Passed() function's support for pointers.
773 std::unique_ptr<DeleteCounter> ptr(new DeleteCounter(&deletes));
774 Callback<std::unique_ptr<DeleteCounter>()> unused_callback =
775 Bind(&PassThru<std::unique_ptr<DeleteCounter>>, Passed(&ptr));
776 EXPECT_FALSE(ptr.get());
777 EXPECT_EQ(0, deletes);
778
779 // If we never invoke the Callback, it retains ownership and deletes.
780 unused_callback.Reset();
781 EXPECT_EQ(1, deletes);
782
783 // Tests the Passed() function's support for rvalues.
784 deletes = 0;
785 DeleteCounter* counter = new DeleteCounter(&deletes);
786 Callback<std::unique_ptr<DeleteCounter>()> callback =
787 Bind(&PassThru<std::unique_ptr<DeleteCounter>>,
788 Passed(std::unique_ptr<DeleteCounter>(counter)));
789 EXPECT_FALSE(ptr.get());
790 EXPECT_EQ(0, deletes);
791
792 // Check that ownership can be transferred back out.
793 std::unique_ptr<DeleteCounter> result = callback.Run();
794 ASSERT_EQ(counter, result.get());
795 EXPECT_EQ(0, deletes);
796
797 // Resetting does not delete since ownership was transferred.
798 callback.Reset();
799 EXPECT_EQ(0, deletes);
800
801 // Ensure that we actually did get ownership.
802 result.reset();
803 EXPECT_EQ(1, deletes);
804
805 // Test unbound argument forwarding.
806 Callback<std::unique_ptr<DeleteCounter>(std::unique_ptr<DeleteCounter>)>
807 cb_unbound = Bind(&PassThru<std::unique_ptr<DeleteCounter>>);
808 ptr.reset(new DeleteCounter(&deletes));
809 cb_unbound.Run(std::move(ptr));
810 }
811
812 // Argument Copy-constructor usage for non-reference parameters.
813 // - Bound arguments are only copied once.
814 // - Forwarded arguments are only copied once.
815 // - Forwarded arguments with coercions are only copied twice (once for the
816 // coercion, and one for the final dispatch).
TEST_F(BindTest,ArgumentCopies)817 TEST_F(BindTest, ArgumentCopies) {
818 int copies = 0;
819 int assigns = 0;
820
821 CopyCounter counter(&copies, &assigns);
822
823 Callback<void()> copy_cb =
824 Bind(&VoidPolymorphic<CopyCounter>::Run, counter);
825 EXPECT_GE(1, copies);
826 EXPECT_EQ(0, assigns);
827
828 copies = 0;
829 assigns = 0;
830 Callback<void(CopyCounter)> forward_cb =
831 Bind(&VoidPolymorphic<CopyCounter>::Run);
832 forward_cb.Run(counter);
833 EXPECT_GE(1, copies);
834 EXPECT_EQ(0, assigns);
835
836 copies = 0;
837 assigns = 0;
838 DerivedCopyCounter derived(&copies, &assigns);
839 Callback<void(CopyCounter)> coerce_cb =
840 Bind(&VoidPolymorphic<CopyCounter>::Run);
841 coerce_cb.Run(CopyCounter(derived));
842 EXPECT_GE(2, copies);
843 EXPECT_EQ(0, assigns);
844 }
845
846 // Callback construction and assignment tests.
847 // - Construction from an InvokerStorageHolder should not cause ref/deref.
848 // - Assignment from other callback should only cause one ref
849 //
850 // TODO(ajwong): Is there actually a way to test this?
851
852 #if defined(OS_WIN)
FastCallFunc(int n)853 int __fastcall FastCallFunc(int n) {
854 return n;
855 }
856
StdCallFunc(int n)857 int __stdcall StdCallFunc(int n) {
858 return n;
859 }
860
861 // Windows specific calling convention support.
862 // - Can bind a __fastcall function.
863 // - Can bind a __stdcall function.
TEST_F(BindTest,WindowsCallingConventions)864 TEST_F(BindTest, WindowsCallingConventions) {
865 Callback<int()> fastcall_cb = Bind(&FastCallFunc, 1);
866 EXPECT_EQ(1, fastcall_cb.Run());
867
868 Callback<int()> stdcall_cb = Bind(&StdCallFunc, 2);
869 EXPECT_EQ(2, stdcall_cb.Run());
870 }
871 #endif
872
873 #if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)) && GTEST_HAS_DEATH_TEST
874
875 // Test null callbacks cause a DCHECK.
TEST(BindDeathTest,NullCallback)876 TEST(BindDeathTest, NullCallback) {
877 base::Callback<void(int)> null_cb;
878 ASSERT_TRUE(null_cb.is_null());
879 EXPECT_DEATH(base::Bind(null_cb, 42), "");
880 }
881
882 #endif // (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)) &&
883 // GTEST_HAS_DEATH_TEST
884
885 } // namespace
886 } // namespace base
887