blob: f1f95880f3804f4ff3dc4c1d52a9ededbecc57fc [file] [log] [blame]
William A. Kennington III458aeae2021-06-14 15:07:16 -07001#include <stdplus/cancel.hpp>
2
Patrick Williamsd1984dd2023-05-10 16:12:44 -05003#include <functional>
4
William A. Kennington III458aeae2021-06-14 15:07:16 -07005#include <gtest/gtest.h>
6
7namespace stdplus
8{
9
10struct FakeCancelable : public Cancelable
11{
12 size_t count = 0;
13 void cancel() noexcept override
14 {
15 count++;
16 }
17};
18
19TEST(CancelTest, Cancel)
20{
21 FakeCancelable c;
22 EXPECT_EQ(c.count, 0);
23 {
24 Cancel cancel(&c);
William A. Kennington III8ec04ce2021-06-29 18:08:30 -070025 EXPECT_TRUE(cancel);
26 Cancel cancel2(std::move(cancel));
27 EXPECT_FALSE(cancel);
28 EXPECT_TRUE(cancel2);
William A. Kennington III458aeae2021-06-14 15:07:16 -070029 EXPECT_EQ(c.count, 0);
30 }
31 EXPECT_EQ(c.count, 1);
32}
33
William A. Kennington III8ec04ce2021-06-29 18:08:30 -070034TEST(CancelTest, EmptyCancel)
35{
36 Cancel cancel, cancel2(std::nullopt);
37 EXPECT_FALSE(cancel);
38 EXPECT_FALSE(cancel2);
39}
40
William A. Kennington III20cab0c2021-06-14 15:13:19 -070041TEST(CancelTest, AlwaysCallOnceLambda)
42{
43 size_t ctr = 0;
44 {
45 auto i = std::make_unique<size_t>(1);
46 auto acb = alwaysCallOnce([&, i = std::move(i)]() { ctr += *i; });
47 EXPECT_EQ(ctr, 0);
48 acb();
49 EXPECT_EQ(ctr, 1);
50 }
51 EXPECT_EQ(ctr, 1);
52 {
53 auto acb = alwaysCallOnce([&](size_t i) { ctr += i; }, 3);
54 EXPECT_EQ(ctr, 1);
55 }
56 EXPECT_EQ(ctr, 4);
57}
58
59TEST(CanceTest, AlwaysCallOnceFunction)
60{
61 size_t ctr = 0;
62 {
63 auto acb = alwaysCallOnce(std::function<void()>(nullptr));
64 }
65 {
66 auto acb = alwaysCallOnce(std::function<void()>([&]() { ctr++; }));
67 EXPECT_EQ(ctr, 0);
68 acb = alwaysCallOnce(std::function<void()>([&]() { ctr += 2; }));
69 EXPECT_EQ(ctr, 1);
70 }
71 EXPECT_EQ(ctr, 3);
72}
73
William A. Kennington III458aeae2021-06-14 15:07:16 -070074} // namespace stdplus