callback_unittest.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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/callback.h"
  5. #include <memory>
  6. #include <utility>
  7. #include "base/bind.h"
  8. #include "base/callback_internal.h"
  9. #include "base/memory/raw_ptr.h"
  10. #include "base/memory/ref_counted.h"
  11. #include "base/notreached.h"
  12. #include "base/strings/string_number_conversions.h"
  13. #include "base/test/bind.h"
  14. #include "base/test/test_timeouts.h"
  15. #include "base/threading/thread.h"
  16. #include "testing/gtest/include/gtest/gtest.h"
  17. namespace base {
  18. void NopInvokeFunc() {}
  19. // White-box testpoints to inject into a callback object for checking
  20. // comparators and emptiness APIs. Use a BindState that is specialized based on
  21. // a type we declared in the anonymous namespace above to remove any chance of
  22. // colliding with another instantiation and breaking the one-definition-rule.
  23. struct FakeBindState : internal::BindStateBase {
  24. FakeBindState() : BindStateBase(&NopInvokeFunc, &Destroy, &IsCancelled) {}
  25. private:
  26. ~FakeBindState() = default;
  27. static void Destroy(const internal::BindStateBase* self) {
  28. delete static_cast<const FakeBindState*>(self);
  29. }
  30. static bool IsCancelled(const internal::BindStateBase*,
  31. internal::BindStateBase::CancellationQueryMode mode) {
  32. switch (mode) {
  33. case internal::BindStateBase::IS_CANCELLED:
  34. return false;
  35. case internal::BindStateBase::MAYBE_VALID:
  36. return true;
  37. }
  38. NOTREACHED();
  39. }
  40. };
  41. namespace {
  42. class CallbackTest : public ::testing::Test {
  43. public:
  44. CallbackTest()
  45. : callback_a_(new FakeBindState()), callback_b_(new FakeBindState()) {}
  46. ~CallbackTest() override = default;
  47. protected:
  48. RepeatingCallback<void()> callback_a_;
  49. const RepeatingCallback<void()> callback_b_; // Ensure APIs work with const.
  50. RepeatingCallback<void()> null_callback_;
  51. };
  52. TEST_F(CallbackTest, Types) {
  53. static_assert(std::is_same<void, OnceClosure::ResultType>::value, "");
  54. static_assert(std::is_same<void(), OnceClosure::RunType>::value, "");
  55. using OnceCallbackT = OnceCallback<double(int, char)>;
  56. static_assert(std::is_same<double, OnceCallbackT::ResultType>::value, "");
  57. static_assert(std::is_same<double(int, char), OnceCallbackT::RunType>::value,
  58. "");
  59. static_assert(std::is_same<void, RepeatingClosure::ResultType>::value, "");
  60. static_assert(std::is_same<void(), RepeatingClosure::RunType>::value, "");
  61. using RepeatingCallbackT = RepeatingCallback<bool(float, short)>;
  62. static_assert(std::is_same<bool, RepeatingCallbackT::ResultType>::value, "");
  63. static_assert(
  64. std::is_same<bool(float, short), RepeatingCallbackT::RunType>::value, "");
  65. }
  66. // Ensure we can create unbound callbacks. We need this to be able to store
  67. // them in class members that can be initialized later.
  68. TEST_F(CallbackTest, DefaultConstruction) {
  69. RepeatingCallback<void()> c0;
  70. RepeatingCallback<void(int)> c1;
  71. RepeatingCallback<void(int, int)> c2;
  72. RepeatingCallback<void(int, int, int)> c3;
  73. RepeatingCallback<void(int, int, int, int)> c4;
  74. RepeatingCallback<void(int, int, int, int, int)> c5;
  75. RepeatingCallback<void(int, int, int, int, int, int)> c6;
  76. EXPECT_TRUE(c0.is_null());
  77. EXPECT_TRUE(c1.is_null());
  78. EXPECT_TRUE(c2.is_null());
  79. EXPECT_TRUE(c3.is_null());
  80. EXPECT_TRUE(c4.is_null());
  81. EXPECT_TRUE(c5.is_null());
  82. EXPECT_TRUE(c6.is_null());
  83. }
  84. TEST_F(CallbackTest, IsNull) {
  85. EXPECT_TRUE(null_callback_.is_null());
  86. EXPECT_FALSE(callback_a_.is_null());
  87. EXPECT_FALSE(callback_b_.is_null());
  88. }
  89. TEST_F(CallbackTest, Equals) {
  90. EXPECT_EQ(callback_a_, callback_a_);
  91. EXPECT_NE(callback_a_, callback_b_);
  92. EXPECT_NE(callback_b_, callback_a_);
  93. // We should compare based on instance, not type.
  94. RepeatingCallback<void()> callback_c(new FakeBindState());
  95. RepeatingCallback<void()> callback_a2 = callback_a_;
  96. EXPECT_EQ(callback_a_, callback_a2);
  97. EXPECT_NE(callback_a_, callback_c);
  98. // Empty, however, is always equal to empty.
  99. RepeatingCallback<void()> empty2;
  100. EXPECT_EQ(null_callback_, empty2);
  101. }
  102. TEST_F(CallbackTest, Reset) {
  103. // Resetting should bring us back to empty.
  104. ASSERT_FALSE(callback_a_.is_null());
  105. EXPECT_NE(callback_a_, null_callback_);
  106. callback_a_.Reset();
  107. EXPECT_TRUE(callback_a_.is_null());
  108. EXPECT_EQ(callback_a_, null_callback_);
  109. }
  110. TEST_F(CallbackTest, Move) {
  111. // Moving should reset the callback.
  112. ASSERT_FALSE(callback_a_.is_null());
  113. EXPECT_NE(callback_a_, null_callback_);
  114. auto tmp = std::move(callback_a_);
  115. EXPECT_TRUE(callback_a_.is_null());
  116. EXPECT_EQ(callback_a_, null_callback_);
  117. }
  118. TEST_F(CallbackTest, NullAfterMoveRun) {
  119. RepeatingCallback<void(void*)> cb = BindRepeating([](void* param) {
  120. EXPECT_TRUE(static_cast<RepeatingCallback<void(void*)>*>(param)->is_null());
  121. });
  122. ASSERT_TRUE(cb);
  123. std::move(cb).Run(&cb);
  124. EXPECT_FALSE(cb);
  125. const RepeatingClosure cb2 = BindRepeating([] {});
  126. ASSERT_TRUE(cb2);
  127. std::move(cb2).Run();
  128. EXPECT_TRUE(cb2);
  129. OnceCallback<void(void*)> cb3 = BindOnce([](void* param) {
  130. EXPECT_TRUE(static_cast<OnceCallback<void(void*)>*>(param)->is_null());
  131. });
  132. ASSERT_TRUE(cb3);
  133. std::move(cb3).Run(&cb3);
  134. EXPECT_FALSE(cb3);
  135. }
  136. TEST_F(CallbackTest, MaybeValidReturnsTrue) {
  137. RepeatingCallback<void()> cb = BindRepeating([]() {});
  138. // By default, MaybeValid() just returns true all the time.
  139. EXPECT_TRUE(cb.MaybeValid());
  140. cb.Run();
  141. EXPECT_TRUE(cb.MaybeValid());
  142. }
  143. TEST_F(CallbackTest, ThenResetsOriginalCallback) {
  144. {
  145. // OnceCallback::Then() always destroys the original callback.
  146. OnceClosure orig = base::BindOnce([]() {});
  147. EXPECT_TRUE(!!orig);
  148. OnceClosure joined = std::move(orig).Then(base::BindOnce([]() {}));
  149. EXPECT_TRUE(!!joined);
  150. EXPECT_FALSE(!!orig);
  151. }
  152. {
  153. // RepeatingCallback::Then() destroys the original callback if it's an
  154. // rvalue.
  155. RepeatingClosure orig = base::BindRepeating([]() {});
  156. EXPECT_TRUE(!!orig);
  157. RepeatingClosure joined =
  158. std::move(orig).Then(base::BindRepeating([]() {}));
  159. EXPECT_TRUE(!!joined);
  160. EXPECT_FALSE(!!orig);
  161. }
  162. {
  163. // RepeatingCallback::Then() doesn't destroy the original callback if it's
  164. // not an rvalue.
  165. RepeatingClosure orig = base::BindRepeating([]() {});
  166. RepeatingClosure copy = orig;
  167. EXPECT_TRUE(!!orig);
  168. RepeatingClosure joined = orig.Then(base::BindRepeating([]() {}));
  169. EXPECT_TRUE(!!joined);
  170. EXPECT_TRUE(!!orig);
  171. // The original callback is not changed.
  172. EXPECT_EQ(orig, copy);
  173. EXPECT_NE(joined, copy);
  174. }
  175. }
  176. // A RepeatingCallback will implicitly convert to a OnceCallback, so a
  177. // once_callback.Then(repeating_callback) should turn into a OnceCallback
  178. // that holds 2 OnceCallbacks which it will run.
  179. TEST_F(CallbackTest, ThenCanConvertRepeatingToOnce) {
  180. {
  181. RepeatingClosure repeating_closure = base::BindRepeating([]() {});
  182. OnceClosure once_closure = base::BindOnce([]() {});
  183. std::move(once_closure).Then(repeating_closure).Run();
  184. RepeatingCallback<int(int)> repeating_callback =
  185. base::BindRepeating([](int i) { return i + 1; });
  186. OnceCallback<int(int)> once_callback =
  187. base::BindOnce([](int i) { return i * 2; });
  188. EXPECT_EQ(3, std::move(once_callback).Then(repeating_callback).Run(1));
  189. }
  190. {
  191. RepeatingClosure repeating_closure = base::BindRepeating([]() {});
  192. OnceClosure once_closure = base::BindOnce([]() {});
  193. std::move(once_closure).Then(std::move(repeating_closure)).Run();
  194. RepeatingCallback<int(int)> repeating_callback =
  195. base::BindRepeating([](int i) { return i + 1; });
  196. OnceCallback<int(int)> once_callback =
  197. base::BindOnce([](int i) { return i * 2; });
  198. EXPECT_EQ(
  199. 3, std::move(once_callback).Then(std::move(repeating_callback)).Run(1));
  200. }
  201. }
  202. // `Then()` should should allow a return value of type `R` to be passed to a
  203. // callback with one parameter of type `const R&` or type `R&&`.
  204. TEST_F(CallbackTest, ThenWithCompatibleButNotSameType) {
  205. {
  206. OnceCallback<std::string()> once_callback =
  207. BindOnce([] { return std::string("hello"); });
  208. EXPECT_EQ("hello",
  209. std::move(once_callback)
  210. .Then(BindOnce([](const std::string& s) { return s; }))
  211. .Run());
  212. }
  213. class NotCopied {
  214. public:
  215. NotCopied() = default;
  216. NotCopied(NotCopied&&) = default;
  217. NotCopied& operator=(NotCopied&&) = default;
  218. NotCopied(const NotCopied&) {
  219. ADD_FAILURE() << "should not have been copied";
  220. }
  221. NotCopied& operator=(const NotCopied&) {
  222. ADD_FAILURE() << "should not have been copied";
  223. return *this;
  224. }
  225. };
  226. {
  227. OnceCallback<NotCopied()> once_callback =
  228. BindOnce([] { return NotCopied(); });
  229. std::move(once_callback).Then(BindOnce([](const NotCopied&) {})).Run();
  230. }
  231. {
  232. OnceCallback<NotCopied()> once_callback =
  233. BindOnce([] { return NotCopied(); });
  234. std::move(once_callback).Then(BindOnce([](NotCopied&&) {})).Run();
  235. }
  236. }
  237. // A factory class for building an outer and inner callback for calling
  238. // Then() on either a OnceCallback or RepeatingCallback with combinations of
  239. // void return types, non-void, and move-only return types.
  240. template <bool use_once, typename R, typename ThenR, typename... Args>
  241. class CallbackThenTest;
  242. template <bool use_once, typename R, typename ThenR, typename... Args>
  243. class CallbackThenTest<use_once, R(Args...), ThenR> {
  244. public:
  245. using CallbackType =
  246. typename std::conditional<use_once,
  247. OnceCallback<R(Args...)>,
  248. RepeatingCallback<R(Args...)>>::type;
  249. using ThenType =
  250. typename std::conditional<use_once, OnceClosure, RepeatingClosure>::type;
  251. // Gets the Callback that will have Then() called on it. Has a return type
  252. // of `R`, which would chain to the inner callback for Then(). Has inputs of
  253. // type `Args...`.
  254. static auto GetOuter(std::string& s) {
  255. s = "";
  256. return Bind(
  257. [](std::string* s, Args... args) {
  258. return Outer(s, std::forward<Args>(args)...);
  259. },
  260. &s);
  261. }
  262. // Gets the Callback that will be passed to Then(). Has a return type of
  263. // `ThenR`, specified for the class instance. Receives as input the return
  264. // type `R` from the function bound and returned in GetOuter().
  265. static auto GetInner(std::string& s) { return Bind(&Inner<R, ThenR>, &s); }
  266. private:
  267. template <bool bind_once = use_once,
  268. typename F,
  269. typename... FArgs,
  270. std::enable_if_t<bind_once, int> = 0>
  271. static auto Bind(F function, FArgs... args) {
  272. return BindOnce(function, std::forward<FArgs>(args)...);
  273. }
  274. template <bool bind_once = use_once,
  275. typename F,
  276. typename... FArgs,
  277. std::enable_if_t<!bind_once, int> = 0>
  278. static auto Bind(F function, FArgs... args) {
  279. return BindRepeating(function, std::forward<FArgs>(args)...);
  280. }
  281. template <typename R2 = R,
  282. std::enable_if_t<!std::is_void<R2>::value, int> = 0>
  283. static int Outer(std::string* s,
  284. std::unique_ptr<int> a,
  285. std::unique_ptr<int> b) {
  286. *s += "Outer";
  287. *s += base::NumberToString(*a) + base::NumberToString(*b);
  288. return *a + *b;
  289. }
  290. template <typename R2 = R,
  291. std::enable_if_t<!std::is_void<R2>::value, int> = 0>
  292. static int Outer(std::string* s, int a, int b) {
  293. *s += "Outer";
  294. *s += base::NumberToString(a) + base::NumberToString(b);
  295. return a + b;
  296. }
  297. template <typename R2 = R,
  298. std::enable_if_t<!std::is_void<R2>::value, int> = 0>
  299. static int Outer(std::string* s) {
  300. *s += "Outer";
  301. *s += "None";
  302. return 99;
  303. }
  304. template <typename R2 = R, std::enable_if_t<std::is_void<R2>::value, int> = 0>
  305. static void Outer(std::string* s,
  306. std::unique_ptr<int> a,
  307. std::unique_ptr<int> b) {
  308. *s += "Outer";
  309. *s += base::NumberToString(*a) + base::NumberToString(*b);
  310. }
  311. template <typename R2 = R, std::enable_if_t<std::is_void<R2>::value, int> = 0>
  312. static void Outer(std::string* s, int a, int b) {
  313. *s += "Outer";
  314. *s += base::NumberToString(a) + base::NumberToString(b);
  315. }
  316. template <typename R2 = R, std::enable_if_t<std::is_void<R2>::value, int> = 0>
  317. static void Outer(std::string* s) {
  318. *s += "Outer";
  319. *s += "None";
  320. }
  321. template <typename OuterR,
  322. typename InnerR,
  323. std::enable_if_t<!std::is_void<OuterR>::value, int> = 0,
  324. std::enable_if_t<!std::is_void<InnerR>::value, int> = 0>
  325. static int Inner(std::string* s, OuterR a) {
  326. static_assert(std::is_same<InnerR, int>::value, "Use int return type");
  327. *s += "Inner";
  328. *s += base::NumberToString(a);
  329. return a;
  330. }
  331. template <typename OuterR,
  332. typename InnerR,
  333. std::enable_if_t<std::is_void<OuterR>::value, int> = 0,
  334. std::enable_if_t<!std::is_void<InnerR>::value, int> = 0>
  335. static int Inner(std::string* s) {
  336. static_assert(std::is_same<InnerR, int>::value, "Use int return type");
  337. *s += "Inner";
  338. *s += "None";
  339. return 99;
  340. }
  341. template <typename OuterR,
  342. typename InnerR,
  343. std::enable_if_t<!std::is_void<OuterR>::value, int> = 0,
  344. std::enable_if_t<std::is_void<InnerR>::value, int> = 0>
  345. static void Inner(std::string* s, OuterR a) {
  346. *s += "Inner";
  347. *s += base::NumberToString(a);
  348. }
  349. template <typename OuterR,
  350. typename InnerR,
  351. std::enable_if_t<std::is_void<OuterR>::value, int> = 0,
  352. std::enable_if_t<std::is_void<InnerR>::value, int> = 0>
  353. static void Inner(std::string* s) {
  354. *s += "Inner";
  355. *s += "None";
  356. }
  357. };
  358. template <typename R, typename ThenR = void, typename... Args>
  359. using CallbackThenOnceTest = CallbackThenTest<true, R, ThenR, Args...>;
  360. template <typename R, typename ThenR = void, typename... Args>
  361. using CallbackThenRepeatingTest = CallbackThenTest<false, R, ThenR, Args...>;
  362. TEST_F(CallbackTest, ThenOnce) {
  363. std::string s;
  364. // Void return from outer + void return from Then().
  365. {
  366. using VoidReturnWithoutArgs = void();
  367. using ThenReturn = void;
  368. using Test = CallbackThenOnceTest<VoidReturnWithoutArgs, ThenReturn>;
  369. Test::GetOuter(s).Then(Test::GetInner(s)).Run();
  370. EXPECT_EQ(s, "OuterNoneInnerNone");
  371. }
  372. {
  373. using VoidReturnWithArgs = void(int, int);
  374. using ThenReturn = void;
  375. using Test = CallbackThenOnceTest<VoidReturnWithArgs, ThenReturn>;
  376. Test::GetOuter(s).Then(Test::GetInner(s)).Run(1, 2);
  377. EXPECT_EQ(s, "Outer12InnerNone");
  378. }
  379. {
  380. using VoidReturnWithMoveOnlyArgs =
  381. void(std::unique_ptr<int>, std::unique_ptr<int>);
  382. using ThenReturn = void;
  383. using Test = CallbackThenOnceTest<VoidReturnWithMoveOnlyArgs, ThenReturn>;
  384. Test::GetOuter(s)
  385. .Then(Test::GetInner(s))
  386. .Run(std::make_unique<int>(1), std::make_unique<int>(2));
  387. EXPECT_EQ(s, "Outer12InnerNone");
  388. }
  389. // Void return from outer + non-void return from Then().
  390. {
  391. using VoidReturnWithoutArgs = void();
  392. using ThenReturn = int;
  393. using Test = CallbackThenOnceTest<VoidReturnWithoutArgs, ThenReturn>;
  394. EXPECT_EQ(99, Test::GetOuter(s).Then(Test::GetInner(s)).Run());
  395. EXPECT_EQ(s, "OuterNoneInnerNone");
  396. }
  397. {
  398. using VoidReturnWithArgs = void(int, int);
  399. using ThenReturn = int;
  400. using Test = CallbackThenOnceTest<VoidReturnWithArgs, ThenReturn>;
  401. EXPECT_EQ(99, Test::GetOuter(s).Then(Test::GetInner(s)).Run(1, 2));
  402. EXPECT_EQ(s, "Outer12InnerNone");
  403. }
  404. {
  405. using VoidReturnWithMoveOnlyArgs =
  406. void(std::unique_ptr<int>, std::unique_ptr<int>);
  407. using ThenReturn = int;
  408. using Test = CallbackThenOnceTest<VoidReturnWithMoveOnlyArgs, ThenReturn>;
  409. EXPECT_EQ(99, Test::GetOuter(s)
  410. .Then(Test::GetInner(s))
  411. .Run(std::make_unique<int>(1), std::make_unique<int>(2)));
  412. EXPECT_EQ(s, "Outer12InnerNone");
  413. }
  414. // Non-void return from outer + void return from Then().
  415. {
  416. using NonVoidReturnWithoutArgs = int();
  417. using ThenReturn = void;
  418. using Test = CallbackThenOnceTest<NonVoidReturnWithoutArgs, ThenReturn>;
  419. Test::GetOuter(s).Then(Test::GetInner(s)).Run();
  420. EXPECT_EQ(s, "OuterNoneInner99");
  421. }
  422. {
  423. using NonVoidReturnWithArgs = int(int, int);
  424. using ThenReturn = void;
  425. using Test = CallbackThenOnceTest<NonVoidReturnWithArgs, ThenReturn>;
  426. Test::GetOuter(s).Then(Test::GetInner(s)).Run(1, 2);
  427. EXPECT_EQ(s, "Outer12Inner3");
  428. }
  429. {
  430. using NonVoidReturnWithMoveOnlyArgs =
  431. int(std::unique_ptr<int>, std::unique_ptr<int>);
  432. using ThenReturn = void;
  433. using Test =
  434. CallbackThenOnceTest<NonVoidReturnWithMoveOnlyArgs, ThenReturn>;
  435. Test::GetOuter(s)
  436. .Then(Test::GetInner(s))
  437. .Run(std::make_unique<int>(1), std::make_unique<int>(2));
  438. EXPECT_EQ(s, "Outer12Inner3");
  439. }
  440. // Non-void return from outer + non-void return from Then().
  441. {
  442. using NonVoidReturnWithoutArgs = int();
  443. using ThenReturn = int;
  444. using Test = CallbackThenOnceTest<NonVoidReturnWithoutArgs, ThenReturn>;
  445. EXPECT_EQ(99, Test::GetOuter(s).Then(Test::GetInner(s)).Run());
  446. EXPECT_EQ(s, "OuterNoneInner99");
  447. }
  448. {
  449. using NonVoidReturnWithArgs = int(int, int);
  450. using ThenReturn = int;
  451. using Test = CallbackThenOnceTest<NonVoidReturnWithArgs, ThenReturn>;
  452. EXPECT_EQ(3, Test::GetOuter(s).Then(Test::GetInner(s)).Run(1, 2));
  453. EXPECT_EQ(s, "Outer12Inner3");
  454. }
  455. {
  456. using NonVoidReturnWithMoveOnlyArgs =
  457. int(std::unique_ptr<int>, std::unique_ptr<int>);
  458. using ThenReturn = int;
  459. using Test =
  460. CallbackThenOnceTest<NonVoidReturnWithMoveOnlyArgs, ThenReturn>;
  461. EXPECT_EQ(3, Test::GetOuter(s)
  462. .Then(Test::GetInner(s))
  463. .Run(std::make_unique<int>(1), std::make_unique<int>(2)));
  464. EXPECT_EQ(s, "Outer12Inner3");
  465. }
  466. }
  467. TEST_F(CallbackTest, ThenRepeating) {
  468. std::string s;
  469. // Void return from outer + void return from Then().
  470. {
  471. using VoidReturnWithoutArgs = void();
  472. using ThenReturn = void;
  473. using Test = CallbackThenRepeatingTest<VoidReturnWithoutArgs, ThenReturn>;
  474. auto outer = Test::GetOuter(s);
  475. outer.Then(Test::GetInner(s)).Run();
  476. EXPECT_EQ(s, "OuterNoneInnerNone");
  477. std::move(outer).Then(Test::GetInner(s)).Run();
  478. EXPECT_EQ(s, "OuterNoneInnerNoneOuterNoneInnerNone");
  479. }
  480. {
  481. using VoidReturnWithArgs = void(int, int);
  482. using ThenReturn = void;
  483. using Test = CallbackThenRepeatingTest<VoidReturnWithArgs, ThenReturn>;
  484. auto outer = Test::GetOuter(s);
  485. outer.Then(Test::GetInner(s)).Run(1, 2);
  486. EXPECT_EQ(s, "Outer12InnerNone");
  487. std::move(outer).Then(Test::GetInner(s)).Run(1, 2);
  488. EXPECT_EQ(s, "Outer12InnerNoneOuter12InnerNone");
  489. }
  490. {
  491. using VoidReturnWithMoveOnlyArgs =
  492. void(std::unique_ptr<int>, std::unique_ptr<int>);
  493. using ThenReturn = void;
  494. using Test =
  495. CallbackThenRepeatingTest<VoidReturnWithMoveOnlyArgs, ThenReturn>;
  496. auto outer = Test::GetOuter(s);
  497. outer.Then(Test::GetInner(s))
  498. .Run(std::make_unique<int>(1), std::make_unique<int>(2));
  499. EXPECT_EQ(s, "Outer12InnerNone");
  500. std::move(outer)
  501. .Then(Test::GetInner(s))
  502. .Run(std::make_unique<int>(1), std::make_unique<int>(2));
  503. EXPECT_EQ(s, "Outer12InnerNoneOuter12InnerNone");
  504. }
  505. // Void return from outer + non-void return from Then().
  506. {
  507. using VoidReturnWithoutArgs = void();
  508. using ThenReturn = int;
  509. using Test = CallbackThenRepeatingTest<VoidReturnWithoutArgs, ThenReturn>;
  510. auto outer = Test::GetOuter(s);
  511. EXPECT_EQ(99, outer.Then(Test::GetInner(s)).Run());
  512. EXPECT_EQ(s, "OuterNoneInnerNone");
  513. EXPECT_EQ(99, std::move(outer).Then(Test::GetInner(s)).Run());
  514. EXPECT_EQ(s, "OuterNoneInnerNoneOuterNoneInnerNone");
  515. }
  516. {
  517. using VoidReturnWithArgs = void(int, int);
  518. using ThenReturn = int;
  519. using Test = CallbackThenRepeatingTest<VoidReturnWithArgs, ThenReturn>;
  520. auto outer = Test::GetOuter(s);
  521. EXPECT_EQ(99, outer.Then(Test::GetInner(s)).Run(1, 2));
  522. EXPECT_EQ(s, "Outer12InnerNone");
  523. EXPECT_EQ(99, std::move(outer).Then(Test::GetInner(s)).Run(1, 2));
  524. EXPECT_EQ(s, "Outer12InnerNoneOuter12InnerNone");
  525. }
  526. {
  527. using VoidReturnWithMoveOnlyArgs =
  528. void(std::unique_ptr<int>, std::unique_ptr<int>);
  529. using ThenReturn = int;
  530. using Test =
  531. CallbackThenRepeatingTest<VoidReturnWithMoveOnlyArgs, ThenReturn>;
  532. auto outer = Test::GetOuter(s);
  533. EXPECT_EQ(99, outer.Then(Test::GetInner(s))
  534. .Run(std::make_unique<int>(1), std::make_unique<int>(2)));
  535. EXPECT_EQ(s, "Outer12InnerNone");
  536. EXPECT_EQ(99, std::move(outer)
  537. .Then(Test::GetInner(s))
  538. .Run(std::make_unique<int>(1), std::make_unique<int>(2)));
  539. EXPECT_EQ(s, "Outer12InnerNoneOuter12InnerNone");
  540. }
  541. // Non-void return from outer + void return from Then().
  542. {
  543. using NonVoidReturnWithoutArgs = int();
  544. using ThenReturn = void;
  545. using Test =
  546. CallbackThenRepeatingTest<NonVoidReturnWithoutArgs, ThenReturn>;
  547. auto outer = Test::GetOuter(s);
  548. outer.Then(Test::GetInner(s)).Run();
  549. EXPECT_EQ(s, "OuterNoneInner99");
  550. std::move(outer).Then(Test::GetInner(s)).Run();
  551. EXPECT_EQ(s, "OuterNoneInner99OuterNoneInner99");
  552. }
  553. {
  554. using NonVoidReturnWithArgs = int(int, int);
  555. using ThenReturn = void;
  556. using Test = CallbackThenRepeatingTest<NonVoidReturnWithArgs, ThenReturn>;
  557. auto outer = Test::GetOuter(s);
  558. outer.Then(Test::GetInner(s)).Run(1, 2);
  559. EXPECT_EQ(s, "Outer12Inner3");
  560. std::move(outer).Then(Test::GetInner(s)).Run(1, 2);
  561. EXPECT_EQ(s, "Outer12Inner3Outer12Inner3");
  562. }
  563. {
  564. using NonVoidReturnWithMoveOnlyArgs =
  565. int(std::unique_ptr<int>, std::unique_ptr<int>);
  566. using ThenReturn = void;
  567. using Test =
  568. CallbackThenRepeatingTest<NonVoidReturnWithMoveOnlyArgs, ThenReturn>;
  569. auto outer = Test::GetOuter(s);
  570. outer.Then(Test::GetInner(s))
  571. .Run(std::make_unique<int>(1), std::make_unique<int>(2));
  572. EXPECT_EQ(s, "Outer12Inner3");
  573. std::move(outer)
  574. .Then(Test::GetInner(s))
  575. .Run(std::make_unique<int>(1), std::make_unique<int>(2));
  576. EXPECT_EQ(s, "Outer12Inner3Outer12Inner3");
  577. }
  578. // Non-void return from outer + non-void return from Then().
  579. {
  580. using NonVoidReturnWithoutArgs = int();
  581. using ThenReturn = int;
  582. using Test =
  583. CallbackThenRepeatingTest<NonVoidReturnWithoutArgs, ThenReturn>;
  584. auto outer = Test::GetOuter(s);
  585. EXPECT_EQ(99, outer.Then(Test::GetInner(s)).Run());
  586. EXPECT_EQ(s, "OuterNoneInner99");
  587. EXPECT_EQ(99, std::move(outer).Then(Test::GetInner(s)).Run());
  588. EXPECT_EQ(s, "OuterNoneInner99OuterNoneInner99");
  589. }
  590. {
  591. using NonVoidReturnWithArgs = int(int, int);
  592. using ThenReturn = int;
  593. using Test = CallbackThenRepeatingTest<NonVoidReturnWithArgs, ThenReturn>;
  594. auto outer = Test::GetOuter(s);
  595. EXPECT_EQ(3, outer.Then(Test::GetInner(s)).Run(1, 2));
  596. EXPECT_EQ(s, "Outer12Inner3");
  597. EXPECT_EQ(3, std::move(outer).Then(Test::GetInner(s)).Run(1, 2));
  598. EXPECT_EQ(s, "Outer12Inner3Outer12Inner3");
  599. }
  600. {
  601. using NonVoidReturnWithMoveOnlyArgs =
  602. int(std::unique_ptr<int>, std::unique_ptr<int>);
  603. using ThenReturn = int;
  604. using Test =
  605. CallbackThenRepeatingTest<NonVoidReturnWithMoveOnlyArgs, ThenReturn>;
  606. auto outer = Test::GetOuter(s);
  607. EXPECT_EQ(3, outer.Then(Test::GetInner(s))
  608. .Run(std::make_unique<int>(1), std::make_unique<int>(2)));
  609. EXPECT_EQ(s, "Outer12Inner3");
  610. EXPECT_EQ(3, std::move(outer)
  611. .Then(Test::GetInner(s))
  612. .Run(std::make_unique<int>(1), std::make_unique<int>(2)));
  613. EXPECT_EQ(s, "Outer12Inner3Outer12Inner3");
  614. }
  615. }
  616. // WeakPtr detection in BindRepeating() requires a method, not just any
  617. // function.
  618. class ClassWithAMethod {
  619. public:
  620. void TheMethod() { method_called = true; }
  621. bool method_called = false;
  622. };
  623. TEST_F(CallbackTest, MaybeValidInvalidateWeakPtrsOnSameSequence) {
  624. ClassWithAMethod obj;
  625. WeakPtrFactory<ClassWithAMethod> factory(&obj);
  626. WeakPtr<ClassWithAMethod> ptr = factory.GetWeakPtr();
  627. RepeatingCallback<void()> cb =
  628. BindRepeating(&ClassWithAMethod::TheMethod, ptr);
  629. EXPECT_TRUE(cb.MaybeValid());
  630. EXPECT_FALSE(cb.IsCancelled());
  631. factory.InvalidateWeakPtrs();
  632. // MaybeValid() should be false and IsCancelled() should become true because
  633. // InvalidateWeakPtrs() was called on the same thread.
  634. EXPECT_FALSE(cb.MaybeValid());
  635. EXPECT_TRUE(cb.IsCancelled());
  636. // is_null() is not affected by the invalidated WeakPtr.
  637. EXPECT_FALSE(cb.is_null());
  638. }
  639. TEST_F(CallbackTest, MaybeValidInvalidateWeakPtrsOnOtherSequence) {
  640. ClassWithAMethod obj;
  641. WeakPtrFactory<ClassWithAMethod> factory(&obj);
  642. WeakPtr<ClassWithAMethod> ptr = factory.GetWeakPtr();
  643. RepeatingCallback<void()> cb =
  644. BindRepeating(&ClassWithAMethod::TheMethod, ptr);
  645. EXPECT_TRUE(cb.MaybeValid());
  646. Thread other_thread("other_thread");
  647. other_thread.StartAndWaitForTesting();
  648. other_thread.task_runner()->PostTask(
  649. FROM_HERE,
  650. BindOnce(
  651. [](RepeatingCallback<void()> cb) {
  652. // Check that MaybeValid() _eventually_ returns false.
  653. const TimeDelta timeout = TestTimeouts::tiny_timeout();
  654. const TimeTicks begin = TimeTicks::Now();
  655. while (cb.MaybeValid() && (TimeTicks::Now() - begin) < timeout)
  656. PlatformThread::YieldCurrentThread();
  657. EXPECT_FALSE(cb.MaybeValid());
  658. },
  659. cb));
  660. factory.InvalidateWeakPtrs();
  661. // |other_thread|'s destructor will join, ensuring we wait for the task to be
  662. // run.
  663. }
  664. TEST_F(CallbackTest, ThenAfterWeakPtr) {
  665. ClassWithAMethod obj;
  666. WeakPtrFactory<ClassWithAMethod> factory(&obj);
  667. WeakPtr<ClassWithAMethod> ptr = factory.GetWeakPtr();
  668. // If the first callback of a chain is skipped due to InvalidateWeakPtrs(),
  669. // the remaining callbacks should still run.
  670. bool chained_closure_called = false;
  671. OnceClosure closure =
  672. BindOnce(&ClassWithAMethod::TheMethod, ptr)
  673. .Then(BindLambdaForTesting(
  674. [&chained_closure_called] { chained_closure_called = true; }));
  675. factory.InvalidateWeakPtrs();
  676. std::move(closure).Run();
  677. EXPECT_FALSE(obj.method_called);
  678. EXPECT_TRUE(chained_closure_called);
  679. }
  680. class CallbackOwner : public base::RefCounted<CallbackOwner> {
  681. public:
  682. explicit CallbackOwner(bool* deleted) {
  683. // WrapRefCounted() here is needed to avoid the check failure in the
  684. // BindRepeating implementation, that refuses to create the first reference
  685. // to ref-counted objects.
  686. callback_ = BindRepeating(&CallbackOwner::Unused, WrapRefCounted(this));
  687. deleted_ = deleted;
  688. }
  689. void Reset() {
  690. callback_.Reset();
  691. // We are deleted here if no-one else had a ref to us.
  692. }
  693. private:
  694. friend class base::RefCounted<CallbackOwner>;
  695. virtual ~CallbackOwner() {
  696. *deleted_ = true;
  697. }
  698. void Unused() {
  699. FAIL() << "Should never be called";
  700. }
  701. RepeatingClosure callback_;
  702. raw_ptr<bool> deleted_;
  703. };
  704. TEST_F(CallbackTest, CallbackHasLastRefOnContainingObject) {
  705. bool deleted = false;
  706. CallbackOwner* owner = new CallbackOwner(&deleted);
  707. owner->Reset();
  708. ASSERT_TRUE(deleted);
  709. }
  710. } // namespace
  711. } // namespace base