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
matchRule()13 static auto matchRule()
14 {
15 using namespace sdbusplus::bus::match::rules;
16 return nameOwnerChanged() + argN(0, busName);
17 }
18
waitForIt(bool & triggered)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
TEST_F(Match,FunctorIs_sd_bus_message_handler_t)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
TEST_F(Match,FunctorIs_LambdaTakingMessage)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
TEST_F(Match,FunctorIs_MemberFunctionTakingMessage)69 TEST_F(Match, FunctorIs_MemberFunctionTakingMessage)
70 {
71 class BoolHolder
72 {
73 public:
74 bool triggered = false;
75
76 void callback(sdbusplus::message_t& /*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