Add test to ensure task deleted on TQ

Bug: webrtc:14449
Change-Id: I85757af9c1ad6ad630d9ffe7b2528ca7c7161883
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/308900
Reviewed-by: Danil Chapovalov <danilchap@webrtc.org>
Commit-Queue: Per Kjellander <perkj@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#40301}
diff --git a/api/task_queue/task_queue_test.cc b/api/task_queue/task_queue_test.cc
index 7849f42..b02333e 100644
--- a/api/task_queue/task_queue_test.cc
+++ b/api/task_queue/task_queue_test.cc
@@ -177,14 +177,35 @@
       CreateTaskQueue(factory, "PostedUnexecutedClosureDestroyedOnTaskQueue");
   TaskQueueBase* queue_ptr = queue.get();
   queue->PostTask([] { SleepFor(TimeDelta::Millis(100)); });
-  // Give the task queue a chance to start executing the first lambda.
+  //  Give the task queue a chance to start executing the first lambda.
   SleepFor(TimeDelta::Millis(10));
-  // Then ensure the next lambda (which is likely not executing yet) is
-  // destroyed in the task queue context when the queue is deleted.
-  auto cleanup = absl::Cleanup(
-      [queue_ptr] { EXPECT_EQ(queue_ptr, TaskQueueBase::Current()); });
+  rtc::Event finished;
+  //  Then ensure the next lambda (which is likely not executing yet) is
+  //  destroyed in the task queue context when the queue is deleted.
+  auto cleanup = absl::Cleanup([queue_ptr, &finished] {
+    EXPECT_EQ(queue_ptr, TaskQueueBase::Current());
+    finished.Set();
+  });
   queue->PostTask([cleanup = std::move(cleanup)] {});
   queue = nullptr;
+  finished.Wait(TimeDelta::Seconds(1));
+}
+
+TEST_P(TaskQueueTest, PostedClosureDestroyedOnTaskQueue) {
+  std::unique_ptr<webrtc::TaskQueueFactory> factory = GetParam()(nullptr);
+  auto queue = CreateTaskQueue(factory, "PostedClosureDestroyedOnTaskQueue");
+  TaskQueueBase* queue_ptr = queue.get();
+  rtc::Event finished;
+  auto cleanup = absl::Cleanup([queue_ptr, &finished] {
+    EXPECT_EQ(queue_ptr, TaskQueueBase::Current());
+    finished.Set();
+  });
+  // The cleanup task may or may not have had time to execute when the task
+  // queue is destroyed. Regardless, the task should be destroyed on the
+  // queue.
+  queue->PostTask([cleanup = std::move(cleanup)] {});
+  queue = nullptr;
+  finished.Wait(TimeDelta::Seconds(1));
 }
 
 TEST_P(TaskQueueTest, PostedExecutedClosureDestroyedOnTaskQueue) {
@@ -198,7 +219,7 @@
                      EXPECT_EQ(queue_ptr, TaskQueueBase::Current());
                      finished.Set();
                    })] {});
-  finished.Wait(rtc::Event::kForever);
+  finished.Wait(TimeDelta::Seconds(1));
 }
 
 TEST_P(TaskQueueTest, PostAndReuse) {