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.
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/posix/eintr_wrapper.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"
21 #include "base/message_pump_win.h"
22 #include "base/win/scoped_handle.h"
25 using base::PlatformThread
;
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.
36 class Foo
: public base::RefCounted
<Foo
> {
38 Foo() : test_count_(0) {
45 void Test1ConstRef(const std::string
& a
) {
50 void Test1Ptr(std::string
* a
) {
55 void Test1Int(int a
) {
59 void Test2Ptr(std::string
* a
, std::string
* b
) {
65 void Test2Mixed(const std::string
& a
, std::string
* b
) {
71 int test_count() const { return test_count_
; }
72 const std::string
& result() const { return result_
; }
75 friend class base::RefCounted
<Foo
>;
83 void RunTest_PostTask(MessageLoop::Type message_loop_type
) {
84 MessageLoop
loop(message_loop_type
);
86 // Add tests to message loop
87 scoped_refptr
<Foo
> foo(new Foo());
88 std::string
a("a"), b("b"), c("c"), d("d");
89 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
90 &Foo::Test0
, foo
.get()));
91 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
92 &Foo::Test1ConstRef
, foo
.get(), a
));
93 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
94 &Foo::Test1Ptr
, foo
.get(), &b
));
95 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
96 &Foo::Test1Int
, foo
.get(), 100));
97 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
98 &Foo::Test2Ptr
, foo
.get(), &a
, &c
));
99 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
100 &Foo::Test2Mixed
, foo
.get(), a
, &d
));
102 // After all tests, post a message that will shut down the message loop
103 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
104 &MessageLoop::Quit
, base::Unretained(MessageLoop::current())));
106 // Now kick things off
107 MessageLoop::current()->Run();
109 EXPECT_EQ(foo
->test_count(), 105);
110 EXPECT_EQ(foo
->result(), "abacad");
113 void RunTest_PostTask_SEH(MessageLoop::Type message_loop_type
) {
114 MessageLoop
loop(message_loop_type
);
116 // Add tests to message loop
117 scoped_refptr
<Foo
> foo(new Foo());
118 std::string
a("a"), b("b"), c("c"), d("d");
119 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
120 &Foo::Test0
, foo
.get()));
121 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
122 &Foo::Test1ConstRef
, foo
.get(), a
));
123 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
124 &Foo::Test1Ptr
, foo
.get(), &b
));
125 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
126 &Foo::Test1Int
, foo
.get(), 100));
127 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
128 &Foo::Test2Ptr
, foo
.get(), &a
, &c
));
129 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
130 &Foo::Test2Mixed
, foo
.get(), a
, &d
));
132 // After all tests, post a message that will shut down the message loop
133 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
134 &MessageLoop::Quit
, base::Unretained(MessageLoop::current())));
136 // Now kick things off with the SEH block active.
137 MessageLoop::current()->set_exception_restoration(true);
138 MessageLoop::current()->Run();
139 MessageLoop::current()->set_exception_restoration(false);
141 EXPECT_EQ(foo
->test_count(), 105);
142 EXPECT_EQ(foo
->result(), "abacad");
145 // This function runs slowly to simulate a large amount of work being done.
146 static void SlowFunc(TimeDelta pause
, int* quit_counter
) {
147 PlatformThread::Sleep(pause
);
148 if (--(*quit_counter
) == 0)
149 MessageLoop::current()->Quit();
152 // This function records the time when Run was called in a Time object, which is
153 // useful for building a variety of MessageLoop tests.
154 static void RecordRunTimeFunc(Time
* run_time
, int* quit_counter
) {
155 *run_time
= Time::Now();
157 // Cause our Run function to take some time to execute. As a result we can
158 // count on subsequent RecordRunTimeFunc()s running at a future time,
159 // without worry about the resolution of our system clock being an issue.
160 SlowFunc(TimeDelta::FromMilliseconds(10), quit_counter
);
163 void RunTest_PostDelayedTask_Basic(MessageLoop::Type message_loop_type
) {
164 MessageLoop
loop(message_loop_type
);
166 // Test that PostDelayedTask results in a delayed task.
168 const TimeDelta kDelay
= TimeDelta::FromMilliseconds(100);
173 loop
.PostDelayedTask(
174 FROM_HERE
, base::Bind(&RecordRunTimeFunc
, &run_time
, &num_tasks
),
177 Time time_before_run
= Time::Now();
179 Time time_after_run
= Time::Now();
181 EXPECT_EQ(0, num_tasks
);
182 EXPECT_LT(kDelay
, time_after_run
- time_before_run
);
185 void RunTest_PostDelayedTask_InDelayOrder(
186 MessageLoop::Type message_loop_type
) {
187 MessageLoop
loop(message_loop_type
);
189 // Test that two tasks with different delays run in the right order.
191 Time run_time1
, run_time2
;
193 loop
.PostDelayedTask(
195 base::Bind(&RecordRunTimeFunc
, &run_time1
, &num_tasks
),
196 TimeDelta::FromMilliseconds(200));
197 // If we get a large pause in execution (due to a context switch) here, this
199 loop
.PostDelayedTask(
201 base::Bind(&RecordRunTimeFunc
, &run_time2
, &num_tasks
),
202 TimeDelta::FromMilliseconds(10));
205 EXPECT_EQ(0, num_tasks
);
207 EXPECT_TRUE(run_time2
< run_time1
);
210 void RunTest_PostDelayedTask_InPostOrder(
211 MessageLoop::Type message_loop_type
) {
212 MessageLoop
loop(message_loop_type
);
214 // Test that two tasks with the same delay run in the order in which they
217 // NOTE: This is actually an approximate test since the API only takes a
218 // "delay" parameter, so we are not exactly simulating two tasks that get
219 // posted at the exact same time. It would be nice if the API allowed us to
220 // specify the desired run time.
222 const TimeDelta kDelay
= TimeDelta::FromMilliseconds(100);
225 Time run_time1
, run_time2
;
227 loop
.PostDelayedTask(
229 base::Bind(&RecordRunTimeFunc
, &run_time1
, &num_tasks
), kDelay
);
230 loop
.PostDelayedTask(
232 base::Bind(&RecordRunTimeFunc
, &run_time2
, &num_tasks
), kDelay
);
235 EXPECT_EQ(0, num_tasks
);
237 EXPECT_TRUE(run_time1
< run_time2
);
240 void RunTest_PostDelayedTask_InPostOrder_2(
241 MessageLoop::Type message_loop_type
) {
242 MessageLoop
loop(message_loop_type
);
244 // Test that a delayed task still runs after a normal tasks even if the
245 // normal tasks take a long time to run.
247 const TimeDelta kPause
= TimeDelta::FromMilliseconds(50);
252 loop
.PostTask(FROM_HERE
, base::Bind(&SlowFunc
, kPause
, &num_tasks
));
253 loop
.PostDelayedTask(
255 base::Bind(&RecordRunTimeFunc
, &run_time
, &num_tasks
),
256 TimeDelta::FromMilliseconds(10));
258 Time time_before_run
= Time::Now();
260 Time time_after_run
= Time::Now();
262 EXPECT_EQ(0, num_tasks
);
264 EXPECT_LT(kPause
, time_after_run
- time_before_run
);
267 void RunTest_PostDelayedTask_InPostOrder_3(
268 MessageLoop::Type message_loop_type
) {
269 MessageLoop
loop(message_loop_type
);
271 // Test that a delayed task still runs after a pile of normal tasks. The key
272 // difference between this test and the previous one is that here we return
273 // the MessageLoop a lot so we give the MessageLoop plenty of opportunities
274 // to maybe run the delayed task. It should know not to do so until the
275 // delayed task's delay has passed.
278 Time run_time1
, run_time2
;
280 // Clutter the ML with tasks.
281 for (int i
= 1; i
< num_tasks
; ++i
)
282 loop
.PostTask(FROM_HERE
,
283 base::Bind(&RecordRunTimeFunc
, &run_time1
, &num_tasks
));
285 loop
.PostDelayedTask(
286 FROM_HERE
, base::Bind(&RecordRunTimeFunc
, &run_time2
, &num_tasks
),
287 TimeDelta::FromMilliseconds(1));
290 EXPECT_EQ(0, num_tasks
);
292 EXPECT_TRUE(run_time2
> run_time1
);
295 void RunTest_PostDelayedTask_SharedTimer(
296 MessageLoop::Type message_loop_type
) {
297 MessageLoop
loop(message_loop_type
);
299 // Test that the interval of the timer, used to run the next delayed task, is
300 // set to a value corresponding to when the next delayed task should run.
302 // By setting num_tasks to 1, we ensure that the first task to run causes the
305 Time run_time1
, run_time2
;
307 loop
.PostDelayedTask(
309 base::Bind(&RecordRunTimeFunc
, &run_time1
, &num_tasks
),
310 TimeDelta::FromSeconds(1000));
311 loop
.PostDelayedTask(
313 base::Bind(&RecordRunTimeFunc
, &run_time2
, &num_tasks
),
314 TimeDelta::FromMilliseconds(10));
316 Time start_time
= Time::Now();
319 EXPECT_EQ(0, num_tasks
);
321 // Ensure that we ran in far less time than the slower timer.
322 TimeDelta total_time
= Time::Now() - start_time
;
323 EXPECT_GT(5000, total_time
.InMilliseconds());
325 // In case both timers somehow run at nearly the same time, sleep a little
326 // and then run all pending to force them both to have run. This is just
327 // encouraging flakiness if there is any.
328 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
331 EXPECT_TRUE(run_time1
.is_null());
332 EXPECT_FALSE(run_time2
.is_null());
338 MessageLoop::current()->SetNestableTasksAllowed(true);
340 while (GetMessage(&msg
, NULL
, 0, 0)) {
341 TranslateMessage(&msg
);
342 DispatchMessage(&msg
);
344 MessageLoop::current()->Quit();
347 void RunTest_PostDelayedTask_SharedTimer_SubPump() {
348 MessageLoop
loop(MessageLoop::TYPE_UI
);
350 // Test that the interval of the timer, used to run the next delayed task, is
351 // set to a value corresponding to when the next delayed task should run.
353 // By setting num_tasks to 1, we ensure that the first task to run causes the
358 loop
.PostTask(FROM_HERE
, base::Bind(&SubPumpFunc
));
360 // This very delayed task should never run.
361 loop
.PostDelayedTask(
363 base::Bind(&RecordRunTimeFunc
, &run_time
, &num_tasks
),
364 TimeDelta::FromSeconds(1000));
366 // This slightly delayed task should run from within SubPumpFunc).
367 loop
.PostDelayedTask(
369 base::Bind(&PostQuitMessage
, 0),
370 TimeDelta::FromMilliseconds(10));
372 Time start_time
= Time::Now();
375 EXPECT_EQ(1, num_tasks
);
377 // Ensure that we ran in far less time than the slower timer.
378 TimeDelta total_time
= Time::Now() - start_time
;
379 EXPECT_GT(5000, total_time
.InMilliseconds());
381 // In case both timers somehow run at nearly the same time, sleep a little
382 // and then run all pending to force them both to have run. This is just
383 // encouraging flakiness if there is any.
384 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
387 EXPECT_TRUE(run_time
.is_null());
390 #endif // defined(OS_WIN)
392 // This is used to inject a test point for recording the destructor calls for
393 // Closure objects send to MessageLoop::PostTask(). It is awkward usage since we
394 // are trying to hook the actual destruction, which is not a common operation.
395 class RecordDeletionProbe
: public base::RefCounted
<RecordDeletionProbe
> {
397 RecordDeletionProbe(RecordDeletionProbe
* post_on_delete
, bool* was_deleted
)
398 : post_on_delete_(post_on_delete
), was_deleted_(was_deleted
) {
403 friend class base::RefCounted
<RecordDeletionProbe
>;
405 ~RecordDeletionProbe() {
406 *was_deleted_
= true;
408 MessageLoop::current()->PostTask(
410 base::Bind(&RecordDeletionProbe::Run
, post_on_delete_
.get()));
413 scoped_refptr
<RecordDeletionProbe
> post_on_delete_
;
417 void RunTest_EnsureDeletion(MessageLoop::Type message_loop_type
) {
418 bool a_was_deleted
= false;
419 bool b_was_deleted
= false;
421 MessageLoop
loop(message_loop_type
);
423 FROM_HERE
, base::Bind(&RecordDeletionProbe::Run
,
424 new RecordDeletionProbe(NULL
, &a_was_deleted
)));
425 // TODO(ajwong): Do we really need 1000ms here?
426 loop
.PostDelayedTask(
427 FROM_HERE
, base::Bind(&RecordDeletionProbe::Run
,
428 new RecordDeletionProbe(NULL
, &b_was_deleted
)),
429 TimeDelta::FromMilliseconds(1000));
431 EXPECT_TRUE(a_was_deleted
);
432 EXPECT_TRUE(b_was_deleted
);
435 void RunTest_EnsureDeletion_Chain(MessageLoop::Type message_loop_type
) {
436 bool a_was_deleted
= false;
437 bool b_was_deleted
= false;
438 bool c_was_deleted
= false;
440 MessageLoop
loop(message_loop_type
);
441 // The scoped_refptr for each of the below is held either by the chained
442 // RecordDeletionProbe, or the bound RecordDeletionProbe::Run() callback.
443 RecordDeletionProbe
* a
= new RecordDeletionProbe(NULL
, &a_was_deleted
);
444 RecordDeletionProbe
* b
= new RecordDeletionProbe(a
, &b_was_deleted
);
445 RecordDeletionProbe
* c
= new RecordDeletionProbe(b
, &c_was_deleted
);
446 loop
.PostTask(FROM_HERE
, base::Bind(&RecordDeletionProbe::Run
, c
));
448 EXPECT_TRUE(a_was_deleted
);
449 EXPECT_TRUE(b_was_deleted
);
450 EXPECT_TRUE(c_was_deleted
);
453 void NestingFunc(int* depth
) {
456 MessageLoop::current()->PostTask(FROM_HERE
,
457 base::Bind(&NestingFunc
, depth
));
459 MessageLoop::current()->SetNestableTasksAllowed(true);
460 MessageLoop::current()->Run();
462 MessageLoop::current()->Quit();
467 LONG WINAPI
BadExceptionHandler(EXCEPTION_POINTERS
*ex_info
) {
468 ADD_FAILURE() << "bad exception handler";
469 ::ExitProcess(ex_info
->ExceptionRecord
->ExceptionCode
);
470 return EXCEPTION_EXECUTE_HANDLER
;
473 // This task throws an SEH exception: initially write to an invalid address.
474 // If the right SEH filter is installed, it will fix the error.
475 class Crasher
: public base::RefCounted
<Crasher
> {
477 // Ctor. If trash_SEH_handler is true, the task will override the unhandled
478 // exception handler with one sure to crash this test.
479 explicit Crasher(bool trash_SEH_handler
)
480 : trash_SEH_handler_(trash_SEH_handler
) {
484 PlatformThread::Sleep(TimeDelta::FromMilliseconds(1));
485 if (trash_SEH_handler_
)
486 ::SetUnhandledExceptionFilter(&BadExceptionHandler
);
487 // Generate a SEH fault. We do it in asm to make sure we know how to undo
493 mov eax
, dword ptr
[Crasher::bad_array_
]
494 mov byte ptr
[eax
], 66
497 #elif defined(_M_X64)
502 #error "needs architecture support"
505 MessageLoop::current()->Quit();
507 // Points the bad array to a valid memory location.
508 static void FixError() {
509 bad_array_
= &valid_store_
;
513 bool trash_SEH_handler_
;
514 static volatile char* bad_array_
;
515 static char valid_store_
;
518 volatile char* Crasher::bad_array_
= 0;
519 char Crasher::valid_store_
= 0;
521 // This SEH filter fixes the problem and retries execution. Fixing requires
522 // that the last instruction: mov eax, [Crasher::bad_array_] to be retried
523 // so we move the instruction pointer 5 bytes back.
524 LONG WINAPI
HandleCrasherException(EXCEPTION_POINTERS
*ex_info
) {
525 if (ex_info
->ExceptionRecord
->ExceptionCode
!= EXCEPTION_ACCESS_VIOLATION
)
526 return EXCEPTION_EXECUTE_HANDLER
;
532 ex_info
->ContextRecord
->Eip
-= 5;
534 #elif defined(_M_X64)
536 ex_info
->ContextRecord
->Rip
-= 5;
540 return EXCEPTION_CONTINUE_EXECUTION
;
543 void RunTest_Crasher(MessageLoop::Type message_loop_type
) {
544 MessageLoop
loop(message_loop_type
);
546 if (::IsDebuggerPresent())
549 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter
=
550 ::SetUnhandledExceptionFilter(&HandleCrasherException
);
552 MessageLoop::current()->PostTask(
554 base::Bind(&Crasher::Run
, new Crasher(false)));
555 MessageLoop::current()->set_exception_restoration(true);
556 MessageLoop::current()->Run();
557 MessageLoop::current()->set_exception_restoration(false);
559 ::SetUnhandledExceptionFilter(old_SEH_filter
);
562 void RunTest_CrasherNasty(MessageLoop::Type message_loop_type
) {
563 MessageLoop
loop(message_loop_type
);
565 if (::IsDebuggerPresent())
568 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter
=
569 ::SetUnhandledExceptionFilter(&HandleCrasherException
);
571 MessageLoop::current()->PostTask(
573 base::Bind(&Crasher::Run
, new Crasher(true)));
574 MessageLoop::current()->set_exception_restoration(true);
575 MessageLoop::current()->Run();
576 MessageLoop::current()->set_exception_restoration(false);
578 ::SetUnhandledExceptionFilter(old_SEH_filter
);
581 #endif // defined(OS_WIN)
583 void RunTest_Nesting(MessageLoop::Type message_loop_type
) {
584 MessageLoop
loop(message_loop_type
);
587 MessageLoop::current()->PostTask(FROM_HERE
,
588 base::Bind(&NestingFunc
, &depth
));
589 MessageLoop::current()->Run();
593 const wchar_t* const kMessageBoxTitle
= L
"MessageLoop Unit Test";
607 // Saves the order in which the tasks executed.
609 TaskItem(TaskType t
, int c
, bool s
)
619 bool operator == (const TaskItem
& other
) const {
620 return type
== other
.type
&& cookie
== other
.cookie
&& start
== other
.start
;
624 std::ostream
& operator <<(std::ostream
& os
, TaskType type
) {
626 case MESSAGEBOX
: os
<< "MESSAGEBOX"; break;
627 case ENDDIALOG
: os
<< "ENDDIALOG"; break;
628 case RECURSIVE
: os
<< "RECURSIVE"; break;
629 case TIMEDMESSAGELOOP
: os
<< "TIMEDMESSAGELOOP"; break;
630 case QUITMESSAGELOOP
: os
<< "QUITMESSAGELOOP"; break;
631 case ORDERED
: os
<< "ORDERED"; break;
632 case PUMPS
: os
<< "PUMPS"; break;
633 case SLEEP
: os
<< "SLEEP"; break;
636 os
<< "Unknown TaskType";
642 std::ostream
& operator <<(std::ostream
& os
, const TaskItem
& item
) {
644 return os
<< item
.type
<< " " << item
.cookie
<< " starts";
646 return os
<< item
.type
<< " " << item
.cookie
<< " ends";
651 void RecordStart(TaskType type
, int cookie
) {
652 TaskItem
item(type
, cookie
, true);
654 task_list_
.push_back(item
);
657 void RecordEnd(TaskType type
, int cookie
) {
658 TaskItem
item(type
, cookie
, false);
660 task_list_
.push_back(item
);
664 return task_list_
.size();
667 TaskItem
Get(int n
) {
668 return task_list_
[n
];
672 std::vector
<TaskItem
> task_list_
;
675 // Saves the order the tasks ran.
676 void OrderedFunc(TaskList
* order
, int cookie
) {
677 order
->RecordStart(ORDERED
, cookie
);
678 order
->RecordEnd(ORDERED
, cookie
);
683 // MessageLoop implicitly start a "modal message loop". Modal dialog boxes,
684 // common controls (like OpenFile) and StartDoc printing function can cause
685 // implicit message loops.
686 void MessageBoxFunc(TaskList
* order
, int cookie
, bool is_reentrant
) {
687 order
->RecordStart(MESSAGEBOX
, cookie
);
689 MessageLoop::current()->SetNestableTasksAllowed(true);
690 MessageBox(NULL
, L
"Please wait...", kMessageBoxTitle
, MB_OK
);
691 order
->RecordEnd(MESSAGEBOX
, cookie
);
694 // Will end the MessageBox.
695 void EndDialogFunc(TaskList
* order
, int cookie
) {
696 order
->RecordStart(ENDDIALOG
, cookie
);
697 HWND window
= GetActiveWindow();
698 if (window
!= NULL
) {
699 EXPECT_NE(EndDialog(window
, IDCONTINUE
), 0);
700 // Cheap way to signal that the window wasn't found if RunEnd() isn't
702 order
->RecordEnd(ENDDIALOG
, cookie
);
706 #endif // defined(OS_WIN)
708 void RecursiveFunc(TaskList
* order
, int cookie
, int depth
,
710 order
->RecordStart(RECURSIVE
, cookie
);
713 MessageLoop::current()->SetNestableTasksAllowed(true);
714 MessageLoop::current()->PostTask(
716 base::Bind(&RecursiveFunc
, order
, cookie
, depth
- 1, is_reentrant
));
718 order
->RecordEnd(RECURSIVE
, cookie
);
721 void RecursiveSlowFunc(TaskList
* order
, int cookie
, int depth
,
723 RecursiveFunc(order
, cookie
, depth
, is_reentrant
);
724 PlatformThread::Sleep(TimeDelta::FromMilliseconds(10));
727 void QuitFunc(TaskList
* order
, int cookie
) {
728 order
->RecordStart(QUITMESSAGELOOP
, cookie
);
729 MessageLoop::current()->Quit();
730 order
->RecordEnd(QUITMESSAGELOOP
, cookie
);
733 void SleepFunc(TaskList
* order
, int cookie
, TimeDelta delay
) {
734 order
->RecordStart(SLEEP
, cookie
);
735 PlatformThread::Sleep(delay
);
736 order
->RecordEnd(SLEEP
, cookie
);
740 void RecursiveFuncWin(MessageLoop
* target
,
745 target
->PostTask(FROM_HERE
,
746 base::Bind(&RecursiveFunc
, order
, 1, 2, is_reentrant
));
747 target
->PostTask(FROM_HERE
,
748 base::Bind(&MessageBoxFunc
, order
, 2, is_reentrant
));
749 target
->PostTask(FROM_HERE
,
750 base::Bind(&RecursiveFunc
, order
, 3, 2, is_reentrant
));
751 // The trick here is that for recursive task processing, this task will be
752 // ran _inside_ the MessageBox message loop, dismissing the MessageBox
754 // For non-recursive task processing, this will be executed _after_ the
755 // MessageBox will have been dismissed by the code below, where
756 // expect_window_ is true.
757 target
->PostTask(FROM_HERE
,
758 base::Bind(&EndDialogFunc
, order
, 4));
759 target
->PostTask(FROM_HERE
,
760 base::Bind(&QuitFunc
, order
, 5));
762 // Enforce that every tasks are sent before starting to run the main thread
764 ASSERT_TRUE(SetEvent(event
));
766 // Poll for the MessageBox. Don't do this at home! At the speed we do it,
767 // you will never realize one MessageBox was shown.
768 for (; expect_window
;) {
769 HWND window
= FindWindow(L
"#32770", kMessageBoxTitle
);
773 HWND button
= FindWindowEx(window
, NULL
, L
"Button", NULL
);
774 if (button
!= NULL
) {
775 EXPECT_EQ(0, SendMessage(button
, WM_LBUTTONDOWN
, 0, 0));
776 EXPECT_EQ(0, SendMessage(button
, WM_LBUTTONUP
, 0, 0));
785 #endif // defined(OS_WIN)
787 void RunTest_RecursiveDenial1(MessageLoop::Type message_loop_type
) {
788 MessageLoop
loop(message_loop_type
);
790 EXPECT_TRUE(MessageLoop::current()->NestableTasksAllowed());
792 MessageLoop::current()->PostTask(
794 base::Bind(&RecursiveFunc
, &order
, 1, 2, false));
795 MessageLoop::current()->PostTask(
797 base::Bind(&RecursiveFunc
, &order
, 2, 2, false));
798 MessageLoop::current()->PostTask(
800 base::Bind(&QuitFunc
, &order
, 3));
802 MessageLoop::current()->Run();
805 ASSERT_EQ(14U, order
.Size());
806 EXPECT_EQ(order
.Get(0), TaskItem(RECURSIVE
, 1, true));
807 EXPECT_EQ(order
.Get(1), TaskItem(RECURSIVE
, 1, false));
808 EXPECT_EQ(order
.Get(2), TaskItem(RECURSIVE
, 2, true));
809 EXPECT_EQ(order
.Get(3), TaskItem(RECURSIVE
, 2, false));
810 EXPECT_EQ(order
.Get(4), TaskItem(QUITMESSAGELOOP
, 3, true));
811 EXPECT_EQ(order
.Get(5), TaskItem(QUITMESSAGELOOP
, 3, false));
812 EXPECT_EQ(order
.Get(6), TaskItem(RECURSIVE
, 1, true));
813 EXPECT_EQ(order
.Get(7), TaskItem(RECURSIVE
, 1, false));
814 EXPECT_EQ(order
.Get(8), TaskItem(RECURSIVE
, 2, true));
815 EXPECT_EQ(order
.Get(9), TaskItem(RECURSIVE
, 2, false));
816 EXPECT_EQ(order
.Get(10), TaskItem(RECURSIVE
, 1, true));
817 EXPECT_EQ(order
.Get(11), TaskItem(RECURSIVE
, 1, false));
818 EXPECT_EQ(order
.Get(12), TaskItem(RECURSIVE
, 2, true));
819 EXPECT_EQ(order
.Get(13), TaskItem(RECURSIVE
, 2, false));
822 void RunTest_RecursiveDenial3(MessageLoop::Type message_loop_type
) {
823 MessageLoop
loop(message_loop_type
);
825 EXPECT_TRUE(MessageLoop::current()->NestableTasksAllowed());
827 MessageLoop::current()->PostTask(
828 FROM_HERE
, base::Bind(&RecursiveSlowFunc
, &order
, 1, 2, false));
829 MessageLoop::current()->PostTask(
830 FROM_HERE
, base::Bind(&RecursiveSlowFunc
, &order
, 2, 2, false));
831 MessageLoop::current()->PostDelayedTask(
833 base::Bind(&OrderedFunc
, &order
, 3),
834 TimeDelta::FromMilliseconds(5));
835 MessageLoop::current()->PostDelayedTask(
837 base::Bind(&QuitFunc
, &order
, 4),
838 TimeDelta::FromMilliseconds(5));
840 MessageLoop::current()->Run();
843 ASSERT_EQ(16U, order
.Size());
844 EXPECT_EQ(order
.Get(0), TaskItem(RECURSIVE
, 1, true));
845 EXPECT_EQ(order
.Get(1), TaskItem(RECURSIVE
, 1, false));
846 EXPECT_EQ(order
.Get(2), TaskItem(RECURSIVE
, 2, true));
847 EXPECT_EQ(order
.Get(3), TaskItem(RECURSIVE
, 2, false));
848 EXPECT_EQ(order
.Get(4), TaskItem(RECURSIVE
, 1, true));
849 EXPECT_EQ(order
.Get(5), TaskItem(RECURSIVE
, 1, false));
850 EXPECT_EQ(order
.Get(6), TaskItem(ORDERED
, 3, true));
851 EXPECT_EQ(order
.Get(7), TaskItem(ORDERED
, 3, false));
852 EXPECT_EQ(order
.Get(8), TaskItem(RECURSIVE
, 2, true));
853 EXPECT_EQ(order
.Get(9), TaskItem(RECURSIVE
, 2, false));
854 EXPECT_EQ(order
.Get(10), TaskItem(QUITMESSAGELOOP
, 4, true));
855 EXPECT_EQ(order
.Get(11), TaskItem(QUITMESSAGELOOP
, 4, false));
856 EXPECT_EQ(order
.Get(12), TaskItem(RECURSIVE
, 1, true));
857 EXPECT_EQ(order
.Get(13), TaskItem(RECURSIVE
, 1, false));
858 EXPECT_EQ(order
.Get(14), TaskItem(RECURSIVE
, 2, true));
859 EXPECT_EQ(order
.Get(15), TaskItem(RECURSIVE
, 2, false));
862 void RunTest_RecursiveSupport1(MessageLoop::Type message_loop_type
) {
863 MessageLoop
loop(message_loop_type
);
866 MessageLoop::current()->PostTask(
867 FROM_HERE
, base::Bind(&RecursiveFunc
, &order
, 1, 2, true));
868 MessageLoop::current()->PostTask(
869 FROM_HERE
, base::Bind(&RecursiveFunc
, &order
, 2, 2, true));
870 MessageLoop::current()->PostTask(
871 FROM_HERE
, base::Bind(&QuitFunc
, &order
, 3));
873 MessageLoop::current()->Run();
876 ASSERT_EQ(14U, order
.Size());
877 EXPECT_EQ(order
.Get(0), TaskItem(RECURSIVE
, 1, true));
878 EXPECT_EQ(order
.Get(1), TaskItem(RECURSIVE
, 1, false));
879 EXPECT_EQ(order
.Get(2), TaskItem(RECURSIVE
, 2, true));
880 EXPECT_EQ(order
.Get(3), TaskItem(RECURSIVE
, 2, false));
881 EXPECT_EQ(order
.Get(4), TaskItem(QUITMESSAGELOOP
, 3, true));
882 EXPECT_EQ(order
.Get(5), TaskItem(QUITMESSAGELOOP
, 3, false));
883 EXPECT_EQ(order
.Get(6), TaskItem(RECURSIVE
, 1, true));
884 EXPECT_EQ(order
.Get(7), TaskItem(RECURSIVE
, 1, false));
885 EXPECT_EQ(order
.Get(8), TaskItem(RECURSIVE
, 2, true));
886 EXPECT_EQ(order
.Get(9), TaskItem(RECURSIVE
, 2, false));
887 EXPECT_EQ(order
.Get(10), TaskItem(RECURSIVE
, 1, true));
888 EXPECT_EQ(order
.Get(11), TaskItem(RECURSIVE
, 1, false));
889 EXPECT_EQ(order
.Get(12), TaskItem(RECURSIVE
, 2, true));
890 EXPECT_EQ(order
.Get(13), TaskItem(RECURSIVE
, 2, false));
894 // TODO(darin): These tests need to be ported since they test critical
895 // message loop functionality.
897 // A side effect of this test is the generation a beep. Sorry.
898 void RunTest_RecursiveDenial2(MessageLoop::Type message_loop_type
) {
899 MessageLoop
loop(message_loop_type
);
901 Thread
worker("RecursiveDenial2_worker");
902 Thread::Options options
;
903 options
.message_loop_type
= message_loop_type
;
904 ASSERT_EQ(true, worker
.StartWithOptions(options
));
906 base::win::ScopedHandle
event(CreateEvent(NULL
, FALSE
, FALSE
, NULL
));
907 worker
.message_loop()->PostTask(FROM_HERE
,
908 base::Bind(&RecursiveFuncWin
,
909 MessageLoop::current(),
914 // Let the other thread execute.
915 WaitForSingleObject(event
, INFINITE
);
916 MessageLoop::current()->Run();
918 ASSERT_EQ(order
.Size(), 17);
919 EXPECT_EQ(order
.Get(0), TaskItem(RECURSIVE
, 1, true));
920 EXPECT_EQ(order
.Get(1), TaskItem(RECURSIVE
, 1, false));
921 EXPECT_EQ(order
.Get(2), TaskItem(MESSAGEBOX
, 2, true));
922 EXPECT_EQ(order
.Get(3), TaskItem(MESSAGEBOX
, 2, false));
923 EXPECT_EQ(order
.Get(4), TaskItem(RECURSIVE
, 3, true));
924 EXPECT_EQ(order
.Get(5), TaskItem(RECURSIVE
, 3, false));
925 // When EndDialogFunc is processed, the window is already dismissed, hence no
927 EXPECT_EQ(order
.Get(6), TaskItem(ENDDIALOG
, 4, true));
928 EXPECT_EQ(order
.Get(7), TaskItem(QUITMESSAGELOOP
, 5, true));
929 EXPECT_EQ(order
.Get(8), TaskItem(QUITMESSAGELOOP
, 5, false));
930 EXPECT_EQ(order
.Get(9), TaskItem(RECURSIVE
, 1, true));
931 EXPECT_EQ(order
.Get(10), TaskItem(RECURSIVE
, 1, false));
932 EXPECT_EQ(order
.Get(11), TaskItem(RECURSIVE
, 3, true));
933 EXPECT_EQ(order
.Get(12), TaskItem(RECURSIVE
, 3, false));
934 EXPECT_EQ(order
.Get(13), TaskItem(RECURSIVE
, 1, true));
935 EXPECT_EQ(order
.Get(14), TaskItem(RECURSIVE
, 1, false));
936 EXPECT_EQ(order
.Get(15), TaskItem(RECURSIVE
, 3, true));
937 EXPECT_EQ(order
.Get(16), TaskItem(RECURSIVE
, 3, false));
940 // A side effect of this test is the generation a beep. Sorry. This test also
941 // needs to process windows messages on the current thread.
942 void RunTest_RecursiveSupport2(MessageLoop::Type message_loop_type
) {
943 MessageLoop
loop(message_loop_type
);
945 Thread
worker("RecursiveSupport2_worker");
946 Thread::Options options
;
947 options
.message_loop_type
= message_loop_type
;
948 ASSERT_EQ(true, worker
.StartWithOptions(options
));
950 base::win::ScopedHandle
event(CreateEvent(NULL
, FALSE
, FALSE
, NULL
));
951 worker
.message_loop()->PostTask(FROM_HERE
,
952 base::Bind(&RecursiveFuncWin
,
953 MessageLoop::current(),
958 // Let the other thread execute.
959 WaitForSingleObject(event
, INFINITE
);
960 MessageLoop::current()->Run();
962 ASSERT_EQ(order
.Size(), 18);
963 EXPECT_EQ(order
.Get(0), TaskItem(RECURSIVE
, 1, true));
964 EXPECT_EQ(order
.Get(1), TaskItem(RECURSIVE
, 1, false));
965 EXPECT_EQ(order
.Get(2), TaskItem(MESSAGEBOX
, 2, true));
966 // Note that this executes in the MessageBox modal loop.
967 EXPECT_EQ(order
.Get(3), TaskItem(RECURSIVE
, 3, true));
968 EXPECT_EQ(order
.Get(4), TaskItem(RECURSIVE
, 3, false));
969 EXPECT_EQ(order
.Get(5), TaskItem(ENDDIALOG
, 4, true));
970 EXPECT_EQ(order
.Get(6), TaskItem(ENDDIALOG
, 4, false));
971 EXPECT_EQ(order
.Get(7), TaskItem(MESSAGEBOX
, 2, false));
972 /* The order can subtly change here. The reason is that when RecursiveFunc(1)
973 is called in the main thread, if it is faster than getting to the
974 PostTask(FROM_HERE, base::Bind(&QuitFunc) execution, the order of task
975 execution can change. We don't care anyway that the order isn't correct.
976 EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, true));
977 EXPECT_EQ(order.Get(9), TaskItem(QUITMESSAGELOOP, 5, false));
978 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
979 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
981 EXPECT_EQ(order
.Get(12), TaskItem(RECURSIVE
, 3, true));
982 EXPECT_EQ(order
.Get(13), TaskItem(RECURSIVE
, 3, false));
983 EXPECT_EQ(order
.Get(14), TaskItem(RECURSIVE
, 1, true));
984 EXPECT_EQ(order
.Get(15), TaskItem(RECURSIVE
, 1, false));
985 EXPECT_EQ(order
.Get(16), TaskItem(RECURSIVE
, 3, true));
986 EXPECT_EQ(order
.Get(17), TaskItem(RECURSIVE
, 3, false));
989 #endif // defined(OS_WIN)
991 void FuncThatPumps(TaskList
* order
, int cookie
) {
992 order
->RecordStart(PUMPS
, cookie
);
994 MessageLoop::ScopedNestableTaskAllower
allow(MessageLoop::current());
995 MessageLoop::current()->RunUntilIdle();
997 order
->RecordEnd(PUMPS
, cookie
);
1000 void FuncThatRuns(TaskList
* order
, int cookie
, base::RunLoop
* run_loop
) {
1001 order
->RecordStart(RUNS
, cookie
);
1003 MessageLoop::ScopedNestableTaskAllower
allow(MessageLoop::current());
1006 order
->RecordEnd(RUNS
, cookie
);
1009 void FuncThatQuitsNow() {
1010 MessageLoop::current()->QuitNow();
1013 // Tests that non nestable tasks run in FIFO if there are no nested loops.
1014 void RunTest_NonNestableWithNoNesting(
1015 MessageLoop::Type message_loop_type
) {
1016 MessageLoop
loop(message_loop_type
);
1020 MessageLoop::current()->PostNonNestableTask(
1022 base::Bind(&OrderedFunc
, &order
, 1));
1023 MessageLoop::current()->PostTask(FROM_HERE
,
1024 base::Bind(&OrderedFunc
, &order
, 2));
1025 MessageLoop::current()->PostTask(FROM_HERE
,
1026 base::Bind(&QuitFunc
, &order
, 3));
1027 MessageLoop::current()->Run();
1030 ASSERT_EQ(6U, order
.Size());
1031 EXPECT_EQ(order
.Get(0), TaskItem(ORDERED
, 1, true));
1032 EXPECT_EQ(order
.Get(1), TaskItem(ORDERED
, 1, false));
1033 EXPECT_EQ(order
.Get(2), TaskItem(ORDERED
, 2, true));
1034 EXPECT_EQ(order
.Get(3), TaskItem(ORDERED
, 2, false));
1035 EXPECT_EQ(order
.Get(4), TaskItem(QUITMESSAGELOOP
, 3, true));
1036 EXPECT_EQ(order
.Get(5), TaskItem(QUITMESSAGELOOP
, 3, false));
1039 // Tests that non nestable tasks don't run when there's code in the call stack.
1040 void RunTest_NonNestableInNestedLoop(MessageLoop::Type message_loop_type
,
1042 MessageLoop
loop(message_loop_type
);
1046 MessageLoop::current()->PostTask(
1048 base::Bind(&FuncThatPumps
, &order
, 1));
1050 MessageLoop::current()->PostNonNestableDelayedTask(
1052 base::Bind(&OrderedFunc
, &order
, 2),
1053 TimeDelta::FromMilliseconds(1));
1055 MessageLoop::current()->PostNonNestableTask(
1057 base::Bind(&OrderedFunc
, &order
, 2));
1059 MessageLoop::current()->PostTask(FROM_HERE
,
1060 base::Bind(&OrderedFunc
, &order
, 3));
1061 MessageLoop::current()->PostTask(
1063 base::Bind(&SleepFunc
, &order
, 4, TimeDelta::FromMilliseconds(50)));
1064 MessageLoop::current()->PostTask(FROM_HERE
,
1065 base::Bind(&OrderedFunc
, &order
, 5));
1067 MessageLoop::current()->PostNonNestableDelayedTask(
1069 base::Bind(&QuitFunc
, &order
, 6),
1070 TimeDelta::FromMilliseconds(2));
1072 MessageLoop::current()->PostNonNestableTask(
1074 base::Bind(&QuitFunc
, &order
, 6));
1077 MessageLoop::current()->Run();
1080 ASSERT_EQ(12U, order
.Size());
1081 EXPECT_EQ(order
.Get(0), TaskItem(PUMPS
, 1, true));
1082 EXPECT_EQ(order
.Get(1), TaskItem(ORDERED
, 3, true));
1083 EXPECT_EQ(order
.Get(2), TaskItem(ORDERED
, 3, false));
1084 EXPECT_EQ(order
.Get(3), TaskItem(SLEEP
, 4, true));
1085 EXPECT_EQ(order
.Get(4), TaskItem(SLEEP
, 4, false));
1086 EXPECT_EQ(order
.Get(5), TaskItem(ORDERED
, 5, true));
1087 EXPECT_EQ(order
.Get(6), TaskItem(ORDERED
, 5, false));
1088 EXPECT_EQ(order
.Get(7), TaskItem(PUMPS
, 1, false));
1089 EXPECT_EQ(order
.Get(8), TaskItem(ORDERED
, 2, true));
1090 EXPECT_EQ(order
.Get(9), TaskItem(ORDERED
, 2, false));
1091 EXPECT_EQ(order
.Get(10), TaskItem(QUITMESSAGELOOP
, 6, true));
1092 EXPECT_EQ(order
.Get(11), TaskItem(QUITMESSAGELOOP
, 6, false));
1095 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1096 void RunTest_QuitNow(MessageLoop::Type message_loop_type
) {
1097 MessageLoop
loop(message_loop_type
);
1101 base::RunLoop run_loop
;
1103 MessageLoop::current()->PostTask(FROM_HERE
,
1104 base::Bind(&FuncThatRuns
, &order
, 1, base::Unretained(&run_loop
)));
1105 MessageLoop::current()->PostTask(
1106 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 2));
1107 MessageLoop::current()->PostTask(
1108 FROM_HERE
, base::Bind(&FuncThatQuitsNow
));
1109 MessageLoop::current()->PostTask(
1110 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 3));
1111 MessageLoop::current()->PostTask(
1112 FROM_HERE
, base::Bind(&FuncThatQuitsNow
));
1113 MessageLoop::current()->PostTask(
1114 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 4)); // never runs
1116 MessageLoop::current()->Run();
1118 ASSERT_EQ(6U, order
.Size());
1120 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, true));
1121 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, true));
1122 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, false));
1123 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, false));
1124 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 3, true));
1125 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 3, false));
1126 EXPECT_EQ(static_cast<size_t>(task_index
), order
.Size());
1129 // Tests RunLoopQuit works before RunWithID.
1130 void RunTest_RunLoopQuitOrderBefore(MessageLoop::Type message_loop_type
) {
1131 MessageLoop
loop(message_loop_type
);
1135 base::RunLoop run_loop
;
1139 MessageLoop::current()->PostTask(
1140 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 1)); // never runs
1141 MessageLoop::current()->PostTask(
1142 FROM_HERE
, base::Bind(&FuncThatQuitsNow
)); // never runs
1146 ASSERT_EQ(0U, order
.Size());
1149 // Tests RunLoopQuit works during RunWithID.
1150 void RunTest_RunLoopQuitOrderDuring(MessageLoop::Type message_loop_type
) {
1151 MessageLoop
loop(message_loop_type
);
1155 base::RunLoop run_loop
;
1157 MessageLoop::current()->PostTask(
1158 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 1));
1159 MessageLoop::current()->PostTask(
1160 FROM_HERE
, run_loop
.QuitClosure());
1161 MessageLoop::current()->PostTask(
1162 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 2)); // never runs
1163 MessageLoop::current()->PostTask(
1164 FROM_HERE
, base::Bind(&FuncThatQuitsNow
)); // never runs
1168 ASSERT_EQ(2U, order
.Size());
1170 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 1, true));
1171 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 1, false));
1172 EXPECT_EQ(static_cast<size_t>(task_index
), order
.Size());
1175 // Tests RunLoopQuit works after RunWithID.
1176 void RunTest_RunLoopQuitOrderAfter(MessageLoop::Type message_loop_type
) {
1177 MessageLoop
loop(message_loop_type
);
1181 base::RunLoop run_loop
;
1183 MessageLoop::current()->PostTask(FROM_HERE
,
1184 base::Bind(&FuncThatRuns
, &order
, 1, base::Unretained(&run_loop
)));
1185 MessageLoop::current()->PostTask(
1186 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 2));
1187 MessageLoop::current()->PostTask(
1188 FROM_HERE
, base::Bind(&FuncThatQuitsNow
));
1189 MessageLoop::current()->PostTask(
1190 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 3));
1191 MessageLoop::current()->PostTask(
1192 FROM_HERE
, run_loop
.QuitClosure()); // has no affect
1193 MessageLoop::current()->PostTask(
1194 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 4));
1195 MessageLoop::current()->PostTask(
1196 FROM_HERE
, base::Bind(&FuncThatQuitsNow
));
1198 base::RunLoop outer_run_loop
;
1199 outer_run_loop
.Run();
1201 ASSERT_EQ(8U, order
.Size());
1203 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, true));
1204 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, true));
1205 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, false));
1206 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, false));
1207 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 3, true));
1208 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 3, false));
1209 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 4, true));
1210 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 4, false));
1211 EXPECT_EQ(static_cast<size_t>(task_index
), order
.Size());
1214 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1215 void RunTest_RunLoopQuitTop(MessageLoop::Type message_loop_type
) {
1216 MessageLoop
loop(message_loop_type
);
1220 base::RunLoop outer_run_loop
;
1221 base::RunLoop nested_run_loop
;
1223 MessageLoop::current()->PostTask(FROM_HERE
,
1224 base::Bind(&FuncThatRuns
, &order
, 1, base::Unretained(&nested_run_loop
)));
1225 MessageLoop::current()->PostTask(
1226 FROM_HERE
, outer_run_loop
.QuitClosure());
1227 MessageLoop::current()->PostTask(
1228 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 2));
1229 MessageLoop::current()->PostTask(
1230 FROM_HERE
, nested_run_loop
.QuitClosure());
1232 outer_run_loop
.Run();
1234 ASSERT_EQ(4U, order
.Size());
1236 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, true));
1237 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, true));
1238 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, false));
1239 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, false));
1240 EXPECT_EQ(static_cast<size_t>(task_index
), order
.Size());
1243 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1244 void RunTest_RunLoopQuitNested(MessageLoop::Type message_loop_type
) {
1245 MessageLoop
loop(message_loop_type
);
1249 base::RunLoop outer_run_loop
;
1250 base::RunLoop nested_run_loop
;
1252 MessageLoop::current()->PostTask(FROM_HERE
,
1253 base::Bind(&FuncThatRuns
, &order
, 1, base::Unretained(&nested_run_loop
)));
1254 MessageLoop::current()->PostTask(
1255 FROM_HERE
, nested_run_loop
.QuitClosure());
1256 MessageLoop::current()->PostTask(
1257 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 2));
1258 MessageLoop::current()->PostTask(
1259 FROM_HERE
, outer_run_loop
.QuitClosure());
1261 outer_run_loop
.Run();
1263 ASSERT_EQ(4U, order
.Size());
1265 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, true));
1266 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, false));
1267 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, true));
1268 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, false));
1269 EXPECT_EQ(static_cast<size_t>(task_index
), order
.Size());
1272 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1273 void RunTest_RunLoopQuitBogus(MessageLoop::Type message_loop_type
) {
1274 MessageLoop
loop(message_loop_type
);
1278 base::RunLoop outer_run_loop
;
1279 base::RunLoop nested_run_loop
;
1280 base::RunLoop bogus_run_loop
;
1282 MessageLoop::current()->PostTask(FROM_HERE
,
1283 base::Bind(&FuncThatRuns
, &order
, 1, base::Unretained(&nested_run_loop
)));
1284 MessageLoop::current()->PostTask(
1285 FROM_HERE
, bogus_run_loop
.QuitClosure());
1286 MessageLoop::current()->PostTask(
1287 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 2));
1288 MessageLoop::current()->PostTask(
1289 FROM_HERE
, outer_run_loop
.QuitClosure());
1290 MessageLoop::current()->PostTask(
1291 FROM_HERE
, nested_run_loop
.QuitClosure());
1293 outer_run_loop
.Run();
1295 ASSERT_EQ(4U, order
.Size());
1297 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, true));
1298 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, true));
1299 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 2, false));
1300 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, false));
1301 EXPECT_EQ(static_cast<size_t>(task_index
), order
.Size());
1304 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1305 void RunTest_RunLoopQuitDeep(MessageLoop::Type message_loop_type
) {
1306 MessageLoop
loop(message_loop_type
);
1310 base::RunLoop outer_run_loop
;
1311 base::RunLoop nested_loop1
;
1312 base::RunLoop nested_loop2
;
1313 base::RunLoop nested_loop3
;
1314 base::RunLoop nested_loop4
;
1316 MessageLoop::current()->PostTask(FROM_HERE
,
1317 base::Bind(&FuncThatRuns
, &order
, 1, base::Unretained(&nested_loop1
)));
1318 MessageLoop::current()->PostTask(FROM_HERE
,
1319 base::Bind(&FuncThatRuns
, &order
, 2, base::Unretained(&nested_loop2
)));
1320 MessageLoop::current()->PostTask(FROM_HERE
,
1321 base::Bind(&FuncThatRuns
, &order
, 3, base::Unretained(&nested_loop3
)));
1322 MessageLoop::current()->PostTask(FROM_HERE
,
1323 base::Bind(&FuncThatRuns
, &order
, 4, base::Unretained(&nested_loop4
)));
1324 MessageLoop::current()->PostTask(
1325 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 5));
1326 MessageLoop::current()->PostTask(
1327 FROM_HERE
, outer_run_loop
.QuitClosure());
1328 MessageLoop::current()->PostTask(
1329 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 6));
1330 MessageLoop::current()->PostTask(
1331 FROM_HERE
, nested_loop1
.QuitClosure());
1332 MessageLoop::current()->PostTask(
1333 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 7));
1334 MessageLoop::current()->PostTask(
1335 FROM_HERE
, nested_loop2
.QuitClosure());
1336 MessageLoop::current()->PostTask(
1337 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 8));
1338 MessageLoop::current()->PostTask(
1339 FROM_HERE
, nested_loop3
.QuitClosure());
1340 MessageLoop::current()->PostTask(
1341 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 9));
1342 MessageLoop::current()->PostTask(
1343 FROM_HERE
, nested_loop4
.QuitClosure());
1344 MessageLoop::current()->PostTask(
1345 FROM_HERE
, base::Bind(&OrderedFunc
, &order
, 10));
1347 outer_run_loop
.Run();
1349 ASSERT_EQ(18U, order
.Size());
1351 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, true));
1352 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 2, true));
1353 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 3, true));
1354 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 4, true));
1355 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 5, true));
1356 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 5, false));
1357 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 6, true));
1358 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 6, false));
1359 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 7, true));
1360 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 7, false));
1361 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 8, true));
1362 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 8, false));
1363 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 9, true));
1364 EXPECT_EQ(order
.Get(task_index
++), TaskItem(ORDERED
, 9, false));
1365 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 4, false));
1366 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 3, false));
1367 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 2, false));
1368 EXPECT_EQ(order
.Get(task_index
++), TaskItem(RUNS
, 1, false));
1369 EXPECT_EQ(static_cast<size_t>(task_index
), order
.Size());
1374 class DispatcherImpl
: public MessageLoopForUI::Dispatcher
{
1376 DispatcherImpl() : dispatch_count_(0) {}
1378 virtual bool Dispatch(const base::NativeEvent
& msg
) OVERRIDE
{
1379 ::TranslateMessage(&msg
);
1380 ::DispatchMessage(&msg
);
1381 // Do not count WM_TIMER since it is not what we post and it will cause
1383 if (msg
.message
!= WM_TIMER
)
1385 // We treat WM_LBUTTONUP as the last message.
1386 return msg
.message
!= WM_LBUTTONUP
;
1389 int dispatch_count_
;
1392 void MouseDownUp() {
1393 PostMessage(NULL
, WM_LBUTTONDOWN
, 0, 0);
1394 PostMessage(NULL
, WM_LBUTTONUP
, 'A', 0);
1397 void RunTest_Dispatcher(MessageLoop::Type message_loop_type
) {
1398 MessageLoop
loop(message_loop_type
);
1400 MessageLoop::current()->PostDelayedTask(
1402 base::Bind(&MouseDownUp
),
1403 TimeDelta::FromMilliseconds(100));
1404 DispatcherImpl dispatcher
;
1405 base::RunLoop
run_loop(&dispatcher
);
1407 ASSERT_EQ(2, dispatcher
.dispatch_count_
);
1410 LRESULT CALLBACK
MsgFilterProc(int code
, WPARAM wparam
, LPARAM lparam
) {
1411 if (code
== base::MessagePumpForUI::kMessageFilterCode
) {
1412 MSG
* msg
= reinterpret_cast<MSG
*>(lparam
);
1413 if (msg
->message
== WM_LBUTTONDOWN
)
1419 void RunTest_DispatcherWithMessageHook(MessageLoop::Type message_loop_type
) {
1420 MessageLoop
loop(message_loop_type
);
1422 MessageLoop::current()->PostDelayedTask(
1424 base::Bind(&MouseDownUp
),
1425 TimeDelta::FromMilliseconds(100));
1426 HHOOK msg_hook
= SetWindowsHookEx(WH_MSGFILTER
,
1429 GetCurrentThreadId());
1430 DispatcherImpl dispatcher
;
1431 base::RunLoop
run_loop(&dispatcher
);
1433 ASSERT_EQ(1, dispatcher
.dispatch_count_
);
1434 UnhookWindowsHookEx(msg_hook
);
1437 class TestIOHandler
: public MessageLoopForIO::IOHandler
{
1439 TestIOHandler(const wchar_t* name
, HANDLE signal
, bool wait
);
1441 virtual void OnIOCompleted(MessageLoopForIO::IOContext
* context
,
1442 DWORD bytes_transfered
, DWORD error
);
1446 OVERLAPPED
* context() { return &context_
.overlapped
; }
1447 DWORD
size() { return sizeof(buffer_
); }
1451 MessageLoopForIO::IOContext context_
;
1453 base::win::ScopedHandle file_
;
1457 TestIOHandler::TestIOHandler(const wchar_t* name
, HANDLE signal
, bool wait
)
1458 : signal_(signal
), wait_(wait
) {
1459 memset(buffer_
, 0, sizeof(buffer_
));
1460 memset(&context_
, 0, sizeof(context_
));
1461 context_
.handler
= this;
1463 file_
.Set(CreateFile(name
, GENERIC_READ
, 0, NULL
, OPEN_EXISTING
,
1464 FILE_FLAG_OVERLAPPED
, NULL
));
1465 EXPECT_TRUE(file_
.IsValid());
1468 void TestIOHandler::Init() {
1469 MessageLoopForIO::current()->RegisterIOHandler(file_
, this);
1472 EXPECT_FALSE(ReadFile(file_
, buffer_
, size(), &read
, context()));
1473 EXPECT_EQ(ERROR_IO_PENDING
, GetLastError());
1478 void TestIOHandler::OnIOCompleted(MessageLoopForIO::IOContext
* context
,
1479 DWORD bytes_transfered
, DWORD error
) {
1480 ASSERT_TRUE(context
== &context_
);
1481 ASSERT_TRUE(SetEvent(signal_
));
1484 void TestIOHandler::WaitForIO() {
1485 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(300, this));
1486 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(400, this));
1489 void RunTest_IOHandler() {
1490 base::win::ScopedHandle
callback_called(CreateEvent(NULL
, TRUE
, FALSE
, NULL
));
1491 ASSERT_TRUE(callback_called
.IsValid());
1493 const wchar_t* kPipeName
= L
"\\\\.\\pipe\\iohandler_pipe";
1494 base::win::ScopedHandle
server(
1495 CreateNamedPipe(kPipeName
, PIPE_ACCESS_OUTBOUND
, 0, 1, 0, 0, 0, NULL
));
1496 ASSERT_TRUE(server
.IsValid());
1498 Thread
thread("IOHandler test");
1499 Thread::Options options
;
1500 options
.message_loop_type
= MessageLoop::TYPE_IO
;
1501 ASSERT_TRUE(thread
.StartWithOptions(options
));
1503 MessageLoop
* thread_loop
= thread
.message_loop();
1504 ASSERT_TRUE(NULL
!= thread_loop
);
1506 TestIOHandler
handler(kPipeName
, callback_called
, false);
1507 thread_loop
->PostTask(FROM_HERE
, base::Bind(&TestIOHandler::Init
,
1508 base::Unretained(&handler
)));
1509 // Make sure the thread runs and sleeps for lack of work.
1510 base::PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
1512 const char buffer
[] = "Hello there!";
1514 EXPECT_TRUE(WriteFile(server
, buffer
, sizeof(buffer
), &written
, NULL
));
1516 DWORD result
= WaitForSingleObject(callback_called
, 1000);
1517 EXPECT_EQ(WAIT_OBJECT_0
, result
);
1522 void RunTest_WaitForIO() {
1523 base::win::ScopedHandle
callback1_called(
1524 CreateEvent(NULL
, TRUE
, FALSE
, NULL
));
1525 base::win::ScopedHandle
callback2_called(
1526 CreateEvent(NULL
, TRUE
, FALSE
, NULL
));
1527 ASSERT_TRUE(callback1_called
.IsValid());
1528 ASSERT_TRUE(callback2_called
.IsValid());
1530 const wchar_t* kPipeName1
= L
"\\\\.\\pipe\\iohandler_pipe1";
1531 const wchar_t* kPipeName2
= L
"\\\\.\\pipe\\iohandler_pipe2";
1532 base::win::ScopedHandle
server1(
1533 CreateNamedPipe(kPipeName1
, PIPE_ACCESS_OUTBOUND
, 0, 1, 0, 0, 0, NULL
));
1534 base::win::ScopedHandle
server2(
1535 CreateNamedPipe(kPipeName2
, PIPE_ACCESS_OUTBOUND
, 0, 1, 0, 0, 0, NULL
));
1536 ASSERT_TRUE(server1
.IsValid());
1537 ASSERT_TRUE(server2
.IsValid());
1539 Thread
thread("IOHandler test");
1540 Thread::Options options
;
1541 options
.message_loop_type
= MessageLoop::TYPE_IO
;
1542 ASSERT_TRUE(thread
.StartWithOptions(options
));
1544 MessageLoop
* thread_loop
= thread
.message_loop();
1545 ASSERT_TRUE(NULL
!= thread_loop
);
1547 TestIOHandler
handler1(kPipeName1
, callback1_called
, false);
1548 TestIOHandler
handler2(kPipeName2
, callback2_called
, true);
1549 thread_loop
->PostTask(FROM_HERE
, base::Bind(&TestIOHandler::Init
,
1550 base::Unretained(&handler1
)));
1551 // TODO(ajwong): Do we really need such long Sleeps in ths function?
1552 // Make sure the thread runs and sleeps for lack of work.
1553 TimeDelta delay
= TimeDelta::FromMilliseconds(100);
1554 base::PlatformThread::Sleep(delay
);
1555 thread_loop
->PostTask(FROM_HERE
, base::Bind(&TestIOHandler::Init
,
1556 base::Unretained(&handler2
)));
1557 base::PlatformThread::Sleep(delay
);
1559 // At this time handler1 is waiting to be called, and the thread is waiting
1560 // on the Init method of handler2, filtering only handler2 callbacks.
1562 const char buffer
[] = "Hello there!";
1564 EXPECT_TRUE(WriteFile(server1
, buffer
, sizeof(buffer
), &written
, NULL
));
1565 base::PlatformThread::Sleep(2 * delay
);
1566 EXPECT_EQ(WAIT_TIMEOUT
, WaitForSingleObject(callback1_called
, 0)) <<
1567 "handler1 has not been called";
1569 EXPECT_TRUE(WriteFile(server2
, buffer
, sizeof(buffer
), &written
, NULL
));
1571 HANDLE objects
[2] = { callback1_called
.Get(), callback2_called
.Get() };
1572 DWORD result
= WaitForMultipleObjects(2, objects
, TRUE
, 1000);
1573 EXPECT_EQ(WAIT_OBJECT_0
, result
);
1578 #endif // defined(OS_WIN)
1582 //-----------------------------------------------------------------------------
1583 // Each test is run against each type of MessageLoop. That way we are sure
1584 // that message loops work properly in all configurations. Of course, in some
1585 // cases, a unit test may only be for a particular type of loop.
1587 TEST(MessageLoopTest
, PostTask
) {
1588 RunTest_PostTask(MessageLoop::TYPE_DEFAULT
);
1589 RunTest_PostTask(MessageLoop::TYPE_UI
);
1590 RunTest_PostTask(MessageLoop::TYPE_IO
);
1593 TEST(MessageLoopTest
, PostTask_SEH
) {
1594 RunTest_PostTask_SEH(MessageLoop::TYPE_DEFAULT
);
1595 RunTest_PostTask_SEH(MessageLoop::TYPE_UI
);
1596 RunTest_PostTask_SEH(MessageLoop::TYPE_IO
);
1599 TEST(MessageLoopTest
, PostDelayedTask_Basic
) {
1600 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_DEFAULT
);
1601 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_UI
);
1602 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_IO
);
1605 TEST(MessageLoopTest
, PostDelayedTask_InDelayOrder
) {
1606 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_DEFAULT
);
1607 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_UI
);
1608 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_IO
);
1611 TEST(MessageLoopTest
, PostDelayedTask_InPostOrder
) {
1612 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_DEFAULT
);
1613 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_UI
);
1614 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_IO
);
1617 TEST(MessageLoopTest
, PostDelayedTask_InPostOrder_2
) {
1618 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_DEFAULT
);
1619 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_UI
);
1620 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_IO
);
1623 TEST(MessageLoopTest
, PostDelayedTask_InPostOrder_3
) {
1624 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_DEFAULT
);
1625 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_UI
);
1626 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_IO
);
1629 TEST(MessageLoopTest
, PostDelayedTask_SharedTimer
) {
1630 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_DEFAULT
);
1631 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_UI
);
1632 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_IO
);
1636 TEST(MessageLoopTest
, PostDelayedTask_SharedTimer_SubPump
) {
1637 RunTest_PostDelayedTask_SharedTimer_SubPump();
1641 // TODO(darin): MessageLoop does not support deleting all tasks in the
1643 // Fails, http://crbug.com/50272.
1644 TEST(MessageLoopTest
, DISABLED_EnsureDeletion
) {
1645 RunTest_EnsureDeletion(MessageLoop::TYPE_DEFAULT
);
1646 RunTest_EnsureDeletion(MessageLoop::TYPE_UI
);
1647 RunTest_EnsureDeletion(MessageLoop::TYPE_IO
);
1650 // TODO(darin): MessageLoop does not support deleting all tasks in the
1652 // Fails, http://crbug.com/50272.
1653 TEST(MessageLoopTest
, DISABLED_EnsureDeletion_Chain
) {
1654 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_DEFAULT
);
1655 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_UI
);
1656 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_IO
);
1660 TEST(MessageLoopTest
, Crasher
) {
1661 RunTest_Crasher(MessageLoop::TYPE_DEFAULT
);
1662 RunTest_Crasher(MessageLoop::TYPE_UI
);
1663 RunTest_Crasher(MessageLoop::TYPE_IO
);
1666 TEST(MessageLoopTest
, CrasherNasty
) {
1667 RunTest_CrasherNasty(MessageLoop::TYPE_DEFAULT
);
1668 RunTest_CrasherNasty(MessageLoop::TYPE_UI
);
1669 RunTest_CrasherNasty(MessageLoop::TYPE_IO
);
1671 #endif // defined(OS_WIN)
1673 TEST(MessageLoopTest
, Nesting
) {
1674 RunTest_Nesting(MessageLoop::TYPE_DEFAULT
);
1675 RunTest_Nesting(MessageLoop::TYPE_UI
);
1676 RunTest_Nesting(MessageLoop::TYPE_IO
);
1679 TEST(MessageLoopTest
, RecursiveDenial1
) {
1680 RunTest_RecursiveDenial1(MessageLoop::TYPE_DEFAULT
);
1681 RunTest_RecursiveDenial1(MessageLoop::TYPE_UI
);
1682 RunTest_RecursiveDenial1(MessageLoop::TYPE_IO
);
1685 TEST(MessageLoopTest
, RecursiveDenial3
) {
1686 RunTest_RecursiveDenial3(MessageLoop::TYPE_DEFAULT
);
1687 RunTest_RecursiveDenial3(MessageLoop::TYPE_UI
);
1688 RunTest_RecursiveDenial3(MessageLoop::TYPE_IO
);
1691 TEST(MessageLoopTest
, RecursiveSupport1
) {
1692 RunTest_RecursiveSupport1(MessageLoop::TYPE_DEFAULT
);
1693 RunTest_RecursiveSupport1(MessageLoop::TYPE_UI
);
1694 RunTest_RecursiveSupport1(MessageLoop::TYPE_IO
);
1698 // This test occasionally hangs http://crbug.com/44567
1699 TEST(MessageLoopTest
, DISABLED_RecursiveDenial2
) {
1700 RunTest_RecursiveDenial2(MessageLoop::TYPE_DEFAULT
);
1701 RunTest_RecursiveDenial2(MessageLoop::TYPE_UI
);
1702 RunTest_RecursiveDenial2(MessageLoop::TYPE_IO
);
1705 TEST(MessageLoopTest
, RecursiveSupport2
) {
1706 // This test requires a UI loop
1707 RunTest_RecursiveSupport2(MessageLoop::TYPE_UI
);
1709 #endif // defined(OS_WIN)
1711 TEST(MessageLoopTest
, NonNestableWithNoNesting
) {
1712 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_DEFAULT
);
1713 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_UI
);
1714 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_IO
);
1717 TEST(MessageLoopTest
, NonNestableInNestedLoop
) {
1718 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT
, false);
1719 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI
, false);
1720 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO
, false);
1723 TEST(MessageLoopTest
, NonNestableDelayedInNestedLoop
) {
1724 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT
, true);
1725 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI
, true);
1726 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO
, true);
1729 TEST(MessageLoopTest
, QuitNow
) {
1730 RunTest_QuitNow(MessageLoop::TYPE_DEFAULT
);
1731 RunTest_QuitNow(MessageLoop::TYPE_UI
);
1732 RunTest_QuitNow(MessageLoop::TYPE_IO
);
1735 TEST(MessageLoopTest
, RunLoopQuitTop
) {
1736 RunTest_RunLoopQuitTop(MessageLoop::TYPE_DEFAULT
);
1737 RunTest_RunLoopQuitTop(MessageLoop::TYPE_UI
);
1738 RunTest_RunLoopQuitTop(MessageLoop::TYPE_IO
);
1741 TEST(MessageLoopTest
, RunLoopQuitNested
) {
1742 RunTest_RunLoopQuitNested(MessageLoop::TYPE_DEFAULT
);
1743 RunTest_RunLoopQuitNested(MessageLoop::TYPE_UI
);
1744 RunTest_RunLoopQuitNested(MessageLoop::TYPE_IO
);
1747 TEST(MessageLoopTest
, RunLoopQuitBogus
) {
1748 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_DEFAULT
);
1749 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_UI
);
1750 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_IO
);
1753 TEST(MessageLoopTest
, RunLoopQuitDeep
) {
1754 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_DEFAULT
);
1755 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_UI
);
1756 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_IO
);
1759 TEST(MessageLoopTest
, RunLoopQuitOrderBefore
) {
1760 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_DEFAULT
);
1761 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_UI
);
1762 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_IO
);
1765 TEST(MessageLoopTest
, RunLoopQuitOrderDuring
) {
1766 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_DEFAULT
);
1767 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_UI
);
1768 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_IO
);
1771 TEST(MessageLoopTest
, RunLoopQuitOrderAfter
) {
1772 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_DEFAULT
);
1773 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_UI
);
1774 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_IO
);
1777 void PostNTasksThenQuit(int posts_remaining
) {
1778 if (posts_remaining
> 1) {
1779 MessageLoop::current()->PostTask(
1781 base::Bind(&PostNTasksThenQuit
, posts_remaining
- 1));
1783 MessageLoop::current()->Quit();
1787 class DummyTaskObserver
: public MessageLoop::TaskObserver
{
1789 explicit DummyTaskObserver(int num_tasks
)
1790 : num_tasks_started_(0),
1791 num_tasks_processed_(0),
1792 num_tasks_(num_tasks
) {}
1794 virtual ~DummyTaskObserver() {}
1796 virtual void WillProcessTask(TimeTicks time_posted
) OVERRIDE
{
1797 num_tasks_started_
++;
1798 EXPECT_TRUE(time_posted
!= TimeTicks());
1799 EXPECT_LE(num_tasks_started_
, num_tasks_
);
1800 EXPECT_EQ(num_tasks_started_
, num_tasks_processed_
+ 1);
1803 virtual void DidProcessTask(TimeTicks time_posted
) OVERRIDE
{
1804 num_tasks_processed_
++;
1805 EXPECT_TRUE(time_posted
!= TimeTicks());
1806 EXPECT_LE(num_tasks_started_
, num_tasks_
);
1807 EXPECT_EQ(num_tasks_started_
, num_tasks_processed_
);
1810 int num_tasks_started() const { return num_tasks_started_
; }
1811 int num_tasks_processed() const { return num_tasks_processed_
; }
1814 int num_tasks_started_
;
1815 int num_tasks_processed_
;
1816 const int num_tasks_
;
1818 DISALLOW_COPY_AND_ASSIGN(DummyTaskObserver
);
1821 TEST(MessageLoopTest
, TaskObserver
) {
1822 const int kNumPosts
= 6;
1823 DummyTaskObserver
observer(kNumPosts
);
1826 loop
.AddTaskObserver(&observer
);
1827 loop
.PostTask(FROM_HERE
, base::Bind(&PostNTasksThenQuit
, kNumPosts
));
1829 loop
.RemoveTaskObserver(&observer
);
1831 EXPECT_EQ(kNumPosts
, observer
.num_tasks_started());
1832 EXPECT_EQ(kNumPosts
, observer
.num_tasks_processed());
1836 TEST(MessageLoopTest
, Dispatcher
) {
1837 // This test requires a UI loop
1838 RunTest_Dispatcher(MessageLoop::TYPE_UI
);
1841 TEST(MessageLoopTest
, DispatcherWithMessageHook
) {
1842 // This test requires a UI loop
1843 RunTest_DispatcherWithMessageHook(MessageLoop::TYPE_UI
);
1846 TEST(MessageLoopTest
, IOHandler
) {
1847 RunTest_IOHandler();
1850 TEST(MessageLoopTest
, WaitForIO
) {
1851 RunTest_WaitForIO();
1854 TEST(MessageLoopTest
, HighResolutionTimer
) {
1857 const TimeDelta kFastTimer
= TimeDelta::FromMilliseconds(5);
1858 const TimeDelta kSlowTimer
= TimeDelta::FromMilliseconds(100);
1860 EXPECT_FALSE(loop
.high_resolution_timers_enabled());
1862 // Post a fast task to enable the high resolution timers.
1863 loop
.PostDelayedTask(FROM_HERE
, base::Bind(&PostNTasksThenQuit
, 1),
1866 EXPECT_TRUE(loop
.high_resolution_timers_enabled());
1868 // Post a slow task and verify high resolution timers
1869 // are still enabled.
1870 loop
.PostDelayedTask(FROM_HERE
, base::Bind(&PostNTasksThenQuit
, 1),
1873 EXPECT_TRUE(loop
.high_resolution_timers_enabled());
1875 // Wait for a while so that high-resolution mode elapses.
1876 base::PlatformThread::Sleep(TimeDelta::FromMilliseconds(
1877 MessageLoop::kHighResolutionTimerModeLeaseTimeMs
));
1879 // Post a slow task to disable the high resolution timers.
1880 loop
.PostDelayedTask(FROM_HERE
, base::Bind(&PostNTasksThenQuit
, 1),
1883 EXPECT_FALSE(loop
.high_resolution_timers_enabled());
1886 #endif // defined(OS_WIN)
1888 #if defined(OS_POSIX) && !defined(OS_NACL)
1892 class QuitDelegate
: public MessageLoopForIO::Watcher
{
1894 virtual void OnFileCanWriteWithoutBlocking(int fd
) OVERRIDE
{
1895 MessageLoop::current()->Quit();
1897 virtual void OnFileCanReadWithoutBlocking(int fd
) OVERRIDE
{
1898 MessageLoop::current()->Quit();
1902 TEST(MessageLoopTest
, FileDescriptorWatcherOutlivesMessageLoop
) {
1903 // Simulate a MessageLoop that dies before an FileDescriptorWatcher.
1904 // This could happen when people use the Singleton pattern or atexit.
1906 // Create a file descriptor. Doesn't need to be readable or writable,
1907 // as we don't need to actually get any notifications.
1908 // pipe() is just the easiest way to do it.
1910 int err
= pipe(pipefds
);
1912 int fd
= pipefds
[1];
1914 // Arrange for controller to live longer than message loop.
1915 MessageLoopForIO::FileDescriptorWatcher controller
;
1917 MessageLoopForIO message_loop
;
1919 QuitDelegate delegate
;
1920 message_loop
.WatchFileDescriptor(fd
,
1921 true, MessageLoopForIO::WATCH_WRITE
, &controller
, &delegate
);
1922 // and don't run the message loop, just destroy it.
1925 if (HANDLE_EINTR(close(pipefds
[0])) < 0)
1926 PLOG(ERROR
) << "close";
1927 if (HANDLE_EINTR(close(pipefds
[1])) < 0)
1928 PLOG(ERROR
) << "close";
1931 TEST(MessageLoopTest
, FileDescriptorWatcherDoubleStop
) {
1932 // Verify that it's ok to call StopWatchingFileDescriptor().
1933 // (Errors only showed up in valgrind.)
1935 int err
= pipe(pipefds
);
1937 int fd
= pipefds
[1];
1939 // Arrange for message loop to live longer than controller.
1940 MessageLoopForIO message_loop
;
1942 MessageLoopForIO::FileDescriptorWatcher controller
;
1944 QuitDelegate delegate
;
1945 message_loop
.WatchFileDescriptor(fd
,
1946 true, MessageLoopForIO::WATCH_WRITE
, &controller
, &delegate
);
1947 controller
.StopWatchingFileDescriptor();
1950 if (HANDLE_EINTR(close(pipefds
[0])) < 0)
1951 PLOG(ERROR
) << "close";
1952 if (HANDLE_EINTR(close(pipefds
[1])) < 0)
1953 PLOG(ERROR
) << "close";
1958 #endif // defined(OS_POSIX) && !defined(OS_NACL)
1961 // Inject a test point for recording the destructor calls for Closure objects
1962 // send to MessageLoop::PostTask(). It is awkward usage since we are trying to
1963 // hook the actual destruction, which is not a common operation.
1964 class DestructionObserverProbe
:
1965 public base::RefCounted
<DestructionObserverProbe
> {
1967 DestructionObserverProbe(bool* task_destroyed
,
1968 bool* destruction_observer_called
)
1969 : task_destroyed_(task_destroyed
),
1970 destruction_observer_called_(destruction_observer_called
) {
1972 virtual void Run() {
1973 // This task should never run.
1977 friend class base::RefCounted
<DestructionObserverProbe
>;
1979 virtual ~DestructionObserverProbe() {
1980 EXPECT_FALSE(*destruction_observer_called_
);
1981 *task_destroyed_
= true;
1984 bool* task_destroyed_
;
1985 bool* destruction_observer_called_
;
1988 class MLDestructionObserver
: public MessageLoop::DestructionObserver
{
1990 MLDestructionObserver(bool* task_destroyed
, bool* destruction_observer_called
)
1991 : task_destroyed_(task_destroyed
),
1992 destruction_observer_called_(destruction_observer_called
),
1993 task_destroyed_before_message_loop_(false) {
1995 virtual void WillDestroyCurrentMessageLoop() OVERRIDE
{
1996 task_destroyed_before_message_loop_
= *task_destroyed_
;
1997 *destruction_observer_called_
= true;
1999 bool task_destroyed_before_message_loop() const {
2000 return task_destroyed_before_message_loop_
;
2003 bool* task_destroyed_
;
2004 bool* destruction_observer_called_
;
2005 bool task_destroyed_before_message_loop_
;
2010 TEST(MessageLoopTest
, DestructionObserverTest
) {
2011 // Verify that the destruction observer gets called at the very end (after
2012 // all the pending tasks have been destroyed).
2013 MessageLoop
* loop
= new MessageLoop
;
2014 const TimeDelta kDelay
= TimeDelta::FromMilliseconds(100);
2016 bool task_destroyed
= false;
2017 bool destruction_observer_called
= false;
2019 MLDestructionObserver
observer(&task_destroyed
, &destruction_observer_called
);
2020 loop
->AddDestructionObserver(&observer
);
2021 loop
->PostDelayedTask(
2023 base::Bind(&DestructionObserverProbe::Run
,
2024 new DestructionObserverProbe(&task_destroyed
,
2025 &destruction_observer_called
)),
2028 EXPECT_TRUE(observer
.task_destroyed_before_message_loop());
2029 // The task should have been destroyed when we deleted the loop.
2030 EXPECT_TRUE(task_destroyed
);
2031 EXPECT_TRUE(destruction_observer_called
);
2035 // Verify that MessageLoop sets ThreadMainTaskRunner::current() and it
2036 // posts tasks on that message loop.
2037 TEST(MessageLoopTest
, ThreadMainTaskRunner
) {
2040 scoped_refptr
<Foo
> foo(new Foo());
2042 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE
, base::Bind(
2043 &Foo::Test1ConstRef
, foo
.get(), a
));
2046 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
2047 &MessageLoop::Quit
, base::Unretained(MessageLoop::current())));
2049 // Now kick things off
2050 MessageLoop::current()->Run();
2052 EXPECT_EQ(foo
->test_count(), 1);
2053 EXPECT_EQ(foo
->result(), "a");
2056 TEST(MessageLoopTest
, IsType
) {
2057 MessageLoop
loop(MessageLoop::TYPE_UI
);
2058 EXPECT_TRUE(loop
.IsType(MessageLoop::TYPE_UI
));
2059 EXPECT_FALSE(loop
.IsType(MessageLoop::TYPE_IO
));
2060 EXPECT_FALSE(loop
.IsType(MessageLoop::TYPE_DEFAULT
));