bind_unittest.cc 56 KB

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