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