1 // Copyright (c) 2011 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.
5 #include "base/memory/ref_counted.h"
7 #include "testing/gtest/include/gtest/gtest.h"
11 class CancelInDestructor
: public base::RefCounted
<CancelInDestructor
> {
13 CancelInDestructor() : cancelable_task_(NULL
) {}
16 if (cancelable_task_
) {
21 cancelable_task_
= NewRunnableMethod(
22 this, &CancelInDestructor::NeverIssuedCallback
);
26 CancelableTask
* cancelable_task() {
27 return cancelable_task_
;
31 friend class base::RefCounted
<CancelInDestructor
>;
33 ~CancelInDestructor() {
35 cancelable_task_
->Cancel();
38 void NeverIssuedCallback() { NOTREACHED(); }
40 CancelableTask
* cancelable_task_
;
43 TEST(TaskTest
, TestCancelInDestructor
) {
44 // Intentionally not using a scoped_refptr for cancel_in_destructor.
45 CancelInDestructor
* cancel_in_destructor
= new CancelInDestructor();
46 cancel_in_destructor
->Start();
47 CancelableTask
* cancelable_task
= cancel_in_destructor
->cancelable_task();
48 ASSERT_TRUE(cancelable_task
);
49 delete cancelable_task
;
52 class DoneTask
: public Task
{
54 DoneTask(int* run_count
, bool* was_deleted
)
55 : run_count_(run_count
), was_deleted_(was_deleted
) {
69 TEST(TaskTest
, TestScopedTaskRunnerExitScope
) {
71 bool was_deleted
= false;
73 base::ScopedTaskRunner
runner(new DoneTask(&run_count
, &was_deleted
));
74 EXPECT_EQ(0, run_count
);
76 EXPECT_EQ(1, run_count
);
77 EXPECT_TRUE(was_deleted
);
80 TEST(TaskTest
, TestScopedTaskRunnerRelease
) {
82 bool was_deleted
= false;
84 base::ScopedTaskRunner
runner(new DoneTask(&run_count
, &was_deleted
));
85 delete runner
.Release();
86 EXPECT_TRUE(was_deleted
);
88 EXPECT_EQ(0, run_count
);
91 TEST(TaskTest
, TestScopedTaskRunnerManualRun
) {
93 Task
* done_task
= NULL
;
94 bool was_deleted
= false;
96 base::ScopedTaskRunner
runner(new DoneTask(&run_count
, &was_deleted
));
97 done_task
= runner
.Release();
98 EXPECT_TRUE(NULL
!= done_task
);
99 EXPECT_FALSE(was_deleted
);
100 EXPECT_EQ(0, run_count
);
102 EXPECT_FALSE(was_deleted
);
103 EXPECT_EQ(1, run_count
);
105 EXPECT_EQ(1, run_count
);
107 EXPECT_TRUE(was_deleted
);