1 // Copyright 2018 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/task/sequence_manager/sequence_manager_impl.h"
6
7 #include <stddef.h>
8 #include <memory>
9 #include <utility>
10
11 #include "base/location.h"
12 #include "base/memory/ref_counted_memory.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/message_loop/message_loop_current.h"
15 #include "base/optional.h"
16 #include "base/run_loop.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/synchronization/waitable_event.h"
19 #include "base/task/sequence_manager/real_time_domain.h"
20 #include "base/task/sequence_manager/task_queue_impl.h"
21 #include "base/task/sequence_manager/task_queue_selector.h"
22 #include "base/task/sequence_manager/test/mock_time_domain.h"
23 #include "base/task/sequence_manager/test/sequence_manager_for_test.h"
24 #include "base/task/sequence_manager/test/test_task_queue.h"
25 #include "base/task/sequence_manager/test/test_task_time_observer.h"
26 #include "base/task/sequence_manager/thread_controller_with_message_pump_impl.h"
27 #include "base/task/sequence_manager/work_queue.h"
28 #include "base/task/sequence_manager/work_queue_sets.h"
29 #include "base/test/simple_test_tick_clock.h"
30 #include "base/test/test_mock_time_task_runner.h"
31 #include "base/test/test_simple_task_runner.h"
32 #include "base/test/trace_event_analyzer.h"
33 #include "base/threading/thread.h"
34 #include "base/threading/thread_task_runner_handle.h"
35 #include "base/trace_event/blame_context.h"
36 #include "testing/gmock/include/gmock/gmock.h"
37
38 using testing::AnyNumber;
39 using testing::Contains;
40 using testing::ElementsAre;
41 using testing::ElementsAreArray;
42 using testing::Mock;
43 using testing::Not;
44 using testing::_;
45 using base::sequence_manager::internal::EnqueueOrder;
46
47 namespace base {
48 namespace sequence_manager {
49 namespace internal {
50 // To avoid symbol collisions in jumbo builds.
51 namespace sequence_manager_impl_unittest {
52
53 enum class TestType : int {
54 kCustom = 0,
55 kUseMockTaskRunner = 1,
56 kUseMessageLoop = 2,
57 kUseMessagePump = 3,
58 };
59
60 class SequenceManagerTestBase : public testing::TestWithParam<TestType> {
61 protected:
TearDown()62 void TearDown() override {
63 // SequenceManager should be deleted before an underlying task runner.
64 manager_.reset();
65 }
66
CreateTaskQueue(TaskQueue::Spec spec=TaskQueue::Spec ("test"))67 scoped_refptr<TestTaskQueue> CreateTaskQueue(
68 TaskQueue::Spec spec = TaskQueue::Spec("test")) {
69 return manager_->CreateTaskQueue<TestTaskQueue>(spec);
70 }
71
CreateTaskQueues(size_t num_queues)72 void CreateTaskQueues(size_t num_queues) {
73 for (size_t i = 0; i < num_queues; i++)
74 runners_.push_back(CreateTaskQueue());
75 }
76
77 std::unique_ptr<SequenceManagerForTest> manager_;
78 std::vector<scoped_refptr<TestTaskQueue>> runners_;
79 TimeTicks start_time_;
80 TestTaskTimeObserver test_task_time_observer_;
81 };
82
83 // SequenceManagerImpl uses TestMockTimeTaskRunner which controls
84 // both task execution and mock clock.
85 // TODO(kraynov): Make this class to support all TestTypes.
86 // It will allow us to re-run tests in various environments before we'll
87 // eventually move to MessagePump and remove current ThreadControllerImpl.
88 class SequenceManagerTest : public SequenceManagerTestBase {
89 public:
DeleteSequenceManagerTask()90 void DeleteSequenceManagerTask() { manager_.reset(); }
91
92 protected:
SetUp()93 void SetUp() override {
94 ASSERT_EQ(GetParam(), TestType::kUseMockTaskRunner);
95 test_task_runner_ = WrapRefCounted(new TestMockTimeTaskRunner(
96 TestMockTimeTaskRunner::Type::kBoundToThread));
97 // A null clock triggers some assertions.
98 test_task_runner_->AdvanceMockTickClock(TimeDelta::FromMilliseconds(1));
99 start_time_ = GetTickClock()->NowTicks();
100
101 manager_ =
102 SequenceManagerForTest::Create(nullptr, ThreadTaskRunnerHandle::Get(),
103 test_task_runner_->GetMockTickClock());
104 }
105
GetTickClock()106 const TickClock* GetTickClock() {
107 return test_task_runner_->GetMockTickClock();
108 }
109
RunPendingTasks()110 void RunPendingTasks() {
111 // We should only run tasks already posted by that moment.
112 RunLoop run_loop;
113 test_task_runner_->PostTask(FROM_HERE, run_loop.QuitClosure());
114 // TestMockTimeTaskRunner will fast-forward mock clock if necessary.
115 run_loop.Run();
116 }
117
118 // Runs all immediate tasks until there is no more work to do and advances
119 // time if there is a pending delayed task. |per_run_time_callback| is called
120 // when the clock advances.
121 // The only difference to FastForwardUntilNoTasksRemain is that time
122 // advancing isn't driven by the test task runner, but uses time domain's
123 // next scheduled run time instead. It allows us to double-check consistency
124 // and allows to count such bursts of doing work, which is a test subject.
RunUntilManagerIsIdle(RepeatingClosure per_run_time_callback)125 void RunUntilManagerIsIdle(RepeatingClosure per_run_time_callback) {
126 for (;;) {
127 // Advance time if we've run out of immediate work to do.
128 if (!manager_->HasImmediateWork()) {
129 LazyNow lazy_now(GetTickClock());
130 Optional<TimeDelta> delay =
131 manager_->GetRealTimeDomain()->DelayTillNextTask(&lazy_now);
132 if (delay) {
133 test_task_runner_->AdvanceMockTickClock(*delay);
134 per_run_time_callback.Run();
135 } else {
136 break;
137 }
138 }
139 RunPendingTasks();
140 }
141 }
142
143 scoped_refptr<TestMockTimeTaskRunner> test_task_runner_;
144 };
145
146 // SequenceManagerImpl is being initialized with real MessageLoop
147 // at cost of less control over a task runner.
148 // It also runs a version with experimental MessagePump support.
149 // TODO(kraynov): Generalize as many tests as possible to run it
150 // in all supported environments.
151 class SequenceManagerTestWithMessageLoop : public SequenceManagerTestBase {
152 protected:
SetUp()153 void SetUp() override {
154 switch (GetParam()) {
155 case TestType::kUseMessageLoop:
156 SetUpWithMessageLoop();
157 break;
158 case TestType::kUseMessagePump:
159 SetUpWithMessagePump();
160 break;
161 default:
162 FAIL();
163 }
164 }
165
SetUpWithMessageLoop()166 void SetUpWithMessageLoop() {
167 message_loop_.reset(new MessageLoop());
168 // A null clock triggers some assertions.
169 mock_clock_.Advance(TimeDelta::FromMilliseconds(1));
170 start_time_ = mock_clock_.NowTicks();
171
172 manager_ = SequenceManagerForTest::Create(
173 message_loop_.get(), ThreadTaskRunnerHandle::Get(), &mock_clock_);
174 }
175
SetUpWithMessagePump()176 void SetUpWithMessagePump() {
177 mock_clock_.Advance(TimeDelta::FromMilliseconds(1));
178 start_time_ = mock_clock_.NowTicks();
179 manager_ = std::make_unique<SequenceManagerForTest>(
180 std::make_unique<ThreadControllerWithMessagePumpImpl>(&mock_clock_));
181 // ThreadControllerWithMessagePumpImpl doesn't provide a default tas runner.
182 scoped_refptr<TaskQueue> default_task_queue =
183 manager_->CreateTaskQueue<TestTaskQueue>(TaskQueue::Spec("default"));
184 manager_->SetDefaultTaskRunner(default_task_queue);
185 }
186
GetTickClock()187 const TickClock* GetTickClock() { return &mock_clock_; }
188
189 std::unique_ptr<MessageLoop> message_loop_;
190 SimpleTestTickClock mock_clock_;
191 };
192
193 class SequenceManagerTestWithCustomInitialization
194 : public SequenceManagerTestWithMessageLoop {
195 protected:
SetUp()196 void SetUp() override { ASSERT_EQ(GetParam(), TestType::kCustom); }
197 };
198
199 INSTANTIATE_TEST_CASE_P(,
200 SequenceManagerTest,
201 testing::Values(TestType::kUseMockTaskRunner));
202
203 INSTANTIATE_TEST_CASE_P(,
204 SequenceManagerTestWithMessageLoop,
205 testing::Values(TestType::kUseMessageLoop,
206 TestType::kUseMessagePump));
207
208 INSTANTIATE_TEST_CASE_P(,
209 SequenceManagerTestWithCustomInitialization,
210 testing::Values(TestType::kCustom));
211
PostFromNestedRunloop(SingleThreadTaskRunner * runner,std::vector<std::pair<OnceClosure,bool>> * tasks)212 void PostFromNestedRunloop(SingleThreadTaskRunner* runner,
213 std::vector<std::pair<OnceClosure, bool>>* tasks) {
214 for (std::pair<OnceClosure, bool>& pair : *tasks) {
215 if (pair.second) {
216 runner->PostTask(FROM_HERE, std::move(pair.first));
217 } else {
218 runner->PostNonNestableTask(FROM_HERE, std::move(pair.first));
219 }
220 }
221 RunLoop(RunLoop::Type::kNestableTasksAllowed).RunUntilIdle();
222 }
223
NopTask()224 void NopTask() {}
225
226 class TestCountUsesTimeSource : public TickClock {
227 public:
228 TestCountUsesTimeSource() = default;
229 ~TestCountUsesTimeSource() override = default;
230
NowTicks() const231 TimeTicks NowTicks() const override {
232 now_calls_count_++;
233 // Don't return 0, as it triggers some assertions.
234 return TimeTicks() + TimeDelta::FromSeconds(1);
235 }
236
now_calls_count() const237 int now_calls_count() const { return now_calls_count_; }
238
239 private:
240 mutable int now_calls_count_ = 0;
241
242 DISALLOW_COPY_AND_ASSIGN(TestCountUsesTimeSource);
243 };
244
TEST_P(SequenceManagerTestWithCustomInitialization,NowCalledMinimumNumberOfTimesToComputeTaskDurations)245 TEST_P(SequenceManagerTestWithCustomInitialization,
246 NowCalledMinimumNumberOfTimesToComputeTaskDurations) {
247 message_loop_.reset(new MessageLoop());
248 // This memory is managed by the SequenceManager, but we need to hold a
249 // pointer to this object to read out how many times Now was called.
250 TestCountUsesTimeSource test_count_uses_time_source;
251
252 manager_ = SequenceManagerForTest::Create(
253 nullptr, ThreadTaskRunnerHandle::Get(), &test_count_uses_time_source);
254 manager_->SetWorkBatchSize(6);
255 manager_->AddTaskTimeObserver(&test_task_time_observer_);
256
257 for (size_t i = 0; i < 3; i++)
258 runners_.push_back(CreateTaskQueue());
259
260 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
261 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
262 runners_[1]->PostTask(FROM_HERE, BindOnce(&NopTask));
263 runners_[1]->PostTask(FROM_HERE, BindOnce(&NopTask));
264 runners_[2]->PostTask(FROM_HERE, BindOnce(&NopTask));
265 runners_[2]->PostTask(FROM_HERE, BindOnce(&NopTask));
266
267 RunLoop().RunUntilIdle();
268 // Now is called each time a task is queued, when first task is started
269 // running, and when a task is completed. 6 * 3 = 18 calls.
270 EXPECT_EQ(18, test_count_uses_time_source.now_calls_count());
271 }
272
NullTask()273 void NullTask() {}
274
TestTask(uint64_t value,std::vector<EnqueueOrder> * out_result)275 void TestTask(uint64_t value, std::vector<EnqueueOrder>* out_result) {
276 out_result->push_back(EnqueueOrder::FromIntForTesting(value));
277 }
278
DisableQueueTestTask(uint64_t value,std::vector<EnqueueOrder> * out_result,TaskQueue::QueueEnabledVoter * voter)279 void DisableQueueTestTask(uint64_t value,
280 std::vector<EnqueueOrder>* out_result,
281 TaskQueue::QueueEnabledVoter* voter) {
282 out_result->push_back(EnqueueOrder::FromIntForTesting(value));
283 voter->SetQueueEnabled(false);
284 }
285
TEST_P(SequenceManagerTest,SingleQueuePosting)286 TEST_P(SequenceManagerTest, SingleQueuePosting) {
287 CreateTaskQueues(1u);
288
289 std::vector<EnqueueOrder> run_order;
290 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
291 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
292 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
293
294 RunLoop().RunUntilIdle();
295 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u));
296 }
297
TEST_P(SequenceManagerTest,MultiQueuePosting)298 TEST_P(SequenceManagerTest, MultiQueuePosting) {
299 CreateTaskQueues(3u);
300
301 std::vector<EnqueueOrder> run_order;
302 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
303 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
304 runners_[1]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
305 runners_[1]->PostTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order));
306 runners_[2]->PostTask(FROM_HERE, BindOnce(&TestTask, 5, &run_order));
307 runners_[2]->PostTask(FROM_HERE, BindOnce(&TestTask, 6, &run_order));
308
309 RunLoop().RunUntilIdle();
310 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u, 4u, 5u, 6u));
311 }
312
TEST_P(SequenceManagerTestWithMessageLoop,NonNestableTaskPosting)313 TEST_P(SequenceManagerTestWithMessageLoop, NonNestableTaskPosting) {
314 CreateTaskQueues(1u);
315
316 std::vector<EnqueueOrder> run_order;
317 runners_[0]->PostNonNestableTask(FROM_HERE,
318 BindOnce(&TestTask, 1, &run_order));
319
320 RunLoop().RunUntilIdle();
321 EXPECT_THAT(run_order, ElementsAre(1u));
322 }
323
TEST_P(SequenceManagerTestWithMessageLoop,NonNestableTaskExecutesInExpectedOrder)324 TEST_P(SequenceManagerTestWithMessageLoop,
325 NonNestableTaskExecutesInExpectedOrder) {
326 CreateTaskQueues(1u);
327
328 std::vector<EnqueueOrder> run_order;
329 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
330 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
331 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
332 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order));
333 runners_[0]->PostNonNestableTask(FROM_HERE,
334 BindOnce(&TestTask, 5, &run_order));
335
336 RunLoop().RunUntilIdle();
337 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u, 4u, 5u));
338 }
339
TEST_P(SequenceManagerTestWithMessageLoop,NonNestableTasksDoesntExecuteInNestedLoop)340 TEST_P(SequenceManagerTestWithMessageLoop,
341 NonNestableTasksDoesntExecuteInNestedLoop) {
342 CreateTaskQueues(1u);
343
344 std::vector<EnqueueOrder> run_order;
345 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
346 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
347
348 std::vector<std::pair<OnceClosure, bool>> tasks_to_post_from_nested_loop;
349 tasks_to_post_from_nested_loop.push_back(
350 std::make_pair(BindOnce(&TestTask, 3, &run_order), false));
351 tasks_to_post_from_nested_loop.push_back(
352 std::make_pair(BindOnce(&TestTask, 4, &run_order), false));
353 tasks_to_post_from_nested_loop.push_back(
354 std::make_pair(BindOnce(&TestTask, 5, &run_order), true));
355 tasks_to_post_from_nested_loop.push_back(
356 std::make_pair(BindOnce(&TestTask, 6, &run_order), true));
357
358 runners_[0]->PostTask(
359 FROM_HERE, BindOnce(&PostFromNestedRunloop, RetainedRef(runners_[0]),
360 Unretained(&tasks_to_post_from_nested_loop)));
361
362 RunLoop().RunUntilIdle();
363 // Note we expect tasks 3 & 4 to run last because they're non-nestable.
364 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 5u, 6u, 3u, 4u));
365 }
366
367 namespace {
368
InsertFenceAndPostTestTask(int id,std::vector<EnqueueOrder> * run_order,scoped_refptr<TestTaskQueue> task_queue)369 void InsertFenceAndPostTestTask(int id,
370 std::vector<EnqueueOrder>* run_order,
371 scoped_refptr<TestTaskQueue> task_queue) {
372 run_order->push_back(EnqueueOrder::FromIntForTesting(id));
373 task_queue->InsertFence(TaskQueue::InsertFencePosition::kNow);
374 task_queue->PostTask(FROM_HERE, BindOnce(&TestTask, id + 1, run_order));
375
376 // Force reload of immediate work queue. In real life the same effect can be
377 // achieved with cross-thread posting.
378 task_queue->GetTaskQueueImpl()->ReloadImmediateWorkQueueIfEmpty();
379 }
380
381 } // namespace
382
TEST_P(SequenceManagerTestWithMessageLoop,TaskQueueDisabledFromNestedLoop)383 TEST_P(SequenceManagerTestWithMessageLoop, TaskQueueDisabledFromNestedLoop) {
384 CreateTaskQueues(1u);
385 std::vector<EnqueueOrder> run_order;
386
387 std::vector<std::pair<OnceClosure, bool>> tasks_to_post_from_nested_loop;
388
389 tasks_to_post_from_nested_loop.push_back(
390 std::make_pair(BindOnce(&TestTask, 1, &run_order), false));
391 tasks_to_post_from_nested_loop.push_back(std::make_pair(
392 BindOnce(&InsertFenceAndPostTestTask, 2, &run_order, runners_[0]), true));
393
394 runners_[0]->PostTask(
395 FROM_HERE, BindOnce(&PostFromNestedRunloop, RetainedRef(runners_[0]),
396 Unretained(&tasks_to_post_from_nested_loop)));
397 RunLoop().RunUntilIdle();
398
399 // Task 1 shouldn't run first due to it being non-nestable and queue gets
400 // blocked after task 2. Task 1 runs after existing nested message loop
401 // due to being posted before inserting a fence.
402 // This test checks that breaks when nestable task is pushed into a redo
403 // queue.
404 EXPECT_THAT(run_order, ElementsAre(2u, 1u));
405
406 runners_[0]->RemoveFence();
407 RunLoop().RunUntilIdle();
408 EXPECT_THAT(run_order, ElementsAre(2u, 1u, 3u));
409 }
410
TEST_P(SequenceManagerTest,HasPendingImmediateWork_ImmediateTask)411 TEST_P(SequenceManagerTest, HasPendingImmediateWork_ImmediateTask) {
412 CreateTaskQueues(1u);
413
414 std::vector<EnqueueOrder> run_order;
415 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
416 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
417 EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately());
418
419 // Move the task into the |immediate_work_queue|.
420 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->immediate_work_queue()->Empty());
421 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
422 runners_[0]->CreateQueueEnabledVoter();
423 voter->SetQueueEnabled(false);
424 RunLoop().RunUntilIdle();
425 EXPECT_FALSE(
426 runners_[0]->GetTaskQueueImpl()->immediate_work_queue()->Empty());
427 EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately());
428
429 // Run the task, making the queue empty.
430 voter->SetQueueEnabled(true);
431 RunLoop().RunUntilIdle();
432 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
433 }
434
TEST_P(SequenceManagerTest,HasPendingImmediateWork_DelayedTask)435 TEST_P(SequenceManagerTest, HasPendingImmediateWork_DelayedTask) {
436 CreateTaskQueues(1u);
437
438 std::vector<EnqueueOrder> run_order;
439 TimeDelta delay(TimeDelta::FromMilliseconds(10));
440 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
441 delay);
442 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
443 test_task_runner_->AdvanceMockTickClock(delay);
444 EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately());
445
446 // Move the task into the |delayed_work_queue|.
447 LazyNow lazy_now(GetTickClock());
448 manager_->WakeUpReadyDelayedQueues(&lazy_now);
449 EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->delayed_work_queue()->Empty());
450 EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately());
451
452 // Run the task, making the queue empty.
453 RunLoop().RunUntilIdle();
454 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
455 }
456
TEST_P(SequenceManagerTest,DelayedTaskPosting)457 TEST_P(SequenceManagerTest, DelayedTaskPosting) {
458 CreateTaskQueues(1u);
459
460 std::vector<EnqueueOrder> run_order;
461 TimeDelta delay(TimeDelta::FromMilliseconds(10));
462 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
463 delay);
464 EXPECT_EQ(TimeDelta::FromMilliseconds(10),
465 test_task_runner_->NextPendingTaskDelay());
466 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
467 EXPECT_TRUE(run_order.empty());
468
469 // The task doesn't run before the delay has completed.
470 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(9));
471 EXPECT_TRUE(run_order.empty());
472
473 // After the delay has completed, the task runs normally.
474 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1));
475 EXPECT_THAT(run_order, ElementsAre(1u));
476 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
477 }
478
TEST_P(SequenceManagerTest,DelayedTaskExecutedInOneMessageLoopTask)479 TEST_P(SequenceManagerTest, DelayedTaskExecutedInOneMessageLoopTask) {
480 CreateTaskQueues(1u);
481
482 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
483 TimeDelta::FromMilliseconds(10));
484 RunLoop().RunUntilIdle();
485 EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
486 test_task_runner_->FastForwardUntilNoTasksRemain();
487 EXPECT_EQ(0u, test_task_runner_->GetPendingTaskCount());
488 }
489
TEST_P(SequenceManagerTest,DelayedTaskPosting_MultipleTasks_DecendingOrder)490 TEST_P(SequenceManagerTest, DelayedTaskPosting_MultipleTasks_DecendingOrder) {
491 CreateTaskQueues(1u);
492
493 std::vector<EnqueueOrder> run_order;
494 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
495 TimeDelta::FromMilliseconds(10));
496
497 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
498 TimeDelta::FromMilliseconds(8));
499
500 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order),
501 TimeDelta::FromMilliseconds(5));
502
503 EXPECT_EQ(TimeDelta::FromMilliseconds(5),
504 test_task_runner_->NextPendingTaskDelay());
505
506 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(5));
507 EXPECT_THAT(run_order, ElementsAre(3u));
508 EXPECT_EQ(TimeDelta::FromMilliseconds(3),
509 test_task_runner_->NextPendingTaskDelay());
510
511 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(3));
512 EXPECT_THAT(run_order, ElementsAre(3u, 2u));
513 EXPECT_EQ(TimeDelta::FromMilliseconds(2),
514 test_task_runner_->NextPendingTaskDelay());
515
516 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(2));
517 EXPECT_THAT(run_order, ElementsAre(3u, 2u, 1u));
518 }
519
TEST_P(SequenceManagerTest,DelayedTaskPosting_MultipleTasks_AscendingOrder)520 TEST_P(SequenceManagerTest, DelayedTaskPosting_MultipleTasks_AscendingOrder) {
521 CreateTaskQueues(1u);
522
523 std::vector<EnqueueOrder> run_order;
524 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
525 TimeDelta::FromMilliseconds(1));
526
527 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
528 TimeDelta::FromMilliseconds(5));
529
530 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order),
531 TimeDelta::FromMilliseconds(10));
532
533 EXPECT_EQ(TimeDelta::FromMilliseconds(1),
534 test_task_runner_->NextPendingTaskDelay());
535
536 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1));
537 EXPECT_THAT(run_order, ElementsAre(1u));
538 EXPECT_EQ(TimeDelta::FromMilliseconds(4),
539 test_task_runner_->NextPendingTaskDelay());
540
541 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(4));
542 EXPECT_THAT(run_order, ElementsAre(1u, 2u));
543 EXPECT_EQ(TimeDelta::FromMilliseconds(5),
544 test_task_runner_->NextPendingTaskDelay());
545
546 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(5));
547 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u));
548 }
549
TEST_P(SequenceManagerTest,PostDelayedTask_SharesUnderlyingDelayedTasks)550 TEST_P(SequenceManagerTest, PostDelayedTask_SharesUnderlyingDelayedTasks) {
551 CreateTaskQueues(1u);
552
553 std::vector<EnqueueOrder> run_order;
554 TimeDelta delay(TimeDelta::FromMilliseconds(10));
555 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
556 delay);
557 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
558 delay);
559 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order),
560 delay);
561
562 EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
563 }
564
565 class TestObject {
566 public:
~TestObject()567 ~TestObject() { destructor_count__++; }
568
Run()569 void Run() { FAIL() << "TestObject::Run should not be called"; }
570
571 static int destructor_count__;
572 };
573
574 int TestObject::destructor_count__ = 0;
575
TEST_P(SequenceManagerTest,PendingDelayedTasksRemovedOnShutdown)576 TEST_P(SequenceManagerTest, PendingDelayedTasksRemovedOnShutdown) {
577 CreateTaskQueues(1u);
578
579 TestObject::destructor_count__ = 0;
580
581 TimeDelta delay(TimeDelta::FromMilliseconds(10));
582 runners_[0]->PostDelayedTask(
583 FROM_HERE, BindOnce(&TestObject::Run, Owned(new TestObject())), delay);
584 runners_[0]->PostTask(FROM_HERE,
585 BindOnce(&TestObject::Run, Owned(new TestObject())));
586
587 manager_.reset();
588
589 EXPECT_EQ(2, TestObject::destructor_count__);
590 }
591
TEST_P(SequenceManagerTest,InsertAndRemoveFence)592 TEST_P(SequenceManagerTest, InsertAndRemoveFence) {
593 CreateTaskQueues(1u);
594 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
595
596 std::vector<EnqueueOrder> run_order;
597 // Posting a task when pumping is disabled doesn't result in work getting
598 // posted.
599 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
600 EXPECT_FALSE(test_task_runner_->HasPendingTask());
601
602 // However polling still works.
603 EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately());
604
605 // After removing the fence the task runs normally.
606 runners_[0]->RemoveFence();
607 EXPECT_TRUE(test_task_runner_->HasPendingTask());
608 RunLoop().RunUntilIdle();
609 EXPECT_THAT(run_order, ElementsAre(1u));
610 }
611
TEST_P(SequenceManagerTest,RemovingFenceForDisabledQueueDoesNotPostDoWork)612 TEST_P(SequenceManagerTest, RemovingFenceForDisabledQueueDoesNotPostDoWork) {
613 CreateTaskQueues(1u);
614
615 std::vector<EnqueueOrder> run_order;
616 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
617 runners_[0]->CreateQueueEnabledVoter();
618 voter->SetQueueEnabled(false);
619 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
620 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
621
622 runners_[0]->RemoveFence();
623 EXPECT_FALSE(test_task_runner_->HasPendingTask());
624 }
625
TEST_P(SequenceManagerTest,EnablingFencedQueueDoesNotPostDoWork)626 TEST_P(SequenceManagerTest, EnablingFencedQueueDoesNotPostDoWork) {
627 CreateTaskQueues(1u);
628
629 std::vector<EnqueueOrder> run_order;
630 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
631 runners_[0]->CreateQueueEnabledVoter();
632 voter->SetQueueEnabled(false);
633 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
634 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
635
636 voter->SetQueueEnabled(true);
637 EXPECT_FALSE(test_task_runner_->HasPendingTask());
638 }
639
TEST_P(SequenceManagerTest,DenyRunning_BeforePosting)640 TEST_P(SequenceManagerTest, DenyRunning_BeforePosting) {
641 CreateTaskQueues(1u);
642
643 std::vector<EnqueueOrder> run_order;
644 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
645 runners_[0]->CreateQueueEnabledVoter();
646 voter->SetQueueEnabled(false);
647 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
648 EXPECT_FALSE(test_task_runner_->HasPendingTask());
649
650 RunLoop().RunUntilIdle();
651 EXPECT_TRUE(run_order.empty());
652
653 voter->SetQueueEnabled(true);
654 RunLoop().RunUntilIdle();
655 EXPECT_THAT(run_order, ElementsAre(1u));
656 }
657
TEST_P(SequenceManagerTest,DenyRunning_AfterPosting)658 TEST_P(SequenceManagerTest, DenyRunning_AfterPosting) {
659 CreateTaskQueues(1u);
660
661 std::vector<EnqueueOrder> run_order;
662 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
663 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
664 runners_[0]->CreateQueueEnabledVoter();
665 EXPECT_TRUE(test_task_runner_->HasPendingTask());
666 voter->SetQueueEnabled(false);
667
668 RunLoop().RunUntilIdle();
669 EXPECT_TRUE(run_order.empty());
670
671 voter->SetQueueEnabled(true);
672 RunLoop().RunUntilIdle();
673 EXPECT_THAT(run_order, ElementsAre(1u));
674 }
675
TEST_P(SequenceManagerTest,DenyRunning_AfterRemovingFence)676 TEST_P(SequenceManagerTest, DenyRunning_AfterRemovingFence) {
677 CreateTaskQueues(1u);
678
679 std::vector<EnqueueOrder> run_order;
680 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
681 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
682 runners_[0]->CreateQueueEnabledVoter();
683 voter->SetQueueEnabled(false);
684 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
685
686 RunLoop().RunUntilIdle();
687 EXPECT_TRUE(run_order.empty());
688
689 runners_[0]->RemoveFence();
690 voter->SetQueueEnabled(true);
691 RunLoop().RunUntilIdle();
692 EXPECT_THAT(run_order, ElementsAre(1u));
693 }
694
TEST_P(SequenceManagerTest,RemovingFenceWithDelayedTask)695 TEST_P(SequenceManagerTest, RemovingFenceWithDelayedTask) {
696 CreateTaskQueues(1u);
697 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
698
699 std::vector<EnqueueOrder> run_order;
700 // Posting a delayed task when fenced will apply the delay, but won't cause
701 // work to executed afterwards.
702 TimeDelta delay(TimeDelta::FromMilliseconds(10));
703 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
704 delay);
705
706 // The task does not run even though it's delay is up.
707 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(10));
708 EXPECT_TRUE(run_order.empty());
709
710 // Removing the fence causes the task to run.
711 runners_[0]->RemoveFence();
712 EXPECT_TRUE(test_task_runner_->HasPendingTask());
713 RunPendingTasks();
714 EXPECT_THAT(run_order, ElementsAre(1u));
715 }
716
TEST_P(SequenceManagerTest,RemovingFenceWithMultipleDelayedTasks)717 TEST_P(SequenceManagerTest, RemovingFenceWithMultipleDelayedTasks) {
718 CreateTaskQueues(1u);
719 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
720
721 std::vector<EnqueueOrder> run_order;
722 // Posting a delayed task when fenced will apply the delay, but won't cause
723 // work to executed afterwards.
724 TimeDelta delay1(TimeDelta::FromMilliseconds(1));
725 TimeDelta delay2(TimeDelta::FromMilliseconds(10));
726 TimeDelta delay3(TimeDelta::FromMilliseconds(20));
727 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
728 delay1);
729 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
730 delay2);
731 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order),
732 delay3);
733
734 test_task_runner_->AdvanceMockTickClock(TimeDelta::FromMilliseconds(15));
735 RunLoop().RunUntilIdle();
736 EXPECT_TRUE(run_order.empty());
737
738 // Removing the fence causes the ready tasks to run.
739 runners_[0]->RemoveFence();
740 RunLoop().RunUntilIdle();
741 EXPECT_THAT(run_order, ElementsAre(1u, 2u));
742 }
743
TEST_P(SequenceManagerTest,InsertFencePreventsDelayedTasksFromRunning)744 TEST_P(SequenceManagerTest, InsertFencePreventsDelayedTasksFromRunning) {
745 CreateTaskQueues(1u);
746 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
747
748 std::vector<EnqueueOrder> run_order;
749 TimeDelta delay(TimeDelta::FromMilliseconds(10));
750 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
751 delay);
752
753 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(10));
754 EXPECT_TRUE(run_order.empty());
755 }
756
TEST_P(SequenceManagerTest,MultipleFences)757 TEST_P(SequenceManagerTest, MultipleFences) {
758 CreateTaskQueues(1u);
759
760 std::vector<EnqueueOrder> run_order;
761 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
762 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
763 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
764
765 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
766 RunLoop().RunUntilIdle();
767 EXPECT_THAT(run_order, ElementsAre(1u, 2u));
768
769 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
770 // Subsequent tasks should be blocked.
771 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order));
772 RunLoop().RunUntilIdle();
773 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u));
774 }
775
TEST_P(SequenceManagerTest,InsertFenceThenImmediatlyRemoveDoesNotBlock)776 TEST_P(SequenceManagerTest, InsertFenceThenImmediatlyRemoveDoesNotBlock) {
777 CreateTaskQueues(1u);
778 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
779 runners_[0]->RemoveFence();
780
781 std::vector<EnqueueOrder> run_order;
782 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
783 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
784
785 RunLoop().RunUntilIdle();
786 EXPECT_THAT(run_order, ElementsAre(1u, 2u));
787 }
788
TEST_P(SequenceManagerTest,InsertFencePostThenRemoveDoesNotBlock)789 TEST_P(SequenceManagerTest, InsertFencePostThenRemoveDoesNotBlock) {
790 CreateTaskQueues(1u);
791 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
792
793 std::vector<EnqueueOrder> run_order;
794 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
795 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
796 runners_[0]->RemoveFence();
797
798 RunLoop().RunUntilIdle();
799 EXPECT_THAT(run_order, ElementsAre(1u, 2u));
800 }
801
TEST_P(SequenceManagerTest,MultipleFencesWithInitiallyEmptyQueue)802 TEST_P(SequenceManagerTest, MultipleFencesWithInitiallyEmptyQueue) {
803 CreateTaskQueues(1u);
804 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
805
806 std::vector<EnqueueOrder> run_order;
807 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
808 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
809 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
810
811 RunLoop().RunUntilIdle();
812 EXPECT_THAT(run_order, ElementsAre(1u));
813 }
814
TEST_P(SequenceManagerTest,BlockedByFence)815 TEST_P(SequenceManagerTest, BlockedByFence) {
816 CreateTaskQueues(1u);
817 EXPECT_FALSE(runners_[0]->BlockedByFence());
818
819 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
820 EXPECT_TRUE(runners_[0]->BlockedByFence());
821
822 runners_[0]->RemoveFence();
823 EXPECT_FALSE(runners_[0]->BlockedByFence());
824
825 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
826 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
827 EXPECT_FALSE(runners_[0]->BlockedByFence());
828
829 RunLoop().RunUntilIdle();
830 EXPECT_TRUE(runners_[0]->BlockedByFence());
831
832 runners_[0]->RemoveFence();
833 EXPECT_FALSE(runners_[0]->BlockedByFence());
834 }
835
TEST_P(SequenceManagerTest,BlockedByFence_BothTypesOfFence)836 TEST_P(SequenceManagerTest, BlockedByFence_BothTypesOfFence) {
837 CreateTaskQueues(1u);
838
839 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
840
841 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
842 EXPECT_FALSE(runners_[0]->BlockedByFence());
843
844 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kBeginningOfTime);
845 EXPECT_TRUE(runners_[0]->BlockedByFence());
846 }
847
848 namespace {
849
RecordTimeTask(std::vector<TimeTicks> * run_times,const TickClock * clock)850 void RecordTimeTask(std::vector<TimeTicks>* run_times, const TickClock* clock) {
851 run_times->push_back(clock->NowTicks());
852 }
853
RecordTimeAndQueueTask(std::vector<std::pair<scoped_refptr<TestTaskQueue>,TimeTicks>> * run_times,scoped_refptr<TestTaskQueue> task_queue,const TickClock * clock)854 void RecordTimeAndQueueTask(
855 std::vector<std::pair<scoped_refptr<TestTaskQueue>, TimeTicks>>* run_times,
856 scoped_refptr<TestTaskQueue> task_queue,
857 const TickClock* clock) {
858 run_times->emplace_back(task_queue, clock->NowTicks());
859 }
860
861 } // namespace
862
TEST_P(SequenceManagerTest,DelayedFence_DelayedTasks)863 TEST_P(SequenceManagerTest, DelayedFence_DelayedTasks) {
864 CreateTaskQueues(1u);
865
866 std::vector<TimeTicks> run_times;
867 runners_[0]->PostDelayedTask(
868 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()),
869 TimeDelta::FromMilliseconds(100));
870 runners_[0]->PostDelayedTask(
871 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()),
872 TimeDelta::FromMilliseconds(200));
873 runners_[0]->PostDelayedTask(
874 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()),
875 TimeDelta::FromMilliseconds(300));
876
877 runners_[0]->InsertFenceAt(GetTickClock()->NowTicks() +
878 TimeDelta::FromMilliseconds(250));
879 EXPECT_FALSE(runners_[0]->HasActiveFence());
880
881 test_task_runner_->FastForwardUntilNoTasksRemain();
882
883 EXPECT_TRUE(runners_[0]->HasActiveFence());
884 EXPECT_THAT(run_times,
885 ElementsAre(start_time_ + TimeDelta::FromMilliseconds(100),
886 start_time_ + TimeDelta::FromMilliseconds(200)));
887 run_times.clear();
888
889 runners_[0]->RemoveFence();
890
891 test_task_runner_->FastForwardUntilNoTasksRemain();
892
893 EXPECT_FALSE(runners_[0]->HasActiveFence());
894 EXPECT_THAT(run_times,
895 ElementsAre(start_time_ + TimeDelta::FromMilliseconds(300)));
896 }
897
TEST_P(SequenceManagerTest,DelayedFence_ImmediateTasks)898 TEST_P(SequenceManagerTest, DelayedFence_ImmediateTasks) {
899 CreateTaskQueues(1u);
900
901 std::vector<TimeTicks> run_times;
902 runners_[0]->InsertFenceAt(GetTickClock()->NowTicks() +
903 TimeDelta::FromMilliseconds(250));
904
905 for (int i = 0; i < 5; ++i) {
906 runners_[0]->PostTask(
907 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()));
908 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100));
909 if (i < 2) {
910 EXPECT_FALSE(runners_[0]->HasActiveFence());
911 } else {
912 EXPECT_TRUE(runners_[0]->HasActiveFence());
913 }
914 }
915
916 EXPECT_THAT(
917 run_times,
918 ElementsAre(start_time_, start_time_ + TimeDelta::FromMilliseconds(100),
919 start_time_ + TimeDelta::FromMilliseconds(200)));
920 run_times.clear();
921
922 runners_[0]->RemoveFence();
923 test_task_runner_->FastForwardUntilNoTasksRemain();
924
925 EXPECT_THAT(run_times,
926 ElementsAre(start_time_ + TimeDelta::FromMilliseconds(500),
927 start_time_ + TimeDelta::FromMilliseconds(500)));
928 }
929
TEST_P(SequenceManagerTest,DelayedFence_RemovedFenceDoesNotActivate)930 TEST_P(SequenceManagerTest, DelayedFence_RemovedFenceDoesNotActivate) {
931 CreateTaskQueues(1u);
932
933 std::vector<TimeTicks> run_times;
934 runners_[0]->InsertFenceAt(GetTickClock()->NowTicks() +
935 TimeDelta::FromMilliseconds(250));
936
937 for (int i = 0; i < 3; ++i) {
938 runners_[0]->PostTask(
939 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()));
940 EXPECT_FALSE(runners_[0]->HasActiveFence());
941 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100));
942 }
943
944 EXPECT_TRUE(runners_[0]->HasActiveFence());
945 runners_[0]->RemoveFence();
946
947 for (int i = 0; i < 2; ++i) {
948 runners_[0]->PostTask(
949 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()));
950 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100));
951 EXPECT_FALSE(runners_[0]->HasActiveFence());
952 }
953
954 EXPECT_THAT(
955 run_times,
956 ElementsAre(start_time_, start_time_ + TimeDelta::FromMilliseconds(100),
957 start_time_ + TimeDelta::FromMilliseconds(200),
958 start_time_ + TimeDelta::FromMilliseconds(300),
959 start_time_ + TimeDelta::FromMilliseconds(400)));
960 }
961
TEST_P(SequenceManagerTest,DelayedFence_TakeIncomingImmediateQueue)962 TEST_P(SequenceManagerTest, DelayedFence_TakeIncomingImmediateQueue) {
963 // This test checks that everything works correctly when a work queue
964 // is swapped with an immediate incoming queue and a delayed fence
965 // is activated, forcing a different queue to become active.
966 CreateTaskQueues(2u);
967
968 scoped_refptr<TestTaskQueue> queue1 = runners_[0];
969 scoped_refptr<TestTaskQueue> queue2 = runners_[1];
970
971 std::vector<std::pair<scoped_refptr<TestTaskQueue>, TimeTicks>> run_times;
972
973 // Fence ensures that the task posted after advancing time is blocked.
974 queue1->InsertFenceAt(GetTickClock()->NowTicks() +
975 TimeDelta::FromMilliseconds(250));
976
977 // This task should not be blocked and should run immediately after
978 // advancing time at 301ms.
979 queue1->PostTask(FROM_HERE, BindOnce(&RecordTimeAndQueueTask, &run_times,
980 queue1, GetTickClock()));
981 // Force reload of immediate work queue. In real life the same effect can be
982 // achieved with cross-thread posting.
983 queue1->GetTaskQueueImpl()->ReloadImmediateWorkQueueIfEmpty();
984
985 test_task_runner_->AdvanceMockTickClock(TimeDelta::FromMilliseconds(300));
986
987 // This task should be blocked.
988 queue1->PostTask(FROM_HERE, BindOnce(&RecordTimeAndQueueTask, &run_times,
989 queue1, GetTickClock()));
990 // This task on a different runner should run as expected.
991 queue2->PostTask(FROM_HERE, BindOnce(&RecordTimeAndQueueTask, &run_times,
992 queue2, GetTickClock()));
993
994 test_task_runner_->FastForwardUntilNoTasksRemain();
995
996 EXPECT_THAT(
997 run_times,
998 ElementsAre(std::make_pair(
999 queue1, start_time_ + TimeDelta::FromMilliseconds(300)),
1000 std::make_pair(
1001 queue2, start_time_ + TimeDelta::FromMilliseconds(300))));
1002 }
1003
1004 namespace {
1005
ReentrantTestTask(scoped_refptr<SingleThreadTaskRunner> runner,int countdown,std::vector<EnqueueOrder> * out_result)1006 void ReentrantTestTask(scoped_refptr<SingleThreadTaskRunner> runner,
1007 int countdown,
1008 std::vector<EnqueueOrder>* out_result) {
1009 out_result->push_back(EnqueueOrder::FromIntForTesting(countdown));
1010 if (--countdown) {
1011 runner->PostTask(
1012 FROM_HERE, BindOnce(&ReentrantTestTask, runner, countdown, out_result));
1013 }
1014 }
1015
1016 } // namespace
1017
TEST_P(SequenceManagerTest,ReentrantPosting)1018 TEST_P(SequenceManagerTest, ReentrantPosting) {
1019 CreateTaskQueues(1u);
1020
1021 std::vector<EnqueueOrder> run_order;
1022 runners_[0]->PostTask(
1023 FROM_HERE, BindOnce(&ReentrantTestTask, runners_[0], 3, &run_order));
1024
1025 RunLoop().RunUntilIdle();
1026 EXPECT_THAT(run_order, ElementsAre(3u, 2u, 1u));
1027 }
1028
TEST_P(SequenceManagerTest,NoTasksAfterShutdown)1029 TEST_P(SequenceManagerTest, NoTasksAfterShutdown) {
1030 CreateTaskQueues(1u);
1031
1032 std::vector<EnqueueOrder> run_order;
1033 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1034 manager_.reset();
1035 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1036
1037 RunLoop().RunUntilIdle();
1038 EXPECT_TRUE(run_order.empty());
1039 }
1040
PostTaskToRunner(scoped_refptr<SingleThreadTaskRunner> runner,std::vector<EnqueueOrder> * run_order)1041 void PostTaskToRunner(scoped_refptr<SingleThreadTaskRunner> runner,
1042 std::vector<EnqueueOrder>* run_order) {
1043 runner->PostTask(FROM_HERE, BindOnce(&TestTask, 1, run_order));
1044 }
1045
TEST_P(SequenceManagerTestWithMessageLoop,PostFromThread)1046 TEST_P(SequenceManagerTestWithMessageLoop, PostFromThread) {
1047 CreateTaskQueues(1u);
1048
1049 std::vector<EnqueueOrder> run_order;
1050 Thread thread("TestThread");
1051 thread.Start();
1052 thread.task_runner()->PostTask(
1053 FROM_HERE, BindOnce(&PostTaskToRunner, runners_[0], &run_order));
1054 thread.Stop();
1055
1056 RunLoop().RunUntilIdle();
1057 EXPECT_THAT(run_order, ElementsAre(1u));
1058 }
1059
RePostingTestTask(scoped_refptr<SingleThreadTaskRunner> runner,int * run_count)1060 void RePostingTestTask(scoped_refptr<SingleThreadTaskRunner> runner,
1061 int* run_count) {
1062 (*run_count)++;
1063 runner->PostTask(FROM_HERE, BindOnce(&RePostingTestTask,
1064 Unretained(runner.get()), run_count));
1065 }
1066
TEST_P(SequenceManagerTest,DoWorkCantPostItselfMultipleTimes)1067 TEST_P(SequenceManagerTest, DoWorkCantPostItselfMultipleTimes) {
1068 CreateTaskQueues(1u);
1069
1070 int run_count = 0;
1071 runners_[0]->PostTask(FROM_HERE,
1072 BindOnce(&RePostingTestTask, runners_[0], &run_count));
1073
1074 RunPendingTasks();
1075 EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
1076 EXPECT_EQ(1, run_count);
1077 }
1078
TEST_P(SequenceManagerTestWithMessageLoop,PostFromNestedRunloop)1079 TEST_P(SequenceManagerTestWithMessageLoop, PostFromNestedRunloop) {
1080 CreateTaskQueues(1u);
1081
1082 std::vector<EnqueueOrder> run_order;
1083 std::vector<std::pair<OnceClosure, bool>> tasks_to_post_from_nested_loop;
1084 tasks_to_post_from_nested_loop.push_back(
1085 std::make_pair(BindOnce(&TestTask, 1, &run_order), true));
1086
1087 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 0, &run_order));
1088 runners_[0]->PostTask(
1089 FROM_HERE, BindOnce(&PostFromNestedRunloop, RetainedRef(runners_[0]),
1090 Unretained(&tasks_to_post_from_nested_loop)));
1091 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
1092
1093 RunLoop().RunUntilIdle();
1094
1095 EXPECT_THAT(run_order, ElementsAre(0u, 2u, 1u));
1096 }
1097
TEST_P(SequenceManagerTest,WorkBatching)1098 TEST_P(SequenceManagerTest, WorkBatching) {
1099 CreateTaskQueues(1u);
1100
1101 manager_->SetWorkBatchSize(2);
1102
1103 std::vector<EnqueueOrder> run_order;
1104 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1105 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
1106 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
1107 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order));
1108
1109 // Running one task in the host message loop should cause two posted tasks to
1110 // get executed.
1111 EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
1112 RunPendingTasks();
1113 EXPECT_THAT(run_order, ElementsAre(1u, 2u));
1114
1115 // The second task runs the remaining two posted tasks.
1116 EXPECT_EQ(1u, test_task_runner_->GetPendingTaskCount());
1117 RunPendingTasks();
1118 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u, 4u));
1119 }
1120
1121 class MockTaskObserver : public MessageLoop::TaskObserver {
1122 public:
1123 MOCK_METHOD1(DidProcessTask, void(const PendingTask& task));
1124 MOCK_METHOD1(WillProcessTask, void(const PendingTask& task));
1125 };
1126
TEST_P(SequenceManagerTestWithMessageLoop,TaskObserverAdding)1127 TEST_P(SequenceManagerTestWithMessageLoop, TaskObserverAdding) {
1128 CreateTaskQueues(1u);
1129 MockTaskObserver observer;
1130
1131 manager_->SetWorkBatchSize(2);
1132 manager_->AddTaskObserver(&observer);
1133
1134 std::vector<EnqueueOrder> run_order;
1135 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1136 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
1137
1138 EXPECT_CALL(observer, WillProcessTask(_)).Times(2);
1139 EXPECT_CALL(observer, DidProcessTask(_)).Times(2);
1140 RunLoop().RunUntilIdle();
1141 }
1142
TEST_P(SequenceManagerTestWithMessageLoop,TaskObserverRemoving)1143 TEST_P(SequenceManagerTestWithMessageLoop, TaskObserverRemoving) {
1144 CreateTaskQueues(1u);
1145 MockTaskObserver observer;
1146 manager_->SetWorkBatchSize(2);
1147 manager_->AddTaskObserver(&observer);
1148 manager_->RemoveTaskObserver(&observer);
1149
1150 std::vector<EnqueueOrder> run_order;
1151 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1152
1153 EXPECT_CALL(observer, WillProcessTask(_)).Times(0);
1154 EXPECT_CALL(observer, DidProcessTask(_)).Times(0);
1155 RunLoop().RunUntilIdle();
1156 }
1157
RemoveObserverTask(SequenceManagerImpl * manager,MessageLoop::TaskObserver * observer)1158 void RemoveObserverTask(SequenceManagerImpl* manager,
1159 MessageLoop::TaskObserver* observer) {
1160 manager->RemoveTaskObserver(observer);
1161 }
1162
TEST_P(SequenceManagerTestWithMessageLoop,TaskObserverRemovingInsideTask)1163 TEST_P(SequenceManagerTestWithMessageLoop, TaskObserverRemovingInsideTask) {
1164 CreateTaskQueues(1u);
1165 MockTaskObserver observer;
1166 manager_->SetWorkBatchSize(3);
1167 manager_->AddTaskObserver(&observer);
1168
1169 runners_[0]->PostTask(
1170 FROM_HERE, BindOnce(&RemoveObserverTask, manager_.get(), &observer));
1171
1172 EXPECT_CALL(observer, WillProcessTask(_)).Times(1);
1173 EXPECT_CALL(observer, DidProcessTask(_)).Times(0);
1174 RunLoop().RunUntilIdle();
1175 }
1176
TEST_P(SequenceManagerTestWithMessageLoop,QueueTaskObserverAdding)1177 TEST_P(SequenceManagerTestWithMessageLoop, QueueTaskObserverAdding) {
1178 CreateTaskQueues(2u);
1179 MockTaskObserver observer;
1180
1181 manager_->SetWorkBatchSize(2);
1182 runners_[0]->AddTaskObserver(&observer);
1183
1184 std::vector<EnqueueOrder> run_order;
1185 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1186 runners_[1]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
1187
1188 EXPECT_CALL(observer, WillProcessTask(_)).Times(1);
1189 EXPECT_CALL(observer, DidProcessTask(_)).Times(1);
1190 RunLoop().RunUntilIdle();
1191 }
1192
TEST_P(SequenceManagerTestWithMessageLoop,QueueTaskObserverRemoving)1193 TEST_P(SequenceManagerTestWithMessageLoop, QueueTaskObserverRemoving) {
1194 CreateTaskQueues(1u);
1195 MockTaskObserver observer;
1196 manager_->SetWorkBatchSize(2);
1197 runners_[0]->AddTaskObserver(&observer);
1198 runners_[0]->RemoveTaskObserver(&observer);
1199
1200 std::vector<EnqueueOrder> run_order;
1201 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1202
1203 EXPECT_CALL(observer, WillProcessTask(_)).Times(0);
1204 EXPECT_CALL(observer, DidProcessTask(_)).Times(0);
1205
1206 RunLoop().RunUntilIdle();
1207 }
1208
RemoveQueueObserverTask(scoped_refptr<TaskQueue> queue,MessageLoop::TaskObserver * observer)1209 void RemoveQueueObserverTask(scoped_refptr<TaskQueue> queue,
1210 MessageLoop::TaskObserver* observer) {
1211 queue->RemoveTaskObserver(observer);
1212 }
1213
TEST_P(SequenceManagerTestWithMessageLoop,QueueTaskObserverRemovingInsideTask)1214 TEST_P(SequenceManagerTestWithMessageLoop,
1215 QueueTaskObserverRemovingInsideTask) {
1216 CreateTaskQueues(1u);
1217 MockTaskObserver observer;
1218 runners_[0]->AddTaskObserver(&observer);
1219
1220 runners_[0]->PostTask(
1221 FROM_HERE, BindOnce(&RemoveQueueObserverTask, runners_[0], &observer));
1222
1223 EXPECT_CALL(observer, WillProcessTask(_)).Times(1);
1224 EXPECT_CALL(observer, DidProcessTask(_)).Times(0);
1225 RunLoop().RunUntilIdle();
1226 }
1227
TEST_P(SequenceManagerTest,ThreadCheckAfterTermination)1228 TEST_P(SequenceManagerTest, ThreadCheckAfterTermination) {
1229 CreateTaskQueues(1u);
1230 EXPECT_TRUE(runners_[0]->RunsTasksInCurrentSequence());
1231 manager_.reset();
1232 EXPECT_TRUE(runners_[0]->RunsTasksInCurrentSequence());
1233 }
1234
TEST_P(SequenceManagerTest,TimeDomain_NextScheduledRunTime)1235 TEST_P(SequenceManagerTest, TimeDomain_NextScheduledRunTime) {
1236 CreateTaskQueues(2u);
1237 test_task_runner_->AdvanceMockTickClock(TimeDelta::FromMicroseconds(10000));
1238 LazyNow lazy_now_1(GetTickClock());
1239
1240 // With no delayed tasks.
1241 EXPECT_FALSE(manager_->GetRealTimeDomain()->DelayTillNextTask(&lazy_now_1));
1242
1243 // With a non-delayed task.
1244 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
1245 EXPECT_FALSE(manager_->GetRealTimeDomain()->DelayTillNextTask(&lazy_now_1));
1246
1247 // With a delayed task.
1248 TimeDelta expected_delay = TimeDelta::FromMilliseconds(50);
1249 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), expected_delay);
1250 EXPECT_EQ(expected_delay,
1251 manager_->GetRealTimeDomain()->DelayTillNextTask(&lazy_now_1));
1252
1253 // With another delayed task in the same queue with a longer delay.
1254 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
1255 TimeDelta::FromMilliseconds(100));
1256 EXPECT_EQ(expected_delay,
1257 manager_->GetRealTimeDomain()->DelayTillNextTask(&lazy_now_1));
1258
1259 // With another delayed task in the same queue with a shorter delay.
1260 expected_delay = TimeDelta::FromMilliseconds(20);
1261 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), expected_delay);
1262 EXPECT_EQ(expected_delay,
1263 manager_->GetRealTimeDomain()->DelayTillNextTask(&lazy_now_1));
1264
1265 // With another delayed task in a different queue with a shorter delay.
1266 expected_delay = TimeDelta::FromMilliseconds(10);
1267 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), expected_delay);
1268 EXPECT_EQ(expected_delay,
1269 manager_->GetRealTimeDomain()->DelayTillNextTask(&lazy_now_1));
1270
1271 // Test it updates as time progresses
1272 test_task_runner_->AdvanceMockTickClock(expected_delay);
1273 LazyNow lazy_now_2(GetTickClock());
1274 EXPECT_EQ(TimeDelta(),
1275 manager_->GetRealTimeDomain()->DelayTillNextTask(&lazy_now_2));
1276 }
1277
TEST_P(SequenceManagerTest,TimeDomain_NextScheduledRunTime_MultipleQueues)1278 TEST_P(SequenceManagerTest, TimeDomain_NextScheduledRunTime_MultipleQueues) {
1279 CreateTaskQueues(3u);
1280
1281 TimeDelta delay1 = TimeDelta::FromMilliseconds(50);
1282 TimeDelta delay2 = TimeDelta::FromMilliseconds(5);
1283 TimeDelta delay3 = TimeDelta::FromMilliseconds(10);
1284 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay1);
1285 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay2);
1286 runners_[2]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay3);
1287 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
1288
1289 LazyNow lazy_now(GetTickClock());
1290 EXPECT_EQ(delay2,
1291 manager_->GetRealTimeDomain()->DelayTillNextTask(&lazy_now));
1292 }
1293
TEST_P(SequenceManagerTest,DeleteSequenceManagerInsideATask)1294 TEST_P(SequenceManagerTest, DeleteSequenceManagerInsideATask) {
1295 CreateTaskQueues(1u);
1296
1297 runners_[0]->PostTask(
1298 FROM_HERE, BindOnce(&SequenceManagerTest::DeleteSequenceManagerTask,
1299 Unretained(this)));
1300
1301 // This should not crash, assuming DoWork detects the SequenceManager has
1302 // been deleted.
1303 RunLoop().RunUntilIdle();
1304 }
1305
TEST_P(SequenceManagerTest,GetAndClearSystemIsQuiescentBit)1306 TEST_P(SequenceManagerTest, GetAndClearSystemIsQuiescentBit) {
1307 CreateTaskQueues(3u);
1308
1309 scoped_refptr<TaskQueue> queue0 =
1310 CreateTaskQueue(TaskQueue::Spec("test").SetShouldMonitorQuiescence(true));
1311 scoped_refptr<TaskQueue> queue1 =
1312 CreateTaskQueue(TaskQueue::Spec("test").SetShouldMonitorQuiescence(true));
1313 scoped_refptr<TaskQueue> queue2 = CreateTaskQueue();
1314
1315 EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit());
1316
1317 queue0->PostTask(FROM_HERE, BindOnce(&NopTask));
1318 RunLoop().RunUntilIdle();
1319 EXPECT_FALSE(manager_->GetAndClearSystemIsQuiescentBit());
1320 EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit());
1321
1322 queue1->PostTask(FROM_HERE, BindOnce(&NopTask));
1323 RunLoop().RunUntilIdle();
1324 EXPECT_FALSE(manager_->GetAndClearSystemIsQuiescentBit());
1325 EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit());
1326
1327 queue2->PostTask(FROM_HERE, BindOnce(&NopTask));
1328 RunLoop().RunUntilIdle();
1329 EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit());
1330
1331 queue0->PostTask(FROM_HERE, BindOnce(&NopTask));
1332 queue1->PostTask(FROM_HERE, BindOnce(&NopTask));
1333 RunLoop().RunUntilIdle();
1334 EXPECT_FALSE(manager_->GetAndClearSystemIsQuiescentBit());
1335 EXPECT_TRUE(manager_->GetAndClearSystemIsQuiescentBit());
1336 }
1337
TEST_P(SequenceManagerTest,HasPendingImmediateWork)1338 TEST_P(SequenceManagerTest, HasPendingImmediateWork) {
1339 CreateTaskQueues(1u);
1340
1341 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
1342 runners_[0]->PostTask(FROM_HERE, BindOnce(NullTask));
1343 EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately());
1344
1345 RunLoop().RunUntilIdle();
1346 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
1347 }
1348
TEST_P(SequenceManagerTest,HasPendingImmediateWork_DelayedTasks)1349 TEST_P(SequenceManagerTest, HasPendingImmediateWork_DelayedTasks) {
1350 CreateTaskQueues(1u);
1351
1352 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
1353 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(NullTask),
1354 TimeDelta::FromMilliseconds(12));
1355 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
1356
1357 // Move time forwards until just before the delayed task should run.
1358 test_task_runner_->AdvanceMockTickClock(TimeDelta::FromMilliseconds(10));
1359 LazyNow lazy_now_1(GetTickClock());
1360 manager_->WakeUpReadyDelayedQueues(&lazy_now_1);
1361 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
1362
1363 // Force the delayed task onto the work queue.
1364 test_task_runner_->AdvanceMockTickClock(TimeDelta::FromMilliseconds(2));
1365 LazyNow lazy_now_2(GetTickClock());
1366 manager_->WakeUpReadyDelayedQueues(&lazy_now_2);
1367 EXPECT_TRUE(runners_[0]->HasTaskToRunImmediately());
1368
1369 RunLoop().RunUntilIdle();
1370 EXPECT_FALSE(runners_[0]->HasTaskToRunImmediately());
1371 }
1372
ExpensiveTestTask(int value,scoped_refptr<TestMockTimeTaskRunner> test_task_runner,std::vector<EnqueueOrder> * out_result)1373 void ExpensiveTestTask(int value,
1374 scoped_refptr<TestMockTimeTaskRunner> test_task_runner,
1375 std::vector<EnqueueOrder>* out_result) {
1376 out_result->push_back(EnqueueOrder::FromIntForTesting(value));
1377 test_task_runner->FastForwardBy(TimeDelta::FromMilliseconds(1));
1378 }
1379
TEST_P(SequenceManagerTest,ImmediateAndDelayedTaskInterleaving)1380 TEST_P(SequenceManagerTest, ImmediateAndDelayedTaskInterleaving) {
1381 CreateTaskQueues(1u);
1382
1383 std::vector<EnqueueOrder> run_order;
1384 TimeDelta delay = TimeDelta::FromMilliseconds(10);
1385 for (int i = 10; i < 19; i++) {
1386 runners_[0]->PostDelayedTask(
1387 FROM_HERE,
1388 BindOnce(&ExpensiveTestTask, i, test_task_runner_, &run_order), delay);
1389 }
1390
1391 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(10));
1392
1393 for (int i = 0; i < 9; i++) {
1394 runners_[0]->PostTask(FROM_HERE, BindOnce(&ExpensiveTestTask, i,
1395 test_task_runner_, &run_order));
1396 }
1397
1398 test_task_runner_->FastForwardUntilNoTasksRemain();
1399
1400 // Delayed tasks are not allowed to starve out immediate work which is why
1401 // some of the immediate tasks run out of order.
1402 uint64_t expected_run_order[] = {10u, 11u, 12u, 13u, 0u, 14u, 15u, 16u, 1u,
1403 17u, 18u, 2u, 3u, 4u, 5u, 6u, 7u, 8u};
1404 EXPECT_THAT(run_order, ElementsAreArray(expected_run_order));
1405 }
1406
TEST_P(SequenceManagerTest,DelayedTaskDoesNotSkipAHeadOfNonDelayedTask_SameQueue)1407 TEST_P(SequenceManagerTest,
1408 DelayedTaskDoesNotSkipAHeadOfNonDelayedTask_SameQueue) {
1409 CreateTaskQueues(1u);
1410
1411 std::vector<EnqueueOrder> run_order;
1412 TimeDelta delay = TimeDelta::FromMilliseconds(10);
1413 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
1414 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
1415 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
1416 delay);
1417
1418 test_task_runner_->AdvanceMockTickClock(delay * 2);
1419 RunLoop().RunUntilIdle();
1420
1421 EXPECT_THAT(run_order, ElementsAre(2u, 3u, 1u));
1422 }
1423
TEST_P(SequenceManagerTest,DelayedTaskDoesNotSkipAHeadOfNonDelayedTask_DifferentQueues)1424 TEST_P(SequenceManagerTest,
1425 DelayedTaskDoesNotSkipAHeadOfNonDelayedTask_DifferentQueues) {
1426 CreateTaskQueues(2u);
1427
1428 std::vector<EnqueueOrder> run_order;
1429 TimeDelta delay = TimeDelta::FromMilliseconds(10);
1430 runners_[1]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
1431 runners_[1]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
1432 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
1433 delay);
1434
1435 test_task_runner_->AdvanceMockTickClock(delay * 2);
1436 RunLoop().RunUntilIdle();
1437
1438 EXPECT_THAT(run_order, ElementsAre(2u, 3u, 1u));
1439 }
1440
TEST_P(SequenceManagerTest,DelayedTaskDoesNotSkipAHeadOfShorterDelayedTask)1441 TEST_P(SequenceManagerTest, DelayedTaskDoesNotSkipAHeadOfShorterDelayedTask) {
1442 CreateTaskQueues(2u);
1443
1444 std::vector<EnqueueOrder> run_order;
1445 TimeDelta delay1 = TimeDelta::FromMilliseconds(10);
1446 TimeDelta delay2 = TimeDelta::FromMilliseconds(5);
1447 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
1448 delay1);
1449 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
1450 delay2);
1451
1452 test_task_runner_->AdvanceMockTickClock(delay1 * 2);
1453 RunLoop().RunUntilIdle();
1454
1455 EXPECT_THAT(run_order, ElementsAre(2u, 1u));
1456 }
1457
CheckIsNested(bool * is_nested)1458 void CheckIsNested(bool* is_nested) {
1459 *is_nested = RunLoop::IsNestedOnCurrentThread();
1460 }
1461
PostAndQuitFromNestedRunloop(RunLoop * run_loop,SingleThreadTaskRunner * runner,bool * was_nested)1462 void PostAndQuitFromNestedRunloop(RunLoop* run_loop,
1463 SingleThreadTaskRunner* runner,
1464 bool* was_nested) {
1465 runner->PostTask(FROM_HERE, run_loop->QuitClosure());
1466 runner->PostTask(FROM_HERE, BindOnce(&CheckIsNested, was_nested));
1467 run_loop->Run();
1468 }
1469
TEST_P(SequenceManagerTestWithMessageLoop,QuitWhileNested)1470 TEST_P(SequenceManagerTestWithMessageLoop, QuitWhileNested) {
1471 // This test makes sure we don't continue running a work batch after a nested
1472 // run loop has been exited in the middle of the batch.
1473 CreateTaskQueues(1u);
1474 manager_->SetWorkBatchSize(2);
1475
1476 bool was_nested = true;
1477 RunLoop run_loop(RunLoop::Type::kNestableTasksAllowed);
1478 runners_[0]->PostTask(
1479 FROM_HERE, BindOnce(&PostAndQuitFromNestedRunloop, Unretained(&run_loop),
1480 RetainedRef(runners_[0]), Unretained(&was_nested)));
1481
1482 RunLoop().RunUntilIdle();
1483 EXPECT_FALSE(was_nested);
1484 }
1485
1486 class SequenceNumberCapturingTaskObserver : public MessageLoop::TaskObserver {
1487 public:
1488 // MessageLoop::TaskObserver overrides.
WillProcessTask(const PendingTask & pending_task)1489 void WillProcessTask(const PendingTask& pending_task) override {}
DidProcessTask(const PendingTask & pending_task)1490 void DidProcessTask(const PendingTask& pending_task) override {
1491 sequence_numbers_.push_back(pending_task.sequence_num);
1492 }
1493
sequence_numbers() const1494 const std::vector<int>& sequence_numbers() const { return sequence_numbers_; }
1495
1496 private:
1497 std::vector<int> sequence_numbers_;
1498 };
1499
TEST_P(SequenceManagerTest,SequenceNumSetWhenTaskIsPosted)1500 TEST_P(SequenceManagerTest, SequenceNumSetWhenTaskIsPosted) {
1501 CreateTaskQueues(1u);
1502
1503 SequenceNumberCapturingTaskObserver observer;
1504 manager_->AddTaskObserver(&observer);
1505
1506 // Register four tasks that will run in reverse order.
1507 std::vector<EnqueueOrder> run_order;
1508 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
1509 TimeDelta::FromMilliseconds(30));
1510 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
1511 TimeDelta::FromMilliseconds(20));
1512 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order),
1513 TimeDelta::FromMilliseconds(10));
1514 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order));
1515
1516 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(40));
1517 ASSERT_THAT(run_order, ElementsAre(4u, 3u, 2u, 1u));
1518
1519 // The sequence numbers are a one-based monotonically incrememting counter
1520 // which should be set when the task is posted rather than when it's enqueued
1521 // onto the Incoming queue. This counter starts with 2.
1522 EXPECT_THAT(observer.sequence_numbers(), ElementsAre(5, 4, 3, 2));
1523
1524 manager_->RemoveTaskObserver(&observer);
1525 }
1526
TEST_P(SequenceManagerTest,NewTaskQueues)1527 TEST_P(SequenceManagerTest, NewTaskQueues) {
1528 CreateTaskQueues(1u);
1529
1530 scoped_refptr<TaskQueue> queue1 = CreateTaskQueue();
1531 scoped_refptr<TaskQueue> queue2 = CreateTaskQueue();
1532 scoped_refptr<TaskQueue> queue3 = CreateTaskQueue();
1533
1534 ASSERT_NE(queue1, queue2);
1535 ASSERT_NE(queue1, queue3);
1536 ASSERT_NE(queue2, queue3);
1537
1538 std::vector<EnqueueOrder> run_order;
1539 queue1->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1540 queue2->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
1541 queue3->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
1542 RunLoop().RunUntilIdle();
1543
1544 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u));
1545 }
1546
TEST_P(SequenceManagerTest,ShutdownTaskQueue)1547 TEST_P(SequenceManagerTest, ShutdownTaskQueue) {
1548 CreateTaskQueues(1u);
1549
1550 scoped_refptr<TaskQueue> queue1 = CreateTaskQueue();
1551 scoped_refptr<TaskQueue> queue2 = CreateTaskQueue();
1552 scoped_refptr<TaskQueue> queue3 = CreateTaskQueue();
1553
1554 ASSERT_NE(queue1, queue2);
1555 ASSERT_NE(queue1, queue3);
1556 ASSERT_NE(queue2, queue3);
1557
1558 std::vector<EnqueueOrder> run_order;
1559 queue1->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1560 queue2->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
1561 queue3->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
1562
1563 queue2->ShutdownTaskQueue();
1564 RunLoop().RunUntilIdle();
1565
1566 EXPECT_THAT(run_order, ElementsAre(1u, 3u));
1567 }
1568
TEST_P(SequenceManagerTest,ShutdownTaskQueue_WithDelayedTasks)1569 TEST_P(SequenceManagerTest, ShutdownTaskQueue_WithDelayedTasks) {
1570 CreateTaskQueues(2u);
1571
1572 // Register three delayed tasks
1573 std::vector<EnqueueOrder> run_order;
1574 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
1575 TimeDelta::FromMilliseconds(10));
1576 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
1577 TimeDelta::FromMilliseconds(20));
1578 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order),
1579 TimeDelta::FromMilliseconds(30));
1580
1581 runners_[1]->ShutdownTaskQueue();
1582 RunLoop().RunUntilIdle();
1583
1584 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(40));
1585 ASSERT_THAT(run_order, ElementsAre(1u, 3u));
1586 }
1587
1588 namespace {
ShutdownQueue(scoped_refptr<TaskQueue> queue)1589 void ShutdownQueue(scoped_refptr<TaskQueue> queue) {
1590 queue->ShutdownTaskQueue();
1591 }
1592 } // namespace
1593
TEST_P(SequenceManagerTest,ShutdownTaskQueue_InTasks)1594 TEST_P(SequenceManagerTest, ShutdownTaskQueue_InTasks) {
1595 CreateTaskQueues(3u);
1596
1597 std::vector<EnqueueOrder> run_order;
1598 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1599 runners_[0]->PostTask(FROM_HERE, BindOnce(&ShutdownQueue, runners_[1]));
1600 runners_[0]->PostTask(FROM_HERE, BindOnce(&ShutdownQueue, runners_[2]));
1601 runners_[1]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
1602 runners_[2]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
1603
1604 RunLoop().RunUntilIdle();
1605 ASSERT_THAT(run_order, ElementsAre(1u));
1606 }
1607
1608 namespace {
1609
1610 class MockObserver : public SequenceManager::Observer {
1611 public:
1612 MOCK_METHOD0(OnTriedToExecuteBlockedTask, void());
1613 MOCK_METHOD0(OnBeginNestedRunLoop, void());
1614 MOCK_METHOD0(OnExitNestedRunLoop, void());
1615 };
1616
1617 } // namespace
1618
TEST_P(SequenceManagerTestWithMessageLoop,ShutdownTaskQueueInNestedLoop)1619 TEST_P(SequenceManagerTestWithMessageLoop, ShutdownTaskQueueInNestedLoop) {
1620 CreateTaskQueues(1u);
1621
1622 // We retain a reference to the task queue even when the manager has deleted
1623 // its reference.
1624 scoped_refptr<TaskQueue> task_queue = CreateTaskQueue();
1625
1626 std::vector<bool> log;
1627 std::vector<std::pair<OnceClosure, bool>> tasks_to_post_from_nested_loop;
1628
1629 // Inside a nested run loop, call task_queue->ShutdownTaskQueue, bookended
1630 // by calls to HasOneRefTask to make sure the manager doesn't release its
1631 // reference until the nested run loop exits.
1632 // NB: This first HasOneRefTask is a sanity check.
1633 tasks_to_post_from_nested_loop.push_back(
1634 std::make_pair(BindOnce(&NopTask), true));
1635 tasks_to_post_from_nested_loop.push_back(std::make_pair(
1636 BindOnce(&TaskQueue::ShutdownTaskQueue, Unretained(task_queue.get())),
1637 true));
1638 tasks_to_post_from_nested_loop.push_back(
1639 std::make_pair(BindOnce(&NopTask), true));
1640 runners_[0]->PostTask(
1641 FROM_HERE, BindOnce(&PostFromNestedRunloop, RetainedRef(runners_[0]),
1642 Unretained(&tasks_to_post_from_nested_loop)));
1643 RunLoop().RunUntilIdle();
1644
1645 // Just make sure that we don't crash.
1646 }
1647
TEST_P(SequenceManagerTest,TimeDomainsAreIndependant)1648 TEST_P(SequenceManagerTest, TimeDomainsAreIndependant) {
1649 CreateTaskQueues(2u);
1650
1651 TimeTicks start_time_ticks = manager_->NowTicks();
1652 std::unique_ptr<MockTimeDomain> domain_a =
1653 std::make_unique<MockTimeDomain>(start_time_ticks);
1654 std::unique_ptr<MockTimeDomain> domain_b =
1655 std::make_unique<MockTimeDomain>(start_time_ticks);
1656 manager_->RegisterTimeDomain(domain_a.get());
1657 manager_->RegisterTimeDomain(domain_b.get());
1658 runners_[0]->SetTimeDomain(domain_a.get());
1659 runners_[1]->SetTimeDomain(domain_b.get());
1660
1661 std::vector<EnqueueOrder> run_order;
1662 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
1663 TimeDelta::FromMilliseconds(10));
1664 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
1665 TimeDelta::FromMilliseconds(20));
1666 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order),
1667 TimeDelta::FromMilliseconds(30));
1668
1669 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order),
1670 TimeDelta::FromMilliseconds(10));
1671 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 5, &run_order),
1672 TimeDelta::FromMilliseconds(20));
1673 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 6, &run_order),
1674 TimeDelta::FromMilliseconds(30));
1675
1676 domain_b->SetNowTicks(start_time_ticks + TimeDelta::FromMilliseconds(50));
1677 manager_->MaybeScheduleImmediateWork(FROM_HERE);
1678
1679 RunLoop().RunUntilIdle();
1680 EXPECT_THAT(run_order, ElementsAre(4u, 5u, 6u));
1681
1682 domain_a->SetNowTicks(start_time_ticks + TimeDelta::FromMilliseconds(50));
1683 manager_->MaybeScheduleImmediateWork(FROM_HERE);
1684
1685 RunLoop().RunUntilIdle();
1686 EXPECT_THAT(run_order, ElementsAre(4u, 5u, 6u, 1u, 2u, 3u));
1687
1688 runners_[0]->ShutdownTaskQueue();
1689 runners_[1]->ShutdownTaskQueue();
1690
1691 manager_->UnregisterTimeDomain(domain_a.get());
1692 manager_->UnregisterTimeDomain(domain_b.get());
1693 }
1694
TEST_P(SequenceManagerTest,TimeDomainMigration)1695 TEST_P(SequenceManagerTest, TimeDomainMigration) {
1696 CreateTaskQueues(1u);
1697
1698 TimeTicks start_time_ticks = manager_->NowTicks();
1699 std::unique_ptr<MockTimeDomain> domain_a =
1700 std::make_unique<MockTimeDomain>(start_time_ticks);
1701 manager_->RegisterTimeDomain(domain_a.get());
1702 runners_[0]->SetTimeDomain(domain_a.get());
1703
1704 std::vector<EnqueueOrder> run_order;
1705 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
1706 TimeDelta::FromMilliseconds(10));
1707 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
1708 TimeDelta::FromMilliseconds(20));
1709 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order),
1710 TimeDelta::FromMilliseconds(30));
1711 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order),
1712 TimeDelta::FromMilliseconds(40));
1713
1714 domain_a->SetNowTicks(start_time_ticks + TimeDelta::FromMilliseconds(20));
1715 manager_->MaybeScheduleImmediateWork(FROM_HERE);
1716 RunLoop().RunUntilIdle();
1717 EXPECT_THAT(run_order, ElementsAre(1u, 2u));
1718
1719 std::unique_ptr<MockTimeDomain> domain_b =
1720 std::make_unique<MockTimeDomain>(start_time_ticks);
1721 manager_->RegisterTimeDomain(domain_b.get());
1722 runners_[0]->SetTimeDomain(domain_b.get());
1723
1724 domain_b->SetNowTicks(start_time_ticks + TimeDelta::FromMilliseconds(50));
1725 manager_->MaybeScheduleImmediateWork(FROM_HERE);
1726
1727 RunLoop().RunUntilIdle();
1728 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u, 4u));
1729
1730 runners_[0]->ShutdownTaskQueue();
1731
1732 manager_->UnregisterTimeDomain(domain_a.get());
1733 manager_->UnregisterTimeDomain(domain_b.get());
1734 }
1735
TEST_P(SequenceManagerTest,TimeDomainMigrationWithIncomingImmediateTasks)1736 TEST_P(SequenceManagerTest, TimeDomainMigrationWithIncomingImmediateTasks) {
1737 CreateTaskQueues(1u);
1738
1739 TimeTicks start_time_ticks = manager_->NowTicks();
1740 std::unique_ptr<MockTimeDomain> domain_a =
1741 std::make_unique<MockTimeDomain>(start_time_ticks);
1742 std::unique_ptr<MockTimeDomain> domain_b =
1743 std::make_unique<MockTimeDomain>(start_time_ticks);
1744 manager_->RegisterTimeDomain(domain_a.get());
1745 manager_->RegisterTimeDomain(domain_b.get());
1746
1747 runners_[0]->SetTimeDomain(domain_a.get());
1748 std::vector<EnqueueOrder> run_order;
1749 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
1750 runners_[0]->SetTimeDomain(domain_b.get());
1751
1752 RunLoop().RunUntilIdle();
1753 EXPECT_THAT(run_order, ElementsAre(1u));
1754
1755 runners_[0]->ShutdownTaskQueue();
1756
1757 manager_->UnregisterTimeDomain(domain_a.get());
1758 manager_->UnregisterTimeDomain(domain_b.get());
1759 }
1760
TEST_P(SequenceManagerTest,PostDelayedTasksReverseOrderAlternatingTimeDomains)1761 TEST_P(SequenceManagerTest,
1762 PostDelayedTasksReverseOrderAlternatingTimeDomains) {
1763 CreateTaskQueues(1u);
1764
1765 std::vector<EnqueueOrder> run_order;
1766
1767 std::unique_ptr<internal::RealTimeDomain> domain_a =
1768 std::make_unique<internal::RealTimeDomain>();
1769 std::unique_ptr<internal::RealTimeDomain> domain_b =
1770 std::make_unique<internal::RealTimeDomain>();
1771 manager_->RegisterTimeDomain(domain_a.get());
1772 manager_->RegisterTimeDomain(domain_b.get());
1773
1774 runners_[0]->SetTimeDomain(domain_a.get());
1775 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order),
1776 TimeDelta::FromMilliseconds(40));
1777
1778 runners_[0]->SetTimeDomain(domain_b.get());
1779 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order),
1780 TimeDelta::FromMilliseconds(30));
1781
1782 runners_[0]->SetTimeDomain(domain_a.get());
1783 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order),
1784 TimeDelta::FromMilliseconds(20));
1785
1786 runners_[0]->SetTimeDomain(domain_b.get());
1787 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order),
1788 TimeDelta::FromMilliseconds(10));
1789
1790 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(40));
1791 EXPECT_THAT(run_order, ElementsAre(4u, 3u, 2u, 1u));
1792
1793 runners_[0]->ShutdownTaskQueue();
1794
1795 manager_->UnregisterTimeDomain(domain_a.get());
1796 manager_->UnregisterTimeDomain(domain_b.get());
1797 }
1798
1799 namespace {
1800
1801 class MockTaskQueueObserver : public TaskQueue::Observer {
1802 public:
1803 ~MockTaskQueueObserver() override = default;
1804
1805 MOCK_METHOD2(OnQueueNextWakeUpChanged, void(TaskQueue*, TimeTicks));
1806 };
1807
1808 } // namespace
1809
TEST_P(SequenceManagerTest,TaskQueueObserver_ImmediateTask)1810 TEST_P(SequenceManagerTest, TaskQueueObserver_ImmediateTask) {
1811 CreateTaskQueues(1u);
1812
1813 MockTaskQueueObserver observer;
1814 runners_[0]->SetObserver(&observer);
1815
1816 // We should get a notification when a task is posted on an empty queue.
1817 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), _));
1818 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
1819 Mock::VerifyAndClearExpectations(&observer);
1820
1821 // But not subsequently.
1822 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0);
1823 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
1824 Mock::VerifyAndClearExpectations(&observer);
1825
1826 // Unless the immediate work queue is emptied.
1827 runners_[0]->GetTaskQueueImpl()->ReloadImmediateWorkQueueIfEmpty();
1828 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), _));
1829 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
1830
1831 // Tidy up.
1832 runners_[0]->ShutdownTaskQueue();
1833 }
1834
TEST_P(SequenceManagerTest,TaskQueueObserver_DelayedTask)1835 TEST_P(SequenceManagerTest, TaskQueueObserver_DelayedTask) {
1836 CreateTaskQueues(1u);
1837
1838 TimeTicks start_time = manager_->NowTicks();
1839 TimeDelta delay10s(TimeDelta::FromSeconds(10));
1840 TimeDelta delay100s(TimeDelta::FromSeconds(100));
1841 TimeDelta delay1s(TimeDelta::FromSeconds(1));
1842
1843 MockTaskQueueObserver observer;
1844 runners_[0]->SetObserver(&observer);
1845
1846 // We should get a notification when a delayed task is posted on an empty
1847 // queue.
1848 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(),
1849 start_time + delay10s));
1850 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay10s);
1851 Mock::VerifyAndClearExpectations(&observer);
1852
1853 // We should not get a notification for a longer delay.
1854 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0);
1855 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay100s);
1856 Mock::VerifyAndClearExpectations(&observer);
1857
1858 // We should get a notification for a shorter delay.
1859 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(),
1860 start_time + delay1s));
1861 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay1s);
1862 Mock::VerifyAndClearExpectations(&observer);
1863
1864 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
1865 runners_[0]->CreateQueueEnabledVoter();
1866 voter->SetQueueEnabled(false);
1867 Mock::VerifyAndClearExpectations(&observer);
1868
1869 // When a queue has been enabled, we may get a notification if the
1870 // TimeDomain's next scheduled wake-up has changed.
1871 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(),
1872 start_time + delay1s));
1873 voter->SetQueueEnabled(true);
1874 Mock::VerifyAndClearExpectations(&observer);
1875
1876 // Tidy up.
1877 runners_[0]->ShutdownTaskQueue();
1878 }
1879
TEST_P(SequenceManagerTest,TaskQueueObserver_DelayedTaskMultipleQueues)1880 TEST_P(SequenceManagerTest, TaskQueueObserver_DelayedTaskMultipleQueues) {
1881 CreateTaskQueues(2u);
1882
1883 MockTaskQueueObserver observer;
1884 runners_[0]->SetObserver(&observer);
1885 runners_[1]->SetObserver(&observer);
1886
1887 TimeTicks start_time = manager_->NowTicks();
1888 TimeDelta delay1s(TimeDelta::FromSeconds(1));
1889 TimeDelta delay10s(TimeDelta::FromSeconds(10));
1890
1891 EXPECT_CALL(observer,
1892 OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay1s))
1893 .Times(1);
1894 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[1].get(),
1895 start_time + delay10s))
1896 .Times(1);
1897 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay1s);
1898 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay10s);
1899 testing::Mock::VerifyAndClearExpectations(&observer);
1900
1901 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter0 =
1902 runners_[0]->CreateQueueEnabledVoter();
1903 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter1 =
1904 runners_[1]->CreateQueueEnabledVoter();
1905
1906 // Disabling a queue should not trigger a notification.
1907 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0);
1908 voter0->SetQueueEnabled(false);
1909 Mock::VerifyAndClearExpectations(&observer);
1910
1911 // Re-enabling it should should also trigger a notification.
1912 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(),
1913 start_time + delay1s));
1914 voter0->SetQueueEnabled(true);
1915 Mock::VerifyAndClearExpectations(&observer);
1916
1917 // Disabling a queue should not trigger a notification.
1918 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0);
1919 voter1->SetQueueEnabled(false);
1920 Mock::VerifyAndClearExpectations(&observer);
1921
1922 // Re-enabling it should should trigger a notification.
1923 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[1].get(),
1924 start_time + delay10s));
1925 voter1->SetQueueEnabled(true);
1926 Mock::VerifyAndClearExpectations(&observer);
1927
1928 // Tidy up.
1929 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(AnyNumber());
1930 runners_[0]->ShutdownTaskQueue();
1931 runners_[1]->ShutdownTaskQueue();
1932 }
1933
TEST_P(SequenceManagerTest,TaskQueueObserver_DelayedWorkWhichCanRunNow)1934 TEST_P(SequenceManagerTest, TaskQueueObserver_DelayedWorkWhichCanRunNow) {
1935 // This test checks that when delayed work becomes available
1936 // the notification still fires. This usually happens when time advances
1937 // and task becomes available in the middle of the scheduling code.
1938 // For this test we rely on the fact that notification dispatching code
1939 // is the same in all conditions and just change a time domain to
1940 // trigger notification.
1941
1942 CreateTaskQueues(1u);
1943
1944 TimeDelta delay1s(TimeDelta::FromSeconds(1));
1945 TimeDelta delay10s(TimeDelta::FromSeconds(10));
1946
1947 MockTaskQueueObserver observer;
1948 runners_[0]->SetObserver(&observer);
1949
1950 // We should get a notification when a delayed task is posted on an empty
1951 // queue.
1952 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _));
1953 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay1s);
1954 Mock::VerifyAndClearExpectations(&observer);
1955
1956 std::unique_ptr<TimeDomain> mock_time_domain =
1957 std::make_unique<internal::RealTimeDomain>();
1958 manager_->RegisterTimeDomain(mock_time_domain.get());
1959
1960 test_task_runner_->AdvanceMockTickClock(delay10s);
1961
1962 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _));
1963 runners_[0]->SetTimeDomain(mock_time_domain.get());
1964 Mock::VerifyAndClearExpectations(&observer);
1965
1966 // Tidy up.
1967 runners_[0]->ShutdownTaskQueue();
1968 }
1969
1970 class CancelableTask {
1971 public:
CancelableTask(const TickClock * clock)1972 explicit CancelableTask(const TickClock* clock)
1973 : clock_(clock), weak_factory_(this) {}
1974
RecordTimeTask(std::vector<TimeTicks> * run_times)1975 void RecordTimeTask(std::vector<TimeTicks>* run_times) {
1976 run_times->push_back(clock_->NowTicks());
1977 }
1978
1979 const TickClock* clock_;
1980 WeakPtrFactory<CancelableTask> weak_factory_;
1981 };
1982
TEST_P(SequenceManagerTest,TaskQueueObserver_SweepCanceledDelayedTasks)1983 TEST_P(SequenceManagerTest, TaskQueueObserver_SweepCanceledDelayedTasks) {
1984 CreateTaskQueues(1u);
1985
1986 MockTaskQueueObserver observer;
1987 runners_[0]->SetObserver(&observer);
1988
1989 TimeTicks start_time = manager_->NowTicks();
1990 TimeDelta delay1(TimeDelta::FromSeconds(5));
1991 TimeDelta delay2(TimeDelta::FromSeconds(10));
1992
1993 EXPECT_CALL(observer,
1994 OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay1))
1995 .Times(1);
1996
1997 CancelableTask task1(GetTickClock());
1998 CancelableTask task2(GetTickClock());
1999 std::vector<TimeTicks> run_times;
2000 runners_[0]->PostDelayedTask(
2001 FROM_HERE,
2002 BindOnce(&CancelableTask::RecordTimeTask,
2003 task1.weak_factory_.GetWeakPtr(), &run_times),
2004 delay1);
2005 runners_[0]->PostDelayedTask(
2006 FROM_HERE,
2007 BindOnce(&CancelableTask::RecordTimeTask,
2008 task2.weak_factory_.GetWeakPtr(), &run_times),
2009 delay2);
2010
2011 task1.weak_factory_.InvalidateWeakPtrs();
2012
2013 // Sweeping away canceled delayed tasks should trigger a notification.
2014 EXPECT_CALL(observer,
2015 OnQueueNextWakeUpChanged(runners_[0].get(), start_time + delay2))
2016 .Times(1);
2017 manager_->SweepCanceledDelayedTasks();
2018 }
2019
2020 namespace {
ChromiumRunloopInspectionTask(scoped_refptr<TestMockTimeTaskRunner> test_task_runner)2021 void ChromiumRunloopInspectionTask(
2022 scoped_refptr<TestMockTimeTaskRunner> test_task_runner) {
2023 // We don't expect more than 1 pending task at any time.
2024 EXPECT_GE(1u, test_task_runner->GetPendingTaskCount());
2025 }
2026 } // namespace
2027
TEST_P(SequenceManagerTest,NumberOfPendingTasksOnChromiumRunLoop)2028 TEST_P(SequenceManagerTest, NumberOfPendingTasksOnChromiumRunLoop) {
2029 CreateTaskQueues(1u);
2030
2031 // NOTE because tasks posted to the chromiumrun loop are not cancellable, we
2032 // will end up with a lot more tasks posted if the delayed tasks were posted
2033 // in the reverse order.
2034 // TODO(alexclarke): Consider talking to the message pump directly.
2035 for (int i = 1; i < 100; i++) {
2036 runners_[0]->PostDelayedTask(
2037 FROM_HERE, BindOnce(&ChromiumRunloopInspectionTask, test_task_runner_),
2038 TimeDelta::FromMilliseconds(i));
2039 }
2040 test_task_runner_->FastForwardUntilNoTasksRemain();
2041 }
2042
2043 namespace {
2044
2045 class QuadraticTask {
2046 public:
QuadraticTask(scoped_refptr<TaskQueue> task_queue,TimeDelta delay,scoped_refptr<TestMockTimeTaskRunner> test_task_runner)2047 QuadraticTask(scoped_refptr<TaskQueue> task_queue,
2048 TimeDelta delay,
2049 scoped_refptr<TestMockTimeTaskRunner> test_task_runner)
2050 : count_(0),
2051 task_queue_(task_queue),
2052 delay_(delay),
2053 test_task_runner_(test_task_runner) {}
2054
SetShouldExit(RepeatingCallback<bool ()> should_exit)2055 void SetShouldExit(RepeatingCallback<bool()> should_exit) {
2056 should_exit_ = should_exit;
2057 }
2058
Run()2059 void Run() {
2060 if (should_exit_.Run())
2061 return;
2062 count_++;
2063 task_queue_->PostDelayedTask(
2064 FROM_HERE, BindOnce(&QuadraticTask::Run, Unretained(this)), delay_);
2065 task_queue_->PostDelayedTask(
2066 FROM_HERE, BindOnce(&QuadraticTask::Run, Unretained(this)), delay_);
2067 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(5));
2068 }
2069
Count() const2070 int Count() const { return count_; }
2071
2072 private:
2073 int count_;
2074 scoped_refptr<TaskQueue> task_queue_;
2075 TimeDelta delay_;
2076 RepeatingCallback<bool()> should_exit_;
2077 scoped_refptr<TestMockTimeTaskRunner> test_task_runner_;
2078 };
2079
2080 class LinearTask {
2081 public:
LinearTask(scoped_refptr<TaskQueue> task_queue,TimeDelta delay,scoped_refptr<TestMockTimeTaskRunner> test_task_runner)2082 LinearTask(scoped_refptr<TaskQueue> task_queue,
2083 TimeDelta delay,
2084 scoped_refptr<TestMockTimeTaskRunner> test_task_runner)
2085 : count_(0),
2086 task_queue_(task_queue),
2087 delay_(delay),
2088 test_task_runner_(test_task_runner) {}
2089
SetShouldExit(RepeatingCallback<bool ()> should_exit)2090 void SetShouldExit(RepeatingCallback<bool()> should_exit) {
2091 should_exit_ = should_exit;
2092 }
2093
Run()2094 void Run() {
2095 if (should_exit_.Run())
2096 return;
2097 count_++;
2098 task_queue_->PostDelayedTask(
2099 FROM_HERE, BindOnce(&LinearTask::Run, Unretained(this)), delay_);
2100 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(5));
2101 }
2102
Count() const2103 int Count() const { return count_; }
2104
2105 private:
2106 int count_;
2107 scoped_refptr<TaskQueue> task_queue_;
2108 TimeDelta delay_;
2109 RepeatingCallback<bool()> should_exit_;
2110 scoped_refptr<TestMockTimeTaskRunner> test_task_runner_;
2111 };
2112
ShouldExit(QuadraticTask * quadratic_task,LinearTask * linear_task)2113 bool ShouldExit(QuadraticTask* quadratic_task, LinearTask* linear_task) {
2114 return quadratic_task->Count() == 1000 || linear_task->Count() == 1000;
2115 }
2116
2117 } // namespace
2118
TEST_P(SequenceManagerTest,DelayedTasksDontBadlyStarveNonDelayedWork_SameQueue)2119 TEST_P(SequenceManagerTest,
2120 DelayedTasksDontBadlyStarveNonDelayedWork_SameQueue) {
2121 CreateTaskQueues(1u);
2122
2123 QuadraticTask quadratic_delayed_task(
2124 runners_[0], TimeDelta::FromMilliseconds(10), test_task_runner_);
2125 LinearTask linear_immediate_task(runners_[0], TimeDelta(), test_task_runner_);
2126 RepeatingCallback<bool()> should_exit = BindRepeating(
2127 ShouldExit, &quadratic_delayed_task, &linear_immediate_task);
2128 quadratic_delayed_task.SetShouldExit(should_exit);
2129 linear_immediate_task.SetShouldExit(should_exit);
2130
2131 quadratic_delayed_task.Run();
2132 linear_immediate_task.Run();
2133
2134 test_task_runner_->FastForwardUntilNoTasksRemain();
2135
2136 double ratio = static_cast<double>(linear_immediate_task.Count()) /
2137 static_cast<double>(quadratic_delayed_task.Count());
2138
2139 EXPECT_GT(ratio, 0.333);
2140 EXPECT_LT(ratio, 1.1);
2141 }
2142
TEST_P(SequenceManagerTest,ImmediateWorkCanStarveDelayedTasks_SameQueue)2143 TEST_P(SequenceManagerTest, ImmediateWorkCanStarveDelayedTasks_SameQueue) {
2144 CreateTaskQueues(1u);
2145
2146 QuadraticTask quadratic_immediate_task(runners_[0], TimeDelta(),
2147 test_task_runner_);
2148 LinearTask linear_delayed_task(runners_[0], TimeDelta::FromMilliseconds(10),
2149 test_task_runner_);
2150 RepeatingCallback<bool()> should_exit = BindRepeating(
2151 &ShouldExit, &quadratic_immediate_task, &linear_delayed_task);
2152
2153 quadratic_immediate_task.SetShouldExit(should_exit);
2154 linear_delayed_task.SetShouldExit(should_exit);
2155
2156 quadratic_immediate_task.Run();
2157 linear_delayed_task.Run();
2158
2159 test_task_runner_->FastForwardUntilNoTasksRemain();
2160
2161 double ratio = static_cast<double>(linear_delayed_task.Count()) /
2162 static_cast<double>(quadratic_immediate_task.Count());
2163
2164 // This is by design, we want to enforce a strict ordering in task execution
2165 // where by delayed tasks can not skip ahead of non-delayed work.
2166 EXPECT_GT(ratio, 0.0);
2167 EXPECT_LT(ratio, 0.1);
2168 }
2169
TEST_P(SequenceManagerTest,DelayedTasksDontBadlyStarveNonDelayedWork_DifferentQueue)2170 TEST_P(SequenceManagerTest,
2171 DelayedTasksDontBadlyStarveNonDelayedWork_DifferentQueue) {
2172 CreateTaskQueues(2u);
2173
2174 QuadraticTask quadratic_delayed_task(
2175 runners_[0], TimeDelta::FromMilliseconds(10), test_task_runner_);
2176 LinearTask linear_immediate_task(runners_[1], TimeDelta(), test_task_runner_);
2177 RepeatingCallback<bool()> should_exit = BindRepeating(
2178 ShouldExit, &quadratic_delayed_task, &linear_immediate_task);
2179 quadratic_delayed_task.SetShouldExit(should_exit);
2180 linear_immediate_task.SetShouldExit(should_exit);
2181
2182 quadratic_delayed_task.Run();
2183 linear_immediate_task.Run();
2184
2185 test_task_runner_->FastForwardUntilNoTasksRemain();
2186
2187 double ratio = static_cast<double>(linear_immediate_task.Count()) /
2188 static_cast<double>(quadratic_delayed_task.Count());
2189
2190 EXPECT_GT(ratio, 0.333);
2191 EXPECT_LT(ratio, 1.1);
2192 }
2193
TEST_P(SequenceManagerTest,ImmediateWorkCanStarveDelayedTasks_DifferentQueue)2194 TEST_P(SequenceManagerTest, ImmediateWorkCanStarveDelayedTasks_DifferentQueue) {
2195 CreateTaskQueues(2u);
2196
2197 QuadraticTask quadratic_immediate_task(runners_[0], TimeDelta(),
2198 test_task_runner_);
2199 LinearTask linear_delayed_task(runners_[1], TimeDelta::FromMilliseconds(10),
2200 test_task_runner_);
2201 RepeatingCallback<bool()> should_exit = BindRepeating(
2202 &ShouldExit, &quadratic_immediate_task, &linear_delayed_task);
2203
2204 quadratic_immediate_task.SetShouldExit(should_exit);
2205 linear_delayed_task.SetShouldExit(should_exit);
2206
2207 quadratic_immediate_task.Run();
2208 linear_delayed_task.Run();
2209
2210 test_task_runner_->FastForwardUntilNoTasksRemain();
2211
2212 double ratio = static_cast<double>(linear_delayed_task.Count()) /
2213 static_cast<double>(quadratic_immediate_task.Count());
2214
2215 // This is by design, we want to enforce a strict ordering in task execution
2216 // where by delayed tasks can not skip ahead of non-delayed work.
2217 EXPECT_GT(ratio, 0.0);
2218 EXPECT_LT(ratio, 0.1);
2219 }
2220
TEST_P(SequenceManagerTest,CurrentlyExecutingTaskQueue_NoTaskRunning)2221 TEST_P(SequenceManagerTest, CurrentlyExecutingTaskQueue_NoTaskRunning) {
2222 CreateTaskQueues(1u);
2223
2224 EXPECT_EQ(nullptr, manager_->currently_executing_task_queue());
2225 }
2226
2227 namespace {
CurrentlyExecutingTaskQueueTestTask(SequenceManagerImpl * sequence_manager,std::vector<internal::TaskQueueImpl * > * task_sources)2228 void CurrentlyExecutingTaskQueueTestTask(
2229 SequenceManagerImpl* sequence_manager,
2230 std::vector<internal::TaskQueueImpl*>* task_sources) {
2231 task_sources->push_back(sequence_manager->currently_executing_task_queue());
2232 }
2233 } // namespace
2234
TEST_P(SequenceManagerTest,CurrentlyExecutingTaskQueue_TaskRunning)2235 TEST_P(SequenceManagerTest, CurrentlyExecutingTaskQueue_TaskRunning) {
2236 CreateTaskQueues(2u);
2237
2238 TestTaskQueue* queue0 = runners_[0].get();
2239 TestTaskQueue* queue1 = runners_[1].get();
2240
2241 std::vector<internal::TaskQueueImpl*> task_sources;
2242 queue0->PostTask(FROM_HERE, BindOnce(&CurrentlyExecutingTaskQueueTestTask,
2243 manager_.get(), &task_sources));
2244 queue1->PostTask(FROM_HERE, BindOnce(&CurrentlyExecutingTaskQueueTestTask,
2245 manager_.get(), &task_sources));
2246 RunLoop().RunUntilIdle();
2247
2248 EXPECT_THAT(task_sources, ElementsAre(queue0->GetTaskQueueImpl(),
2249 queue1->GetTaskQueueImpl()));
2250 EXPECT_EQ(nullptr, manager_->currently_executing_task_queue());
2251 }
2252
2253 namespace {
RunloopCurrentlyExecutingTaskQueueTestTask(SequenceManagerImpl * sequence_manager,std::vector<internal::TaskQueueImpl * > * task_sources,std::vector<std::pair<OnceClosure,TestTaskQueue * >> * tasks)2254 void RunloopCurrentlyExecutingTaskQueueTestTask(
2255 SequenceManagerImpl* sequence_manager,
2256 std::vector<internal::TaskQueueImpl*>* task_sources,
2257 std::vector<std::pair<OnceClosure, TestTaskQueue*>>* tasks) {
2258 task_sources->push_back(sequence_manager->currently_executing_task_queue());
2259
2260 for (std::pair<OnceClosure, TestTaskQueue*>& pair : *tasks) {
2261 pair.second->PostTask(FROM_HERE, std::move(pair.first));
2262 }
2263
2264 RunLoop(RunLoop::Type::kNestableTasksAllowed).RunUntilIdle();
2265 task_sources->push_back(sequence_manager->currently_executing_task_queue());
2266 }
2267 } // namespace
2268
TEST_P(SequenceManagerTestWithMessageLoop,CurrentlyExecutingTaskQueue_NestedLoop)2269 TEST_P(SequenceManagerTestWithMessageLoop,
2270 CurrentlyExecutingTaskQueue_NestedLoop) {
2271 CreateTaskQueues(3u);
2272
2273 TestTaskQueue* queue0 = runners_[0].get();
2274 TestTaskQueue* queue1 = runners_[1].get();
2275 TestTaskQueue* queue2 = runners_[2].get();
2276
2277 std::vector<internal::TaskQueueImpl*> task_sources;
2278 std::vector<std::pair<OnceClosure, TestTaskQueue*>>
2279 tasks_to_post_from_nested_loop;
2280 tasks_to_post_from_nested_loop.push_back(
2281 std::make_pair(BindOnce(&CurrentlyExecutingTaskQueueTestTask,
2282 manager_.get(), &task_sources),
2283 queue1));
2284 tasks_to_post_from_nested_loop.push_back(
2285 std::make_pair(BindOnce(&CurrentlyExecutingTaskQueueTestTask,
2286 manager_.get(), &task_sources),
2287 queue2));
2288
2289 queue0->PostTask(
2290 FROM_HERE,
2291 BindOnce(&RunloopCurrentlyExecutingTaskQueueTestTask, manager_.get(),
2292 &task_sources, &tasks_to_post_from_nested_loop));
2293
2294 RunLoop().RunUntilIdle();
2295 EXPECT_THAT(
2296 task_sources,
2297 ElementsAre(queue0->GetTaskQueueImpl(), queue1->GetTaskQueueImpl(),
2298 queue2->GetTaskQueueImpl(), queue0->GetTaskQueueImpl()));
2299 EXPECT_EQ(nullptr, manager_->currently_executing_task_queue());
2300 }
2301
TEST_P(SequenceManagerTestWithMessageLoop,BlameContextAttribution)2302 TEST_P(SequenceManagerTestWithMessageLoop, BlameContextAttribution) {
2303 using trace_analyzer::Query;
2304
2305 CreateTaskQueues(1u);
2306 TestTaskQueue* queue = runners_[0].get();
2307
2308 trace_analyzer::Start("*");
2309 {
2310 trace_event::BlameContext blame_context("cat", "name", "type", "scope", 0,
2311 nullptr);
2312 blame_context.Initialize();
2313 queue->SetBlameContext(&blame_context);
2314 queue->PostTask(FROM_HERE, BindOnce(&NopTask));
2315 RunLoop().RunUntilIdle();
2316 }
2317 auto analyzer = trace_analyzer::Stop();
2318
2319 trace_analyzer::TraceEventVector events;
2320 Query q = Query::EventPhaseIs(TRACE_EVENT_PHASE_ENTER_CONTEXT) ||
2321 Query::EventPhaseIs(TRACE_EVENT_PHASE_LEAVE_CONTEXT);
2322 analyzer->FindEvents(q, &events);
2323
2324 EXPECT_EQ(2u, events.size());
2325 }
2326
TEST_P(SequenceManagerTest,NoWakeUpsForCanceledDelayedTasks)2327 TEST_P(SequenceManagerTest, NoWakeUpsForCanceledDelayedTasks) {
2328 CreateTaskQueues(1u);
2329
2330 TimeTicks start_time = manager_->NowTicks();
2331
2332 CancelableTask task1(GetTickClock());
2333 CancelableTask task2(GetTickClock());
2334 CancelableTask task3(GetTickClock());
2335 CancelableTask task4(GetTickClock());
2336 TimeDelta delay1(TimeDelta::FromSeconds(5));
2337 TimeDelta delay2(TimeDelta::FromSeconds(10));
2338 TimeDelta delay3(TimeDelta::FromSeconds(15));
2339 TimeDelta delay4(TimeDelta::FromSeconds(30));
2340 std::vector<TimeTicks> run_times;
2341 runners_[0]->PostDelayedTask(
2342 FROM_HERE,
2343 BindOnce(&CancelableTask::RecordTimeTask,
2344 task1.weak_factory_.GetWeakPtr(), &run_times),
2345 delay1);
2346 runners_[0]->PostDelayedTask(
2347 FROM_HERE,
2348 BindOnce(&CancelableTask::RecordTimeTask,
2349 task2.weak_factory_.GetWeakPtr(), &run_times),
2350 delay2);
2351 runners_[0]->PostDelayedTask(
2352 FROM_HERE,
2353 BindOnce(&CancelableTask::RecordTimeTask,
2354 task3.weak_factory_.GetWeakPtr(), &run_times),
2355 delay3);
2356 runners_[0]->PostDelayedTask(
2357 FROM_HERE,
2358 BindOnce(&CancelableTask::RecordTimeTask,
2359 task4.weak_factory_.GetWeakPtr(), &run_times),
2360 delay4);
2361
2362 task2.weak_factory_.InvalidateWeakPtrs();
2363 task3.weak_factory_.InvalidateWeakPtrs();
2364
2365 std::set<TimeTicks> wake_up_times;
2366
2367 RunUntilManagerIsIdle(BindRepeating(
2368 [](std::set<TimeTicks>* wake_up_times, const TickClock* clock) {
2369 wake_up_times->insert(clock->NowTicks());
2370 },
2371 &wake_up_times, GetTickClock()));
2372
2373 EXPECT_THAT(wake_up_times,
2374 ElementsAre(start_time + delay1, start_time + delay4));
2375 EXPECT_THAT(run_times, ElementsAre(start_time + delay1, start_time + delay4));
2376 }
2377
TEST_P(SequenceManagerTest,NoWakeUpsForCanceledDelayedTasksReversePostOrder)2378 TEST_P(SequenceManagerTest, NoWakeUpsForCanceledDelayedTasksReversePostOrder) {
2379 CreateTaskQueues(1u);
2380
2381 TimeTicks start_time = manager_->NowTicks();
2382
2383 CancelableTask task1(GetTickClock());
2384 CancelableTask task2(GetTickClock());
2385 CancelableTask task3(GetTickClock());
2386 CancelableTask task4(GetTickClock());
2387 TimeDelta delay1(TimeDelta::FromSeconds(5));
2388 TimeDelta delay2(TimeDelta::FromSeconds(10));
2389 TimeDelta delay3(TimeDelta::FromSeconds(15));
2390 TimeDelta delay4(TimeDelta::FromSeconds(30));
2391 std::vector<TimeTicks> run_times;
2392 runners_[0]->PostDelayedTask(
2393 FROM_HERE,
2394 BindOnce(&CancelableTask::RecordTimeTask,
2395 task4.weak_factory_.GetWeakPtr(), &run_times),
2396 delay4);
2397 runners_[0]->PostDelayedTask(
2398 FROM_HERE,
2399 BindOnce(&CancelableTask::RecordTimeTask,
2400 task3.weak_factory_.GetWeakPtr(), &run_times),
2401 delay3);
2402 runners_[0]->PostDelayedTask(
2403 FROM_HERE,
2404 BindOnce(&CancelableTask::RecordTimeTask,
2405 task2.weak_factory_.GetWeakPtr(), &run_times),
2406 delay2);
2407 runners_[0]->PostDelayedTask(
2408 FROM_HERE,
2409 BindOnce(&CancelableTask::RecordTimeTask,
2410 task1.weak_factory_.GetWeakPtr(), &run_times),
2411 delay1);
2412
2413 task2.weak_factory_.InvalidateWeakPtrs();
2414 task3.weak_factory_.InvalidateWeakPtrs();
2415
2416 std::set<TimeTicks> wake_up_times;
2417
2418 RunUntilManagerIsIdle(BindRepeating(
2419 [](std::set<TimeTicks>* wake_up_times, const TickClock* clock) {
2420 wake_up_times->insert(clock->NowTicks());
2421 },
2422 &wake_up_times, GetTickClock()));
2423
2424 EXPECT_THAT(wake_up_times,
2425 ElementsAre(start_time + delay1, start_time + delay4));
2426 EXPECT_THAT(run_times, ElementsAre(start_time + delay1, start_time + delay4));
2427 }
2428
TEST_P(SequenceManagerTest,TimeDomainWakeUpOnlyCancelledIfAllUsesCancelled)2429 TEST_P(SequenceManagerTest, TimeDomainWakeUpOnlyCancelledIfAllUsesCancelled) {
2430 CreateTaskQueues(1u);
2431
2432 TimeTicks start_time = manager_->NowTicks();
2433
2434 CancelableTask task1(GetTickClock());
2435 CancelableTask task2(GetTickClock());
2436 CancelableTask task3(GetTickClock());
2437 CancelableTask task4(GetTickClock());
2438 TimeDelta delay1(TimeDelta::FromSeconds(5));
2439 TimeDelta delay2(TimeDelta::FromSeconds(10));
2440 TimeDelta delay3(TimeDelta::FromSeconds(15));
2441 TimeDelta delay4(TimeDelta::FromSeconds(30));
2442 std::vector<TimeTicks> run_times;
2443 runners_[0]->PostDelayedTask(
2444 FROM_HERE,
2445 BindOnce(&CancelableTask::RecordTimeTask,
2446 task1.weak_factory_.GetWeakPtr(), &run_times),
2447 delay1);
2448 runners_[0]->PostDelayedTask(
2449 FROM_HERE,
2450 BindOnce(&CancelableTask::RecordTimeTask,
2451 task2.weak_factory_.GetWeakPtr(), &run_times),
2452 delay2);
2453 runners_[0]->PostDelayedTask(
2454 FROM_HERE,
2455 BindOnce(&CancelableTask::RecordTimeTask,
2456 task3.weak_factory_.GetWeakPtr(), &run_times),
2457 delay3);
2458 runners_[0]->PostDelayedTask(
2459 FROM_HERE,
2460 BindOnce(&CancelableTask::RecordTimeTask,
2461 task4.weak_factory_.GetWeakPtr(), &run_times),
2462 delay4);
2463
2464 // Post a non-canceled task with |delay3|. So we should still get a wake-up at
2465 // |delay3| even though we cancel |task3|.
2466 runners_[0]->PostDelayedTask(
2467 FROM_HERE,
2468 BindOnce(&CancelableTask::RecordTimeTask, Unretained(&task3), &run_times),
2469 delay3);
2470
2471 task2.weak_factory_.InvalidateWeakPtrs();
2472 task3.weak_factory_.InvalidateWeakPtrs();
2473 task1.weak_factory_.InvalidateWeakPtrs();
2474
2475 std::set<TimeTicks> wake_up_times;
2476
2477 RunUntilManagerIsIdle(BindRepeating(
2478 [](std::set<TimeTicks>* wake_up_times, const TickClock* clock) {
2479 wake_up_times->insert(clock->NowTicks());
2480 },
2481 &wake_up_times, GetTickClock()));
2482
2483 EXPECT_THAT(wake_up_times,
2484 ElementsAre(start_time + delay1, start_time + delay3,
2485 start_time + delay4));
2486
2487 EXPECT_THAT(run_times, ElementsAre(start_time + delay3, start_time + delay4));
2488 }
2489
TEST_P(SequenceManagerTest,TaskQueueVoters)2490 TEST_P(SequenceManagerTest, TaskQueueVoters) {
2491 CreateTaskQueues(1u);
2492
2493 // The task queue should be initially enabled.
2494 EXPECT_TRUE(runners_[0]->IsQueueEnabled());
2495
2496 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter1 =
2497 runners_[0]->CreateQueueEnabledVoter();
2498 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter2 =
2499 runners_[0]->CreateQueueEnabledVoter();
2500 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter3 =
2501 runners_[0]->CreateQueueEnabledVoter();
2502 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter4 =
2503 runners_[0]->CreateQueueEnabledVoter();
2504
2505 // Voters should initially vote for the queue to be enabled.
2506 EXPECT_TRUE(runners_[0]->IsQueueEnabled());
2507
2508 // If any voter wants to disable, the queue is disabled.
2509 voter1->SetQueueEnabled(false);
2510 EXPECT_FALSE(runners_[0]->IsQueueEnabled());
2511
2512 // If the voter is deleted then the queue should be re-enabled.
2513 voter1.reset();
2514 EXPECT_TRUE(runners_[0]->IsQueueEnabled());
2515
2516 // If any of the remaining voters wants to disable, the queue should be
2517 // disabled.
2518 voter2->SetQueueEnabled(false);
2519 EXPECT_FALSE(runners_[0]->IsQueueEnabled());
2520
2521 // If another queue votes to disable, nothing happens because it's already
2522 // disabled.
2523 voter3->SetQueueEnabled(false);
2524 EXPECT_FALSE(runners_[0]->IsQueueEnabled());
2525
2526 // There are two votes to disable, so one of them voting to enable does
2527 // nothing.
2528 voter2->SetQueueEnabled(true);
2529 EXPECT_FALSE(runners_[0]->IsQueueEnabled());
2530
2531 // IF all queues vote to enable then the queue is enabled.
2532 voter3->SetQueueEnabled(true);
2533 EXPECT_TRUE(runners_[0]->IsQueueEnabled());
2534 }
2535
TEST_P(SequenceManagerTest,ShutdownQueueBeforeEnabledVoterDeleted)2536 TEST_P(SequenceManagerTest, ShutdownQueueBeforeEnabledVoterDeleted) {
2537 CreateTaskQueues(1u);
2538
2539 scoped_refptr<TaskQueue> queue = CreateTaskQueue();
2540
2541 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
2542 queue->CreateQueueEnabledVoter();
2543
2544 voter->SetQueueEnabled(true); // NOP
2545 queue->ShutdownTaskQueue();
2546
2547 // This should complete without DCHECKing.
2548 voter.reset();
2549 }
2550
TEST_P(SequenceManagerTest,ShutdownQueueBeforeDisabledVoterDeleted)2551 TEST_P(SequenceManagerTest, ShutdownQueueBeforeDisabledVoterDeleted) {
2552 CreateTaskQueues(1u);
2553
2554 scoped_refptr<TaskQueue> queue = CreateTaskQueue();
2555
2556 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
2557 queue->CreateQueueEnabledVoter();
2558
2559 voter->SetQueueEnabled(false);
2560 queue->ShutdownTaskQueue();
2561
2562 // This should complete without DCHECKing.
2563 voter.reset();
2564 }
2565
TEST_P(SequenceManagerTest,SweepCanceledDelayedTasks)2566 TEST_P(SequenceManagerTest, SweepCanceledDelayedTasks) {
2567 CreateTaskQueues(1u);
2568
2569 CancelableTask task1(GetTickClock());
2570 CancelableTask task2(GetTickClock());
2571 CancelableTask task3(GetTickClock());
2572 CancelableTask task4(GetTickClock());
2573 TimeDelta delay1(TimeDelta::FromSeconds(5));
2574 TimeDelta delay2(TimeDelta::FromSeconds(10));
2575 TimeDelta delay3(TimeDelta::FromSeconds(15));
2576 TimeDelta delay4(TimeDelta::FromSeconds(30));
2577 std::vector<TimeTicks> run_times;
2578 runners_[0]->PostDelayedTask(
2579 FROM_HERE,
2580 BindOnce(&CancelableTask::RecordTimeTask,
2581 task1.weak_factory_.GetWeakPtr(), &run_times),
2582 delay1);
2583 runners_[0]->PostDelayedTask(
2584 FROM_HERE,
2585 BindOnce(&CancelableTask::RecordTimeTask,
2586 task2.weak_factory_.GetWeakPtr(), &run_times),
2587 delay2);
2588 runners_[0]->PostDelayedTask(
2589 FROM_HERE,
2590 BindOnce(&CancelableTask::RecordTimeTask,
2591 task3.weak_factory_.GetWeakPtr(), &run_times),
2592 delay3);
2593 runners_[0]->PostDelayedTask(
2594 FROM_HERE,
2595 BindOnce(&CancelableTask::RecordTimeTask,
2596 task4.weak_factory_.GetWeakPtr(), &run_times),
2597 delay4);
2598
2599 EXPECT_EQ(4u, runners_[0]->GetNumberOfPendingTasks());
2600 task2.weak_factory_.InvalidateWeakPtrs();
2601 task3.weak_factory_.InvalidateWeakPtrs();
2602 EXPECT_EQ(4u, runners_[0]->GetNumberOfPendingTasks());
2603
2604 manager_->SweepCanceledDelayedTasks();
2605 EXPECT_EQ(2u, runners_[0]->GetNumberOfPendingTasks());
2606
2607 task1.weak_factory_.InvalidateWeakPtrs();
2608 task4.weak_factory_.InvalidateWeakPtrs();
2609
2610 manager_->SweepCanceledDelayedTasks();
2611 EXPECT_EQ(0u, runners_[0]->GetNumberOfPendingTasks());
2612 }
2613
TEST_P(SequenceManagerTest,DelayTillNextTask)2614 TEST_P(SequenceManagerTest, DelayTillNextTask) {
2615 CreateTaskQueues(2u);
2616
2617 LazyNow lazy_now(GetTickClock());
2618 EXPECT_EQ(TimeDelta::Max(), manager_->DelayTillNextTask(&lazy_now));
2619
2620 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
2621 TimeDelta::FromSeconds(10));
2622
2623 EXPECT_EQ(TimeDelta::FromSeconds(10), manager_->DelayTillNextTask(&lazy_now));
2624
2625 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
2626 TimeDelta::FromSeconds(15));
2627
2628 EXPECT_EQ(TimeDelta::FromSeconds(10), manager_->DelayTillNextTask(&lazy_now));
2629
2630 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
2631 TimeDelta::FromSeconds(5));
2632
2633 EXPECT_EQ(TimeDelta::FromSeconds(5), manager_->DelayTillNextTask(&lazy_now));
2634
2635 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
2636
2637 EXPECT_EQ(TimeDelta(), manager_->DelayTillNextTask(&lazy_now));
2638 }
2639
TEST_P(SequenceManagerTest,DelayTillNextTask_Disabled)2640 TEST_P(SequenceManagerTest, DelayTillNextTask_Disabled) {
2641 CreateTaskQueues(1u);
2642
2643 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
2644 runners_[0]->CreateQueueEnabledVoter();
2645 voter->SetQueueEnabled(false);
2646 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
2647
2648 LazyNow lazy_now(GetTickClock());
2649 EXPECT_EQ(TimeDelta::Max(), manager_->DelayTillNextTask(&lazy_now));
2650 }
2651
TEST_P(SequenceManagerTest,DelayTillNextTask_Fence)2652 TEST_P(SequenceManagerTest, DelayTillNextTask_Fence) {
2653 CreateTaskQueues(1u);
2654
2655 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
2656 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
2657
2658 LazyNow lazy_now(GetTickClock());
2659 EXPECT_EQ(TimeDelta::Max(), manager_->DelayTillNextTask(&lazy_now));
2660 }
2661
TEST_P(SequenceManagerTest,DelayTillNextTask_FenceUnblocking)2662 TEST_P(SequenceManagerTest, DelayTillNextTask_FenceUnblocking) {
2663 CreateTaskQueues(1u);
2664
2665 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
2666 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
2667 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
2668
2669 LazyNow lazy_now(GetTickClock());
2670 EXPECT_EQ(TimeDelta(), manager_->DelayTillNextTask(&lazy_now));
2671 }
2672
TEST_P(SequenceManagerTest,DelayTillNextTask_DelayedTaskReady)2673 TEST_P(SequenceManagerTest, DelayTillNextTask_DelayedTaskReady) {
2674 CreateTaskQueues(1u);
2675
2676 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
2677 TimeDelta::FromSeconds(1));
2678
2679 test_task_runner_->AdvanceMockTickClock(TimeDelta::FromSeconds(10));
2680
2681 LazyNow lazy_now(GetTickClock());
2682 EXPECT_EQ(TimeDelta(), manager_->DelayTillNextTask(&lazy_now));
2683 }
2684
2685 namespace {
MessageLoopTaskWithDelayedQuit(SimpleTestTickClock * now_src,scoped_refptr<TaskQueue> task_queue)2686 void MessageLoopTaskWithDelayedQuit(SimpleTestTickClock* now_src,
2687 scoped_refptr<TaskQueue> task_queue) {
2688 RunLoop run_loop(RunLoop::Type::kNestableTasksAllowed);
2689 task_queue->PostDelayedTask(FROM_HERE, run_loop.QuitClosure(),
2690 TimeDelta::FromMilliseconds(100));
2691 now_src->Advance(TimeDelta::FromMilliseconds(200));
2692 run_loop.Run();
2693 }
2694 } // namespace
2695
TEST_P(SequenceManagerTestWithMessageLoop,DelayedTaskRunsInNestedMessageLoop)2696 TEST_P(SequenceManagerTestWithMessageLoop, DelayedTaskRunsInNestedMessageLoop) {
2697 CreateTaskQueues(1u);
2698 RunLoop run_loop;
2699 runners_[0]->PostTask(FROM_HERE,
2700 BindOnce(&MessageLoopTaskWithDelayedQuit, &mock_clock_,
2701 RetainedRef(runners_[0])));
2702 run_loop.RunUntilIdle();
2703 }
2704
2705 namespace {
MessageLoopTaskWithImmediateQuit(OnceClosure non_nested_quit_closure,scoped_refptr<TaskQueue> task_queue)2706 void MessageLoopTaskWithImmediateQuit(OnceClosure non_nested_quit_closure,
2707 scoped_refptr<TaskQueue> task_queue) {
2708 RunLoop run_loop(RunLoop::Type::kNestableTasksAllowed);
2709 // Needed because entering the nested run loop causes a DoWork to get
2710 // posted.
2711 task_queue->PostTask(FROM_HERE, BindOnce(&NopTask));
2712 task_queue->PostTask(FROM_HERE, run_loop.QuitClosure());
2713 run_loop.Run();
2714 std::move(non_nested_quit_closure).Run();
2715 }
2716 } // namespace
2717
TEST_P(SequenceManagerTestWithMessageLoop,DelayedNestedMessageLoopDoesntPreventTasksRunning)2718 TEST_P(SequenceManagerTestWithMessageLoop,
2719 DelayedNestedMessageLoopDoesntPreventTasksRunning) {
2720 CreateTaskQueues(1u);
2721 RunLoop run_loop;
2722 runners_[0]->PostDelayedTask(
2723 FROM_HERE,
2724 BindOnce(&MessageLoopTaskWithImmediateQuit, run_loop.QuitClosure(),
2725 RetainedRef(runners_[0])),
2726 TimeDelta::FromMilliseconds(100));
2727
2728 mock_clock_.Advance(TimeDelta::FromMilliseconds(200));
2729 run_loop.Run();
2730 }
2731
TEST_P(SequenceManagerTest,CouldTaskRun_DisableAndReenable)2732 TEST_P(SequenceManagerTest, CouldTaskRun_DisableAndReenable) {
2733 CreateTaskQueues(1u);
2734
2735 EnqueueOrder enqueue_order = manager_->GetNextSequenceNumber();
2736 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order));
2737
2738 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
2739 runners_[0]->CreateQueueEnabledVoter();
2740 voter->SetQueueEnabled(false);
2741 EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order));
2742
2743 voter->SetQueueEnabled(true);
2744 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order));
2745 }
2746
TEST_P(SequenceManagerTest,CouldTaskRun_Fence)2747 TEST_P(SequenceManagerTest, CouldTaskRun_Fence) {
2748 CreateTaskQueues(1u);
2749
2750 EnqueueOrder enqueue_order = manager_->GetNextSequenceNumber();
2751 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order));
2752
2753 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
2754 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order));
2755
2756 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kBeginningOfTime);
2757 EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order));
2758
2759 runners_[0]->RemoveFence();
2760 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order));
2761 }
2762
TEST_P(SequenceManagerTest,CouldTaskRun_FenceBeforeThenAfter)2763 TEST_P(SequenceManagerTest, CouldTaskRun_FenceBeforeThenAfter) {
2764 CreateTaskQueues(1u);
2765
2766 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
2767
2768 EnqueueOrder enqueue_order = manager_->GetNextSequenceNumber();
2769 EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order));
2770
2771 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kNow);
2772 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->CouldTaskRun(enqueue_order));
2773 }
2774
TEST_P(SequenceManagerTest,DelayedDoWorkNotPostedForDisabledQueue)2775 TEST_P(SequenceManagerTest, DelayedDoWorkNotPostedForDisabledQueue) {
2776 CreateTaskQueues(1u);
2777
2778 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
2779 TimeDelta::FromMilliseconds(1));
2780 ASSERT_TRUE(test_task_runner_->HasPendingTask());
2781 EXPECT_EQ(TimeDelta::FromMilliseconds(1),
2782 test_task_runner_->NextPendingTaskDelay());
2783
2784 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
2785 runners_[0]->CreateQueueEnabledVoter();
2786 voter->SetQueueEnabled(false);
2787 EXPECT_FALSE(test_task_runner_->HasPendingTask());
2788
2789 voter->SetQueueEnabled(true);
2790 ASSERT_TRUE(test_task_runner_->HasPendingTask());
2791 EXPECT_EQ(TimeDelta::FromMilliseconds(1),
2792 test_task_runner_->NextPendingTaskDelay());
2793 }
2794
TEST_P(SequenceManagerTest,DisablingQueuesChangesDelayTillNextDoWork)2795 TEST_P(SequenceManagerTest, DisablingQueuesChangesDelayTillNextDoWork) {
2796 CreateTaskQueues(3u);
2797 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
2798 TimeDelta::FromMilliseconds(1));
2799 runners_[1]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
2800 TimeDelta::FromMilliseconds(10));
2801 runners_[2]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
2802 TimeDelta::FromMilliseconds(100));
2803
2804 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter0 =
2805 runners_[0]->CreateQueueEnabledVoter();
2806 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter1 =
2807 runners_[1]->CreateQueueEnabledVoter();
2808 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter2 =
2809 runners_[2]->CreateQueueEnabledVoter();
2810
2811 ASSERT_TRUE(test_task_runner_->HasPendingTask());
2812 EXPECT_EQ(TimeDelta::FromMilliseconds(1),
2813 test_task_runner_->NextPendingTaskDelay());
2814
2815 voter0->SetQueueEnabled(false);
2816 ASSERT_TRUE(test_task_runner_->HasPendingTask());
2817 EXPECT_EQ(TimeDelta::FromMilliseconds(10),
2818 test_task_runner_->NextPendingTaskDelay());
2819
2820 voter1->SetQueueEnabled(false);
2821 ASSERT_TRUE(test_task_runner_->HasPendingTask());
2822 EXPECT_EQ(TimeDelta::FromMilliseconds(100),
2823 test_task_runner_->NextPendingTaskDelay());
2824
2825 voter2->SetQueueEnabled(false);
2826 EXPECT_FALSE(test_task_runner_->HasPendingTask());
2827 }
2828
TEST_P(SequenceManagerTest,GetNextScheduledWakeUp)2829 TEST_P(SequenceManagerTest, GetNextScheduledWakeUp) {
2830 CreateTaskQueues(1u);
2831
2832 EXPECT_EQ(nullopt, runners_[0]->GetNextScheduledWakeUp());
2833
2834 TimeTicks start_time = manager_->NowTicks();
2835 TimeDelta delay1 = TimeDelta::FromMilliseconds(10);
2836 TimeDelta delay2 = TimeDelta::FromMilliseconds(2);
2837
2838 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay1);
2839 EXPECT_EQ(start_time + delay1, runners_[0]->GetNextScheduledWakeUp());
2840
2841 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask), delay2);
2842 EXPECT_EQ(start_time + delay2, runners_[0]->GetNextScheduledWakeUp());
2843
2844 // We don't have wake-ups scheduled for disabled queues.
2845 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
2846 runners_[0]->CreateQueueEnabledVoter();
2847 voter->SetQueueEnabled(false);
2848 EXPECT_EQ(nullopt, runners_[0]->GetNextScheduledWakeUp());
2849
2850 voter->SetQueueEnabled(true);
2851 EXPECT_EQ(start_time + delay2, runners_[0]->GetNextScheduledWakeUp());
2852
2853 // Immediate tasks shouldn't make any difference.
2854 runners_[0]->PostTask(FROM_HERE, BindOnce(&NopTask));
2855 EXPECT_EQ(start_time + delay2, runners_[0]->GetNextScheduledWakeUp());
2856
2857 // Neither should fences.
2858 runners_[0]->InsertFence(TaskQueue::InsertFencePosition::kBeginningOfTime);
2859 EXPECT_EQ(start_time + delay2, runners_[0]->GetNextScheduledWakeUp());
2860 }
2861
TEST_P(SequenceManagerTest,SetTimeDomainForDisabledQueue)2862 TEST_P(SequenceManagerTest, SetTimeDomainForDisabledQueue) {
2863 CreateTaskQueues(1u);
2864
2865 MockTaskQueueObserver observer;
2866 runners_[0]->SetObserver(&observer);
2867
2868 runners_[0]->PostDelayedTask(FROM_HERE, BindOnce(&NopTask),
2869 TimeDelta::FromMilliseconds(1));
2870
2871 std::unique_ptr<TaskQueue::QueueEnabledVoter> voter =
2872 runners_[0]->CreateQueueEnabledVoter();
2873 voter->SetQueueEnabled(false);
2874
2875 // We should not get a notification for a disabled queue.
2876 EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0);
2877
2878 std::unique_ptr<MockTimeDomain> domain =
2879 std::make_unique<MockTimeDomain>(manager_->NowTicks());
2880 manager_->RegisterTimeDomain(domain.get());
2881 runners_[0]->SetTimeDomain(domain.get());
2882
2883 // Tidy up.
2884 runners_[0]->ShutdownTaskQueue();
2885 manager_->UnregisterTimeDomain(domain.get());
2886 }
2887
2888 namespace {
SetOnTaskHandlers(scoped_refptr<TestTaskQueue> task_queue,int * start_counter,int * complete_counter)2889 void SetOnTaskHandlers(scoped_refptr<TestTaskQueue> task_queue,
2890 int* start_counter,
2891 int* complete_counter) {
2892 task_queue->GetTaskQueueImpl()->SetOnTaskStartedHandler(BindRepeating(
2893 [](int* counter, const TaskQueue::Task& task,
2894 const TaskQueue::TaskTiming& task_timing) { ++(*counter); },
2895 start_counter));
2896 task_queue->GetTaskQueueImpl()->SetOnTaskCompletedHandler(BindRepeating(
2897 [](int* counter, const TaskQueue::Task& task,
2898 const TaskQueue::TaskTiming& task_timing) { ++(*counter); },
2899 complete_counter));
2900 }
2901
UnsetOnTaskHandlers(scoped_refptr<TestTaskQueue> task_queue)2902 void UnsetOnTaskHandlers(scoped_refptr<TestTaskQueue> task_queue) {
2903 task_queue->GetTaskQueueImpl()->SetOnTaskStartedHandler(
2904 internal::TaskQueueImpl::OnTaskStartedHandler());
2905 task_queue->GetTaskQueueImpl()->SetOnTaskCompletedHandler(
2906 internal::TaskQueueImpl::OnTaskStartedHandler());
2907 }
2908 } // namespace
2909
TEST_P(SequenceManagerTest,ProcessTasksWithoutTaskTimeObservers)2910 TEST_P(SequenceManagerTest, ProcessTasksWithoutTaskTimeObservers) {
2911 CreateTaskQueues(1u);
2912 int start_counter = 0;
2913 int complete_counter = 0;
2914 std::vector<EnqueueOrder> run_order;
2915 SetOnTaskHandlers(runners_[0], &start_counter, &complete_counter);
2916 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->RequiresTaskTiming());
2917 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
2918 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
2919 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
2920
2921 RunLoop().RunUntilIdle();
2922 EXPECT_EQ(start_counter, 3);
2923 EXPECT_EQ(complete_counter, 3);
2924 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u));
2925
2926 UnsetOnTaskHandlers(runners_[0]);
2927 EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->RequiresTaskTiming());
2928 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order));
2929 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 5, &run_order));
2930 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 6, &run_order));
2931
2932 RunLoop().RunUntilIdle();
2933 EXPECT_EQ(start_counter, 3);
2934 EXPECT_EQ(complete_counter, 3);
2935 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u, 4u, 5u, 6u));
2936 }
2937
TEST_P(SequenceManagerTest,ProcessTasksWithTaskTimeObservers)2938 TEST_P(SequenceManagerTest, ProcessTasksWithTaskTimeObservers) {
2939 CreateTaskQueues(1u);
2940 int start_counter = 0;
2941 int complete_counter = 0;
2942
2943 manager_->AddTaskTimeObserver(&test_task_time_observer_);
2944 SetOnTaskHandlers(runners_[0], &start_counter, &complete_counter);
2945 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->RequiresTaskTiming());
2946 std::vector<EnqueueOrder> run_order;
2947 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
2948 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
2949
2950 RunLoop().RunUntilIdle();
2951 EXPECT_EQ(start_counter, 2);
2952 EXPECT_EQ(complete_counter, 2);
2953 EXPECT_THAT(run_order, ElementsAre(1u, 2u));
2954
2955 UnsetOnTaskHandlers(runners_[0]);
2956 EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->RequiresTaskTiming());
2957 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 3, &run_order));
2958 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 4, &run_order));
2959
2960 RunLoop().RunUntilIdle();
2961 EXPECT_EQ(start_counter, 2);
2962 EXPECT_EQ(complete_counter, 2);
2963 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u, 4u));
2964
2965 manager_->RemoveTaskTimeObserver(&test_task_time_observer_);
2966 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 5, &run_order));
2967 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 6, &run_order));
2968
2969 RunLoop().RunUntilIdle();
2970 EXPECT_EQ(start_counter, 2);
2971 EXPECT_EQ(complete_counter, 2);
2972 EXPECT_FALSE(runners_[0]->GetTaskQueueImpl()->RequiresTaskTiming());
2973 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u, 4u, 5u, 6u));
2974
2975 SetOnTaskHandlers(runners_[0], &start_counter, &complete_counter);
2976 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 7, &run_order));
2977 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 8, &run_order));
2978
2979 RunLoop().RunUntilIdle();
2980 EXPECT_EQ(start_counter, 4);
2981 EXPECT_EQ(complete_counter, 4);
2982 EXPECT_TRUE(runners_[0]->GetTaskQueueImpl()->RequiresTaskTiming());
2983 EXPECT_THAT(run_order, ElementsAre(1u, 2u, 3u, 4u, 5u, 6u, 7u, 8u));
2984 UnsetOnTaskHandlers(runners_[0]);
2985 }
2986
TEST_P(SequenceManagerTest,GracefulShutdown)2987 TEST_P(SequenceManagerTest, GracefulShutdown) {
2988 std::vector<TimeTicks> run_times;
2989 scoped_refptr<TestTaskQueue> main_tq = CreateTaskQueue();
2990 WeakPtr<TestTaskQueue> main_tq_weak_ptr = main_tq->GetWeakPtr();
2991
2992 EXPECT_EQ(1u, manager_->ActiveQueuesCount());
2993 EXPECT_EQ(0u, manager_->QueuesToShutdownCount());
2994 EXPECT_EQ(0u, manager_->QueuesToDeleteCount());
2995
2996 for (int i = 1; i <= 5; ++i) {
2997 main_tq->PostDelayedTask(
2998 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()),
2999 TimeDelta::FromMilliseconds(i * 100));
3000 }
3001 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(250));
3002
3003 main_tq = nullptr;
3004 // Ensure that task queue went away.
3005 EXPECT_FALSE(main_tq_weak_ptr.get());
3006
3007 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1));
3008
3009 EXPECT_EQ(1u, manager_->ActiveQueuesCount());
3010 EXPECT_EQ(1u, manager_->QueuesToShutdownCount());
3011 EXPECT_EQ(0u, manager_->QueuesToDeleteCount());
3012
3013 test_task_runner_->FastForwardUntilNoTasksRemain();
3014
3015 // Even with TaskQueue gone, tasks are executed.
3016 EXPECT_THAT(run_times,
3017 ElementsAre(start_time_ + TimeDelta::FromMilliseconds(100),
3018 start_time_ + TimeDelta::FromMilliseconds(200),
3019 start_time_ + TimeDelta::FromMilliseconds(300),
3020 start_time_ + TimeDelta::FromMilliseconds(400),
3021 start_time_ + TimeDelta::FromMilliseconds(500)));
3022
3023 EXPECT_EQ(0u, manager_->ActiveQueuesCount());
3024 EXPECT_EQ(0u, manager_->QueuesToShutdownCount());
3025 EXPECT_EQ(0u, manager_->QueuesToDeleteCount());
3026 }
3027
TEST_P(SequenceManagerTest,GracefulShutdown_ManagerDeletedInFlight)3028 TEST_P(SequenceManagerTest, GracefulShutdown_ManagerDeletedInFlight) {
3029 std::vector<TimeTicks> run_times;
3030 scoped_refptr<TestTaskQueue> control_tq = CreateTaskQueue();
3031 std::vector<scoped_refptr<TestTaskQueue>> main_tqs;
3032 std::vector<WeakPtr<TestTaskQueue>> main_tq_weak_ptrs;
3033
3034 // There might be a race condition - async task queues should be unregistered
3035 // first. Increase the number of task queues to surely detect that.
3036 // The problem is that pointers are compared in a set and generally for
3037 // a small number of allocations value of the pointers increases
3038 // monotonically. 100 is large enough to force allocations from different
3039 // pages.
3040 const int N = 100;
3041 for (int i = 0; i < N; ++i) {
3042 scoped_refptr<TestTaskQueue> tq = CreateTaskQueue();
3043 main_tq_weak_ptrs.push_back(tq->GetWeakPtr());
3044 main_tqs.push_back(std::move(tq));
3045 }
3046
3047 for (int i = 1; i <= 5; ++i) {
3048 main_tqs[0]->PostDelayedTask(
3049 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()),
3050 TimeDelta::FromMilliseconds(i * 100));
3051 }
3052 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(250));
3053
3054 main_tqs.clear();
3055 // Ensure that task queues went away.
3056 for (int i = 0; i < N; ++i) {
3057 EXPECT_FALSE(main_tq_weak_ptrs[i].get());
3058 }
3059
3060 // No leaks should occur when TQM was destroyed before processing
3061 // shutdown task and TaskQueueImpl should be safely deleted on a correct
3062 // thread.
3063 manager_.reset();
3064
3065 test_task_runner_->FastForwardUntilNoTasksRemain();
3066
3067 EXPECT_THAT(run_times,
3068 ElementsAre(start_time_ + TimeDelta::FromMilliseconds(100),
3069 start_time_ + TimeDelta::FromMilliseconds(200)));
3070 }
3071
TEST_P(SequenceManagerTest,GracefulShutdown_ManagerDeletedWithQueuesToShutdown)3072 TEST_P(SequenceManagerTest,
3073 GracefulShutdown_ManagerDeletedWithQueuesToShutdown) {
3074 std::vector<TimeTicks> run_times;
3075 scoped_refptr<TestTaskQueue> main_tq = CreateTaskQueue();
3076 WeakPtr<TestTaskQueue> main_tq_weak_ptr = main_tq->GetWeakPtr();
3077
3078 EXPECT_EQ(1u, manager_->ActiveQueuesCount());
3079 EXPECT_EQ(0u, manager_->QueuesToShutdownCount());
3080 EXPECT_EQ(0u, manager_->QueuesToDeleteCount());
3081
3082 for (int i = 1; i <= 5; ++i) {
3083 main_tq->PostDelayedTask(
3084 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()),
3085 TimeDelta::FromMilliseconds(i * 100));
3086 }
3087 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(250));
3088
3089 main_tq = nullptr;
3090 // Ensure that task queue went away.
3091 EXPECT_FALSE(main_tq_weak_ptr.get());
3092
3093 test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1));
3094
3095 EXPECT_EQ(1u, manager_->ActiveQueuesCount());
3096 EXPECT_EQ(1u, manager_->QueuesToShutdownCount());
3097 EXPECT_EQ(0u, manager_->QueuesToDeleteCount());
3098
3099 // Ensure that all queues-to-gracefully-shutdown are properly unregistered.
3100 manager_.reset();
3101
3102 test_task_runner_->FastForwardUntilNoTasksRemain();
3103
3104 EXPECT_THAT(run_times,
3105 ElementsAre(start_time_ + TimeDelta::FromMilliseconds(100),
3106 start_time_ + TimeDelta::FromMilliseconds(200)));
3107 }
3108
TEST_P(SequenceManagerTestWithCustomInitialization,DefaultTaskRunnerSupport)3109 TEST_P(SequenceManagerTestWithCustomInitialization, DefaultTaskRunnerSupport) {
3110 MessageLoop message_loop;
3111 scoped_refptr<SingleThreadTaskRunner> original_task_runner =
3112 message_loop.task_runner();
3113 scoped_refptr<SingleThreadTaskRunner> custom_task_runner =
3114 MakeRefCounted<TestSimpleTaskRunner>();
3115 {
3116 std::unique_ptr<SequenceManagerForTest> manager =
3117 SequenceManagerForTest::Create(&message_loop,
3118 message_loop.task_runner(), nullptr);
3119 manager->SetDefaultTaskRunner(custom_task_runner);
3120 DCHECK_EQ(custom_task_runner, message_loop.task_runner());
3121 }
3122 DCHECK_EQ(original_task_runner, message_loop.task_runner());
3123 }
3124
TEST_P(SequenceManagerTest,CanceledTasksInQueueCantMakeOtherTasksSkipAhead)3125 TEST_P(SequenceManagerTest, CanceledTasksInQueueCantMakeOtherTasksSkipAhead) {
3126 CreateTaskQueues(2u);
3127
3128 CancelableTask task1(GetTickClock());
3129 CancelableTask task2(GetTickClock());
3130 std::vector<TimeTicks> run_times;
3131
3132 runners_[0]->PostTask(FROM_HERE,
3133 BindOnce(&CancelableTask::RecordTimeTask,
3134 task1.weak_factory_.GetWeakPtr(), &run_times));
3135 runners_[0]->PostTask(FROM_HERE,
3136 BindOnce(&CancelableTask::RecordTimeTask,
3137 task2.weak_factory_.GetWeakPtr(), &run_times));
3138
3139 std::vector<EnqueueOrder> run_order;
3140 runners_[1]->PostTask(FROM_HERE, BindOnce(&TestTask, 1, &run_order));
3141
3142 runners_[0]->PostTask(FROM_HERE, BindOnce(&TestTask, 2, &run_order));
3143
3144 task1.weak_factory_.InvalidateWeakPtrs();
3145 task2.weak_factory_.InvalidateWeakPtrs();
3146 RunLoop().RunUntilIdle();
3147
3148 EXPECT_THAT(run_order, ElementsAre(1u, 2u));
3149 }
3150
TEST_P(SequenceManagerTest,TaskQueueDeletedOnAnotherThread)3151 TEST_P(SequenceManagerTest, TaskQueueDeletedOnAnotherThread) {
3152 std::vector<TimeTicks> run_times;
3153 scoped_refptr<TestTaskQueue> main_tq = CreateTaskQueue();
3154
3155 int start_counter = 0;
3156 int complete_counter = 0;
3157 SetOnTaskHandlers(main_tq, &start_counter, &complete_counter);
3158
3159 EXPECT_EQ(1u, manager_->ActiveQueuesCount());
3160 EXPECT_EQ(0u, manager_->QueuesToShutdownCount());
3161 EXPECT_EQ(0u, manager_->QueuesToDeleteCount());
3162
3163 for (int i = 1; i <= 5; ++i) {
3164 main_tq->PostDelayedTask(
3165 FROM_HERE, BindOnce(&RecordTimeTask, &run_times, GetTickClock()),
3166 TimeDelta::FromMilliseconds(i * 100));
3167 }
3168
3169 // TODO(altimin): do not do this after switching to weak pointer-based
3170 // task handlers.
3171 UnsetOnTaskHandlers(main_tq);
3172
3173 WaitableEvent task_queue_deleted(WaitableEvent::ResetPolicy::MANUAL,
3174 WaitableEvent::InitialState::NOT_SIGNALED);
3175 std::unique_ptr<Thread> thread = std::make_unique<Thread>("test thread");
3176 thread->StartAndWaitForTesting();
3177
3178 thread->task_runner()->PostTask(
3179 FROM_HERE, BindOnce(
3180 [](scoped_refptr<SingleThreadTaskRunner> task_queue,
3181 WaitableEvent* task_queue_deleted) {
3182 task_queue = nullptr;
3183 task_queue_deleted->Signal();
3184 },
3185 std::move(main_tq), &task_queue_deleted));
3186 task_queue_deleted.Wait();
3187
3188 EXPECT_EQ(1u, manager_->ActiveQueuesCount());
3189 EXPECT_EQ(1u, manager_->QueuesToShutdownCount());
3190 EXPECT_EQ(0u, manager_->QueuesToDeleteCount());
3191
3192 test_task_runner_->FastForwardUntilNoTasksRemain();
3193
3194 // Even with TaskQueue gone, tasks are executed.
3195 EXPECT_THAT(run_times,
3196 ElementsAre(start_time_ + TimeDelta::FromMilliseconds(100),
3197 start_time_ + TimeDelta::FromMilliseconds(200),
3198 start_time_ + TimeDelta::FromMilliseconds(300),
3199 start_time_ + TimeDelta::FromMilliseconds(400),
3200 start_time_ + TimeDelta::FromMilliseconds(500)));
3201
3202 EXPECT_EQ(0u, manager_->ActiveQueuesCount());
3203 EXPECT_EQ(0u, manager_->QueuesToShutdownCount());
3204 EXPECT_EQ(0u, manager_->QueuesToDeleteCount());
3205
3206 thread->Stop();
3207 }
3208
3209 namespace {
3210
DoNothing()3211 void DoNothing() {}
3212
3213 class PostTaskInDestructor {
3214 public:
PostTaskInDestructor(scoped_refptr<TaskQueue> task_queue)3215 explicit PostTaskInDestructor(scoped_refptr<TaskQueue> task_queue)
3216 : task_queue_(task_queue) {}
3217
~PostTaskInDestructor()3218 ~PostTaskInDestructor() {
3219 task_queue_->PostTask(FROM_HERE, BindOnce(&DoNothing));
3220 }
3221
Do()3222 void Do() {}
3223
3224 private:
3225 scoped_refptr<TaskQueue> task_queue_;
3226 };
3227
3228 } // namespace
3229
TEST_P(SequenceManagerTest,TaskQueueUsedInTaskDestructorAfterShutdown)3230 TEST_P(SequenceManagerTest, TaskQueueUsedInTaskDestructorAfterShutdown) {
3231 // This test checks that when a task is posted to a shutdown queue and
3232 // destroyed, it can try to post a task to the same queue without deadlocks.
3233 scoped_refptr<TestTaskQueue> main_tq = CreateTaskQueue();
3234
3235 WaitableEvent test_executed(WaitableEvent::ResetPolicy::MANUAL,
3236 WaitableEvent::InitialState::NOT_SIGNALED);
3237 std::unique_ptr<Thread> thread = std::make_unique<Thread>("test thread");
3238 thread->StartAndWaitForTesting();
3239
3240 manager_.reset();
3241
3242 thread->task_runner()->PostTask(
3243 FROM_HERE, BindOnce(
3244 [](scoped_refptr<SingleThreadTaskRunner> task_queue,
3245 std::unique_ptr<PostTaskInDestructor> test_object,
3246 WaitableEvent* test_executed) {
3247 task_queue->PostTask(FROM_HERE,
3248 BindOnce(&PostTaskInDestructor::Do,
3249 std::move(test_object)));
3250 test_executed->Signal();
3251 },
3252 main_tq, std::make_unique<PostTaskInDestructor>(main_tq),
3253 &test_executed));
3254 test_executed.Wait();
3255 }
3256
3257 } // namespace sequence_manager_impl_unittest
3258 } // namespace internal
3259 } // namespace sequence_manager
3260 } // namespace base
3261