• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "gtest/gtest.h"
17 #include "pw_async/fake_dispatcher.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 ///    RunUntilIdle();
32 ///    EXPECT_TRUE(some condition);
33 ///
34 ///    obj.ScheduleTaskToRunIn30Seconds();
35 ///    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()`.
RunUntilIdle()48   void RunUntilIdle() { dispatcher_.RunUntilIdle(); }
49 
50   /// Dispatches all tasks with due times up to `end_time`, progressively
51   /// advancing the fake clock.
RunUntil(chrono::SystemClock::time_point end_time)52   void RunUntil(chrono::SystemClock::time_point end_time) {
53     dispatcher_.RunUntil(end_time);
54   }
55 
56   /// Dispatches all tasks with due times up to `now() + duration`,
57   /// progressively advancing the fake clock.
RunFor(chrono::SystemClock::duration duration)58   void RunFor(chrono::SystemClock::duration duration) {
59     dispatcher_.RunFor(duration);
60   }
61 
62  private:
63   FakeDispatcher dispatcher_;
64 };
65 
66 }  // namespace pw::async::test
67