run_loop_unittest.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. // Copyright 2016 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/run_loop.h"
  5. #include <functional>
  6. #include <memory>
  7. #include <utility>
  8. #include "base/bind.h"
  9. #include "base/callback_helpers.h"
  10. #include "base/containers/queue.h"
  11. #include "base/location.h"
  12. #include "base/memory/ptr_util.h"
  13. #include "base/memory/ref_counted.h"
  14. #include "base/synchronization/lock.h"
  15. #include "base/synchronization/waitable_event.h"
  16. #include "base/task/single_thread_task_runner.h"
  17. #include "base/test/bind.h"
  18. #include "base/test/gtest_util.h"
  19. #include "base/test/scoped_run_loop_timeout.h"
  20. #include "base/test/task_environment.h"
  21. #include "base/test/test_timeouts.h"
  22. #include "base/threading/platform_thread.h"
  23. #include "base/threading/sequenced_task_runner_handle.h"
  24. #include "base/threading/thread.h"
  25. #include "base/threading/thread_checker_impl.h"
  26. #include "base/threading/thread_task_runner_handle.h"
  27. #include "build/build_config.h"
  28. #include "testing/gmock/include/gmock/gmock.h"
  29. #include "testing/gtest/include/gtest/gtest.h"
  30. namespace base {
  31. namespace {
  32. void QuitWhenIdleTask(RunLoop* run_loop, int* counter) {
  33. run_loop->QuitWhenIdle();
  34. ++(*counter);
  35. }
  36. void RunNestedLoopTask(int* counter) {
  37. RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
  38. // This task should quit |nested_run_loop| but not the main RunLoop.
  39. ThreadTaskRunnerHandle::Get()->PostTask(
  40. FROM_HERE, BindOnce(&QuitWhenIdleTask, Unretained(&nested_run_loop),
  41. Unretained(counter)));
  42. ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  43. FROM_HERE, MakeExpectedNotRunClosure(FROM_HERE), Days(1));
  44. nested_run_loop.Run();
  45. ++(*counter);
  46. }
  47. // A simple SingleThreadTaskRunner that just queues undelayed tasks (and ignores
  48. // delayed tasks). Tasks can then be processed one by one by ProcessTask() which
  49. // will return true if it processed a task and false otherwise.
  50. class SimpleSingleThreadTaskRunner : public SingleThreadTaskRunner {
  51. public:
  52. SimpleSingleThreadTaskRunner() = default;
  53. SimpleSingleThreadTaskRunner(const SimpleSingleThreadTaskRunner&) = delete;
  54. SimpleSingleThreadTaskRunner& operator=(const SimpleSingleThreadTaskRunner&) =
  55. delete;
  56. bool PostDelayedTask(const Location& from_here,
  57. OnceClosure task,
  58. base::TimeDelta delay) override {
  59. if (delay.is_positive())
  60. return false;
  61. AutoLock auto_lock(tasks_lock_);
  62. pending_tasks_.push(std::move(task));
  63. return true;
  64. }
  65. bool PostNonNestableDelayedTask(const Location& from_here,
  66. OnceClosure task,
  67. base::TimeDelta delay) override {
  68. return PostDelayedTask(from_here, std::move(task), delay);
  69. }
  70. bool RunsTasksInCurrentSequence() const override {
  71. return origin_thread_checker_.CalledOnValidThread();
  72. }
  73. bool ProcessSingleTask() {
  74. OnceClosure task;
  75. {
  76. AutoLock auto_lock(tasks_lock_);
  77. if (pending_tasks_.empty())
  78. return false;
  79. task = std::move(pending_tasks_.front());
  80. pending_tasks_.pop();
  81. }
  82. // It's important to Run() after pop() and outside the lock as |task| may
  83. // run a nested loop which will re-enter ProcessSingleTask().
  84. std::move(task).Run();
  85. return true;
  86. }
  87. private:
  88. ~SimpleSingleThreadTaskRunner() override = default;
  89. Lock tasks_lock_;
  90. base::queue<OnceClosure> pending_tasks_;
  91. // RunLoop relies on RunsTasksInCurrentSequence() signal. Use a
  92. // ThreadCheckerImpl to be able to reliably provide that signal even in
  93. // non-dcheck builds.
  94. ThreadCheckerImpl origin_thread_checker_;
  95. };
  96. // The basis of all TestDelegates, allows safely injecting a OnceClosure to be
  97. // run in the next idle phase of this delegate's Run() implementation. This can
  98. // be used to have code run on a thread that is otherwise livelocked in an idle
  99. // phase (sometimes a simple PostTask() won't do it -- e.g. when processing
  100. // application tasks is disallowed).
  101. class InjectableTestDelegate : public RunLoop::Delegate {
  102. public:
  103. void InjectClosureOnDelegate(OnceClosure closure) {
  104. AutoLock auto_lock(closure_lock_);
  105. closure_ = std::move(closure);
  106. }
  107. bool RunInjectedClosure() {
  108. AutoLock auto_lock(closure_lock_);
  109. if (closure_.is_null())
  110. return false;
  111. std::move(closure_).Run();
  112. return true;
  113. }
  114. private:
  115. Lock closure_lock_;
  116. OnceClosure closure_;
  117. };
  118. // A simple test RunLoop::Delegate to exercise Runloop logic independent of any
  119. // other base constructs. BindToCurrentThread() must be called before this
  120. // TestBoundDelegate is operational.
  121. class TestBoundDelegate final : public InjectableTestDelegate {
  122. public:
  123. TestBoundDelegate() = default;
  124. // Makes this TestBoundDelegate become the RunLoop::Delegate and
  125. // ThreadTaskRunnerHandle for this thread.
  126. void BindToCurrentThread() {
  127. thread_task_runner_handle_ =
  128. std::make_unique<ThreadTaskRunnerHandle>(simple_task_runner_);
  129. RunLoop::RegisterDelegateForCurrentThread(this);
  130. }
  131. private:
  132. void Run(bool application_tasks_allowed, TimeDelta timeout) override {
  133. if (nested_run_allowing_tasks_incoming_) {
  134. EXPECT_TRUE(RunLoop::IsNestedOnCurrentThread());
  135. EXPECT_TRUE(application_tasks_allowed);
  136. } else if (RunLoop::IsNestedOnCurrentThread()) {
  137. EXPECT_FALSE(application_tasks_allowed);
  138. }
  139. nested_run_allowing_tasks_incoming_ = false;
  140. while (!should_quit_) {
  141. if (application_tasks_allowed && simple_task_runner_->ProcessSingleTask())
  142. continue;
  143. if (ShouldQuitWhenIdle())
  144. break;
  145. if (RunInjectedClosure())
  146. continue;
  147. PlatformThread::YieldCurrentThread();
  148. }
  149. should_quit_ = false;
  150. }
  151. void Quit() override { should_quit_ = true; }
  152. void EnsureWorkScheduled() override {
  153. nested_run_allowing_tasks_incoming_ = true;
  154. }
  155. // True if the next invocation of Run() is expected to be from a
  156. // kNestableTasksAllowed RunLoop.
  157. bool nested_run_allowing_tasks_incoming_ = false;
  158. scoped_refptr<SimpleSingleThreadTaskRunner> simple_task_runner_ =
  159. MakeRefCounted<SimpleSingleThreadTaskRunner>();
  160. std::unique_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
  161. bool should_quit_ = false;
  162. };
  163. enum class RunLoopTestType {
  164. // Runs all RunLoopTests under a TaskEnvironment to make sure real world
  165. // scenarios work.
  166. kRealEnvironment,
  167. // Runs all RunLoopTests under a test RunLoop::Delegate to make sure the
  168. // delegate interface fully works standalone.
  169. kTestDelegate,
  170. };
  171. // The task environment for the RunLoopTest of a given type. A separate class
  172. // so it can be instantiated on the stack in the RunLoopTest fixture.
  173. class RunLoopTestEnvironment {
  174. public:
  175. explicit RunLoopTestEnvironment(RunLoopTestType type) {
  176. switch (type) {
  177. case RunLoopTestType::kRealEnvironment: {
  178. task_environment_ = std::make_unique<test::TaskEnvironment>();
  179. break;
  180. }
  181. case RunLoopTestType::kTestDelegate: {
  182. auto test_delegate = std::make_unique<TestBoundDelegate>();
  183. test_delegate->BindToCurrentThread();
  184. test_delegate_ = std::move(test_delegate);
  185. break;
  186. }
  187. }
  188. }
  189. private:
  190. // Instantiates one or the other based on the RunLoopTestType.
  191. std::unique_ptr<test::TaskEnvironment> task_environment_;
  192. std::unique_ptr<InjectableTestDelegate> test_delegate_;
  193. };
  194. class RunLoopTest : public testing::TestWithParam<RunLoopTestType> {
  195. public:
  196. RunLoopTest(const RunLoopTest&) = delete;
  197. RunLoopTest& operator=(const RunLoopTest&) = delete;
  198. protected:
  199. RunLoopTest() : test_environment_(GetParam()) {}
  200. RunLoopTestEnvironment test_environment_;
  201. RunLoop run_loop_;
  202. };
  203. } // namespace
  204. TEST_P(RunLoopTest, QuitWhenIdle) {
  205. int counter = 0;
  206. ThreadTaskRunnerHandle::Get()->PostTask(
  207. FROM_HERE, BindOnce(&QuitWhenIdleTask, Unretained(&run_loop_),
  208. Unretained(&counter)));
  209. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  210. MakeExpectedRunClosure(FROM_HERE));
  211. ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  212. FROM_HERE, MakeExpectedNotRunClosure(FROM_HERE), Days(1));
  213. run_loop_.Run();
  214. EXPECT_EQ(1, counter);
  215. }
  216. TEST_P(RunLoopTest, QuitWhenIdleNestedLoop) {
  217. int counter = 0;
  218. ThreadTaskRunnerHandle::Get()->PostTask(
  219. FROM_HERE, BindOnce(&RunNestedLoopTask, Unretained(&counter)));
  220. ThreadTaskRunnerHandle::Get()->PostTask(
  221. FROM_HERE, BindOnce(&QuitWhenIdleTask, Unretained(&run_loop_),
  222. Unretained(&counter)));
  223. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  224. MakeExpectedRunClosure(FROM_HERE));
  225. ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  226. FROM_HERE, MakeExpectedNotRunClosure(FROM_HERE), Days(1));
  227. run_loop_.Run();
  228. EXPECT_EQ(3, counter);
  229. }
  230. TEST_P(RunLoopTest, QuitWhenIdleClosure) {
  231. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  232. run_loop_.QuitWhenIdleClosure());
  233. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  234. MakeExpectedRunClosure(FROM_HERE));
  235. ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  236. FROM_HERE, MakeExpectedNotRunClosure(FROM_HERE), Days(1));
  237. run_loop_.Run();
  238. }
  239. // Verify that the QuitWhenIdleClosure() can run after the RunLoop has been
  240. // deleted. It should have no effect.
  241. TEST_P(RunLoopTest, QuitWhenIdleClosureAfterRunLoopScope) {
  242. RepeatingClosure quit_when_idle_closure;
  243. {
  244. RunLoop run_loop;
  245. quit_when_idle_closure = run_loop.QuitWhenIdleClosure();
  246. run_loop.RunUntilIdle();
  247. }
  248. quit_when_idle_closure.Run();
  249. }
  250. // Verify that Quit can be executed from another sequence.
  251. TEST_P(RunLoopTest, QuitFromOtherSequence) {
  252. Thread other_thread("test");
  253. other_thread.Start();
  254. scoped_refptr<SequencedTaskRunner> other_sequence =
  255. other_thread.task_runner();
  256. // Always expected to run before asynchronous Quit() kicks in.
  257. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  258. MakeExpectedRunClosure(FROM_HERE));
  259. WaitableEvent loop_was_quit(WaitableEvent::ResetPolicy::MANUAL,
  260. WaitableEvent::InitialState::NOT_SIGNALED);
  261. other_sequence->PostTask(
  262. FROM_HERE, base::BindOnce([](RunLoop* run_loop) { run_loop->Quit(); },
  263. Unretained(&run_loop_)));
  264. other_sequence->PostTask(
  265. FROM_HERE,
  266. base::BindOnce(&WaitableEvent::Signal, base::Unretained(&loop_was_quit)));
  267. // Anything that's posted after the Quit closure was posted back to this
  268. // sequence shouldn't get a chance to run.
  269. loop_was_quit.Wait();
  270. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  271. MakeExpectedNotRunClosure(FROM_HERE));
  272. run_loop_.Run();
  273. }
  274. // Verify that QuitClosure can be executed from another sequence.
  275. TEST_P(RunLoopTest, QuitFromOtherSequenceWithClosure) {
  276. Thread other_thread("test");
  277. other_thread.Start();
  278. scoped_refptr<SequencedTaskRunner> other_sequence =
  279. other_thread.task_runner();
  280. // Always expected to run before asynchronous Quit() kicks in.
  281. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  282. MakeExpectedRunClosure(FROM_HERE));
  283. WaitableEvent loop_was_quit(WaitableEvent::ResetPolicy::MANUAL,
  284. WaitableEvent::InitialState::NOT_SIGNALED);
  285. other_sequence->PostTask(FROM_HERE, run_loop_.QuitClosure());
  286. other_sequence->PostTask(
  287. FROM_HERE,
  288. base::BindOnce(&WaitableEvent::Signal, base::Unretained(&loop_was_quit)));
  289. // Anything that's posted after the Quit closure was posted back to this
  290. // sequence shouldn't get a chance to run.
  291. loop_was_quit.Wait();
  292. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  293. MakeExpectedNotRunClosure(FROM_HERE));
  294. run_loop_.Run();
  295. }
  296. // Verify that Quit can be executed from another sequence even when the
  297. // Quit is racing with Run() -- i.e. forgo the WaitableEvent used above.
  298. TEST_P(RunLoopTest, QuitFromOtherSequenceRacy) {
  299. Thread other_thread("test");
  300. other_thread.Start();
  301. scoped_refptr<SequencedTaskRunner> other_sequence =
  302. other_thread.task_runner();
  303. // Always expected to run before asynchronous Quit() kicks in.
  304. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  305. MakeExpectedRunClosure(FROM_HERE));
  306. other_sequence->PostTask(FROM_HERE, run_loop_.QuitClosure());
  307. run_loop_.Run();
  308. }
  309. // Verify that QuitClosure can be executed from another sequence even when the
  310. // Quit is racing with Run() -- i.e. forgo the WaitableEvent used above.
  311. TEST_P(RunLoopTest, QuitFromOtherSequenceRacyWithClosure) {
  312. Thread other_thread("test");
  313. other_thread.Start();
  314. scoped_refptr<SequencedTaskRunner> other_sequence =
  315. other_thread.task_runner();
  316. // Always expected to run before asynchronous Quit() kicks in.
  317. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  318. MakeExpectedRunClosure(FROM_HERE));
  319. other_sequence->PostTask(FROM_HERE, run_loop_.QuitClosure());
  320. run_loop_.Run();
  321. }
  322. // Verify that QuitWhenIdle can be executed from another sequence.
  323. TEST_P(RunLoopTest, QuitWhenIdleFromOtherSequence) {
  324. Thread other_thread("test");
  325. other_thread.Start();
  326. scoped_refptr<SequencedTaskRunner> other_sequence =
  327. other_thread.task_runner();
  328. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  329. MakeExpectedRunClosure(FROM_HERE));
  330. other_sequence->PostTask(
  331. FROM_HERE,
  332. base::BindOnce([](RunLoop* run_loop) { run_loop->QuitWhenIdle(); },
  333. Unretained(&run_loop_)));
  334. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  335. MakeExpectedRunClosure(FROM_HERE));
  336. run_loop_.Run();
  337. // Regardless of the outcome of the race this thread shouldn't have been idle
  338. // until both tasks posted to this sequence have run.
  339. }
  340. // Verify that QuitWhenIdleClosure can be executed from another sequence.
  341. TEST_P(RunLoopTest, QuitWhenIdleFromOtherSequenceWithClosure) {
  342. Thread other_thread("test");
  343. other_thread.Start();
  344. scoped_refptr<SequencedTaskRunner> other_sequence =
  345. other_thread.task_runner();
  346. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  347. MakeExpectedRunClosure(FROM_HERE));
  348. other_sequence->PostTask(FROM_HERE, run_loop_.QuitWhenIdleClosure());
  349. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  350. MakeExpectedRunClosure(FROM_HERE));
  351. run_loop_.Run();
  352. // Regardless of the outcome of the race this thread shouldn't have been idle
  353. // until the both tasks posted to this sequence have run.
  354. }
  355. TEST_P(RunLoopTest, IsRunningOnCurrentThread) {
  356. EXPECT_FALSE(RunLoop::IsRunningOnCurrentThread());
  357. ThreadTaskRunnerHandle::Get()->PostTask(
  358. FROM_HERE,
  359. BindOnce([]() { EXPECT_TRUE(RunLoop::IsRunningOnCurrentThread()); }));
  360. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
  361. run_loop_.Run();
  362. }
  363. TEST_P(RunLoopTest, IsNestedOnCurrentThread) {
  364. EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
  365. ThreadTaskRunnerHandle::Get()->PostTask(
  366. FROM_HERE, BindOnce([]() {
  367. EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
  368. RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
  369. ThreadTaskRunnerHandle::Get()->PostTask(
  370. FROM_HERE, BindOnce([]() {
  371. EXPECT_TRUE(RunLoop::IsNestedOnCurrentThread());
  372. }));
  373. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  374. nested_run_loop.QuitClosure());
  375. EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
  376. nested_run_loop.Run();
  377. EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
  378. }));
  379. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
  380. run_loop_.Run();
  381. }
  382. TEST_P(RunLoopTest, CannotRunMoreThanOnce) {
  383. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
  384. run_loop_.Run();
  385. EXPECT_DCHECK_DEATH({ run_loop_.Run(); });
  386. }
  387. TEST_P(RunLoopTest, CanRunUntilIdleMoreThanOnce) {
  388. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
  389. run_loop_.RunUntilIdle();
  390. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
  391. run_loop_.RunUntilIdle();
  392. run_loop_.RunUntilIdle();
  393. }
  394. TEST_P(RunLoopTest, CanRunUntilIdleThenRunIfNotQuit) {
  395. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
  396. run_loop_.RunUntilIdle();
  397. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
  398. run_loop_.Run();
  399. }
  400. TEST_P(RunLoopTest, CannotRunUntilIdleThenRunIfQuit) {
  401. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop_.QuitClosure());
  402. run_loop_.RunUntilIdle();
  403. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, DoNothing());
  404. EXPECT_DCHECK_DEATH({ run_loop_.Run(); });
  405. }
  406. TEST_P(RunLoopTest, CannotRunAgainIfQuitWhenIdle) {
  407. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  408. run_loop_.QuitWhenIdleClosure());
  409. run_loop_.RunUntilIdle();
  410. EXPECT_DCHECK_DEATH({ run_loop_.RunUntilIdle(); });
  411. }
  412. namespace {
  413. class MockNestingObserver : public RunLoop::NestingObserver {
  414. public:
  415. MockNestingObserver() = default;
  416. MockNestingObserver(const MockNestingObserver&) = delete;
  417. MockNestingObserver& operator=(const MockNestingObserver&) = delete;
  418. // RunLoop::NestingObserver:
  419. MOCK_METHOD0(OnBeginNestedRunLoop, void());
  420. MOCK_METHOD0(OnExitNestedRunLoop, void());
  421. };
  422. class MockTask {
  423. public:
  424. MockTask() = default;
  425. MockTask(const MockTask&) = delete;
  426. MockTask& operator=(const MockTask&) = delete;
  427. MOCK_METHOD0(Task, void());
  428. };
  429. } // namespace
  430. TEST_P(RunLoopTest, NestingObservers) {
  431. testing::StrictMock<MockNestingObserver> nesting_observer;
  432. testing::StrictMock<MockTask> mock_task_a;
  433. testing::StrictMock<MockTask> mock_task_b;
  434. RunLoop::AddNestingObserverOnCurrentThread(&nesting_observer);
  435. const RepeatingClosure run_nested_loop = BindRepeating([]() {
  436. RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed);
  437. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  438. nested_run_loop.QuitClosure());
  439. nested_run_loop.Run();
  440. });
  441. // Generate a stack of nested RunLoops. OnBeginNestedRunLoop() is expected
  442. // when beginning each nesting depth and OnExitNestedRunLoop() is expected
  443. // when exiting each nesting depth. Each one of these tasks is ahead of the
  444. // QuitClosures as those are only posted at the end of the queue when
  445. // |run_nested_loop| is executed.
  446. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_nested_loop);
  447. ThreadTaskRunnerHandle::Get()->PostTask(
  448. FROM_HERE,
  449. base::BindOnce(&MockTask::Task, base::Unretained(&mock_task_a)));
  450. ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_nested_loop);
  451. ThreadTaskRunnerHandle::Get()->PostTask(
  452. FROM_HERE,
  453. base::BindOnce(&MockTask::Task, base::Unretained(&mock_task_b)));
  454. {
  455. testing::InSequence in_sequence;
  456. EXPECT_CALL(nesting_observer, OnBeginNestedRunLoop());
  457. EXPECT_CALL(mock_task_a, Task());
  458. EXPECT_CALL(nesting_observer, OnBeginNestedRunLoop());
  459. EXPECT_CALL(mock_task_b, Task());
  460. EXPECT_CALL(nesting_observer, OnExitNestedRunLoop()).Times(2);
  461. }
  462. run_loop_.RunUntilIdle();
  463. RunLoop::RemoveNestingObserverOnCurrentThread(&nesting_observer);
  464. }
  465. TEST_P(RunLoopTest, DisallowRunning) {
  466. ScopedDisallowRunningRunLoop disallow_running;
  467. EXPECT_DCHECK_DEATH({ run_loop_.RunUntilIdle(); });
  468. }
  469. TEST_P(RunLoopTest, ExpiredDisallowRunning) {
  470. { ScopedDisallowRunningRunLoop disallow_running; }
  471. // Running should be fine after |disallow_running| goes out of scope.
  472. run_loop_.RunUntilIdle();
  473. }
  474. INSTANTIATE_TEST_SUITE_P(Real,
  475. RunLoopTest,
  476. testing::Values(RunLoopTestType::kRealEnvironment));
  477. INSTANTIATE_TEST_SUITE_P(Mock,
  478. RunLoopTest,
  479. testing::Values(RunLoopTestType::kTestDelegate));
  480. TEST(RunLoopDeathTest, MustRegisterBeforeInstantiating) {
  481. TestBoundDelegate unbound_test_delegate_;
  482. // RunLoop::RunLoop() should CHECK fetching the ThreadTaskRunnerHandle.
  483. EXPECT_DEATH_IF_SUPPORTED({ RunLoop(); }, "");
  484. }
  485. TEST(RunLoopDelegateTest, NestableTasksDontRunInDefaultNestedLoops) {
  486. TestBoundDelegate test_delegate;
  487. test_delegate.BindToCurrentThread();
  488. base::Thread other_thread("test");
  489. other_thread.Start();
  490. RunLoop main_loop;
  491. // A nested run loop which isn't kNestableTasksAllowed.
  492. RunLoop nested_run_loop(RunLoop::Type::kDefault);
  493. bool nested_run_loop_ended = false;
  494. // The first task on the main loop will result in a nested run loop. Since
  495. // it's not kNestableTasksAllowed, no further task should be processed until
  496. // it's quit.
  497. ThreadTaskRunnerHandle::Get()->PostTask(
  498. FROM_HERE,
  499. BindOnce([](RunLoop* nested_run_loop) { nested_run_loop->Run(); },
  500. Unretained(&nested_run_loop)));
  501. // Post a task that will fail if it runs inside the nested run loop.
  502. ThreadTaskRunnerHandle::Get()->PostTask(
  503. FROM_HERE,
  504. BindOnce(
  505. [](const bool& nested_run_loop_ended,
  506. OnceClosure continuation_callback) {
  507. EXPECT_TRUE(nested_run_loop_ended);
  508. EXPECT_FALSE(RunLoop::IsNestedOnCurrentThread());
  509. std::move(continuation_callback).Run();
  510. },
  511. std::cref(nested_run_loop_ended), main_loop.QuitClosure()));
  512. // Post a task flipping the boolean bit for extra verification right before
  513. // quitting |nested_run_loop|.
  514. other_thread.task_runner()->PostDelayedTask(
  515. FROM_HERE,
  516. BindOnce(
  517. [](bool* nested_run_loop_ended) {
  518. EXPECT_FALSE(*nested_run_loop_ended);
  519. *nested_run_loop_ended = true;
  520. },
  521. Unretained(&nested_run_loop_ended)),
  522. TestTimeouts::tiny_timeout());
  523. // Post an async delayed task to exit the run loop when idle. This confirms
  524. // that (1) the test task only ran in the main loop after the nested loop
  525. // exited and (2) the nested run loop actually considers itself idle while
  526. // spinning. Note: The quit closure needs to be injected directly on the
  527. // delegate as invoking QuitWhenIdle() off-thread results in a thread bounce
  528. // which will not processed because of the very logic under test (nestable
  529. // tasks don't run in |nested_run_loop|).
  530. other_thread.task_runner()->PostDelayedTask(
  531. FROM_HERE,
  532. BindOnce(
  533. [](TestBoundDelegate* test_delegate, OnceClosure injected_closure) {
  534. test_delegate->InjectClosureOnDelegate(std::move(injected_closure));
  535. },
  536. Unretained(&test_delegate), nested_run_loop.QuitWhenIdleClosure()),
  537. TestTimeouts::tiny_timeout());
  538. main_loop.Run();
  539. }
  540. } // namespace base