OLD | NEW |
(Empty) | |
| 1 // Copyright 2016 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_scheduler/test_task_factory.h" |
| 6 |
| 7 #include "base/bind.h" |
| 8 #include "base/bind_helpers.h" |
| 9 #include "base/location.h" |
| 10 #include "base/logging.h" |
| 11 #include "base/synchronization/waitable_event.h" |
| 12 #include "testing/gtest/include/gtest/gtest.h" |
| 13 |
| 14 namespace base { |
| 15 namespace internal { |
| 16 namespace test { |
| 17 |
| 18 TestTaskFactory::TestTaskFactory(scoped_refptr<TaskRunner> task_runner, |
| 19 ExecutionMode execution_mode) |
| 20 : cv_(&lock_), |
| 21 task_runner_(std::move(task_runner)), |
| 22 execution_mode_(execution_mode) { |
| 23 // Detach |thread_checker_| from the current thread. It will be attached to |
| 24 // the first thread that calls ThreadCheckerImpl::CalledOnValidThread(). |
| 25 thread_checker_.DetachFromThread(); |
| 26 } |
| 27 |
| 28 TestTaskFactory::~TestTaskFactory() { |
| 29 WaitForAllTasksToRun(); |
| 30 } |
| 31 |
| 32 bool TestTaskFactory::PostTask(PostNestedTask post_nested_task, |
| 33 WaitableEvent* event) { |
| 34 AutoLock auto_lock(lock_); |
| 35 return task_runner_->PostTask( |
| 36 FROM_HERE, |
| 37 Bind(&TestTaskFactory::RunTaskCallback, Unretained(this), |
| 38 num_posted_tasks_++, post_nested_task, Unretained(event))); |
| 39 } |
| 40 |
| 41 void TestTaskFactory::WaitForAllTasksToRun() const { |
| 42 AutoLock auto_lock(lock_); |
| 43 while (ran_tasks_.size() < num_posted_tasks_) |
| 44 cv_.Wait(); |
| 45 } |
| 46 |
| 47 void TestTaskFactory::RunTaskCallback(size_t task_index, |
| 48 PostNestedTask post_nested_task, |
| 49 WaitableEvent* event) { |
| 50 if (post_nested_task == PostNestedTask::YES) |
| 51 PostTask(PostNestedTask::NO, nullptr); |
| 52 |
| 53 EXPECT_TRUE(task_runner_->RunsTasksOnCurrentThread()); |
| 54 |
| 55 { |
| 56 AutoLock auto_lock(lock_); |
| 57 |
| 58 DCHECK_LE(task_index, num_posted_tasks_); |
| 59 |
| 60 if ((execution_mode_ == ExecutionMode::SINGLE_THREADED || |
| 61 execution_mode_ == ExecutionMode::SEQUENCED) && |
| 62 task_index != ran_tasks_.size()) { |
| 63 ADD_FAILURE() << "A task didn't run in the expected order."; |
| 64 } |
| 65 |
| 66 if (execution_mode_ == ExecutionMode::SINGLE_THREADED) |
| 67 EXPECT_TRUE(thread_checker_.CalledOnValidThread()); |
| 68 |
| 69 if (ran_tasks_.find(task_index) != ran_tasks_.end()) |
| 70 ADD_FAILURE() << "A task ran more than once."; |
| 71 ran_tasks_.insert(task_index); |
| 72 |
| 73 cv_.Signal(); |
| 74 } |
| 75 |
| 76 if (event) |
| 77 event->Wait(); |
| 78 } |
| 79 |
| 80 } // namespace test |
| 81 } // namespace internal |
| 82 } // namespace base |
OLD | NEW |