From 4d8a018b0efc7cb3b0c0afbbb43f3a3c8ff22550 Mon Sep 17 00:00:00 2001 From: Guogang Li Date: Mon, 7 Jul 2025 18:56:04 -0700 Subject: [PATCH] Add more unit test for thread pool PiperOrigin-RevId: 780348093 --- .../implementation/windows/thread_pool.cc | 4 +- .../windows/thread_pool_test.cc | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/internal/platform/implementation/windows/thread_pool.cc b/internal/platform/implementation/windows/thread_pool.cc index 52804267..b46879f4 100644 --- a/internal/platform/implementation/windows/thread_pool.cc +++ b/internal/platform/implementation/windows/thread_pool.cc @@ -128,12 +128,12 @@ std::optional ThreadPool::Run(Runnable task, absl::Duration delay, if (task == nullptr) { LOG(WARNING) << __func__ << ": Invalid task."; - return false; + return std::nullopt; } if (is_shut_down_) { LOG(WARNING) << __func__ << ": Thread pool is shut down."; - return false; + return std::nullopt; } // Closing the timer within its callback is prohibited. The thread pool diff --git a/internal/platform/implementation/windows/thread_pool_test.cc b/internal/platform/implementation/windows/thread_pool_test.cc index 0e4f430e..03ee3369 100644 --- a/internal/platform/implementation/windows/thread_pool_test.cc +++ b/internal/platform/implementation/windows/thread_pool_test.cc @@ -189,6 +189,46 @@ TEST(ThreadPool, CancelRepeatedTaskInCallback) { pool->ShutDown(); } +TEST(ThreadPool, CreateWithZeroMaxPoolSizeReturnsNull) { + auto pool = ThreadPool::Create(0); + EXPECT_EQ(pool, nullptr); +} + +TEST(ThreadPool, RunNullTaskReturnsFalse) { + auto pool = ThreadPool::Create(1); + EXPECT_FALSE(pool->Run(nullptr)); + pool->ShutDown(); +} + +TEST(ThreadPool, RunTaskAfterShutdownReturnsFalse) { + auto pool = ThreadPool::Create(1); + pool->ShutDown(); + std::atomic_int value = 0; + EXPECT_FALSE(pool->Run([&]() { value += 1; })); + EXPECT_EQ(value, 0); +} + +TEST(ThreadPool, RunDelayedTaskAfterShutdownReturnsNullOpt) { + auto pool = ThreadPool::Create(1); + pool->ShutDown(); + std::atomic_int value = 0; + std::optional delayed_task_id = + pool->Run([&]() { value += 1; }, absl::Seconds(1)); + EXPECT_FALSE(delayed_task_id.has_value()); + EXPECT_EQ(value, 0); +} + +TEST(ThreadPool, ShutdownWithPendingDelayedTasks) { + auto pool = ThreadPool::Create(1); + std::atomic_int value = 0; + std::optional delayed_task_id = + pool->Run([&]() { value += 1; }, absl::Seconds(2)); + EXPECT_TRUE(delayed_task_id.has_value()); + absl::SleepFor(absl::Milliseconds(100)); + pool->ShutDown(); + EXPECT_EQ(value, 0); +} + } // namespace } // namespace windows } // namespace nearby