xref: /openbmc/sdbusplus/test/bus/match.cpp (revision 0f282c48)
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     sdbusplus::bus_t bus = sdbusplus::bus::new_bus();
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,
33                       sd_bus_error* /*e*/) {
34         *static_cast<bool*>(context) = true;
35         return 0;
36     };
37 
38     sdbusplus::bus::match_t m{bus, matchRule(), trigger, &triggered};
39     auto m2 = std::move(m); // ensure match is move-safe.
40 
41     waitForIt(triggered);
42     ASSERT_FALSE(triggered);
43 
44     bus.request_name(busName);
45 
46     waitForIt(triggered);
47     ASSERT_TRUE(triggered);
48 }
49 
50 TEST_F(Match, FunctorIs_LambdaTakingMessage)
51 {
52     bool triggered = false;
53     auto trigger = [&triggered](sdbusplus::message_t& /*m*/) {
54         triggered = true;
55     };
56 
57     sdbusplus::bus::match_t m{bus, matchRule(), trigger};
58     auto m2 = std::move(m); // ensure match is move-safe.
59 
60     waitForIt(triggered);
61     ASSERT_FALSE(triggered);
62 
63     bus.request_name(busName);
64 
65     waitForIt(triggered);
66     ASSERT_TRUE(triggered);
67 }
68 
69 TEST_F(Match, FunctorIs_MemberFunctionTakingMessage)
70 {
71 
72     class BoolHolder
73     {
74       public:
75         bool triggered = false;
76 
77         void callback(sdbusplus::message_t& /*m*/)
78         {
79             triggered = true;
80         }
81     };
82     BoolHolder b;
83 
84     sdbusplus::bus::match_t m{bus, matchRule(),
85                               std::bind(std::mem_fn(&BoolHolder::callback), &b,
86                                         std::placeholders::_1)};
87     auto m2 = std::move(m); // ensure match is move-safe.
88 
89     waitForIt(b.triggered);
90     ASSERT_FALSE(b.triggered);
91 
92     bus.request_name(busName);
93 
94     waitForIt(b.triggered);
95     ASSERT_TRUE(b.triggered);
96 }
97