1 // Copyright 2015 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 #ifndef BASE_TEST_TEST_MOCK_TIME_TASK_RUNNER_H_ 6 #define BASE_TEST_TEST_MOCK_TIME_TASK_RUNNER_H_ 7 8 #include <stddef.h> 9 10 #include <memory> 11 #include <queue> 12 #include <vector> 13 14 #include "base/callback.h" 15 #include "base/callback_helpers.h" 16 #include "base/containers/circular_deque.h" 17 #include "base/macros.h" 18 #include "base/run_loop.h" 19 #include "base/single_thread_task_runner.h" 20 #include "base/synchronization/condition_variable.h" 21 #include "base/synchronization/lock.h" 22 #include "base/test/test_pending_task.h" 23 #include "base/threading/thread_checker_impl.h" 24 #include "base/time/clock.h" 25 #include "base/time/tick_clock.h" 26 #include "base/time/time.h" 27 28 namespace base { 29 30 class ThreadTaskRunnerHandle; 31 32 // Runs pending tasks in the order of the tasks' post time + delay, and keeps 33 // track of a mock (virtual) tick clock time that can be fast-forwarded. 34 // 35 // TestMockTimeTaskRunner has the following properties: 36 // 37 // - Methods RunsTasksInCurrentSequence() and Post[Delayed]Task() can be 38 // called from any thread, but the rest of the methods must be called on 39 // the same thread the TestMockTimeTaskRunner was created on. 40 // - It allows for reentrancy, in that it handles the running of tasks that in 41 // turn call back into it (e.g., to post more tasks). 42 // - Tasks are stored in a priority queue, and executed in the increasing 43 // order of post time + delay, but ignoring nestability. 44 // - It does not check for overflow when doing time arithmetic. A sufficient 45 // condition for preventing overflows is to make sure that the sum of all 46 // posted task delays and fast-forward increments is still representable by 47 // a TimeDelta, and that adding this delta to the starting values of Time 48 // and TickTime is still within their respective range. 49 // 50 // A TestMockTimeTaskRunner of Type::kBoundToThread has the following additional 51 // properties: 52 // - Thread/SequencedTaskRunnerHandle refers to it on its thread. 53 // - It can be driven by a RunLoop on the thread it was created on. 54 // RunLoop::Run() will result in running non-delayed tasks until idle and 55 // then, if RunLoop::QuitWhenIdle() wasn't invoked, fast-forwarding time to 56 // the next delayed task and looping again. And so on, until either 57 // RunLoop::Quit() is invoked (quits immediately after the current task) or 58 // RunLoop::QuitWhenIdle() is invoked (quits before having to fast forward 59 // time once again). Should RunLoop::Run() process all tasks (including 60 // delayed ones), it will block until more are posted. As usual, 61 // RunLoop::RunUntilIdle() is equivalent to RunLoop::Run() followed by an 62 // immediate RunLoop::QuitWhenIdle(). 63 // - 64 // 65 // This is a slightly more sophisticated version of TestSimpleTaskRunner, in 66 // that it supports running delayed tasks in the correct temporal order. 67 class TestMockTimeTaskRunner : public SingleThreadTaskRunner, 68 public RunLoop::Delegate { 69 public: 70 // Everything that is executed in the scope of a ScopedContext will behave as 71 // though it ran under |scope| (i.e. ThreadTaskRunnerHandle, 72 // RunsTasksInCurrentSequence, etc.). This allows the test body to be all in 73 // one block when multiple TestMockTimeTaskRunners share the main thread. 74 // Note: RunLoop isn't supported: will DCHECK if used inside a ScopedContext. 75 // 76 // For example: 77 // 78 // class ExampleFixture { 79 // protected: 80 // DoBarOnFoo() { 81 // DCHECK(foo_task_runner_->RunsOnCurrentThread()); 82 // EXPECT_EQ(foo_task_runner_, ThreadTaskRunnerHandle::Get()); 83 // DoBar(); 84 // } 85 // 86 // // Mock main task runner. 87 // base::MessageLoop message_loop_; 88 // base::ScopedMockTimeMessageLoopTaskRunner main_task_runner_; 89 // 90 // // Mock foo task runner. 91 // scoped_refptr<TestMockTimeTaskRunner> foo_task_runner_ = 92 // new TestMockTimeTaskRunner(); 93 // }; 94 // 95 // TEST_F(ExampleFixture, DoBarOnFoo) { 96 // DoThingsOnMain(); 97 // { 98 // TestMockTimeTaskRunner::ScopedContext scoped_context( 99 // foo_task_runner_.get()); 100 // DoBarOnFoo(); 101 // } 102 // DoMoreThingsOnMain(); 103 // } 104 // 105 class ScopedContext { 106 public: 107 // Note: |scope| is ran until idle as part of this constructor to ensure 108 // that anything which runs in the underlying scope runs after any already 109 // pending tasks (the contrary would break the SequencedTaskRunner 110 // contract). 111 explicit ScopedContext(scoped_refptr<TestMockTimeTaskRunner> scope); 112 ~ScopedContext(); 113 114 private: 115 ScopedClosureRunner on_destroy_; 116 DISALLOW_COPY_AND_ASSIGN(ScopedContext); 117 }; 118 119 enum class Type { 120 // A TestMockTimeTaskRunner which can only be driven directly through its 121 // API. Thread/SequencedTaskRunnerHandle will refer to it only in the scope 122 // of its tasks. 123 kStandalone, 124 // A TestMockTimeTaskRunner which will associate to the thread it is created 125 // on, enabling RunLoop to drive it and making 126 // Thread/SequencedTaskRunnerHandle refer to it on that thread. 127 kBoundToThread, 128 }; 129 130 // Constructs an instance whose virtual time will start at the Unix epoch, and 131 // whose time ticks will start at zero. 132 TestMockTimeTaskRunner(Type type = Type::kStandalone); 133 134 // Constructs an instance starting at the given virtual time and time ticks. 135 TestMockTimeTaskRunner(Time start_time, 136 TimeTicks start_ticks, 137 Type type = Type::kStandalone); 138 139 // Fast-forwards virtual time by |delta|, causing all tasks with a remaining 140 // delay less than or equal to |delta| to be executed. |delta| must be 141 // non-negative. 142 void FastForwardBy(TimeDelta delta); 143 144 // Fast-forwards virtual time by |delta| but not causing any task execution. 145 void AdvanceMockTickClock(TimeDelta delta); 146 147 // Fast-forwards virtual time just until all tasks are executed. 148 void FastForwardUntilNoTasksRemain(); 149 150 // Executes all tasks that have no remaining delay. Tasks with a remaining 151 // delay greater than zero will remain enqueued, and no virtual time will 152 // elapse. 153 void RunUntilIdle(); 154 155 // Clears the queue of pending tasks without running them. 156 void ClearPendingTasks(); 157 158 // Returns the current virtual time (initially starting at the Unix epoch). 159 Time Now() const; 160 161 // Returns the current virtual tick time (initially starting at 0). 162 TimeTicks NowTicks() const; 163 164 // Returns a Clock that uses the virtual time of |this| as its time source. 165 // The returned Clock will hold a reference to |this|. 166 // TODO(tzik): Remove DeprecatedGetMockClock() after updating all callers to 167 // use non-owning Clock. 168 std::unique_ptr<Clock> DeprecatedGetMockClock() const; 169 Clock* GetMockClock() const; 170 171 // Returns a TickClock that uses the virtual time ticks of |this| as its tick 172 // source. The returned TickClock will hold a reference to |this|. 173 // TODO(tzik): Replace Remove DeprecatedGetMockTickClock() after updating all 174 // callers to use non-owning TickClock. 175 std::unique_ptr<TickClock> DeprecatedGetMockTickClock() const; 176 const TickClock* GetMockTickClock() const; 177 178 // Cancelled pending tasks get pruned automatically. 179 base::circular_deque<TestPendingTask> TakePendingTasks(); 180 bool HasPendingTask(); 181 size_t GetPendingTaskCount(); 182 TimeDelta NextPendingTaskDelay(); 183 184 // SingleThreadTaskRunner: 185 bool RunsTasksInCurrentSequence() const override; 186 bool PostDelayedTask(const Location& from_here, 187 OnceClosure task, 188 TimeDelta delay) override; 189 bool PostNonNestableDelayedTask(const Location& from_here, 190 OnceClosure task, 191 TimeDelta delay) override; 192 193 protected: 194 ~TestMockTimeTaskRunner() override; 195 196 // Called before the next task to run is selected, so that subclasses have a 197 // last chance to make sure all tasks are posted. 198 virtual void OnBeforeSelectingTask(); 199 200 // Called after the current mock time has been incremented so that subclasses 201 // can react to the passing of time. 202 virtual void OnAfterTimePassed(); 203 204 // Called after each task is run so that subclasses may perform additional 205 // activities, e.g., pump additional task runners. 206 virtual void OnAfterTaskRun(); 207 208 private: 209 class NonOwningProxyTaskRunner; 210 211 // MockClock implements TickClock and Clock. Always returns the then-current 212 // mock time of |task_runner| as the current time or time ticks. 213 class MockClock : public TickClock, public Clock { 214 public: MockClock(TestMockTimeTaskRunner * task_runner)215 explicit MockClock(TestMockTimeTaskRunner* task_runner) 216 : task_runner_(task_runner) {} 217 218 // TickClock: 219 TimeTicks NowTicks() const override; 220 221 // Clock: 222 Time Now() const override; 223 224 private: 225 TestMockTimeTaskRunner* task_runner_; 226 227 DISALLOW_COPY_AND_ASSIGN(MockClock); 228 }; 229 230 struct TestOrderedPendingTask; 231 232 // Predicate that defines a strict weak temporal ordering of tasks. 233 class TemporalOrder { 234 public: 235 bool operator()(const TestOrderedPendingTask& first_task, 236 const TestOrderedPendingTask& second_task) const; 237 }; 238 239 typedef std::priority_queue<TestOrderedPendingTask, 240 std::vector<TestOrderedPendingTask>, 241 TemporalOrder> TaskPriorityQueue; 242 243 // Core of the implementation for all flavors of fast-forward methods. Given a 244 // non-negative |max_delta|, runs all tasks with a remaining delay less than 245 // or equal to |max_delta|, and moves virtual time forward as needed for each 246 // processed task. Pass in TimeDelta::Max() as |max_delta| to run all tasks. 247 void ProcessAllTasksNoLaterThan(TimeDelta max_delta); 248 249 // Forwards |now_ticks_| until it equals |later_ticks|, and forwards |now_| by 250 // the same amount. Calls OnAfterTimePassed() if |later_ticks| > |now_ticks_|. 251 // Does nothing if |later_ticks| <= |now_ticks_|. 252 void ForwardClocksUntilTickTime(TimeTicks later_ticks); 253 254 // Returns the |next_task| to run if there is any with a running time that is 255 // at most |reference| + |max_delta|. This additional complexity is required 256 // so that |max_delta| == TimeDelta::Max() can be supported. 257 bool DequeueNextTask(const TimeTicks& reference, 258 const TimeDelta& max_delta, 259 TestPendingTask* next_task); 260 261 // RunLoop::Delegate: 262 void Run(bool application_tasks_allowed) override; 263 void Quit() override; 264 void EnsureWorkScheduled() override; 265 266 // Also used for non-dcheck logic (RunsTasksInCurrentSequence()) and as such 267 // needs to be a ThreadCheckerImpl. 268 ThreadCheckerImpl thread_checker_; 269 270 Time now_; 271 TimeTicks now_ticks_; 272 273 // Temporally ordered heap of pending tasks. Must only be accessed while the 274 // |tasks_lock_| is held. 275 TaskPriorityQueue tasks_; 276 277 // The ordinal to use for the next task. Must only be accessed while the 278 // |tasks_lock_| is held. 279 size_t next_task_ordinal_ = 0; 280 281 mutable Lock tasks_lock_; 282 ConditionVariable tasks_lock_cv_; 283 284 const scoped_refptr<NonOwningProxyTaskRunner> proxy_task_runner_; 285 std::unique_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_; 286 287 // Set to true in RunLoop::Delegate::Quit() to signal the topmost 288 // RunLoop::Delegate::Run() instance to stop, reset to false when it does. 289 bool quit_run_loop_ = false; 290 291 mutable MockClock mock_clock_; 292 293 DISALLOW_COPY_AND_ASSIGN(TestMockTimeTaskRunner); 294 }; 295 296 } // namespace base 297 298 #endif // BASE_TEST_TEST_MOCK_TIME_TASK_RUNNER_H_ 299