blob: 6a961e66815edffe9cc740b602a32f4b54b41850 [file] [log] [blame]
Krzysztof Grobelnyb5645942020-09-29 11:52:45 +02001#include <sdbusplus/asio/object_server.hpp>
Wludzik, Jozef2f9f9b82020-10-13 09:07:45 +02002#include <sdbusplus/asio/property.hpp>
Krzysztof Grobelnyb5645942020-09-29 11:52:45 +02003
4#include <future>
5#include <thread>
6
7#include <gmock/gmock.h>
8
9class 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
33 template <class Functor>
34 static void synchronizedPost(Functor&& functor)
35 {
36 boost::asio::post(ioc, std::forward<Functor>(functor));
37 synchronizeIoc();
38 }
39
40 template <class T>
Krzysztof Grobelnyf32f6fe2020-10-30 13:51:58 +010041 static T waitForFuture(
Krzysztof Grobelnyb5645942020-09-29 11:52:45 +020042 std::future<T> future,
43 std::chrono::milliseconds timeout = std::chrono::seconds(10))
44 {
45 constexpr auto precission = std::chrono::milliseconds(10);
46 auto elapsed = std::chrono::milliseconds(0);
47
48 while (future.valid() && elapsed < timeout)
49 {
50 synchronizeIoc();
51
Krzysztof Grobelnyf32f6fe2020-10-30 13:51:58 +010052 if (future.wait_for(precission) == std::future_status::ready)
Krzysztof Grobelnyb5645942020-09-29 11:52:45 +020053 {
Krzysztof Grobelnyf32f6fe2020-10-30 13:51:58 +010054 return future.get();
Krzysztof Grobelnyb5645942020-09-29 11:52:45 +020055 }
Krzysztof Grobelnyf32f6fe2020-10-30 13:51:58 +010056 else
Krzysztof Grobelnyb5645942020-09-29 11:52:45 +020057 {
Krzysztof Grobelnyf32f6fe2020-10-30 13:51:58 +010058 elapsed += precission;
Krzysztof Grobelnyb5645942020-09-29 11:52:45 +020059 }
60 }
61
Krzysztof Grobelnyf32f6fe2020-10-30 13:51:58 +010062 throw std::runtime_error("Timed out while waiting for future");
Krzysztof Grobelnyb5645942020-09-29 11:52:45 +020063 }
64
65 static bool waitForFuture(
66 std::string_view name,
67 std::chrono::milliseconds timeout = std::chrono::seconds(10));
68
69 private:
70 static std::future<bool> getFuture(std::string_view name);
71
72 static boost::asio::io_context ioc;
73 static std::shared_ptr<sdbusplus::asio::connection> bus;
74 static std::shared_ptr<sdbusplus::asio::object_server> objServer;
75 static std::map<std::string, std::vector<std::future<bool>>> futures;
76 static bool setUp;
77};