Log the freshness of the Variations seed in a histogram.
[chromium-blink-merge.git] / base / message_loop_unittest.cc
blob984a025754c2b28d381e19fecfd37fa465e2803a
1 // Copyright (c) 2012 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.
5 #include <vector>
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/compiler_specific.h"
10 #include "base/logging.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/message_loop.h"
13 #include "base/pending_task.h"
14 #include "base/posix/eintr_wrapper.h"
15 #include "base/run_loop.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/threading/platform_thread.h"
18 #include "base/threading/thread.h"
19 #include "testing/gtest/include/gtest/gtest.h"
21 #if defined(OS_WIN)
22 #include "base/message_pump_win.h"
23 #include "base/win/scoped_handle.h"
24 #endif
26 using base::PlatformThread;
27 using base::Thread;
28 using base::Time;
29 using base::TimeDelta;
30 using base::TimeTicks;
32 // TODO(darin): Platform-specific MessageLoop tests should be grouped together
33 // to avoid chopping this file up with so many #ifdefs.
35 namespace {
37 class Foo : public base::RefCounted<Foo> {
38 public:
39 Foo() : test_count_(0) {
42 void Test0() {
43 ++test_count_;
46 void Test1ConstRef(const std::string& a) {
47 ++test_count_;
48 result_.append(a);
51 void Test1Ptr(std::string* a) {
52 ++test_count_;
53 result_.append(*a);
56 void Test1Int(int a) {
57 test_count_ += a;
60 void Test2Ptr(std::string* a, std::string* b) {
61 ++test_count_;
62 result_.append(*a);
63 result_.append(*b);
66 void Test2Mixed(const std::string& a, std::string* b) {
67 ++test_count_;
68 result_.append(a);
69 result_.append(*b);
72 int test_count() const { return test_count_; }
73 const std::string& result() const { return result_; }
75 private:
76 friend class base::RefCounted<Foo>;
78 ~Foo() {}
80 int test_count_;
81 std::string result_;
84 void RunTest_PostTask(MessageLoop::Type message_loop_type) {
85 MessageLoop loop(message_loop_type);
87 // Add tests to message loop
88 scoped_refptr<Foo> foo(new Foo());
89 std::string a("a"), b("b"), c("c"), d("d");
90 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
91 &Foo::Test0, foo.get()));
92 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
93 &Foo::Test1ConstRef, foo.get(), a));
94 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
95 &Foo::Test1Ptr, foo.get(), &b));
96 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
97 &Foo::Test1Int, foo.get(), 100));
98 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
99 &Foo::Test2Ptr, foo.get(), &a, &c));
100 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
101 &Foo::Test2Mixed, foo.get(), a, &d));
103 // After all tests, post a message that will shut down the message loop
104 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
105 &MessageLoop::Quit, base::Unretained(MessageLoop::current())));
107 // Now kick things off
108 MessageLoop::current()->Run();
110 EXPECT_EQ(foo->test_count(), 105);
111 EXPECT_EQ(foo->result(), "abacad");
114 void RunTest_PostTask_SEH(MessageLoop::Type message_loop_type) {
115 MessageLoop loop(message_loop_type);
117 // Add tests to message loop
118 scoped_refptr<Foo> foo(new Foo());
119 std::string a("a"), b("b"), c("c"), d("d");
120 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
121 &Foo::Test0, foo.get()));
122 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
123 &Foo::Test1ConstRef, foo.get(), a));
124 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
125 &Foo::Test1Ptr, foo.get(), &b));
126 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
127 &Foo::Test1Int, foo.get(), 100));
128 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
129 &Foo::Test2Ptr, foo.get(), &a, &c));
130 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
131 &Foo::Test2Mixed, foo.get(), a, &d));
133 // After all tests, post a message that will shut down the message loop
134 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
135 &MessageLoop::Quit, base::Unretained(MessageLoop::current())));
137 // Now kick things off with the SEH block active.
138 MessageLoop::current()->set_exception_restoration(true);
139 MessageLoop::current()->Run();
140 MessageLoop::current()->set_exception_restoration(false);
142 EXPECT_EQ(foo->test_count(), 105);
143 EXPECT_EQ(foo->result(), "abacad");
146 // This function runs slowly to simulate a large amount of work being done.
147 static void SlowFunc(TimeDelta pause, int* quit_counter) {
148 PlatformThread::Sleep(pause);
149 if (--(*quit_counter) == 0)
150 MessageLoop::current()->QuitWhenIdle();
153 // This function records the time when Run was called in a Time object, which is
154 // useful for building a variety of MessageLoop tests.
155 static void RecordRunTimeFunc(Time* run_time, int* quit_counter) {
156 *run_time = Time::Now();
158 // Cause our Run function to take some time to execute. As a result we can
159 // count on subsequent RecordRunTimeFunc()s running at a future time,
160 // without worry about the resolution of our system clock being an issue.
161 SlowFunc(TimeDelta::FromMilliseconds(10), quit_counter);
164 void RunTest_PostDelayedTask_Basic(MessageLoop::Type message_loop_type) {
165 MessageLoop loop(message_loop_type);
167 // Test that PostDelayedTask results in a delayed task.
169 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
171 int num_tasks = 1;
172 Time run_time;
174 loop.PostDelayedTask(
175 FROM_HERE, base::Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
176 kDelay);
178 Time time_before_run = Time::Now();
179 loop.Run();
180 Time time_after_run = Time::Now();
182 EXPECT_EQ(0, num_tasks);
183 EXPECT_LT(kDelay, time_after_run - time_before_run);
186 void RunTest_PostDelayedTask_InDelayOrder(
187 MessageLoop::Type message_loop_type) {
188 MessageLoop loop(message_loop_type);
190 // Test that two tasks with different delays run in the right order.
191 int num_tasks = 2;
192 Time run_time1, run_time2;
194 loop.PostDelayedTask(
195 FROM_HERE,
196 base::Bind(&RecordRunTimeFunc, &run_time1, &num_tasks),
197 TimeDelta::FromMilliseconds(200));
198 // If we get a large pause in execution (due to a context switch) here, this
199 // test could fail.
200 loop.PostDelayedTask(
201 FROM_HERE,
202 base::Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
203 TimeDelta::FromMilliseconds(10));
205 loop.Run();
206 EXPECT_EQ(0, num_tasks);
208 EXPECT_TRUE(run_time2 < run_time1);
211 void RunTest_PostDelayedTask_InPostOrder(
212 MessageLoop::Type message_loop_type) {
213 MessageLoop loop(message_loop_type);
215 // Test that two tasks with the same delay run in the order in which they
216 // were posted.
218 // NOTE: This is actually an approximate test since the API only takes a
219 // "delay" parameter, so we are not exactly simulating two tasks that get
220 // posted at the exact same time. It would be nice if the API allowed us to
221 // specify the desired run time.
223 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
225 int num_tasks = 2;
226 Time run_time1, run_time2;
228 loop.PostDelayedTask(
229 FROM_HERE,
230 base::Bind(&RecordRunTimeFunc, &run_time1, &num_tasks), kDelay);
231 loop.PostDelayedTask(
232 FROM_HERE,
233 base::Bind(&RecordRunTimeFunc, &run_time2, &num_tasks), kDelay);
235 loop.Run();
236 EXPECT_EQ(0, num_tasks);
238 EXPECT_TRUE(run_time1 < run_time2);
241 void RunTest_PostDelayedTask_InPostOrder_2(
242 MessageLoop::Type message_loop_type) {
243 MessageLoop loop(message_loop_type);
245 // Test that a delayed task still runs after a normal tasks even if the
246 // normal tasks take a long time to run.
248 const TimeDelta kPause = TimeDelta::FromMilliseconds(50);
250 int num_tasks = 2;
251 Time run_time;
253 loop.PostTask(FROM_HERE, base::Bind(&SlowFunc, kPause, &num_tasks));
254 loop.PostDelayedTask(
255 FROM_HERE,
256 base::Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
257 TimeDelta::FromMilliseconds(10));
259 Time time_before_run = Time::Now();
260 loop.Run();
261 Time time_after_run = Time::Now();
263 EXPECT_EQ(0, num_tasks);
265 EXPECT_LT(kPause, time_after_run - time_before_run);
268 void RunTest_PostDelayedTask_InPostOrder_3(
269 MessageLoop::Type message_loop_type) {
270 MessageLoop loop(message_loop_type);
272 // Test that a delayed task still runs after a pile of normal tasks. The key
273 // difference between this test and the previous one is that here we return
274 // the MessageLoop a lot so we give the MessageLoop plenty of opportunities
275 // to maybe run the delayed task. It should know not to do so until the
276 // delayed task's delay has passed.
278 int num_tasks = 11;
279 Time run_time1, run_time2;
281 // Clutter the ML with tasks.
282 for (int i = 1; i < num_tasks; ++i)
283 loop.PostTask(FROM_HERE,
284 base::Bind(&RecordRunTimeFunc, &run_time1, &num_tasks));
286 loop.PostDelayedTask(
287 FROM_HERE, base::Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
288 TimeDelta::FromMilliseconds(1));
290 loop.Run();
291 EXPECT_EQ(0, num_tasks);
293 EXPECT_TRUE(run_time2 > run_time1);
296 void RunTest_PostDelayedTask_SharedTimer(
297 MessageLoop::Type message_loop_type) {
298 MessageLoop loop(message_loop_type);
300 // Test that the interval of the timer, used to run the next delayed task, is
301 // set to a value corresponding to when the next delayed task should run.
303 // By setting num_tasks to 1, we ensure that the first task to run causes the
304 // run loop to exit.
305 int num_tasks = 1;
306 Time run_time1, run_time2;
308 loop.PostDelayedTask(
309 FROM_HERE,
310 base::Bind(&RecordRunTimeFunc, &run_time1, &num_tasks),
311 TimeDelta::FromSeconds(1000));
312 loop.PostDelayedTask(
313 FROM_HERE,
314 base::Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
315 TimeDelta::FromMilliseconds(10));
317 Time start_time = Time::Now();
319 loop.Run();
320 EXPECT_EQ(0, num_tasks);
322 // Ensure that we ran in far less time than the slower timer.
323 TimeDelta total_time = Time::Now() - start_time;
324 EXPECT_GT(5000, total_time.InMilliseconds());
326 // In case both timers somehow run at nearly the same time, sleep a little
327 // and then run all pending to force them both to have run. This is just
328 // encouraging flakiness if there is any.
329 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
330 base::RunLoop().RunUntilIdle();
332 EXPECT_TRUE(run_time1.is_null());
333 EXPECT_FALSE(run_time2.is_null());
336 #if defined(OS_WIN)
338 void SubPumpFunc() {
339 MessageLoop::current()->SetNestableTasksAllowed(true);
340 MSG msg;
341 while (GetMessage(&msg, NULL, 0, 0)) {
342 TranslateMessage(&msg);
343 DispatchMessage(&msg);
345 MessageLoop::current()->QuitWhenIdle();
348 void RunTest_PostDelayedTask_SharedTimer_SubPump() {
349 MessageLoop loop(MessageLoop::TYPE_UI);
351 // Test that the interval of the timer, used to run the next delayed task, is
352 // set to a value corresponding to when the next delayed task should run.
354 // By setting num_tasks to 1, we ensure that the first task to run causes the
355 // run loop to exit.
356 int num_tasks = 1;
357 Time run_time;
359 loop.PostTask(FROM_HERE, base::Bind(&SubPumpFunc));
361 // This very delayed task should never run.
362 loop.PostDelayedTask(
363 FROM_HERE,
364 base::Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
365 TimeDelta::FromSeconds(1000));
367 // This slightly delayed task should run from within SubPumpFunc).
368 loop.PostDelayedTask(
369 FROM_HERE,
370 base::Bind(&PostQuitMessage, 0),
371 TimeDelta::FromMilliseconds(10));
373 Time start_time = Time::Now();
375 loop.Run();
376 EXPECT_EQ(1, num_tasks);
378 // Ensure that we ran in far less time than the slower timer.
379 TimeDelta total_time = Time::Now() - start_time;
380 EXPECT_GT(5000, total_time.InMilliseconds());
382 // In case both timers somehow run at nearly the same time, sleep a little
383 // and then run all pending to force them both to have run. This is just
384 // encouraging flakiness if there is any.
385 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
386 base::RunLoop().RunUntilIdle();
388 EXPECT_TRUE(run_time.is_null());
391 #endif // defined(OS_WIN)
393 // This is used to inject a test point for recording the destructor calls for
394 // Closure objects send to MessageLoop::PostTask(). It is awkward usage since we
395 // are trying to hook the actual destruction, which is not a common operation.
396 class RecordDeletionProbe : public base::RefCounted<RecordDeletionProbe> {
397 public:
398 RecordDeletionProbe(RecordDeletionProbe* post_on_delete, bool* was_deleted)
399 : post_on_delete_(post_on_delete), was_deleted_(was_deleted) {
401 void Run() {}
403 private:
404 friend class base::RefCounted<RecordDeletionProbe>;
406 ~RecordDeletionProbe() {
407 *was_deleted_ = true;
408 if (post_on_delete_)
409 MessageLoop::current()->PostTask(
410 FROM_HERE,
411 base::Bind(&RecordDeletionProbe::Run, post_on_delete_.get()));
414 scoped_refptr<RecordDeletionProbe> post_on_delete_;
415 bool* was_deleted_;
418 void RunTest_EnsureDeletion(MessageLoop::Type message_loop_type) {
419 bool a_was_deleted = false;
420 bool b_was_deleted = false;
422 MessageLoop loop(message_loop_type);
423 loop.PostTask(
424 FROM_HERE, base::Bind(&RecordDeletionProbe::Run,
425 new RecordDeletionProbe(NULL, &a_was_deleted)));
426 // TODO(ajwong): Do we really need 1000ms here?
427 loop.PostDelayedTask(
428 FROM_HERE, base::Bind(&RecordDeletionProbe::Run,
429 new RecordDeletionProbe(NULL, &b_was_deleted)),
430 TimeDelta::FromMilliseconds(1000));
432 EXPECT_TRUE(a_was_deleted);
433 EXPECT_TRUE(b_was_deleted);
436 void RunTest_EnsureDeletion_Chain(MessageLoop::Type message_loop_type) {
437 bool a_was_deleted = false;
438 bool b_was_deleted = false;
439 bool c_was_deleted = false;
441 MessageLoop loop(message_loop_type);
442 // The scoped_refptr for each of the below is held either by the chained
443 // RecordDeletionProbe, or the bound RecordDeletionProbe::Run() callback.
444 RecordDeletionProbe* a = new RecordDeletionProbe(NULL, &a_was_deleted);
445 RecordDeletionProbe* b = new RecordDeletionProbe(a, &b_was_deleted);
446 RecordDeletionProbe* c = new RecordDeletionProbe(b, &c_was_deleted);
447 loop.PostTask(FROM_HERE, base::Bind(&RecordDeletionProbe::Run, c));
449 EXPECT_TRUE(a_was_deleted);
450 EXPECT_TRUE(b_was_deleted);
451 EXPECT_TRUE(c_was_deleted);
454 void NestingFunc(int* depth) {
455 if (*depth > 0) {
456 *depth -= 1;
457 MessageLoop::current()->PostTask(FROM_HERE,
458 base::Bind(&NestingFunc, depth));
460 MessageLoop::current()->SetNestableTasksAllowed(true);
461 MessageLoop::current()->Run();
463 MessageLoop::current()->QuitWhenIdle();
466 #if defined(OS_WIN)
468 LONG WINAPI BadExceptionHandler(EXCEPTION_POINTERS *ex_info) {
469 ADD_FAILURE() << "bad exception handler";
470 ::ExitProcess(ex_info->ExceptionRecord->ExceptionCode);
471 return EXCEPTION_EXECUTE_HANDLER;
474 // This task throws an SEH exception: initially write to an invalid address.
475 // If the right SEH filter is installed, it will fix the error.
476 class Crasher : public base::RefCounted<Crasher> {
477 public:
478 // Ctor. If trash_SEH_handler is true, the task will override the unhandled
479 // exception handler with one sure to crash this test.
480 explicit Crasher(bool trash_SEH_handler)
481 : trash_SEH_handler_(trash_SEH_handler) {
484 void Run() {
485 PlatformThread::Sleep(TimeDelta::FromMilliseconds(1));
486 if (trash_SEH_handler_)
487 ::SetUnhandledExceptionFilter(&BadExceptionHandler);
488 // Generate a SEH fault. We do it in asm to make sure we know how to undo
489 // the damage.
491 #if defined(_M_IX86)
493 __asm {
494 mov eax, dword ptr [Crasher::bad_array_]
495 mov byte ptr [eax], 66
498 #elif defined(_M_X64)
500 bad_array_[0] = 66;
502 #else
503 #error "needs architecture support"
504 #endif
506 MessageLoop::current()->QuitWhenIdle();
508 // Points the bad array to a valid memory location.
509 static void FixError() {
510 bad_array_ = &valid_store_;
513 private:
514 bool trash_SEH_handler_;
515 static volatile char* bad_array_;
516 static char valid_store_;
519 volatile char* Crasher::bad_array_ = 0;
520 char Crasher::valid_store_ = 0;
522 // This SEH filter fixes the problem and retries execution. Fixing requires
523 // that the last instruction: mov eax, [Crasher::bad_array_] to be retried
524 // so we move the instruction pointer 5 bytes back.
525 LONG WINAPI HandleCrasherException(EXCEPTION_POINTERS *ex_info) {
526 if (ex_info->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION)
527 return EXCEPTION_EXECUTE_HANDLER;
529 Crasher::FixError();
531 #if defined(_M_IX86)
533 ex_info->ContextRecord->Eip -= 5;
535 #elif defined(_M_X64)
537 ex_info->ContextRecord->Rip -= 5;
539 #endif
541 return EXCEPTION_CONTINUE_EXECUTION;
544 void RunTest_Crasher(MessageLoop::Type message_loop_type) {
545 MessageLoop loop(message_loop_type);
547 if (::IsDebuggerPresent())
548 return;
550 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter =
551 ::SetUnhandledExceptionFilter(&HandleCrasherException);
553 MessageLoop::current()->PostTask(
554 FROM_HERE,
555 base::Bind(&Crasher::Run, new Crasher(false)));
556 MessageLoop::current()->set_exception_restoration(true);
557 MessageLoop::current()->Run();
558 MessageLoop::current()->set_exception_restoration(false);
560 ::SetUnhandledExceptionFilter(old_SEH_filter);
563 void RunTest_CrasherNasty(MessageLoop::Type message_loop_type) {
564 MessageLoop loop(message_loop_type);
566 if (::IsDebuggerPresent())
567 return;
569 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter =
570 ::SetUnhandledExceptionFilter(&HandleCrasherException);
572 MessageLoop::current()->PostTask(
573 FROM_HERE,
574 base::Bind(&Crasher::Run, new Crasher(true)));
575 MessageLoop::current()->set_exception_restoration(true);
576 MessageLoop::current()->Run();
577 MessageLoop::current()->set_exception_restoration(false);
579 ::SetUnhandledExceptionFilter(old_SEH_filter);
582 #endif // defined(OS_WIN)
584 void RunTest_Nesting(MessageLoop::Type message_loop_type) {
585 MessageLoop loop(message_loop_type);
587 int depth = 100;
588 MessageLoop::current()->PostTask(FROM_HERE,
589 base::Bind(&NestingFunc, &depth));
590 MessageLoop::current()->Run();
591 EXPECT_EQ(depth, 0);
594 const wchar_t* const kMessageBoxTitle = L"MessageLoop Unit Test";
596 enum TaskType {
597 MESSAGEBOX,
598 ENDDIALOG,
599 RECURSIVE,
600 TIMEDMESSAGELOOP,
601 QUITMESSAGELOOP,
602 ORDERED,
603 PUMPS,
604 SLEEP,
605 RUNS,
608 // Saves the order in which the tasks executed.
609 struct TaskItem {
610 TaskItem(TaskType t, int c, bool s)
611 : type(t),
612 cookie(c),
613 start(s) {
616 TaskType type;
617 int cookie;
618 bool start;
620 bool operator == (const TaskItem& other) const {
621 return type == other.type && cookie == other.cookie && start == other.start;
625 std::ostream& operator <<(std::ostream& os, TaskType type) {
626 switch (type) {
627 case MESSAGEBOX: os << "MESSAGEBOX"; break;
628 case ENDDIALOG: os << "ENDDIALOG"; break;
629 case RECURSIVE: os << "RECURSIVE"; break;
630 case TIMEDMESSAGELOOP: os << "TIMEDMESSAGELOOP"; break;
631 case QUITMESSAGELOOP: os << "QUITMESSAGELOOP"; break;
632 case ORDERED: os << "ORDERED"; break;
633 case PUMPS: os << "PUMPS"; break;
634 case SLEEP: os << "SLEEP"; break;
635 default:
636 NOTREACHED();
637 os << "Unknown TaskType";
638 break;
640 return os;
643 std::ostream& operator <<(std::ostream& os, const TaskItem& item) {
644 if (item.start)
645 return os << item.type << " " << item.cookie << " starts";
646 else
647 return os << item.type << " " << item.cookie << " ends";
650 class TaskList {
651 public:
652 void RecordStart(TaskType type, int cookie) {
653 TaskItem item(type, cookie, true);
654 DVLOG(1) << item;
655 task_list_.push_back(item);
658 void RecordEnd(TaskType type, int cookie) {
659 TaskItem item(type, cookie, false);
660 DVLOG(1) << item;
661 task_list_.push_back(item);
664 size_t Size() {
665 return task_list_.size();
668 TaskItem Get(int n) {
669 return task_list_[n];
672 private:
673 std::vector<TaskItem> task_list_;
676 // Saves the order the tasks ran.
677 void OrderedFunc(TaskList* order, int cookie) {
678 order->RecordStart(ORDERED, cookie);
679 order->RecordEnd(ORDERED, cookie);
682 #if defined(OS_WIN)
684 // MessageLoop implicitly start a "modal message loop". Modal dialog boxes,
685 // common controls (like OpenFile) and StartDoc printing function can cause
686 // implicit message loops.
687 void MessageBoxFunc(TaskList* order, int cookie, bool is_reentrant) {
688 order->RecordStart(MESSAGEBOX, cookie);
689 if (is_reentrant)
690 MessageLoop::current()->SetNestableTasksAllowed(true);
691 MessageBox(NULL, L"Please wait...", kMessageBoxTitle, MB_OK);
692 order->RecordEnd(MESSAGEBOX, cookie);
695 // Will end the MessageBox.
696 void EndDialogFunc(TaskList* order, int cookie) {
697 order->RecordStart(ENDDIALOG, cookie);
698 HWND window = GetActiveWindow();
699 if (window != NULL) {
700 EXPECT_NE(EndDialog(window, IDCONTINUE), 0);
701 // Cheap way to signal that the window wasn't found if RunEnd() isn't
702 // called.
703 order->RecordEnd(ENDDIALOG, cookie);
707 #endif // defined(OS_WIN)
709 void RecursiveFunc(TaskList* order, int cookie, int depth,
710 bool is_reentrant) {
711 order->RecordStart(RECURSIVE, cookie);
712 if (depth > 0) {
713 if (is_reentrant)
714 MessageLoop::current()->SetNestableTasksAllowed(true);
715 MessageLoop::current()->PostTask(
716 FROM_HERE,
717 base::Bind(&RecursiveFunc, order, cookie, depth - 1, is_reentrant));
719 order->RecordEnd(RECURSIVE, cookie);
722 void RecursiveSlowFunc(TaskList* order, int cookie, int depth,
723 bool is_reentrant) {
724 RecursiveFunc(order, cookie, depth, is_reentrant);
725 PlatformThread::Sleep(TimeDelta::FromMilliseconds(10));
728 void QuitFunc(TaskList* order, int cookie) {
729 order->RecordStart(QUITMESSAGELOOP, cookie);
730 MessageLoop::current()->QuitWhenIdle();
731 order->RecordEnd(QUITMESSAGELOOP, cookie);
734 void SleepFunc(TaskList* order, int cookie, TimeDelta delay) {
735 order->RecordStart(SLEEP, cookie);
736 PlatformThread::Sleep(delay);
737 order->RecordEnd(SLEEP, cookie);
740 #if defined(OS_WIN)
741 void RecursiveFuncWin(MessageLoop* target,
742 HANDLE event,
743 bool expect_window,
744 TaskList* order,
745 bool is_reentrant) {
746 target->PostTask(FROM_HERE,
747 base::Bind(&RecursiveFunc, order, 1, 2, is_reentrant));
748 target->PostTask(FROM_HERE,
749 base::Bind(&MessageBoxFunc, order, 2, is_reentrant));
750 target->PostTask(FROM_HERE,
751 base::Bind(&RecursiveFunc, order, 3, 2, is_reentrant));
752 // The trick here is that for recursive task processing, this task will be
753 // ran _inside_ the MessageBox message loop, dismissing the MessageBox
754 // without a chance.
755 // For non-recursive task processing, this will be executed _after_ the
756 // MessageBox will have been dismissed by the code below, where
757 // expect_window_ is true.
758 target->PostTask(FROM_HERE,
759 base::Bind(&EndDialogFunc, order, 4));
760 target->PostTask(FROM_HERE,
761 base::Bind(&QuitFunc, order, 5));
763 // Enforce that every tasks are sent before starting to run the main thread
764 // message loop.
765 ASSERT_TRUE(SetEvent(event));
767 // Poll for the MessageBox. Don't do this at home! At the speed we do it,
768 // you will never realize one MessageBox was shown.
769 for (; expect_window;) {
770 HWND window = FindWindow(L"#32770", kMessageBoxTitle);
771 if (window) {
772 // Dismiss it.
773 for (;;) {
774 HWND button = FindWindowEx(window, NULL, L"Button", NULL);
775 if (button != NULL) {
776 EXPECT_EQ(0, SendMessage(button, WM_LBUTTONDOWN, 0, 0));
777 EXPECT_EQ(0, SendMessage(button, WM_LBUTTONUP, 0, 0));
778 break;
781 break;
786 #endif // defined(OS_WIN)
788 void RunTest_RecursiveDenial1(MessageLoop::Type message_loop_type) {
789 MessageLoop loop(message_loop_type);
791 EXPECT_TRUE(MessageLoop::current()->NestableTasksAllowed());
792 TaskList order;
793 MessageLoop::current()->PostTask(
794 FROM_HERE,
795 base::Bind(&RecursiveFunc, &order, 1, 2, false));
796 MessageLoop::current()->PostTask(
797 FROM_HERE,
798 base::Bind(&RecursiveFunc, &order, 2, 2, false));
799 MessageLoop::current()->PostTask(
800 FROM_HERE,
801 base::Bind(&QuitFunc, &order, 3));
803 MessageLoop::current()->Run();
805 // FIFO order.
806 ASSERT_EQ(14U, order.Size());
807 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
808 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
809 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
810 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
811 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
812 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
813 EXPECT_EQ(order.Get(6), TaskItem(RECURSIVE, 1, true));
814 EXPECT_EQ(order.Get(7), TaskItem(RECURSIVE, 1, false));
815 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
816 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
817 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
818 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
819 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 2, true));
820 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 2, false));
823 void RunTest_RecursiveDenial3(MessageLoop::Type message_loop_type) {
824 MessageLoop loop(message_loop_type);
826 EXPECT_TRUE(MessageLoop::current()->NestableTasksAllowed());
827 TaskList order;
828 MessageLoop::current()->PostTask(
829 FROM_HERE, base::Bind(&RecursiveSlowFunc, &order, 1, 2, false));
830 MessageLoop::current()->PostTask(
831 FROM_HERE, base::Bind(&RecursiveSlowFunc, &order, 2, 2, false));
832 MessageLoop::current()->PostDelayedTask(
833 FROM_HERE,
834 base::Bind(&OrderedFunc, &order, 3),
835 TimeDelta::FromMilliseconds(5));
836 MessageLoop::current()->PostDelayedTask(
837 FROM_HERE,
838 base::Bind(&QuitFunc, &order, 4),
839 TimeDelta::FromMilliseconds(5));
841 MessageLoop::current()->Run();
843 // FIFO order.
844 ASSERT_EQ(16U, order.Size());
845 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
846 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
847 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
848 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
849 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 1, true));
850 EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 1, false));
851 EXPECT_EQ(order.Get(6), TaskItem(ORDERED, 3, true));
852 EXPECT_EQ(order.Get(7), TaskItem(ORDERED, 3, false));
853 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
854 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
855 EXPECT_EQ(order.Get(10), TaskItem(QUITMESSAGELOOP, 4, true));
856 EXPECT_EQ(order.Get(11), TaskItem(QUITMESSAGELOOP, 4, false));
857 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 1, true));
858 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, false));
859 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 2, true));
860 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 2, false));
863 void RunTest_RecursiveSupport1(MessageLoop::Type message_loop_type) {
864 MessageLoop loop(message_loop_type);
866 TaskList order;
867 MessageLoop::current()->PostTask(
868 FROM_HERE, base::Bind(&RecursiveFunc, &order, 1, 2, true));
869 MessageLoop::current()->PostTask(
870 FROM_HERE, base::Bind(&RecursiveFunc, &order, 2, 2, true));
871 MessageLoop::current()->PostTask(
872 FROM_HERE, base::Bind(&QuitFunc, &order, 3));
874 MessageLoop::current()->Run();
876 // FIFO order.
877 ASSERT_EQ(14U, order.Size());
878 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
879 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
880 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
881 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
882 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
883 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
884 EXPECT_EQ(order.Get(6), TaskItem(RECURSIVE, 1, true));
885 EXPECT_EQ(order.Get(7), TaskItem(RECURSIVE, 1, false));
886 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
887 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
888 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
889 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
890 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 2, true));
891 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 2, false));
894 #if defined(OS_WIN)
895 // TODO(darin): These tests need to be ported since they test critical
896 // message loop functionality.
898 // A side effect of this test is the generation a beep. Sorry.
899 void RunTest_RecursiveDenial2(MessageLoop::Type message_loop_type) {
900 MessageLoop loop(message_loop_type);
902 Thread worker("RecursiveDenial2_worker");
903 Thread::Options options;
904 options.message_loop_type = message_loop_type;
905 ASSERT_EQ(true, worker.StartWithOptions(options));
906 TaskList order;
907 base::win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
908 worker.message_loop()->PostTask(FROM_HERE,
909 base::Bind(&RecursiveFuncWin,
910 MessageLoop::current(),
911 event.Get(),
912 true,
913 &order,
914 false));
915 // Let the other thread execute.
916 WaitForSingleObject(event, INFINITE);
917 MessageLoop::current()->Run();
919 ASSERT_EQ(order.Size(), 17);
920 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
921 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
922 EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
923 EXPECT_EQ(order.Get(3), TaskItem(MESSAGEBOX, 2, false));
924 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, true));
925 EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 3, false));
926 // When EndDialogFunc is processed, the window is already dismissed, hence no
927 // "end" entry.
928 EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, true));
929 EXPECT_EQ(order.Get(7), TaskItem(QUITMESSAGELOOP, 5, true));
930 EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, false));
931 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 1, true));
932 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, false));
933 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 3, true));
934 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, false));
935 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, true));
936 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, false));
937 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 3, true));
938 EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, false));
941 // A side effect of this test is the generation a beep. Sorry. This test also
942 // needs to process windows messages on the current thread.
943 void RunTest_RecursiveSupport2(MessageLoop::Type message_loop_type) {
944 MessageLoop loop(message_loop_type);
946 Thread worker("RecursiveSupport2_worker");
947 Thread::Options options;
948 options.message_loop_type = message_loop_type;
949 ASSERT_EQ(true, worker.StartWithOptions(options));
950 TaskList order;
951 base::win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
952 worker.message_loop()->PostTask(FROM_HERE,
953 base::Bind(&RecursiveFuncWin,
954 MessageLoop::current(),
955 event.Get(),
956 false,
957 &order,
958 true));
959 // Let the other thread execute.
960 WaitForSingleObject(event, INFINITE);
961 MessageLoop::current()->Run();
963 ASSERT_EQ(order.Size(), 18);
964 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
965 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
966 EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
967 // Note that this executes in the MessageBox modal loop.
968 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 3, true));
969 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, false));
970 EXPECT_EQ(order.Get(5), TaskItem(ENDDIALOG, 4, true));
971 EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, false));
972 EXPECT_EQ(order.Get(7), TaskItem(MESSAGEBOX, 2, false));
973 /* The order can subtly change here. The reason is that when RecursiveFunc(1)
974 is called in the main thread, if it is faster than getting to the
975 PostTask(FROM_HERE, base::Bind(&QuitFunc) execution, the order of task
976 execution can change. We don't care anyway that the order isn't correct.
977 EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, true));
978 EXPECT_EQ(order.Get(9), TaskItem(QUITMESSAGELOOP, 5, false));
979 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
980 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
982 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, true));
983 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 3, false));
984 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, true));
985 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 1, false));
986 EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, true));
987 EXPECT_EQ(order.Get(17), TaskItem(RECURSIVE, 3, false));
990 #endif // defined(OS_WIN)
992 void FuncThatPumps(TaskList* order, int cookie) {
993 order->RecordStart(PUMPS, cookie);
995 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
996 base::RunLoop().RunUntilIdle();
998 order->RecordEnd(PUMPS, cookie);
1001 void FuncThatRuns(TaskList* order, int cookie, base::RunLoop* run_loop) {
1002 order->RecordStart(RUNS, cookie);
1004 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
1005 run_loop->Run();
1007 order->RecordEnd(RUNS, cookie);
1010 void FuncThatQuitsNow() {
1011 MessageLoop::current()->QuitNow();
1014 // Tests that non nestable tasks run in FIFO if there are no nested loops.
1015 void RunTest_NonNestableWithNoNesting(
1016 MessageLoop::Type message_loop_type) {
1017 MessageLoop loop(message_loop_type);
1019 TaskList order;
1021 MessageLoop::current()->PostNonNestableTask(
1022 FROM_HERE,
1023 base::Bind(&OrderedFunc, &order, 1));
1024 MessageLoop::current()->PostTask(FROM_HERE,
1025 base::Bind(&OrderedFunc, &order, 2));
1026 MessageLoop::current()->PostTask(FROM_HERE,
1027 base::Bind(&QuitFunc, &order, 3));
1028 MessageLoop::current()->Run();
1030 // FIFO order.
1031 ASSERT_EQ(6U, order.Size());
1032 EXPECT_EQ(order.Get(0), TaskItem(ORDERED, 1, true));
1033 EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 1, false));
1034 EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 2, true));
1035 EXPECT_EQ(order.Get(3), TaskItem(ORDERED, 2, false));
1036 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
1037 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
1040 // Tests that non nestable tasks don't run when there's code in the call stack.
1041 void RunTest_NonNestableInNestedLoop(MessageLoop::Type message_loop_type,
1042 bool use_delayed) {
1043 MessageLoop loop(message_loop_type);
1045 TaskList order;
1047 MessageLoop::current()->PostTask(
1048 FROM_HERE,
1049 base::Bind(&FuncThatPumps, &order, 1));
1050 if (use_delayed) {
1051 MessageLoop::current()->PostNonNestableDelayedTask(
1052 FROM_HERE,
1053 base::Bind(&OrderedFunc, &order, 2),
1054 TimeDelta::FromMilliseconds(1));
1055 } else {
1056 MessageLoop::current()->PostNonNestableTask(
1057 FROM_HERE,
1058 base::Bind(&OrderedFunc, &order, 2));
1060 MessageLoop::current()->PostTask(FROM_HERE,
1061 base::Bind(&OrderedFunc, &order, 3));
1062 MessageLoop::current()->PostTask(
1063 FROM_HERE,
1064 base::Bind(&SleepFunc, &order, 4, TimeDelta::FromMilliseconds(50)));
1065 MessageLoop::current()->PostTask(FROM_HERE,
1066 base::Bind(&OrderedFunc, &order, 5));
1067 if (use_delayed) {
1068 MessageLoop::current()->PostNonNestableDelayedTask(
1069 FROM_HERE,
1070 base::Bind(&QuitFunc, &order, 6),
1071 TimeDelta::FromMilliseconds(2));
1072 } else {
1073 MessageLoop::current()->PostNonNestableTask(
1074 FROM_HERE,
1075 base::Bind(&QuitFunc, &order, 6));
1078 MessageLoop::current()->Run();
1080 // FIFO order.
1081 ASSERT_EQ(12U, order.Size());
1082 EXPECT_EQ(order.Get(0), TaskItem(PUMPS, 1, true));
1083 EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 3, true));
1084 EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 3, false));
1085 EXPECT_EQ(order.Get(3), TaskItem(SLEEP, 4, true));
1086 EXPECT_EQ(order.Get(4), TaskItem(SLEEP, 4, false));
1087 EXPECT_EQ(order.Get(5), TaskItem(ORDERED, 5, true));
1088 EXPECT_EQ(order.Get(6), TaskItem(ORDERED, 5, false));
1089 EXPECT_EQ(order.Get(7), TaskItem(PUMPS, 1, false));
1090 EXPECT_EQ(order.Get(8), TaskItem(ORDERED, 2, true));
1091 EXPECT_EQ(order.Get(9), TaskItem(ORDERED, 2, false));
1092 EXPECT_EQ(order.Get(10), TaskItem(QUITMESSAGELOOP, 6, true));
1093 EXPECT_EQ(order.Get(11), TaskItem(QUITMESSAGELOOP, 6, false));
1096 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1097 void RunTest_QuitNow(MessageLoop::Type message_loop_type) {
1098 MessageLoop loop(message_loop_type);
1100 TaskList order;
1102 base::RunLoop run_loop;
1104 MessageLoop::current()->PostTask(FROM_HERE,
1105 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&run_loop)));
1106 MessageLoop::current()->PostTask(
1107 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1108 MessageLoop::current()->PostTask(
1109 FROM_HERE, base::Bind(&FuncThatQuitsNow));
1110 MessageLoop::current()->PostTask(
1111 FROM_HERE, base::Bind(&OrderedFunc, &order, 3));
1112 MessageLoop::current()->PostTask(
1113 FROM_HERE, base::Bind(&FuncThatQuitsNow));
1114 MessageLoop::current()->PostTask(
1115 FROM_HERE, base::Bind(&OrderedFunc, &order, 4)); // never runs
1117 MessageLoop::current()->Run();
1119 ASSERT_EQ(6U, order.Size());
1120 int task_index = 0;
1121 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1122 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1123 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1124 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1125 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
1126 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
1127 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1130 // Tests RunLoopQuit works before RunWithID.
1131 void RunTest_RunLoopQuitOrderBefore(MessageLoop::Type message_loop_type) {
1132 MessageLoop loop(message_loop_type);
1134 TaskList order;
1136 base::RunLoop run_loop;
1138 run_loop.Quit();
1140 MessageLoop::current()->PostTask(
1141 FROM_HERE, base::Bind(&OrderedFunc, &order, 1)); // never runs
1142 MessageLoop::current()->PostTask(
1143 FROM_HERE, base::Bind(&FuncThatQuitsNow)); // never runs
1145 run_loop.Run();
1147 ASSERT_EQ(0U, order.Size());
1150 // Tests RunLoopQuit works during RunWithID.
1151 void RunTest_RunLoopQuitOrderDuring(MessageLoop::Type message_loop_type) {
1152 MessageLoop loop(message_loop_type);
1154 TaskList order;
1156 base::RunLoop run_loop;
1158 MessageLoop::current()->PostTask(
1159 FROM_HERE, base::Bind(&OrderedFunc, &order, 1));
1160 MessageLoop::current()->PostTask(
1161 FROM_HERE, run_loop.QuitClosure());
1162 MessageLoop::current()->PostTask(
1163 FROM_HERE, base::Bind(&OrderedFunc, &order, 2)); // never runs
1164 MessageLoop::current()->PostTask(
1165 FROM_HERE, base::Bind(&FuncThatQuitsNow)); // never runs
1167 run_loop.Run();
1169 ASSERT_EQ(2U, order.Size());
1170 int task_index = 0;
1171 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, true));
1172 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, false));
1173 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1176 // Tests RunLoopQuit works after RunWithID.
1177 void RunTest_RunLoopQuitOrderAfter(MessageLoop::Type message_loop_type) {
1178 MessageLoop loop(message_loop_type);
1180 TaskList order;
1182 base::RunLoop run_loop;
1184 MessageLoop::current()->PostTask(FROM_HERE,
1185 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&run_loop)));
1186 MessageLoop::current()->PostTask(
1187 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1188 MessageLoop::current()->PostTask(
1189 FROM_HERE, base::Bind(&FuncThatQuitsNow));
1190 MessageLoop::current()->PostTask(
1191 FROM_HERE, base::Bind(&OrderedFunc, &order, 3));
1192 MessageLoop::current()->PostTask(
1193 FROM_HERE, run_loop.QuitClosure()); // has no affect
1194 MessageLoop::current()->PostTask(
1195 FROM_HERE, base::Bind(&OrderedFunc, &order, 4));
1196 MessageLoop::current()->PostTask(
1197 FROM_HERE, base::Bind(&FuncThatQuitsNow));
1199 base::RunLoop outer_run_loop;
1200 outer_run_loop.Run();
1202 ASSERT_EQ(8U, order.Size());
1203 int task_index = 0;
1204 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1205 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1206 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1207 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1208 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
1209 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
1210 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, true));
1211 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, false));
1212 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1215 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1216 void RunTest_RunLoopQuitTop(MessageLoop::Type message_loop_type) {
1217 MessageLoop loop(message_loop_type);
1219 TaskList order;
1221 base::RunLoop outer_run_loop;
1222 base::RunLoop nested_run_loop;
1224 MessageLoop::current()->PostTask(FROM_HERE,
1225 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&nested_run_loop)));
1226 MessageLoop::current()->PostTask(
1227 FROM_HERE, outer_run_loop.QuitClosure());
1228 MessageLoop::current()->PostTask(
1229 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1230 MessageLoop::current()->PostTask(
1231 FROM_HERE, nested_run_loop.QuitClosure());
1233 outer_run_loop.Run();
1235 ASSERT_EQ(4U, order.Size());
1236 int task_index = 0;
1237 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1238 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1239 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1240 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1241 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1244 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1245 void RunTest_RunLoopQuitNested(MessageLoop::Type message_loop_type) {
1246 MessageLoop loop(message_loop_type);
1248 TaskList order;
1250 base::RunLoop outer_run_loop;
1251 base::RunLoop nested_run_loop;
1253 MessageLoop::current()->PostTask(FROM_HERE,
1254 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&nested_run_loop)));
1255 MessageLoop::current()->PostTask(
1256 FROM_HERE, nested_run_loop.QuitClosure());
1257 MessageLoop::current()->PostTask(
1258 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1259 MessageLoop::current()->PostTask(
1260 FROM_HERE, outer_run_loop.QuitClosure());
1262 outer_run_loop.Run();
1264 ASSERT_EQ(4U, order.Size());
1265 int task_index = 0;
1266 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1267 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1268 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1269 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1270 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1273 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1274 void RunTest_RunLoopQuitBogus(MessageLoop::Type message_loop_type) {
1275 MessageLoop loop(message_loop_type);
1277 TaskList order;
1279 base::RunLoop outer_run_loop;
1280 base::RunLoop nested_run_loop;
1281 base::RunLoop bogus_run_loop;
1283 MessageLoop::current()->PostTask(FROM_HERE,
1284 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&nested_run_loop)));
1285 MessageLoop::current()->PostTask(
1286 FROM_HERE, bogus_run_loop.QuitClosure());
1287 MessageLoop::current()->PostTask(
1288 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1289 MessageLoop::current()->PostTask(
1290 FROM_HERE, outer_run_loop.QuitClosure());
1291 MessageLoop::current()->PostTask(
1292 FROM_HERE, nested_run_loop.QuitClosure());
1294 outer_run_loop.Run();
1296 ASSERT_EQ(4U, order.Size());
1297 int task_index = 0;
1298 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1299 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1300 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1301 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1302 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1305 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1306 void RunTest_RunLoopQuitDeep(MessageLoop::Type message_loop_type) {
1307 MessageLoop loop(message_loop_type);
1309 TaskList order;
1311 base::RunLoop outer_run_loop;
1312 base::RunLoop nested_loop1;
1313 base::RunLoop nested_loop2;
1314 base::RunLoop nested_loop3;
1315 base::RunLoop nested_loop4;
1317 MessageLoop::current()->PostTask(FROM_HERE,
1318 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&nested_loop1)));
1319 MessageLoop::current()->PostTask(FROM_HERE,
1320 base::Bind(&FuncThatRuns, &order, 2, base::Unretained(&nested_loop2)));
1321 MessageLoop::current()->PostTask(FROM_HERE,
1322 base::Bind(&FuncThatRuns, &order, 3, base::Unretained(&nested_loop3)));
1323 MessageLoop::current()->PostTask(FROM_HERE,
1324 base::Bind(&FuncThatRuns, &order, 4, base::Unretained(&nested_loop4)));
1325 MessageLoop::current()->PostTask(
1326 FROM_HERE, base::Bind(&OrderedFunc, &order, 5));
1327 MessageLoop::current()->PostTask(
1328 FROM_HERE, outer_run_loop.QuitClosure());
1329 MessageLoop::current()->PostTask(
1330 FROM_HERE, base::Bind(&OrderedFunc, &order, 6));
1331 MessageLoop::current()->PostTask(
1332 FROM_HERE, nested_loop1.QuitClosure());
1333 MessageLoop::current()->PostTask(
1334 FROM_HERE, base::Bind(&OrderedFunc, &order, 7));
1335 MessageLoop::current()->PostTask(
1336 FROM_HERE, nested_loop2.QuitClosure());
1337 MessageLoop::current()->PostTask(
1338 FROM_HERE, base::Bind(&OrderedFunc, &order, 8));
1339 MessageLoop::current()->PostTask(
1340 FROM_HERE, nested_loop3.QuitClosure());
1341 MessageLoop::current()->PostTask(
1342 FROM_HERE, base::Bind(&OrderedFunc, &order, 9));
1343 MessageLoop::current()->PostTask(
1344 FROM_HERE, nested_loop4.QuitClosure());
1345 MessageLoop::current()->PostTask(
1346 FROM_HERE, base::Bind(&OrderedFunc, &order, 10));
1348 outer_run_loop.Run();
1350 ASSERT_EQ(18U, order.Size());
1351 int task_index = 0;
1352 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1353 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, true));
1354 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, true));
1355 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, true));
1356 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, true));
1357 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, false));
1358 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, true));
1359 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, false));
1360 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, true));
1361 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, false));
1362 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, true));
1363 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, false));
1364 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, true));
1365 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, false));
1366 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, false));
1367 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, false));
1368 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, false));
1369 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1370 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1373 void PostNTasksThenQuit(int posts_remaining) {
1374 if (posts_remaining > 1) {
1375 MessageLoop::current()->PostTask(
1376 FROM_HERE,
1377 base::Bind(&PostNTasksThenQuit, posts_remaining - 1));
1378 } else {
1379 MessageLoop::current()->QuitWhenIdle();
1383 void RunTest_RecursivePosts(MessageLoop::Type message_loop_type,
1384 int num_times) {
1385 MessageLoop loop(message_loop_type);
1386 loop.PostTask(FROM_HERE, base::Bind(&PostNTasksThenQuit, num_times));
1387 loop.Run();
1390 #if defined(OS_WIN)
1392 class DispatcherImpl : public MessageLoopForUI::Dispatcher {
1393 public:
1394 DispatcherImpl() : dispatch_count_(0) {}
1396 virtual bool Dispatch(const base::NativeEvent& msg) OVERRIDE {
1397 ::TranslateMessage(&msg);
1398 ::DispatchMessage(&msg);
1399 // Do not count WM_TIMER since it is not what we post and it will cause
1400 // flakiness.
1401 if (msg.message != WM_TIMER)
1402 ++dispatch_count_;
1403 // We treat WM_LBUTTONUP as the last message.
1404 return msg.message != WM_LBUTTONUP;
1407 int dispatch_count_;
1410 void MouseDownUp() {
1411 PostMessage(NULL, WM_LBUTTONDOWN, 0, 0);
1412 PostMessage(NULL, WM_LBUTTONUP, 'A', 0);
1415 void RunTest_Dispatcher(MessageLoop::Type message_loop_type) {
1416 MessageLoop loop(message_loop_type);
1418 MessageLoop::current()->PostDelayedTask(
1419 FROM_HERE,
1420 base::Bind(&MouseDownUp),
1421 TimeDelta::FromMilliseconds(100));
1422 DispatcherImpl dispatcher;
1423 base::RunLoop run_loop(&dispatcher);
1424 run_loop.Run();
1425 ASSERT_EQ(2, dispatcher.dispatch_count_);
1428 LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) {
1429 if (code == base::MessagePumpForUI::kMessageFilterCode) {
1430 MSG* msg = reinterpret_cast<MSG*>(lparam);
1431 if (msg->message == WM_LBUTTONDOWN)
1432 return TRUE;
1434 return FALSE;
1437 void RunTest_DispatcherWithMessageHook(MessageLoop::Type message_loop_type) {
1438 MessageLoop loop(message_loop_type);
1440 MessageLoop::current()->PostDelayedTask(
1441 FROM_HERE,
1442 base::Bind(&MouseDownUp),
1443 TimeDelta::FromMilliseconds(100));
1444 HHOOK msg_hook = SetWindowsHookEx(WH_MSGFILTER,
1445 MsgFilterProc,
1446 NULL,
1447 GetCurrentThreadId());
1448 DispatcherImpl dispatcher;
1449 base::RunLoop run_loop(&dispatcher);
1450 run_loop.Run();
1451 ASSERT_EQ(1, dispatcher.dispatch_count_);
1452 UnhookWindowsHookEx(msg_hook);
1455 class TestIOHandler : public MessageLoopForIO::IOHandler {
1456 public:
1457 TestIOHandler(const wchar_t* name, HANDLE signal, bool wait);
1459 virtual void OnIOCompleted(MessageLoopForIO::IOContext* context,
1460 DWORD bytes_transfered, DWORD error);
1462 void Init();
1463 void WaitForIO();
1464 OVERLAPPED* context() { return &context_.overlapped; }
1465 DWORD size() { return sizeof(buffer_); }
1467 private:
1468 char buffer_[48];
1469 MessageLoopForIO::IOContext context_;
1470 HANDLE signal_;
1471 base::win::ScopedHandle file_;
1472 bool wait_;
1475 TestIOHandler::TestIOHandler(const wchar_t* name, HANDLE signal, bool wait)
1476 : signal_(signal), wait_(wait) {
1477 memset(buffer_, 0, sizeof(buffer_));
1478 memset(&context_, 0, sizeof(context_));
1479 context_.handler = this;
1481 file_.Set(CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING,
1482 FILE_FLAG_OVERLAPPED, NULL));
1483 EXPECT_TRUE(file_.IsValid());
1486 void TestIOHandler::Init() {
1487 MessageLoopForIO::current()->RegisterIOHandler(file_, this);
1489 DWORD read;
1490 EXPECT_FALSE(ReadFile(file_, buffer_, size(), &read, context()));
1491 EXPECT_EQ(ERROR_IO_PENDING, GetLastError());
1492 if (wait_)
1493 WaitForIO();
1496 void TestIOHandler::OnIOCompleted(MessageLoopForIO::IOContext* context,
1497 DWORD bytes_transfered, DWORD error) {
1498 ASSERT_TRUE(context == &context_);
1499 ASSERT_TRUE(SetEvent(signal_));
1502 void TestIOHandler::WaitForIO() {
1503 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(300, this));
1504 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(400, this));
1507 void RunTest_IOHandler() {
1508 base::win::ScopedHandle callback_called(CreateEvent(NULL, TRUE, FALSE, NULL));
1509 ASSERT_TRUE(callback_called.IsValid());
1511 const wchar_t* kPipeName = L"\\\\.\\pipe\\iohandler_pipe";
1512 base::win::ScopedHandle server(
1513 CreateNamedPipe(kPipeName, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1514 ASSERT_TRUE(server.IsValid());
1516 Thread thread("IOHandler test");
1517 Thread::Options options;
1518 options.message_loop_type = MessageLoop::TYPE_IO;
1519 ASSERT_TRUE(thread.StartWithOptions(options));
1521 MessageLoop* thread_loop = thread.message_loop();
1522 ASSERT_TRUE(NULL != thread_loop);
1524 TestIOHandler handler(kPipeName, callback_called, false);
1525 thread_loop->PostTask(FROM_HERE, base::Bind(&TestIOHandler::Init,
1526 base::Unretained(&handler)));
1527 // Make sure the thread runs and sleeps for lack of work.
1528 base::PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
1530 const char buffer[] = "Hello there!";
1531 DWORD written;
1532 EXPECT_TRUE(WriteFile(server, buffer, sizeof(buffer), &written, NULL));
1534 DWORD result = WaitForSingleObject(callback_called, 1000);
1535 EXPECT_EQ(WAIT_OBJECT_0, result);
1537 thread.Stop();
1540 void RunTest_WaitForIO() {
1541 base::win::ScopedHandle callback1_called(
1542 CreateEvent(NULL, TRUE, FALSE, NULL));
1543 base::win::ScopedHandle callback2_called(
1544 CreateEvent(NULL, TRUE, FALSE, NULL));
1545 ASSERT_TRUE(callback1_called.IsValid());
1546 ASSERT_TRUE(callback2_called.IsValid());
1548 const wchar_t* kPipeName1 = L"\\\\.\\pipe\\iohandler_pipe1";
1549 const wchar_t* kPipeName2 = L"\\\\.\\pipe\\iohandler_pipe2";
1550 base::win::ScopedHandle server1(
1551 CreateNamedPipe(kPipeName1, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1552 base::win::ScopedHandle server2(
1553 CreateNamedPipe(kPipeName2, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1554 ASSERT_TRUE(server1.IsValid());
1555 ASSERT_TRUE(server2.IsValid());
1557 Thread thread("IOHandler test");
1558 Thread::Options options;
1559 options.message_loop_type = MessageLoop::TYPE_IO;
1560 ASSERT_TRUE(thread.StartWithOptions(options));
1562 MessageLoop* thread_loop = thread.message_loop();
1563 ASSERT_TRUE(NULL != thread_loop);
1565 TestIOHandler handler1(kPipeName1, callback1_called, false);
1566 TestIOHandler handler2(kPipeName2, callback2_called, true);
1567 thread_loop->PostTask(FROM_HERE, base::Bind(&TestIOHandler::Init,
1568 base::Unretained(&handler1)));
1569 // TODO(ajwong): Do we really need such long Sleeps in ths function?
1570 // Make sure the thread runs and sleeps for lack of work.
1571 TimeDelta delay = TimeDelta::FromMilliseconds(100);
1572 base::PlatformThread::Sleep(delay);
1573 thread_loop->PostTask(FROM_HERE, base::Bind(&TestIOHandler::Init,
1574 base::Unretained(&handler2)));
1575 base::PlatformThread::Sleep(delay);
1577 // At this time handler1 is waiting to be called, and the thread is waiting
1578 // on the Init method of handler2, filtering only handler2 callbacks.
1580 const char buffer[] = "Hello there!";
1581 DWORD written;
1582 EXPECT_TRUE(WriteFile(server1, buffer, sizeof(buffer), &written, NULL));
1583 base::PlatformThread::Sleep(2 * delay);
1584 EXPECT_EQ(WAIT_TIMEOUT, WaitForSingleObject(callback1_called, 0)) <<
1585 "handler1 has not been called";
1587 EXPECT_TRUE(WriteFile(server2, buffer, sizeof(buffer), &written, NULL));
1589 HANDLE objects[2] = { callback1_called.Get(), callback2_called.Get() };
1590 DWORD result = WaitForMultipleObjects(2, objects, TRUE, 1000);
1591 EXPECT_EQ(WAIT_OBJECT_0, result);
1593 thread.Stop();
1596 #endif // defined(OS_WIN)
1598 } // namespace
1600 //-----------------------------------------------------------------------------
1601 // Each test is run against each type of MessageLoop. That way we are sure
1602 // that message loops work properly in all configurations. Of course, in some
1603 // cases, a unit test may only be for a particular type of loop.
1605 TEST(MessageLoopTest, PostTask) {
1606 RunTest_PostTask(MessageLoop::TYPE_DEFAULT);
1607 RunTest_PostTask(MessageLoop::TYPE_UI);
1608 RunTest_PostTask(MessageLoop::TYPE_IO);
1611 TEST(MessageLoopTest, PostTask_SEH) {
1612 RunTest_PostTask_SEH(MessageLoop::TYPE_DEFAULT);
1613 RunTest_PostTask_SEH(MessageLoop::TYPE_UI);
1614 RunTest_PostTask_SEH(MessageLoop::TYPE_IO);
1617 TEST(MessageLoopTest, PostDelayedTask_Basic) {
1618 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_DEFAULT);
1619 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_UI);
1620 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_IO);
1623 TEST(MessageLoopTest, PostDelayedTask_InDelayOrder) {
1624 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_DEFAULT);
1625 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_UI);
1626 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_IO);
1629 TEST(MessageLoopTest, PostDelayedTask_InPostOrder) {
1630 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_DEFAULT);
1631 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_UI);
1632 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_IO);
1635 TEST(MessageLoopTest, PostDelayedTask_InPostOrder_2) {
1636 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_DEFAULT);
1637 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_UI);
1638 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_IO);
1641 TEST(MessageLoopTest, PostDelayedTask_InPostOrder_3) {
1642 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_DEFAULT);
1643 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_UI);
1644 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_IO);
1647 TEST(MessageLoopTest, PostDelayedTask_SharedTimer) {
1648 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_DEFAULT);
1649 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_UI);
1650 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_IO);
1653 #if defined(OS_WIN)
1654 TEST(MessageLoopTest, PostDelayedTask_SharedTimer_SubPump) {
1655 RunTest_PostDelayedTask_SharedTimer_SubPump();
1657 #endif
1659 // TODO(darin): MessageLoop does not support deleting all tasks in the
1660 // destructor.
1661 // Fails, http://crbug.com/50272.
1662 TEST(MessageLoopTest, DISABLED_EnsureDeletion) {
1663 RunTest_EnsureDeletion(MessageLoop::TYPE_DEFAULT);
1664 RunTest_EnsureDeletion(MessageLoop::TYPE_UI);
1665 RunTest_EnsureDeletion(MessageLoop::TYPE_IO);
1668 // TODO(darin): MessageLoop does not support deleting all tasks in the
1669 // destructor.
1670 // Fails, http://crbug.com/50272.
1671 TEST(MessageLoopTest, DISABLED_EnsureDeletion_Chain) {
1672 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_DEFAULT);
1673 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_UI);
1674 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_IO);
1677 #if defined(OS_WIN)
1678 TEST(MessageLoopTest, Crasher) {
1679 RunTest_Crasher(MessageLoop::TYPE_DEFAULT);
1680 RunTest_Crasher(MessageLoop::TYPE_UI);
1681 RunTest_Crasher(MessageLoop::TYPE_IO);
1684 TEST(MessageLoopTest, CrasherNasty) {
1685 RunTest_CrasherNasty(MessageLoop::TYPE_DEFAULT);
1686 RunTest_CrasherNasty(MessageLoop::TYPE_UI);
1687 RunTest_CrasherNasty(MessageLoop::TYPE_IO);
1689 #endif // defined(OS_WIN)
1691 TEST(MessageLoopTest, Nesting) {
1692 RunTest_Nesting(MessageLoop::TYPE_DEFAULT);
1693 RunTest_Nesting(MessageLoop::TYPE_UI);
1694 RunTest_Nesting(MessageLoop::TYPE_IO);
1697 TEST(MessageLoopTest, RecursiveDenial1) {
1698 RunTest_RecursiveDenial1(MessageLoop::TYPE_DEFAULT);
1699 RunTest_RecursiveDenial1(MessageLoop::TYPE_UI);
1700 RunTest_RecursiveDenial1(MessageLoop::TYPE_IO);
1703 TEST(MessageLoopTest, RecursiveDenial3) {
1704 RunTest_RecursiveDenial3(MessageLoop::TYPE_DEFAULT);
1705 RunTest_RecursiveDenial3(MessageLoop::TYPE_UI);
1706 RunTest_RecursiveDenial3(MessageLoop::TYPE_IO);
1709 TEST(MessageLoopTest, RecursiveSupport1) {
1710 RunTest_RecursiveSupport1(MessageLoop::TYPE_DEFAULT);
1711 RunTest_RecursiveSupport1(MessageLoop::TYPE_UI);
1712 RunTest_RecursiveSupport1(MessageLoop::TYPE_IO);
1715 #if defined(OS_WIN)
1716 // This test occasionally hangs http://crbug.com/44567
1717 TEST(MessageLoopTest, DISABLED_RecursiveDenial2) {
1718 RunTest_RecursiveDenial2(MessageLoop::TYPE_DEFAULT);
1719 RunTest_RecursiveDenial2(MessageLoop::TYPE_UI);
1720 RunTest_RecursiveDenial2(MessageLoop::TYPE_IO);
1723 TEST(MessageLoopTest, RecursiveSupport2) {
1724 // This test requires a UI loop
1725 RunTest_RecursiveSupport2(MessageLoop::TYPE_UI);
1727 #endif // defined(OS_WIN)
1729 TEST(MessageLoopTest, NonNestableWithNoNesting) {
1730 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_DEFAULT);
1731 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_UI);
1732 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_IO);
1735 TEST(MessageLoopTest, NonNestableInNestedLoop) {
1736 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT, false);
1737 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI, false);
1738 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO, false);
1741 TEST(MessageLoopTest, NonNestableDelayedInNestedLoop) {
1742 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT, true);
1743 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI, true);
1744 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO, true);
1747 TEST(MessageLoopTest, QuitNow) {
1748 RunTest_QuitNow(MessageLoop::TYPE_DEFAULT);
1749 RunTest_QuitNow(MessageLoop::TYPE_UI);
1750 RunTest_QuitNow(MessageLoop::TYPE_IO);
1753 TEST(MessageLoopTest, RunLoopQuitTop) {
1754 RunTest_RunLoopQuitTop(MessageLoop::TYPE_DEFAULT);
1755 RunTest_RunLoopQuitTop(MessageLoop::TYPE_UI);
1756 RunTest_RunLoopQuitTop(MessageLoop::TYPE_IO);
1759 TEST(MessageLoopTest, RunLoopQuitNested) {
1760 RunTest_RunLoopQuitNested(MessageLoop::TYPE_DEFAULT);
1761 RunTest_RunLoopQuitNested(MessageLoop::TYPE_UI);
1762 RunTest_RunLoopQuitNested(MessageLoop::TYPE_IO);
1765 TEST(MessageLoopTest, RunLoopQuitBogus) {
1766 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_DEFAULT);
1767 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_UI);
1768 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_IO);
1771 TEST(MessageLoopTest, RunLoopQuitDeep) {
1772 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_DEFAULT);
1773 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_UI);
1774 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_IO);
1777 TEST(MessageLoopTest, RunLoopQuitOrderBefore) {
1778 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_DEFAULT);
1779 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_UI);
1780 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_IO);
1783 TEST(MessageLoopTest, RunLoopQuitOrderDuring) {
1784 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_DEFAULT);
1785 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_UI);
1786 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_IO);
1789 TEST(MessageLoopTest, RunLoopQuitOrderAfter) {
1790 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_DEFAULT);
1791 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_UI);
1792 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_IO);
1795 class DummyTaskObserver : public MessageLoop::TaskObserver {
1796 public:
1797 explicit DummyTaskObserver(int num_tasks)
1798 : num_tasks_started_(0),
1799 num_tasks_processed_(0),
1800 num_tasks_(num_tasks) {}
1802 virtual ~DummyTaskObserver() {}
1804 virtual void WillProcessTask(const base::PendingTask& pending_task) OVERRIDE {
1805 num_tasks_started_++;
1806 EXPECT_TRUE(pending_task.time_posted != TimeTicks());
1807 EXPECT_LE(num_tasks_started_, num_tasks_);
1808 EXPECT_EQ(num_tasks_started_, num_tasks_processed_ + 1);
1811 virtual void DidProcessTask(const base::PendingTask& pending_task) OVERRIDE {
1812 num_tasks_processed_++;
1813 EXPECT_TRUE(pending_task.time_posted != TimeTicks());
1814 EXPECT_LE(num_tasks_started_, num_tasks_);
1815 EXPECT_EQ(num_tasks_started_, num_tasks_processed_);
1818 int num_tasks_started() const { return num_tasks_started_; }
1819 int num_tasks_processed() const { return num_tasks_processed_; }
1821 private:
1822 int num_tasks_started_;
1823 int num_tasks_processed_;
1824 const int num_tasks_;
1826 DISALLOW_COPY_AND_ASSIGN(DummyTaskObserver);
1829 TEST(MessageLoopTest, TaskObserver) {
1830 const int kNumPosts = 6;
1831 DummyTaskObserver observer(kNumPosts);
1833 MessageLoop loop;
1834 loop.AddTaskObserver(&observer);
1835 loop.PostTask(FROM_HERE, base::Bind(&PostNTasksThenQuit, kNumPosts));
1836 loop.Run();
1837 loop.RemoveTaskObserver(&observer);
1839 EXPECT_EQ(kNumPosts, observer.num_tasks_started());
1840 EXPECT_EQ(kNumPosts, observer.num_tasks_processed());
1843 #if defined(OS_WIN)
1844 TEST(MessageLoopTest, Dispatcher) {
1845 // This test requires a UI loop
1846 RunTest_Dispatcher(MessageLoop::TYPE_UI);
1849 TEST(MessageLoopTest, DispatcherWithMessageHook) {
1850 // This test requires a UI loop
1851 RunTest_DispatcherWithMessageHook(MessageLoop::TYPE_UI);
1854 TEST(MessageLoopTest, IOHandler) {
1855 RunTest_IOHandler();
1858 TEST(MessageLoopTest, WaitForIO) {
1859 RunTest_WaitForIO();
1862 TEST(MessageLoopTest, HighResolutionTimer) {
1863 MessageLoop loop;
1865 const TimeDelta kFastTimer = TimeDelta::FromMilliseconds(5);
1866 const TimeDelta kSlowTimer = TimeDelta::FromMilliseconds(100);
1868 EXPECT_FALSE(loop.high_resolution_timers_enabled());
1870 // Post a fast task to enable the high resolution timers.
1871 loop.PostDelayedTask(FROM_HERE, base::Bind(&PostNTasksThenQuit, 1),
1872 kFastTimer);
1873 loop.Run();
1874 EXPECT_TRUE(loop.high_resolution_timers_enabled());
1876 // Post a slow task and verify high resolution timers
1877 // are still enabled.
1878 loop.PostDelayedTask(FROM_HERE, base::Bind(&PostNTasksThenQuit, 1),
1879 kSlowTimer);
1880 loop.Run();
1881 EXPECT_TRUE(loop.high_resolution_timers_enabled());
1883 // Wait for a while so that high-resolution mode elapses.
1884 base::PlatformThread::Sleep(TimeDelta::FromMilliseconds(
1885 MessageLoop::kHighResolutionTimerModeLeaseTimeMs));
1887 // Post a slow task to disable the high resolution timers.
1888 loop.PostDelayedTask(FROM_HERE, base::Bind(&PostNTasksThenQuit, 1),
1889 kSlowTimer);
1890 loop.Run();
1891 EXPECT_FALSE(loop.high_resolution_timers_enabled());
1894 #endif // defined(OS_WIN)
1896 #if defined(OS_POSIX) && !defined(OS_NACL)
1898 namespace {
1900 class QuitDelegate : public MessageLoopForIO::Watcher {
1901 public:
1902 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
1903 MessageLoop::current()->QuitWhenIdle();
1905 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE {
1906 MessageLoop::current()->QuitWhenIdle();
1910 TEST(MessageLoopTest, FileDescriptorWatcherOutlivesMessageLoop) {
1911 // Simulate a MessageLoop that dies before an FileDescriptorWatcher.
1912 // This could happen when people use the Singleton pattern or atexit.
1914 // Create a file descriptor. Doesn't need to be readable or writable,
1915 // as we don't need to actually get any notifications.
1916 // pipe() is just the easiest way to do it.
1917 int pipefds[2];
1918 int err = pipe(pipefds);
1919 ASSERT_EQ(0, err);
1920 int fd = pipefds[1];
1922 // Arrange for controller to live longer than message loop.
1923 MessageLoopForIO::FileDescriptorWatcher controller;
1925 MessageLoopForIO message_loop;
1927 QuitDelegate delegate;
1928 message_loop.WatchFileDescriptor(fd,
1929 true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate);
1930 // and don't run the message loop, just destroy it.
1933 if (HANDLE_EINTR(close(pipefds[0])) < 0)
1934 PLOG(ERROR) << "close";
1935 if (HANDLE_EINTR(close(pipefds[1])) < 0)
1936 PLOG(ERROR) << "close";
1939 TEST(MessageLoopTest, FileDescriptorWatcherDoubleStop) {
1940 // Verify that it's ok to call StopWatchingFileDescriptor().
1941 // (Errors only showed up in valgrind.)
1942 int pipefds[2];
1943 int err = pipe(pipefds);
1944 ASSERT_EQ(0, err);
1945 int fd = pipefds[1];
1947 // Arrange for message loop to live longer than controller.
1948 MessageLoopForIO message_loop;
1950 MessageLoopForIO::FileDescriptorWatcher controller;
1952 QuitDelegate delegate;
1953 message_loop.WatchFileDescriptor(fd,
1954 true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate);
1955 controller.StopWatchingFileDescriptor();
1958 if (HANDLE_EINTR(close(pipefds[0])) < 0)
1959 PLOG(ERROR) << "close";
1960 if (HANDLE_EINTR(close(pipefds[1])) < 0)
1961 PLOG(ERROR) << "close";
1964 } // namespace
1966 #endif // defined(OS_POSIX) && !defined(OS_NACL)
1968 namespace {
1969 // Inject a test point for recording the destructor calls for Closure objects
1970 // send to MessageLoop::PostTask(). It is awkward usage since we are trying to
1971 // hook the actual destruction, which is not a common operation.
1972 class DestructionObserverProbe :
1973 public base::RefCounted<DestructionObserverProbe> {
1974 public:
1975 DestructionObserverProbe(bool* task_destroyed,
1976 bool* destruction_observer_called)
1977 : task_destroyed_(task_destroyed),
1978 destruction_observer_called_(destruction_observer_called) {
1980 virtual void Run() {
1981 // This task should never run.
1982 ADD_FAILURE();
1984 private:
1985 friend class base::RefCounted<DestructionObserverProbe>;
1987 virtual ~DestructionObserverProbe() {
1988 EXPECT_FALSE(*destruction_observer_called_);
1989 *task_destroyed_ = true;
1992 bool* task_destroyed_;
1993 bool* destruction_observer_called_;
1996 class MLDestructionObserver : public MessageLoop::DestructionObserver {
1997 public:
1998 MLDestructionObserver(bool* task_destroyed, bool* destruction_observer_called)
1999 : task_destroyed_(task_destroyed),
2000 destruction_observer_called_(destruction_observer_called),
2001 task_destroyed_before_message_loop_(false) {
2003 virtual void WillDestroyCurrentMessageLoop() OVERRIDE {
2004 task_destroyed_before_message_loop_ = *task_destroyed_;
2005 *destruction_observer_called_ = true;
2007 bool task_destroyed_before_message_loop() const {
2008 return task_destroyed_before_message_loop_;
2010 private:
2011 bool* task_destroyed_;
2012 bool* destruction_observer_called_;
2013 bool task_destroyed_before_message_loop_;
2016 } // namespace
2018 TEST(MessageLoopTest, DestructionObserverTest) {
2019 // Verify that the destruction observer gets called at the very end (after
2020 // all the pending tasks have been destroyed).
2021 MessageLoop* loop = new MessageLoop;
2022 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
2024 bool task_destroyed = false;
2025 bool destruction_observer_called = false;
2027 MLDestructionObserver observer(&task_destroyed, &destruction_observer_called);
2028 loop->AddDestructionObserver(&observer);
2029 loop->PostDelayedTask(
2030 FROM_HERE,
2031 base::Bind(&DestructionObserverProbe::Run,
2032 new DestructionObserverProbe(&task_destroyed,
2033 &destruction_observer_called)),
2034 kDelay);
2035 delete loop;
2036 EXPECT_TRUE(observer.task_destroyed_before_message_loop());
2037 // The task should have been destroyed when we deleted the loop.
2038 EXPECT_TRUE(task_destroyed);
2039 EXPECT_TRUE(destruction_observer_called);
2043 // Verify that MessageLoop sets ThreadMainTaskRunner::current() and it
2044 // posts tasks on that message loop.
2045 TEST(MessageLoopTest, ThreadMainTaskRunner) {
2046 MessageLoop loop;
2048 scoped_refptr<Foo> foo(new Foo());
2049 std::string a("a");
2050 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(
2051 &Foo::Test1ConstRef, foo.get(), a));
2053 // Post quit task;
2054 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
2055 &MessageLoop::Quit, base::Unretained(MessageLoop::current())));
2057 // Now kick things off
2058 MessageLoop::current()->Run();
2060 EXPECT_EQ(foo->test_count(), 1);
2061 EXPECT_EQ(foo->result(), "a");
2064 TEST(MessageLoopTest, IsType) {
2065 MessageLoop loop(MessageLoop::TYPE_UI);
2066 EXPECT_TRUE(loop.IsType(MessageLoop::TYPE_UI));
2067 EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_IO));
2068 EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_DEFAULT));
2071 TEST(MessageLoopTest, RecursivePosts) {
2072 // There was a bug in the MessagePumpGLib where posting tasks recursively
2073 // caused the message loop to hang, due to the buffer of the internal pipe
2074 // becoming full. Test all MessageLoop types to ensure this issue does not
2075 // exist in other MessagePumps.
2077 // On Linux, the pipe buffer size is 64KiB by default. The bug caused one
2078 // byte accumulated in the pipe per two posts, so we should repeat 128K
2079 // times to reproduce the bug.
2080 const int kNumTimes = 1 << 17;
2081 RunTest_RecursivePosts(MessageLoop::TYPE_DEFAULT, kNumTimes);
2082 RunTest_RecursivePosts(MessageLoop::TYPE_UI, kNumTimes);
2083 RunTest_RecursivePosts(MessageLoop::TYPE_IO, kNumTimes);