xref: /aosp_15_r20/external/pigweed/pw_async/public/pw_async/fake_dispatcher_fixture.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include "pw_async/fake_dispatcher.h"
17 #include "pw_unit_test/framework.h"
18 
19 namespace pw::async::test {
20 
21 /// Test fixture that is a simple wrapper around a FakeDispatcher.
22 ///
23 /// Example:
24 /// @code{.cpp}
25 ///  using ExampleTest = pw::async::test::FakeDispatcherFixture;
26 ///
27 ///  TEST_F(ExampleTest, Example) {
28 ///    MyClass obj(dispatcher());
29 ///
30 ///    obj.ScheduleSomeTasks();
31 ///    EXPECT_TRUE(RunUntilIdle());
32 ///    EXPECT_TRUE(some condition);
33 ///
34 ///    obj.ScheduleTaskToRunIn30Seconds();
35 ///    EXPECT_TRUE(RunFor(30s));
36 ///    EXPECT_TRUE(task ran);
37 ///  }
38 /// @endcode
39 class FakeDispatcherFixture : public ::testing::Test {
40  public:
41   /// Returns the FakeDispatcher that should be used for dependency injection.
dispatcher()42   FakeDispatcher& dispatcher() { return dispatcher_; }
43 
44   /// Returns the current fake time.
now()45   chrono::SystemClock::time_point now() { return dispatcher_.now(); }
46 
47   /// Dispatches all tasks with due times up until `now()`.
48   /// Returns true iff any tasks were invoked during the run.
RunUntilIdle()49   bool RunUntilIdle() { return dispatcher_.RunUntilIdle(); }
50 
51   /// Dispatches all tasks with due times up to `end_time`, progressively
52   /// advancing the fake clock.
53   /// Returns true iff any tasks were invoked during the run.
RunUntil(chrono::SystemClock::time_point end_time)54   bool RunUntil(chrono::SystemClock::time_point end_time) {
55     return dispatcher_.RunUntil(end_time);
56   }
57 
58   /// Dispatches all tasks with due times up to `now() + duration`,
59   /// progressively advancing the fake clock.
60   /// Returns true iff any tasks were invoked during the run.
RunFor(chrono::SystemClock::duration duration)61   bool RunFor(chrono::SystemClock::duration duration) {
62     return dispatcher_.RunFor(duration);
63   }
64 
65  private:
66   FakeDispatcher dispatcher_;
67 };
68 
69 }  // namespace pw::async::test
70