Unify various test TaskRunner implementations
Remove various ad-hoc test implementations of TaskRunner and implement TestSimpleTaskRunner instead.
Add TestPendingTask class for use by test TaskRunner implementations.
Clean up TestTaskRunner implementation in net/ and make it use TestPendingTask.
BUG=165806
Review URL: https://codereview.chromium.org/11554036
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@174016 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/base/base.gyp b/base/base.gyp
index ea00db2..612cb2c 100644
--- a/base/base.gyp
+++ b/base/base.gyp
@@ -800,10 +800,14 @@
'test/test_file_util_win.cc',
'test/test_listener_ios.h',
'test/test_listener_ios.mm',
+ 'test/test_pending_task.cc',
+ 'test/test_pending_task.h',
'test/test_reg_util_win.cc',
'test/test_reg_util_win.h',
'test/test_shortcut_win.cc',
'test/test_shortcut_win.h',
+ 'test/test_simple_task_runner.cc',
+ 'test/test_simple_task_runner.h',
'test/test_suite.cc',
'test/test_suite.h',
'test/test_support_android.cc',
diff --git a/base/single_thread_task_runner.h b/base/single_thread_task_runner.h
index 993d8293..a9ba6fd8 100644
--- a/base/single_thread_task_runner.h
+++ b/base/single_thread_task_runner.h
@@ -37,4 +37,4 @@
} // namespace base
-#endif // BASE_SERIAL_TASK_RUNNER_H_
+#endif // BASE_SINGLE_THREAD_TASK_RUNNER_H_
diff --git a/base/test/test_pending_task.cc b/base/test/test_pending_task.cc
new file mode 100644
index 0000000..cb8412c
--- /dev/null
+++ b/base/test/test_pending_task.cc
@@ -0,0 +1,35 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/test/test_pending_task.h"
+
+namespace base {
+
+TestPendingTask::TestPendingTask() : nestability(NESTABLE) {}
+
+TestPendingTask::TestPendingTask(
+ const tracked_objects::Location& location,
+ const Closure& task,
+ TimeTicks post_time,
+ TimeDelta delay,
+ TestNestability nestability)
+ : location(location),
+ task(task),
+ post_time(post_time),
+ delay(delay),
+ nestability(nestability) {}
+
+TimeTicks TestPendingTask::GetTimeToRun() const {
+ return post_time + delay;
+}
+
+bool TestPendingTask::ShouldRunBefore(const TestPendingTask& other) const {
+ if (nestability != other.nestability)
+ return (nestability == NESTABLE);
+ return GetTimeToRun() < other.GetTimeToRun();
+}
+
+TestPendingTask::~TestPendingTask() {}
+
+} // namespace base
diff --git a/base/test/test_pending_task.h b/base/test/test_pending_task.h
new file mode 100644
index 0000000..c4a83bd
--- /dev/null
+++ b/base/test/test_pending_task.h
@@ -0,0 +1,58 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_TEST_TEST_PENDING_TASK_H_
+#define BASE_TEST_TEST_PENDING_TASK_H_
+
+#include "base/callback.h"
+#include "base/location.h"
+#include "base/time.h"
+
+namespace base {
+
+// TestPendingTask is a helper class for test TaskRunner
+// implementations. See test_simple_task_runner.h for example usage.
+
+struct TestPendingTask {
+ enum TestNestability { NESTABLE, NON_NESTABLE };
+
+ TestPendingTask();
+ TestPendingTask(const tracked_objects::Location& location,
+ const Closure& task,
+ TimeTicks post_time,
+ TimeDelta delay,
+ TestNestability nestability);
+ ~TestPendingTask();
+
+ // Returns post_time + delay.
+ TimeTicks GetTimeToRun() const;
+
+ // Returns true if this task is nestable and |other| isn't, or if
+ // this task's time to run is strictly earlier than |other|'s time
+ // to run.
+ //
+ // Note that two tasks may both have the same nestability and delay.
+ // In that case, the caller must use some other criterion (probably
+ // the position in some queue) to break the tie. Conveniently, the
+ // following STL functions already do so:
+ //
+ // - std::min_element
+ // - std::stable_sort
+ //
+ // but the following STL functions don't:
+ //
+ // - std::max_element
+ // - std::sort.
+ bool ShouldRunBefore(const TestPendingTask& other) const;
+
+ tracked_objects::Location location;
+ Closure task;
+ TimeTicks post_time;
+ TimeDelta delay;
+ TestNestability nestability;
+};
+
+} // namespace base
+
+#endif // BASE_TEST_TEST_TASK_RUNNER_H_
diff --git a/base/test/test_simple_task_runner.cc b/base/test/test_simple_task_runner.cc
new file mode 100644
index 0000000..440d6a1
--- /dev/null
+++ b/base/test/test_simple_task_runner.cc
@@ -0,0 +1,72 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "base/test/test_simple_task_runner.h"
+
+#include "base/logging.h"
+
+namespace base {
+
+TestSimpleTaskRunner::TestSimpleTaskRunner() {}
+
+TestSimpleTaskRunner::~TestSimpleTaskRunner() {
+ DCHECK(thread_checker_.CalledOnValidThread());
+}
+
+bool TestSimpleTaskRunner::PostDelayedTask(
+ const tracked_objects::Location& from_here,
+ const Closure& task,
+ TimeDelta delay) {
+ DCHECK(thread_checker_.CalledOnValidThread());
+ pending_tasks_.push_back(
+ TestPendingTask(from_here, task, TimeTicks(), delay,
+ TestPendingTask::NESTABLE));
+ return true;
+}
+
+bool TestSimpleTaskRunner::PostNonNestableDelayedTask(
+ const tracked_objects::Location& from_here,
+ const Closure& task,
+ TimeDelta delay) {
+ DCHECK(thread_checker_.CalledOnValidThread());
+ pending_tasks_.push_back(
+ TestPendingTask(from_here, task, TimeTicks(), delay,
+ TestPendingTask::NON_NESTABLE));
+ return true;
+}
+
+bool TestSimpleTaskRunner::RunsTasksOnCurrentThread() const {
+ DCHECK(thread_checker_.CalledOnValidThread());
+ return true;
+}
+
+const std::deque<TestPendingTask>&
+TestSimpleTaskRunner::GetPendingTasks() const {
+ DCHECK(thread_checker_.CalledOnValidThread());
+ return pending_tasks_;
+}
+
+void TestSimpleTaskRunner::ClearPendingTasks() {
+ DCHECK(thread_checker_.CalledOnValidThread());
+ pending_tasks_.clear();
+}
+
+void TestSimpleTaskRunner::RunPendingTasks() {
+ DCHECK(thread_checker_.CalledOnValidThread());
+ // Swap with a local variable to avoid re-entrancy problems.
+ std::deque<TestPendingTask> tasks_to_run;
+ tasks_to_run.swap(pending_tasks_);
+ for (std::deque<TestPendingTask>::iterator it = tasks_to_run.begin();
+ it != tasks_to_run.end(); ++it) {
+ it->task.Run();
+ }
+}
+
+void TestSimpleTaskRunner::RunUntilIdle() {
+ while (!pending_tasks_.empty()) {
+ RunPendingTasks();
+ }
+}
+
+} // namespace base
diff --git a/base/test/test_simple_task_runner.h b/base/test/test_simple_task_runner.h
new file mode 100644
index 0000000..88113be
--- /dev/null
+++ b/base/test/test_simple_task_runner.h
@@ -0,0 +1,82 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_TEST_TEST_SIMPLE_TASK_RUNNER_H_
+#define BASE_TEST_TEST_SIMPLE_TASK_RUNNER_H_
+
+#include <deque>
+
+#include "base/basictypes.h"
+#include "base/compiler_specific.h"
+#include "base/single_thread_task_runner.h"
+#include "base/test/test_pending_task.h"
+#include "base/threading/thread_checker.h"
+
+namespace base {
+
+// TestSimpleTaskRunner is a simple TaskRunner implementation that can
+// be used for testing. It implements SingleThreadTaskRunner as that
+// interface implements SequencedTaskRunner, which in turn implements
+// TaskRunner, so TestSimpleTaskRunner can be passed in to a function
+// that accepts any *TaskRunner object.
+//
+// TestSimpleTaskRunner has the following properties which make it simple:
+//
+// - It is non-thread safe; all member functions must be called on
+// the same thread.
+// - Tasks are simply stored in a queue in FIFO order, ignoring delay
+// and nestability.
+// - Tasks aren't guaranteed to be destroyed immediately after
+// they're run.
+//
+// However, TestSimpleTaskRunner allows for reentrancy, in that it
+// handles the running of tasks that in turn call back into itself
+// (e.g., to post more tasks).
+//
+// If you need more complicated properties, consider using this class
+// as a template for writing a test TaskRunner implementation using
+// TestPendingTask.
+//
+// Note that, like any TaskRunner, TestSimpleTaskRunner is
+// ref-counted.
+class TestSimpleTaskRunner : public SingleThreadTaskRunner {
+ public:
+ TestSimpleTaskRunner();
+
+ // SingleThreadTaskRunner implementation.
+ virtual bool PostDelayedTask(const tracked_objects::Location& from_here,
+ const Closure& task,
+ TimeDelta delay) OVERRIDE;
+ virtual bool PostNonNestableDelayedTask(
+ const tracked_objects::Location& from_here,
+ const Closure& task,
+ TimeDelta delay) OVERRIDE;
+
+ virtual bool RunsTasksOnCurrentThread() const OVERRIDE;
+
+ const std::deque<TestPendingTask>& GetPendingTasks() const;
+
+ // Clears the queue of pending tasks without running them.
+ void ClearPendingTasks();
+
+ // Runs each current pending task in order and clears the queue.
+ // Any tasks posted by the tasks are not run.
+ void RunPendingTasks();
+
+ // Runs pending tasks until the queue is empty.
+ void RunUntilIdle();
+
+ protected:
+ virtual ~TestSimpleTaskRunner();
+
+ private:
+ ThreadChecker thread_checker_;
+ std::deque<TestPendingTask> pending_tasks_;
+
+ DISALLOW_COPY_AND_ASSIGN(TestSimpleTaskRunner);
+};
+
+} // namespace base
+
+#endif // BASE_TEST_TEST_SIMPLE_TASK_RUNNER_H_
diff --git a/chrome/browser/policy/cloud_policy_refresh_scheduler_unittest.cc b/chrome/browser/policy/cloud_policy_refresh_scheduler_unittest.cc
index 2d78f8e..71e3f1b0 100644
--- a/chrome/browser/policy/cloud_policy_refresh_scheduler_unittest.cc
+++ b/chrome/browser/policy/cloud_policy_refresh_scheduler_unittest.cc
@@ -7,10 +7,10 @@
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
+#include "base/test/test_simple_task_runner.h"
#include "chrome/browser/policy/cloud_policy_refresh_scheduler.h"
#include "chrome/browser/policy/mock_cloud_policy_client.h"
#include "chrome/browser/policy/mock_cloud_policy_store.h"
-#include "chrome/browser/policy/test_task_runner.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "policy/policy_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -32,7 +32,7 @@
class CloudPolicyRefreshSchedulerTest : public testing::Test {
protected:
CloudPolicyRefreshSchedulerTest()
- : task_runner_(new TestTaskRunner()),
+ : task_runner_(new base::TestSimpleTaskRunner()),
network_change_notifier_(net::NetworkChangeNotifier::CreateMock()) {}
virtual void SetUp() OVERRIDE {
@@ -48,12 +48,6 @@
last_refresh_ =
base::Time::UnixEpoch() +
base::TimeDelta::FromMilliseconds(store_.policy_->timestamp());
-
- // Keep track of when the last task was posted.
- EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, _))
- .WillRepeatedly(DoAll(SaveArg<1>(&last_callback_),
- SaveArg<2>(&last_delay_),
- Return(true)));
}
CloudPolicyRefreshScheduler* CreateRefreshScheduler() {
@@ -68,51 +62,55 @@
loop_.RunUntilIdle();
}
- void CheckTiming(int64 expected_delay_ms) {
+ base::TimeDelta GetLastDelay() const {
+ const std::deque<base::TestPendingTask>& pending_tasks =
+ task_runner_->GetPendingTasks();
+ return
+ pending_tasks.empty() ? base::TimeDelta() : pending_tasks.back().delay;
+ }
+
+ void CheckTiming(int64 expected_delay_ms) const {
+ EXPECT_FALSE(task_runner_->GetPendingTasks().empty());
base::Time now(base::Time::NowFromSystemTime());
base::TimeDelta expected_delay(
base::TimeDelta::FromMilliseconds(expected_delay_ms));
- EXPECT_GE(last_delay_, expected_delay - (now - last_refresh_));
- EXPECT_LE(last_delay_, expected_delay);
+ EXPECT_GE(GetLastDelay(), expected_delay - (now - last_refresh_));
+ EXPECT_LE(GetLastDelay(), expected_delay);
}
MessageLoop loop_;
MockCloudPolicyClient client_;
MockCloudPolicyStore store_;
- scoped_refptr<TestTaskRunner> task_runner_;
+ scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
scoped_ptr<net::NetworkChangeNotifier> network_change_notifier_;
// Base time for the refresh that the scheduler should be using.
base::Time last_refresh_;
-
- base::Closure last_callback_;
- base::TimeDelta last_delay_;
};
TEST_F(CloudPolicyRefreshSchedulerTest, InitialRefreshNoPolicy) {
store_.policy_.reset();
scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler());
- EXPECT_EQ(last_delay_, base::TimeDelta());
- ASSERT_FALSE(last_callback_.is_null());
+ EXPECT_FALSE(task_runner_->GetPendingTasks().empty());
+ EXPECT_EQ(GetLastDelay(), base::TimeDelta());
EXPECT_CALL(client_, FetchPolicy()).Times(1);
- last_callback_.Run();
+ task_runner_->RunUntilIdle();
}
TEST_F(CloudPolicyRefreshSchedulerTest, InitialRefreshUnmanaged) {
store_.policy_->set_state(em::PolicyData::UNMANAGED);
scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler());
CheckTiming(CloudPolicyRefreshScheduler::kUnmanagedRefreshDelayMs);
- ASSERT_FALSE(last_callback_.is_null());
EXPECT_CALL(client_, FetchPolicy()).Times(1);
- last_callback_.Run();
+ task_runner_->RunUntilIdle();
}
TEST_F(CloudPolicyRefreshSchedulerTest, InitialRefreshManagedNotYetFetched) {
scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler());
- EXPECT_EQ(last_delay_, base::TimeDelta());
- ASSERT_FALSE(last_callback_.is_null());
+ EXPECT_FALSE(task_runner_->GetPendingTasks().empty());
+ EXPECT_EQ(GetLastDelay(), base::TimeDelta());
EXPECT_CALL(client_, FetchPolicy()).Times(1);
- last_callback_.Run();
+ task_runner_->RunUntilIdle();
}
TEST_F(CloudPolicyRefreshSchedulerTest, InitialRefreshManagedAlreadyFetched) {
@@ -120,14 +118,12 @@
client_.SetPolicy(em::PolicyFetchResponse());
scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler());
CheckTiming(kPolicyRefreshRate);
- ASSERT_FALSE(last_callback_.is_null());
EXPECT_CALL(client_, FetchPolicy()).Times(1);
- last_callback_.Run();
+ task_runner_->RunUntilIdle();
}
TEST_F(CloudPolicyRefreshSchedulerTest, Unregistered) {
client_.SetDMToken("");
- EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, _)).Times(0);
scoped_ptr<CloudPolicyRefreshScheduler> scheduler(CreateRefreshScheduler());
client_.NotifyPolicyFetched();
client_.NotifyRegistrationStateChanged();
@@ -135,6 +131,7 @@
scheduler->SetRefreshDelay(12 * 60 * 60 * 1000);
store_.NotifyStoreLoaded();
store_.NotifyStoreError();
+ EXPECT_TRUE(task_runner_->GetPendingTasks().empty());
}
class CloudPolicyRefreshSchedulerSteadyStateTest
@@ -162,11 +159,12 @@
TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, OnRegistrationStateChanged) {
client_.SetDMToken("new_token");
client_.NotifyRegistrationStateChanged();
- EXPECT_EQ(last_delay_, base::TimeDelta());
+ EXPECT_EQ(GetLastDelay(), base::TimeDelta());
- EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, _)).Times(0);
+ task_runner_->ClearPendingTasks();
client_.SetDMToken("");
client_.NotifyRegistrationStateChanged();
+ EXPECT_TRUE(task_runner_->GetPendingTasks().empty());
}
TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, OnStoreLoaded) {
@@ -175,8 +173,9 @@
}
TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, OnStoreError) {
- EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, _)).Times(0);
+ task_runner_->ClearPendingTasks();
store_.NotifyStoreError();
+ EXPECT_TRUE(task_runner_->GetPendingTasks().empty());
}
TEST_F(CloudPolicyRefreshSchedulerSteadyStateTest, RefreshDelayChange) {
@@ -199,7 +198,7 @@
client_.SetStatus(DM_STATUS_REQUEST_FAILED);
NotifyIPAddressChanged();
- EXPECT_EQ(last_delay_, base::TimeDelta());
+ EXPECT_EQ(GetLastDelay(), base::TimeDelta());
}
struct ClientErrorTestParam {
@@ -244,8 +243,7 @@
TEST_P(CloudPolicyRefreshSchedulerClientErrorTest, OnClientError) {
client_.SetStatus(GetParam().client_error);
- last_delay_ = base::TimeDelta();
- last_callback_.Reset();
+ task_runner_->ClearPendingTasks();
// See whether the error triggers the right refresh delay.
int64 expected_delay_ms = GetParam().expected_delay_ms;
@@ -264,8 +262,8 @@
} while (GetParam().backoff_factor > 1 &&
expected_delay_ms <= kPolicyRefreshRate);
} else {
- EXPECT_EQ(base::TimeDelta(), last_delay_);
- EXPECT_TRUE(last_callback_.is_null());
+ EXPECT_EQ(base::TimeDelta(), GetLastDelay());
+ EXPECT_TRUE(task_runner_->GetPendingTasks().empty());
}
}
diff --git a/chrome/browser/policy/policy_statistics_collector_unittest.cc b/chrome/browser/policy/policy_statistics_collector_unittest.cc
index 915b6f15..c3d627d 100644
--- a/chrome/browser/policy/policy_statistics_collector_unittest.cc
+++ b/chrome/browser/policy/policy_statistics_collector_unittest.cc
@@ -8,13 +8,13 @@
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
+#include "base/test/test_simple_task_runner.h"
#include "base/time.h"
#include "base/values.h"
#include "chrome/browser/policy/mock_policy_service.h"
#include "chrome/browser/policy/policy_map.h"
#include "chrome/browser/policy/policy_statistics_collector.h"
#include "chrome/browser/policy/policy_types.h"
-#include "chrome/browser/policy/test_task_runner.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_pref_service.h"
@@ -56,7 +56,7 @@
PolicyStatisticsCollector::kStatisticsUpdateRate)),
test_policy_id1_(-1),
test_policy_id2_(-1),
- task_runner_(new TestTaskRunner) {
+ task_runner_(new base::TestSimpleTaskRunner()) {
}
virtual void SetUp() OVERRIDE {
@@ -94,6 +94,14 @@
base::Value::CreateBooleanValue(true));
}
+ base::TimeDelta GetFirstDelay() const {
+ if (task_runner_->GetPendingTasks().empty()) {
+ ADD_FAILURE();
+ return base::TimeDelta();
+ }
+ return task_runner_->GetPendingTasks().front().delay;
+ }
+
const base::TimeDelta update_delay_;
int test_policy_id1_;
@@ -105,7 +113,7 @@
MockPolicyService policy_service_;
PolicyMap policy_map_;
- scoped_refptr<TestTaskRunner> task_runner_;
+ scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
scoped_ptr<TestPolicyStatisticsCollector> policy_statistics_collector_;
};
@@ -117,10 +125,10 @@
EXPECT_CALL(*policy_statistics_collector_.get(),
RecordPolicyUse(test_policy_id1_));
- EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, update_delay_)).
- WillOnce(Return(true));
policy_statistics_collector_->Initialize();
+ EXPECT_EQ(1u, task_runner_->GetPendingTasks().size());
+ EXPECT_EQ(update_delay_, GetFirstDelay());
}
TEST_F(PolicyStatisticsCollectorTest, CollectPendingVeryOld) {
@@ -132,10 +140,10 @@
EXPECT_CALL(*policy_statistics_collector_.get(),
RecordPolicyUse(test_policy_id1_));
- EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, update_delay_)).
- WillOnce(Return(true));
policy_statistics_collector_->Initialize();
+ EXPECT_EQ(1u, task_runner_->GetPendingTasks().size());
+ EXPECT_EQ(update_delay_, GetFirstDelay());
}
TEST_F(PolicyStatisticsCollectorTest, CollectLater) {
@@ -144,10 +152,9 @@
prefs_.SetInt64(prefs::kLastPolicyStatisticsUpdate,
(base::Time::Now() - update_delay_ / 2).ToInternalValue());
- EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, Lt(update_delay_))).
- WillOnce(Return(true));
-
policy_statistics_collector_->Initialize();
+ EXPECT_EQ(1u, task_runner_->GetPendingTasks().size());
+ EXPECT_LT(GetFirstDelay(), update_delay_);
}
TEST_F(PolicyStatisticsCollectorTest, MultiplePolicies) {
@@ -161,10 +168,9 @@
RecordPolicyUse(test_policy_id1_));
EXPECT_CALL(*policy_statistics_collector_.get(),
RecordPolicyUse(test_policy_id2_));
- EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, _)).
- WillOnce(Return(true));
policy_statistics_collector_->Initialize();
+ EXPECT_EQ(1u, task_runner_->GetPendingTasks().size());
}
} // namespace policy
diff --git a/chrome/browser/policy/test_task_runner.cc b/chrome/browser/policy/test_task_runner.cc
deleted file mode 100644
index 85727e7e..0000000
--- a/chrome/browser/policy/test_task_runner.cc
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "chrome/browser/policy/test_task_runner.h"
-
-namespace policy {
-
-TestTaskRunner::TestTaskRunner() {
-}
-
-TestTaskRunner::~TestTaskRunner() {
-}
-
-} // namespace policy
diff --git a/chrome/browser/policy/test_task_runner.h b/chrome/browser/policy/test_task_runner.h
deleted file mode 100644
index 8b19778..0000000
--- a/chrome/browser/policy/test_task_runner.h
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef CHROME_BROWSER_POLICY_TEST_TASK_RUNNER_H_
-#define CHROME_BROWSER_POLICY_TEST_TASK_RUNNER_H_
-
-#include "base/basictypes.h"
-#include "base/callback.h"
-#include "base/location.h"
-#include "base/single_thread_task_runner.h"
-#include "testing/gmock/include/gmock/gmock.h"
-
-namespace policy {
-
-class TestTaskRunner : public base::TaskRunner {
- public:
- TestTaskRunner();
-
- virtual bool RunsTasksOnCurrentThread() const OVERRIDE { return true; }
- MOCK_METHOD3(PostDelayedTask, bool(const tracked_objects::Location&,
- const base::Closure&,
- base::TimeDelta));
-
- protected:
- virtual ~TestTaskRunner();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TestTaskRunner);
-};
-
-} // namespace policy
-
-#endif // CHROME_BROWSER_POLICY_TEST_TASK_RUNNER_H_
diff --git a/chrome/browser/safe_browsing/protocol_manager_unittest.cc b/chrome/browser/safe_browsing/protocol_manager_unittest.cc
index aad096d..8db97706 100644
--- a/chrome/browser/safe_browsing/protocol_manager_unittest.cc
+++ b/chrome/browser/safe_browsing/protocol_manager_unittest.cc
@@ -3,9 +3,8 @@
// found in the LICENSE file.
//
-#include "base/logging.h"
-#include "base/single_thread_task_runner.h"
#include "base/stringprintf.h"
+#include "base/test/test_simple_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "base/time.h"
#include "chrome/browser/safe_browsing/protocol_manager.h"
@@ -67,50 +66,50 @@
TEST_F(SafeBrowsingProtocolManagerTest, TestBackOffTimes) {
scoped_ptr<SafeBrowsingProtocolManager> pm(CreateProtocolManager(NULL));
- pm->next_update_interval_ = base::TimeDelta::FromSeconds(1800);
+ pm->next_update_interval_ = TimeDelta::FromSeconds(1800);
ASSERT_TRUE(pm->back_off_fuzz_ >= 0.0 && pm->back_off_fuzz_ <= 1.0);
- base::TimeDelta next;
+ TimeDelta next;
// No errors received so far.
next = pm->GetNextUpdateInterval(false);
- EXPECT_EQ(next, base::TimeDelta::FromSeconds(1800));
+ EXPECT_EQ(next, TimeDelta::FromSeconds(1800));
// 1 error.
next = pm->GetNextUpdateInterval(true);
- EXPECT_EQ(next, base::TimeDelta::FromSeconds(60));
+ EXPECT_EQ(next, TimeDelta::FromSeconds(60));
// 2 errors.
next = pm->GetNextUpdateInterval(true);
- EXPECT_TRUE(next >= base::TimeDelta::FromMinutes(30) &&
- next <= base::TimeDelta::FromMinutes(60));
+ EXPECT_TRUE(next >= TimeDelta::FromMinutes(30) &&
+ next <= TimeDelta::FromMinutes(60));
// 3 errors.
next = pm->GetNextUpdateInterval(true);
- EXPECT_TRUE(next >= base::TimeDelta::FromMinutes(60) &&
- next <= base::TimeDelta::FromMinutes(120));
+ EXPECT_TRUE(next >= TimeDelta::FromMinutes(60) &&
+ next <= TimeDelta::FromMinutes(120));
// 4 errors.
next = pm->GetNextUpdateInterval(true);
- EXPECT_TRUE(next >= base::TimeDelta::FromMinutes(120) &&
- next <= base::TimeDelta::FromMinutes(240));
+ EXPECT_TRUE(next >= TimeDelta::FromMinutes(120) &&
+ next <= TimeDelta::FromMinutes(240));
// 5 errors.
next = pm->GetNextUpdateInterval(true);
- EXPECT_TRUE(next >= base::TimeDelta::FromMinutes(240) &&
- next <= base::TimeDelta::FromMinutes(480));
+ EXPECT_TRUE(next >= TimeDelta::FromMinutes(240) &&
+ next <= TimeDelta::FromMinutes(480));
// 6 errors, reached max backoff.
next = pm->GetNextUpdateInterval(true);
- EXPECT_EQ(next, base::TimeDelta::FromMinutes(480));
+ EXPECT_EQ(next, TimeDelta::FromMinutes(480));
// 7 errors.
next = pm->GetNextUpdateInterval(true);
- EXPECT_EQ(next, base::TimeDelta::FromMinutes(480));
+ EXPECT_EQ(next, TimeDelta::FromMinutes(480));
// Received a successful response.
next = pm->GetNextUpdateInterval(false);
- EXPECT_EQ(next, base::TimeDelta::FromSeconds(1800));
+ EXPECT_EQ(next, TimeDelta::FromSeconds(1800));
}
TEST_F(SafeBrowsingProtocolManagerTest, TestChunkStrings) {
@@ -257,51 +256,6 @@
MOCK_METHOD1(DeleteChunks, void(std::vector<SBChunkDelete>*));
};
-// ImmediateSingleThreadTaskRunner will ignore delayed times for tasks.
-// This is primarily used to run the timer tasks immediately, and prevent
-// the need for constructing a MessageLoop.
-class ImmediateSingleThreadTaskRunner : public base::SingleThreadTaskRunner {
- public:
- virtual bool RunsTasksOnCurrentThread() const OVERRIDE {
- return true;
- }
-
- virtual bool PostDelayedTask(const tracked_objects::Location& from_here,
- const base::Closure& task,
- base::TimeDelta delay) OVERRIDE {
- task_list_.push_back(task);
- return true;
- }
-
- virtual bool PostNonNestableDelayedTask(
- const tracked_objects::Location& from_here,
- const base::Closure& task,
- base::TimeDelta delay) OVERRIDE {
- NOTREACHED();
- return false;
- }
-
- void RunTasks() {
- // Pop stuff off and run them. All on same thread so no locking need.
- TaskList task_list;
- task_list.swap(task_list_);
- for (TaskList::iterator it = task_list.begin();
- it != task_list.end();
- ++it) {
- it->Run();
- }
- }
-
- size_t NumTasks() const {
- return task_list_.size();
- }
-
- private:
- typedef std::deque<base::Closure> TaskList;
- virtual ~ImmediateSingleThreadTaskRunner() {}
- TaskList task_list_;
-};
-
// |InvokeGetChunksCallback| is required because GMock's InvokeArgument action
// expects to use operator(), and a Callback only provides Run().
// TODO(cbentzel): Use ACTION or ACTION_TEMPLATE instead?
@@ -317,8 +271,8 @@
// Tests that the Update protocol will be skipped if there are problems
// accessing the database.
TEST_F(SafeBrowsingProtocolManagerTest, ProblemAccessingDatabase) {
- scoped_refptr<ImmediateSingleThreadTaskRunner> runner(
- new ImmediateSingleThreadTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> runner(
+ new base::TestSimpleTaskRunner());
base::ThreadTaskRunnerHandle runner_handler(runner);
testing::StrictMock<MockProtocolDelegate> test_delegate;
@@ -332,16 +286,16 @@
scoped_ptr<SafeBrowsingProtocolManager> pm(
CreateProtocolManager(&test_delegate));
- pm->ForceScheduleNextUpdate(base::TimeDelta());
- runner->RunTasks();
+ pm->ForceScheduleNextUpdate(TimeDelta());
+ runner->RunPendingTasks();
}
// Tests the contents of the POST body when there are contents in the
// local database. This is not exhaustive, as the actual list formatting
// is covered by SafeBrowsingProtocolManagerTest.TestChunkStrings.
TEST_F(SafeBrowsingProtocolManagerTest, ExistingDatabase) {
- scoped_refptr<ImmediateSingleThreadTaskRunner> runner(
- new ImmediateSingleThreadTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> runner(
+ new base::TestSimpleTaskRunner());
base::ThreadTaskRunnerHandle runner_handler(runner);
net::TestURLFetcherFactory url_fetcher_factory;
@@ -367,8 +321,8 @@
CreateProtocolManager(&test_delegate));
// Kick off initialization. This returns chunks from the DB synchronously.
- pm->ForceScheduleNextUpdate(base::TimeDelta());
- runner->RunTasks();
+ pm->ForceScheduleNextUpdate(TimeDelta());
+ runner->RunPendingTasks();
// We should have an URLFetcher at this point in time.
net::TestURLFetcher* url_fetcher = url_fetcher_factory.GetFetcherByID(0);
@@ -385,8 +339,8 @@
// Tests what happens when there is a response with no chunks.
TEST_F(SafeBrowsingProtocolManagerTest, UpdateResponseEmptyBody) {
- scoped_refptr<ImmediateSingleThreadTaskRunner> runner(
- new ImmediateSingleThreadTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> runner(
+ new base::TestSimpleTaskRunner());
base::ThreadTaskRunnerHandle runner_handler(runner);
net::TestURLFetcherFactory url_fetcher_factory;
@@ -402,8 +356,8 @@
CreateProtocolManager(&test_delegate));
// Kick off initialization. This returns chunks from the DB synchronously.
- pm->ForceScheduleNextUpdate(base::TimeDelta());
- runner->RunTasks();
+ pm->ForceScheduleNextUpdate(TimeDelta());
+ runner->RunPendingTasks();
// We should have an URLFetcher at this point in time.
net::TestURLFetcher* url_fetcher = url_fetcher_factory.GetFetcherByID(0);
@@ -417,8 +371,8 @@
}
TEST_F(SafeBrowsingProtocolManagerTest, UpdateResponseBadBody) {
- scoped_refptr<ImmediateSingleThreadTaskRunner> runner(
- new ImmediateSingleThreadTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> runner(
+ new base::TestSimpleTaskRunner());
base::ThreadTaskRunnerHandle runner_handler(runner);
net::TestURLFetcherFactory url_fetcher_factory;
@@ -434,8 +388,8 @@
CreateProtocolManager(&test_delegate));
// Kick off initialization. This returns chunks from the DB synchronously.
- pm->ForceScheduleNextUpdate(base::TimeDelta());
- runner->RunTasks();
+ pm->ForceScheduleNextUpdate(TimeDelta());
+ runner->RunPendingTasks();
// We should have an URLFetcher at this point in time.
net::TestURLFetcher* url_fetcher = url_fetcher_factory.GetFetcherByID(0);
@@ -450,8 +404,8 @@
// Tests what happens when there is an error in the update response.
TEST_F(SafeBrowsingProtocolManagerTest, UpdateResponseHttpError) {
- scoped_refptr<ImmediateSingleThreadTaskRunner> runner(
- new ImmediateSingleThreadTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> runner(
+ new base::TestSimpleTaskRunner());
base::ThreadTaskRunnerHandle runner_handler(runner);
net::TestURLFetcherFactory url_fetcher_factory;
@@ -467,8 +421,8 @@
CreateProtocolManager(&test_delegate));
// Kick off initialization. This returns chunks from the DB synchronously.
- pm->ForceScheduleNextUpdate(base::TimeDelta());
- runner->RunTasks();
+ pm->ForceScheduleNextUpdate(TimeDelta());
+ runner->RunPendingTasks();
// We should have an URLFetcher at this point in time.
net::TestURLFetcher* url_fetcher = url_fetcher_factory.GetFetcherByID(0);
@@ -483,8 +437,8 @@
// Tests what happens when there is an error with the connection.
TEST_F(SafeBrowsingProtocolManagerTest, UpdateResponseConnectionError) {
- scoped_refptr<ImmediateSingleThreadTaskRunner> runner(
- new ImmediateSingleThreadTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> runner(
+ new base::TestSimpleTaskRunner());
base::ThreadTaskRunnerHandle runner_handler(runner);
net::TestURLFetcherFactory url_fetcher_factory;
@@ -500,8 +454,8 @@
CreateProtocolManager(&test_delegate));
// Kick off initialization. This returns chunks from the DB synchronously.
- pm->ForceScheduleNextUpdate(base::TimeDelta());
- runner->RunTasks();
+ pm->ForceScheduleNextUpdate(TimeDelta());
+ runner->RunPendingTasks();
// We should have an URLFetcher at this point in time.
net::TestURLFetcher* url_fetcher = url_fetcher_factory.GetFetcherByID(0);
@@ -515,8 +469,8 @@
// Tests what happens when there is a timeout before an update response.
TEST_F(SafeBrowsingProtocolManagerTest, UpdateResponseTimeout) {
- scoped_refptr<ImmediateSingleThreadTaskRunner> runner(
- new ImmediateSingleThreadTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> runner(
+ new base::TestSimpleTaskRunner());
base::ThreadTaskRunnerHandle runner_handler(runner);
net::TestURLFetcherFactory url_fetcher_factory;
@@ -532,8 +486,8 @@
CreateProtocolManager(&test_delegate));
// Kick off initialization. This returns chunks from the DB synchronously.
- pm->ForceScheduleNextUpdate(base::TimeDelta());
- runner->RunTasks();
+ pm->ForceScheduleNextUpdate(TimeDelta());
+ runner->RunPendingTasks();
// We should have an URLFetcher at this point in time.
net::TestURLFetcher* url_fetcher = url_fetcher_factory.GetFetcherByID(0);
@@ -541,13 +495,13 @@
// The first time RunTasks is called above, the update timeout timer is not
// handled. This call of RunTasks will handle the update.
- runner->RunTasks();
+ runner->RunPendingTasks();
}
// Tests what happens when there is a reset command in the response.
TEST_F(SafeBrowsingProtocolManagerTest, UpdateResponseReset) {
- scoped_refptr<ImmediateSingleThreadTaskRunner> runner(
- new ImmediateSingleThreadTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> runner(
+ new base::TestSimpleTaskRunner());
base::ThreadTaskRunnerHandle runner_handler(runner);
net::TestURLFetcherFactory url_fetcher_factory;
@@ -564,8 +518,8 @@
CreateProtocolManager(&test_delegate));
// Kick off initialization. This returns chunks from the DB synchronously.
- pm->ForceScheduleNextUpdate(base::TimeDelta());
- runner->RunTasks();
+ pm->ForceScheduleNextUpdate(TimeDelta());
+ runner->RunPendingTasks();
// We should have an URLFetcher at this point in time.
net::TestURLFetcher* url_fetcher = url_fetcher_factory.GetFetcherByID(0);
diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi
index 73b5ef8..61c68ee5 100644
--- a/chrome/chrome_tests_unit.gypi
+++ b/chrome/chrome_tests_unit.gypi
@@ -936,8 +936,6 @@
'browser/policy/policy_service_impl_unittest.cc',
'browser/policy/policy_statistics_collector_unittest.cc',
'browser/policy/proxy_policy_provider_unittest.cc',
- 'browser/policy/test_task_runner.cc',
- 'browser/policy/test_task_runner.h',
'browser/policy/testing_cloud_policy_subsystem.cc',
'browser/policy/testing_cloud_policy_subsystem.h',
'browser/policy/testing_policy_url_fetcher_factory.cc',
diff --git a/chrome/common/cancelable_task_tracker_unittest.cc b/chrome/common/cancelable_task_tracker_unittest.cc
index ca62151..8b79ee90 100644
--- a/chrome/common/cancelable_task_tracker_unittest.cc
+++ b/chrome/common/cancelable_task_tracker_unittest.cc
@@ -9,59 +9,18 @@
#include "base/bind.h"
#include "base/bind_helpers.h"
-#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/run_loop.h"
-#include "base/task_runner.h"
+#include "base/test/test_simple_task_runner.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
-// Test TaskRunner implementation that simply stores posted tasks in a
-// queue.
-//
-// TOOD(akalin): Pull this out into its own file once something else
-// needs it.
-class FakeNonThreadSafeTaskRunner : public base::TaskRunner {
- public:
- // base::TaskRunner implementation.
- // Stores posted tasks in a FIFO, ignoring |delay|.
- virtual bool PostDelayedTask(const tracked_objects::Location& from_here,
- const base::Closure& task,
- base::TimeDelta delay) OVERRIDE {
- tasks_.push_back(task);
- return true;
- }
-
- virtual bool RunsTasksOnCurrentThread() const OVERRIDE {
- return true;
- }
-
- size_t GetPendingTaskCount() const {
- return tasks_.size();
- }
-
- void RunUntilIdle() {
- // Use a while loop since a task may post more tasks.
- while (!tasks_.empty()) {
- base::Closure task = tasks_.front();
- tasks_.pop_front();
- task.Run();
- }
- }
-
- protected:
- virtual ~FakeNonThreadSafeTaskRunner() {}
-
- private:
- std::deque<base::Closure> tasks_;
-};
-
class CancelableTaskTrackerTest : public testing::Test {
protected:
virtual ~CancelableTaskTrackerTest() {
@@ -154,33 +113,33 @@
// Post a task with the task tracker but cancel it before running the
// task runner. The task should not run.
TEST_F(CancelableTaskTrackerTest, CancelPostedTask) {
- scoped_refptr<FakeNonThreadSafeTaskRunner> fake_task_runner(
- new FakeNonThreadSafeTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> test_task_runner(
+ new base::TestSimpleTaskRunner());
CancelableTaskTracker::TaskId task_id =
task_tracker_.PostTask(
- fake_task_runner.get(),
+ test_task_runner.get(),
FROM_HERE,
MakeExpectedNotRunClosure(FROM_HERE));
EXPECT_NE(CancelableTaskTracker::kBadTaskId, task_id);
- EXPECT_EQ(1U, fake_task_runner->GetPendingTaskCount());
+ EXPECT_EQ(1U, test_task_runner->GetPendingTasks().size());
task_tracker_.TryCancel(task_id);
- fake_task_runner->RunUntilIdle();
+ test_task_runner->RunUntilIdle();
}
// Post a task with reply with the task tracker and cancel it before
// running the task runner. Neither the task nor the reply should
// run.
TEST_F(CancelableTaskTrackerTest, CancelPostedTaskAndReply) {
- scoped_refptr<FakeNonThreadSafeTaskRunner> fake_task_runner(
- new FakeNonThreadSafeTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> test_task_runner(
+ new base::TestSimpleTaskRunner());
CancelableTaskTracker::TaskId task_id =
task_tracker_.PostTaskAndReply(
- fake_task_runner.get(),
+ test_task_runner.get(),
FROM_HERE,
MakeExpectedNotRunClosure(FROM_HERE),
MakeExpectedNotRunClosure(FROM_HERE));
@@ -188,25 +147,25 @@
task_tracker_.TryCancel(task_id);
- fake_task_runner->RunUntilIdle();
+ test_task_runner->RunUntilIdle();
}
// Post a task with reply with the task tracker and cancel it after
// running the task runner but before running the current message
// loop. The task should run but the reply should not.
TEST_F(CancelableTaskTrackerTest, CancelReply) {
- scoped_refptr<FakeNonThreadSafeTaskRunner> fake_task_runner(
- new FakeNonThreadSafeTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> test_task_runner(
+ new base::TestSimpleTaskRunner());
CancelableTaskTracker::TaskId task_id =
task_tracker_.PostTaskAndReply(
- fake_task_runner.get(),
+ test_task_runner.get(),
FROM_HERE,
MakeExpectedRunClosure(FROM_HERE),
MakeExpectedNotRunClosure(FROM_HERE));
EXPECT_NE(CancelableTaskTracker::kBadTaskId, task_id);
- fake_task_runner->RunUntilIdle();
+ test_task_runner->RunUntilIdle();
task_tracker_.TryCancel(task_id);
}
@@ -268,18 +227,18 @@
// reply should run and the "is canceled" callback should return
// true.
TEST_F(CancelableTaskTrackerTest, CancelAll) {
- scoped_refptr<FakeNonThreadSafeTaskRunner> fake_task_runner(
- new FakeNonThreadSafeTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> test_task_runner(
+ new base::TestSimpleTaskRunner());
ignore_result(
task_tracker_.PostTask(
- fake_task_runner,
+ test_task_runner,
FROM_HERE,
MakeExpectedNotRunClosure(FROM_HERE)));
ignore_result(
task_tracker_.PostTaskAndReply(
- fake_task_runner,
+ test_task_runner,
FROM_HERE,
MakeExpectedNotRunClosure(FROM_HERE),
MakeExpectedNotRunClosure(FROM_HERE)));
@@ -289,7 +248,7 @@
task_tracker_.TryCancelAll();
- fake_task_runner->RunUntilIdle();
+ test_task_runner->RunUntilIdle();
RunCurrentLoopUntilIdle();
@@ -301,8 +260,8 @@
// reply should run and the "is canceled" callback should return
// true.
TEST_F(CancelableTaskTrackerTest, DestructionCancelsAll) {
- scoped_refptr<FakeNonThreadSafeTaskRunner> fake_task_runner(
- new FakeNonThreadSafeTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> test_task_runner(
+ new base::TestSimpleTaskRunner());
CancelableTaskTracker::IsCanceledCallback is_canceled;
@@ -312,13 +271,13 @@
ignore_result(
task_tracker.PostTask(
- fake_task_runner,
+ test_task_runner,
FROM_HERE,
MakeExpectedNotRunClosure(FROM_HERE)));
ignore_result(
task_tracker.PostTaskAndReply(
- fake_task_runner,
+ test_task_runner,
FROM_HERE,
MakeExpectedNotRunClosure(FROM_HERE),
MakeExpectedNotRunClosure(FROM_HERE)));
@@ -326,7 +285,7 @@
ignore_result(task_tracker_.NewTrackedTaskId(&is_canceled));
}
- fake_task_runner->RunUntilIdle();
+ test_task_runner->RunUntilIdle();
RunCurrentLoopUntilIdle();
@@ -337,20 +296,20 @@
// from when the task is posted until the (do-nothing) reply task is
// flushed.
TEST_F(CancelableTaskTrackerTest, HasTrackedTasksPost) {
- scoped_refptr<FakeNonThreadSafeTaskRunner> fake_task_runner(
- new FakeNonThreadSafeTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> test_task_runner(
+ new base::TestSimpleTaskRunner());
EXPECT_FALSE(task_tracker_.HasTrackedTasks());
ignore_result(
task_tracker_.PostTask(
- fake_task_runner,
+ test_task_runner,
FROM_HERE,
MakeExpectedNotRunClosure(FROM_HERE)));
task_tracker_.TryCancelAll();
- fake_task_runner->RunUntilIdle();
+ test_task_runner->RunUntilIdle();
EXPECT_TRUE(task_tracker_.HasTrackedTasks());
@@ -362,21 +321,21 @@
// Post a task with a reply and cancel it. HasTrackedTasks() should
// return true from when the task is posted until it is canceled.
TEST_F(CancelableTaskTrackerTest, HasTrackedTasksPostWithReply) {
- scoped_refptr<FakeNonThreadSafeTaskRunner> fake_task_runner(
- new FakeNonThreadSafeTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> test_task_runner(
+ new base::TestSimpleTaskRunner());
EXPECT_FALSE(task_tracker_.HasTrackedTasks());
ignore_result(
task_tracker_.PostTaskAndReply(
- fake_task_runner,
+ test_task_runner,
FROM_HERE,
MakeExpectedNotRunClosure(FROM_HERE),
MakeExpectedNotRunClosure(FROM_HERE)));
task_tracker_.TryCancelAll();
- fake_task_runner->RunUntilIdle();
+ test_task_runner->RunUntilIdle();
EXPECT_TRUE(task_tracker_.HasTrackedTasks());
@@ -438,8 +397,8 @@
void PostDoNothingTask(CancelableTaskTracker* task_tracker) {
ignore_result(
task_tracker->PostTask(
- scoped_refptr<FakeNonThreadSafeTaskRunner>(
- new FakeNonThreadSafeTaskRunner()),
+ scoped_refptr<base::TestSimpleTaskRunner>(
+ new base::TestSimpleTaskRunner()),
FROM_HERE, base::Bind(&base::DoNothing)));
}
@@ -460,15 +419,15 @@
}
TEST_F(CancelableTaskTrackerDeathTest, CancelOnDifferentThread) {
- scoped_refptr<FakeNonThreadSafeTaskRunner> fake_task_runner(
- new FakeNonThreadSafeTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> test_task_runner(
+ new base::TestSimpleTaskRunner());
base::Thread bad_thread("bad thread");
ASSERT_TRUE(bad_thread.Start());
CancelableTaskTracker::TaskId task_id =
task_tracker_.PostTask(
- fake_task_runner.get(),
+ test_task_runner.get(),
FROM_HERE,
base::Bind(&base::DoNothing));
EXPECT_NE(CancelableTaskTracker::kBadTaskId, task_id);
@@ -479,19 +438,19 @@
base::Unretained(&task_tracker_),
base::Bind(&TryCancel, task_id)));
- fake_task_runner->RunUntilIdle();
+ test_task_runner->RunUntilIdle();
}
TEST_F(CancelableTaskTrackerDeathTest, CancelAllOnDifferentThread) {
- scoped_refptr<FakeNonThreadSafeTaskRunner> fake_task_runner(
- new FakeNonThreadSafeTaskRunner());
+ scoped_refptr<base::TestSimpleTaskRunner> test_task_runner(
+ new base::TestSimpleTaskRunner());
base::Thread bad_thread("bad thread");
ASSERT_TRUE(bad_thread.Start());
CancelableTaskTracker::TaskId task_id =
task_tracker_.PostTask(
- fake_task_runner.get(),
+ test_task_runner.get(),
FROM_HERE,
base::Bind(&base::DoNothing));
EXPECT_NE(CancelableTaskTracker::kBadTaskId, task_id);
@@ -502,7 +461,7 @@
base::Unretained(&task_tracker_),
base::Bind(&CancelableTaskTracker::TryCancelAll)));
- fake_task_runner->RunUntilIdle();
+ test_task_runner->RunUntilIdle();
}
} // namespace
diff --git a/content/browser/download/byte_stream_unittest.cc b/content/browser/download/byte_stream_unittest.cc
index 3f235f2..5422a8bd 100644
--- a/content/browser/download/byte_stream_unittest.cc
+++ b/content/browser/download/byte_stream_unittest.cc
@@ -8,49 +8,15 @@
#include "base/bind.h"
#include "base/callback.h"
-#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
-#include "base/task_runner.h"
+#include "base/test/test_simple_task_runner.h"
#include "net/base/io_buffer.h"
-#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-using ::testing::_;
-using ::testing::Return;
-using ::testing::SaveArg;
-using ::testing::StrictMock;
-
-namespace tracked_objects {
-class Location;
-}
-
namespace content {
namespace {
-class MockTaskRunner : public base::SequencedTaskRunner {
- public:
- MockTaskRunner();
-
- // TaskRunner functions.
- MOCK_METHOD3(PostDelayedTask, bool(const tracked_objects::Location&,
- const base::Closure&, base::TimeDelta));
-
- MOCK_METHOD3(PostNonNestableDelayedTask, bool(
- const tracked_objects::Location&,
- const base::Closure&,
- base::TimeDelta));
-
- MOCK_CONST_METHOD0(RunsTasksOnCurrentThread, bool());
-
- protected:
- ~MockTaskRunner();
-};
-
-MockTaskRunner::MockTaskRunner() { }
-
-MockTaskRunner::~MockTaskRunner() { }
-
void CountCallbacks(int* counter) {
++*counter;
}
@@ -303,9 +269,8 @@
// Confirm that callbacks on the sink side are triggered when they should be.
TEST_F(ByteStreamTest, ByteStream_SinkCallback) {
- scoped_refptr<MockTaskRunner> task_runner(new StrictMock<MockTaskRunner>());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
+ scoped_refptr<base::TestSimpleTaskRunner> task_runner(
+ new base::TestSimpleTaskRunner());
scoped_ptr<ByteStreamWriter> byte_stream_input;
scoped_ptr<ByteStreamReader> byte_stream_output;
@@ -315,7 +280,6 @@
scoped_refptr<net::IOBuffer> output_io_buffer;
size_t output_length;
- base::Closure intermediate_callback;
// Note that the specifics of when the callbacks are called with regard
// to how much data is pushed onto the stream is not (currently) part
@@ -328,19 +292,12 @@
int num_callbacks = 0;
byte_stream_output->RegisterCallback(
base::Bind(CountCallbacks, &num_callbacks));
- EXPECT_CALL(*task_runner.get(), PostDelayedTask(_, _, base::TimeDelta()))
- .WillOnce(DoAll(SaveArg<1>(&intermediate_callback),
- Return(true)));
EXPECT_TRUE(Write(byte_stream_input.get(), 4000));
message_loop_.RunUntilIdle();
- // Check callback results match expectations.
- ::testing::Mock::VerifyAndClearExpectations(task_runner.get());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
EXPECT_EQ(0, num_callbacks);
- intermediate_callback.Run();
+ task_runner->RunUntilIdle();
EXPECT_EQ(1, num_callbacks);
// Check data and stream state.
@@ -364,9 +321,8 @@
// Confirm that callbacks on the source side are triggered when they should
// be.
TEST_F(ByteStreamTest, ByteStream_SourceCallback) {
- scoped_refptr<MockTaskRunner> task_runner(new StrictMock<MockTaskRunner>());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
+ scoped_refptr<base::TestSimpleTaskRunner> task_runner(
+ new base::TestSimpleTaskRunner());
scoped_ptr<ByteStreamWriter> byte_stream_input;
scoped_ptr<ByteStreamReader> byte_stream_output;
@@ -376,7 +332,6 @@
scoped_refptr<net::IOBuffer> output_io_buffer;
size_t output_length;
- base::Closure intermediate_callback;
// Note that the specifics of when the callbacks are called with regard
// to how much data is pulled from the stream is not (currently) part
@@ -386,7 +341,7 @@
// Confirm callback called when about 33% space available, and not
// at other transitions.
- // Setup expectations and add data.
+ // Add data.
int num_callbacks = 0;
byte_stream_input->RegisterCallback(
base::Bind(CountCallbacks, &num_callbacks));
@@ -401,39 +356,25 @@
byte_stream_output->Read(&output_io_buffer, &output_length));
EXPECT_TRUE(ValidateIOBuffer(output_io_buffer, output_length));
- // Setup expectations.
- EXPECT_CALL(*task_runner.get(), PostDelayedTask(_, _, base::TimeDelta()))
- .WillOnce(DoAll(SaveArg<1>(&intermediate_callback),
- Return(true)));
-
// Grab data, triggering callback. Recorded on dispatch, but doesn't
// happen because it's caught by the mock.
EXPECT_EQ(ByteStreamReader::STREAM_HAS_DATA,
byte_stream_output->Read(&output_io_buffer, &output_length));
- ::testing::Mock::VerifyAndClearExpectations(task_runner.get());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
EXPECT_TRUE(ValidateIOBuffer(output_io_buffer, output_length));
// Confirm that the callback passed to the mock does what we expect.
EXPECT_EQ(0, num_callbacks);
- intermediate_callback.Run();
+ task_runner->RunUntilIdle();
EXPECT_EQ(1, num_callbacks);
// Same drill with final buffer.
- EXPECT_CALL(*task_runner.get(), PostDelayedTask(_, _, base::TimeDelta()))
- .WillOnce(DoAll(SaveArg<1>(&intermediate_callback),
- Return(true)));
EXPECT_EQ(ByteStreamReader::STREAM_HAS_DATA,
byte_stream_output->Read(&output_io_buffer, &output_length));
- ::testing::Mock::VerifyAndClearExpectations(task_runner.get());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
EXPECT_TRUE(ValidateIOBuffer(output_io_buffer, output_length));
EXPECT_EQ(ByteStreamReader::STREAM_EMPTY,
byte_stream_output->Read(&output_io_buffer, &output_length));
EXPECT_EQ(1, num_callbacks);
- intermediate_callback.Run();
+ task_runner->RunUntilIdle();
// Should have updated the internal structures but not called the
// callback.
EXPECT_EQ(1, num_callbacks);
@@ -442,9 +383,8 @@
// Confirm that racing a change to a sink callback with a post results
// in the new callback being called.
TEST_F(ByteStreamTest, ByteStream_SinkInterrupt) {
- scoped_refptr<MockTaskRunner> task_runner(new StrictMock<MockTaskRunner>());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
+ scoped_refptr<base::TestSimpleTaskRunner> task_runner(
+ new base::TestSimpleTaskRunner());
scoped_ptr<ByteStreamWriter> byte_stream_input;
scoped_ptr<ByteStreamReader> byte_stream_output;
@@ -456,13 +396,10 @@
size_t output_length;
base::Closure intermediate_callback;
- // Setup expectations and record initial state.
+ // Record initial state.
int num_callbacks = 0;
byte_stream_output->RegisterCallback(
base::Bind(CountCallbacks, &num_callbacks));
- EXPECT_CALL(*task_runner.get(), PostDelayedTask(_, _, base::TimeDelta()))
- .WillOnce(DoAll(SaveArg<1>(&intermediate_callback),
- Return(true)));
// Add data, and pass it across.
EXPECT_TRUE(Write(byte_stream_input.get(), 4000));
@@ -470,9 +407,6 @@
// The task runner should have been hit, but the callback count
// isn't changed until we actually run the callback.
- ::testing::Mock::VerifyAndClearExpectations(task_runner.get());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
EXPECT_EQ(0, num_callbacks);
// If we change the callback now, the new one should be run
@@ -480,7 +414,7 @@
int num_alt_callbacks = 0;
byte_stream_output->RegisterCallback(
base::Bind(CountCallbacks, &num_alt_callbacks));
- intermediate_callback.Run();
+ task_runner->RunUntilIdle();
EXPECT_EQ(0, num_callbacks);
EXPECT_EQ(1, num_alt_callbacks);
@@ -496,9 +430,8 @@
// Confirm that racing a change to a source callback with a post results
// in the new callback being called.
TEST_F(ByteStreamTest, ByteStream_SourceInterrupt) {
- scoped_refptr<MockTaskRunner> task_runner(new StrictMock<MockTaskRunner>());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
+ scoped_refptr<base::TestSimpleTaskRunner> task_runner(
+ new base::TestSimpleTaskRunner());
scoped_ptr<ByteStreamWriter> byte_stream_input;
scoped_ptr<ByteStreamReader> byte_stream_output;
@@ -510,7 +443,7 @@
size_t output_length;
base::Closure intermediate_callback;
- // Setup state for test and record initiali expectations
+ // Setup state for test.
int num_callbacks = 0;
byte_stream_input->RegisterCallback(
base::Bind(CountCallbacks, &num_callbacks));
@@ -525,36 +458,22 @@
EXPECT_TRUE(ValidateIOBuffer(output_io_buffer, output_length));
message_loop_.RunUntilIdle();
- // Setup expectations.
- EXPECT_CALL(*task_runner.get(), PostDelayedTask(_, _, base::TimeDelta()))
- .WillOnce(DoAll(SaveArg<1>(&intermediate_callback),
- Return(true)));
-
// Second get *should* trigger callback.
EXPECT_EQ(ByteStreamReader::STREAM_HAS_DATA,
byte_stream_output->Read(&output_io_buffer, &output_length));
- ::testing::Mock::VerifyAndClearExpectations(task_runner.get());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
EXPECT_TRUE(ValidateIOBuffer(output_io_buffer, output_length));
// Which should do the right thing when it's run.
int num_alt_callbacks = 0;
byte_stream_input->RegisterCallback(
base::Bind(CountCallbacks, &num_alt_callbacks));
- intermediate_callback.Run();
+ task_runner->RunUntilIdle();
EXPECT_EQ(0, num_callbacks);
EXPECT_EQ(1, num_alt_callbacks);
// Third get should also trigger callback.
- EXPECT_CALL(*task_runner.get(), PostDelayedTask(_, _, base::TimeDelta()))
- .WillOnce(DoAll(SaveArg<1>(&intermediate_callback),
- Return(true)));
EXPECT_EQ(ByteStreamReader::STREAM_HAS_DATA,
byte_stream_output->Read(&output_io_buffer, &output_length));
- ::testing::Mock::VerifyAndClearExpectations(task_runner.get());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
EXPECT_TRUE(ValidateIOBuffer(output_io_buffer, output_length));
EXPECT_EQ(ByteStreamReader::STREAM_EMPTY,
byte_stream_output->Read(&output_io_buffer, &output_length));
@@ -563,9 +482,8 @@
// Confirm that callback is called on zero data transfer but source
// complete.
TEST_F(ByteStreamTest, ByteStream_ZeroCallback) {
- scoped_refptr<MockTaskRunner> task_runner(new StrictMock<MockTaskRunner>());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
+ scoped_refptr<base::TestSimpleTaskRunner> task_runner(
+ new base::TestSimpleTaskRunner());
scoped_ptr<ByteStreamWriter> byte_stream_input;
scoped_ptr<ByteStreamReader> byte_stream_output;
@@ -575,20 +493,14 @@
base::Closure intermediate_callback;
- // Setup expectations and record initial state.
+ // Record initial state.
int num_callbacks = 0;
byte_stream_output->RegisterCallback(
base::Bind(CountCallbacks, &num_callbacks));
- EXPECT_CALL(*task_runner.get(), PostDelayedTask(_, _, base::TimeDelta()))
- .WillOnce(DoAll(SaveArg<1>(&intermediate_callback),
- Return(true)));
// Immediately close the stream.
byte_stream_input->Close(DOWNLOAD_INTERRUPT_REASON_NONE);
- ::testing::Mock::VerifyAndClearExpectations(task_runner.get());
- EXPECT_CALL(*task_runner.get(), RunsTasksOnCurrentThread())
- .WillRepeatedly(Return(true));
- intermediate_callback.Run();
+ task_runner->RunUntilIdle();
EXPECT_EQ(1, num_callbacks);
}
diff --git a/net/quic/quic_connection_helper_test.cc b/net/quic/quic_connection_helper_test.cc
index 7528869..0fc45a5 100644
--- a/net/quic/quic_connection_helper_test.cc
+++ b/net/quic/quic_connection_helper_test.cc
@@ -242,9 +242,9 @@
Initialize();
// Verify that a single task was posted.
- EXPECT_EQ(1u, runner_->tasks()->size());
+ ASSERT_EQ(1u, runner_->GetPostedTasks().size());
EXPECT_EQ(base::TimeDelta::FromMicroseconds(kDefaultTimeoutUs),
- runner_->GetTask(0).delta);
+ runner_->GetPostedTasks().front().delay);
EXPECT_CALL(*scheduler_, SentPacket(1, _, false));
// After we run the next task, we should close the connection.
diff --git a/net/quic/test_tools/test_task_runner.cc b/net/quic/test_tools/test_task_runner.cc
index 695e2c4..385fd5d 100644
--- a/net/quic/test_tools/test_task_runner.cc
+++ b/net/quic/test_tools/test_task_runner.cc
@@ -4,32 +4,14 @@
#include "net/quic/test_tools/test_task_runner.h"
-#include <vector>
+#include <algorithm>
-#include "base/stl_util.h"
-#include "net/base/net_errors.h"
#include "net/quic/test_tools/mock_clock.h"
-#include "net/quic/test_tools/quic_test_utils.h"
-#include "net/socket/socket_test_util.h"
-#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace test {
-PostedTask::PostedTask(const tracked_objects::Location& location,
- const base::Closure& closure,
- base::TimeDelta delta,
- base::TimeTicks time)
- : location(location),
- closure(closure),
- delta(delta),
- time(time) {
-}
-
-PostedTask::~PostedTask() {
-}
-
TestTaskRunner::TestTaskRunner(MockClock* clock)
: clock_(clock) {
}
@@ -37,37 +19,22 @@
TestTaskRunner::~TestTaskRunner() {
}
+bool TestTaskRunner::PostDelayedTask(const tracked_objects::Location& from_here,
+ const base::Closure& task,
+ base::TimeDelta delay) {
+ EXPECT_GE(delay, base::TimeDelta());
+ tasks_.push_back(
+ PostedTask(from_here, task, clock_->NowInTicks(), delay,
+ base::TestPendingTask::NESTABLE));
+ return false;
+}
+
bool TestTaskRunner::RunsTasksOnCurrentThread() const {
return true;
}
-bool TestTaskRunner::PostDelayedTask(const tracked_objects::Location& location,
- const base::Closure& closure,
- base::TimeDelta delta) {
- EXPECT_GE(delta, base::TimeDelta());
- tasks_.push_back(PostedTask(location, closure, delta,
- clock_->NowInTicks() + delta));
- return false;
-}
-
-PostedTask TestTaskRunner::GetTask(size_t n) {
- return tasks_.at(n);
-}
-
-std::vector<PostedTask>::iterator TestTaskRunner::FindNextTask() {
- if (tasks_.size() == 0) {
- return tasks_.end();
- } else {
- std::vector<PostedTask>::iterator next = tasks_.begin();
- for (std::vector<PostedTask>::iterator it = next + 1; it != tasks_.end();
- ++it) {
- // Note, that this gives preference to FIFO when times match.
- if (it->time < next->time) {
- next = it;
- }
- }
- return next;
- }
+const std::vector<PostedTask>& TestTaskRunner::GetPostedTasks() const {
+ return tasks_;
}
void TestTaskRunner::RunNextTask() {
@@ -76,10 +43,25 @@
std::vector<PostedTask>::iterator next = FindNextTask();
DCHECK(next != tasks_.end());
clock_->AdvanceTime(QuicTime::Delta::FromMicroseconds(
- (next->time - clock_->NowInTicks()).InMicroseconds()));
+ (next->GetTimeToRun() - clock_->NowInTicks()).InMicroseconds()));
PostedTask task = *next;
tasks_.erase(next);
- task.closure.Run();
+ task.task.Run();
+}
+
+namespace {
+
+struct ShouldRunBeforeLessThan {
+ bool operator()(const PostedTask& task1, const PostedTask& task2) const {
+ return task1.ShouldRunBefore(task2);
+ }
+};
+
+} // namespace
+
+std::vector<PostedTask>::iterator TestTaskRunner::FindNextTask() {
+ return std::min_element(
+ tasks_.begin(), tasks_.end(), ShouldRunBeforeLessThan());
}
} // namespace test
diff --git a/net/quic/test_tools/test_task_runner.h b/net/quic/test_tools/test_task_runner.h
index 47e4685..e25bf2a 100644
--- a/net/quic/test_tools/test_task_runner.h
+++ b/net/quic/test_tools/test_task_runner.h
@@ -7,63 +7,43 @@
#ifndef NET_QUIC_TEST_TOOLS_TEST_TASK_RUNNER_H_
#define NET_QUIC_TEST_TOOLS_TEST_TASK_RUNNER_H_
-#include "base/task_runner.h"
-
#include <vector>
-#include "base/time.h"
-
-#include "base/stl_util.h"
-#include "net/base/net_errors.h"
-#include "net/quic/test_tools/mock_clock.h"
-#include "net/quic/test_tools/quic_test_utils.h"
-#include "net/socket/socket_test_util.h"
-#include "testing/gmock/include/gmock/gmock.h"
-#include "testing/gtest/include/gtest/gtest.h"
+#include "base/basictypes.h"
+#include "base/task_runner.h"
+#include "base/test/test_pending_task.h"
namespace net {
+class MockClock;
+
namespace test {
-struct PostedTask {
- PostedTask(const tracked_objects::Location& location,
- const base::Closure& closure,
- base::TimeDelta delta,
- base::TimeTicks time);
- ~PostedTask();
-
- tracked_objects::Location location;
- base::Closure closure;
- base::TimeDelta delta;
- base::TimeTicks time;
-};
+typedef base::TestPendingTask PostedTask;
class TestTaskRunner : public base::TaskRunner {
public:
explicit TestTaskRunner(MockClock* clock);
+ // base::TaskRunner implementation.
+ virtual bool PostDelayedTask(const tracked_objects::Location& from_here,
+ const base::Closure& task,
+ base::TimeDelta delay) OVERRIDE;
virtual bool RunsTasksOnCurrentThread() const OVERRIDE;
- virtual bool PostDelayedTask(const tracked_objects::Location& location,
- const base::Closure& closure,
- base::TimeDelta delta) OVERRIDE;
- std::vector<PostedTask>::iterator FindNextTask();
+ const std::vector<PostedTask>& GetPostedTasks() const;
void RunNextTask();
- std::vector<PostedTask>* tasks() {
- return &tasks_;
- }
-
- // Returns the nth task in the queue.
- PostedTask GetTask(size_t n);
-
protected:
virtual ~TestTaskRunner();
private:
- MockClock* clock_;
+ std::vector<PostedTask>::iterator FindNextTask();
+
+ MockClock* const clock_;
std::vector<PostedTask> tasks_;
+
DISALLOW_COPY_AND_ASSIGN(TestTaskRunner);
};