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/basictypes.h"
6 #include "base/memory/scoped_ptr.h"
8 #include "base/task_queue.h"
9 #include "testing/gtest/include/gtest/gtest.h"
13 // Sets bools according to whether Run or the destructor were called.
14 class TrackCallsTask
: public Task
{
16 TrackCallsTask(bool* ran
, bool* deleted
)
23 virtual ~TrackCallsTask() {
35 DISALLOW_COPY_AND_ASSIGN(TrackCallsTask
);
38 // Adds a given task to the queue when run.
39 class TaskQueuerTask
: public Task
{
41 TaskQueuerTask(TaskQueue
* queue
, Task
* task_to_queue
)
43 task_to_queue_(task_to_queue
) {
47 queue_
->Push(task_to_queue_
);
54 DISALLOW_COPY_AND_ASSIGN(TaskQueuerTask
);
59 TEST(TaskQueueTest
, RunNoTasks
) {
61 EXPECT_TRUE(queue
.IsEmpty());
64 EXPECT_TRUE(queue
.IsEmpty());
67 TEST(TaskQueueTest
, RunTasks
) {
70 bool ran_task1
= false;
71 bool deleted_task1
= false;
72 queue
.Push(new TrackCallsTask(&ran_task1
, &deleted_task1
));
74 bool ran_task2
= false;
75 bool deleted_task2
= false;
76 queue
.Push(new TrackCallsTask(&ran_task2
, &deleted_task2
));
80 EXPECT_TRUE(ran_task1
);
81 EXPECT_TRUE(deleted_task1
);
82 EXPECT_TRUE(ran_task2
);
83 EXPECT_TRUE(deleted_task2
);
84 EXPECT_TRUE(queue
.IsEmpty());
87 TEST(TaskQueueTest
, ClearTasks
) {
90 bool ran_task1
= false;
91 bool deleted_task1
= false;
92 queue
.Push(new TrackCallsTask(&ran_task1
, &deleted_task1
));
94 bool ran_task2
= false;
95 bool deleted_task2
= false;
96 queue
.Push(new TrackCallsTask(&ran_task2
, &deleted_task2
));
100 EXPECT_TRUE(queue
.IsEmpty());
104 EXPECT_FALSE(ran_task1
);
105 EXPECT_TRUE(deleted_task1
);
106 EXPECT_FALSE(ran_task2
);
107 EXPECT_TRUE(deleted_task2
);
108 EXPECT_TRUE(queue
.IsEmpty());
111 TEST(TaskQueueTest
, OneTaskQueuesMore
) {
112 TaskQueue main_queue
;
114 // Build a task which will queue two more when run.
115 scoped_ptr
<TaskQueue
> nested_queue(new TaskQueue());
116 bool ran_task1
= false;
117 bool deleted_task1
= false;
119 new TaskQueuerTask(&main_queue
,
120 new TrackCallsTask(&ran_task1
, &deleted_task1
)));
121 bool ran_task2
= false;
122 bool deleted_task2
= false;
124 new TaskQueuerTask(&main_queue
,
125 new TrackCallsTask(&ran_task2
, &deleted_task2
)));
127 main_queue
.Push(nested_queue
.release());
129 // Run the task which pushes two more tasks.
132 // None of the pushed tasks shoudl have run yet.
133 EXPECT_FALSE(ran_task1
);
134 EXPECT_FALSE(deleted_task1
);
135 EXPECT_FALSE(ran_task2
);
136 EXPECT_FALSE(deleted_task2
);
137 EXPECT_FALSE(main_queue
.IsEmpty());
139 // Now run the nested tasks.
142 EXPECT_TRUE(ran_task1
);
143 EXPECT_TRUE(deleted_task1
);
144 EXPECT_TRUE(ran_task2
);
145 EXPECT_TRUE(deleted_task2
);
146 EXPECT_TRUE(main_queue
.IsEmpty());