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