xref: /openbmc/telemetry/tests/src/dbus_environment.hpp (revision 753e4b3c843dd5d1068949c4106a6389f0e0ffbc)
1 #include <sdbusplus/asio/object_server.hpp>
2 #include <sdbusplus/asio/property.hpp>
3 
4 #include <future>
5 #include <thread>
6 
7 #include <gmock/gmock.h>
8 
9 class DbusEnvironment : public ::testing::Environment
10 {
11   public:
12     ~DbusEnvironment();
13 
14     void SetUp() override;
15     void TearDown() override;
16     void teardown();
17 
18     static boost::asio::io_context& getIoc();
19     static std::shared_ptr<sdbusplus::asio::connection> getBus();
20     static std::shared_ptr<sdbusplus::asio::object_server> getObjServer();
21     static const char* serviceName();
22     static std::function<void()> setPromise(std::string_view name);
23     static void sleepFor(std::chrono::milliseconds);
24     static std::chrono::milliseconds measureTime(std::function<void()>);
25 
26     static void synchronizeIoc()
27     {
28         while (ioc.poll() > 0)
29         {}
30     }
31 
32     template <class Functor>
33     static void synchronizedPost(Functor&& functor)
34     {
35         boost::asio::post(ioc, std::forward<Functor>(functor));
36         synchronizeIoc();
37     }
38 
39     template <class T>
40     static T waitForFuture(
41         std::future<T> future,
42         std::chrono::milliseconds timeout = std::chrono::seconds(10))
43     {
44         constexpr auto precission = std::chrono::milliseconds(10);
45         auto elapsed = std::chrono::milliseconds(0);
46 
47         while (future.valid() && elapsed < timeout)
48         {
49             synchronizeIoc();
50 
51             if (future.wait_for(precission) == std::future_status::ready)
52             {
53                 return future.get();
54             }
55             else
56             {
57                 elapsed += precission;
58             }
59         }
60 
61         throw std::runtime_error("Timed out while waiting for future");
62     }
63 
64     static bool waitForFuture(
65         std::string_view name,
66         std::chrono::milliseconds timeout = std::chrono::seconds(10));
67 
68   private:
69     static std::future<bool> getFuture(std::string_view name);
70 
71     static boost::asio::io_context ioc;
72     static std::shared_ptr<sdbusplus::asio::connection> bus;
73     static std::shared_ptr<sdbusplus::asio::object_server> objServer;
74     static std::map<std::string, std::vector<std::future<bool>>> futures;
75     static bool setUp;
76 };
77