Fix clang error caused by lack of OVERRIDE in r161270.
[chromium-blink-merge.git] / base / message_loop_unittest.cc
blob01fb1b3b2fd3b14a6c9ecd40a377fbd1b115a2f4
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/eintr_wrapper.h"
11 #include "base/logging.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/message_loop.h"
14 #include "base/run_loop.h"
15 #include "base/thread_task_runner_handle.h"
16 #include "base/threading/platform_thread.h"
17 #include "base/threading/thread.h"
18 #include "testing/gtest/include/gtest/gtest.h"
20 #if defined(OS_WIN)
21 #include "base/message_pump_win.h"
22 #include "base/win/scoped_handle.h"
23 #endif
25 using base::PlatformThread;
26 using base::Thread;
27 using base::Time;
28 using base::TimeDelta;
29 using base::TimeTicks;
31 // TODO(darin): Platform-specific MessageLoop tests should be grouped together
32 // to avoid chopping this file up with so many #ifdefs.
34 namespace {
36 class MessageLoopTest : public testing::Test {};
38 class Foo : public base::RefCounted<Foo> {
39 public:
40 Foo() : test_count_(0) {
43 void Test0() {
44 ++test_count_;
47 void Test1ConstRef(const std::string& a) {
48 ++test_count_;
49 result_.append(a);
52 void Test1Ptr(std::string* a) {
53 ++test_count_;
54 result_.append(*a);
57 void Test1Int(int a) {
58 test_count_ += a;
61 void Test2Ptr(std::string* a, std::string* b) {
62 ++test_count_;
63 result_.append(*a);
64 result_.append(*b);
67 void Test2Mixed(const std::string& a, std::string* b) {
68 ++test_count_;
69 result_.append(a);
70 result_.append(*b);
73 int test_count() const { return test_count_; }
74 const std::string& result() const { return result_; }
76 private:
77 friend class base::RefCounted<Foo>;
79 ~Foo() {}
81 int test_count_;
82 std::string result_;
85 void RunTest_PostTask(MessageLoop::Type message_loop_type) {
86 MessageLoop loop(message_loop_type);
88 // Add tests to message loop
89 scoped_refptr<Foo> foo(new Foo());
90 std::string a("a"), b("b"), c("c"), d("d");
91 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
92 &Foo::Test0, foo.get()));
93 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
94 &Foo::Test1ConstRef, foo.get(), a));
95 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
96 &Foo::Test1Ptr, foo.get(), &b));
97 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
98 &Foo::Test1Int, foo.get(), 100));
99 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
100 &Foo::Test2Ptr, foo.get(), &a, &c));
101 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
102 &Foo::Test2Mixed, foo.get(), a, &d));
104 // After all tests, post a message that will shut down the message loop
105 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
106 &MessageLoop::Quit, base::Unretained(MessageLoop::current())));
108 // Now kick things off
109 MessageLoop::current()->Run();
111 EXPECT_EQ(foo->test_count(), 105);
112 EXPECT_EQ(foo->result(), "abacad");
115 void RunTest_PostTask_SEH(MessageLoop::Type message_loop_type) {
116 MessageLoop loop(message_loop_type);
118 // Add tests to message loop
119 scoped_refptr<Foo> foo(new Foo());
120 std::string a("a"), b("b"), c("c"), d("d");
121 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
122 &Foo::Test0, foo.get()));
123 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
124 &Foo::Test1ConstRef, foo.get(), a));
125 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
126 &Foo::Test1Ptr, foo.get(), &b));
127 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
128 &Foo::Test1Int, foo.get(), 100));
129 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
130 &Foo::Test2Ptr, foo.get(), &a, &c));
131 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
132 &Foo::Test2Mixed, foo.get(), a, &d));
134 // After all tests, post a message that will shut down the message loop
135 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
136 &MessageLoop::Quit, base::Unretained(MessageLoop::current())));
138 // Now kick things off with the SEH block active.
139 MessageLoop::current()->set_exception_restoration(true);
140 MessageLoop::current()->Run();
141 MessageLoop::current()->set_exception_restoration(false);
143 EXPECT_EQ(foo->test_count(), 105);
144 EXPECT_EQ(foo->result(), "abacad");
147 // This function runs slowly to simulate a large amount of work being done.
148 static void SlowFunc(TimeDelta pause, int* quit_counter) {
149 PlatformThread::Sleep(pause);
150 if (--(*quit_counter) == 0)
151 MessageLoop::current()->Quit();
154 // This function records the time when Run was called in a Time object, which is
155 // useful for building a variety of MessageLoop tests.
156 static void RecordRunTimeFunc(Time* run_time, int* quit_counter) {
157 *run_time = Time::Now();
159 // Cause our Run function to take some time to execute. As a result we can
160 // count on subsequent RecordRunTimeFunc()s running at a future time,
161 // without worry about the resolution of our system clock being an issue.
162 SlowFunc(TimeDelta::FromMilliseconds(10), quit_counter);
165 void RunTest_PostDelayedTask_Basic(MessageLoop::Type message_loop_type) {
166 MessageLoop loop(message_loop_type);
168 // Test that PostDelayedTask results in a delayed task.
170 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
172 int num_tasks = 1;
173 Time run_time;
175 loop.PostDelayedTask(
176 FROM_HERE, base::Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
177 kDelay);
179 Time time_before_run = Time::Now();
180 loop.Run();
181 Time time_after_run = Time::Now();
183 EXPECT_EQ(0, num_tasks);
184 EXPECT_LT(kDelay, time_after_run - time_before_run);
187 void RunTest_PostDelayedTask_InDelayOrder(
188 MessageLoop::Type message_loop_type) {
189 MessageLoop loop(message_loop_type);
191 // Test that two tasks with different delays run in the right order.
192 int num_tasks = 2;
193 Time run_time1, run_time2;
195 loop.PostDelayedTask(
196 FROM_HERE,
197 base::Bind(&RecordRunTimeFunc, &run_time1, &num_tasks),
198 TimeDelta::FromMilliseconds(200));
199 // If we get a large pause in execution (due to a context switch) here, this
200 // test could fail.
201 loop.PostDelayedTask(
202 FROM_HERE,
203 base::Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
204 TimeDelta::FromMilliseconds(10));
206 loop.Run();
207 EXPECT_EQ(0, num_tasks);
209 EXPECT_TRUE(run_time2 < run_time1);
212 void RunTest_PostDelayedTask_InPostOrder(
213 MessageLoop::Type message_loop_type) {
214 MessageLoop loop(message_loop_type);
216 // Test that two tasks with the same delay run in the order in which they
217 // were posted.
219 // NOTE: This is actually an approximate test since the API only takes a
220 // "delay" parameter, so we are not exactly simulating two tasks that get
221 // posted at the exact same time. It would be nice if the API allowed us to
222 // specify the desired run time.
224 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
226 int num_tasks = 2;
227 Time run_time1, run_time2;
229 loop.PostDelayedTask(
230 FROM_HERE,
231 base::Bind(&RecordRunTimeFunc, &run_time1, &num_tasks), kDelay);
232 loop.PostDelayedTask(
233 FROM_HERE,
234 base::Bind(&RecordRunTimeFunc, &run_time2, &num_tasks), kDelay);
236 loop.Run();
237 EXPECT_EQ(0, num_tasks);
239 EXPECT_TRUE(run_time1 < run_time2);
242 void RunTest_PostDelayedTask_InPostOrder_2(
243 MessageLoop::Type message_loop_type) {
244 MessageLoop loop(message_loop_type);
246 // Test that a delayed task still runs after a normal tasks even if the
247 // normal tasks take a long time to run.
249 const TimeDelta kPause = TimeDelta::FromMilliseconds(50);
251 int num_tasks = 2;
252 Time run_time;
254 loop.PostTask(FROM_HERE, base::Bind(&SlowFunc, kPause, &num_tasks));
255 loop.PostDelayedTask(
256 FROM_HERE,
257 base::Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
258 TimeDelta::FromMilliseconds(10));
260 Time time_before_run = Time::Now();
261 loop.Run();
262 Time time_after_run = Time::Now();
264 EXPECT_EQ(0, num_tasks);
266 EXPECT_LT(kPause, time_after_run - time_before_run);
269 void RunTest_PostDelayedTask_InPostOrder_3(
270 MessageLoop::Type message_loop_type) {
271 MessageLoop loop(message_loop_type);
273 // Test that a delayed task still runs after a pile of normal tasks. The key
274 // difference between this test and the previous one is that here we return
275 // the MessageLoop a lot so we give the MessageLoop plenty of opportunities
276 // to maybe run the delayed task. It should know not to do so until the
277 // delayed task's delay has passed.
279 int num_tasks = 11;
280 Time run_time1, run_time2;
282 // Clutter the ML with tasks.
283 for (int i = 1; i < num_tasks; ++i)
284 loop.PostTask(FROM_HERE,
285 base::Bind(&RecordRunTimeFunc, &run_time1, &num_tasks));
287 loop.PostDelayedTask(
288 FROM_HERE, base::Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
289 TimeDelta::FromMilliseconds(1));
291 loop.Run();
292 EXPECT_EQ(0, num_tasks);
294 EXPECT_TRUE(run_time2 > run_time1);
297 void RunTest_PostDelayedTask_SharedTimer(
298 MessageLoop::Type message_loop_type) {
299 MessageLoop loop(message_loop_type);
301 // Test that the interval of the timer, used to run the next delayed task, is
302 // set to a value corresponding to when the next delayed task should run.
304 // By setting num_tasks to 1, we ensure that the first task to run causes the
305 // run loop to exit.
306 int num_tasks = 1;
307 Time run_time1, run_time2;
309 loop.PostDelayedTask(
310 FROM_HERE,
311 base::Bind(&RecordRunTimeFunc, &run_time1, &num_tasks),
312 TimeDelta::FromSeconds(1000));
313 loop.PostDelayedTask(
314 FROM_HERE,
315 base::Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
316 TimeDelta::FromMilliseconds(10));
318 Time start_time = Time::Now();
320 loop.Run();
321 EXPECT_EQ(0, num_tasks);
323 // Ensure that we ran in far less time than the slower timer.
324 TimeDelta total_time = Time::Now() - start_time;
325 EXPECT_GT(5000, total_time.InMilliseconds());
327 // In case both timers somehow run at nearly the same time, sleep a little
328 // and then run all pending to force them both to have run. This is just
329 // encouraging flakiness if there is any.
330 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
331 loop.RunAllPending();
333 EXPECT_TRUE(run_time1.is_null());
334 EXPECT_FALSE(run_time2.is_null());
337 #if defined(OS_WIN)
339 void SubPumpFunc() {
340 MessageLoop::current()->SetNestableTasksAllowed(true);
341 MSG msg;
342 while (GetMessage(&msg, NULL, 0, 0)) {
343 TranslateMessage(&msg);
344 DispatchMessage(&msg);
346 MessageLoop::current()->Quit();
349 void RunTest_PostDelayedTask_SharedTimer_SubPump() {
350 MessageLoop loop(MessageLoop::TYPE_UI);
352 // Test that the interval of the timer, used to run the next delayed task, is
353 // set to a value corresponding to when the next delayed task should run.
355 // By setting num_tasks to 1, we ensure that the first task to run causes the
356 // run loop to exit.
357 int num_tasks = 1;
358 Time run_time;
360 loop.PostTask(FROM_HERE, base::Bind(&SubPumpFunc));
362 // This very delayed task should never run.
363 loop.PostDelayedTask(
364 FROM_HERE,
365 base::Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
366 TimeDelta::FromSeconds(1000));
368 // This slightly delayed task should run from within SubPumpFunc).
369 loop.PostDelayedTask(
370 FROM_HERE,
371 base::Bind(&PostQuitMessage, 0),
372 TimeDelta::FromMilliseconds(10));
374 Time start_time = Time::Now();
376 loop.Run();
377 EXPECT_EQ(1, num_tasks);
379 // Ensure that we ran in far less time than the slower timer.
380 TimeDelta total_time = Time::Now() - start_time;
381 EXPECT_GT(5000, total_time.InMilliseconds());
383 // In case both timers somehow run at nearly the same time, sleep a little
384 // and then run all pending to force them both to have run. This is just
385 // encouraging flakiness if there is any.
386 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
387 loop.RunAllPending();
389 EXPECT_TRUE(run_time.is_null());
392 #endif // defined(OS_WIN)
394 // This is used to inject a test point for recording the destructor calls for
395 // Closure objects send to MessageLoop::PostTask(). It is awkward usage since we
396 // are trying to hook the actual destruction, which is not a common operation.
397 class RecordDeletionProbe : public base::RefCounted<RecordDeletionProbe> {
398 public:
399 RecordDeletionProbe(RecordDeletionProbe* post_on_delete, bool* was_deleted)
400 : post_on_delete_(post_on_delete), was_deleted_(was_deleted) {
402 void Run() {}
404 private:
405 friend class base::RefCounted<RecordDeletionProbe>;
407 ~RecordDeletionProbe() {
408 *was_deleted_ = true;
409 if (post_on_delete_)
410 MessageLoop::current()->PostTask(
411 FROM_HERE,
412 base::Bind(&RecordDeletionProbe::Run, post_on_delete_.get()));
415 scoped_refptr<RecordDeletionProbe> post_on_delete_;
416 bool* was_deleted_;
419 void RunTest_EnsureDeletion(MessageLoop::Type message_loop_type) {
420 bool a_was_deleted = false;
421 bool b_was_deleted = false;
423 MessageLoop loop(message_loop_type);
424 loop.PostTask(
425 FROM_HERE, base::Bind(&RecordDeletionProbe::Run,
426 new RecordDeletionProbe(NULL, &a_was_deleted)));
427 // TODO(ajwong): Do we really need 1000ms here?
428 loop.PostDelayedTask(
429 FROM_HERE, base::Bind(&RecordDeletionProbe::Run,
430 new RecordDeletionProbe(NULL, &b_was_deleted)),
431 TimeDelta::FromMilliseconds(1000));
433 EXPECT_TRUE(a_was_deleted);
434 EXPECT_TRUE(b_was_deleted);
437 void RunTest_EnsureDeletion_Chain(MessageLoop::Type message_loop_type) {
438 bool a_was_deleted = false;
439 bool b_was_deleted = false;
440 bool c_was_deleted = false;
442 MessageLoop loop(message_loop_type);
443 // The scoped_refptr for each of the below is held either by the chained
444 // RecordDeletionProbe, or the bound RecordDeletionProbe::Run() callback.
445 RecordDeletionProbe* a = new RecordDeletionProbe(NULL, &a_was_deleted);
446 RecordDeletionProbe* b = new RecordDeletionProbe(a, &b_was_deleted);
447 RecordDeletionProbe* c = new RecordDeletionProbe(b, &c_was_deleted);
448 loop.PostTask(FROM_HERE, base::Bind(&RecordDeletionProbe::Run, c));
450 EXPECT_TRUE(a_was_deleted);
451 EXPECT_TRUE(b_was_deleted);
452 EXPECT_TRUE(c_was_deleted);
455 void NestingFunc(int* depth) {
456 if (*depth > 0) {
457 *depth -= 1;
458 MessageLoop::current()->PostTask(FROM_HERE,
459 base::Bind(&NestingFunc, depth));
461 MessageLoop::current()->SetNestableTasksAllowed(true);
462 MessageLoop::current()->Run();
464 MessageLoop::current()->Quit();
467 #if defined(OS_WIN)
469 LONG WINAPI BadExceptionHandler(EXCEPTION_POINTERS *ex_info) {
470 ADD_FAILURE() << "bad exception handler";
471 ::ExitProcess(ex_info->ExceptionRecord->ExceptionCode);
472 return EXCEPTION_EXECUTE_HANDLER;
475 // This task throws an SEH exception: initially write to an invalid address.
476 // If the right SEH filter is installed, it will fix the error.
477 class Crasher : public base::RefCounted<Crasher> {
478 public:
479 // Ctor. If trash_SEH_handler is true, the task will override the unhandled
480 // exception handler with one sure to crash this test.
481 explicit Crasher(bool trash_SEH_handler)
482 : trash_SEH_handler_(trash_SEH_handler) {
485 void Run() {
486 PlatformThread::Sleep(TimeDelta::FromMilliseconds(1));
487 if (trash_SEH_handler_)
488 ::SetUnhandledExceptionFilter(&BadExceptionHandler);
489 // Generate a SEH fault. We do it in asm to make sure we know how to undo
490 // the damage.
492 #if defined(_M_IX86)
494 __asm {
495 mov eax, dword ptr [Crasher::bad_array_]
496 mov byte ptr [eax], 66
499 #elif defined(_M_X64)
501 bad_array_[0] = 66;
503 #else
504 #error "needs architecture support"
505 #endif
507 MessageLoop::current()->Quit();
509 // Points the bad array to a valid memory location.
510 static void FixError() {
511 bad_array_ = &valid_store_;
514 private:
515 bool trash_SEH_handler_;
516 static volatile char* bad_array_;
517 static char valid_store_;
520 volatile char* Crasher::bad_array_ = 0;
521 char Crasher::valid_store_ = 0;
523 // This SEH filter fixes the problem and retries execution. Fixing requires
524 // that the last instruction: mov eax, [Crasher::bad_array_] to be retried
525 // so we move the instruction pointer 5 bytes back.
526 LONG WINAPI HandleCrasherException(EXCEPTION_POINTERS *ex_info) {
527 if (ex_info->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION)
528 return EXCEPTION_EXECUTE_HANDLER;
530 Crasher::FixError();
532 #if defined(_M_IX86)
534 ex_info->ContextRecord->Eip -= 5;
536 #elif defined(_M_X64)
538 ex_info->ContextRecord->Rip -= 5;
540 #endif
542 return EXCEPTION_CONTINUE_EXECUTION;
545 void RunTest_Crasher(MessageLoop::Type message_loop_type) {
546 MessageLoop loop(message_loop_type);
548 if (::IsDebuggerPresent())
549 return;
551 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter =
552 ::SetUnhandledExceptionFilter(&HandleCrasherException);
554 MessageLoop::current()->PostTask(
555 FROM_HERE,
556 base::Bind(&Crasher::Run, new Crasher(false)));
557 MessageLoop::current()->set_exception_restoration(true);
558 MessageLoop::current()->Run();
559 MessageLoop::current()->set_exception_restoration(false);
561 ::SetUnhandledExceptionFilter(old_SEH_filter);
564 void RunTest_CrasherNasty(MessageLoop::Type message_loop_type) {
565 MessageLoop loop(message_loop_type);
567 if (::IsDebuggerPresent())
568 return;
570 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter =
571 ::SetUnhandledExceptionFilter(&HandleCrasherException);
573 MessageLoop::current()->PostTask(
574 FROM_HERE,
575 base::Bind(&Crasher::Run, new Crasher(true)));
576 MessageLoop::current()->set_exception_restoration(true);
577 MessageLoop::current()->Run();
578 MessageLoop::current()->set_exception_restoration(false);
580 ::SetUnhandledExceptionFilter(old_SEH_filter);
583 #endif // defined(OS_WIN)
585 void RunTest_Nesting(MessageLoop::Type message_loop_type) {
586 MessageLoop loop(message_loop_type);
588 int depth = 100;
589 MessageLoop::current()->PostTask(FROM_HERE,
590 base::Bind(&NestingFunc, &depth));
591 MessageLoop::current()->Run();
592 EXPECT_EQ(depth, 0);
595 const wchar_t* const kMessageBoxTitle = L"MessageLoop Unit Test";
597 enum TaskType {
598 MESSAGEBOX,
599 ENDDIALOG,
600 RECURSIVE,
601 TIMEDMESSAGELOOP,
602 QUITMESSAGELOOP,
603 ORDERED,
604 PUMPS,
605 SLEEP,
606 RUNS,
609 // Saves the order in which the tasks executed.
610 struct TaskItem {
611 TaskItem(TaskType t, int c, bool s)
612 : type(t),
613 cookie(c),
614 start(s) {
617 TaskType type;
618 int cookie;
619 bool start;
621 bool operator == (const TaskItem& other) const {
622 return type == other.type && cookie == other.cookie && start == other.start;
626 std::ostream& operator <<(std::ostream& os, TaskType type) {
627 switch (type) {
628 case MESSAGEBOX: os << "MESSAGEBOX"; break;
629 case ENDDIALOG: os << "ENDDIALOG"; break;
630 case RECURSIVE: os << "RECURSIVE"; break;
631 case TIMEDMESSAGELOOP: os << "TIMEDMESSAGELOOP"; break;
632 case QUITMESSAGELOOP: os << "QUITMESSAGELOOP"; break;
633 case ORDERED: os << "ORDERED"; break;
634 case PUMPS: os << "PUMPS"; break;
635 case SLEEP: os << "SLEEP"; break;
636 default:
637 NOTREACHED();
638 os << "Unknown TaskType";
639 break;
641 return os;
644 std::ostream& operator <<(std::ostream& os, const TaskItem& item) {
645 if (item.start)
646 return os << item.type << " " << item.cookie << " starts";
647 else
648 return os << item.type << " " << item.cookie << " ends";
651 class TaskList {
652 public:
653 void RecordStart(TaskType type, int cookie) {
654 TaskItem item(type, cookie, true);
655 DVLOG(1) << item;
656 task_list_.push_back(item);
659 void RecordEnd(TaskType type, int cookie) {
660 TaskItem item(type, cookie, false);
661 DVLOG(1) << item;
662 task_list_.push_back(item);
665 size_t Size() {
666 return task_list_.size();
669 TaskItem Get(int n) {
670 return task_list_[n];
673 private:
674 std::vector<TaskItem> task_list_;
677 // Saves the order the tasks ran.
678 void OrderedFunc(TaskList* order, int cookie) {
679 order->RecordStart(ORDERED, cookie);
680 order->RecordEnd(ORDERED, cookie);
683 #if defined(OS_WIN)
685 // MessageLoop implicitly start a "modal message loop". Modal dialog boxes,
686 // common controls (like OpenFile) and StartDoc printing function can cause
687 // implicit message loops.
688 void MessageBoxFunc(TaskList* order, int cookie, bool is_reentrant) {
689 order->RecordStart(MESSAGEBOX, cookie);
690 if (is_reentrant)
691 MessageLoop::current()->SetNestableTasksAllowed(true);
692 MessageBox(NULL, L"Please wait...", kMessageBoxTitle, MB_OK);
693 order->RecordEnd(MESSAGEBOX, cookie);
696 // Will end the MessageBox.
697 void EndDialogFunc(TaskList* order, int cookie) {
698 order->RecordStart(ENDDIALOG, cookie);
699 HWND window = GetActiveWindow();
700 if (window != NULL) {
701 EXPECT_NE(EndDialog(window, IDCONTINUE), 0);
702 // Cheap way to signal that the window wasn't found if RunEnd() isn't
703 // called.
704 order->RecordEnd(ENDDIALOG, cookie);
708 #endif // defined(OS_WIN)
710 void RecursiveFunc(TaskList* order, int cookie, int depth,
711 bool is_reentrant) {
712 order->RecordStart(RECURSIVE, cookie);
713 if (depth > 0) {
714 if (is_reentrant)
715 MessageLoop::current()->SetNestableTasksAllowed(true);
716 MessageLoop::current()->PostTask(
717 FROM_HERE,
718 base::Bind(&RecursiveFunc, order, cookie, depth - 1, is_reentrant));
720 order->RecordEnd(RECURSIVE, cookie);
723 void RecursiveSlowFunc(TaskList* order, int cookie, int depth,
724 bool is_reentrant) {
725 RecursiveFunc(order, cookie, depth, is_reentrant);
726 PlatformThread::Sleep(TimeDelta::FromMilliseconds(10));
729 void QuitFunc(TaskList* order, int cookie) {
730 order->RecordStart(QUITMESSAGELOOP, cookie);
731 MessageLoop::current()->Quit();
732 order->RecordEnd(QUITMESSAGELOOP, cookie);
735 void SleepFunc(TaskList* order, int cookie, TimeDelta delay) {
736 order->RecordStart(SLEEP, cookie);
737 PlatformThread::Sleep(delay);
738 order->RecordEnd(SLEEP, cookie);
741 #if defined(OS_WIN)
742 void RecursiveFuncWin(MessageLoop* target,
743 HANDLE event,
744 bool expect_window,
745 TaskList* order,
746 bool is_reentrant) {
747 target->PostTask(FROM_HERE,
748 base::Bind(&RecursiveFunc, order, 1, 2, is_reentrant));
749 target->PostTask(FROM_HERE,
750 base::Bind(&MessageBoxFunc, order, 2, is_reentrant));
751 target->PostTask(FROM_HERE,
752 base::Bind(&RecursiveFunc, order, 3, 2, is_reentrant));
753 // The trick here is that for recursive task processing, this task will be
754 // ran _inside_ the MessageBox message loop, dismissing the MessageBox
755 // without a chance.
756 // For non-recursive task processing, this will be executed _after_ the
757 // MessageBox will have been dismissed by the code below, where
758 // expect_window_ is true.
759 target->PostTask(FROM_HERE,
760 base::Bind(&EndDialogFunc, order, 4));
761 target->PostTask(FROM_HERE,
762 base::Bind(&QuitFunc, order, 5));
764 // Enforce that every tasks are sent before starting to run the main thread
765 // message loop.
766 ASSERT_TRUE(SetEvent(event));
768 // Poll for the MessageBox. Don't do this at home! At the speed we do it,
769 // you will never realize one MessageBox was shown.
770 for (; expect_window;) {
771 HWND window = FindWindow(L"#32770", kMessageBoxTitle);
772 if (window) {
773 // Dismiss it.
774 for (;;) {
775 HWND button = FindWindowEx(window, NULL, L"Button", NULL);
776 if (button != NULL) {
777 EXPECT_EQ(0, SendMessage(button, WM_LBUTTONDOWN, 0, 0));
778 EXPECT_EQ(0, SendMessage(button, WM_LBUTTONUP, 0, 0));
779 break;
782 break;
787 #endif // defined(OS_WIN)
789 void RunTest_RecursiveDenial1(MessageLoop::Type message_loop_type) {
790 MessageLoop loop(message_loop_type);
792 EXPECT_TRUE(MessageLoop::current()->NestableTasksAllowed());
793 TaskList order;
794 MessageLoop::current()->PostTask(
795 FROM_HERE,
796 base::Bind(&RecursiveFunc, &order, 1, 2, false));
797 MessageLoop::current()->PostTask(
798 FROM_HERE,
799 base::Bind(&RecursiveFunc, &order, 2, 2, false));
800 MessageLoop::current()->PostTask(
801 FROM_HERE,
802 base::Bind(&QuitFunc, &order, 3));
804 MessageLoop::current()->Run();
806 // FIFO order.
807 ASSERT_EQ(14U, order.Size());
808 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
809 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
810 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
811 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
812 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
813 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
814 EXPECT_EQ(order.Get(6), TaskItem(RECURSIVE, 1, true));
815 EXPECT_EQ(order.Get(7), TaskItem(RECURSIVE, 1, false));
816 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
817 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
818 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
819 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
820 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 2, true));
821 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 2, false));
824 void RunTest_RecursiveDenial3(MessageLoop::Type message_loop_type) {
825 MessageLoop loop(message_loop_type);
827 EXPECT_TRUE(MessageLoop::current()->NestableTasksAllowed());
828 TaskList order;
829 MessageLoop::current()->PostTask(
830 FROM_HERE, base::Bind(&RecursiveSlowFunc, &order, 1, 2, false));
831 MessageLoop::current()->PostTask(
832 FROM_HERE, base::Bind(&RecursiveSlowFunc, &order, 2, 2, false));
833 MessageLoop::current()->PostDelayedTask(
834 FROM_HERE,
835 base::Bind(&OrderedFunc, &order, 3),
836 TimeDelta::FromMilliseconds(5));
837 MessageLoop::current()->PostDelayedTask(
838 FROM_HERE,
839 base::Bind(&QuitFunc, &order, 4),
840 TimeDelta::FromMilliseconds(5));
842 MessageLoop::current()->Run();
844 // FIFO order.
845 ASSERT_EQ(16U, order.Size());
846 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
847 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
848 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
849 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
850 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 1, true));
851 EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 1, false));
852 EXPECT_EQ(order.Get(6), TaskItem(ORDERED, 3, true));
853 EXPECT_EQ(order.Get(7), TaskItem(ORDERED, 3, false));
854 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
855 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
856 EXPECT_EQ(order.Get(10), TaskItem(QUITMESSAGELOOP, 4, true));
857 EXPECT_EQ(order.Get(11), TaskItem(QUITMESSAGELOOP, 4, false));
858 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 1, true));
859 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, false));
860 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 2, true));
861 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 2, false));
864 void RunTest_RecursiveSupport1(MessageLoop::Type message_loop_type) {
865 MessageLoop loop(message_loop_type);
867 TaskList order;
868 MessageLoop::current()->PostTask(
869 FROM_HERE, base::Bind(&RecursiveFunc, &order, 1, 2, true));
870 MessageLoop::current()->PostTask(
871 FROM_HERE, base::Bind(&RecursiveFunc, &order, 2, 2, true));
872 MessageLoop::current()->PostTask(
873 FROM_HERE, base::Bind(&QuitFunc, &order, 3));
875 MessageLoop::current()->Run();
877 // FIFO order.
878 ASSERT_EQ(14U, order.Size());
879 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
880 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
881 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
882 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
883 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
884 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
885 EXPECT_EQ(order.Get(6), TaskItem(RECURSIVE, 1, true));
886 EXPECT_EQ(order.Get(7), TaskItem(RECURSIVE, 1, false));
887 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
888 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
889 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
890 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
891 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 2, true));
892 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 2, false));
895 #if defined(OS_WIN)
896 // TODO(darin): These tests need to be ported since they test critical
897 // message loop functionality.
899 // A side effect of this test is the generation a beep. Sorry.
900 void RunTest_RecursiveDenial2(MessageLoop::Type message_loop_type) {
901 MessageLoop loop(message_loop_type);
903 Thread worker("RecursiveDenial2_worker");
904 Thread::Options options;
905 options.message_loop_type = message_loop_type;
906 ASSERT_EQ(true, worker.StartWithOptions(options));
907 TaskList order;
908 base::win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
909 worker.message_loop()->PostTask(FROM_HERE,
910 base::Bind(&RecursiveFuncWin,
911 MessageLoop::current(),
912 event.Get(),
913 true,
914 &order,
915 false));
916 // Let the other thread execute.
917 WaitForSingleObject(event, INFINITE);
918 MessageLoop::current()->Run();
920 ASSERT_EQ(order.Size(), 17);
921 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
922 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
923 EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
924 EXPECT_EQ(order.Get(3), TaskItem(MESSAGEBOX, 2, false));
925 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, true));
926 EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 3, false));
927 // When EndDialogFunc is processed, the window is already dismissed, hence no
928 // "end" entry.
929 EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, true));
930 EXPECT_EQ(order.Get(7), TaskItem(QUITMESSAGELOOP, 5, true));
931 EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, false));
932 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 1, true));
933 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, false));
934 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 3, true));
935 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, false));
936 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, true));
937 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, false));
938 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 3, true));
939 EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, false));
942 // A side effect of this test is the generation a beep. Sorry. This test also
943 // needs to process windows messages on the current thread.
944 void RunTest_RecursiveSupport2(MessageLoop::Type message_loop_type) {
945 MessageLoop loop(message_loop_type);
947 Thread worker("RecursiveSupport2_worker");
948 Thread::Options options;
949 options.message_loop_type = message_loop_type;
950 ASSERT_EQ(true, worker.StartWithOptions(options));
951 TaskList order;
952 base::win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
953 worker.message_loop()->PostTask(FROM_HERE,
954 base::Bind(&RecursiveFuncWin,
955 MessageLoop::current(),
956 event.Get(),
957 false,
958 &order,
959 true));
960 // Let the other thread execute.
961 WaitForSingleObject(event, INFINITE);
962 MessageLoop::current()->Run();
964 ASSERT_EQ(order.Size(), 18);
965 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
966 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
967 EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
968 // Note that this executes in the MessageBox modal loop.
969 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 3, true));
970 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, false));
971 EXPECT_EQ(order.Get(5), TaskItem(ENDDIALOG, 4, true));
972 EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, false));
973 EXPECT_EQ(order.Get(7), TaskItem(MESSAGEBOX, 2, false));
974 /* The order can subtly change here. The reason is that when RecursiveFunc(1)
975 is called in the main thread, if it is faster than getting to the
976 PostTask(FROM_HERE, base::Bind(&QuitFunc) execution, the order of task
977 execution can change. We don't care anyway that the order isn't correct.
978 EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, true));
979 EXPECT_EQ(order.Get(9), TaskItem(QUITMESSAGELOOP, 5, false));
980 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
981 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
983 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, true));
984 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 3, false));
985 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, true));
986 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 1, false));
987 EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, true));
988 EXPECT_EQ(order.Get(17), TaskItem(RECURSIVE, 3, false));
991 #endif // defined(OS_WIN)
993 void FuncThatPumps(TaskList* order, int cookie) {
994 order->RecordStart(PUMPS, cookie);
996 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
997 MessageLoop::current()->RunAllPending();
999 order->RecordEnd(PUMPS, cookie);
1002 void FuncThatRuns(TaskList* order, int cookie, base::RunLoop* run_loop) {
1003 order->RecordStart(RUNS, cookie);
1005 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
1006 run_loop->Run();
1008 order->RecordEnd(RUNS, cookie);
1011 void FuncThatQuitsNow() {
1012 MessageLoop::current()->QuitNow();
1015 // Tests that non nestable tasks run in FIFO if there are no nested loops.
1016 void RunTest_NonNestableWithNoNesting(
1017 MessageLoop::Type message_loop_type) {
1018 MessageLoop loop(message_loop_type);
1020 TaskList order;
1022 MessageLoop::current()->PostNonNestableTask(
1023 FROM_HERE,
1024 base::Bind(&OrderedFunc, &order, 1));
1025 MessageLoop::current()->PostTask(FROM_HERE,
1026 base::Bind(&OrderedFunc, &order, 2));
1027 MessageLoop::current()->PostTask(FROM_HERE,
1028 base::Bind(&QuitFunc, &order, 3));
1029 MessageLoop::current()->Run();
1031 // FIFO order.
1032 ASSERT_EQ(6U, order.Size());
1033 EXPECT_EQ(order.Get(0), TaskItem(ORDERED, 1, true));
1034 EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 1, false));
1035 EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 2, true));
1036 EXPECT_EQ(order.Get(3), TaskItem(ORDERED, 2, false));
1037 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
1038 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
1041 // Tests that non nestable tasks don't run when there's code in the call stack.
1042 void RunTest_NonNestableInNestedLoop(MessageLoop::Type message_loop_type,
1043 bool use_delayed) {
1044 MessageLoop loop(message_loop_type);
1046 TaskList order;
1048 MessageLoop::current()->PostTask(
1049 FROM_HERE,
1050 base::Bind(&FuncThatPumps, &order, 1));
1051 if (use_delayed) {
1052 MessageLoop::current()->PostNonNestableDelayedTask(
1053 FROM_HERE,
1054 base::Bind(&OrderedFunc, &order, 2),
1055 TimeDelta::FromMilliseconds(1));
1056 } else {
1057 MessageLoop::current()->PostNonNestableTask(
1058 FROM_HERE,
1059 base::Bind(&OrderedFunc, &order, 2));
1061 MessageLoop::current()->PostTask(FROM_HERE,
1062 base::Bind(&OrderedFunc, &order, 3));
1063 MessageLoop::current()->PostTask(
1064 FROM_HERE,
1065 base::Bind(&SleepFunc, &order, 4, TimeDelta::FromMilliseconds(50)));
1066 MessageLoop::current()->PostTask(FROM_HERE,
1067 base::Bind(&OrderedFunc, &order, 5));
1068 if (use_delayed) {
1069 MessageLoop::current()->PostNonNestableDelayedTask(
1070 FROM_HERE,
1071 base::Bind(&QuitFunc, &order, 6),
1072 TimeDelta::FromMilliseconds(2));
1073 } else {
1074 MessageLoop::current()->PostNonNestableTask(
1075 FROM_HERE,
1076 base::Bind(&QuitFunc, &order, 6));
1079 MessageLoop::current()->Run();
1081 // FIFO order.
1082 ASSERT_EQ(12U, order.Size());
1083 EXPECT_EQ(order.Get(0), TaskItem(PUMPS, 1, true));
1084 EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 3, true));
1085 EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 3, false));
1086 EXPECT_EQ(order.Get(3), TaskItem(SLEEP, 4, true));
1087 EXPECT_EQ(order.Get(4), TaskItem(SLEEP, 4, false));
1088 EXPECT_EQ(order.Get(5), TaskItem(ORDERED, 5, true));
1089 EXPECT_EQ(order.Get(6), TaskItem(ORDERED, 5, false));
1090 EXPECT_EQ(order.Get(7), TaskItem(PUMPS, 1, false));
1091 EXPECT_EQ(order.Get(8), TaskItem(ORDERED, 2, true));
1092 EXPECT_EQ(order.Get(9), TaskItem(ORDERED, 2, false));
1093 EXPECT_EQ(order.Get(10), TaskItem(QUITMESSAGELOOP, 6, true));
1094 EXPECT_EQ(order.Get(11), TaskItem(QUITMESSAGELOOP, 6, false));
1097 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1098 void RunTest_QuitNow(MessageLoop::Type message_loop_type) {
1099 MessageLoop loop(message_loop_type);
1101 TaskList order;
1103 base::RunLoop run_loop;
1105 MessageLoop::current()->PostTask(FROM_HERE,
1106 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&run_loop)));
1107 MessageLoop::current()->PostTask(
1108 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1109 MessageLoop::current()->PostTask(
1110 FROM_HERE, base::Bind(&FuncThatQuitsNow));
1111 MessageLoop::current()->PostTask(
1112 FROM_HERE, base::Bind(&OrderedFunc, &order, 3));
1113 MessageLoop::current()->PostTask(
1114 FROM_HERE, base::Bind(&FuncThatQuitsNow));
1115 MessageLoop::current()->PostTask(
1116 FROM_HERE, base::Bind(&OrderedFunc, &order, 4)); // never runs
1118 MessageLoop::current()->Run();
1120 ASSERT_EQ(6U, order.Size());
1121 int task_index = 0;
1122 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1123 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1124 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1125 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1126 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
1127 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
1128 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1131 // Tests RunLoopQuit works before RunWithID.
1132 void RunTest_RunLoopQuitOrderBefore(MessageLoop::Type message_loop_type) {
1133 MessageLoop loop(message_loop_type);
1135 TaskList order;
1137 base::RunLoop run_loop;
1139 run_loop.Quit();
1141 MessageLoop::current()->PostTask(
1142 FROM_HERE, base::Bind(&OrderedFunc, &order, 1)); // never runs
1143 MessageLoop::current()->PostTask(
1144 FROM_HERE, base::Bind(&FuncThatQuitsNow)); // never runs
1146 run_loop.Run();
1148 ASSERT_EQ(0U, order.Size());
1151 // Tests RunLoopQuit works during RunWithID.
1152 void RunTest_RunLoopQuitOrderDuring(MessageLoop::Type message_loop_type) {
1153 MessageLoop loop(message_loop_type);
1155 TaskList order;
1157 base::RunLoop run_loop;
1159 MessageLoop::current()->PostTask(
1160 FROM_HERE, base::Bind(&OrderedFunc, &order, 1));
1161 MessageLoop::current()->PostTask(
1162 FROM_HERE, run_loop.QuitClosure());
1163 MessageLoop::current()->PostTask(
1164 FROM_HERE, base::Bind(&OrderedFunc, &order, 2)); // never runs
1165 MessageLoop::current()->PostTask(
1166 FROM_HERE, base::Bind(&FuncThatQuitsNow)); // never runs
1168 run_loop.Run();
1170 ASSERT_EQ(2U, order.Size());
1171 int task_index = 0;
1172 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, true));
1173 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, false));
1174 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1177 // Tests RunLoopQuit works after RunWithID.
1178 void RunTest_RunLoopQuitOrderAfter(MessageLoop::Type message_loop_type) {
1179 MessageLoop loop(message_loop_type);
1181 TaskList order;
1183 base::RunLoop run_loop;
1185 MessageLoop::current()->PostTask(FROM_HERE,
1186 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&run_loop)));
1187 MessageLoop::current()->PostTask(
1188 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1189 MessageLoop::current()->PostTask(
1190 FROM_HERE, base::Bind(&FuncThatQuitsNow));
1191 MessageLoop::current()->PostTask(
1192 FROM_HERE, base::Bind(&OrderedFunc, &order, 3));
1193 MessageLoop::current()->PostTask(
1194 FROM_HERE, run_loop.QuitClosure()); // has no affect
1195 MessageLoop::current()->PostTask(
1196 FROM_HERE, base::Bind(&OrderedFunc, &order, 4));
1197 MessageLoop::current()->PostTask(
1198 FROM_HERE, base::Bind(&FuncThatQuitsNow));
1200 base::RunLoop outer_run_loop;
1201 outer_run_loop.Run();
1203 ASSERT_EQ(8U, order.Size());
1204 int task_index = 0;
1205 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1206 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1207 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1208 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1209 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
1210 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
1211 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, true));
1212 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, false));
1213 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1216 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1217 void RunTest_RunLoopQuitTop(MessageLoop::Type message_loop_type) {
1218 MessageLoop loop(message_loop_type);
1220 TaskList order;
1222 base::RunLoop outer_run_loop;
1223 base::RunLoop nested_run_loop;
1225 MessageLoop::current()->PostTask(FROM_HERE,
1226 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&nested_run_loop)));
1227 MessageLoop::current()->PostTask(
1228 FROM_HERE, outer_run_loop.QuitClosure());
1229 MessageLoop::current()->PostTask(
1230 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1231 MessageLoop::current()->PostTask(
1232 FROM_HERE, nested_run_loop.QuitClosure());
1234 outer_run_loop.Run();
1236 ASSERT_EQ(4U, order.Size());
1237 int task_index = 0;
1238 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1239 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1240 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1241 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1242 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1245 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1246 void RunTest_RunLoopQuitNested(MessageLoop::Type message_loop_type) {
1247 MessageLoop loop(message_loop_type);
1249 TaskList order;
1251 base::RunLoop outer_run_loop;
1252 base::RunLoop nested_run_loop;
1254 MessageLoop::current()->PostTask(FROM_HERE,
1255 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&nested_run_loop)));
1256 MessageLoop::current()->PostTask(
1257 FROM_HERE, nested_run_loop.QuitClosure());
1258 MessageLoop::current()->PostTask(
1259 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1260 MessageLoop::current()->PostTask(
1261 FROM_HERE, outer_run_loop.QuitClosure());
1263 outer_run_loop.Run();
1265 ASSERT_EQ(4U, order.Size());
1266 int task_index = 0;
1267 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1268 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1269 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1270 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1271 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1274 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1275 void RunTest_RunLoopQuitBogus(MessageLoop::Type message_loop_type) {
1276 MessageLoop loop(message_loop_type);
1278 TaskList order;
1280 base::RunLoop outer_run_loop;
1281 base::RunLoop nested_run_loop;
1282 base::RunLoop bogus_run_loop;
1284 MessageLoop::current()->PostTask(FROM_HERE,
1285 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&nested_run_loop)));
1286 MessageLoop::current()->PostTask(
1287 FROM_HERE, bogus_run_loop.QuitClosure());
1288 MessageLoop::current()->PostTask(
1289 FROM_HERE, base::Bind(&OrderedFunc, &order, 2));
1290 MessageLoop::current()->PostTask(
1291 FROM_HERE, outer_run_loop.QuitClosure());
1292 MessageLoop::current()->PostTask(
1293 FROM_HERE, nested_run_loop.QuitClosure());
1295 outer_run_loop.Run();
1297 ASSERT_EQ(4U, order.Size());
1298 int task_index = 0;
1299 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1300 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1301 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1302 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1303 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1306 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1307 void RunTest_RunLoopQuitDeep(MessageLoop::Type message_loop_type) {
1308 MessageLoop loop(message_loop_type);
1310 TaskList order;
1312 base::RunLoop outer_run_loop;
1313 base::RunLoop nested_loop1;
1314 base::RunLoop nested_loop2;
1315 base::RunLoop nested_loop3;
1316 base::RunLoop nested_loop4;
1318 MessageLoop::current()->PostTask(FROM_HERE,
1319 base::Bind(&FuncThatRuns, &order, 1, base::Unretained(&nested_loop1)));
1320 MessageLoop::current()->PostTask(FROM_HERE,
1321 base::Bind(&FuncThatRuns, &order, 2, base::Unretained(&nested_loop2)));
1322 MessageLoop::current()->PostTask(FROM_HERE,
1323 base::Bind(&FuncThatRuns, &order, 3, base::Unretained(&nested_loop3)));
1324 MessageLoop::current()->PostTask(FROM_HERE,
1325 base::Bind(&FuncThatRuns, &order, 4, base::Unretained(&nested_loop4)));
1326 MessageLoop::current()->PostTask(
1327 FROM_HERE, base::Bind(&OrderedFunc, &order, 5));
1328 MessageLoop::current()->PostTask(
1329 FROM_HERE, outer_run_loop.QuitClosure());
1330 MessageLoop::current()->PostTask(
1331 FROM_HERE, base::Bind(&OrderedFunc, &order, 6));
1332 MessageLoop::current()->PostTask(
1333 FROM_HERE, nested_loop1.QuitClosure());
1334 MessageLoop::current()->PostTask(
1335 FROM_HERE, base::Bind(&OrderedFunc, &order, 7));
1336 MessageLoop::current()->PostTask(
1337 FROM_HERE, nested_loop2.QuitClosure());
1338 MessageLoop::current()->PostTask(
1339 FROM_HERE, base::Bind(&OrderedFunc, &order, 8));
1340 MessageLoop::current()->PostTask(
1341 FROM_HERE, nested_loop3.QuitClosure());
1342 MessageLoop::current()->PostTask(
1343 FROM_HERE, base::Bind(&OrderedFunc, &order, 9));
1344 MessageLoop::current()->PostTask(
1345 FROM_HERE, nested_loop4.QuitClosure());
1346 MessageLoop::current()->PostTask(
1347 FROM_HERE, base::Bind(&OrderedFunc, &order, 10));
1349 outer_run_loop.Run();
1351 ASSERT_EQ(18U, order.Size());
1352 int task_index = 0;
1353 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1354 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, true));
1355 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, true));
1356 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, true));
1357 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, true));
1358 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, false));
1359 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, true));
1360 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, false));
1361 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, true));
1362 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, false));
1363 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, true));
1364 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, false));
1365 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, true));
1366 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, false));
1367 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, false));
1368 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, false));
1369 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, false));
1370 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1371 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1374 #if defined(OS_WIN)
1376 class DispatcherImpl : public MessageLoopForUI::Dispatcher {
1377 public:
1378 DispatcherImpl() : dispatch_count_(0) {}
1380 virtual bool Dispatch(const base::NativeEvent& msg) OVERRIDE {
1381 ::TranslateMessage(&msg);
1382 ::DispatchMessage(&msg);
1383 // Do not count WM_TIMER since it is not what we post and it will cause
1384 // flakiness.
1385 if (msg.message != WM_TIMER)
1386 ++dispatch_count_;
1387 // We treat WM_LBUTTONUP as the last message.
1388 return msg.message != WM_LBUTTONUP;
1391 int dispatch_count_;
1394 void MouseDownUp() {
1395 PostMessage(NULL, WM_LBUTTONDOWN, 0, 0);
1396 PostMessage(NULL, WM_LBUTTONUP, 'A', 0);
1399 void RunTest_Dispatcher(MessageLoop::Type message_loop_type) {
1400 MessageLoop loop(message_loop_type);
1402 MessageLoop::current()->PostDelayedTask(
1403 FROM_HERE,
1404 base::Bind(&MouseDownUp),
1405 TimeDelta::FromMilliseconds(100));
1406 DispatcherImpl dispatcher;
1407 base::RunLoop run_loop(&dispatcher);
1408 run_loop.Run();
1409 ASSERT_EQ(2, dispatcher.dispatch_count_);
1412 LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) {
1413 if (code == base::MessagePumpForUI::kMessageFilterCode) {
1414 MSG* msg = reinterpret_cast<MSG*>(lparam);
1415 if (msg->message == WM_LBUTTONDOWN)
1416 return TRUE;
1418 return FALSE;
1421 void RunTest_DispatcherWithMessageHook(MessageLoop::Type message_loop_type) {
1422 MessageLoop loop(message_loop_type);
1424 MessageLoop::current()->PostDelayedTask(
1425 FROM_HERE,
1426 base::Bind(&MouseDownUp),
1427 TimeDelta::FromMilliseconds(100));
1428 HHOOK msg_hook = SetWindowsHookEx(WH_MSGFILTER,
1429 MsgFilterProc,
1430 NULL,
1431 GetCurrentThreadId());
1432 DispatcherImpl dispatcher;
1433 base::RunLoop run_loop(&dispatcher);
1434 run_loop.Run();
1435 ASSERT_EQ(1, dispatcher.dispatch_count_);
1436 UnhookWindowsHookEx(msg_hook);
1439 class TestIOHandler : public MessageLoopForIO::IOHandler {
1440 public:
1441 TestIOHandler(const wchar_t* name, HANDLE signal, bool wait);
1443 virtual void OnIOCompleted(MessageLoopForIO::IOContext* context,
1444 DWORD bytes_transfered, DWORD error);
1446 void Init();
1447 void WaitForIO();
1448 OVERLAPPED* context() { return &context_.overlapped; }
1449 DWORD size() { return sizeof(buffer_); }
1451 private:
1452 char buffer_[48];
1453 MessageLoopForIO::IOContext context_;
1454 HANDLE signal_;
1455 base::win::ScopedHandle file_;
1456 bool wait_;
1459 TestIOHandler::TestIOHandler(const wchar_t* name, HANDLE signal, bool wait)
1460 : signal_(signal), wait_(wait) {
1461 memset(buffer_, 0, sizeof(buffer_));
1462 memset(&context_, 0, sizeof(context_));
1463 context_.handler = this;
1465 file_.Set(CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING,
1466 FILE_FLAG_OVERLAPPED, NULL));
1467 EXPECT_TRUE(file_.IsValid());
1470 void TestIOHandler::Init() {
1471 MessageLoopForIO::current()->RegisterIOHandler(file_, this);
1473 DWORD read;
1474 EXPECT_FALSE(ReadFile(file_, buffer_, size(), &read, context()));
1475 EXPECT_EQ(ERROR_IO_PENDING, GetLastError());
1476 if (wait_)
1477 WaitForIO();
1480 void TestIOHandler::OnIOCompleted(MessageLoopForIO::IOContext* context,
1481 DWORD bytes_transfered, DWORD error) {
1482 ASSERT_TRUE(context == &context_);
1483 ASSERT_TRUE(SetEvent(signal_));
1486 void TestIOHandler::WaitForIO() {
1487 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(300, this));
1488 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(400, this));
1491 void RunTest_IOHandler() {
1492 base::win::ScopedHandle callback_called(CreateEvent(NULL, TRUE, FALSE, NULL));
1493 ASSERT_TRUE(callback_called.IsValid());
1495 const wchar_t* kPipeName = L"\\\\.\\pipe\\iohandler_pipe";
1496 base::win::ScopedHandle server(
1497 CreateNamedPipe(kPipeName, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1498 ASSERT_TRUE(server.IsValid());
1500 Thread thread("IOHandler test");
1501 Thread::Options options;
1502 options.message_loop_type = MessageLoop::TYPE_IO;
1503 ASSERT_TRUE(thread.StartWithOptions(options));
1505 MessageLoop* thread_loop = thread.message_loop();
1506 ASSERT_TRUE(NULL != thread_loop);
1508 TestIOHandler handler(kPipeName, callback_called, false);
1509 thread_loop->PostTask(FROM_HERE, base::Bind(&TestIOHandler::Init,
1510 base::Unretained(&handler)));
1511 // Make sure the thread runs and sleeps for lack of work.
1512 base::PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
1514 const char buffer[] = "Hello there!";
1515 DWORD written;
1516 EXPECT_TRUE(WriteFile(server, buffer, sizeof(buffer), &written, NULL));
1518 DWORD result = WaitForSingleObject(callback_called, 1000);
1519 EXPECT_EQ(WAIT_OBJECT_0, result);
1521 thread.Stop();
1524 void RunTest_WaitForIO() {
1525 base::win::ScopedHandle callback1_called(
1526 CreateEvent(NULL, TRUE, FALSE, NULL));
1527 base::win::ScopedHandle callback2_called(
1528 CreateEvent(NULL, TRUE, FALSE, NULL));
1529 ASSERT_TRUE(callback1_called.IsValid());
1530 ASSERT_TRUE(callback2_called.IsValid());
1532 const wchar_t* kPipeName1 = L"\\\\.\\pipe\\iohandler_pipe1";
1533 const wchar_t* kPipeName2 = L"\\\\.\\pipe\\iohandler_pipe2";
1534 base::win::ScopedHandle server1(
1535 CreateNamedPipe(kPipeName1, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1536 base::win::ScopedHandle server2(
1537 CreateNamedPipe(kPipeName2, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1538 ASSERT_TRUE(server1.IsValid());
1539 ASSERT_TRUE(server2.IsValid());
1541 Thread thread("IOHandler test");
1542 Thread::Options options;
1543 options.message_loop_type = MessageLoop::TYPE_IO;
1544 ASSERT_TRUE(thread.StartWithOptions(options));
1546 MessageLoop* thread_loop = thread.message_loop();
1547 ASSERT_TRUE(NULL != thread_loop);
1549 TestIOHandler handler1(kPipeName1, callback1_called, false);
1550 TestIOHandler handler2(kPipeName2, callback2_called, true);
1551 thread_loop->PostTask(FROM_HERE, base::Bind(&TestIOHandler::Init,
1552 base::Unretained(&handler1)));
1553 // TODO(ajwong): Do we really need such long Sleeps in ths function?
1554 // Make sure the thread runs and sleeps for lack of work.
1555 TimeDelta delay = TimeDelta::FromMilliseconds(100);
1556 base::PlatformThread::Sleep(delay);
1557 thread_loop->PostTask(FROM_HERE, base::Bind(&TestIOHandler::Init,
1558 base::Unretained(&handler2)));
1559 base::PlatformThread::Sleep(delay);
1561 // At this time handler1 is waiting to be called, and the thread is waiting
1562 // on the Init method of handler2, filtering only handler2 callbacks.
1564 const char buffer[] = "Hello there!";
1565 DWORD written;
1566 EXPECT_TRUE(WriteFile(server1, buffer, sizeof(buffer), &written, NULL));
1567 base::PlatformThread::Sleep(2 * delay);
1568 EXPECT_EQ(WAIT_TIMEOUT, WaitForSingleObject(callback1_called, 0)) <<
1569 "handler1 has not been called";
1571 EXPECT_TRUE(WriteFile(server2, buffer, sizeof(buffer), &written, NULL));
1573 HANDLE objects[2] = { callback1_called.Get(), callback2_called.Get() };
1574 DWORD result = WaitForMultipleObjects(2, objects, TRUE, 1000);
1575 EXPECT_EQ(WAIT_OBJECT_0, result);
1577 thread.Stop();
1580 #endif // defined(OS_WIN)
1582 } // namespace
1584 //-----------------------------------------------------------------------------
1585 // Each test is run against each type of MessageLoop. That way we are sure
1586 // that message loops work properly in all configurations. Of course, in some
1587 // cases, a unit test may only be for a particular type of loop.
1589 TEST(MessageLoopTest, PostTask) {
1590 RunTest_PostTask(MessageLoop::TYPE_DEFAULT);
1591 RunTest_PostTask(MessageLoop::TYPE_UI);
1592 RunTest_PostTask(MessageLoop::TYPE_IO);
1595 TEST(MessageLoopTest, PostTask_SEH) {
1596 RunTest_PostTask_SEH(MessageLoop::TYPE_DEFAULT);
1597 RunTest_PostTask_SEH(MessageLoop::TYPE_UI);
1598 RunTest_PostTask_SEH(MessageLoop::TYPE_IO);
1601 TEST(MessageLoopTest, PostDelayedTask_Basic) {
1602 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_DEFAULT);
1603 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_UI);
1604 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_IO);
1607 TEST(MessageLoopTest, PostDelayedTask_InDelayOrder) {
1608 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_DEFAULT);
1609 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_UI);
1610 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_IO);
1613 TEST(MessageLoopTest, PostDelayedTask_InPostOrder) {
1614 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_DEFAULT);
1615 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_UI);
1616 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_IO);
1619 TEST(MessageLoopTest, PostDelayedTask_InPostOrder_2) {
1620 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_DEFAULT);
1621 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_UI);
1622 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_IO);
1625 TEST(MessageLoopTest, PostDelayedTask_InPostOrder_3) {
1626 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_DEFAULT);
1627 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_UI);
1628 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_IO);
1631 TEST(MessageLoopTest, PostDelayedTask_SharedTimer) {
1632 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_DEFAULT);
1633 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_UI);
1634 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_IO);
1637 #if defined(OS_WIN)
1638 TEST(MessageLoopTest, PostDelayedTask_SharedTimer_SubPump) {
1639 RunTest_PostDelayedTask_SharedTimer_SubPump();
1641 #endif
1643 // TODO(darin): MessageLoop does not support deleting all tasks in the
1644 // destructor.
1645 // Fails, http://crbug.com/50272.
1646 TEST(MessageLoopTest, FAILS_EnsureDeletion) {
1647 RunTest_EnsureDeletion(MessageLoop::TYPE_DEFAULT);
1648 RunTest_EnsureDeletion(MessageLoop::TYPE_UI);
1649 RunTest_EnsureDeletion(MessageLoop::TYPE_IO);
1652 // TODO(darin): MessageLoop does not support deleting all tasks in the
1653 // destructor.
1654 // Fails, http://crbug.com/50272.
1655 TEST(MessageLoopTest, FAILS_EnsureDeletion_Chain) {
1656 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_DEFAULT);
1657 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_UI);
1658 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_IO);
1661 #if defined(OS_WIN)
1662 TEST(MessageLoopTest, Crasher) {
1663 RunTest_Crasher(MessageLoop::TYPE_DEFAULT);
1664 RunTest_Crasher(MessageLoop::TYPE_UI);
1665 RunTest_Crasher(MessageLoop::TYPE_IO);
1668 TEST(MessageLoopTest, CrasherNasty) {
1669 RunTest_CrasherNasty(MessageLoop::TYPE_DEFAULT);
1670 RunTest_CrasherNasty(MessageLoop::TYPE_UI);
1671 RunTest_CrasherNasty(MessageLoop::TYPE_IO);
1673 #endif // defined(OS_WIN)
1675 TEST(MessageLoopTest, Nesting) {
1676 RunTest_Nesting(MessageLoop::TYPE_DEFAULT);
1677 RunTest_Nesting(MessageLoop::TYPE_UI);
1678 RunTest_Nesting(MessageLoop::TYPE_IO);
1681 TEST(MessageLoopTest, RecursiveDenial1) {
1682 RunTest_RecursiveDenial1(MessageLoop::TYPE_DEFAULT);
1683 RunTest_RecursiveDenial1(MessageLoop::TYPE_UI);
1684 RunTest_RecursiveDenial1(MessageLoop::TYPE_IO);
1687 TEST(MessageLoopTest, RecursiveDenial3) {
1688 RunTest_RecursiveDenial3(MessageLoop::TYPE_DEFAULT);
1689 RunTest_RecursiveDenial3(MessageLoop::TYPE_UI);
1690 RunTest_RecursiveDenial3(MessageLoop::TYPE_IO);
1693 TEST(MessageLoopTest, RecursiveSupport1) {
1694 RunTest_RecursiveSupport1(MessageLoop::TYPE_DEFAULT);
1695 RunTest_RecursiveSupport1(MessageLoop::TYPE_UI);
1696 RunTest_RecursiveSupport1(MessageLoop::TYPE_IO);
1699 #if defined(OS_WIN)
1700 // This test occasionally hangs http://crbug.com/44567
1701 TEST(MessageLoopTest, DISABLED_RecursiveDenial2) {
1702 RunTest_RecursiveDenial2(MessageLoop::TYPE_DEFAULT);
1703 RunTest_RecursiveDenial2(MessageLoop::TYPE_UI);
1704 RunTest_RecursiveDenial2(MessageLoop::TYPE_IO);
1707 TEST(MessageLoopTest, RecursiveSupport2) {
1708 // This test requires a UI loop
1709 RunTest_RecursiveSupport2(MessageLoop::TYPE_UI);
1711 #endif // defined(OS_WIN)
1713 TEST(MessageLoopTest, NonNestableWithNoNesting) {
1714 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_DEFAULT);
1715 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_UI);
1716 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_IO);
1719 TEST(MessageLoopTest, NonNestableInNestedLoop) {
1720 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT, false);
1721 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI, false);
1722 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO, false);
1725 TEST(MessageLoopTest, NonNestableDelayedInNestedLoop) {
1726 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT, true);
1727 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI, true);
1728 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO, true);
1731 TEST(MessageLoopTest, QuitNow) {
1732 RunTest_QuitNow(MessageLoop::TYPE_DEFAULT);
1733 RunTest_QuitNow(MessageLoop::TYPE_UI);
1734 RunTest_QuitNow(MessageLoop::TYPE_IO);
1737 TEST(MessageLoopTest, RunLoopQuitTop) {
1738 RunTest_RunLoopQuitTop(MessageLoop::TYPE_DEFAULT);
1739 RunTest_RunLoopQuitTop(MessageLoop::TYPE_UI);
1740 RunTest_RunLoopQuitTop(MessageLoop::TYPE_IO);
1743 TEST(MessageLoopTest, RunLoopQuitNested) {
1744 RunTest_RunLoopQuitNested(MessageLoop::TYPE_DEFAULT);
1745 RunTest_RunLoopQuitNested(MessageLoop::TYPE_UI);
1746 RunTest_RunLoopQuitNested(MessageLoop::TYPE_IO);
1749 TEST(MessageLoopTest, RunLoopQuitBogus) {
1750 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_DEFAULT);
1751 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_UI);
1752 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_IO);
1755 TEST(MessageLoopTest, RunLoopQuitDeep) {
1756 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_DEFAULT);
1757 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_UI);
1758 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_IO);
1761 TEST(MessageLoopTest, RunLoopQuitOrderBefore) {
1762 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_DEFAULT);
1763 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_UI);
1764 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_IO);
1767 TEST(MessageLoopTest, RunLoopQuitOrderDuring) {
1768 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_DEFAULT);
1769 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_UI);
1770 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_IO);
1773 TEST(MessageLoopTest, RunLoopQuitOrderAfter) {
1774 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_DEFAULT);
1775 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_UI);
1776 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_IO);
1779 void PostNTasksThenQuit(int posts_remaining) {
1780 if (posts_remaining > 1) {
1781 MessageLoop::current()->PostTask(
1782 FROM_HERE,
1783 base::Bind(&PostNTasksThenQuit, posts_remaining - 1));
1784 } else {
1785 MessageLoop::current()->Quit();
1789 class DummyTaskObserver : public MessageLoop::TaskObserver {
1790 public:
1791 explicit DummyTaskObserver(int num_tasks)
1792 : num_tasks_started_(0),
1793 num_tasks_processed_(0),
1794 num_tasks_(num_tasks) {}
1796 virtual ~DummyTaskObserver() {}
1798 virtual void WillProcessTask(TimeTicks time_posted) OVERRIDE {
1799 num_tasks_started_++;
1800 EXPECT_TRUE(time_posted != TimeTicks());
1801 EXPECT_LE(num_tasks_started_, num_tasks_);
1802 EXPECT_EQ(num_tasks_started_, num_tasks_processed_ + 1);
1805 virtual void DidProcessTask(TimeTicks time_posted) OVERRIDE {
1806 num_tasks_processed_++;
1807 EXPECT_TRUE(time_posted != TimeTicks());
1808 EXPECT_LE(num_tasks_started_, num_tasks_);
1809 EXPECT_EQ(num_tasks_started_, num_tasks_processed_);
1812 int num_tasks_started() const { return num_tasks_started_; }
1813 int num_tasks_processed() const { return num_tasks_processed_; }
1815 private:
1816 int num_tasks_started_;
1817 int num_tasks_processed_;
1818 const int num_tasks_;
1820 DISALLOW_COPY_AND_ASSIGN(DummyTaskObserver);
1823 TEST(MessageLoopTest, TaskObserver) {
1824 const int kNumPosts = 6;
1825 DummyTaskObserver observer(kNumPosts);
1827 MessageLoop loop;
1828 loop.AddTaskObserver(&observer);
1829 loop.PostTask(FROM_HERE, base::Bind(&PostNTasksThenQuit, kNumPosts));
1830 loop.Run();
1831 loop.RemoveTaskObserver(&observer);
1833 EXPECT_EQ(kNumPosts, observer.num_tasks_started());
1834 EXPECT_EQ(kNumPosts, observer.num_tasks_processed());
1837 #if defined(OS_WIN)
1838 TEST(MessageLoopTest, Dispatcher) {
1839 // This test requires a UI loop
1840 RunTest_Dispatcher(MessageLoop::TYPE_UI);
1843 TEST(MessageLoopTest, DispatcherWithMessageHook) {
1844 // This test requires a UI loop
1845 RunTest_DispatcherWithMessageHook(MessageLoop::TYPE_UI);
1848 TEST(MessageLoopTest, IOHandler) {
1849 RunTest_IOHandler();
1852 TEST(MessageLoopTest, WaitForIO) {
1853 RunTest_WaitForIO();
1856 TEST(MessageLoopTest, HighResolutionTimer) {
1857 MessageLoop loop;
1859 const TimeDelta kFastTimer = TimeDelta::FromMilliseconds(5);
1860 const TimeDelta kSlowTimer = TimeDelta::FromMilliseconds(100);
1862 EXPECT_FALSE(loop.high_resolution_timers_enabled());
1864 // Post a fast task to enable the high resolution timers.
1865 loop.PostDelayedTask(FROM_HERE, base::Bind(&PostNTasksThenQuit, 1),
1866 kFastTimer);
1867 loop.Run();
1868 EXPECT_TRUE(loop.high_resolution_timers_enabled());
1870 // Post a slow task and verify high resolution timers
1871 // are still enabled.
1872 loop.PostDelayedTask(FROM_HERE, base::Bind(&PostNTasksThenQuit, 1),
1873 kSlowTimer);
1874 loop.Run();
1875 EXPECT_TRUE(loop.high_resolution_timers_enabled());
1877 // Wait for a while so that high-resolution mode elapses.
1878 base::PlatformThread::Sleep(TimeDelta::FromMilliseconds(
1879 MessageLoop::kHighResolutionTimerModeLeaseTimeMs));
1881 // Post a slow task to disable the high resolution timers.
1882 loop.PostDelayedTask(FROM_HERE, base::Bind(&PostNTasksThenQuit, 1),
1883 kSlowTimer);
1884 loop.Run();
1885 EXPECT_FALSE(loop.high_resolution_timers_enabled());
1888 #endif // defined(OS_WIN)
1890 #if defined(OS_POSIX) && !defined(OS_NACL)
1892 namespace {
1894 class QuitDelegate : public MessageLoopForIO::Watcher {
1895 public:
1896 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
1897 MessageLoop::current()->Quit();
1899 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE {
1900 MessageLoop::current()->Quit();
1904 TEST(MessageLoopTest, FileDescriptorWatcherOutlivesMessageLoop) {
1905 // Simulate a MessageLoop that dies before an FileDescriptorWatcher.
1906 // This could happen when people use the Singleton pattern or atexit.
1908 // Create a file descriptor. Doesn't need to be readable or writable,
1909 // as we don't need to actually get any notifications.
1910 // pipe() is just the easiest way to do it.
1911 int pipefds[2];
1912 int err = pipe(pipefds);
1913 ASSERT_EQ(0, err);
1914 int fd = pipefds[1];
1916 // Arrange for controller to live longer than message loop.
1917 MessageLoopForIO::FileDescriptorWatcher controller;
1919 MessageLoopForIO message_loop;
1921 QuitDelegate delegate;
1922 message_loop.WatchFileDescriptor(fd,
1923 true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate);
1924 // and don't run the message loop, just destroy it.
1927 if (HANDLE_EINTR(close(pipefds[0])) < 0)
1928 PLOG(ERROR) << "close";
1929 if (HANDLE_EINTR(close(pipefds[1])) < 0)
1930 PLOG(ERROR) << "close";
1933 TEST(MessageLoopTest, FileDescriptorWatcherDoubleStop) {
1934 // Verify that it's ok to call StopWatchingFileDescriptor().
1935 // (Errors only showed up in valgrind.)
1936 int pipefds[2];
1937 int err = pipe(pipefds);
1938 ASSERT_EQ(0, err);
1939 int fd = pipefds[1];
1941 // Arrange for message loop to live longer than controller.
1942 MessageLoopForIO message_loop;
1944 MessageLoopForIO::FileDescriptorWatcher controller;
1946 QuitDelegate delegate;
1947 message_loop.WatchFileDescriptor(fd,
1948 true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate);
1949 controller.StopWatchingFileDescriptor();
1952 if (HANDLE_EINTR(close(pipefds[0])) < 0)
1953 PLOG(ERROR) << "close";
1954 if (HANDLE_EINTR(close(pipefds[1])) < 0)
1955 PLOG(ERROR) << "close";
1958 } // namespace
1960 #endif // defined(OS_POSIX) && !defined(OS_NACL)
1962 namespace {
1963 // Inject a test point for recording the destructor calls for Closure objects
1964 // send to MessageLoop::PostTask(). It is awkward usage since we are trying to
1965 // hook the actual destruction, which is not a common operation.
1966 class DestructionObserverProbe :
1967 public base::RefCounted<DestructionObserverProbe> {
1968 public:
1969 DestructionObserverProbe(bool* task_destroyed,
1970 bool* destruction_observer_called)
1971 : task_destroyed_(task_destroyed),
1972 destruction_observer_called_(destruction_observer_called) {
1974 virtual void Run() {
1975 // This task should never run.
1976 ADD_FAILURE();
1978 private:
1979 friend class base::RefCounted<DestructionObserverProbe>;
1981 virtual ~DestructionObserverProbe() {
1982 EXPECT_FALSE(*destruction_observer_called_);
1983 *task_destroyed_ = true;
1986 bool* task_destroyed_;
1987 bool* destruction_observer_called_;
1990 class MLDestructionObserver : public MessageLoop::DestructionObserver {
1991 public:
1992 MLDestructionObserver(bool* task_destroyed, bool* destruction_observer_called)
1993 : task_destroyed_(task_destroyed),
1994 destruction_observer_called_(destruction_observer_called),
1995 task_destroyed_before_message_loop_(false) {
1997 virtual void WillDestroyCurrentMessageLoop() OVERRIDE {
1998 task_destroyed_before_message_loop_ = *task_destroyed_;
1999 *destruction_observer_called_ = true;
2001 bool task_destroyed_before_message_loop() const {
2002 return task_destroyed_before_message_loop_;
2004 private:
2005 bool* task_destroyed_;
2006 bool* destruction_observer_called_;
2007 bool task_destroyed_before_message_loop_;
2010 } // namespace
2012 TEST(MessageLoopTest, DestructionObserverTest) {
2013 // Verify that the destruction observer gets called at the very end (after
2014 // all the pending tasks have been destroyed).
2015 MessageLoop* loop = new MessageLoop;
2016 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
2018 bool task_destroyed = false;
2019 bool destruction_observer_called = false;
2021 MLDestructionObserver observer(&task_destroyed, &destruction_observer_called);
2022 loop->AddDestructionObserver(&observer);
2023 loop->PostDelayedTask(
2024 FROM_HERE,
2025 base::Bind(&DestructionObserverProbe::Run,
2026 new DestructionObserverProbe(&task_destroyed,
2027 &destruction_observer_called)),
2028 kDelay);
2029 delete loop;
2030 EXPECT_TRUE(observer.task_destroyed_before_message_loop());
2031 // The task should have been destroyed when we deleted the loop.
2032 EXPECT_TRUE(task_destroyed);
2033 EXPECT_TRUE(destruction_observer_called);
2037 // Verify that MessageLoop sets ThreadMainTaskRunner::current() and it
2038 // posts tasks on that message loop.
2039 TEST(MessageLoopTest, ThreadMainTaskRunner) {
2040 MessageLoop loop;
2042 scoped_refptr<Foo> foo(new Foo());
2043 std::string a("a");
2044 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(
2045 &Foo::Test1ConstRef, foo.get(), a));
2047 // Post quit task;
2048 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
2049 &MessageLoop::Quit, base::Unretained(MessageLoop::current())));
2051 // Now kick things off
2052 MessageLoop::current()->Run();
2054 EXPECT_EQ(foo->test_count(), 1);
2055 EXPECT_EQ(foo->result(), "a");
2058 TEST(MessageLoopTest, IsType) {
2059 MessageLoop loop(MessageLoop::TYPE_UI);
2060 EXPECT_TRUE(loop.IsType(MessageLoop::TYPE_UI));
2061 EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_IO));
2062 EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_DEFAULT));