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