xref: /openbmc/sdbusplus/test/async/context.cpp (revision 78e436fe)
1 #include <sdbusplus/async.hpp>
2 
3 #include <gtest/gtest.h>
4 
5 struct Context : public testing::Test
6 {
7     ~Context() noexcept = default;
8 
9     void TearDown() override
10     {
11         // Destructing the context can throw, so we have to do it in
12         // the TearDown in order to make our destructor noexcept.
13         ctx.reset();
14     }
15 
16     std::optional<sdbusplus::async::context> ctx{std::in_place};
17 };
18 
19 TEST_F(Context, RunSimple)
20 {
21     ctx->run(std::execution::just() |
22              std::execution::then([this]() { ctx->request_stop(); }));
23 }
24 
25 TEST_F(Context, SpawnedTask)
26 {
27     ctx->spawn(std::execution::just());
28 
29     ctx->run(std::execution::just() |
30              std::execution::then([this]() { ctx->request_stop(); }));
31 }
32 
33 TEST_F(Context, SpawnDelayedTask)
34 {
35     using namespace std::literals;
36     static constexpr auto timeout = 500ms;
37 
38     auto start = std::chrono::steady_clock::now();
39 
40     bool ran = false;
41     ctx->spawn(sdbusplus::async::sleep_for(*ctx, timeout) |
42                std::execution::then([&ran]() { ran = true; }));
43 
44     ctx->run(std::execution::just() |
45              std::execution::then([this]() { ctx->request_stop(); }));
46 
47     auto stop = std::chrono::steady_clock::now();
48 
49     EXPECT_TRUE(ran);
50     EXPECT_GT(stop - start, timeout);
51     EXPECT_LT(stop - start, timeout * 2);
52 }
53