xref: /openbmc/sdbusplus/test/bus/match.cpp (revision b641d103)
1 #include <sdbusplus/bus.hpp>
2 #include <sdbusplus/bus/match.hpp>
3 
4 #include <gtest/gtest.h>
5 
6 class Match : public ::testing::Test
7 {
8   protected:
9     decltype(sdbusplus::bus::new_default()) bus = sdbusplus::bus::new_default();
10 
11     static constexpr auto busName = "xyz.openbmc_project.sdbusplus.test.Match";
12 
13     static auto matchRule()
14     {
15         using namespace sdbusplus::bus::match::rules;
16         return nameOwnerChanged() + argN(0, busName);
17     }
18 
19     void waitForIt(bool& triggered)
20     {
21         for (size_t i = 0; (i < 16) && !triggered; ++i)
22         {
23             bus.wait(0);
24             bus.process_discard();
25         }
26     }
27 };
28 
29 TEST_F(Match, FunctorIs_sd_bus_message_handler_t)
30 {
31     bool triggered = false;
32     auto trigger = [](sd_bus_message* m, void* context, sd_bus_error* e) {
33         *static_cast<bool*>(context) = true;
34         return 0;
35     };
36 
37     sdbusplus::bus::match_t m{bus, matchRule(), trigger, &triggered};
38     auto m2 = std::move(m); // ensure match is move-safe.
39 
40     waitForIt(triggered);
41     ASSERT_FALSE(triggered);
42 
43     bus.request_name(busName);
44 
45     waitForIt(triggered);
46     ASSERT_TRUE(triggered);
47 }
48 
49 TEST_F(Match, FunctorIs_LambdaTakingMessage)
50 {
51     bool triggered = false;
52     auto trigger = [&triggered](sdbusplus::message::message& m) {
53         triggered = true;
54     };
55 
56     sdbusplus::bus::match_t m{bus, matchRule(), trigger};
57     auto m2 = std::move(m); // ensure match is move-safe.
58 
59     waitForIt(triggered);
60     ASSERT_FALSE(triggered);
61 
62     bus.request_name(busName);
63 
64     waitForIt(triggered);
65     ASSERT_TRUE(triggered);
66 }
67 
68 TEST_F(Match, FunctorIs_MemberFunctionTakingMessage)
69 {
70 
71     class BoolHolder
72     {
73       public:
74         bool triggered = false;
75 
76         void callback(sdbusplus::message::message& m)
77         {
78             triggered = true;
79         }
80     };
81     BoolHolder b;
82 
83     sdbusplus::bus::match_t m{bus, matchRule(),
84                               std::bind(std::mem_fn(&BoolHolder::callback), &b,
85                                         std::placeholders::_1)};
86     auto m2 = std::move(m); // ensure match is move-safe.
87 
88     waitForIt(b.triggered);
89     ASSERT_FALSE(b.triggered);
90 
91     bus.request_name(busName);
92 
93     waitForIt(b.triggered);
94     ASSERT_TRUE(b.triggered);
95 }
96