Add support for indeterminate checkbox on Windows classic theme.
[chromium-blink-merge.git] / base / message_loop_unittest.cc
blob5a90a6f5dd465f7eb352b268aaed9b66fb90de91
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <vector>
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/compiler_specific.h"
10 #include "base/logging.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/message_loop.h"
13 #include "base/pending_task.h"
14 #include "base/posix/eintr_wrapper.h"
15 #include "base/run_loop.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/threading/platform_thread.h"
18 #include "base/threading/thread.h"
19 #include "testing/gtest/include/gtest/gtest.h"
21 #if defined(OS_WIN)
22 #include "base/message_pump_win.h"
23 #include "base/win/scoped_handle.h"
24 #endif
26 namespace base {
28 // TODO(darin): Platform-specific MessageLoop tests should be grouped together
29 // to avoid chopping this file up with so many #ifdefs.
31 namespace {
33 class Foo : public RefCounted<Foo> {
34 public:
35 Foo() : test_count_(0) {
38 void Test0() {
39 ++test_count_;
42 void Test1ConstRef(const std::string& a) {
43 ++test_count_;
44 result_.append(a);
47 void Test1Ptr(std::string* a) {
48 ++test_count_;
49 result_.append(*a);
52 void Test1Int(int a) {
53 test_count_ += a;
56 void Test2Ptr(std::string* a, std::string* b) {
57 ++test_count_;
58 result_.append(*a);
59 result_.append(*b);
62 void Test2Mixed(const std::string& a, std::string* b) {
63 ++test_count_;
64 result_.append(a);
65 result_.append(*b);
68 int test_count() const { return test_count_; }
69 const std::string& result() const { return result_; }
71 private:
72 friend class RefCounted<Foo>;
74 ~Foo() {}
76 int test_count_;
77 std::string result_;
80 void RunTest_PostTask(MessageLoop::Type message_loop_type) {
81 MessageLoop loop(message_loop_type);
83 // Add tests to message loop
84 scoped_refptr<Foo> foo(new Foo());
85 std::string a("a"), b("b"), c("c"), d("d");
86 MessageLoop::current()->PostTask(FROM_HERE, Bind(
87 &Foo::Test0, foo.get()));
88 MessageLoop::current()->PostTask(FROM_HERE, Bind(
89 &Foo::Test1ConstRef, foo.get(), a));
90 MessageLoop::current()->PostTask(FROM_HERE, Bind(
91 &Foo::Test1Ptr, foo.get(), &b));
92 MessageLoop::current()->PostTask(FROM_HERE, Bind(
93 &Foo::Test1Int, foo.get(), 100));
94 MessageLoop::current()->PostTask(FROM_HERE, Bind(
95 &Foo::Test2Ptr, foo.get(), &a, &c));
96 MessageLoop::current()->PostTask(FROM_HERE, Bind(
97 &Foo::Test2Mixed, foo.get(), a, &d));
99 // After all tests, post a message that will shut down the message loop
100 MessageLoop::current()->PostTask(FROM_HERE, Bind(
101 &MessageLoop::Quit, Unretained(MessageLoop::current())));
103 // Now kick things off
104 MessageLoop::current()->Run();
106 EXPECT_EQ(foo->test_count(), 105);
107 EXPECT_EQ(foo->result(), "abacad");
110 void RunTest_PostTask_SEH(MessageLoop::Type message_loop_type) {
111 MessageLoop loop(message_loop_type);
113 // Add tests to message loop
114 scoped_refptr<Foo> foo(new Foo());
115 std::string a("a"), b("b"), c("c"), d("d");
116 MessageLoop::current()->PostTask(FROM_HERE, Bind(
117 &Foo::Test0, foo.get()));
118 MessageLoop::current()->PostTask(FROM_HERE, Bind(
119 &Foo::Test1ConstRef, foo.get(), a));
120 MessageLoop::current()->PostTask(FROM_HERE, Bind(
121 &Foo::Test1Ptr, foo.get(), &b));
122 MessageLoop::current()->PostTask(FROM_HERE, Bind(
123 &Foo::Test1Int, foo.get(), 100));
124 MessageLoop::current()->PostTask(FROM_HERE, Bind(
125 &Foo::Test2Ptr, foo.get(), &a, &c));
126 MessageLoop::current()->PostTask(FROM_HERE, Bind(
127 &Foo::Test2Mixed, foo.get(), a, &d));
129 // After all tests, post a message that will shut down the message loop
130 MessageLoop::current()->PostTask(FROM_HERE, Bind(
131 &MessageLoop::Quit, Unretained(MessageLoop::current())));
133 // Now kick things off with the SEH block active.
134 MessageLoop::current()->set_exception_restoration(true);
135 MessageLoop::current()->Run();
136 MessageLoop::current()->set_exception_restoration(false);
138 EXPECT_EQ(foo->test_count(), 105);
139 EXPECT_EQ(foo->result(), "abacad");
142 // This function runs slowly to simulate a large amount of work being done.
143 static void SlowFunc(TimeDelta pause, int* quit_counter) {
144 PlatformThread::Sleep(pause);
145 if (--(*quit_counter) == 0)
146 MessageLoop::current()->QuitWhenIdle();
149 // This function records the time when Run was called in a Time object, which is
150 // useful for building a variety of MessageLoop tests.
151 static void RecordRunTimeFunc(Time* run_time, int* quit_counter) {
152 *run_time = Time::Now();
154 // Cause our Run function to take some time to execute. As a result we can
155 // count on subsequent RecordRunTimeFunc()s running at a future time,
156 // without worry about the resolution of our system clock being an issue.
157 SlowFunc(TimeDelta::FromMilliseconds(10), quit_counter);
160 void RunTest_PostDelayedTask_Basic(MessageLoop::Type message_loop_type) {
161 MessageLoop loop(message_loop_type);
163 // Test that PostDelayedTask results in a delayed task.
165 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
167 int num_tasks = 1;
168 Time run_time;
170 loop.PostDelayedTask(
171 FROM_HERE, Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
172 kDelay);
174 Time time_before_run = Time::Now();
175 loop.Run();
176 Time time_after_run = Time::Now();
178 EXPECT_EQ(0, num_tasks);
179 EXPECT_LT(kDelay, time_after_run - time_before_run);
182 void RunTest_PostDelayedTask_InDelayOrder(
183 MessageLoop::Type message_loop_type) {
184 MessageLoop loop(message_loop_type);
186 // Test that two tasks with different delays run in the right order.
187 int num_tasks = 2;
188 Time run_time1, run_time2;
190 loop.PostDelayedTask(
191 FROM_HERE,
192 Bind(&RecordRunTimeFunc, &run_time1, &num_tasks),
193 TimeDelta::FromMilliseconds(200));
194 // If we get a large pause in execution (due to a context switch) here, this
195 // test could fail.
196 loop.PostDelayedTask(
197 FROM_HERE,
198 Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
199 TimeDelta::FromMilliseconds(10));
201 loop.Run();
202 EXPECT_EQ(0, num_tasks);
204 EXPECT_TRUE(run_time2 < run_time1);
207 void RunTest_PostDelayedTask_InPostOrder(
208 MessageLoop::Type message_loop_type) {
209 MessageLoop loop(message_loop_type);
211 // Test that two tasks with the same delay run in the order in which they
212 // were posted.
214 // NOTE: This is actually an approximate test since the API only takes a
215 // "delay" parameter, so we are not exactly simulating two tasks that get
216 // posted at the exact same time. It would be nice if the API allowed us to
217 // specify the desired run time.
219 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
221 int num_tasks = 2;
222 Time run_time1, run_time2;
224 loop.PostDelayedTask(
225 FROM_HERE,
226 Bind(&RecordRunTimeFunc, &run_time1, &num_tasks), kDelay);
227 loop.PostDelayedTask(
228 FROM_HERE,
229 Bind(&RecordRunTimeFunc, &run_time2, &num_tasks), kDelay);
231 loop.Run();
232 EXPECT_EQ(0, num_tasks);
234 EXPECT_TRUE(run_time1 < run_time2);
237 void RunTest_PostDelayedTask_InPostOrder_2(
238 MessageLoop::Type message_loop_type) {
239 MessageLoop loop(message_loop_type);
241 // Test that a delayed task still runs after a normal tasks even if the
242 // normal tasks take a long time to run.
244 const TimeDelta kPause = TimeDelta::FromMilliseconds(50);
246 int num_tasks = 2;
247 Time run_time;
249 loop.PostTask(FROM_HERE, Bind(&SlowFunc, kPause, &num_tasks));
250 loop.PostDelayedTask(
251 FROM_HERE,
252 Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
253 TimeDelta::FromMilliseconds(10));
255 Time time_before_run = Time::Now();
256 loop.Run();
257 Time time_after_run = Time::Now();
259 EXPECT_EQ(0, num_tasks);
261 EXPECT_LT(kPause, time_after_run - time_before_run);
264 void RunTest_PostDelayedTask_InPostOrder_3(
265 MessageLoop::Type message_loop_type) {
266 MessageLoop loop(message_loop_type);
268 // Test that a delayed task still runs after a pile of normal tasks. The key
269 // difference between this test and the previous one is that here we return
270 // the MessageLoop a lot so we give the MessageLoop plenty of opportunities
271 // to maybe run the delayed task. It should know not to do so until the
272 // delayed task's delay has passed.
274 int num_tasks = 11;
275 Time run_time1, run_time2;
277 // Clutter the ML with tasks.
278 for (int i = 1; i < num_tasks; ++i)
279 loop.PostTask(FROM_HERE,
280 Bind(&RecordRunTimeFunc, &run_time1, &num_tasks));
282 loop.PostDelayedTask(
283 FROM_HERE, Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
284 TimeDelta::FromMilliseconds(1));
286 loop.Run();
287 EXPECT_EQ(0, num_tasks);
289 EXPECT_TRUE(run_time2 > run_time1);
292 void RunTest_PostDelayedTask_SharedTimer(
293 MessageLoop::Type message_loop_type) {
294 MessageLoop loop(message_loop_type);
296 // Test that the interval of the timer, used to run the next delayed task, is
297 // set to a value corresponding to when the next delayed task should run.
299 // By setting num_tasks to 1, we ensure that the first task to run causes the
300 // run loop to exit.
301 int num_tasks = 1;
302 Time run_time1, run_time2;
304 loop.PostDelayedTask(
305 FROM_HERE,
306 Bind(&RecordRunTimeFunc, &run_time1, &num_tasks),
307 TimeDelta::FromSeconds(1000));
308 loop.PostDelayedTask(
309 FROM_HERE,
310 Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
311 TimeDelta::FromMilliseconds(10));
313 Time start_time = Time::Now();
315 loop.Run();
316 EXPECT_EQ(0, num_tasks);
318 // Ensure that we ran in far less time than the slower timer.
319 TimeDelta total_time = Time::Now() - start_time;
320 EXPECT_GT(5000, total_time.InMilliseconds());
322 // In case both timers somehow run at nearly the same time, sleep a little
323 // and then run all pending to force them both to have run. This is just
324 // encouraging flakiness if there is any.
325 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
326 RunLoop().RunUntilIdle();
328 EXPECT_TRUE(run_time1.is_null());
329 EXPECT_FALSE(run_time2.is_null());
332 #if defined(OS_WIN)
334 void SubPumpFunc() {
335 MessageLoop::current()->SetNestableTasksAllowed(true);
336 MSG msg;
337 while (GetMessage(&msg, NULL, 0, 0)) {
338 TranslateMessage(&msg);
339 DispatchMessage(&msg);
341 MessageLoop::current()->QuitWhenIdle();
344 void RunTest_PostDelayedTask_SharedTimer_SubPump() {
345 MessageLoop loop(MessageLoop::TYPE_UI);
347 // Test that the interval of the timer, used to run the next delayed task, is
348 // set to a value corresponding to when the next delayed task should run.
350 // By setting num_tasks to 1, we ensure that the first task to run causes the
351 // run loop to exit.
352 int num_tasks = 1;
353 Time run_time;
355 loop.PostTask(FROM_HERE, Bind(&SubPumpFunc));
357 // This very delayed task should never run.
358 loop.PostDelayedTask(
359 FROM_HERE,
360 Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
361 TimeDelta::FromSeconds(1000));
363 // This slightly delayed task should run from within SubPumpFunc).
364 loop.PostDelayedTask(
365 FROM_HERE,
366 Bind(&PostQuitMessage, 0),
367 TimeDelta::FromMilliseconds(10));
369 Time start_time = Time::Now();
371 loop.Run();
372 EXPECT_EQ(1, num_tasks);
374 // Ensure that we ran in far less time than the slower timer.
375 TimeDelta total_time = Time::Now() - start_time;
376 EXPECT_GT(5000, total_time.InMilliseconds());
378 // In case both timers somehow run at nearly the same time, sleep a little
379 // and then run all pending to force them both to have run. This is just
380 // encouraging flakiness if there is any.
381 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
382 RunLoop().RunUntilIdle();
384 EXPECT_TRUE(run_time.is_null());
387 #endif // defined(OS_WIN)
389 // This is used to inject a test point for recording the destructor calls for
390 // Closure objects send to MessageLoop::PostTask(). It is awkward usage since we
391 // are trying to hook the actual destruction, which is not a common operation.
392 class RecordDeletionProbe : public RefCounted<RecordDeletionProbe> {
393 public:
394 RecordDeletionProbe(RecordDeletionProbe* post_on_delete, bool* was_deleted)
395 : post_on_delete_(post_on_delete), was_deleted_(was_deleted) {
397 void Run() {}
399 private:
400 friend class RefCounted<RecordDeletionProbe>;
402 ~RecordDeletionProbe() {
403 *was_deleted_ = true;
404 if (post_on_delete_)
405 MessageLoop::current()->PostTask(
406 FROM_HERE,
407 Bind(&RecordDeletionProbe::Run, post_on_delete_.get()));
410 scoped_refptr<RecordDeletionProbe> post_on_delete_;
411 bool* was_deleted_;
414 void RunTest_EnsureDeletion(MessageLoop::Type message_loop_type) {
415 bool a_was_deleted = false;
416 bool b_was_deleted = false;
418 MessageLoop loop(message_loop_type);
419 loop.PostTask(
420 FROM_HERE, Bind(&RecordDeletionProbe::Run,
421 new RecordDeletionProbe(NULL, &a_was_deleted)));
422 // TODO(ajwong): Do we really need 1000ms here?
423 loop.PostDelayedTask(
424 FROM_HERE, Bind(&RecordDeletionProbe::Run,
425 new RecordDeletionProbe(NULL, &b_was_deleted)),
426 TimeDelta::FromMilliseconds(1000));
428 EXPECT_TRUE(a_was_deleted);
429 EXPECT_TRUE(b_was_deleted);
432 void RunTest_EnsureDeletion_Chain(MessageLoop::Type message_loop_type) {
433 bool a_was_deleted = false;
434 bool b_was_deleted = false;
435 bool c_was_deleted = false;
437 MessageLoop loop(message_loop_type);
438 // The scoped_refptr for each of the below is held either by the chained
439 // RecordDeletionProbe, or the bound RecordDeletionProbe::Run() callback.
440 RecordDeletionProbe* a = new RecordDeletionProbe(NULL, &a_was_deleted);
441 RecordDeletionProbe* b = new RecordDeletionProbe(a, &b_was_deleted);
442 RecordDeletionProbe* c = new RecordDeletionProbe(b, &c_was_deleted);
443 loop.PostTask(FROM_HERE, Bind(&RecordDeletionProbe::Run, c));
445 EXPECT_TRUE(a_was_deleted);
446 EXPECT_TRUE(b_was_deleted);
447 EXPECT_TRUE(c_was_deleted);
450 void NestingFunc(int* depth) {
451 if (*depth > 0) {
452 *depth -= 1;
453 MessageLoop::current()->PostTask(FROM_HERE,
454 Bind(&NestingFunc, depth));
456 MessageLoop::current()->SetNestableTasksAllowed(true);
457 MessageLoop::current()->Run();
459 MessageLoop::current()->QuitWhenIdle();
462 #if defined(OS_WIN)
464 LONG WINAPI BadExceptionHandler(EXCEPTION_POINTERS *ex_info) {
465 ADD_FAILURE() << "bad exception handler";
466 ::ExitProcess(ex_info->ExceptionRecord->ExceptionCode);
467 return EXCEPTION_EXECUTE_HANDLER;
470 // This task throws an SEH exception: initially write to an invalid address.
471 // If the right SEH filter is installed, it will fix the error.
472 class Crasher : public RefCounted<Crasher> {
473 public:
474 // Ctor. If trash_SEH_handler is true, the task will override the unhandled
475 // exception handler with one sure to crash this test.
476 explicit Crasher(bool trash_SEH_handler)
477 : trash_SEH_handler_(trash_SEH_handler) {
480 void Run() {
481 PlatformThread::Sleep(TimeDelta::FromMilliseconds(1));
482 if (trash_SEH_handler_)
483 ::SetUnhandledExceptionFilter(&BadExceptionHandler);
484 // Generate a SEH fault. We do it in asm to make sure we know how to undo
485 // the damage.
487 #if defined(_M_IX86)
489 __asm {
490 mov eax, dword ptr [Crasher::bad_array_]
491 mov byte ptr [eax], 66
494 #elif defined(_M_X64)
496 bad_array_[0] = 66;
498 #else
499 #error "needs architecture support"
500 #endif
502 MessageLoop::current()->QuitWhenIdle();
504 // Points the bad array to a valid memory location.
505 static void FixError() {
506 bad_array_ = &valid_store_;
509 private:
510 bool trash_SEH_handler_;
511 static volatile char* bad_array_;
512 static char valid_store_;
515 volatile char* Crasher::bad_array_ = 0;
516 char Crasher::valid_store_ = 0;
518 // This SEH filter fixes the problem and retries execution. Fixing requires
519 // that the last instruction: mov eax, [Crasher::bad_array_] to be retried
520 // so we move the instruction pointer 5 bytes back.
521 LONG WINAPI HandleCrasherException(EXCEPTION_POINTERS *ex_info) {
522 if (ex_info->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION)
523 return EXCEPTION_EXECUTE_HANDLER;
525 Crasher::FixError();
527 #if defined(_M_IX86)
529 ex_info->ContextRecord->Eip -= 5;
531 #elif defined(_M_X64)
533 ex_info->ContextRecord->Rip -= 5;
535 #endif
537 return EXCEPTION_CONTINUE_EXECUTION;
540 void RunTest_Crasher(MessageLoop::Type message_loop_type) {
541 MessageLoop loop(message_loop_type);
543 if (::IsDebuggerPresent())
544 return;
546 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter =
547 ::SetUnhandledExceptionFilter(&HandleCrasherException);
549 MessageLoop::current()->PostTask(
550 FROM_HERE,
551 Bind(&Crasher::Run, new Crasher(false)));
552 MessageLoop::current()->set_exception_restoration(true);
553 MessageLoop::current()->Run();
554 MessageLoop::current()->set_exception_restoration(false);
556 ::SetUnhandledExceptionFilter(old_SEH_filter);
559 void RunTest_CrasherNasty(MessageLoop::Type message_loop_type) {
560 MessageLoop loop(message_loop_type);
562 if (::IsDebuggerPresent())
563 return;
565 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter =
566 ::SetUnhandledExceptionFilter(&HandleCrasherException);
568 MessageLoop::current()->PostTask(
569 FROM_HERE,
570 Bind(&Crasher::Run, new Crasher(true)));
571 MessageLoop::current()->set_exception_restoration(true);
572 MessageLoop::current()->Run();
573 MessageLoop::current()->set_exception_restoration(false);
575 ::SetUnhandledExceptionFilter(old_SEH_filter);
578 #endif // defined(OS_WIN)
580 void RunTest_Nesting(MessageLoop::Type message_loop_type) {
581 MessageLoop loop(message_loop_type);
583 int depth = 100;
584 MessageLoop::current()->PostTask(FROM_HERE,
585 Bind(&NestingFunc, &depth));
586 MessageLoop::current()->Run();
587 EXPECT_EQ(depth, 0);
590 const wchar_t* const kMessageBoxTitle = L"MessageLoop Unit Test";
592 enum TaskType {
593 MESSAGEBOX,
594 ENDDIALOG,
595 RECURSIVE,
596 TIMEDMESSAGELOOP,
597 QUITMESSAGELOOP,
598 ORDERED,
599 PUMPS,
600 SLEEP,
601 RUNS,
604 // Saves the order in which the tasks executed.
605 struct TaskItem {
606 TaskItem(TaskType t, int c, bool s)
607 : type(t),
608 cookie(c),
609 start(s) {
612 TaskType type;
613 int cookie;
614 bool start;
616 bool operator == (const TaskItem& other) const {
617 return type == other.type && cookie == other.cookie && start == other.start;
621 std::ostream& operator <<(std::ostream& os, TaskType type) {
622 switch (type) {
623 case MESSAGEBOX: os << "MESSAGEBOX"; break;
624 case ENDDIALOG: os << "ENDDIALOG"; break;
625 case RECURSIVE: os << "RECURSIVE"; break;
626 case TIMEDMESSAGELOOP: os << "TIMEDMESSAGELOOP"; break;
627 case QUITMESSAGELOOP: os << "QUITMESSAGELOOP"; break;
628 case ORDERED: os << "ORDERED"; break;
629 case PUMPS: os << "PUMPS"; break;
630 case SLEEP: os << "SLEEP"; break;
631 default:
632 NOTREACHED();
633 os << "Unknown TaskType";
634 break;
636 return os;
639 std::ostream& operator <<(std::ostream& os, const TaskItem& item) {
640 if (item.start)
641 return os << item.type << " " << item.cookie << " starts";
642 else
643 return os << item.type << " " << item.cookie << " ends";
646 class TaskList {
647 public:
648 void RecordStart(TaskType type, int cookie) {
649 TaskItem item(type, cookie, true);
650 DVLOG(1) << item;
651 task_list_.push_back(item);
654 void RecordEnd(TaskType type, int cookie) {
655 TaskItem item(type, cookie, false);
656 DVLOG(1) << item;
657 task_list_.push_back(item);
660 size_t Size() {
661 return task_list_.size();
664 TaskItem Get(int n) {
665 return task_list_[n];
668 private:
669 std::vector<TaskItem> task_list_;
672 // Saves the order the tasks ran.
673 void OrderedFunc(TaskList* order, int cookie) {
674 order->RecordStart(ORDERED, cookie);
675 order->RecordEnd(ORDERED, cookie);
678 #if defined(OS_WIN)
680 // MessageLoop implicitly start a "modal message loop". Modal dialog boxes,
681 // common controls (like OpenFile) and StartDoc printing function can cause
682 // implicit message loops.
683 void MessageBoxFunc(TaskList* order, int cookie, bool is_reentrant) {
684 order->RecordStart(MESSAGEBOX, cookie);
685 if (is_reentrant)
686 MessageLoop::current()->SetNestableTasksAllowed(true);
687 MessageBox(NULL, L"Please wait...", kMessageBoxTitle, MB_OK);
688 order->RecordEnd(MESSAGEBOX, cookie);
691 // Will end the MessageBox.
692 void EndDialogFunc(TaskList* order, int cookie) {
693 order->RecordStart(ENDDIALOG, cookie);
694 HWND window = GetActiveWindow();
695 if (window != NULL) {
696 EXPECT_NE(EndDialog(window, IDCONTINUE), 0);
697 // Cheap way to signal that the window wasn't found if RunEnd() isn't
698 // called.
699 order->RecordEnd(ENDDIALOG, cookie);
703 #endif // defined(OS_WIN)
705 void RecursiveFunc(TaskList* order, int cookie, int depth,
706 bool is_reentrant) {
707 order->RecordStart(RECURSIVE, cookie);
708 if (depth > 0) {
709 if (is_reentrant)
710 MessageLoop::current()->SetNestableTasksAllowed(true);
711 MessageLoop::current()->PostTask(
712 FROM_HERE,
713 Bind(&RecursiveFunc, order, cookie, depth - 1, is_reentrant));
715 order->RecordEnd(RECURSIVE, cookie);
718 void RecursiveSlowFunc(TaskList* order, int cookie, int depth,
719 bool is_reentrant) {
720 RecursiveFunc(order, cookie, depth, is_reentrant);
721 PlatformThread::Sleep(TimeDelta::FromMilliseconds(10));
724 void QuitFunc(TaskList* order, int cookie) {
725 order->RecordStart(QUITMESSAGELOOP, cookie);
726 MessageLoop::current()->QuitWhenIdle();
727 order->RecordEnd(QUITMESSAGELOOP, cookie);
730 void SleepFunc(TaskList* order, int cookie, TimeDelta delay) {
731 order->RecordStart(SLEEP, cookie);
732 PlatformThread::Sleep(delay);
733 order->RecordEnd(SLEEP, cookie);
736 #if defined(OS_WIN)
737 void RecursiveFuncWin(MessageLoop* target,
738 HANDLE event,
739 bool expect_window,
740 TaskList* order,
741 bool is_reentrant) {
742 target->PostTask(FROM_HERE,
743 Bind(&RecursiveFunc, order, 1, 2, is_reentrant));
744 target->PostTask(FROM_HERE,
745 Bind(&MessageBoxFunc, order, 2, is_reentrant));
746 target->PostTask(FROM_HERE,
747 Bind(&RecursiveFunc, order, 3, 2, is_reentrant));
748 // The trick here is that for recursive task processing, this task will be
749 // ran _inside_ the MessageBox message loop, dismissing the MessageBox
750 // without a chance.
751 // For non-recursive task processing, this will be executed _after_ the
752 // MessageBox will have been dismissed by the code below, where
753 // expect_window_ is true.
754 target->PostTask(FROM_HERE,
755 Bind(&EndDialogFunc, order, 4));
756 target->PostTask(FROM_HERE,
757 Bind(&QuitFunc, order, 5));
759 // Enforce that every tasks are sent before starting to run the main thread
760 // message loop.
761 ASSERT_TRUE(SetEvent(event));
763 // Poll for the MessageBox. Don't do this at home! At the speed we do it,
764 // you will never realize one MessageBox was shown.
765 for (; expect_window;) {
766 HWND window = FindWindow(L"#32770", kMessageBoxTitle);
767 if (window) {
768 // Dismiss it.
769 for (;;) {
770 HWND button = FindWindowEx(window, NULL, L"Button", NULL);
771 if (button != NULL) {
772 EXPECT_EQ(0, SendMessage(button, WM_LBUTTONDOWN, 0, 0));
773 EXPECT_EQ(0, SendMessage(button, WM_LBUTTONUP, 0, 0));
774 break;
777 break;
782 #endif // defined(OS_WIN)
784 void RunTest_RecursiveDenial1(MessageLoop::Type message_loop_type) {
785 MessageLoop loop(message_loop_type);
787 EXPECT_TRUE(MessageLoop::current()->NestableTasksAllowed());
788 TaskList order;
789 MessageLoop::current()->PostTask(
790 FROM_HERE,
791 Bind(&RecursiveFunc, &order, 1, 2, false));
792 MessageLoop::current()->PostTask(
793 FROM_HERE,
794 Bind(&RecursiveFunc, &order, 2, 2, false));
795 MessageLoop::current()->PostTask(
796 FROM_HERE,
797 Bind(&QuitFunc, &order, 3));
799 MessageLoop::current()->Run();
801 // FIFO order.
802 ASSERT_EQ(14U, order.Size());
803 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
804 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
805 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
806 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
807 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
808 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
809 EXPECT_EQ(order.Get(6), TaskItem(RECURSIVE, 1, true));
810 EXPECT_EQ(order.Get(7), TaskItem(RECURSIVE, 1, false));
811 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
812 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
813 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
814 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
815 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 2, true));
816 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 2, false));
819 void RunTest_RecursiveDenial3(MessageLoop::Type message_loop_type) {
820 MessageLoop loop(message_loop_type);
822 EXPECT_TRUE(MessageLoop::current()->NestableTasksAllowed());
823 TaskList order;
824 MessageLoop::current()->PostTask(
825 FROM_HERE, Bind(&RecursiveSlowFunc, &order, 1, 2, false));
826 MessageLoop::current()->PostTask(
827 FROM_HERE, Bind(&RecursiveSlowFunc, &order, 2, 2, false));
828 MessageLoop::current()->PostDelayedTask(
829 FROM_HERE,
830 Bind(&OrderedFunc, &order, 3),
831 TimeDelta::FromMilliseconds(5));
832 MessageLoop::current()->PostDelayedTask(
833 FROM_HERE,
834 Bind(&QuitFunc, &order, 4),
835 TimeDelta::FromMilliseconds(5));
837 MessageLoop::current()->Run();
839 // FIFO order.
840 ASSERT_EQ(16U, order.Size());
841 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
842 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
843 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
844 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
845 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 1, true));
846 EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 1, false));
847 EXPECT_EQ(order.Get(6), TaskItem(ORDERED, 3, true));
848 EXPECT_EQ(order.Get(7), TaskItem(ORDERED, 3, false));
849 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
850 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
851 EXPECT_EQ(order.Get(10), TaskItem(QUITMESSAGELOOP, 4, true));
852 EXPECT_EQ(order.Get(11), TaskItem(QUITMESSAGELOOP, 4, false));
853 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 1, true));
854 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, false));
855 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 2, true));
856 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 2, false));
859 void RunTest_RecursiveSupport1(MessageLoop::Type message_loop_type) {
860 MessageLoop loop(message_loop_type);
862 TaskList order;
863 MessageLoop::current()->PostTask(
864 FROM_HERE, Bind(&RecursiveFunc, &order, 1, 2, true));
865 MessageLoop::current()->PostTask(
866 FROM_HERE, Bind(&RecursiveFunc, &order, 2, 2, true));
867 MessageLoop::current()->PostTask(
868 FROM_HERE, Bind(&QuitFunc, &order, 3));
870 MessageLoop::current()->Run();
872 // FIFO order.
873 ASSERT_EQ(14U, order.Size());
874 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
875 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
876 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
877 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
878 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
879 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
880 EXPECT_EQ(order.Get(6), TaskItem(RECURSIVE, 1, true));
881 EXPECT_EQ(order.Get(7), TaskItem(RECURSIVE, 1, false));
882 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
883 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
884 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
885 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
886 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 2, true));
887 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 2, false));
890 #if defined(OS_WIN)
891 // TODO(darin): These tests need to be ported since they test critical
892 // message loop functionality.
894 // A side effect of this test is the generation a beep. Sorry.
895 void RunTest_RecursiveDenial2(MessageLoop::Type message_loop_type) {
896 MessageLoop loop(message_loop_type);
898 Thread worker("RecursiveDenial2_worker");
899 Thread::Options options;
900 options.message_loop_type = message_loop_type;
901 ASSERT_EQ(true, worker.StartWithOptions(options));
902 TaskList order;
903 win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
904 worker.message_loop()->PostTask(FROM_HERE,
905 Bind(&RecursiveFuncWin,
906 MessageLoop::current(),
907 event.Get(),
908 true,
909 &order,
910 false));
911 // Let the other thread execute.
912 WaitForSingleObject(event, INFINITE);
913 MessageLoop::current()->Run();
915 ASSERT_EQ(order.Size(), 17);
916 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
917 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
918 EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
919 EXPECT_EQ(order.Get(3), TaskItem(MESSAGEBOX, 2, false));
920 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, true));
921 EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 3, false));
922 // When EndDialogFunc is processed, the window is already dismissed, hence no
923 // "end" entry.
924 EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, true));
925 EXPECT_EQ(order.Get(7), TaskItem(QUITMESSAGELOOP, 5, true));
926 EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, false));
927 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 1, true));
928 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, false));
929 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 3, true));
930 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, false));
931 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, true));
932 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, false));
933 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 3, true));
934 EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, false));
937 // A side effect of this test is the generation a beep. Sorry. This test also
938 // needs to process windows messages on the current thread.
939 void RunTest_RecursiveSupport2(MessageLoop::Type message_loop_type) {
940 MessageLoop loop(message_loop_type);
942 Thread worker("RecursiveSupport2_worker");
943 Thread::Options options;
944 options.message_loop_type = message_loop_type;
945 ASSERT_EQ(true, worker.StartWithOptions(options));
946 TaskList order;
947 win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
948 worker.message_loop()->PostTask(FROM_HERE,
949 Bind(&RecursiveFuncWin,
950 MessageLoop::current(),
951 event.Get(),
952 false,
953 &order,
954 true));
955 // Let the other thread execute.
956 WaitForSingleObject(event, INFINITE);
957 MessageLoop::current()->Run();
959 ASSERT_EQ(order.Size(), 18);
960 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
961 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
962 EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
963 // Note that this executes in the MessageBox modal loop.
964 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 3, true));
965 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, false));
966 EXPECT_EQ(order.Get(5), TaskItem(ENDDIALOG, 4, true));
967 EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, false));
968 EXPECT_EQ(order.Get(7), TaskItem(MESSAGEBOX, 2, false));
969 /* The order can subtly change here. The reason is that when RecursiveFunc(1)
970 is called in the main thread, if it is faster than getting to the
971 PostTask(FROM_HERE, Bind(&QuitFunc) execution, the order of task
972 execution can change. We don't care anyway that the order isn't correct.
973 EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, true));
974 EXPECT_EQ(order.Get(9), TaskItem(QUITMESSAGELOOP, 5, false));
975 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
976 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
978 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, true));
979 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 3, false));
980 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, true));
981 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 1, false));
982 EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, true));
983 EXPECT_EQ(order.Get(17), TaskItem(RECURSIVE, 3, false));
986 #endif // defined(OS_WIN)
988 void FuncThatPumps(TaskList* order, int cookie) {
989 order->RecordStart(PUMPS, cookie);
991 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
992 RunLoop().RunUntilIdle();
994 order->RecordEnd(PUMPS, cookie);
997 void FuncThatRuns(TaskList* order, int cookie, RunLoop* run_loop) {
998 order->RecordStart(RUNS, cookie);
1000 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
1001 run_loop->Run();
1003 order->RecordEnd(RUNS, cookie);
1006 void FuncThatQuitsNow() {
1007 MessageLoop::current()->QuitNow();
1010 // Tests that non nestable tasks run in FIFO if there are no nested loops.
1011 void RunTest_NonNestableWithNoNesting(
1012 MessageLoop::Type message_loop_type) {
1013 MessageLoop loop(message_loop_type);
1015 TaskList order;
1017 MessageLoop::current()->PostNonNestableTask(
1018 FROM_HERE,
1019 Bind(&OrderedFunc, &order, 1));
1020 MessageLoop::current()->PostTask(FROM_HERE,
1021 Bind(&OrderedFunc, &order, 2));
1022 MessageLoop::current()->PostTask(FROM_HERE,
1023 Bind(&QuitFunc, &order, 3));
1024 MessageLoop::current()->Run();
1026 // FIFO order.
1027 ASSERT_EQ(6U, order.Size());
1028 EXPECT_EQ(order.Get(0), TaskItem(ORDERED, 1, true));
1029 EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 1, false));
1030 EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 2, true));
1031 EXPECT_EQ(order.Get(3), TaskItem(ORDERED, 2, false));
1032 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
1033 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
1036 // Tests that non nestable tasks don't run when there's code in the call stack.
1037 void RunTest_NonNestableInNestedLoop(MessageLoop::Type message_loop_type,
1038 bool use_delayed) {
1039 MessageLoop loop(message_loop_type);
1041 TaskList order;
1043 MessageLoop::current()->PostTask(
1044 FROM_HERE,
1045 Bind(&FuncThatPumps, &order, 1));
1046 if (use_delayed) {
1047 MessageLoop::current()->PostNonNestableDelayedTask(
1048 FROM_HERE,
1049 Bind(&OrderedFunc, &order, 2),
1050 TimeDelta::FromMilliseconds(1));
1051 } else {
1052 MessageLoop::current()->PostNonNestableTask(
1053 FROM_HERE,
1054 Bind(&OrderedFunc, &order, 2));
1056 MessageLoop::current()->PostTask(FROM_HERE,
1057 Bind(&OrderedFunc, &order, 3));
1058 MessageLoop::current()->PostTask(
1059 FROM_HERE,
1060 Bind(&SleepFunc, &order, 4, TimeDelta::FromMilliseconds(50)));
1061 MessageLoop::current()->PostTask(FROM_HERE,
1062 Bind(&OrderedFunc, &order, 5));
1063 if (use_delayed) {
1064 MessageLoop::current()->PostNonNestableDelayedTask(
1065 FROM_HERE,
1066 Bind(&QuitFunc, &order, 6),
1067 TimeDelta::FromMilliseconds(2));
1068 } else {
1069 MessageLoop::current()->PostNonNestableTask(
1070 FROM_HERE,
1071 Bind(&QuitFunc, &order, 6));
1074 MessageLoop::current()->Run();
1076 // FIFO order.
1077 ASSERT_EQ(12U, order.Size());
1078 EXPECT_EQ(order.Get(0), TaskItem(PUMPS, 1, true));
1079 EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 3, true));
1080 EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 3, false));
1081 EXPECT_EQ(order.Get(3), TaskItem(SLEEP, 4, true));
1082 EXPECT_EQ(order.Get(4), TaskItem(SLEEP, 4, false));
1083 EXPECT_EQ(order.Get(5), TaskItem(ORDERED, 5, true));
1084 EXPECT_EQ(order.Get(6), TaskItem(ORDERED, 5, false));
1085 EXPECT_EQ(order.Get(7), TaskItem(PUMPS, 1, false));
1086 EXPECT_EQ(order.Get(8), TaskItem(ORDERED, 2, true));
1087 EXPECT_EQ(order.Get(9), TaskItem(ORDERED, 2, false));
1088 EXPECT_EQ(order.Get(10), TaskItem(QUITMESSAGELOOP, 6, true));
1089 EXPECT_EQ(order.Get(11), TaskItem(QUITMESSAGELOOP, 6, false));
1092 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1093 void RunTest_QuitNow(MessageLoop::Type message_loop_type) {
1094 MessageLoop loop(message_loop_type);
1096 TaskList order;
1098 RunLoop run_loop;
1100 MessageLoop::current()->PostTask(FROM_HERE,
1101 Bind(&FuncThatRuns, &order, 1, Unretained(&run_loop)));
1102 MessageLoop::current()->PostTask(
1103 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1104 MessageLoop::current()->PostTask(
1105 FROM_HERE, Bind(&FuncThatQuitsNow));
1106 MessageLoop::current()->PostTask(
1107 FROM_HERE, Bind(&OrderedFunc, &order, 3));
1108 MessageLoop::current()->PostTask(
1109 FROM_HERE, Bind(&FuncThatQuitsNow));
1110 MessageLoop::current()->PostTask(
1111 FROM_HERE, Bind(&OrderedFunc, &order, 4)); // never runs
1113 MessageLoop::current()->Run();
1115 ASSERT_EQ(6U, order.Size());
1116 int task_index = 0;
1117 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1118 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1119 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1120 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1121 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
1122 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
1123 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1126 // Tests RunLoopQuit works before RunWithID.
1127 void RunTest_RunLoopQuitOrderBefore(MessageLoop::Type message_loop_type) {
1128 MessageLoop loop(message_loop_type);
1130 TaskList order;
1132 RunLoop run_loop;
1134 run_loop.Quit();
1136 MessageLoop::current()->PostTask(
1137 FROM_HERE, Bind(&OrderedFunc, &order, 1)); // never runs
1138 MessageLoop::current()->PostTask(
1139 FROM_HERE, Bind(&FuncThatQuitsNow)); // never runs
1141 run_loop.Run();
1143 ASSERT_EQ(0U, order.Size());
1146 // Tests RunLoopQuit works during RunWithID.
1147 void RunTest_RunLoopQuitOrderDuring(MessageLoop::Type message_loop_type) {
1148 MessageLoop loop(message_loop_type);
1150 TaskList order;
1152 RunLoop run_loop;
1154 MessageLoop::current()->PostTask(
1155 FROM_HERE, Bind(&OrderedFunc, &order, 1));
1156 MessageLoop::current()->PostTask(
1157 FROM_HERE, run_loop.QuitClosure());
1158 MessageLoop::current()->PostTask(
1159 FROM_HERE, Bind(&OrderedFunc, &order, 2)); // never runs
1160 MessageLoop::current()->PostTask(
1161 FROM_HERE, Bind(&FuncThatQuitsNow)); // never runs
1163 run_loop.Run();
1165 ASSERT_EQ(2U, order.Size());
1166 int task_index = 0;
1167 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, true));
1168 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, false));
1169 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1172 // Tests RunLoopQuit works after RunWithID.
1173 void RunTest_RunLoopQuitOrderAfter(MessageLoop::Type message_loop_type) {
1174 MessageLoop loop(message_loop_type);
1176 TaskList order;
1178 RunLoop run_loop;
1180 MessageLoop::current()->PostTask(FROM_HERE,
1181 Bind(&FuncThatRuns, &order, 1, Unretained(&run_loop)));
1182 MessageLoop::current()->PostTask(
1183 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1184 MessageLoop::current()->PostTask(
1185 FROM_HERE, Bind(&FuncThatQuitsNow));
1186 MessageLoop::current()->PostTask(
1187 FROM_HERE, Bind(&OrderedFunc, &order, 3));
1188 MessageLoop::current()->PostTask(
1189 FROM_HERE, run_loop.QuitClosure()); // has no affect
1190 MessageLoop::current()->PostTask(
1191 FROM_HERE, Bind(&OrderedFunc, &order, 4));
1192 MessageLoop::current()->PostTask(
1193 FROM_HERE, Bind(&FuncThatQuitsNow));
1195 RunLoop outer_run_loop;
1196 outer_run_loop.Run();
1198 ASSERT_EQ(8U, order.Size());
1199 int task_index = 0;
1200 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1201 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1202 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1203 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1204 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
1205 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
1206 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, true));
1207 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, false));
1208 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1211 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1212 void RunTest_RunLoopQuitTop(MessageLoop::Type message_loop_type) {
1213 MessageLoop loop(message_loop_type);
1215 TaskList order;
1217 RunLoop outer_run_loop;
1218 RunLoop nested_run_loop;
1220 MessageLoop::current()->PostTask(FROM_HERE,
1221 Bind(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
1222 MessageLoop::current()->PostTask(
1223 FROM_HERE, outer_run_loop.QuitClosure());
1224 MessageLoop::current()->PostTask(
1225 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1226 MessageLoop::current()->PostTask(
1227 FROM_HERE, nested_run_loop.QuitClosure());
1229 outer_run_loop.Run();
1231 ASSERT_EQ(4U, order.Size());
1232 int task_index = 0;
1233 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1234 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1235 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1236 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1237 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1240 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1241 void RunTest_RunLoopQuitNested(MessageLoop::Type message_loop_type) {
1242 MessageLoop loop(message_loop_type);
1244 TaskList order;
1246 RunLoop outer_run_loop;
1247 RunLoop nested_run_loop;
1249 MessageLoop::current()->PostTask(FROM_HERE,
1250 Bind(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
1251 MessageLoop::current()->PostTask(
1252 FROM_HERE, nested_run_loop.QuitClosure());
1253 MessageLoop::current()->PostTask(
1254 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1255 MessageLoop::current()->PostTask(
1256 FROM_HERE, outer_run_loop.QuitClosure());
1258 outer_run_loop.Run();
1260 ASSERT_EQ(4U, order.Size());
1261 int task_index = 0;
1262 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1263 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1264 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1265 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1266 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1269 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1270 void RunTest_RunLoopQuitBogus(MessageLoop::Type message_loop_type) {
1271 MessageLoop loop(message_loop_type);
1273 TaskList order;
1275 RunLoop outer_run_loop;
1276 RunLoop nested_run_loop;
1277 RunLoop bogus_run_loop;
1279 MessageLoop::current()->PostTask(FROM_HERE,
1280 Bind(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
1281 MessageLoop::current()->PostTask(
1282 FROM_HERE, bogus_run_loop.QuitClosure());
1283 MessageLoop::current()->PostTask(
1284 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1285 MessageLoop::current()->PostTask(
1286 FROM_HERE, outer_run_loop.QuitClosure());
1287 MessageLoop::current()->PostTask(
1288 FROM_HERE, nested_run_loop.QuitClosure());
1290 outer_run_loop.Run();
1292 ASSERT_EQ(4U, order.Size());
1293 int task_index = 0;
1294 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1295 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1296 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1297 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1298 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1301 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1302 void RunTest_RunLoopQuitDeep(MessageLoop::Type message_loop_type) {
1303 MessageLoop loop(message_loop_type);
1305 TaskList order;
1307 RunLoop outer_run_loop;
1308 RunLoop nested_loop1;
1309 RunLoop nested_loop2;
1310 RunLoop nested_loop3;
1311 RunLoop nested_loop4;
1313 MessageLoop::current()->PostTask(FROM_HERE,
1314 Bind(&FuncThatRuns, &order, 1, Unretained(&nested_loop1)));
1315 MessageLoop::current()->PostTask(FROM_HERE,
1316 Bind(&FuncThatRuns, &order, 2, Unretained(&nested_loop2)));
1317 MessageLoop::current()->PostTask(FROM_HERE,
1318 Bind(&FuncThatRuns, &order, 3, Unretained(&nested_loop3)));
1319 MessageLoop::current()->PostTask(FROM_HERE,
1320 Bind(&FuncThatRuns, &order, 4, Unretained(&nested_loop4)));
1321 MessageLoop::current()->PostTask(
1322 FROM_HERE, Bind(&OrderedFunc, &order, 5));
1323 MessageLoop::current()->PostTask(
1324 FROM_HERE, outer_run_loop.QuitClosure());
1325 MessageLoop::current()->PostTask(
1326 FROM_HERE, Bind(&OrderedFunc, &order, 6));
1327 MessageLoop::current()->PostTask(
1328 FROM_HERE, nested_loop1.QuitClosure());
1329 MessageLoop::current()->PostTask(
1330 FROM_HERE, Bind(&OrderedFunc, &order, 7));
1331 MessageLoop::current()->PostTask(
1332 FROM_HERE, nested_loop2.QuitClosure());
1333 MessageLoop::current()->PostTask(
1334 FROM_HERE, Bind(&OrderedFunc, &order, 8));
1335 MessageLoop::current()->PostTask(
1336 FROM_HERE, nested_loop3.QuitClosure());
1337 MessageLoop::current()->PostTask(
1338 FROM_HERE, Bind(&OrderedFunc, &order, 9));
1339 MessageLoop::current()->PostTask(
1340 FROM_HERE, nested_loop4.QuitClosure());
1341 MessageLoop::current()->PostTask(
1342 FROM_HERE, Bind(&OrderedFunc, &order, 10));
1344 outer_run_loop.Run();
1346 ASSERT_EQ(18U, order.Size());
1347 int task_index = 0;
1348 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1349 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, true));
1350 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, true));
1351 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, true));
1352 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, true));
1353 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, false));
1354 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, true));
1355 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, false));
1356 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, true));
1357 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, false));
1358 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, true));
1359 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, false));
1360 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, true));
1361 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, false));
1362 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, false));
1363 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, false));
1364 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, false));
1365 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1366 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1369 void PostNTasksThenQuit(int posts_remaining) {
1370 if (posts_remaining > 1) {
1371 MessageLoop::current()->PostTask(
1372 FROM_HERE,
1373 Bind(&PostNTasksThenQuit, posts_remaining - 1));
1374 } else {
1375 MessageLoop::current()->QuitWhenIdle();
1379 void RunTest_RecursivePosts(MessageLoop::Type message_loop_type,
1380 int num_times) {
1381 MessageLoop loop(message_loop_type);
1382 loop.PostTask(FROM_HERE, Bind(&PostNTasksThenQuit, num_times));
1383 loop.Run();
1386 #if defined(OS_WIN)
1388 class DispatcherImpl : public MessageLoopForUI::Dispatcher {
1389 public:
1390 DispatcherImpl() : dispatch_count_(0) {}
1392 virtual bool Dispatch(const NativeEvent& msg) OVERRIDE {
1393 ::TranslateMessage(&msg);
1394 ::DispatchMessage(&msg);
1395 // Do not count WM_TIMER since it is not what we post and it will cause
1396 // flakiness.
1397 if (msg.message != WM_TIMER)
1398 ++dispatch_count_;
1399 // We treat WM_LBUTTONUP as the last message.
1400 return msg.message != WM_LBUTTONUP;
1403 int dispatch_count_;
1406 void MouseDownUp() {
1407 PostMessage(NULL, WM_LBUTTONDOWN, 0, 0);
1408 PostMessage(NULL, WM_LBUTTONUP, 'A', 0);
1411 void RunTest_Dispatcher(MessageLoop::Type message_loop_type) {
1412 MessageLoop loop(message_loop_type);
1414 MessageLoop::current()->PostDelayedTask(
1415 FROM_HERE,
1416 Bind(&MouseDownUp),
1417 TimeDelta::FromMilliseconds(100));
1418 DispatcherImpl dispatcher;
1419 RunLoop run_loop(&dispatcher);
1420 run_loop.Run();
1421 ASSERT_EQ(2, dispatcher.dispatch_count_);
1424 LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) {
1425 if (code == MessagePumpForUI::kMessageFilterCode) {
1426 MSG* msg = reinterpret_cast<MSG*>(lparam);
1427 if (msg->message == WM_LBUTTONDOWN)
1428 return TRUE;
1430 return FALSE;
1433 void RunTest_DispatcherWithMessageHook(MessageLoop::Type message_loop_type) {
1434 MessageLoop loop(message_loop_type);
1436 MessageLoop::current()->PostDelayedTask(
1437 FROM_HERE,
1438 Bind(&MouseDownUp),
1439 TimeDelta::FromMilliseconds(100));
1440 HHOOK msg_hook = SetWindowsHookEx(WH_MSGFILTER,
1441 MsgFilterProc,
1442 NULL,
1443 GetCurrentThreadId());
1444 DispatcherImpl dispatcher;
1445 RunLoop run_loop(&dispatcher);
1446 run_loop.Run();
1447 ASSERT_EQ(1, dispatcher.dispatch_count_);
1448 UnhookWindowsHookEx(msg_hook);
1451 class TestIOHandler : public MessageLoopForIO::IOHandler {
1452 public:
1453 TestIOHandler(const wchar_t* name, HANDLE signal, bool wait);
1455 virtual void OnIOCompleted(MessageLoopForIO::IOContext* context,
1456 DWORD bytes_transfered, DWORD error);
1458 void Init();
1459 void WaitForIO();
1460 OVERLAPPED* context() { return &context_.overlapped; }
1461 DWORD size() { return sizeof(buffer_); }
1463 private:
1464 char buffer_[48];
1465 MessageLoopForIO::IOContext context_;
1466 HANDLE signal_;
1467 win::ScopedHandle file_;
1468 bool wait_;
1471 TestIOHandler::TestIOHandler(const wchar_t* name, HANDLE signal, bool wait)
1472 : signal_(signal), wait_(wait) {
1473 memset(buffer_, 0, sizeof(buffer_));
1474 memset(&context_, 0, sizeof(context_));
1475 context_.handler = this;
1477 file_.Set(CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING,
1478 FILE_FLAG_OVERLAPPED, NULL));
1479 EXPECT_TRUE(file_.IsValid());
1482 void TestIOHandler::Init() {
1483 MessageLoopForIO::current()->RegisterIOHandler(file_, this);
1485 DWORD read;
1486 EXPECT_FALSE(ReadFile(file_, buffer_, size(), &read, context()));
1487 EXPECT_EQ(ERROR_IO_PENDING, GetLastError());
1488 if (wait_)
1489 WaitForIO();
1492 void TestIOHandler::OnIOCompleted(MessageLoopForIO::IOContext* context,
1493 DWORD bytes_transfered, DWORD error) {
1494 ASSERT_TRUE(context == &context_);
1495 ASSERT_TRUE(SetEvent(signal_));
1498 void TestIOHandler::WaitForIO() {
1499 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(300, this));
1500 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(400, this));
1503 void RunTest_IOHandler() {
1504 win::ScopedHandle callback_called(CreateEvent(NULL, TRUE, FALSE, NULL));
1505 ASSERT_TRUE(callback_called.IsValid());
1507 const wchar_t* kPipeName = L"\\\\.\\pipe\\iohandler_pipe";
1508 win::ScopedHandle server(
1509 CreateNamedPipe(kPipeName, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1510 ASSERT_TRUE(server.IsValid());
1512 Thread thread("IOHandler test");
1513 Thread::Options options;
1514 options.message_loop_type = MessageLoop::TYPE_IO;
1515 ASSERT_TRUE(thread.StartWithOptions(options));
1517 MessageLoop* thread_loop = thread.message_loop();
1518 ASSERT_TRUE(NULL != thread_loop);
1520 TestIOHandler handler(kPipeName, callback_called, false);
1521 thread_loop->PostTask(FROM_HERE, Bind(&TestIOHandler::Init,
1522 Unretained(&handler)));
1523 // Make sure the thread runs and sleeps for lack of work.
1524 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
1526 const char buffer[] = "Hello there!";
1527 DWORD written;
1528 EXPECT_TRUE(WriteFile(server, buffer, sizeof(buffer), &written, NULL));
1530 DWORD result = WaitForSingleObject(callback_called, 1000);
1531 EXPECT_EQ(WAIT_OBJECT_0, result);
1533 thread.Stop();
1536 void RunTest_WaitForIO() {
1537 win::ScopedHandle callback1_called(
1538 CreateEvent(NULL, TRUE, FALSE, NULL));
1539 win::ScopedHandle callback2_called(
1540 CreateEvent(NULL, TRUE, FALSE, NULL));
1541 ASSERT_TRUE(callback1_called.IsValid());
1542 ASSERT_TRUE(callback2_called.IsValid());
1544 const wchar_t* kPipeName1 = L"\\\\.\\pipe\\iohandler_pipe1";
1545 const wchar_t* kPipeName2 = L"\\\\.\\pipe\\iohandler_pipe2";
1546 win::ScopedHandle server1(
1547 CreateNamedPipe(kPipeName1, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1548 win::ScopedHandle server2(
1549 CreateNamedPipe(kPipeName2, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1550 ASSERT_TRUE(server1.IsValid());
1551 ASSERT_TRUE(server2.IsValid());
1553 Thread thread("IOHandler test");
1554 Thread::Options options;
1555 options.message_loop_type = MessageLoop::TYPE_IO;
1556 ASSERT_TRUE(thread.StartWithOptions(options));
1558 MessageLoop* thread_loop = thread.message_loop();
1559 ASSERT_TRUE(NULL != thread_loop);
1561 TestIOHandler handler1(kPipeName1, callback1_called, false);
1562 TestIOHandler handler2(kPipeName2, callback2_called, true);
1563 thread_loop->PostTask(FROM_HERE, Bind(&TestIOHandler::Init,
1564 Unretained(&handler1)));
1565 // TODO(ajwong): Do we really need such long Sleeps in ths function?
1566 // Make sure the thread runs and sleeps for lack of work.
1567 TimeDelta delay = TimeDelta::FromMilliseconds(100);
1568 PlatformThread::Sleep(delay);
1569 thread_loop->PostTask(FROM_HERE, Bind(&TestIOHandler::Init,
1570 Unretained(&handler2)));
1571 PlatformThread::Sleep(delay);
1573 // At this time handler1 is waiting to be called, and the thread is waiting
1574 // on the Init method of handler2, filtering only handler2 callbacks.
1576 const char buffer[] = "Hello there!";
1577 DWORD written;
1578 EXPECT_TRUE(WriteFile(server1, buffer, sizeof(buffer), &written, NULL));
1579 PlatformThread::Sleep(2 * delay);
1580 EXPECT_EQ(WAIT_TIMEOUT, WaitForSingleObject(callback1_called, 0)) <<
1581 "handler1 has not been called";
1583 EXPECT_TRUE(WriteFile(server2, buffer, sizeof(buffer), &written, NULL));
1585 HANDLE objects[2] = { callback1_called.Get(), callback2_called.Get() };
1586 DWORD result = WaitForMultipleObjects(2, objects, TRUE, 1000);
1587 EXPECT_EQ(WAIT_OBJECT_0, result);
1589 thread.Stop();
1592 #endif // defined(OS_WIN)
1594 } // namespace
1596 //-----------------------------------------------------------------------------
1597 // Each test is run against each type of MessageLoop. That way we are sure
1598 // that message loops work properly in all configurations. Of course, in some
1599 // cases, a unit test may only be for a particular type of loop.
1601 TEST(MessageLoopTest, PostTask) {
1602 RunTest_PostTask(MessageLoop::TYPE_DEFAULT);
1603 RunTest_PostTask(MessageLoop::TYPE_UI);
1604 RunTest_PostTask(MessageLoop::TYPE_IO);
1607 TEST(MessageLoopTest, PostTask_SEH) {
1608 RunTest_PostTask_SEH(MessageLoop::TYPE_DEFAULT);
1609 RunTest_PostTask_SEH(MessageLoop::TYPE_UI);
1610 RunTest_PostTask_SEH(MessageLoop::TYPE_IO);
1613 TEST(MessageLoopTest, PostDelayedTask_Basic) {
1614 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_DEFAULT);
1615 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_UI);
1616 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_IO);
1619 TEST(MessageLoopTest, PostDelayedTask_InDelayOrder) {
1620 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_DEFAULT);
1621 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_UI);
1622 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_IO);
1625 TEST(MessageLoopTest, PostDelayedTask_InPostOrder) {
1626 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_DEFAULT);
1627 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_UI);
1628 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_IO);
1631 TEST(MessageLoopTest, PostDelayedTask_InPostOrder_2) {
1632 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_DEFAULT);
1633 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_UI);
1634 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_IO);
1637 TEST(MessageLoopTest, PostDelayedTask_InPostOrder_3) {
1638 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_DEFAULT);
1639 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_UI);
1640 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_IO);
1643 TEST(MessageLoopTest, PostDelayedTask_SharedTimer) {
1644 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_DEFAULT);
1645 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_UI);
1646 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_IO);
1649 #if defined(OS_WIN)
1650 TEST(MessageLoopTest, PostDelayedTask_SharedTimer_SubPump) {
1651 RunTest_PostDelayedTask_SharedTimer_SubPump();
1653 #endif
1655 // TODO(darin): MessageLoop does not support deleting all tasks in the
1656 // destructor.
1657 // Fails, http://crbug.com/50272.
1658 TEST(MessageLoopTest, DISABLED_EnsureDeletion) {
1659 RunTest_EnsureDeletion(MessageLoop::TYPE_DEFAULT);
1660 RunTest_EnsureDeletion(MessageLoop::TYPE_UI);
1661 RunTest_EnsureDeletion(MessageLoop::TYPE_IO);
1664 // TODO(darin): MessageLoop does not support deleting all tasks in the
1665 // destructor.
1666 // Fails, http://crbug.com/50272.
1667 TEST(MessageLoopTest, DISABLED_EnsureDeletion_Chain) {
1668 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_DEFAULT);
1669 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_UI);
1670 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_IO);
1673 #if defined(OS_WIN)
1674 TEST(MessageLoopTest, Crasher) {
1675 RunTest_Crasher(MessageLoop::TYPE_DEFAULT);
1676 RunTest_Crasher(MessageLoop::TYPE_UI);
1677 RunTest_Crasher(MessageLoop::TYPE_IO);
1680 TEST(MessageLoopTest, CrasherNasty) {
1681 RunTest_CrasherNasty(MessageLoop::TYPE_DEFAULT);
1682 RunTest_CrasherNasty(MessageLoop::TYPE_UI);
1683 RunTest_CrasherNasty(MessageLoop::TYPE_IO);
1685 #endif // defined(OS_WIN)
1687 TEST(MessageLoopTest, Nesting) {
1688 RunTest_Nesting(MessageLoop::TYPE_DEFAULT);
1689 RunTest_Nesting(MessageLoop::TYPE_UI);
1690 RunTest_Nesting(MessageLoop::TYPE_IO);
1693 TEST(MessageLoopTest, RecursiveDenial1) {
1694 RunTest_RecursiveDenial1(MessageLoop::TYPE_DEFAULT);
1695 RunTest_RecursiveDenial1(MessageLoop::TYPE_UI);
1696 RunTest_RecursiveDenial1(MessageLoop::TYPE_IO);
1699 TEST(MessageLoopTest, RecursiveDenial3) {
1700 RunTest_RecursiveDenial3(MessageLoop::TYPE_DEFAULT);
1701 RunTest_RecursiveDenial3(MessageLoop::TYPE_UI);
1702 RunTest_RecursiveDenial3(MessageLoop::TYPE_IO);
1705 TEST(MessageLoopTest, RecursiveSupport1) {
1706 RunTest_RecursiveSupport1(MessageLoop::TYPE_DEFAULT);
1707 RunTest_RecursiveSupport1(MessageLoop::TYPE_UI);
1708 RunTest_RecursiveSupport1(MessageLoop::TYPE_IO);
1711 #if defined(OS_WIN)
1712 // This test occasionally hangs http://crbug.com/44567
1713 TEST(MessageLoopTest, DISABLED_RecursiveDenial2) {
1714 RunTest_RecursiveDenial2(MessageLoop::TYPE_DEFAULT);
1715 RunTest_RecursiveDenial2(MessageLoop::TYPE_UI);
1716 RunTest_RecursiveDenial2(MessageLoop::TYPE_IO);
1719 TEST(MessageLoopTest, RecursiveSupport2) {
1720 // This test requires a UI loop
1721 RunTest_RecursiveSupport2(MessageLoop::TYPE_UI);
1723 #endif // defined(OS_WIN)
1725 TEST(MessageLoopTest, NonNestableWithNoNesting) {
1726 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_DEFAULT);
1727 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_UI);
1728 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_IO);
1731 TEST(MessageLoopTest, NonNestableInNestedLoop) {
1732 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT, false);
1733 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI, false);
1734 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO, false);
1737 TEST(MessageLoopTest, NonNestableDelayedInNestedLoop) {
1738 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT, true);
1739 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI, true);
1740 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO, true);
1743 TEST(MessageLoopTest, QuitNow) {
1744 RunTest_QuitNow(MessageLoop::TYPE_DEFAULT);
1745 RunTest_QuitNow(MessageLoop::TYPE_UI);
1746 RunTest_QuitNow(MessageLoop::TYPE_IO);
1749 TEST(MessageLoopTest, RunLoopQuitTop) {
1750 RunTest_RunLoopQuitTop(MessageLoop::TYPE_DEFAULT);
1751 RunTest_RunLoopQuitTop(MessageLoop::TYPE_UI);
1752 RunTest_RunLoopQuitTop(MessageLoop::TYPE_IO);
1755 TEST(MessageLoopTest, RunLoopQuitNested) {
1756 RunTest_RunLoopQuitNested(MessageLoop::TYPE_DEFAULT);
1757 RunTest_RunLoopQuitNested(MessageLoop::TYPE_UI);
1758 RunTest_RunLoopQuitNested(MessageLoop::TYPE_IO);
1761 TEST(MessageLoopTest, RunLoopQuitBogus) {
1762 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_DEFAULT);
1763 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_UI);
1764 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_IO);
1767 TEST(MessageLoopTest, RunLoopQuitDeep) {
1768 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_DEFAULT);
1769 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_UI);
1770 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_IO);
1773 TEST(MessageLoopTest, RunLoopQuitOrderBefore) {
1774 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_DEFAULT);
1775 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_UI);
1776 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_IO);
1779 TEST(MessageLoopTest, RunLoopQuitOrderDuring) {
1780 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_DEFAULT);
1781 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_UI);
1782 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_IO);
1785 TEST(MessageLoopTest, RunLoopQuitOrderAfter) {
1786 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_DEFAULT);
1787 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_UI);
1788 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_IO);
1791 class DummyTaskObserver : public MessageLoop::TaskObserver {
1792 public:
1793 explicit DummyTaskObserver(int num_tasks)
1794 : num_tasks_started_(0),
1795 num_tasks_processed_(0),
1796 num_tasks_(num_tasks) {}
1798 virtual ~DummyTaskObserver() {}
1800 virtual void WillProcessTask(const PendingTask& pending_task) OVERRIDE {
1801 num_tasks_started_++;
1802 EXPECT_TRUE(pending_task.time_posted != TimeTicks());
1803 EXPECT_LE(num_tasks_started_, num_tasks_);
1804 EXPECT_EQ(num_tasks_started_, num_tasks_processed_ + 1);
1807 virtual void DidProcessTask(const PendingTask& pending_task) OVERRIDE {
1808 num_tasks_processed_++;
1809 EXPECT_TRUE(pending_task.time_posted != TimeTicks());
1810 EXPECT_LE(num_tasks_started_, num_tasks_);
1811 EXPECT_EQ(num_tasks_started_, num_tasks_processed_);
1814 int num_tasks_started() const { return num_tasks_started_; }
1815 int num_tasks_processed() const { return num_tasks_processed_; }
1817 private:
1818 int num_tasks_started_;
1819 int num_tasks_processed_;
1820 const int num_tasks_;
1822 DISALLOW_COPY_AND_ASSIGN(DummyTaskObserver);
1825 TEST(MessageLoopTest, TaskObserver) {
1826 const int kNumPosts = 6;
1827 DummyTaskObserver observer(kNumPosts);
1829 MessageLoop loop;
1830 loop.AddTaskObserver(&observer);
1831 loop.PostTask(FROM_HERE, Bind(&PostNTasksThenQuit, kNumPosts));
1832 loop.Run();
1833 loop.RemoveTaskObserver(&observer);
1835 EXPECT_EQ(kNumPosts, observer.num_tasks_started());
1836 EXPECT_EQ(kNumPosts, observer.num_tasks_processed());
1839 #if defined(OS_WIN)
1840 TEST(MessageLoopTest, Dispatcher) {
1841 // This test requires a UI loop
1842 RunTest_Dispatcher(MessageLoop::TYPE_UI);
1845 TEST(MessageLoopTest, DispatcherWithMessageHook) {
1846 // This test requires a UI loop
1847 RunTest_DispatcherWithMessageHook(MessageLoop::TYPE_UI);
1850 TEST(MessageLoopTest, IOHandler) {
1851 RunTest_IOHandler();
1854 TEST(MessageLoopTest, WaitForIO) {
1855 RunTest_WaitForIO();
1858 TEST(MessageLoopTest, HighResolutionTimer) {
1859 MessageLoop loop;
1861 const TimeDelta kFastTimer = TimeDelta::FromMilliseconds(5);
1862 const TimeDelta kSlowTimer = TimeDelta::FromMilliseconds(100);
1864 EXPECT_FALSE(loop.high_resolution_timers_enabled());
1866 // Post a fast task to enable the high resolution timers.
1867 loop.PostDelayedTask(FROM_HERE, Bind(&PostNTasksThenQuit, 1),
1868 kFastTimer);
1869 loop.Run();
1870 EXPECT_TRUE(loop.high_resolution_timers_enabled());
1872 // Post a slow task and verify high resolution timers
1873 // are still enabled.
1874 loop.PostDelayedTask(FROM_HERE, Bind(&PostNTasksThenQuit, 1),
1875 kSlowTimer);
1876 loop.Run();
1877 EXPECT_TRUE(loop.high_resolution_timers_enabled());
1879 // Wait for a while so that high-resolution mode elapses.
1880 PlatformThread::Sleep(TimeDelta::FromMilliseconds(
1881 MessageLoop::kHighResolutionTimerModeLeaseTimeMs));
1883 // Post a slow task to disable the high resolution timers.
1884 loop.PostDelayedTask(FROM_HERE, Bind(&PostNTasksThenQuit, 1),
1885 kSlowTimer);
1886 loop.Run();
1887 EXPECT_FALSE(loop.high_resolution_timers_enabled());
1890 #endif // defined(OS_WIN)
1892 #if defined(OS_POSIX) && !defined(OS_NACL)
1894 namespace {
1896 class QuitDelegate : public MessageLoopForIO::Watcher {
1897 public:
1898 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
1899 MessageLoop::current()->QuitWhenIdle();
1901 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE {
1902 MessageLoop::current()->QuitWhenIdle();
1906 TEST(MessageLoopTest, FileDescriptorWatcherOutlivesMessageLoop) {
1907 // Simulate a MessageLoop that dies before an FileDescriptorWatcher.
1908 // This could happen when people use the Singleton pattern or atexit.
1910 // Create a file descriptor. Doesn't need to be readable or writable,
1911 // as we don't need to actually get any notifications.
1912 // pipe() is just the easiest way to do it.
1913 int pipefds[2];
1914 int err = pipe(pipefds);
1915 ASSERT_EQ(0, err);
1916 int fd = pipefds[1];
1918 // Arrange for controller to live longer than message loop.
1919 MessageLoopForIO::FileDescriptorWatcher controller;
1921 MessageLoopForIO message_loop;
1923 QuitDelegate delegate;
1924 message_loop.WatchFileDescriptor(fd,
1925 true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate);
1926 // and don't run the message loop, just destroy it.
1929 if (HANDLE_EINTR(close(pipefds[0])) < 0)
1930 PLOG(ERROR) << "close";
1931 if (HANDLE_EINTR(close(pipefds[1])) < 0)
1932 PLOG(ERROR) << "close";
1935 TEST(MessageLoopTest, FileDescriptorWatcherDoubleStop) {
1936 // Verify that it's ok to call StopWatchingFileDescriptor().
1937 // (Errors only showed up in valgrind.)
1938 int pipefds[2];
1939 int err = pipe(pipefds);
1940 ASSERT_EQ(0, err);
1941 int fd = pipefds[1];
1943 // Arrange for message loop to live longer than controller.
1944 MessageLoopForIO message_loop;
1946 MessageLoopForIO::FileDescriptorWatcher controller;
1948 QuitDelegate delegate;
1949 message_loop.WatchFileDescriptor(fd,
1950 true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate);
1951 controller.StopWatchingFileDescriptor();
1954 if (HANDLE_EINTR(close(pipefds[0])) < 0)
1955 PLOG(ERROR) << "close";
1956 if (HANDLE_EINTR(close(pipefds[1])) < 0)
1957 PLOG(ERROR) << "close";
1960 } // namespace
1962 #endif // defined(OS_POSIX) && !defined(OS_NACL)
1964 namespace {
1965 // Inject a test point for recording the destructor calls for Closure objects
1966 // send to MessageLoop::PostTask(). It is awkward usage since we are trying to
1967 // hook the actual destruction, which is not a common operation.
1968 class DestructionObserverProbe :
1969 public RefCounted<DestructionObserverProbe> {
1970 public:
1971 DestructionObserverProbe(bool* task_destroyed,
1972 bool* destruction_observer_called)
1973 : task_destroyed_(task_destroyed),
1974 destruction_observer_called_(destruction_observer_called) {
1976 virtual void Run() {
1977 // This task should never run.
1978 ADD_FAILURE();
1980 private:
1981 friend class RefCounted<DestructionObserverProbe>;
1983 virtual ~DestructionObserverProbe() {
1984 EXPECT_FALSE(*destruction_observer_called_);
1985 *task_destroyed_ = true;
1988 bool* task_destroyed_;
1989 bool* destruction_observer_called_;
1992 class MLDestructionObserver : public MessageLoop::DestructionObserver {
1993 public:
1994 MLDestructionObserver(bool* task_destroyed, bool* destruction_observer_called)
1995 : task_destroyed_(task_destroyed),
1996 destruction_observer_called_(destruction_observer_called),
1997 task_destroyed_before_message_loop_(false) {
1999 virtual void WillDestroyCurrentMessageLoop() OVERRIDE {
2000 task_destroyed_before_message_loop_ = *task_destroyed_;
2001 *destruction_observer_called_ = true;
2003 bool task_destroyed_before_message_loop() const {
2004 return task_destroyed_before_message_loop_;
2006 private:
2007 bool* task_destroyed_;
2008 bool* destruction_observer_called_;
2009 bool task_destroyed_before_message_loop_;
2012 } // namespace
2014 TEST(MessageLoopTest, DestructionObserverTest) {
2015 // Verify that the destruction observer gets called at the very end (after
2016 // all the pending tasks have been destroyed).
2017 MessageLoop* loop = new MessageLoop;
2018 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
2020 bool task_destroyed = false;
2021 bool destruction_observer_called = false;
2023 MLDestructionObserver observer(&task_destroyed, &destruction_observer_called);
2024 loop->AddDestructionObserver(&observer);
2025 loop->PostDelayedTask(
2026 FROM_HERE,
2027 Bind(&DestructionObserverProbe::Run,
2028 new DestructionObserverProbe(&task_destroyed,
2029 &destruction_observer_called)),
2030 kDelay);
2031 delete loop;
2032 EXPECT_TRUE(observer.task_destroyed_before_message_loop());
2033 // The task should have been destroyed when we deleted the loop.
2034 EXPECT_TRUE(task_destroyed);
2035 EXPECT_TRUE(destruction_observer_called);
2039 // Verify that MessageLoop sets ThreadMainTaskRunner::current() and it
2040 // posts tasks on that message loop.
2041 TEST(MessageLoopTest, ThreadMainTaskRunner) {
2042 MessageLoop loop;
2044 scoped_refptr<Foo> foo(new Foo());
2045 std::string a("a");
2046 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, Bind(
2047 &Foo::Test1ConstRef, foo.get(), a));
2049 // Post quit task;
2050 MessageLoop::current()->PostTask(FROM_HERE, Bind(
2051 &MessageLoop::Quit, Unretained(MessageLoop::current())));
2053 // Now kick things off
2054 MessageLoop::current()->Run();
2056 EXPECT_EQ(foo->test_count(), 1);
2057 EXPECT_EQ(foo->result(), "a");
2060 TEST(MessageLoopTest, IsType) {
2061 MessageLoop loop(MessageLoop::TYPE_UI);
2062 EXPECT_TRUE(loop.IsType(MessageLoop::TYPE_UI));
2063 EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_IO));
2064 EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_DEFAULT));
2067 TEST(MessageLoopTest, RecursivePosts) {
2068 // There was a bug in the MessagePumpGLib where posting tasks recursively
2069 // caused the message loop to hang, due to the buffer of the internal pipe
2070 // becoming full. Test all MessageLoop types to ensure this issue does not
2071 // exist in other MessagePumps.
2073 // On Linux, the pipe buffer size is 64KiB by default. The bug caused one
2074 // byte accumulated in the pipe per two posts, so we should repeat 128K
2075 // times to reproduce the bug.
2076 const int kNumTimes = 1 << 17;
2077 RunTest_RecursivePosts(MessageLoop::TYPE_DEFAULT, kNumTimes);
2078 RunTest_RecursivePosts(MessageLoop::TYPE_UI, kNumTimes);
2079 RunTest_RecursivePosts(MessageLoop::TYPE_IO, kNumTimes);
2082 } // namespace base