William A. Kennington III | 458aeae | 2021-06-14 15:07:16 -0700 | [diff] [blame] | 1 | #include <stdplus/cancel.hpp> |
| 2 | |
Patrick Williams | d1984dd | 2023-05-10 16:12:44 -0500 | [diff] [blame] | 3 | #include <functional> |
| 4 | |
William A. Kennington III | 458aeae | 2021-06-14 15:07:16 -0700 | [diff] [blame] | 5 | #include <gtest/gtest.h> |
| 6 | |
| 7 | namespace stdplus |
| 8 | { |
| 9 | |
| 10 | struct FakeCancelable : public Cancelable |
| 11 | { |
| 12 | size_t count = 0; |
| 13 | void cancel() noexcept override |
| 14 | { |
| 15 | count++; |
| 16 | } |
| 17 | }; |
| 18 | |
| 19 | TEST(CancelTest, Cancel) |
| 20 | { |
| 21 | FakeCancelable c; |
| 22 | EXPECT_EQ(c.count, 0); |
| 23 | { |
| 24 | Cancel cancel(&c); |
William A. Kennington III | 8ec04ce | 2021-06-29 18:08:30 -0700 | [diff] [blame] | 25 | EXPECT_TRUE(cancel); |
| 26 | Cancel cancel2(std::move(cancel)); |
| 27 | EXPECT_FALSE(cancel); |
| 28 | EXPECT_TRUE(cancel2); |
William A. Kennington III | 458aeae | 2021-06-14 15:07:16 -0700 | [diff] [blame] | 29 | EXPECT_EQ(c.count, 0); |
| 30 | } |
| 31 | EXPECT_EQ(c.count, 1); |
| 32 | } |
| 33 | |
William A. Kennington III | 8ec04ce | 2021-06-29 18:08:30 -0700 | [diff] [blame] | 34 | TEST(CancelTest, EmptyCancel) |
| 35 | { |
| 36 | Cancel cancel, cancel2(std::nullopt); |
| 37 | EXPECT_FALSE(cancel); |
| 38 | EXPECT_FALSE(cancel2); |
| 39 | } |
| 40 | |
William A. Kennington III | 20cab0c | 2021-06-14 15:13:19 -0700 | [diff] [blame] | 41 | TEST(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 | |
| 59 | TEST(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 III | 458aeae | 2021-06-14 15:07:16 -0700 | [diff] [blame] | 74 | } // namespace stdplus |