• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 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 PLATFORM_TEST_FAKE_TASK_RUNNER_H_
6 #define PLATFORM_TEST_FAKE_TASK_RUNNER_H_
7 
8 #include <map>
9 #include <vector>
10 
11 #include "platform/api/task_runner.h"
12 #include "platform/api/time.h"
13 #include "platform/test/fake_clock.h"
14 
15 namespace openscreen {
16 
17 // Usage:
18 //
19 //   #include ".../gtest.h"
20 //
21 //   class FooTest : public testing::Test {
22 //    public:
23 //     FakeClock* clock() { return &clock_; }
24 //     FakeTaskRunner* task_runner() { return &task_runner_; }
25 //
26 //    private:
27 //     FakeClock clock_{Clock::now()};
28 //     FakeTaskRunner task_runner_{&clock_};
29 //   };
30 //
31 //   TEST_F(FooTest, RunsTask) {
32 //     Foo foo(task_runner());
33 //     foo.DoSomethingToPostATask();
34 //     task_runner()->RunTasksUntilIdle();
35 //     // Alternatively: clock()->Advance(std::chrono::seconds(0));
36 //   }
37 //
38 //   TEST_F(FooTest, RunsDelayedTask) {
39 //     Foo foo(task_runner());
40 //     foo.DoSomethingInOneSecond();  // Schedules 1-second delayed task.
41 //     clock()->Advance(std::chrono::seconds(3));  // Delayed Task runs here!
42 //   }
43 class FakeTaskRunner : public TaskRunner {
44  public:
45   using Task = TaskRunner::Task;
46 
47   explicit FakeTaskRunner(FakeClock* clock);
48   ~FakeTaskRunner() override;
49 
50   // Runs all ready-to-run tasks.
51   void RunTasksUntilIdle();
52 
53   // TaskRunner implementation.
54   void PostPackagedTask(Task task) override;
55   void PostPackagedTaskWithDelay(Task task, Clock::duration delay) override;
56   bool IsRunningOnTaskRunner() override;
57 
ready_task_count()58   int ready_task_count() const { return ready_to_run_tasks_.size(); }
delayed_task_count()59   int delayed_task_count() const { return delayed_tasks_.size(); }
60 
61   // Returns the time at which the next task is scheduled to run, or
62   // Clock::time_point::max() if there is none scheduled.
63   Clock::time_point GetResumeTime() const;
64 
65  private:
66   FakeClock* const clock_;
67 
68   std::vector<Task> ready_to_run_tasks_;
69   std::multimap<Clock::time_point, Task> delayed_tasks_;
70 };
71 
72 }  // namespace openscreen
73 
74 #endif  // PLATFORM_TEST_FAKE_TASK_RUNNER_H_
75