| #include "worker_pool.h" | |
| #include <atomic> | |
| #include "gmock/gmock.h" | |
| #include "gtest/gtest.h" | |
| #include "absl/synchronization/notification.h" | |
| #include "absl/time/time.h" | |
| namespace safepower_agent { | |
| namespace { | |
| using ::testing::InSequence; | |
| using ::testing::MockFunction; | |
| TEST(WorkerPoolTest, ExecutesTasksInOrderWithSingleWorker) { | |
| MockFunction<void(int)> step; | |
| { | |
| InSequence seq; | |
| for (int i = 0; i < 5; ++i) { | |
| EXPECT_CALL(step, Call(i)); | |
| } | |
| } | |
| WorkerPool pool(/*num_workers=*/1); | |
| for (int i = 0; i < 5; ++i) { | |
| pool.Schedule([&step, i]() { step.Call(i); }); | |
| } | |
| } | |
| TEST(WorkerPoolTest, ExecutesTasksInParallelWithMultipleWorkers) { | |
| absl::Notification first_started; | |
| absl::Notification second_started; | |
| auto notify_and_wait = [](absl::Notification& own, | |
| absl::Notification& other) { | |
| return [&own, &other]() { | |
| own.Notify(); | |
| EXPECT_TRUE(other.WaitForNotificationWithTimeout(absl::Seconds(5))); | |
| }; | |
| }; | |
| WorkerPool pool(/*num_workers=*/2); | |
| pool.Schedule(notify_and_wait(first_started, second_started)); | |
| pool.Schedule(notify_and_wait(second_started, first_started)); | |
| } | |
| TEST(WorkerPoolTest, DestructorDrainsQueuedTasksWhenWorkersAreBusy) { | |
| absl::Notification both_workers_busy; | |
| absl::Notification release; | |
| std::atomic<int> started{0}; | |
| std::atomic<int> completed{0}; | |
| { | |
| WorkerPool pool(/*num_workers=*/2); | |
| for (int i = 0; i < 10; ++i) { | |
| pool.Schedule([&]() { | |
| if (started.fetch_add(1) + 1 == 2) { | |
| both_workers_busy.Notify(); | |
| } | |
| EXPECT_TRUE(release.WaitForNotificationWithTimeout(absl::Seconds(5))); | |
| completed.fetch_add(1); | |
| }); | |
| } | |
| ASSERT_TRUE( | |
| both_workers_busy.WaitForNotificationWithTimeout(absl::Seconds(5))); | |
| EXPECT_EQ(started.load(), 2); | |
| EXPECT_EQ(completed.load(), 0); | |
| release.Notify(); | |
| } | |
| EXPECT_EQ(completed.load(), 10); | |
| } | |
| TEST(WorkerPoolTest, ClampsZeroWorkersToOne) { | |
| MockFunction<void()> task; | |
| EXPECT_CALL(task, Call()); | |
| WorkerPool pool(/*num_workers=*/0); | |
| pool.Schedule([&task]() { task.Call(); }); | |
| } | |
| } // namespace | |
| } // namespace safepower_agent |