xref: /openbmc/sdbusplus/test/message/call.cpp (revision ae019280)
1 #include <sdbusplus/bus.hpp>
2 #include <sdbusplus/message.hpp>
3 
4 #include <chrono>
5 #include <string>
6 
7 #include <gtest/gtest.h>
8 
9 namespace sdbusplus
10 {
11 namespace message
12 {
13 
14 using namespace std::literals::chrono_literals;
15 
16 std::string globalId;
17 
18 void setGlobalId(message&& m)
19 {
20     m.read(globalId);
21 }
22 
23 message newBusIdReq(bus_t& b)
24 {
25     return b.new_method_call("org.freedesktop.DBus", "/org/freedesktop/DBus",
26                              "org.freedesktop.DBus", "GetId");
27 }
28 
29 std::string syncBusId(bus_t& b)
30 {
31     std::string ret;
32     newBusIdReq(b).call().read(ret);
33     return ret;
34 }
35 
36 TEST(CallAsync, Function)
37 {
38     auto b = bus::new_default();
39     globalId = "";
40     while (b.process_discard())
41         ;
42     auto slot = newBusIdReq(b).call_async(setGlobalId);
43     b.wait(1s);
44     b.process_discard();
45     EXPECT_EQ(syncBusId(b), globalId);
46 }
47 
48 TEST(CallAsync, FunctionPointer)
49 {
50     auto b = bus::new_default();
51     globalId = "";
52     while (b.process_discard())
53         ;
54     auto slot = newBusIdReq(b).call_async(&setGlobalId);
55     b.wait(1s);
56     b.process_discard();
57     EXPECT_EQ(syncBusId(b), globalId);
58 }
59 
60 TEST(CallAsync, Lambda)
61 {
62     auto b = bus::new_default();
63     std::string id;
64     while (b.process_discard())
65         ;
66     auto slot = newBusIdReq(b).call_async([&](message&& m) { m.read(id); });
67     b.wait(1s);
68     b.process_discard();
69     EXPECT_EQ(syncBusId(b), id);
70 }
71 
72 TEST(CallAsync, SlotDrop)
73 {
74     auto b = bus::new_default();
75     globalId = "";
76     while (b.process_discard())
77         ;
78     {
79         auto slot = newBusIdReq(b).call_async(setGlobalId);
80     }
81     b.wait(1s);
82     b.process_discard();
83     EXPECT_EQ("", globalId);
84 }
85 
86 TEST(CallAsync, ExceptionCaught)
87 {
88     EXPECT_DEATH(
89         [] {
90         auto b = bus::new_bus();
91         while (b.process_discard())
92             ;
93         auto slot = newBusIdReq(b).call_async(
94             [&](message&&) { throw std::runtime_error("testerror"); });
95         b.wait(1s);
96         b.process_discard();
97     }(),
98         "testerror");
99 }
100 
101 } // namespace message
102 } // namespace sdbusplus
103