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 // Clears the queue of pending tasks without running them.
65 void ClearPendingTasks();
67 // Returns the current virtual time (initially starting at the Unix epoch).
70 // Returns the current virtual tick time (initially starting at 0).
71 TimeTicks
NowTicks() const;
73 // Returns a Clock that uses the virtual time of |this| as its time source.
74 // The returned Clock will hold a reference to |this|.
75 scoped_ptr
<Clock
> GetMockClock() const;
77 // Returns a TickClock that uses the virtual time ticks of |this| as its tick
78 // source. The returned TickClock will hold a reference to |this|.
79 scoped_ptr
<TickClock
> GetMockTickClock() const;
81 bool HasPendingTask() const;
82 size_t GetPendingTaskCount() const;
83 TimeDelta
NextPendingTaskDelay() const;
85 // SingleThreadTaskRunner:
86 bool RunsTasksOnCurrentThread() const override
;
87 bool PostDelayedTask(const tracked_objects::Location
& from_here
,
89 TimeDelta delay
) override
;
90 bool PostNonNestableDelayedTask(const tracked_objects::Location
& from_here
,
92 TimeDelta delay
) override
;
95 ~TestMockTimeTaskRunner() override
;
97 // Whether the elapsing of virtual time is stopped or not. Subclasses can
98 // override this method to perform early exits from a running task runner.
99 // Defaults to always return false.
100 virtual bool IsElapsingStopped();
102 // Called before the next task to run is selected, so that subclasses have a
103 // last chance to make sure all tasks are posted.
104 virtual void OnBeforeSelectingTask();
106 // Called after the current mock time has been incremented so that subclasses
107 // can react to the passing of time.
108 virtual void OnAfterTimePassed();
110 // Called after each task is run so that subclasses may perform additional
111 // activities, e.g., pump additional task runners.
112 virtual void OnAfterTaskRun();
115 // Predicate that defines a strict weak temporal ordering of tasks.
116 class TemporalOrder
{
118 bool operator()(const TestPendingTask
& first_task
,
119 const TestPendingTask
& second_task
) const;
122 typedef std::priority_queue
<TestPendingTask
,
123 std::vector
<TestPendingTask
>,
124 TemporalOrder
> TaskPriorityQueue
;
126 // Core of the implementation for all flavors of fast-forward methods. Given a
127 // non-negative |max_delta|, runs all tasks with a remaining delay less than
128 // or equal to |max_delta|, and moves virtual time forward as needed for each
129 // processed task. Pass in TimeDelta::Max() as |max_delta| to run all tasks.
130 void ProcessAllTasksNoLaterThan(TimeDelta max_delta
);
132 // Forwards |now_ticks_| until it equals |later_ticks|, and forwards |now_| by
133 // the same amount. Calls OnAfterTimePassed() if |later_ticks| > |now_ticks_|.
134 // Does nothing if |later_ticks| <= |now_ticks_|.
135 void ForwardClocksUntilTickTime(TimeTicks later_ticks
);
137 // Returns the |next_task| to run if there is any with a running time that is
138 // at most |reference| + |max_delta|. This additional complexity is required
139 // so that |max_delta| == TimeDelta::Max() can be supported.
140 bool DequeueNextTask(const TimeTicks
& reference
,
141 const TimeDelta
& max_delta
,
142 TestPendingTask
* next_task
);
144 ThreadChecker thread_checker_
;
146 TimeTicks now_ticks_
;
148 // Temporally ordered heap of pending tasks. Must only be accessed while the
149 // |tasks_lock_| is held.
150 TaskPriorityQueue tasks_
;
153 DISALLOW_COPY_AND_ASSIGN(TestMockTimeTaskRunner
);
158 #endif // BASE_TEST_TEST_MOCK_TIME_TASK_RUNNER_H_