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.
5 #ifndef BASE_TEST_TEST_MOCK_TIME_TASK_RUNNER_H_
6 #define BASE_TEST_TEST_MOCK_TIME_TASK_RUNNER_H_
11 #include "base/macros.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/synchronization/lock.h"
15 #include "base/test/test_pending_task.h"
16 #include "base/threading/thread_checker.h"
17 #include "base/time/time.h"
24 // Runs pending tasks in the order of the tasks' post time + delay, and keeps
25 // track of a mock (virtual) tick clock time that can be fast-forwarded.
27 // TestMockTimeTaskRunner has the following properties:
29 // - Methods RunsTasksOnCurrentThread() and Post[Delayed]Task() can be called
30 // from any thread, but the rest of the methods must be called on the same
31 // thread the TaskRunner was created on.
32 // - It allows for reentrancy, in that it handles the running of tasks that in
33 // turn call back into it (e.g., to post more tasks).
34 // - Tasks are stored in a priority queue, and executed in the increasing
35 // order of post time + delay, but ignoring nestability.
36 // - It does not check for overflow when doing time arithmetic. A sufficient
37 // condition for preventing overflows is to make sure that the sum of all
38 // posted task delays and fast-forward increments is still representable by
39 // a TimeDelta, and that adding this delta to the starting values of Time
40 // and TickTime is still within their respective range.
41 // - Tasks aren't guaranteed to be destroyed immediately after they're run.
43 // This is a slightly more sophisticated version of TestSimpleTaskRunner, in
44 // that it supports running delayed tasks in the correct temporal order.
45 class TestMockTimeTaskRunner
: public SingleThreadTaskRunner
{
47 // Constructs an instance whose virtual time will start at the Unix epoch, and
48 // whose time ticks will start at zero.
49 TestMockTimeTaskRunner();
51 // Fast-forwards virtual time by |delta|, causing all tasks with a remaining
52 // delay less than or equal to |delta| to be executed. |delta| must be
54 void FastForwardBy(TimeDelta delta
);
56 // Fast-forwards virtual time just until all tasks are executed.
57 void FastForwardUntilNoTasksRemain();
59 // Executes all tasks that have no remaining delay. Tasks with a remaining
60 // delay greater than zero will remain enqueued, and no virtual time will
64 // Returns the current virtual time (initially starting at the Unix epoch).
67 // Returns the current virtual tick time (initially starting at 0).
68 TimeTicks
NowTicks() const;
70 // Returns a Clock that uses the virtual time of |this| as its time source.
71 // The returned Clock will hold a reference to |this|.
72 scoped_ptr
<Clock
> GetMockClock() const;
74 // Returns a TickClock that uses the virtual time ticks of |this| as its tick
75 // source. The returned TickClock will hold a reference to |this|.
76 scoped_ptr
<TickClock
> GetMockTickClock() const;
78 bool HasPendingTask() const;
79 size_t GetPendingTaskCount() const;
80 TimeDelta
NextPendingTaskDelay() const;
82 // SingleThreadTaskRunner:
83 bool RunsTasksOnCurrentThread() const override
;
84 bool PostDelayedTask(const tracked_objects::Location
& from_here
,
86 TimeDelta delay
) override
;
87 bool PostNonNestableDelayedTask(const tracked_objects::Location
& from_here
,
89 TimeDelta delay
) override
;
92 ~TestMockTimeTaskRunner() override
;
94 // Called before the next task to run is selected, so that subclasses have a
95 // last chance to make sure all tasks are posted.
96 virtual void OnBeforeSelectingTask();
98 // Called after the current mock time has been incremented so that subclasses
99 // can react to the passing of time.
100 virtual void OnAfterTimePassed();
102 // Called after each task is run so that subclasses may perform additional
103 // activities, e.g., pump additional task runners.
104 virtual void OnAfterTaskRun();
107 // Predicate that defines a strict weak temporal ordering of tasks.
108 class TemporalOrder
{
110 bool operator()(const TestPendingTask
& first_task
,
111 const TestPendingTask
& second_task
) const;
114 typedef std::priority_queue
<TestPendingTask
,
115 std::vector
<TestPendingTask
>,
116 TemporalOrder
> TaskPriorityQueue
;
118 // Core of the implementation for all flavors of fast-forward methods. Given a
119 // non-negative |max_delta|, runs all tasks with a remaining delay less than
120 // or equal to |max_delta|, and moves virtual time forward as needed for each
121 // processed task. Pass in TimeDelta::Max() as |max_delta| to run all tasks.
122 void ProcessAllTasksNoLaterThan(TimeDelta max_delta
);
124 // Forwards |now_ticks_| until it equals |later_ticks|, and forwards |now_| by
125 // the same amount. Calls OnAfterTimePassed() if |later_ticks| > |now_ticks_|.
126 // Does nothing if |later_ticks| <= |now_ticks_|.
127 void ForwardClocksUntilTickTime(TimeTicks later_ticks
);
129 // Returns the |next_task| to run if there is any with a running time that is
130 // at most |reference| + |max_delta|. This additional complexity is required
131 // so that |max_delta| == TimeDelta::Max() can be supported.
132 bool DequeueNextTask(const TimeTicks
& reference
,
133 const TimeDelta
& max_delta
,
134 TestPendingTask
* next_task
);
136 ThreadChecker thread_checker_
;
138 TimeTicks now_ticks_
;
140 // Temporally ordered heap of pending tasks. Must only be accessed while the
141 // |tasks_lock_| is held.
142 TaskPriorityQueue tasks_
;
145 DISALLOW_COPY_AND_ASSIGN(TestMockTimeTaskRunner
);
150 #endif // BASE_TEST_TEST_MOCK_TIME_TASK_RUNNER_H_