xref: /openbmc/sdbusplus/test/event/event.cpp (revision 6ea246af)
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 
TEST_F(Event,TimeoutWorks)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);
24     EXPECT_TRUE(stop - start < timeout * 3);
25 }
26 
TEST_F(Event,Runnable)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 
TEST_F(Event,ConditionSignals)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 }
59 
TEST_F(Event,Timer)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);
81     EXPECT_TRUE(stop - start < timeout * 3);
82 }
83