blob: 143fe2a651afcb2baadea633599c46c567f4e8da [file] [log] [blame]
Alex Deymoef3955a2015-06-09 10:14:01 -07001// Copyright 2015 The Chromium OS 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 LIBCHROMEOS_CHROMEOS_MESSAGE_LOOPS_FAKE_MESSAGE_LOOP_H_
6#define LIBCHROMEOS_CHROMEOS_MESSAGE_LOOPS_FAKE_MESSAGE_LOOP_H_
7
8#include <functional>
9#include <map>
10#include <queue>
11#include <utility>
12#include <vector>
13
14#include <base/test/simple_test_clock.h>
15#include <base/time/time.h>
16
17#include <chromeos/chromeos_export.h>
18#include <chromeos/message_loops/message_loop.h>
19
20namespace chromeos {
21
22// The FakeMessageLoop implements a message loop that doesn't block or wait for
23// time based tasks to be ready. The tasks are executed in the order they should
24// be executed in a real message loop implementation, but the time is advanced
25// to the time when the first task should be executed instead of blocking.
26// To keep a consistent notion of time for other classes, FakeMessageLoop
27// optionally updates a SimpleTestClock instance when it needs to advance the
28// clock.
29// This message loop implementation is useful for unittests.
30class CHROMEOS_EXPORT FakeMessageLoop : public MessageLoop {
31 public:
32 // Create a FakeMessageLoop optionally using a SimpleTestClock to update the
33 // time when Run() or RunOnce(true) are called and should block.
34 explicit FakeMessageLoop(base::SimpleTestClock* clock);
35 ~FakeMessageLoop() override = default;
36
37 MessageLoop::TaskId PostDelayedTask(const base::Closure &task,
38 base::TimeDelta delay) override;
39 bool CancelTask(TaskId task_id) override;
40 bool RunOnce(bool may_block) override;
41
42 // FakeMessageLoop methods:
43
44 // Return whether there are peding tasks. Useful to check that no
45 // callbacks were leaked.
46 bool PendingTasks();
47
48 private:
49 // Using std::greater<> for the priority_queue means that the top() of the
50 // queue is the lowest (earliest) time, and for the same time, the smallest
51 // TaskId. This determines the order in which the tasks will be fired.
52 std::priority_queue<
53 std::pair<base::Time, MessageLoop::TaskId>,
54 std::vector<std::pair<base::Time, MessageLoop::TaskId>>,
55 std::greater<std::pair<base::Time, MessageLoop::TaskId>>> fire_order_;
56 std::map<MessageLoop::TaskId, base::Closure> tasks_;
57
58 base::SimpleTestClock* test_clock_ = nullptr;
59 base::Time current_time_ = base::Time::FromDoubleT(1246996800.);
60
61 MessageLoop::TaskId last_id_ = kTaskIdNull;
62
63 DISALLOW_COPY_AND_ASSIGN(FakeMessageLoop);
64};
65
66} // namespace chromeos
67
68#endif // LIBCHROMEOS_CHROMEOS_MESSAGE_LOOPS_FAKE_MESSAGE_LOOP_H_