Revert "Revert "Revert 198403 "Move WrappedTexImage functionality to ui/gl"""
[chromium-blink-merge.git] / base / message_loop_unittest.cc
blobec182d1df59a502ee72f6293a6db6c6a9df9ea83
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/synchronization/waitable_event.h"
17 #include "base/thread_task_runner_handle.h"
18 #include "base/threading/platform_thread.h"
19 #include "base/threading/thread.h"
20 #include "testing/gtest/include/gtest/gtest.h"
22 #if defined(OS_WIN)
23 #include "base/message_pump_win.h"
24 #include "base/win/scoped_handle.h"
25 #endif
27 namespace base {
29 class MessageLoopLockTest {
30 public:
31 static void LockWaitUnLock(MessageLoop* loop,
32 base::WaitableEvent* caller_wait,
33 base::WaitableEvent* caller_signal) {
35 loop->incoming_queue_lock_.Acquire();
36 caller_wait->Signal();
37 caller_signal->Wait();
38 loop->incoming_queue_lock_.Release();
42 // TODO(darin): Platform-specific MessageLoop tests should be grouped together
43 // to avoid chopping this file up with so many #ifdefs.
45 namespace {
47 class Foo : public RefCounted<Foo> {
48 public:
49 Foo() : test_count_(0) {
52 void Test0() {
53 ++test_count_;
56 void Test1ConstRef(const std::string& a) {
57 ++test_count_;
58 result_.append(a);
61 void Test1Ptr(std::string* a) {
62 ++test_count_;
63 result_.append(*a);
66 void Test1Int(int a) {
67 test_count_ += a;
70 void Test2Ptr(std::string* a, std::string* b) {
71 ++test_count_;
72 result_.append(*a);
73 result_.append(*b);
76 void Test2Mixed(const std::string& a, std::string* b) {
77 ++test_count_;
78 result_.append(a);
79 result_.append(*b);
82 int test_count() const { return test_count_; }
83 const std::string& result() const { return result_; }
85 private:
86 friend class RefCounted<Foo>;
88 ~Foo() {}
90 int test_count_;
91 std::string result_;
94 void RunTest_PostTask(MessageLoop::Type message_loop_type) {
95 MessageLoop loop(message_loop_type);
97 // Add tests to message loop
98 scoped_refptr<Foo> foo(new Foo());
99 std::string a("a"), b("b"), c("c"), d("d");
100 MessageLoop::current()->PostTask(FROM_HERE, Bind(
101 &Foo::Test0, foo.get()));
102 MessageLoop::current()->PostTask(FROM_HERE, Bind(
103 &Foo::Test1ConstRef, foo.get(), a));
104 MessageLoop::current()->PostTask(FROM_HERE, Bind(
105 &Foo::Test1Ptr, foo.get(), &b));
106 MessageLoop::current()->PostTask(FROM_HERE, Bind(
107 &Foo::Test1Int, foo.get(), 100));
108 MessageLoop::current()->PostTask(FROM_HERE, Bind(
109 &Foo::Test2Ptr, foo.get(), &a, &c));
111 // TryPost with no contention. It must succeed.
112 EXPECT_TRUE(MessageLoop::current()->TryPostTask(FROM_HERE, Bind(
113 &Foo::Test2Mixed, foo.get(), a, &d)));
115 // TryPost with simulated contention. It must fail. We wait for a helper
116 // thread to lock the queue, we TryPost on this thread and finally we
117 // signal the helper to unlock and exit.
118 WaitableEvent wait(true, false);
119 WaitableEvent signal(true, false);
120 Thread thread("RunTest_PostTask_helper");
121 thread.Start();
122 thread.message_loop()->PostTask(
123 FROM_HERE,
124 base::Bind(&MessageLoopLockTest::LockWaitUnLock,
125 MessageLoop::current(),
126 &wait,
127 &signal));
129 wait.Wait();
130 EXPECT_FALSE(MessageLoop::current()->TryPostTask(FROM_HERE, Bind(
131 &Foo::Test2Mixed, foo.get(), a, &d)));
132 signal.Signal();
134 // After all tests, post a message that will shut down the message loop
135 MessageLoop::current()->PostTask(FROM_HERE, Bind(
136 &MessageLoop::Quit, Unretained(MessageLoop::current())));
138 // Now kick things off
139 MessageLoop::current()->Run();
141 EXPECT_EQ(foo->test_count(), 105);
142 EXPECT_EQ(foo->result(), "abacad");
145 void RunTest_PostTask_SEH(MessageLoop::Type message_loop_type) {
146 MessageLoop loop(message_loop_type);
148 // Add tests to message loop
149 scoped_refptr<Foo> foo(new Foo());
150 std::string a("a"), b("b"), c("c"), d("d");
151 MessageLoop::current()->PostTask(FROM_HERE, Bind(
152 &Foo::Test0, foo.get()));
153 MessageLoop::current()->PostTask(FROM_HERE, Bind(
154 &Foo::Test1ConstRef, foo.get(), a));
155 MessageLoop::current()->PostTask(FROM_HERE, Bind(
156 &Foo::Test1Ptr, foo.get(), &b));
157 MessageLoop::current()->PostTask(FROM_HERE, Bind(
158 &Foo::Test1Int, foo.get(), 100));
159 MessageLoop::current()->PostTask(FROM_HERE, Bind(
160 &Foo::Test2Ptr, foo.get(), &a, &c));
161 MessageLoop::current()->PostTask(FROM_HERE, Bind(
162 &Foo::Test2Mixed, foo.get(), a, &d));
164 // After all tests, post a message that will shut down the message loop
165 MessageLoop::current()->PostTask(FROM_HERE, Bind(
166 &MessageLoop::Quit, Unretained(MessageLoop::current())));
168 // Now kick things off with the SEH block active.
169 MessageLoop::current()->set_exception_restoration(true);
170 MessageLoop::current()->Run();
171 MessageLoop::current()->set_exception_restoration(false);
173 EXPECT_EQ(foo->test_count(), 105);
174 EXPECT_EQ(foo->result(), "abacad");
177 // This function runs slowly to simulate a large amount of work being done.
178 static void SlowFunc(TimeDelta pause, int* quit_counter) {
179 PlatformThread::Sleep(pause);
180 if (--(*quit_counter) == 0)
181 MessageLoop::current()->QuitWhenIdle();
184 // This function records the time when Run was called in a Time object, which is
185 // useful for building a variety of MessageLoop tests.
186 static void RecordRunTimeFunc(Time* run_time, int* quit_counter) {
187 *run_time = Time::Now();
189 // Cause our Run function to take some time to execute. As a result we can
190 // count on subsequent RecordRunTimeFunc()s running at a future time,
191 // without worry about the resolution of our system clock being an issue.
192 SlowFunc(TimeDelta::FromMilliseconds(10), quit_counter);
195 void RunTest_PostDelayedTask_Basic(MessageLoop::Type message_loop_type) {
196 MessageLoop loop(message_loop_type);
198 // Test that PostDelayedTask results in a delayed task.
200 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
202 int num_tasks = 1;
203 Time run_time;
205 loop.PostDelayedTask(
206 FROM_HERE, Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
207 kDelay);
209 Time time_before_run = Time::Now();
210 loop.Run();
211 Time time_after_run = Time::Now();
213 EXPECT_EQ(0, num_tasks);
214 EXPECT_LT(kDelay, time_after_run - time_before_run);
217 void RunTest_PostDelayedTask_InDelayOrder(
218 MessageLoop::Type message_loop_type) {
219 MessageLoop loop(message_loop_type);
221 // Test that two tasks with different delays run in the right order.
222 int num_tasks = 2;
223 Time run_time1, run_time2;
225 loop.PostDelayedTask(
226 FROM_HERE,
227 Bind(&RecordRunTimeFunc, &run_time1, &num_tasks),
228 TimeDelta::FromMilliseconds(200));
229 // If we get a large pause in execution (due to a context switch) here, this
230 // test could fail.
231 loop.PostDelayedTask(
232 FROM_HERE,
233 Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
234 TimeDelta::FromMilliseconds(10));
236 loop.Run();
237 EXPECT_EQ(0, num_tasks);
239 EXPECT_TRUE(run_time2 < run_time1);
242 void RunTest_PostDelayedTask_InPostOrder(
243 MessageLoop::Type message_loop_type) {
244 MessageLoop loop(message_loop_type);
246 // Test that two tasks with the same delay run in the order in which they
247 // were posted.
249 // NOTE: This is actually an approximate test since the API only takes a
250 // "delay" parameter, so we are not exactly simulating two tasks that get
251 // posted at the exact same time. It would be nice if the API allowed us to
252 // specify the desired run time.
254 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
256 int num_tasks = 2;
257 Time run_time1, run_time2;
259 loop.PostDelayedTask(
260 FROM_HERE,
261 Bind(&RecordRunTimeFunc, &run_time1, &num_tasks), kDelay);
262 loop.PostDelayedTask(
263 FROM_HERE,
264 Bind(&RecordRunTimeFunc, &run_time2, &num_tasks), kDelay);
266 loop.Run();
267 EXPECT_EQ(0, num_tasks);
269 EXPECT_TRUE(run_time1 < run_time2);
272 void RunTest_PostDelayedTask_InPostOrder_2(
273 MessageLoop::Type message_loop_type) {
274 MessageLoop loop(message_loop_type);
276 // Test that a delayed task still runs after a normal tasks even if the
277 // normal tasks take a long time to run.
279 const TimeDelta kPause = TimeDelta::FromMilliseconds(50);
281 int num_tasks = 2;
282 Time run_time;
284 loop.PostTask(FROM_HERE, Bind(&SlowFunc, kPause, &num_tasks));
285 loop.PostDelayedTask(
286 FROM_HERE,
287 Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
288 TimeDelta::FromMilliseconds(10));
290 Time time_before_run = Time::Now();
291 loop.Run();
292 Time time_after_run = Time::Now();
294 EXPECT_EQ(0, num_tasks);
296 EXPECT_LT(kPause, time_after_run - time_before_run);
299 void RunTest_PostDelayedTask_InPostOrder_3(
300 MessageLoop::Type message_loop_type) {
301 MessageLoop loop(message_loop_type);
303 // Test that a delayed task still runs after a pile of normal tasks. The key
304 // difference between this test and the previous one is that here we return
305 // the MessageLoop a lot so we give the MessageLoop plenty of opportunities
306 // to maybe run the delayed task. It should know not to do so until the
307 // delayed task's delay has passed.
309 int num_tasks = 11;
310 Time run_time1, run_time2;
312 // Clutter the ML with tasks.
313 for (int i = 1; i < num_tasks; ++i)
314 loop.PostTask(FROM_HERE,
315 Bind(&RecordRunTimeFunc, &run_time1, &num_tasks));
317 loop.PostDelayedTask(
318 FROM_HERE, Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
319 TimeDelta::FromMilliseconds(1));
321 loop.Run();
322 EXPECT_EQ(0, num_tasks);
324 EXPECT_TRUE(run_time2 > run_time1);
327 void RunTest_PostDelayedTask_SharedTimer(
328 MessageLoop::Type message_loop_type) {
329 MessageLoop loop(message_loop_type);
331 // Test that the interval of the timer, used to run the next delayed task, is
332 // set to a value corresponding to when the next delayed task should run.
334 // By setting num_tasks to 1, we ensure that the first task to run causes the
335 // run loop to exit.
336 int num_tasks = 1;
337 Time run_time1, run_time2;
339 loop.PostDelayedTask(
340 FROM_HERE,
341 Bind(&RecordRunTimeFunc, &run_time1, &num_tasks),
342 TimeDelta::FromSeconds(1000));
343 loop.PostDelayedTask(
344 FROM_HERE,
345 Bind(&RecordRunTimeFunc, &run_time2, &num_tasks),
346 TimeDelta::FromMilliseconds(10));
348 Time start_time = Time::Now();
350 loop.Run();
351 EXPECT_EQ(0, num_tasks);
353 // Ensure that we ran in far less time than the slower timer.
354 TimeDelta total_time = Time::Now() - start_time;
355 EXPECT_GT(5000, total_time.InMilliseconds());
357 // In case both timers somehow run at nearly the same time, sleep a little
358 // and then run all pending to force them both to have run. This is just
359 // encouraging flakiness if there is any.
360 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
361 RunLoop().RunUntilIdle();
363 EXPECT_TRUE(run_time1.is_null());
364 EXPECT_FALSE(run_time2.is_null());
367 #if defined(OS_WIN)
369 void SubPumpFunc() {
370 MessageLoop::current()->SetNestableTasksAllowed(true);
371 MSG msg;
372 while (GetMessage(&msg, NULL, 0, 0)) {
373 TranslateMessage(&msg);
374 DispatchMessage(&msg);
376 MessageLoop::current()->QuitWhenIdle();
379 void RunTest_PostDelayedTask_SharedTimer_SubPump() {
380 MessageLoop loop(MessageLoop::TYPE_UI);
382 // Test that the interval of the timer, used to run the next delayed task, is
383 // set to a value corresponding to when the next delayed task should run.
385 // By setting num_tasks to 1, we ensure that the first task to run causes the
386 // run loop to exit.
387 int num_tasks = 1;
388 Time run_time;
390 loop.PostTask(FROM_HERE, Bind(&SubPumpFunc));
392 // This very delayed task should never run.
393 loop.PostDelayedTask(
394 FROM_HERE,
395 Bind(&RecordRunTimeFunc, &run_time, &num_tasks),
396 TimeDelta::FromSeconds(1000));
398 // This slightly delayed task should run from within SubPumpFunc).
399 loop.PostDelayedTask(
400 FROM_HERE,
401 Bind(&PostQuitMessage, 0),
402 TimeDelta::FromMilliseconds(10));
404 Time start_time = Time::Now();
406 loop.Run();
407 EXPECT_EQ(1, num_tasks);
409 // Ensure that we ran in far less time than the slower timer.
410 TimeDelta total_time = Time::Now() - start_time;
411 EXPECT_GT(5000, total_time.InMilliseconds());
413 // In case both timers somehow run at nearly the same time, sleep a little
414 // and then run all pending to force them both to have run. This is just
415 // encouraging flakiness if there is any.
416 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
417 RunLoop().RunUntilIdle();
419 EXPECT_TRUE(run_time.is_null());
422 #endif // defined(OS_WIN)
424 // This is used to inject a test point for recording the destructor calls for
425 // Closure objects send to MessageLoop::PostTask(). It is awkward usage since we
426 // are trying to hook the actual destruction, which is not a common operation.
427 class RecordDeletionProbe : public RefCounted<RecordDeletionProbe> {
428 public:
429 RecordDeletionProbe(RecordDeletionProbe* post_on_delete, bool* was_deleted)
430 : post_on_delete_(post_on_delete), was_deleted_(was_deleted) {
432 void Run() {}
434 private:
435 friend class RefCounted<RecordDeletionProbe>;
437 ~RecordDeletionProbe() {
438 *was_deleted_ = true;
439 if (post_on_delete_)
440 MessageLoop::current()->PostTask(
441 FROM_HERE,
442 Bind(&RecordDeletionProbe::Run, post_on_delete_.get()));
445 scoped_refptr<RecordDeletionProbe> post_on_delete_;
446 bool* was_deleted_;
449 void RunTest_EnsureDeletion(MessageLoop::Type message_loop_type) {
450 bool a_was_deleted = false;
451 bool b_was_deleted = false;
453 MessageLoop loop(message_loop_type);
454 loop.PostTask(
455 FROM_HERE, Bind(&RecordDeletionProbe::Run,
456 new RecordDeletionProbe(NULL, &a_was_deleted)));
457 // TODO(ajwong): Do we really need 1000ms here?
458 loop.PostDelayedTask(
459 FROM_HERE, Bind(&RecordDeletionProbe::Run,
460 new RecordDeletionProbe(NULL, &b_was_deleted)),
461 TimeDelta::FromMilliseconds(1000));
463 EXPECT_TRUE(a_was_deleted);
464 EXPECT_TRUE(b_was_deleted);
467 void RunTest_EnsureDeletion_Chain(MessageLoop::Type message_loop_type) {
468 bool a_was_deleted = false;
469 bool b_was_deleted = false;
470 bool c_was_deleted = false;
472 MessageLoop loop(message_loop_type);
473 // The scoped_refptr for each of the below is held either by the chained
474 // RecordDeletionProbe, or the bound RecordDeletionProbe::Run() callback.
475 RecordDeletionProbe* a = new RecordDeletionProbe(NULL, &a_was_deleted);
476 RecordDeletionProbe* b = new RecordDeletionProbe(a, &b_was_deleted);
477 RecordDeletionProbe* c = new RecordDeletionProbe(b, &c_was_deleted);
478 loop.PostTask(FROM_HERE, Bind(&RecordDeletionProbe::Run, c));
480 EXPECT_TRUE(a_was_deleted);
481 EXPECT_TRUE(b_was_deleted);
482 EXPECT_TRUE(c_was_deleted);
485 void NestingFunc(int* depth) {
486 if (*depth > 0) {
487 *depth -= 1;
488 MessageLoop::current()->PostTask(FROM_HERE,
489 Bind(&NestingFunc, depth));
491 MessageLoop::current()->SetNestableTasksAllowed(true);
492 MessageLoop::current()->Run();
494 MessageLoop::current()->QuitWhenIdle();
497 #if defined(OS_WIN)
499 LONG WINAPI BadExceptionHandler(EXCEPTION_POINTERS *ex_info) {
500 ADD_FAILURE() << "bad exception handler";
501 ::ExitProcess(ex_info->ExceptionRecord->ExceptionCode);
502 return EXCEPTION_EXECUTE_HANDLER;
505 // This task throws an SEH exception: initially write to an invalid address.
506 // If the right SEH filter is installed, it will fix the error.
507 class Crasher : public RefCounted<Crasher> {
508 public:
509 // Ctor. If trash_SEH_handler is true, the task will override the unhandled
510 // exception handler with one sure to crash this test.
511 explicit Crasher(bool trash_SEH_handler)
512 : trash_SEH_handler_(trash_SEH_handler) {
515 void Run() {
516 PlatformThread::Sleep(TimeDelta::FromMilliseconds(1));
517 if (trash_SEH_handler_)
518 ::SetUnhandledExceptionFilter(&BadExceptionHandler);
519 // Generate a SEH fault. We do it in asm to make sure we know how to undo
520 // the damage.
522 #if defined(_M_IX86)
524 __asm {
525 mov eax, dword ptr [Crasher::bad_array_]
526 mov byte ptr [eax], 66
529 #elif defined(_M_X64)
531 bad_array_[0] = 66;
533 #else
534 #error "needs architecture support"
535 #endif
537 MessageLoop::current()->QuitWhenIdle();
539 // Points the bad array to a valid memory location.
540 static void FixError() {
541 bad_array_ = &valid_store_;
544 private:
545 bool trash_SEH_handler_;
546 static volatile char* bad_array_;
547 static char valid_store_;
550 volatile char* Crasher::bad_array_ = 0;
551 char Crasher::valid_store_ = 0;
553 // This SEH filter fixes the problem and retries execution. Fixing requires
554 // that the last instruction: mov eax, [Crasher::bad_array_] to be retried
555 // so we move the instruction pointer 5 bytes back.
556 LONG WINAPI HandleCrasherException(EXCEPTION_POINTERS *ex_info) {
557 if (ex_info->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION)
558 return EXCEPTION_EXECUTE_HANDLER;
560 Crasher::FixError();
562 #if defined(_M_IX86)
564 ex_info->ContextRecord->Eip -= 5;
566 #elif defined(_M_X64)
568 ex_info->ContextRecord->Rip -= 5;
570 #endif
572 return EXCEPTION_CONTINUE_EXECUTION;
575 void RunTest_Crasher(MessageLoop::Type message_loop_type) {
576 MessageLoop loop(message_loop_type);
578 if (::IsDebuggerPresent())
579 return;
581 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter =
582 ::SetUnhandledExceptionFilter(&HandleCrasherException);
584 MessageLoop::current()->PostTask(
585 FROM_HERE,
586 Bind(&Crasher::Run, new Crasher(false)));
587 MessageLoop::current()->set_exception_restoration(true);
588 MessageLoop::current()->Run();
589 MessageLoop::current()->set_exception_restoration(false);
591 ::SetUnhandledExceptionFilter(old_SEH_filter);
594 void RunTest_CrasherNasty(MessageLoop::Type message_loop_type) {
595 MessageLoop loop(message_loop_type);
597 if (::IsDebuggerPresent())
598 return;
600 LPTOP_LEVEL_EXCEPTION_FILTER old_SEH_filter =
601 ::SetUnhandledExceptionFilter(&HandleCrasherException);
603 MessageLoop::current()->PostTask(
604 FROM_HERE,
605 Bind(&Crasher::Run, new Crasher(true)));
606 MessageLoop::current()->set_exception_restoration(true);
607 MessageLoop::current()->Run();
608 MessageLoop::current()->set_exception_restoration(false);
610 ::SetUnhandledExceptionFilter(old_SEH_filter);
613 #endif // defined(OS_WIN)
615 void RunTest_Nesting(MessageLoop::Type message_loop_type) {
616 MessageLoop loop(message_loop_type);
618 int depth = 100;
619 MessageLoop::current()->PostTask(FROM_HERE,
620 Bind(&NestingFunc, &depth));
621 MessageLoop::current()->Run();
622 EXPECT_EQ(depth, 0);
625 const wchar_t* const kMessageBoxTitle = L"MessageLoop Unit Test";
627 enum TaskType {
628 MESSAGEBOX,
629 ENDDIALOG,
630 RECURSIVE,
631 TIMEDMESSAGELOOP,
632 QUITMESSAGELOOP,
633 ORDERED,
634 PUMPS,
635 SLEEP,
636 RUNS,
639 // Saves the order in which the tasks executed.
640 struct TaskItem {
641 TaskItem(TaskType t, int c, bool s)
642 : type(t),
643 cookie(c),
644 start(s) {
647 TaskType type;
648 int cookie;
649 bool start;
651 bool operator == (const TaskItem& other) const {
652 return type == other.type && cookie == other.cookie && start == other.start;
656 std::ostream& operator <<(std::ostream& os, TaskType type) {
657 switch (type) {
658 case MESSAGEBOX: os << "MESSAGEBOX"; break;
659 case ENDDIALOG: os << "ENDDIALOG"; break;
660 case RECURSIVE: os << "RECURSIVE"; break;
661 case TIMEDMESSAGELOOP: os << "TIMEDMESSAGELOOP"; break;
662 case QUITMESSAGELOOP: os << "QUITMESSAGELOOP"; break;
663 case ORDERED: os << "ORDERED"; break;
664 case PUMPS: os << "PUMPS"; break;
665 case SLEEP: os << "SLEEP"; break;
666 default:
667 NOTREACHED();
668 os << "Unknown TaskType";
669 break;
671 return os;
674 std::ostream& operator <<(std::ostream& os, const TaskItem& item) {
675 if (item.start)
676 return os << item.type << " " << item.cookie << " starts";
677 else
678 return os << item.type << " " << item.cookie << " ends";
681 class TaskList {
682 public:
683 void RecordStart(TaskType type, int cookie) {
684 TaskItem item(type, cookie, true);
685 DVLOG(1) << item;
686 task_list_.push_back(item);
689 void RecordEnd(TaskType type, int cookie) {
690 TaskItem item(type, cookie, false);
691 DVLOG(1) << item;
692 task_list_.push_back(item);
695 size_t Size() {
696 return task_list_.size();
699 TaskItem Get(int n) {
700 return task_list_[n];
703 private:
704 std::vector<TaskItem> task_list_;
707 // Saves the order the tasks ran.
708 void OrderedFunc(TaskList* order, int cookie) {
709 order->RecordStart(ORDERED, cookie);
710 order->RecordEnd(ORDERED, cookie);
713 #if defined(OS_WIN)
715 // MessageLoop implicitly start a "modal message loop". Modal dialog boxes,
716 // common controls (like OpenFile) and StartDoc printing function can cause
717 // implicit message loops.
718 void MessageBoxFunc(TaskList* order, int cookie, bool is_reentrant) {
719 order->RecordStart(MESSAGEBOX, cookie);
720 if (is_reentrant)
721 MessageLoop::current()->SetNestableTasksAllowed(true);
722 MessageBox(NULL, L"Please wait...", kMessageBoxTitle, MB_OK);
723 order->RecordEnd(MESSAGEBOX, cookie);
726 // Will end the MessageBox.
727 void EndDialogFunc(TaskList* order, int cookie) {
728 order->RecordStart(ENDDIALOG, cookie);
729 HWND window = GetActiveWindow();
730 if (window != NULL) {
731 EXPECT_NE(EndDialog(window, IDCONTINUE), 0);
732 // Cheap way to signal that the window wasn't found if RunEnd() isn't
733 // called.
734 order->RecordEnd(ENDDIALOG, cookie);
738 #endif // defined(OS_WIN)
740 void RecursiveFunc(TaskList* order, int cookie, int depth,
741 bool is_reentrant) {
742 order->RecordStart(RECURSIVE, cookie);
743 if (depth > 0) {
744 if (is_reentrant)
745 MessageLoop::current()->SetNestableTasksAllowed(true);
746 MessageLoop::current()->PostTask(
747 FROM_HERE,
748 Bind(&RecursiveFunc, order, cookie, depth - 1, is_reentrant));
750 order->RecordEnd(RECURSIVE, cookie);
753 void RecursiveSlowFunc(TaskList* order, int cookie, int depth,
754 bool is_reentrant) {
755 RecursiveFunc(order, cookie, depth, is_reentrant);
756 PlatformThread::Sleep(TimeDelta::FromMilliseconds(10));
759 void QuitFunc(TaskList* order, int cookie) {
760 order->RecordStart(QUITMESSAGELOOP, cookie);
761 MessageLoop::current()->QuitWhenIdle();
762 order->RecordEnd(QUITMESSAGELOOP, cookie);
765 void SleepFunc(TaskList* order, int cookie, TimeDelta delay) {
766 order->RecordStart(SLEEP, cookie);
767 PlatformThread::Sleep(delay);
768 order->RecordEnd(SLEEP, cookie);
771 #if defined(OS_WIN)
772 void RecursiveFuncWin(MessageLoop* target,
773 HANDLE event,
774 bool expect_window,
775 TaskList* order,
776 bool is_reentrant) {
777 target->PostTask(FROM_HERE,
778 Bind(&RecursiveFunc, order, 1, 2, is_reentrant));
779 target->PostTask(FROM_HERE,
780 Bind(&MessageBoxFunc, order, 2, is_reentrant));
781 target->PostTask(FROM_HERE,
782 Bind(&RecursiveFunc, order, 3, 2, is_reentrant));
783 // The trick here is that for recursive task processing, this task will be
784 // ran _inside_ the MessageBox message loop, dismissing the MessageBox
785 // without a chance.
786 // For non-recursive task processing, this will be executed _after_ the
787 // MessageBox will have been dismissed by the code below, where
788 // expect_window_ is true.
789 target->PostTask(FROM_HERE,
790 Bind(&EndDialogFunc, order, 4));
791 target->PostTask(FROM_HERE,
792 Bind(&QuitFunc, order, 5));
794 // Enforce that every tasks are sent before starting to run the main thread
795 // message loop.
796 ASSERT_TRUE(SetEvent(event));
798 // Poll for the MessageBox. Don't do this at home! At the speed we do it,
799 // you will never realize one MessageBox was shown.
800 for (; expect_window;) {
801 HWND window = FindWindow(L"#32770", kMessageBoxTitle);
802 if (window) {
803 // Dismiss it.
804 for (;;) {
805 HWND button = FindWindowEx(window, NULL, L"Button", NULL);
806 if (button != NULL) {
807 EXPECT_EQ(0, SendMessage(button, WM_LBUTTONDOWN, 0, 0));
808 EXPECT_EQ(0, SendMessage(button, WM_LBUTTONUP, 0, 0));
809 break;
812 break;
817 #endif // defined(OS_WIN)
819 void RunTest_RecursiveDenial1(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,
826 Bind(&RecursiveFunc, &order, 1, 2, false));
827 MessageLoop::current()->PostTask(
828 FROM_HERE,
829 Bind(&RecursiveFunc, &order, 2, 2, false));
830 MessageLoop::current()->PostTask(
831 FROM_HERE,
832 Bind(&QuitFunc, &order, 3));
834 MessageLoop::current()->Run();
836 // FIFO order.
837 ASSERT_EQ(14U, order.Size());
838 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
839 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
840 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
841 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
842 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
843 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
844 EXPECT_EQ(order.Get(6), TaskItem(RECURSIVE, 1, true));
845 EXPECT_EQ(order.Get(7), TaskItem(RECURSIVE, 1, false));
846 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
847 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
848 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
849 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
850 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 2, true));
851 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 2, false));
854 void RunTest_RecursiveDenial3(MessageLoop::Type message_loop_type) {
855 MessageLoop loop(message_loop_type);
857 EXPECT_TRUE(MessageLoop::current()->NestableTasksAllowed());
858 TaskList order;
859 MessageLoop::current()->PostTask(
860 FROM_HERE, Bind(&RecursiveSlowFunc, &order, 1, 2, false));
861 MessageLoop::current()->PostTask(
862 FROM_HERE, Bind(&RecursiveSlowFunc, &order, 2, 2, false));
863 MessageLoop::current()->PostDelayedTask(
864 FROM_HERE,
865 Bind(&OrderedFunc, &order, 3),
866 TimeDelta::FromMilliseconds(5));
867 MessageLoop::current()->PostDelayedTask(
868 FROM_HERE,
869 Bind(&QuitFunc, &order, 4),
870 TimeDelta::FromMilliseconds(5));
872 MessageLoop::current()->Run();
874 // FIFO order.
875 ASSERT_EQ(16U, order.Size());
876 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
877 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
878 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
879 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
880 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 1, true));
881 EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 1, false));
882 EXPECT_EQ(order.Get(6), TaskItem(ORDERED, 3, true));
883 EXPECT_EQ(order.Get(7), TaskItem(ORDERED, 3, false));
884 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
885 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
886 EXPECT_EQ(order.Get(10), TaskItem(QUITMESSAGELOOP, 4, true));
887 EXPECT_EQ(order.Get(11), TaskItem(QUITMESSAGELOOP, 4, false));
888 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 1, true));
889 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, false));
890 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 2, true));
891 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 2, false));
894 void RunTest_RecursiveSupport1(MessageLoop::Type message_loop_type) {
895 MessageLoop loop(message_loop_type);
897 TaskList order;
898 MessageLoop::current()->PostTask(
899 FROM_HERE, Bind(&RecursiveFunc, &order, 1, 2, true));
900 MessageLoop::current()->PostTask(
901 FROM_HERE, Bind(&RecursiveFunc, &order, 2, 2, true));
902 MessageLoop::current()->PostTask(
903 FROM_HERE, Bind(&QuitFunc, &order, 3));
905 MessageLoop::current()->Run();
907 // FIFO order.
908 ASSERT_EQ(14U, order.Size());
909 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
910 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
911 EXPECT_EQ(order.Get(2), TaskItem(RECURSIVE, 2, true));
912 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 2, false));
913 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
914 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
915 EXPECT_EQ(order.Get(6), TaskItem(RECURSIVE, 1, true));
916 EXPECT_EQ(order.Get(7), TaskItem(RECURSIVE, 1, false));
917 EXPECT_EQ(order.Get(8), TaskItem(RECURSIVE, 2, true));
918 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 2, false));
919 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
920 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
921 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 2, true));
922 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 2, false));
925 #if defined(OS_WIN)
926 // TODO(darin): These tests need to be ported since they test critical
927 // message loop functionality.
929 // A side effect of this test is the generation a beep. Sorry.
930 void RunTest_RecursiveDenial2(MessageLoop::Type message_loop_type) {
931 MessageLoop loop(message_loop_type);
933 Thread worker("RecursiveDenial2_worker");
934 Thread::Options options;
935 options.message_loop_type = message_loop_type;
936 ASSERT_EQ(true, worker.StartWithOptions(options));
937 TaskList order;
938 win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
939 worker.message_loop()->PostTask(FROM_HERE,
940 Bind(&RecursiveFuncWin,
941 MessageLoop::current(),
942 event.Get(),
943 true,
944 &order,
945 false));
946 // Let the other thread execute.
947 WaitForSingleObject(event, INFINITE);
948 MessageLoop::current()->Run();
950 ASSERT_EQ(order.Size(), 17);
951 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
952 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
953 EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
954 EXPECT_EQ(order.Get(3), TaskItem(MESSAGEBOX, 2, false));
955 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, true));
956 EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 3, false));
957 // When EndDialogFunc is processed, the window is already dismissed, hence no
958 // "end" entry.
959 EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, true));
960 EXPECT_EQ(order.Get(7), TaskItem(QUITMESSAGELOOP, 5, true));
961 EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, false));
962 EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 1, true));
963 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, false));
964 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 3, true));
965 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, false));
966 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, true));
967 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, false));
968 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 3, true));
969 EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, false));
972 // A side effect of this test is the generation a beep. Sorry. This test also
973 // needs to process windows messages on the current thread.
974 void RunTest_RecursiveSupport2(MessageLoop::Type message_loop_type) {
975 MessageLoop loop(message_loop_type);
977 Thread worker("RecursiveSupport2_worker");
978 Thread::Options options;
979 options.message_loop_type = message_loop_type;
980 ASSERT_EQ(true, worker.StartWithOptions(options));
981 TaskList order;
982 win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL));
983 worker.message_loop()->PostTask(FROM_HERE,
984 Bind(&RecursiveFuncWin,
985 MessageLoop::current(),
986 event.Get(),
987 false,
988 &order,
989 true));
990 // Let the other thread execute.
991 WaitForSingleObject(event, INFINITE);
992 MessageLoop::current()->Run();
994 ASSERT_EQ(order.Size(), 18);
995 EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true));
996 EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false));
997 EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true));
998 // Note that this executes in the MessageBox modal loop.
999 EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 3, true));
1000 EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, false));
1001 EXPECT_EQ(order.Get(5), TaskItem(ENDDIALOG, 4, true));
1002 EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, false));
1003 EXPECT_EQ(order.Get(7), TaskItem(MESSAGEBOX, 2, false));
1004 /* The order can subtly change here. The reason is that when RecursiveFunc(1)
1005 is called in the main thread, if it is faster than getting to the
1006 PostTask(FROM_HERE, Bind(&QuitFunc) execution, the order of task
1007 execution can change. We don't care anyway that the order isn't correct.
1008 EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, true));
1009 EXPECT_EQ(order.Get(9), TaskItem(QUITMESSAGELOOP, 5, false));
1010 EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true));
1011 EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false));
1013 EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, true));
1014 EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 3, false));
1015 EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, true));
1016 EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 1, false));
1017 EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, true));
1018 EXPECT_EQ(order.Get(17), TaskItem(RECURSIVE, 3, false));
1021 #endif // defined(OS_WIN)
1023 void FuncThatPumps(TaskList* order, int cookie) {
1024 order->RecordStart(PUMPS, cookie);
1026 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
1027 RunLoop().RunUntilIdle();
1029 order->RecordEnd(PUMPS, cookie);
1032 void FuncThatRuns(TaskList* order, int cookie, RunLoop* run_loop) {
1033 order->RecordStart(RUNS, cookie);
1035 MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
1036 run_loop->Run();
1038 order->RecordEnd(RUNS, cookie);
1041 void FuncThatQuitsNow() {
1042 MessageLoop::current()->QuitNow();
1045 // Tests that non nestable tasks run in FIFO if there are no nested loops.
1046 void RunTest_NonNestableWithNoNesting(
1047 MessageLoop::Type message_loop_type) {
1048 MessageLoop loop(message_loop_type);
1050 TaskList order;
1052 MessageLoop::current()->PostNonNestableTask(
1053 FROM_HERE,
1054 Bind(&OrderedFunc, &order, 1));
1055 MessageLoop::current()->PostTask(FROM_HERE,
1056 Bind(&OrderedFunc, &order, 2));
1057 MessageLoop::current()->PostTask(FROM_HERE,
1058 Bind(&QuitFunc, &order, 3));
1059 MessageLoop::current()->Run();
1061 // FIFO order.
1062 ASSERT_EQ(6U, order.Size());
1063 EXPECT_EQ(order.Get(0), TaskItem(ORDERED, 1, true));
1064 EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 1, false));
1065 EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 2, true));
1066 EXPECT_EQ(order.Get(3), TaskItem(ORDERED, 2, false));
1067 EXPECT_EQ(order.Get(4), TaskItem(QUITMESSAGELOOP, 3, true));
1068 EXPECT_EQ(order.Get(5), TaskItem(QUITMESSAGELOOP, 3, false));
1071 // Tests that non nestable tasks don't run when there's code in the call stack.
1072 void RunTest_NonNestableInNestedLoop(MessageLoop::Type message_loop_type,
1073 bool use_delayed) {
1074 MessageLoop loop(message_loop_type);
1076 TaskList order;
1078 MessageLoop::current()->PostTask(
1079 FROM_HERE,
1080 Bind(&FuncThatPumps, &order, 1));
1081 if (use_delayed) {
1082 MessageLoop::current()->PostNonNestableDelayedTask(
1083 FROM_HERE,
1084 Bind(&OrderedFunc, &order, 2),
1085 TimeDelta::FromMilliseconds(1));
1086 } else {
1087 MessageLoop::current()->PostNonNestableTask(
1088 FROM_HERE,
1089 Bind(&OrderedFunc, &order, 2));
1091 MessageLoop::current()->PostTask(FROM_HERE,
1092 Bind(&OrderedFunc, &order, 3));
1093 MessageLoop::current()->PostTask(
1094 FROM_HERE,
1095 Bind(&SleepFunc, &order, 4, TimeDelta::FromMilliseconds(50)));
1096 MessageLoop::current()->PostTask(FROM_HERE,
1097 Bind(&OrderedFunc, &order, 5));
1098 if (use_delayed) {
1099 MessageLoop::current()->PostNonNestableDelayedTask(
1100 FROM_HERE,
1101 Bind(&QuitFunc, &order, 6),
1102 TimeDelta::FromMilliseconds(2));
1103 } else {
1104 MessageLoop::current()->PostNonNestableTask(
1105 FROM_HERE,
1106 Bind(&QuitFunc, &order, 6));
1109 MessageLoop::current()->Run();
1111 // FIFO order.
1112 ASSERT_EQ(12U, order.Size());
1113 EXPECT_EQ(order.Get(0), TaskItem(PUMPS, 1, true));
1114 EXPECT_EQ(order.Get(1), TaskItem(ORDERED, 3, true));
1115 EXPECT_EQ(order.Get(2), TaskItem(ORDERED, 3, false));
1116 EXPECT_EQ(order.Get(3), TaskItem(SLEEP, 4, true));
1117 EXPECT_EQ(order.Get(4), TaskItem(SLEEP, 4, false));
1118 EXPECT_EQ(order.Get(5), TaskItem(ORDERED, 5, true));
1119 EXPECT_EQ(order.Get(6), TaskItem(ORDERED, 5, false));
1120 EXPECT_EQ(order.Get(7), TaskItem(PUMPS, 1, false));
1121 EXPECT_EQ(order.Get(8), TaskItem(ORDERED, 2, true));
1122 EXPECT_EQ(order.Get(9), TaskItem(ORDERED, 2, false));
1123 EXPECT_EQ(order.Get(10), TaskItem(QUITMESSAGELOOP, 6, true));
1124 EXPECT_EQ(order.Get(11), TaskItem(QUITMESSAGELOOP, 6, false));
1127 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1128 void RunTest_QuitNow(MessageLoop::Type message_loop_type) {
1129 MessageLoop loop(message_loop_type);
1131 TaskList order;
1133 RunLoop run_loop;
1135 MessageLoop::current()->PostTask(FROM_HERE,
1136 Bind(&FuncThatRuns, &order, 1, Unretained(&run_loop)));
1137 MessageLoop::current()->PostTask(
1138 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1139 MessageLoop::current()->PostTask(
1140 FROM_HERE, Bind(&FuncThatQuitsNow));
1141 MessageLoop::current()->PostTask(
1142 FROM_HERE, Bind(&OrderedFunc, &order, 3));
1143 MessageLoop::current()->PostTask(
1144 FROM_HERE, Bind(&FuncThatQuitsNow));
1145 MessageLoop::current()->PostTask(
1146 FROM_HERE, Bind(&OrderedFunc, &order, 4)); // never runs
1148 MessageLoop::current()->Run();
1150 ASSERT_EQ(6U, order.Size());
1151 int task_index = 0;
1152 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1153 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1154 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1155 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1156 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
1157 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
1158 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1161 // Tests RunLoopQuit works before RunWithID.
1162 void RunTest_RunLoopQuitOrderBefore(MessageLoop::Type message_loop_type) {
1163 MessageLoop loop(message_loop_type);
1165 TaskList order;
1167 RunLoop run_loop;
1169 run_loop.Quit();
1171 MessageLoop::current()->PostTask(
1172 FROM_HERE, Bind(&OrderedFunc, &order, 1)); // never runs
1173 MessageLoop::current()->PostTask(
1174 FROM_HERE, Bind(&FuncThatQuitsNow)); // never runs
1176 run_loop.Run();
1178 ASSERT_EQ(0U, order.Size());
1181 // Tests RunLoopQuit works during RunWithID.
1182 void RunTest_RunLoopQuitOrderDuring(MessageLoop::Type message_loop_type) {
1183 MessageLoop loop(message_loop_type);
1185 TaskList order;
1187 RunLoop run_loop;
1189 MessageLoop::current()->PostTask(
1190 FROM_HERE, Bind(&OrderedFunc, &order, 1));
1191 MessageLoop::current()->PostTask(
1192 FROM_HERE, run_loop.QuitClosure());
1193 MessageLoop::current()->PostTask(
1194 FROM_HERE, Bind(&OrderedFunc, &order, 2)); // never runs
1195 MessageLoop::current()->PostTask(
1196 FROM_HERE, Bind(&FuncThatQuitsNow)); // never runs
1198 run_loop.Run();
1200 ASSERT_EQ(2U, order.Size());
1201 int task_index = 0;
1202 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, true));
1203 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 1, false));
1204 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1207 // Tests RunLoopQuit works after RunWithID.
1208 void RunTest_RunLoopQuitOrderAfter(MessageLoop::Type message_loop_type) {
1209 MessageLoop loop(message_loop_type);
1211 TaskList order;
1213 RunLoop run_loop;
1215 MessageLoop::current()->PostTask(FROM_HERE,
1216 Bind(&FuncThatRuns, &order, 1, Unretained(&run_loop)));
1217 MessageLoop::current()->PostTask(
1218 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1219 MessageLoop::current()->PostTask(
1220 FROM_HERE, Bind(&FuncThatQuitsNow));
1221 MessageLoop::current()->PostTask(
1222 FROM_HERE, Bind(&OrderedFunc, &order, 3));
1223 MessageLoop::current()->PostTask(
1224 FROM_HERE, run_loop.QuitClosure()); // has no affect
1225 MessageLoop::current()->PostTask(
1226 FROM_HERE, Bind(&OrderedFunc, &order, 4));
1227 MessageLoop::current()->PostTask(
1228 FROM_HERE, Bind(&FuncThatQuitsNow));
1230 RunLoop outer_run_loop;
1231 outer_run_loop.Run();
1233 ASSERT_EQ(8U, order.Size());
1234 int task_index = 0;
1235 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1236 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1237 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1238 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1239 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, true));
1240 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 3, false));
1241 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, true));
1242 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 4, false));
1243 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1246 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1247 void RunTest_RunLoopQuitTop(MessageLoop::Type message_loop_type) {
1248 MessageLoop loop(message_loop_type);
1250 TaskList order;
1252 RunLoop outer_run_loop;
1253 RunLoop nested_run_loop;
1255 MessageLoop::current()->PostTask(FROM_HERE,
1256 Bind(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
1257 MessageLoop::current()->PostTask(
1258 FROM_HERE, outer_run_loop.QuitClosure());
1259 MessageLoop::current()->PostTask(
1260 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1261 MessageLoop::current()->PostTask(
1262 FROM_HERE, nested_run_loop.QuitClosure());
1264 outer_run_loop.Run();
1266 ASSERT_EQ(4U, order.Size());
1267 int task_index = 0;
1268 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1269 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1270 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1271 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1272 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1275 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1276 void RunTest_RunLoopQuitNested(MessageLoop::Type message_loop_type) {
1277 MessageLoop loop(message_loop_type);
1279 TaskList order;
1281 RunLoop outer_run_loop;
1282 RunLoop nested_run_loop;
1284 MessageLoop::current()->PostTask(FROM_HERE,
1285 Bind(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
1286 MessageLoop::current()->PostTask(
1287 FROM_HERE, nested_run_loop.QuitClosure());
1288 MessageLoop::current()->PostTask(
1289 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1290 MessageLoop::current()->PostTask(
1291 FROM_HERE, outer_run_loop.QuitClosure());
1293 outer_run_loop.Run();
1295 ASSERT_EQ(4U, order.Size());
1296 int task_index = 0;
1297 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1298 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1299 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1300 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1301 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1304 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1305 void RunTest_RunLoopQuitBogus(MessageLoop::Type message_loop_type) {
1306 MessageLoop loop(message_loop_type);
1308 TaskList order;
1310 RunLoop outer_run_loop;
1311 RunLoop nested_run_loop;
1312 RunLoop bogus_run_loop;
1314 MessageLoop::current()->PostTask(FROM_HERE,
1315 Bind(&FuncThatRuns, &order, 1, Unretained(&nested_run_loop)));
1316 MessageLoop::current()->PostTask(
1317 FROM_HERE, bogus_run_loop.QuitClosure());
1318 MessageLoop::current()->PostTask(
1319 FROM_HERE, Bind(&OrderedFunc, &order, 2));
1320 MessageLoop::current()->PostTask(
1321 FROM_HERE, outer_run_loop.QuitClosure());
1322 MessageLoop::current()->PostTask(
1323 FROM_HERE, nested_run_loop.QuitClosure());
1325 outer_run_loop.Run();
1327 ASSERT_EQ(4U, order.Size());
1328 int task_index = 0;
1329 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1330 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, true));
1331 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 2, false));
1332 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1333 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1336 // Tests RunLoopQuit only quits the corresponding MessageLoop::Run.
1337 void RunTest_RunLoopQuitDeep(MessageLoop::Type message_loop_type) {
1338 MessageLoop loop(message_loop_type);
1340 TaskList order;
1342 RunLoop outer_run_loop;
1343 RunLoop nested_loop1;
1344 RunLoop nested_loop2;
1345 RunLoop nested_loop3;
1346 RunLoop nested_loop4;
1348 MessageLoop::current()->PostTask(FROM_HERE,
1349 Bind(&FuncThatRuns, &order, 1, Unretained(&nested_loop1)));
1350 MessageLoop::current()->PostTask(FROM_HERE,
1351 Bind(&FuncThatRuns, &order, 2, Unretained(&nested_loop2)));
1352 MessageLoop::current()->PostTask(FROM_HERE,
1353 Bind(&FuncThatRuns, &order, 3, Unretained(&nested_loop3)));
1354 MessageLoop::current()->PostTask(FROM_HERE,
1355 Bind(&FuncThatRuns, &order, 4, Unretained(&nested_loop4)));
1356 MessageLoop::current()->PostTask(
1357 FROM_HERE, Bind(&OrderedFunc, &order, 5));
1358 MessageLoop::current()->PostTask(
1359 FROM_HERE, outer_run_loop.QuitClosure());
1360 MessageLoop::current()->PostTask(
1361 FROM_HERE, Bind(&OrderedFunc, &order, 6));
1362 MessageLoop::current()->PostTask(
1363 FROM_HERE, nested_loop1.QuitClosure());
1364 MessageLoop::current()->PostTask(
1365 FROM_HERE, Bind(&OrderedFunc, &order, 7));
1366 MessageLoop::current()->PostTask(
1367 FROM_HERE, nested_loop2.QuitClosure());
1368 MessageLoop::current()->PostTask(
1369 FROM_HERE, Bind(&OrderedFunc, &order, 8));
1370 MessageLoop::current()->PostTask(
1371 FROM_HERE, nested_loop3.QuitClosure());
1372 MessageLoop::current()->PostTask(
1373 FROM_HERE, Bind(&OrderedFunc, &order, 9));
1374 MessageLoop::current()->PostTask(
1375 FROM_HERE, nested_loop4.QuitClosure());
1376 MessageLoop::current()->PostTask(
1377 FROM_HERE, Bind(&OrderedFunc, &order, 10));
1379 outer_run_loop.Run();
1381 ASSERT_EQ(18U, order.Size());
1382 int task_index = 0;
1383 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, true));
1384 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, true));
1385 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, true));
1386 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, true));
1387 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, true));
1388 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 5, false));
1389 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, true));
1390 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 6, false));
1391 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, true));
1392 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 7, false));
1393 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, true));
1394 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 8, false));
1395 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, true));
1396 EXPECT_EQ(order.Get(task_index++), TaskItem(ORDERED, 9, false));
1397 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 4, false));
1398 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 3, false));
1399 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 2, false));
1400 EXPECT_EQ(order.Get(task_index++), TaskItem(RUNS, 1, false));
1401 EXPECT_EQ(static_cast<size_t>(task_index), order.Size());
1404 void PostNTasksThenQuit(int posts_remaining) {
1405 if (posts_remaining > 1) {
1406 MessageLoop::current()->PostTask(
1407 FROM_HERE,
1408 Bind(&PostNTasksThenQuit, posts_remaining - 1));
1409 } else {
1410 MessageLoop::current()->QuitWhenIdle();
1414 void RunTest_RecursivePosts(MessageLoop::Type message_loop_type,
1415 int num_times) {
1416 MessageLoop loop(message_loop_type);
1417 loop.PostTask(FROM_HERE, Bind(&PostNTasksThenQuit, num_times));
1418 loop.Run();
1421 #if defined(OS_WIN)
1423 class DispatcherImpl : public MessageLoopForUI::Dispatcher {
1424 public:
1425 DispatcherImpl() : dispatch_count_(0) {}
1427 virtual bool Dispatch(const NativeEvent& msg) OVERRIDE {
1428 ::TranslateMessage(&msg);
1429 ::DispatchMessage(&msg);
1430 // Do not count WM_TIMER since it is not what we post and it will cause
1431 // flakiness.
1432 if (msg.message != WM_TIMER)
1433 ++dispatch_count_;
1434 // We treat WM_LBUTTONUP as the last message.
1435 return msg.message != WM_LBUTTONUP;
1438 int dispatch_count_;
1441 void MouseDownUp() {
1442 PostMessage(NULL, WM_LBUTTONDOWN, 0, 0);
1443 PostMessage(NULL, WM_LBUTTONUP, 'A', 0);
1446 void RunTest_Dispatcher(MessageLoop::Type message_loop_type) {
1447 MessageLoop loop(message_loop_type);
1449 MessageLoop::current()->PostDelayedTask(
1450 FROM_HERE,
1451 Bind(&MouseDownUp),
1452 TimeDelta::FromMilliseconds(100));
1453 DispatcherImpl dispatcher;
1454 RunLoop run_loop(&dispatcher);
1455 run_loop.Run();
1456 ASSERT_EQ(2, dispatcher.dispatch_count_);
1459 LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) {
1460 if (code == MessagePumpForUI::kMessageFilterCode) {
1461 MSG* msg = reinterpret_cast<MSG*>(lparam);
1462 if (msg->message == WM_LBUTTONDOWN)
1463 return TRUE;
1465 return FALSE;
1468 void RunTest_DispatcherWithMessageHook(MessageLoop::Type message_loop_type) {
1469 MessageLoop loop(message_loop_type);
1471 MessageLoop::current()->PostDelayedTask(
1472 FROM_HERE,
1473 Bind(&MouseDownUp),
1474 TimeDelta::FromMilliseconds(100));
1475 HHOOK msg_hook = SetWindowsHookEx(WH_MSGFILTER,
1476 MsgFilterProc,
1477 NULL,
1478 GetCurrentThreadId());
1479 DispatcherImpl dispatcher;
1480 RunLoop run_loop(&dispatcher);
1481 run_loop.Run();
1482 ASSERT_EQ(1, dispatcher.dispatch_count_);
1483 UnhookWindowsHookEx(msg_hook);
1486 class TestIOHandler : public MessageLoopForIO::IOHandler {
1487 public:
1488 TestIOHandler(const wchar_t* name, HANDLE signal, bool wait);
1490 virtual void OnIOCompleted(MessageLoopForIO::IOContext* context,
1491 DWORD bytes_transfered, DWORD error);
1493 void Init();
1494 void WaitForIO();
1495 OVERLAPPED* context() { return &context_.overlapped; }
1496 DWORD size() { return sizeof(buffer_); }
1498 private:
1499 char buffer_[48];
1500 MessageLoopForIO::IOContext context_;
1501 HANDLE signal_;
1502 win::ScopedHandle file_;
1503 bool wait_;
1506 TestIOHandler::TestIOHandler(const wchar_t* name, HANDLE signal, bool wait)
1507 : signal_(signal), wait_(wait) {
1508 memset(buffer_, 0, sizeof(buffer_));
1509 memset(&context_, 0, sizeof(context_));
1510 context_.handler = this;
1512 file_.Set(CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING,
1513 FILE_FLAG_OVERLAPPED, NULL));
1514 EXPECT_TRUE(file_.IsValid());
1517 void TestIOHandler::Init() {
1518 MessageLoopForIO::current()->RegisterIOHandler(file_, this);
1520 DWORD read;
1521 EXPECT_FALSE(ReadFile(file_, buffer_, size(), &read, context()));
1522 EXPECT_EQ(ERROR_IO_PENDING, GetLastError());
1523 if (wait_)
1524 WaitForIO();
1527 void TestIOHandler::OnIOCompleted(MessageLoopForIO::IOContext* context,
1528 DWORD bytes_transfered, DWORD error) {
1529 ASSERT_TRUE(context == &context_);
1530 ASSERT_TRUE(SetEvent(signal_));
1533 void TestIOHandler::WaitForIO() {
1534 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(300, this));
1535 EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(400, this));
1538 void RunTest_IOHandler() {
1539 win::ScopedHandle callback_called(CreateEvent(NULL, TRUE, FALSE, NULL));
1540 ASSERT_TRUE(callback_called.IsValid());
1542 const wchar_t* kPipeName = L"\\\\.\\pipe\\iohandler_pipe";
1543 win::ScopedHandle server(
1544 CreateNamedPipe(kPipeName, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1545 ASSERT_TRUE(server.IsValid());
1547 Thread thread("IOHandler test");
1548 Thread::Options options;
1549 options.message_loop_type = MessageLoop::TYPE_IO;
1550 ASSERT_TRUE(thread.StartWithOptions(options));
1552 MessageLoop* thread_loop = thread.message_loop();
1553 ASSERT_TRUE(NULL != thread_loop);
1555 TestIOHandler handler(kPipeName, callback_called, false);
1556 thread_loop->PostTask(FROM_HERE, Bind(&TestIOHandler::Init,
1557 Unretained(&handler)));
1558 // Make sure the thread runs and sleeps for lack of work.
1559 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
1561 const char buffer[] = "Hello there!";
1562 DWORD written;
1563 EXPECT_TRUE(WriteFile(server, buffer, sizeof(buffer), &written, NULL));
1565 DWORD result = WaitForSingleObject(callback_called, 1000);
1566 EXPECT_EQ(WAIT_OBJECT_0, result);
1568 thread.Stop();
1571 void RunTest_WaitForIO() {
1572 win::ScopedHandle callback1_called(
1573 CreateEvent(NULL, TRUE, FALSE, NULL));
1574 win::ScopedHandle callback2_called(
1575 CreateEvent(NULL, TRUE, FALSE, NULL));
1576 ASSERT_TRUE(callback1_called.IsValid());
1577 ASSERT_TRUE(callback2_called.IsValid());
1579 const wchar_t* kPipeName1 = L"\\\\.\\pipe\\iohandler_pipe1";
1580 const wchar_t* kPipeName2 = L"\\\\.\\pipe\\iohandler_pipe2";
1581 win::ScopedHandle server1(
1582 CreateNamedPipe(kPipeName1, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1583 win::ScopedHandle server2(
1584 CreateNamedPipe(kPipeName2, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL));
1585 ASSERT_TRUE(server1.IsValid());
1586 ASSERT_TRUE(server2.IsValid());
1588 Thread thread("IOHandler test");
1589 Thread::Options options;
1590 options.message_loop_type = MessageLoop::TYPE_IO;
1591 ASSERT_TRUE(thread.StartWithOptions(options));
1593 MessageLoop* thread_loop = thread.message_loop();
1594 ASSERT_TRUE(NULL != thread_loop);
1596 TestIOHandler handler1(kPipeName1, callback1_called, false);
1597 TestIOHandler handler2(kPipeName2, callback2_called, true);
1598 thread_loop->PostTask(FROM_HERE, Bind(&TestIOHandler::Init,
1599 Unretained(&handler1)));
1600 // TODO(ajwong): Do we really need such long Sleeps in ths function?
1601 // Make sure the thread runs and sleeps for lack of work.
1602 TimeDelta delay = TimeDelta::FromMilliseconds(100);
1603 PlatformThread::Sleep(delay);
1604 thread_loop->PostTask(FROM_HERE, Bind(&TestIOHandler::Init,
1605 Unretained(&handler2)));
1606 PlatformThread::Sleep(delay);
1608 // At this time handler1 is waiting to be called, and the thread is waiting
1609 // on the Init method of handler2, filtering only handler2 callbacks.
1611 const char buffer[] = "Hello there!";
1612 DWORD written;
1613 EXPECT_TRUE(WriteFile(server1, buffer, sizeof(buffer), &written, NULL));
1614 PlatformThread::Sleep(2 * delay);
1615 EXPECT_EQ(WAIT_TIMEOUT, WaitForSingleObject(callback1_called, 0)) <<
1616 "handler1 has not been called";
1618 EXPECT_TRUE(WriteFile(server2, buffer, sizeof(buffer), &written, NULL));
1620 HANDLE objects[2] = { callback1_called.Get(), callback2_called.Get() };
1621 DWORD result = WaitForMultipleObjects(2, objects, TRUE, 1000);
1622 EXPECT_EQ(WAIT_OBJECT_0, result);
1624 thread.Stop();
1627 #endif // defined(OS_WIN)
1629 } // namespace
1631 //-----------------------------------------------------------------------------
1632 // Each test is run against each type of MessageLoop. That way we are sure
1633 // that message loops work properly in all configurations. Of course, in some
1634 // cases, a unit test may only be for a particular type of loop.
1636 TEST(MessageLoopTest, PostTask) {
1637 RunTest_PostTask(MessageLoop::TYPE_DEFAULT);
1638 RunTest_PostTask(MessageLoop::TYPE_UI);
1639 RunTest_PostTask(MessageLoop::TYPE_IO);
1642 TEST(MessageLoopTest, PostTask_SEH) {
1643 RunTest_PostTask_SEH(MessageLoop::TYPE_DEFAULT);
1644 RunTest_PostTask_SEH(MessageLoop::TYPE_UI);
1645 RunTest_PostTask_SEH(MessageLoop::TYPE_IO);
1648 TEST(MessageLoopTest, PostDelayedTask_Basic) {
1649 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_DEFAULT);
1650 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_UI);
1651 RunTest_PostDelayedTask_Basic(MessageLoop::TYPE_IO);
1654 TEST(MessageLoopTest, PostDelayedTask_InDelayOrder) {
1655 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_DEFAULT);
1656 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_UI);
1657 RunTest_PostDelayedTask_InDelayOrder(MessageLoop::TYPE_IO);
1660 TEST(MessageLoopTest, PostDelayedTask_InPostOrder) {
1661 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_DEFAULT);
1662 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_UI);
1663 RunTest_PostDelayedTask_InPostOrder(MessageLoop::TYPE_IO);
1666 TEST(MessageLoopTest, PostDelayedTask_InPostOrder_2) {
1667 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_DEFAULT);
1668 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_UI);
1669 RunTest_PostDelayedTask_InPostOrder_2(MessageLoop::TYPE_IO);
1672 TEST(MessageLoopTest, PostDelayedTask_InPostOrder_3) {
1673 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_DEFAULT);
1674 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_UI);
1675 RunTest_PostDelayedTask_InPostOrder_3(MessageLoop::TYPE_IO);
1678 TEST(MessageLoopTest, PostDelayedTask_SharedTimer) {
1679 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_DEFAULT);
1680 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_UI);
1681 RunTest_PostDelayedTask_SharedTimer(MessageLoop::TYPE_IO);
1684 #if defined(OS_WIN)
1685 TEST(MessageLoopTest, PostDelayedTask_SharedTimer_SubPump) {
1686 RunTest_PostDelayedTask_SharedTimer_SubPump();
1688 #endif
1690 // TODO(darin): MessageLoop does not support deleting all tasks in the
1691 // destructor.
1692 // Fails, http://crbug.com/50272.
1693 TEST(MessageLoopTest, DISABLED_EnsureDeletion) {
1694 RunTest_EnsureDeletion(MessageLoop::TYPE_DEFAULT);
1695 RunTest_EnsureDeletion(MessageLoop::TYPE_UI);
1696 RunTest_EnsureDeletion(MessageLoop::TYPE_IO);
1699 // TODO(darin): MessageLoop does not support deleting all tasks in the
1700 // destructor.
1701 // Fails, http://crbug.com/50272.
1702 TEST(MessageLoopTest, DISABLED_EnsureDeletion_Chain) {
1703 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_DEFAULT);
1704 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_UI);
1705 RunTest_EnsureDeletion_Chain(MessageLoop::TYPE_IO);
1708 #if defined(OS_WIN)
1709 TEST(MessageLoopTest, Crasher) {
1710 RunTest_Crasher(MessageLoop::TYPE_DEFAULT);
1711 RunTest_Crasher(MessageLoop::TYPE_UI);
1712 RunTest_Crasher(MessageLoop::TYPE_IO);
1715 TEST(MessageLoopTest, CrasherNasty) {
1716 RunTest_CrasherNasty(MessageLoop::TYPE_DEFAULT);
1717 RunTest_CrasherNasty(MessageLoop::TYPE_UI);
1718 RunTest_CrasherNasty(MessageLoop::TYPE_IO);
1720 #endif // defined(OS_WIN)
1722 TEST(MessageLoopTest, Nesting) {
1723 RunTest_Nesting(MessageLoop::TYPE_DEFAULT);
1724 RunTest_Nesting(MessageLoop::TYPE_UI);
1725 RunTest_Nesting(MessageLoop::TYPE_IO);
1728 TEST(MessageLoopTest, RecursiveDenial1) {
1729 RunTest_RecursiveDenial1(MessageLoop::TYPE_DEFAULT);
1730 RunTest_RecursiveDenial1(MessageLoop::TYPE_UI);
1731 RunTest_RecursiveDenial1(MessageLoop::TYPE_IO);
1734 TEST(MessageLoopTest, RecursiveDenial3) {
1735 RunTest_RecursiveDenial3(MessageLoop::TYPE_DEFAULT);
1736 RunTest_RecursiveDenial3(MessageLoop::TYPE_UI);
1737 RunTest_RecursiveDenial3(MessageLoop::TYPE_IO);
1740 TEST(MessageLoopTest, RecursiveSupport1) {
1741 RunTest_RecursiveSupport1(MessageLoop::TYPE_DEFAULT);
1742 RunTest_RecursiveSupport1(MessageLoop::TYPE_UI);
1743 RunTest_RecursiveSupport1(MessageLoop::TYPE_IO);
1746 #if defined(OS_WIN)
1747 // This test occasionally hangs http://crbug.com/44567
1748 TEST(MessageLoopTest, DISABLED_RecursiveDenial2) {
1749 RunTest_RecursiveDenial2(MessageLoop::TYPE_DEFAULT);
1750 RunTest_RecursiveDenial2(MessageLoop::TYPE_UI);
1751 RunTest_RecursiveDenial2(MessageLoop::TYPE_IO);
1754 TEST(MessageLoopTest, RecursiveSupport2) {
1755 // This test requires a UI loop
1756 RunTest_RecursiveSupport2(MessageLoop::TYPE_UI);
1758 #endif // defined(OS_WIN)
1760 TEST(MessageLoopTest, NonNestableWithNoNesting) {
1761 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_DEFAULT);
1762 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_UI);
1763 RunTest_NonNestableWithNoNesting(MessageLoop::TYPE_IO);
1766 TEST(MessageLoopTest, NonNestableInNestedLoop) {
1767 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT, false);
1768 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI, false);
1769 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO, false);
1772 TEST(MessageLoopTest, NonNestableDelayedInNestedLoop) {
1773 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_DEFAULT, true);
1774 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_UI, true);
1775 RunTest_NonNestableInNestedLoop(MessageLoop::TYPE_IO, true);
1778 TEST(MessageLoopTest, QuitNow) {
1779 RunTest_QuitNow(MessageLoop::TYPE_DEFAULT);
1780 RunTest_QuitNow(MessageLoop::TYPE_UI);
1781 RunTest_QuitNow(MessageLoop::TYPE_IO);
1784 TEST(MessageLoopTest, RunLoopQuitTop) {
1785 RunTest_RunLoopQuitTop(MessageLoop::TYPE_DEFAULT);
1786 RunTest_RunLoopQuitTop(MessageLoop::TYPE_UI);
1787 RunTest_RunLoopQuitTop(MessageLoop::TYPE_IO);
1790 TEST(MessageLoopTest, RunLoopQuitNested) {
1791 RunTest_RunLoopQuitNested(MessageLoop::TYPE_DEFAULT);
1792 RunTest_RunLoopQuitNested(MessageLoop::TYPE_UI);
1793 RunTest_RunLoopQuitNested(MessageLoop::TYPE_IO);
1796 TEST(MessageLoopTest, RunLoopQuitBogus) {
1797 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_DEFAULT);
1798 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_UI);
1799 RunTest_RunLoopQuitBogus(MessageLoop::TYPE_IO);
1802 TEST(MessageLoopTest, RunLoopQuitDeep) {
1803 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_DEFAULT);
1804 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_UI);
1805 RunTest_RunLoopQuitDeep(MessageLoop::TYPE_IO);
1808 TEST(MessageLoopTest, RunLoopQuitOrderBefore) {
1809 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_DEFAULT);
1810 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_UI);
1811 RunTest_RunLoopQuitOrderBefore(MessageLoop::TYPE_IO);
1814 TEST(MessageLoopTest, RunLoopQuitOrderDuring) {
1815 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_DEFAULT);
1816 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_UI);
1817 RunTest_RunLoopQuitOrderDuring(MessageLoop::TYPE_IO);
1820 TEST(MessageLoopTest, RunLoopQuitOrderAfter) {
1821 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_DEFAULT);
1822 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_UI);
1823 RunTest_RunLoopQuitOrderAfter(MessageLoop::TYPE_IO);
1826 class DummyTaskObserver : public MessageLoop::TaskObserver {
1827 public:
1828 explicit DummyTaskObserver(int num_tasks)
1829 : num_tasks_started_(0),
1830 num_tasks_processed_(0),
1831 num_tasks_(num_tasks) {}
1833 virtual ~DummyTaskObserver() {}
1835 virtual void WillProcessTask(const PendingTask& pending_task) OVERRIDE {
1836 num_tasks_started_++;
1837 EXPECT_TRUE(pending_task.time_posted != TimeTicks());
1838 EXPECT_LE(num_tasks_started_, num_tasks_);
1839 EXPECT_EQ(num_tasks_started_, num_tasks_processed_ + 1);
1842 virtual void DidProcessTask(const PendingTask& pending_task) OVERRIDE {
1843 num_tasks_processed_++;
1844 EXPECT_TRUE(pending_task.time_posted != TimeTicks());
1845 EXPECT_LE(num_tasks_started_, num_tasks_);
1846 EXPECT_EQ(num_tasks_started_, num_tasks_processed_);
1849 int num_tasks_started() const { return num_tasks_started_; }
1850 int num_tasks_processed() const { return num_tasks_processed_; }
1852 private:
1853 int num_tasks_started_;
1854 int num_tasks_processed_;
1855 const int num_tasks_;
1857 DISALLOW_COPY_AND_ASSIGN(DummyTaskObserver);
1860 TEST(MessageLoopTest, TaskObserver) {
1861 const int kNumPosts = 6;
1862 DummyTaskObserver observer(kNumPosts);
1864 MessageLoop loop;
1865 loop.AddTaskObserver(&observer);
1866 loop.PostTask(FROM_HERE, Bind(&PostNTasksThenQuit, kNumPosts));
1867 loop.Run();
1868 loop.RemoveTaskObserver(&observer);
1870 EXPECT_EQ(kNumPosts, observer.num_tasks_started());
1871 EXPECT_EQ(kNumPosts, observer.num_tasks_processed());
1874 #if defined(OS_WIN)
1875 TEST(MessageLoopTest, Dispatcher) {
1876 // This test requires a UI loop
1877 RunTest_Dispatcher(MessageLoop::TYPE_UI);
1880 TEST(MessageLoopTest, DispatcherWithMessageHook) {
1881 // This test requires a UI loop
1882 RunTest_DispatcherWithMessageHook(MessageLoop::TYPE_UI);
1885 TEST(MessageLoopTest, IOHandler) {
1886 RunTest_IOHandler();
1889 TEST(MessageLoopTest, WaitForIO) {
1890 RunTest_WaitForIO();
1893 TEST(MessageLoopTest, HighResolutionTimer) {
1894 MessageLoop loop;
1896 const TimeDelta kFastTimer = TimeDelta::FromMilliseconds(5);
1897 const TimeDelta kSlowTimer = TimeDelta::FromMilliseconds(100);
1899 EXPECT_FALSE(loop.high_resolution_timers_enabled());
1901 // Post a fast task to enable the high resolution timers.
1902 loop.PostDelayedTask(FROM_HERE, Bind(&PostNTasksThenQuit, 1),
1903 kFastTimer);
1904 loop.Run();
1905 EXPECT_TRUE(loop.high_resolution_timers_enabled());
1907 // Post a slow task and verify high resolution timers
1908 // are still enabled.
1909 loop.PostDelayedTask(FROM_HERE, Bind(&PostNTasksThenQuit, 1),
1910 kSlowTimer);
1911 loop.Run();
1912 EXPECT_TRUE(loop.high_resolution_timers_enabled());
1914 // Wait for a while so that high-resolution mode elapses.
1915 PlatformThread::Sleep(TimeDelta::FromMilliseconds(
1916 MessageLoop::kHighResolutionTimerModeLeaseTimeMs));
1918 // Post a slow task to disable the high resolution timers.
1919 loop.PostDelayedTask(FROM_HERE, Bind(&PostNTasksThenQuit, 1),
1920 kSlowTimer);
1921 loop.Run();
1922 EXPECT_FALSE(loop.high_resolution_timers_enabled());
1925 #endif // defined(OS_WIN)
1927 #if defined(OS_POSIX) && !defined(OS_NACL)
1929 namespace {
1931 class QuitDelegate : public MessageLoopForIO::Watcher {
1932 public:
1933 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
1934 MessageLoop::current()->QuitWhenIdle();
1936 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE {
1937 MessageLoop::current()->QuitWhenIdle();
1941 TEST(MessageLoopTest, FileDescriptorWatcherOutlivesMessageLoop) {
1942 // Simulate a MessageLoop that dies before an FileDescriptorWatcher.
1943 // This could happen when people use the Singleton pattern or atexit.
1945 // Create a file descriptor. Doesn't need to be readable or writable,
1946 // as we don't need to actually get any notifications.
1947 // pipe() is just the easiest way to do it.
1948 int pipefds[2];
1949 int err = pipe(pipefds);
1950 ASSERT_EQ(0, err);
1951 int fd = pipefds[1];
1953 // Arrange for controller to live longer than message loop.
1954 MessageLoopForIO::FileDescriptorWatcher controller;
1956 MessageLoopForIO message_loop;
1958 QuitDelegate delegate;
1959 message_loop.WatchFileDescriptor(fd,
1960 true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate);
1961 // and don't run the message loop, just destroy it.
1964 if (HANDLE_EINTR(close(pipefds[0])) < 0)
1965 PLOG(ERROR) << "close";
1966 if (HANDLE_EINTR(close(pipefds[1])) < 0)
1967 PLOG(ERROR) << "close";
1970 TEST(MessageLoopTest, FileDescriptorWatcherDoubleStop) {
1971 // Verify that it's ok to call StopWatchingFileDescriptor().
1972 // (Errors only showed up in valgrind.)
1973 int pipefds[2];
1974 int err = pipe(pipefds);
1975 ASSERT_EQ(0, err);
1976 int fd = pipefds[1];
1978 // Arrange for message loop to live longer than controller.
1979 MessageLoopForIO message_loop;
1981 MessageLoopForIO::FileDescriptorWatcher controller;
1983 QuitDelegate delegate;
1984 message_loop.WatchFileDescriptor(fd,
1985 true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate);
1986 controller.StopWatchingFileDescriptor();
1989 if (HANDLE_EINTR(close(pipefds[0])) < 0)
1990 PLOG(ERROR) << "close";
1991 if (HANDLE_EINTR(close(pipefds[1])) < 0)
1992 PLOG(ERROR) << "close";
1995 } // namespace
1997 #endif // defined(OS_POSIX) && !defined(OS_NACL)
1999 namespace {
2000 // Inject a test point for recording the destructor calls for Closure objects
2001 // send to MessageLoop::PostTask(). It is awkward usage since we are trying to
2002 // hook the actual destruction, which is not a common operation.
2003 class DestructionObserverProbe :
2004 public RefCounted<DestructionObserverProbe> {
2005 public:
2006 DestructionObserverProbe(bool* task_destroyed,
2007 bool* destruction_observer_called)
2008 : task_destroyed_(task_destroyed),
2009 destruction_observer_called_(destruction_observer_called) {
2011 virtual void Run() {
2012 // This task should never run.
2013 ADD_FAILURE();
2015 private:
2016 friend class RefCounted<DestructionObserverProbe>;
2018 virtual ~DestructionObserverProbe() {
2019 EXPECT_FALSE(*destruction_observer_called_);
2020 *task_destroyed_ = true;
2023 bool* task_destroyed_;
2024 bool* destruction_observer_called_;
2027 class MLDestructionObserver : public MessageLoop::DestructionObserver {
2028 public:
2029 MLDestructionObserver(bool* task_destroyed, bool* destruction_observer_called)
2030 : task_destroyed_(task_destroyed),
2031 destruction_observer_called_(destruction_observer_called),
2032 task_destroyed_before_message_loop_(false) {
2034 virtual void WillDestroyCurrentMessageLoop() OVERRIDE {
2035 task_destroyed_before_message_loop_ = *task_destroyed_;
2036 *destruction_observer_called_ = true;
2038 bool task_destroyed_before_message_loop() const {
2039 return task_destroyed_before_message_loop_;
2041 private:
2042 bool* task_destroyed_;
2043 bool* destruction_observer_called_;
2044 bool task_destroyed_before_message_loop_;
2047 } // namespace
2049 TEST(MessageLoopTest, DestructionObserverTest) {
2050 // Verify that the destruction observer gets called at the very end (after
2051 // all the pending tasks have been destroyed).
2052 MessageLoop* loop = new MessageLoop;
2053 const TimeDelta kDelay = TimeDelta::FromMilliseconds(100);
2055 bool task_destroyed = false;
2056 bool destruction_observer_called = false;
2058 MLDestructionObserver observer(&task_destroyed, &destruction_observer_called);
2059 loop->AddDestructionObserver(&observer);
2060 loop->PostDelayedTask(
2061 FROM_HERE,
2062 Bind(&DestructionObserverProbe::Run,
2063 new DestructionObserverProbe(&task_destroyed,
2064 &destruction_observer_called)),
2065 kDelay);
2066 delete loop;
2067 EXPECT_TRUE(observer.task_destroyed_before_message_loop());
2068 // The task should have been destroyed when we deleted the loop.
2069 EXPECT_TRUE(task_destroyed);
2070 EXPECT_TRUE(destruction_observer_called);
2074 // Verify that MessageLoop sets ThreadMainTaskRunner::current() and it
2075 // posts tasks on that message loop.
2076 TEST(MessageLoopTest, ThreadMainTaskRunner) {
2077 MessageLoop loop;
2079 scoped_refptr<Foo> foo(new Foo());
2080 std::string a("a");
2081 ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, Bind(
2082 &Foo::Test1ConstRef, foo.get(), a));
2084 // Post quit task;
2085 MessageLoop::current()->PostTask(FROM_HERE, Bind(
2086 &MessageLoop::Quit, Unretained(MessageLoop::current())));
2088 // Now kick things off
2089 MessageLoop::current()->Run();
2091 EXPECT_EQ(foo->test_count(), 1);
2092 EXPECT_EQ(foo->result(), "a");
2095 TEST(MessageLoopTest, IsType) {
2096 MessageLoop loop(MessageLoop::TYPE_UI);
2097 EXPECT_TRUE(loop.IsType(MessageLoop::TYPE_UI));
2098 EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_IO));
2099 EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_DEFAULT));
2102 TEST(MessageLoopTest, RecursivePosts) {
2103 // There was a bug in the MessagePumpGLib where posting tasks recursively
2104 // caused the message loop to hang, due to the buffer of the internal pipe
2105 // becoming full. Test all MessageLoop types to ensure this issue does not
2106 // exist in other MessagePumps.
2108 // On Linux, the pipe buffer size is 64KiB by default. The bug caused one
2109 // byte accumulated in the pipe per two posts, so we should repeat 128K
2110 // times to reproduce the bug.
2111 const int kNumTimes = 1 << 17;
2112 RunTest_RecursivePosts(MessageLoop::TYPE_DEFAULT, kNumTimes);
2113 RunTest_RecursivePosts(MessageLoop::TYPE_UI, kNumTimes);
2114 RunTest_RecursivePosts(MessageLoop::TYPE_IO, kNumTimes);
2117 } // namespace base