blob: 51b17b9d8d3002cdb9a10124b568ef6a69058a64 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2016 The Chromium Authors
fdoraya4f28ec2016-06-10 00:08:582// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/run_loop.h"
6
jdoerrie9d7236f62019-03-05 13:00:237#include <functional>
David Bienvenu5f4d4f02020-09-27 16:55:038#include <memory>
Gabriel Charettee2b632b2017-08-02 03:52:169#include <utility>
10
fdoraya4f28ec2016-06-10 00:08:5811#include "base/bind.h"
danakjdb9ae7942020-11-11 16:01:3512#include "base/callback_helpers.h"
Brett Wilsona62d9c02017-09-20 20:53:2013#include "base/containers/queue.h"
fdoraya4f28ec2016-06-10 00:08:5814#include "base/location.h"
Gabriel Charettee2b632b2017-08-02 03:52:1615#include "base/memory/ptr_util.h"
16#include "base/memory/ref_counted.h"
Gabriel Charettee2b632b2017-08-02 03:52:1617#include "base/synchronization/lock.h"
gabcf5e4ce2017-05-19 22:56:5718#include "base/synchronization/waitable_event.h"
Patrick Monette643cdf62021-10-15 19:13:4219#include "base/task/single_thread_task_runner.h"
Guido Urdanetaef4e91942020-11-09 15:06:2420#include "base/test/bind.h"
Gabriel Charettee2b632b2017-08-02 03:52:1621#include "base/test/gtest_util.h"
Wez9d5dd282020-02-10 17:21:2222#include "base/test/scoped_run_loop_timeout.h"
Gabriel Charettec7108742019-08-23 03:31:4023#include "base/test/task_environment.h"
Gabriel Charette3ff403e2017-08-07 04:22:4824#include "base/test/test_timeouts.h"
Gabriel Charettee2b632b2017-08-02 03:52:1625#include "base/threading/platform_thread.h"
Wezd9e4cb772019-01-09 03:07:0326#include "base/threading/sequenced_task_runner_handle.h"
Gabriel Charettee2b632b2017-08-02 03:52:1627#include "base/threading/thread.h"
28#include "base/threading/thread_checker_impl.h"
fdoraya4f28ec2016-06-10 00:08:5829#include "base/threading/thread_task_runner_handle.h"
Gabriel Charettee2b632b2017-08-02 03:52:1630#include "build/build_config.h"
gab7af9dc02017-05-05 13:38:5431#include "testing/gmock/include/gmock/gmock.h"
fdoraya4f28ec2016-06-10 00:08:5832#include "testing/gtest/include/gtest/gtest.h"
33
34namespace base {
35
36namespace {
37
38void QuitWhenIdleTask(RunLoop* run_loop, int* counter) {
39 run_loop->QuitWhenIdle();
40 ++(*counter);
41}
42
fdoraya4f28ec2016-06-10 00:08:5843void RunNestedLoopTask(int* counter) {
Gabriel Charette3ff403e2017-08-07 04:22:4844 RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
fdoraya4f28ec2016-06-10 00:08:5845
46 // This task should quit |nested_run_loop| but not the main RunLoop.
47 ThreadTaskRunnerHandle::Get()->PostTask(
tzik92b7a422017-04-11 15:00:4448 FROM_HERE, BindOnce(&QuitWhenIdleTask, Unretained(&nested_run_loop),
49 Unretained(counter)));
fdoraya4f28ec2016-06-10 00:08:5850
51 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Peter Kasting53fd6ee2021-10-05 20:40:4852 FROM_HERE, MakeExpectedNotRunClosure(FROM_HERE), Days(1));
fdoraya4f28ec2016-06-10 00:08:5853
fdoraya4f28ec2016-06-10 00:08:5854 nested_run_loop.Run();
55
56 ++(*counter);
57}
58
Gabriel Charettee2b632b2017-08-02 03:52:1659// A simple SingleThreadTaskRunner that just queues undelayed tasks (and ignores
60// delayed tasks). Tasks can then be processed one by one by ProcessTask() which
61// will return true if it processed a task and false otherwise.
62class SimpleSingleThreadTaskRunner : public SingleThreadTaskRunner {
63 public:
64 SimpleSingleThreadTaskRunner() = default;
David Bienvenu5f4d4f02020-09-27 16:55:0365 SimpleSingleThreadTaskRunner(const SimpleSingleThreadTaskRunner&) = delete;
66 SimpleSingleThreadTaskRunner& operator=(const SimpleSingleThreadTaskRunner&) =
67 delete;
fdoraya4f28ec2016-06-10 00:08:5868
Brett Wilson8e88b312017-09-12 05:22:1669 bool PostDelayedTask(const Location& from_here,
Gabriel Charettee2b632b2017-08-02 03:52:1670 OnceClosure task,
71 base::TimeDelta delay) override {
Xiaohan Wangabff0302021-10-27 00:42:5772 if (delay.is_positive())
Gabriel Charettee2b632b2017-08-02 03:52:1673 return false;
74 AutoLock auto_lock(tasks_lock_);
75 pending_tasks_.push(std::move(task));
76 return true;
77 }
78
Brett Wilson8e88b312017-09-12 05:22:1679 bool PostNonNestableDelayedTask(const Location& from_here,
Gabriel Charettee2b632b2017-08-02 03:52:1680 OnceClosure task,
81 base::TimeDelta delay) override {
82 return PostDelayedTask(from_here, std::move(task), delay);
83 }
84
85 bool RunsTasksInCurrentSequence() const override {
86 return origin_thread_checker_.CalledOnValidThread();
87 }
88
Gabriel Charette1ef212b2017-12-03 12:47:2189 bool ProcessSingleTask() {
Gabriel Charettee2b632b2017-08-02 03:52:1690 OnceClosure task;
91 {
92 AutoLock auto_lock(tasks_lock_);
93 if (pending_tasks_.empty())
94 return false;
95 task = std::move(pending_tasks_.front());
96 pending_tasks_.pop();
97 }
98 // It's important to Run() after pop() and outside the lock as |task| may
Gabriel Charette1ef212b2017-12-03 12:47:2199 // run a nested loop which will re-enter ProcessSingleTask().
Gabriel Charettee2b632b2017-08-02 03:52:16100 std::move(task).Run();
101 return true;
102 }
103
104 private:
105 ~SimpleSingleThreadTaskRunner() override = default;
106
107 Lock tasks_lock_;
Brett Wilsona62d9c02017-09-20 20:53:20108 base::queue<OnceClosure> pending_tasks_;
Gabriel Charettee2b632b2017-08-02 03:52:16109
110 // RunLoop relies on RunsTasksInCurrentSequence() signal. Use a
111 // ThreadCheckerImpl to be able to reliably provide that signal even in
112 // non-dcheck builds.
113 ThreadCheckerImpl origin_thread_checker_;
Gabriel Charettee2b632b2017-08-02 03:52:16114};
115
Gabriel Charette1ef212b2017-12-03 12:47:21116// The basis of all TestDelegates, allows safely injecting a OnceClosure to be
117// run in the next idle phase of this delegate's Run() implementation. This can
118// be used to have code run on a thread that is otherwise livelocked in an idle
119// phase (sometimes a simple PostTask() won't do it -- e.g. when processing
120// application tasks is disallowed).
121class InjectableTestDelegate : public RunLoop::Delegate {
Gabriel Charettee2b632b2017-08-02 03:52:16122 public:
Gabriel Charette1ef212b2017-12-03 12:47:21123 void InjectClosureOnDelegate(OnceClosure closure) {
124 AutoLock auto_lock(closure_lock_);
125 closure_ = std::move(closure);
126 }
Gabriel Charettee2b632b2017-08-02 03:52:16127
Gabriel Charette1ef212b2017-12-03 12:47:21128 bool RunInjectedClosure() {
129 AutoLock auto_lock(closure_lock_);
130 if (closure_.is_null())
131 return false;
132 std::move(closure_).Run();
133 return true;
134 }
135
136 private:
137 Lock closure_lock_;
138 OnceClosure closure_;
139};
140
141// A simple test RunLoop::Delegate to exercise Runloop logic independent of any
142// other base constructs. BindToCurrentThread() must be called before this
143// TestBoundDelegate is operational.
144class TestBoundDelegate final : public InjectableTestDelegate {
145 public:
146 TestBoundDelegate() = default;
147
148 // Makes this TestBoundDelegate become the RunLoop::Delegate and
149 // ThreadTaskRunnerHandle for this thread.
Gabriel Charettee2b632b2017-08-02 03:52:16150 void BindToCurrentThread() {
151 thread_task_runner_handle_ =
Jeremy Roman9532f252017-08-16 23:27:24152 std::make_unique<ThreadTaskRunnerHandle>(simple_task_runner_);
Gabriel Charettea3ec9612017-12-14 17:22:40153 RunLoop::RegisterDelegateForCurrentThread(this);
Gabriel Charettee2b632b2017-08-02 03:52:16154 }
155
156 private:
Alex Clarke9752bbf2019-04-01 10:41:20157 void Run(bool application_tasks_allowed, TimeDelta timeout) override {
Gabriel Charette3ff403e2017-08-07 04:22:48158 if (nested_run_allowing_tasks_incoming_) {
Gabriel Charette1ef212b2017-12-03 12:47:21159 EXPECT_TRUE(RunLoop::IsNestedOnCurrentThread());
Gabriel Charetteb030a4a2017-10-26 01:04:40160 EXPECT_TRUE(application_tasks_allowed);
Gabriel Charette1ef212b2017-12-03 12:47:21161 } else if (RunLoop::IsNestedOnCurrentThread()) {
Gabriel Charetteb030a4a2017-10-26 01:04:40162 EXPECT_FALSE(application_tasks_allowed);
Gabriel Charette3ff403e2017-08-07 04:22:48163 }
164 nested_run_allowing_tasks_incoming_ = false;
165
Gabriel Charettee2b632b2017-08-02 03:52:16166 while (!should_quit_) {
Gabriel Charette1ef212b2017-12-03 12:47:21167 if (application_tasks_allowed && simple_task_runner_->ProcessSingleTask())
Gabriel Charettee2b632b2017-08-02 03:52:16168 continue;
169
Gabriel Charettea3ec9612017-12-14 17:22:40170 if (ShouldQuitWhenIdle())
Gabriel Charettee2b632b2017-08-02 03:52:16171 break;
172
Gabriel Charette1ef212b2017-12-03 12:47:21173 if (RunInjectedClosure())
174 continue;
Gabriel Charette3ff403e2017-08-07 04:22:48175
Gabriel Charettee2b632b2017-08-02 03:52:16176 PlatformThread::YieldCurrentThread();
177 }
178 should_quit_ = false;
179 }
180
181 void Quit() override { should_quit_ = true; }
182
Gabriel Charette3ff403e2017-08-07 04:22:48183 void EnsureWorkScheduled() override {
184 nested_run_allowing_tasks_incoming_ = true;
185 }
186
187 // True if the next invocation of Run() is expected to be from a
188 // kNestableTasksAllowed RunLoop.
189 bool nested_run_allowing_tasks_incoming_ = false;
190
Gabriel Charettee2b632b2017-08-02 03:52:16191 scoped_refptr<SimpleSingleThreadTaskRunner> simple_task_runner_ =
192 MakeRefCounted<SimpleSingleThreadTaskRunner>();
Gabriel Charette1ef212b2017-12-03 12:47:21193
Gabriel Charettee2b632b2017-08-02 03:52:16194 std::unique_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
195
196 bool should_quit_ = false;
Gabriel Charette1ef212b2017-12-03 12:47:21197};
198
Gabriel Charettee2b632b2017-08-02 03:52:16199enum class RunLoopTestType {
Gabriel Charette694c3c332019-08-19 14:53:05200 // Runs all RunLoopTests under a TaskEnvironment to make sure real world
Gabriel Charettee2b632b2017-08-02 03:52:16201 // scenarios work.
202 kRealEnvironment,
203
204 // Runs all RunLoopTests under a test RunLoop::Delegate to make sure the
205 // delegate interface fully works standalone.
206 kTestDelegate,
207};
208
209// The task environment for the RunLoopTest of a given type. A separate class
210// so it can be instantiated on the stack in the RunLoopTest fixture.
211class RunLoopTestEnvironment {
212 public:
David Bienvenu5f4d4f02020-09-27 16:55:03213 explicit RunLoopTestEnvironment(RunLoopTestType type) {
Gabriel Charettee2b632b2017-08-02 03:52:16214 switch (type) {
Gabriel Charette1ef212b2017-12-03 12:47:21215 case RunLoopTestType::kRealEnvironment: {
Gabriel Charette694c3c332019-08-19 14:53:05216 task_environment_ = std::make_unique<test::TaskEnvironment>();
Gabriel Charettee2b632b2017-08-02 03:52:16217 break;
Gabriel Charette1ef212b2017-12-03 12:47:21218 }
219 case RunLoopTestType::kTestDelegate: {
220 auto test_delegate = std::make_unique<TestBoundDelegate>();
221 test_delegate->BindToCurrentThread();
222 test_delegate_ = std::move(test_delegate);
Gabriel Charettee2b632b2017-08-02 03:52:16223 break;
Gabriel Charette1ef212b2017-12-03 12:47:21224 }
Gabriel Charettee2b632b2017-08-02 03:52:16225 }
226 }
227
228 private:
Gabriel Charette50518fc2018-05-22 17:53:22229 // Instantiates one or the other based on the RunLoopTestType.
Gabriel Charette694c3c332019-08-19 14:53:05230 std::unique_ptr<test::TaskEnvironment> task_environment_;
Gabriel Charette1ef212b2017-12-03 12:47:21231 std::unique_ptr<InjectableTestDelegate> test_delegate_;
Gabriel Charettee2b632b2017-08-02 03:52:16232};
233
234class RunLoopTest : public testing::TestWithParam<RunLoopTestType> {
David Bienvenu5f4d4f02020-09-27 16:55:03235 public:
236 RunLoopTest(const RunLoopTest&) = delete;
237 RunLoopTest& operator=(const RunLoopTest&) = delete;
238
Gabriel Charettee2b632b2017-08-02 03:52:16239 protected:
240 RunLoopTest() : test_environment_(GetParam()) {}
241
242 RunLoopTestEnvironment test_environment_;
fdoraya4f28ec2016-06-10 00:08:58243 RunLoop run_loop_;
fdoraya4f28ec2016-06-10 00:08:58244};
245
246} // namespace
247
Gabriel Charettee2b632b2017-08-02 03:52:16248TEST_P(RunLoopTest, QuitWhenIdle) {
Wezbbffcc52019-02-21 02:01:20249 int counter = 0;
gab7af9dc02017-05-05 13:38:54250 ThreadTaskRunnerHandle::Get()->PostTask(
tzik92b7a422017-04-11 15:00:44251 FROM_HERE, BindOnce(&QuitWhenIdleTask, Unretained(&run_loop_),
Wezbbffcc52019-02-21 02:01:20252 Unretained(&counter)));
253 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
254 MakeExpectedRunClosure(FROM_HERE));
gab7af9dc02017-05-05 13:38:54255 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Peter Kasting53fd6ee2021-10-05 20:40:48256 FROM_HERE, MakeExpectedNotRunClosure(FROM_HERE), Days(1));
fdoraya4f28ec2016-06-10 00:08:58257
258 run_loop_.Run();
Wezbbffcc52019-02-21 02:01:20259 EXPECT_EQ(1, counter);
fdoraya4f28ec2016-06-10 00:08:58260}
261
Gabriel Charettee2b632b2017-08-02 03:52:16262TEST_P(RunLoopTest, QuitWhenIdleNestedLoop) {
Wezbbffcc52019-02-21 02:01:20263 int counter = 0;
gab7af9dc02017-05-05 13:38:54264 ThreadTaskRunnerHandle::Get()->PostTask(
Wezbbffcc52019-02-21 02:01:20265 FROM_HERE, BindOnce(&RunNestedLoopTask, Unretained(&counter)));
gab7af9dc02017-05-05 13:38:54266 ThreadTaskRunnerHandle::Get()->PostTask(
tzik92b7a422017-04-11 15:00:44267 FROM_HERE, BindOnce(&QuitWhenIdleTask, Unretained(&run_loop_),
Wezbbffcc52019-02-21 02:01:20268 Unretained(&counter)));
269 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
270 MakeExpectedRunClosure(FROM_HERE));
gab7af9dc02017-05-05 13:38:54271 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Peter Kasting53fd6ee2021-10-05 20:40:48272 FROM_HERE, MakeExpectedNotRunClosure(FROM_HERE), Days(1));
fdoraya4f28ec2016-06-10 00:08:58273
274 run_loop_.Run();
Wezbbffcc52019-02-21 02:01:20275 EXPECT_EQ(3, counter);
fdoraya4f28ec2016-06-10 00:08:58276}
277
Gabriel Charettee2b632b2017-08-02 03:52:16278TEST_P(RunLoopTest, QuitWhenIdleClosure) {
gab7af9dc02017-05-05 13:38:54279 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
280 run_loop_.QuitWhenIdleClosure());
Wezbbffcc52019-02-21 02:01:20281 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
282 MakeExpectedRunClosure(FROM_HERE));
gab7af9dc02017-05-05 13:38:54283 ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Peter Kasting53fd6ee2021-10-05 20:40:48284 FROM_HERE, MakeExpectedNotRunClosure(FROM_HERE), Days(1));
fdoraya3658602016-06-10 18:23:15285
286 run_loop_.Run();
fdoraya3658602016-06-10 18:23:15287}
288
289// Verify that the QuitWhenIdleClosure() can run after the RunLoop has been
290// deleted. It should have no effect.
Gabriel Charettee2b632b2017-08-02 03:52:16291TEST_P(RunLoopTest, QuitWhenIdleClosureAfterRunLoopScope) {
kylechar650caf02019-07-17 03:25:41292 RepeatingClosure quit_when_idle_closure;
fdoraya3658602016-06-10 18:23:15293 {
294 RunLoop run_loop;
295 quit_when_idle_closure = run_loop.QuitWhenIdleClosure();
296 run_loop.RunUntilIdle();
297 }
298 quit_when_idle_closure.Run();
299}
300
gabcf5e4ce2017-05-19 22:56:57301// Verify that Quit can be executed from another sequence.
Gabriel Charettee2b632b2017-08-02 03:52:16302TEST_P(RunLoopTest, QuitFromOtherSequence) {
303 Thread other_thread("test");
304 other_thread.Start();
gabcf5e4ce2017-05-19 22:56:57305 scoped_refptr<SequencedTaskRunner> other_sequence =
Gabriel Charettee2b632b2017-08-02 03:52:16306 other_thread.task_runner();
gabcf5e4ce2017-05-19 22:56:57307
308 // Always expected to run before asynchronous Quit() kicks in.
Wezbbffcc52019-02-21 02:01:20309 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
310 MakeExpectedRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57311
312 WaitableEvent loop_was_quit(WaitableEvent::ResetPolicy::MANUAL,
313 WaitableEvent::InitialState::NOT_SIGNALED);
314 other_sequence->PostTask(
315 FROM_HERE, base::BindOnce([](RunLoop* run_loop) { run_loop->Quit(); },
316 Unretained(&run_loop_)));
317 other_sequence->PostTask(
318 FROM_HERE,
319 base::BindOnce(&WaitableEvent::Signal, base::Unretained(&loop_was_quit)));
320
321 // Anything that's posted after the Quit closure was posted back to this
322 // sequence shouldn't get a chance to run.
323 loop_was_quit.Wait();
Gabriel Charettee2b632b2017-08-02 03:52:16324 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
Wezbbffcc52019-02-21 02:01:20325 MakeExpectedNotRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57326
327 run_loop_.Run();
gabcf5e4ce2017-05-19 22:56:57328}
329
330// Verify that QuitClosure can be executed from another sequence.
Gabriel Charettee2b632b2017-08-02 03:52:16331TEST_P(RunLoopTest, QuitFromOtherSequenceWithClosure) {
332 Thread other_thread("test");
333 other_thread.Start();
gabcf5e4ce2017-05-19 22:56:57334 scoped_refptr<SequencedTaskRunner> other_sequence =
Gabriel Charettee2b632b2017-08-02 03:52:16335 other_thread.task_runner();
gabcf5e4ce2017-05-19 22:56:57336
337 // Always expected to run before asynchronous Quit() kicks in.
Wezbbffcc52019-02-21 02:01:20338 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
339 MakeExpectedRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57340
341 WaitableEvent loop_was_quit(WaitableEvent::ResetPolicy::MANUAL,
342 WaitableEvent::InitialState::NOT_SIGNALED);
343 other_sequence->PostTask(FROM_HERE, run_loop_.QuitClosure());
344 other_sequence->PostTask(
345 FROM_HERE,
346 base::BindOnce(&WaitableEvent::Signal, base::Unretained(&loop_was_quit)));
347
348 // Anything that's posted after the Quit closure was posted back to this
349 // sequence shouldn't get a chance to run.
350 loop_was_quit.Wait();
Gabriel Charettee2b632b2017-08-02 03:52:16351 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
Wezbbffcc52019-02-21 02:01:20352 MakeExpectedNotRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57353
354 run_loop_.Run();
gabcf5e4ce2017-05-19 22:56:57355}
356
357// Verify that Quit can be executed from another sequence even when the
358// Quit is racing with Run() -- i.e. forgo the WaitableEvent used above.
Gabriel Charettee2b632b2017-08-02 03:52:16359TEST_P(RunLoopTest, QuitFromOtherSequenceRacy) {
360 Thread other_thread("test");
361 other_thread.Start();
gabcf5e4ce2017-05-19 22:56:57362 scoped_refptr<SequencedTaskRunner> other_sequence =
Gabriel Charettee2b632b2017-08-02 03:52:16363 other_thread.task_runner();
gabcf5e4ce2017-05-19 22:56:57364
365 // Always expected to run before asynchronous Quit() kicks in.
Wezbbffcc52019-02-21 02:01:20366 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
367 MakeExpectedRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57368
Wezbbffcc52019-02-21 02:01:20369 other_sequence->PostTask(FROM_HERE, run_loop_.QuitClosure());
gabcf5e4ce2017-05-19 22:56:57370
371 run_loop_.Run();
gabcf5e4ce2017-05-19 22:56:57372}
373
374// Verify that QuitClosure can be executed from another sequence even when the
375// Quit is racing with Run() -- i.e. forgo the WaitableEvent used above.
Gabriel Charettee2b632b2017-08-02 03:52:16376TEST_P(RunLoopTest, QuitFromOtherSequenceRacyWithClosure) {
377 Thread other_thread("test");
378 other_thread.Start();
gabcf5e4ce2017-05-19 22:56:57379 scoped_refptr<SequencedTaskRunner> other_sequence =
Gabriel Charettee2b632b2017-08-02 03:52:16380 other_thread.task_runner();
gabcf5e4ce2017-05-19 22:56:57381
382 // Always expected to run before asynchronous Quit() kicks in.
Wezbbffcc52019-02-21 02:01:20383 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
384 MakeExpectedRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57385
386 other_sequence->PostTask(FROM_HERE, run_loop_.QuitClosure());
387
388 run_loop_.Run();
gabcf5e4ce2017-05-19 22:56:57389}
390
391// Verify that QuitWhenIdle can be executed from another sequence.
Gabriel Charettee2b632b2017-08-02 03:52:16392TEST_P(RunLoopTest, QuitWhenIdleFromOtherSequence) {
393 Thread other_thread("test");
394 other_thread.Start();
gabcf5e4ce2017-05-19 22:56:57395 scoped_refptr<SequencedTaskRunner> other_sequence =
Gabriel Charettee2b632b2017-08-02 03:52:16396 other_thread.task_runner();
gabcf5e4ce2017-05-19 22:56:57397
Wezbbffcc52019-02-21 02:01:20398 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
399 MakeExpectedRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57400
401 other_sequence->PostTask(
402 FROM_HERE,
403 base::BindOnce([](RunLoop* run_loop) { run_loop->QuitWhenIdle(); },
404 Unretained(&run_loop_)));
405
Wezbbffcc52019-02-21 02:01:20406 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
407 MakeExpectedRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57408
409 run_loop_.Run();
410
411 // Regardless of the outcome of the race this thread shouldn't have been idle
Wezbbffcc52019-02-21 02:01:20412 // until both tasks posted to this sequence have run.
gabcf5e4ce2017-05-19 22:56:57413}
414
415// Verify that QuitWhenIdleClosure can be executed from another sequence.
Gabriel Charettee2b632b2017-08-02 03:52:16416TEST_P(RunLoopTest, QuitWhenIdleFromOtherSequenceWithClosure) {
417 Thread other_thread("test");
418 other_thread.Start();
gabcf5e4ce2017-05-19 22:56:57419 scoped_refptr<SequencedTaskRunner> other_sequence =
Gabriel Charettee2b632b2017-08-02 03:52:16420 other_thread.task_runner();
gabcf5e4ce2017-05-19 22:56:57421
Wezbbffcc52019-02-21 02:01:20422 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
423 MakeExpectedRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57424
425 other_sequence->PostTask(FROM_HERE, run_loop_.QuitWhenIdleClosure());
426
Wezbbffcc52019-02-21 02:01:20427 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
428 MakeExpectedRunClosure(FROM_HERE));
gabcf5e4ce2017-05-19 22:56:57429
430 run_loop_.Run();
431
432 // Regardless of the outcome of the race this thread shouldn't have been idle
Wezbbffcc52019-02-21 02:01:20433 // until the both tasks posted to this sequence have run.
gabcf5e4ce2017-05-19 22:56:57434}
435
Gabriel Charettee2b632b2017-08-02 03:52:16436TEST_P(RunLoopTest, IsRunningOnCurrentThread) {
gab7af9dc02017-05-05 13:38:54437 EXPECT_FALSE(RunLoop::IsRunningOnCurrentThread());
438 ThreadTaskRunnerHandle::Get()->PostTask(
439 FROM_HERE,
tzik0c100dc2017-06-26 06:13:17440 BindOnce([]() { EXPECT_TRUE(RunLoop::IsRunningOnCurrentThread()); }));
gab7af9dc02017-05-05 13:38:54441 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
442 run_loop_.Run();
443}
444
Gabriel Charettee2b632b2017-08-02 03:52:16445TEST_P(RunLoopTest, IsNestedOnCurrentThread) {
gab7af9dc02017-05-05 13:38:54446 EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
447
448 ThreadTaskRunnerHandle::Get()->PostTask(
tzik0c100dc2017-06-26 06:13:17449 FROM_HERE, BindOnce([]() {
gab7af9dc02017-05-05 13:38:54450 EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
451
Gabriel Charette3ff403e2017-08-07 04:22:48452 RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
gab7af9dc02017-05-05 13:38:54453
454 ThreadTaskRunnerHandle::Get()->PostTask(
tzik0c100dc2017-06-26 06:13:17455 FROM_HERE, BindOnce([]() {
456 EXPECT_TRUE(RunLoop::IsNestedOnCurrentThread());
457 }));
gab7af9dc02017-05-05 13:38:54458 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
459 nested_run_loop.QuitClosure());
460
461 EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
gab7af9dc02017-05-05 13:38:54462 nested_run_loop.Run();
463 EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
464 }));
465
466 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
467 run_loop_.Run();
468}
469
Gabriel Charette2a53350172021-05-06 20:22:55470TEST_P(RunLoopTest, CannotRunMoreThanOnce) {
471 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
472 run_loop_.Run();
473 EXPECT_DCHECK_DEATH({ run_loop_.Run(); });
474}
475
476TEST_P(RunLoopTest, CanRunUntilIdleMoreThanOnce) {
477 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
478 run_loop_.RunUntilIdle();
479
480 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
481 run_loop_.RunUntilIdle();
482 run_loop_.RunUntilIdle();
483}
484
485TEST_P(RunLoopTest, CanRunUntilIdleThenRunIfNotQuit) {
486 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
487 run_loop_.RunUntilIdle();
488
489 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
490 run_loop_.Run();
491}
492
493TEST_P(RunLoopTest, CannotRunUntilIdleThenRunIfQuit) {
494 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
495 run_loop_.RunUntilIdle();
496
497 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
498 EXPECT_DCHECK_DEATH({ run_loop_.Run(); });
499}
500
501TEST_P(RunLoopTest, CannotRunAgainIfQuitWhenIdle) {
502 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
503 run_loop_.QuitWhenIdleClosure());
504 run_loop_.RunUntilIdle();
505
506 EXPECT_DCHECK_DEATH({ run_loop_.RunUntilIdle(); });
507}
508
Francois Doray80bdddf2018-01-04 16:17:32509namespace {
510
gab7af9dc02017-05-05 13:38:54511class MockNestingObserver : public RunLoop::NestingObserver {
512 public:
513 MockNestingObserver() = default;
David Bienvenu5f4d4f02020-09-27 16:55:03514 MockNestingObserver(const MockNestingObserver&) = delete;
515 MockNestingObserver& operator=(const MockNestingObserver&) = delete;
gab7af9dc02017-05-05 13:38:54516
517 // RunLoop::NestingObserver:
518 MOCK_METHOD0(OnBeginNestedRunLoop, void());
Francois Doray80bdddf2018-01-04 16:17:32519 MOCK_METHOD0(OnExitNestedRunLoop, void());
gab7af9dc02017-05-05 13:38:54520};
521
Francois Doray80bdddf2018-01-04 16:17:32522class MockTask {
523 public:
524 MockTask() = default;
David Bienvenu5f4d4f02020-09-27 16:55:03525 MockTask(const MockTask&) = delete;
526 MockTask& operator=(const MockTask&) = delete;
Francois Doray80bdddf2018-01-04 16:17:32527
David Bienvenu5f4d4f02020-09-27 16:55:03528 MOCK_METHOD0(Task, void());
Francois Doray80bdddf2018-01-04 16:17:32529};
530
531} // namespace
532
Gabriel Charettee2b632b2017-08-02 03:52:16533TEST_P(RunLoopTest, NestingObservers) {
gab7af9dc02017-05-05 13:38:54534 testing::StrictMock<MockNestingObserver> nesting_observer;
Francois Doray80bdddf2018-01-04 16:17:32535 testing::StrictMock<MockTask> mock_task_a;
536 testing::StrictMock<MockTask> mock_task_b;
gab7af9dc02017-05-05 13:38:54537
538 RunLoop::AddNestingObserverOnCurrentThread(&nesting_observer);
539
kylechar01598d72019-05-21 18:35:31540 const RepeatingClosure run_nested_loop = BindRepeating([]() {
Gabriel Charette3ff403e2017-08-07 04:22:48541 RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
gab7af9dc02017-05-05 13:38:54542 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
543 nested_run_loop.QuitClosure());
gab7af9dc02017-05-05 13:38:54544 nested_run_loop.Run();
545 });
546
Francois Doray80bdddf2018-01-04 16:17:32547 // Generate a stack of nested RunLoops. OnBeginNestedRunLoop() is expected
548 // when beginning each nesting depth and OnExitNestedRunLoop() is expected
Gabriel Charetted8839442018-03-15 18:56:22549 // when exiting each nesting depth. Each one of these tasks is ahead of the
550 // QuitClosures as those are only posted at the end of the queue when
551 // |run_nested_loop| is executed.
gab7af9dc02017-05-05 13:38:54552 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_nested_loop);
Francois Doray80bdddf2018-01-04 16:17:32553 ThreadTaskRunnerHandle::Get()->PostTask(
554 FROM_HERE,
555 base::BindOnce(&MockTask::Task, base::Unretained(&mock_task_a)));
gab7af9dc02017-05-05 13:38:54556 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_nested_loop);
Francois Doray80bdddf2018-01-04 16:17:32557 ThreadTaskRunnerHandle::Get()->PostTask(
558 FROM_HERE,
559 base::BindOnce(&MockTask::Task, base::Unretained(&mock_task_b)));
gab7af9dc02017-05-05 13:38:54560
Francois Doray80bdddf2018-01-04 16:17:32561 {
562 testing::InSequence in_sequence;
563 EXPECT_CALL(nesting_observer, OnBeginNestedRunLoop());
564 EXPECT_CALL(mock_task_a, Task());
565 EXPECT_CALL(nesting_observer, OnBeginNestedRunLoop());
566 EXPECT_CALL(mock_task_b, Task());
567 EXPECT_CALL(nesting_observer, OnExitNestedRunLoop()).Times(2);
568 }
569 run_loop_.RunUntilIdle();
gab7af9dc02017-05-05 13:38:54570
571 RunLoop::RemoveNestingObserverOnCurrentThread(&nesting_observer);
572}
573
Minoru Chikamune76ba6822021-01-12 10:39:51574TEST_P(RunLoopTest, DisallowRunning) {
Hans Wennborg9b292ba2022-02-15 16:01:29575 ScopedDisallowRunningRunLoop disallow_running;
Gabriel Charettef3fd8f02018-05-22 15:31:48576 EXPECT_DCHECK_DEATH({ run_loop_.RunUntilIdle(); });
Gabriel Charettea44975052017-08-21 23:14:04577}
578
Minoru Chikamune76ba6822021-01-12 10:39:51579TEST_P(RunLoopTest, ExpiredDisallowRunning) {
Hans Wennborg9b292ba2022-02-15 16:01:29580 { ScopedDisallowRunningRunLoop disallow_running; }
Gabriel Charettea44975052017-08-21 23:14:04581 // Running should be fine after |disallow_running| goes out of scope.
582 run_loop_.RunUntilIdle();
583}
584
Victor Costan033b9ac2019-01-29 00:52:16585INSTANTIATE_TEST_SUITE_P(Real,
586 RunLoopTest,
587 testing::Values(RunLoopTestType::kRealEnvironment));
588INSTANTIATE_TEST_SUITE_P(Mock,
589 RunLoopTest,
590 testing::Values(RunLoopTestType::kTestDelegate));
Gabriel Charettee2b632b2017-08-02 03:52:16591
592TEST(RunLoopDeathTest, MustRegisterBeforeInstantiating) {
Gabriel Charette1ef212b2017-12-03 12:47:21593 TestBoundDelegate unbound_test_delegate_;
Wez39ee6102018-04-14 21:33:59594 // RunLoop::RunLoop() should CHECK fetching the ThreadTaskRunnerHandle.
595 EXPECT_DEATH_IF_SUPPORTED({ RunLoop(); }, "");
Gabriel Charettee2b632b2017-08-02 03:52:16596}
597
Gabriel Charette3ff403e2017-08-07 04:22:48598TEST(RunLoopDelegateTest, NestableTasksDontRunInDefaultNestedLoops) {
Gabriel Charette1ef212b2017-12-03 12:47:21599 TestBoundDelegate test_delegate;
Gabriel Charette3ff403e2017-08-07 04:22:48600 test_delegate.BindToCurrentThread();
601
602 base::Thread other_thread("test");
603 other_thread.Start();
604
605 RunLoop main_loop;
606 // A nested run loop which isn't kNestableTasksAllowed.
607 RunLoop nested_run_loop(RunLoop::Type::kDefault);
608
609 bool nested_run_loop_ended = false;
610
611 // The first task on the main loop will result in a nested run loop. Since
612 // it's not kNestableTasksAllowed, no further task should be processed until
613 // it's quit.
614 ThreadTaskRunnerHandle::Get()->PostTask(
615 FROM_HERE,
616 BindOnce([](RunLoop* nested_run_loop) { nested_run_loop->Run(); },
617 Unretained(&nested_run_loop)));
618
619 // Post a task that will fail if it runs inside the nested run loop.
620 ThreadTaskRunnerHandle::Get()->PostTask(
jdoerrie9d7236f62019-03-05 13:00:23621 FROM_HERE,
622 BindOnce(
623 [](const bool& nested_run_loop_ended,
624 OnceClosure continuation_callback) {
625 EXPECT_TRUE(nested_run_loop_ended);
626 EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
627 std::move(continuation_callback).Run();
628 },
629 std::cref(nested_run_loop_ended), main_loop.QuitClosure()));
Gabriel Charette3ff403e2017-08-07 04:22:48630
631 // Post a task flipping the boolean bit for extra verification right before
632 // quitting |nested_run_loop|.
633 other_thread.task_runner()->PostDelayedTask(
634 FROM_HERE,
635 BindOnce(
636 [](bool* nested_run_loop_ended) {
637 EXPECT_FALSE(*nested_run_loop_ended);
638 *nested_run_loop_ended = true;
639 },
640 Unretained(&nested_run_loop_ended)),
641 TestTimeouts::tiny_timeout());
642 // Post an async delayed task to exit the run loop when idle. This confirms
643 // that (1) the test task only ran in the main loop after the nested loop
644 // exited and (2) the nested run loop actually considers itself idle while
645 // spinning. Note: The quit closure needs to be injected directly on the
646 // delegate as invoking QuitWhenIdle() off-thread results in a thread bounce
647 // which will not processed because of the very logic under test (nestable
648 // tasks don't run in |nested_run_loop|).
649 other_thread.task_runner()->PostDelayedTask(
650 FROM_HERE,
651 BindOnce(
Gabriel Charette1ef212b2017-12-03 12:47:21652 [](TestBoundDelegate* test_delegate, OnceClosure injected_closure) {
653 test_delegate->InjectClosureOnDelegate(std::move(injected_closure));
Gabriel Charette3ff403e2017-08-07 04:22:48654 },
655 Unretained(&test_delegate), nested_run_loop.QuitWhenIdleClosure()),
656 TestTimeouts::tiny_timeout());
657
658 main_loop.Run();
659}
660
fdoraya4f28ec2016-06-10 00:08:58661} // namespace base