1 // THIS EXISTS AS A COPY OF SDBUSPLUS/TEST/HELPERS.HPP until that is merged.
2 #pragma once
3 
4 #include <sdbusplus/test/sdbus_mock.hpp>
5 #include <string>
6 #include <vector>
7 
8 #include <gmock/gmock.h>
9 #include <gtest/gtest.h>
10 
11 using ::testing::_;
12 using ::testing::Invoke;
13 using ::testing::IsNull;
14 using ::testing::NotNull;
15 using ::testing::Return;
16 using ::testing::StrEq;
17 
18 /** @brief Setup the expectations for sdbus-based object creation.
19  *
20  * Objects created that inherit a composition from sdbusplus will all
21  * require at least these expectations.
22  *
23  * If you have future sd_bus_emit_properties_changed_strv calls expected,
24  * you'll need to add those calls into your test.  This only captures the
25  * property updates you tell it to expect initially.
26  *
27  * TODO: Make it support more cases, as I'm sure there are more.
28  *
29  * @param[in] sdbus_mock - Pointer to your sdbus mock interface used with
30  *     the sdbusplus::bus::bus you created.
31  * @param[in] defer - Whether object announcement is deferred.
32  * @param[in] path - the dbus path passed to the object
33  * @param[in] intf - the dbus interface
34  * @param[in] properties - an ordered list of expected property updates.
35  * @param[in] index - a pointer to a valid integer in a surviving scope.
36  */
37 void SetupDbusObject(sdbusplus::SdBusMock* sdbus_mock, bool defer,
38                      const std::string& path, const std::string& intf,
39                      const std::vector<std::string>& properties, int* index)
40 {
41     EXPECT_CALL(*sdbus_mock,
42                 sd_bus_add_object_vtable(IsNull(), NotNull(), StrEq(path),
43                                          StrEq(intf), NotNull(), NotNull()))
44         .WillOnce(Return(0));
45 
46     if (!defer)
47     {
48         EXPECT_CALL(*sdbus_mock,
49                     sd_bus_emit_object_added(IsNull(), StrEq(path)))
50             .WillOnce(Return(0));
51     }
52 
53     if (!properties.empty())
54     {
55         (*index) = 0;
56         EXPECT_CALL(*sdbus_mock,
57                     sd_bus_emit_properties_changed_strv(IsNull(), StrEq(path),
58                                                         StrEq(intf), NotNull()))
59             .Times(properties.size())
60             .WillRepeatedly(Invoke([=](sd_bus* bus, const char* path,
61                                        const char* interface, char** names) {
62                 EXPECT_STREQ(properties[(*index)++].c_str(), names[0]);
63                 return 0;
64             }));
65     }
66 
67     return;
68 }
69