Patrick Williams | d2b0044 | 2022-09-16 08:28:07 -0500 | [diff] [blame] | 1 | #include <sdbusplus/event.hpp> |
| 2 | |
| 3 | #include <chrono> |
| 4 | #include <thread> |
| 5 | |
| 6 | #include <gtest/gtest.h> |
| 7 | |
| 8 | using namespace std::literals::chrono_literals; |
| 9 | |
| 10 | struct Event : public testing::Test |
| 11 | { |
| 12 | sdbusplus::event_t ev{}; |
| 13 | }; |
| 14 | |
| 15 | TEST_F(Event, TimeoutWorks) |
| 16 | { |
| 17 | static constexpr auto timeout = 250ms; |
| 18 | |
| 19 | auto start = std::chrono::steady_clock::now(); |
| 20 | ev.run_one(timeout); |
| 21 | auto stop = std::chrono::steady_clock::now(); |
| 22 | |
| 23 | EXPECT_TRUE(stop - start > timeout); |
Patrick Williams | 6ea246a | 2022-10-14 07:58:15 -0500 | [diff] [blame^] | 24 | EXPECT_TRUE(stop - start < timeout * 3); |
Patrick Williams | d2b0044 | 2022-09-16 08:28:07 -0500 | [diff] [blame] | 25 | } |
| 26 | |
| 27 | TEST_F(Event, Runnable) |
| 28 | { |
| 29 | static constexpr auto timeout = 10s; |
| 30 | |
| 31 | std::jthread j{[&]() { ev.break_run(); }}; |
| 32 | |
| 33 | auto start = std::chrono::steady_clock::now(); |
| 34 | ev.run_one(timeout); |
| 35 | auto stop = std::chrono::steady_clock::now(); |
| 36 | |
| 37 | EXPECT_TRUE(stop - start < timeout); |
| 38 | } |
| 39 | |
| 40 | TEST_F(Event, ConditionSignals) |
| 41 | { |
| 42 | struct run |
| 43 | { |
| 44 | static int _(sd_event_source*, int, uint32_t, void* data) |
| 45 | { |
| 46 | *static_cast<bool*>(data) = true; |
| 47 | return 0; |
| 48 | } |
| 49 | }; |
| 50 | bool ran = false; |
| 51 | |
| 52 | auto c = ev.add_condition(run::_, &ran); |
| 53 | std::jthread j{[&]() { c.signal(); }}; |
| 54 | |
| 55 | ev.run_one(); |
| 56 | EXPECT_TRUE(ran); |
| 57 | c.ack(); |
| 58 | } |
Patrick Williams | 3ce3159 | 2022-09-16 14:05:56 -0500 | [diff] [blame] | 59 | |
| 60 | TEST_F(Event, Timer) |
| 61 | { |
| 62 | static constexpr auto timeout = 50ms; |
| 63 | |
| 64 | struct handler |
| 65 | { |
| 66 | static int _(sd_event_source*, uint64_t, void* data) |
| 67 | { |
| 68 | *static_cast<bool*>(data) = true; |
| 69 | return 0; |
| 70 | } |
| 71 | }; |
| 72 | bool ran = false; |
| 73 | |
| 74 | auto start = std::chrono::steady_clock::now(); |
| 75 | auto c = ev.add_oneshot_timer(handler::_, &ran, timeout); |
| 76 | ev.run_one(); |
| 77 | auto stop = std::chrono::steady_clock::now(); |
| 78 | |
| 79 | EXPECT_TRUE(ran); |
| 80 | EXPECT_TRUE(stop - start > timeout); |
Patrick Williams | 6ea246a | 2022-10-14 07:58:15 -0500 | [diff] [blame^] | 81 | EXPECT_TRUE(stop - start < timeout * 3); |
Patrick Williams | 3ce3159 | 2022-09-16 14:05:56 -0500 | [diff] [blame] | 82 | } |