Updating trunk VERSION from 935.0 to 936.0
[chromium-blink-merge.git] / base / message_pump_glib_unittest.cc
blob69fbb951b0cdef4db0784e0bedb44f69ca3b1e06
1 // Copyright (c) 2011 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 "base/message_pump_glib.h"
7 #include <math.h>
9 #include <algorithm>
10 #include <vector>
12 #include "base/memory/ref_counted.h"
13 #include "base/message_loop.h"
14 #include "base/threading/thread.h"
15 #include "testing/gtest/include/gtest/gtest.h"
17 #if defined(TOOLKIT_USES_GTK)
18 #include <gtk/gtk.h>
19 #endif
21 namespace {
23 // This class injects dummy "events" into the GLib loop. When "handled" these
24 // events can run tasks. This is intended to mock gtk events (the corresponding
25 // GLib source runs at the same priority).
26 class EventInjector {
27 public:
28 EventInjector() : processed_events_(0) {
29 source_ = static_cast<Source*>(g_source_new(&SourceFuncs, sizeof(Source)));
30 source_->injector = this;
31 g_source_attach(source_, NULL);
32 g_source_set_can_recurse(source_, TRUE);
35 ~EventInjector() {
36 g_source_destroy(source_);
37 g_source_unref(source_);
40 int HandlePrepare() {
41 // If the queue is empty, block.
42 if (events_.empty())
43 return -1;
44 base::TimeDelta delta = events_[0].time - base::Time::NowFromSystemTime();
45 return std::max(0, static_cast<int>(ceil(delta.InMillisecondsF())));
48 bool HandleCheck() {
49 if (events_.empty())
50 return false;
51 return events_[0].time <= base::Time::NowFromSystemTime();
54 void HandleDispatch() {
55 if (events_.empty())
56 return;
57 Event event = events_[0];
58 events_.erase(events_.begin());
59 ++processed_events_;
60 if (event.task) {
61 event.task->Run();
62 delete event.task;
66 // Adds an event to the queue. When "handled", executes |task|.
67 // delay_ms is relative to the last event if any, or to Now() otherwise.
68 void AddEvent(int delay_ms, Task* task) {
69 base::Time last_time;
70 if (!events_.empty()) {
71 last_time = (events_.end()-1)->time;
72 } else {
73 last_time = base::Time::NowFromSystemTime();
75 base::Time future = last_time + base::TimeDelta::FromMilliseconds(delay_ms);
76 EventInjector::Event event = { future, task };
77 events_.push_back(event);
80 void Reset() {
81 processed_events_ = 0;
82 events_.clear();
85 int processed_events() const { return processed_events_; }
87 private:
88 struct Event {
89 base::Time time;
90 Task* task;
93 struct Source : public GSource {
94 EventInjector* injector;
97 static gboolean Prepare(GSource* source, gint* timeout_ms) {
98 *timeout_ms = static_cast<Source*>(source)->injector->HandlePrepare();
99 return FALSE;
102 static gboolean Check(GSource* source) {
103 return static_cast<Source*>(source)->injector->HandleCheck();
106 static gboolean Dispatch(GSource* source,
107 GSourceFunc unused_func,
108 gpointer unused_data) {
109 static_cast<Source*>(source)->injector->HandleDispatch();
110 return TRUE;
113 Source* source_;
114 std::vector<Event> events_;
115 int processed_events_;
116 static GSourceFuncs SourceFuncs;
117 DISALLOW_COPY_AND_ASSIGN(EventInjector);
120 GSourceFuncs EventInjector::SourceFuncs = {
121 EventInjector::Prepare,
122 EventInjector::Check,
123 EventInjector::Dispatch,
124 NULL
127 // Does nothing. This function can be called from a task.
128 void DoNothing() {
131 void IncrementInt(int *value) {
132 ++*value;
135 // Checks how many events have been processed by the injector.
136 void ExpectProcessedEvents(EventInjector* injector, int count) {
137 EXPECT_EQ(injector->processed_events(), count);
140 // Quits the current message loop.
141 void QuitMessageLoop() {
142 MessageLoop::current()->Quit();
145 // Returns a new task that quits the main loop.
146 Task* NewQuitTask() {
147 return NewRunnableFunction(QuitMessageLoop);
150 // Posts a task on the current message loop.
151 void PostMessageLoopTask(const tracked_objects::Location& from_here,
152 Task* task) {
153 MessageLoop::current()->PostTask(from_here, task);
156 // Test fixture.
157 class MessagePumpGLibTest : public testing::Test {
158 public:
159 MessagePumpGLibTest() : loop_(NULL), injector_(NULL) { }
161 virtual void SetUp() {
162 loop_ = new MessageLoop(MessageLoop::TYPE_UI);
163 injector_ = new EventInjector();
166 virtual void TearDown() {
167 delete injector_;
168 injector_ = NULL;
169 delete loop_;
170 loop_ = NULL;
173 MessageLoop* loop() const { return loop_; }
174 EventInjector* injector() const { return injector_; }
176 private:
177 MessageLoop* loop_;
178 EventInjector* injector_;
179 DISALLOW_COPY_AND_ASSIGN(MessagePumpGLibTest);
182 } // namespace
184 // EventInjector is expected to always live longer than the runnable methods.
185 DISABLE_RUNNABLE_METHOD_REFCOUNT(EventInjector);
187 TEST_F(MessagePumpGLibTest, TestQuit) {
188 // Checks that Quit works and that the basic infrastructure is working.
190 // Quit from a task
191 loop()->PostTask(FROM_HERE, NewQuitTask());
192 loop()->Run();
193 EXPECT_EQ(0, injector()->processed_events());
195 injector()->Reset();
196 // Quit from an event
197 injector()->AddEvent(0, NewQuitTask());
198 loop()->Run();
199 EXPECT_EQ(1, injector()->processed_events());
202 TEST_F(MessagePumpGLibTest, TestEventTaskInterleave) {
203 // Checks that tasks posted by events are executed before the next event if
204 // the posted task queue is empty.
205 // MessageLoop doesn't make strong guarantees that it is the case, but the
206 // current implementation ensures it and the tests below rely on it.
207 // If changes cause this test to fail, it is reasonable to change it, but
208 // TestWorkWhileWaitingForEvents and TestEventsWhileWaitingForWork have to be
209 // changed accordingly, otherwise they can become flaky.
210 injector()->AddEvent(0, NewRunnableFunction(DoNothing));
211 Task* check_task = NewRunnableFunction(ExpectProcessedEvents, injector(), 2);
212 Task* posted_task = NewRunnableFunction(PostMessageLoopTask,
213 FROM_HERE, check_task);
214 injector()->AddEvent(0, posted_task);
215 injector()->AddEvent(0, NewRunnableFunction(DoNothing));
216 injector()->AddEvent(0, NewQuitTask());
217 loop()->Run();
218 EXPECT_EQ(4, injector()->processed_events());
220 injector()->Reset();
221 injector()->AddEvent(0, NewRunnableFunction(DoNothing));
222 check_task = NewRunnableFunction(ExpectProcessedEvents, injector(), 2);
223 posted_task = NewRunnableFunction(PostMessageLoopTask, FROM_HERE, check_task);
224 injector()->AddEvent(0, posted_task);
225 injector()->AddEvent(10, NewRunnableFunction(DoNothing));
226 injector()->AddEvent(0, NewQuitTask());
227 loop()->Run();
228 EXPECT_EQ(4, injector()->processed_events());
231 TEST_F(MessagePumpGLibTest, TestWorkWhileWaitingForEvents) {
232 int task_count = 0;
233 // Tests that we process tasks while waiting for new events.
234 // The event queue is empty at first.
235 for (int i = 0; i < 10; ++i) {
236 loop()->PostTask(FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
238 // After all the previous tasks have executed, enqueue an event that will
239 // quit.
240 loop()->PostTask(
241 FROM_HERE, NewRunnableMethod(injector(), &EventInjector::AddEvent,
242 0, NewQuitTask()));
243 loop()->Run();
244 ASSERT_EQ(10, task_count);
245 EXPECT_EQ(1, injector()->processed_events());
247 // Tests that we process delayed tasks while waiting for new events.
248 injector()->Reset();
249 task_count = 0;
250 for (int i = 0; i < 10; ++i) {
251 loop()->PostDelayedTask(
252 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count), 10*i);
254 // After all the previous tasks have executed, enqueue an event that will
255 // quit.
256 // This relies on the fact that delayed tasks are executed in delay order.
257 // That is verified in message_loop_unittest.cc.
258 loop()->PostDelayedTask(
259 FROM_HERE, NewRunnableMethod(injector(), &EventInjector::AddEvent,
260 10, NewQuitTask()), 150);
261 loop()->Run();
262 ASSERT_EQ(10, task_count);
263 EXPECT_EQ(1, injector()->processed_events());
266 TEST_F(MessagePumpGLibTest, TestEventsWhileWaitingForWork) {
267 // Tests that we process events while waiting for work.
268 // The event queue is empty at first.
269 for (int i = 0; i < 10; ++i) {
270 injector()->AddEvent(0, NULL);
272 // After all the events have been processed, post a task that will check that
273 // the events have been processed (note: the task executes after the event
274 // that posted it has been handled, so we expect 11 at that point).
275 Task* check_task = NewRunnableFunction(ExpectProcessedEvents, injector(), 11);
276 Task* posted_task = NewRunnableFunction(PostMessageLoopTask,
277 FROM_HERE, check_task);
278 injector()->AddEvent(10, posted_task);
280 // And then quit (relies on the condition tested by TestEventTaskInterleave).
281 injector()->AddEvent(10, NewQuitTask());
282 loop()->Run();
284 EXPECT_EQ(12, injector()->processed_events());
287 namespace {
289 // This class is a helper for the concurrent events / posted tasks test below.
290 // It will quit the main loop once enough tasks and events have been processed,
291 // while making sure there is always work to do and events in the queue.
292 class ConcurrentHelper : public base::RefCounted<ConcurrentHelper> {
293 public:
294 explicit ConcurrentHelper(EventInjector* injector)
295 : injector_(injector),
296 event_count_(kStartingEventCount),
297 task_count_(kStartingTaskCount) {
300 void FromTask() {
301 if (task_count_ > 0) {
302 --task_count_;
304 if (task_count_ == 0 && event_count_ == 0) {
305 MessageLoop::current()->Quit();
306 } else {
307 MessageLoop::current()->PostTask(
308 FROM_HERE, NewRunnableMethod(this, &ConcurrentHelper::FromTask));
312 void FromEvent() {
313 if (event_count_ > 0) {
314 --event_count_;
316 if (task_count_ == 0 && event_count_ == 0) {
317 MessageLoop::current()->Quit();
318 } else {
319 injector_->AddEvent(
320 0, NewRunnableMethod(this, &ConcurrentHelper::FromEvent));
324 int event_count() const { return event_count_; }
325 int task_count() const { return task_count_; }
327 private:
328 friend class base::RefCounted<ConcurrentHelper>;
330 ~ConcurrentHelper() {}
332 static const int kStartingEventCount = 20;
333 static const int kStartingTaskCount = 20;
335 EventInjector* injector_;
336 int event_count_;
337 int task_count_;
340 } // namespace
342 TEST_F(MessagePumpGLibTest, TestConcurrentEventPostedTask) {
343 // Tests that posted tasks don't starve events, nor the opposite.
344 // We use the helper class above. We keep both event and posted task queues
345 // full, the helper verifies that both tasks and events get processed.
346 // If that is not the case, either event_count_ or task_count_ will not get
347 // to 0, and MessageLoop::Quit() will never be called.
348 scoped_refptr<ConcurrentHelper> helper = new ConcurrentHelper(injector());
350 // Add 2 events to the queue to make sure it is always full (when we remove
351 // the event before processing it).
352 injector()->AddEvent(
353 0, NewRunnableMethod(helper.get(), &ConcurrentHelper::FromEvent));
354 injector()->AddEvent(
355 0, NewRunnableMethod(helper.get(), &ConcurrentHelper::FromEvent));
357 // Similarly post 2 tasks.
358 loop()->PostTask(
359 FROM_HERE, NewRunnableMethod(helper.get(), &ConcurrentHelper::FromTask));
360 loop()->PostTask(
361 FROM_HERE, NewRunnableMethod(helper.get(), &ConcurrentHelper::FromTask));
363 loop()->Run();
364 EXPECT_EQ(0, helper->event_count());
365 EXPECT_EQ(0, helper->task_count());
368 namespace {
370 void AddEventsAndDrainGLib(EventInjector* injector) {
371 // Add a couple of dummy events
372 injector->AddEvent(0, NULL);
373 injector->AddEvent(0, NULL);
374 // Then add an event that will quit the main loop.
375 injector->AddEvent(0, NewQuitTask());
377 // Post a couple of dummy tasks
378 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(DoNothing));
379 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(DoNothing));
381 // Drain the events
382 while (g_main_context_pending(NULL)) {
383 g_main_context_iteration(NULL, FALSE);
387 } // namespace
389 TEST_F(MessagePumpGLibTest, TestDrainingGLib) {
390 // Tests that draining events using GLib works.
391 loop()->PostTask(
392 FROM_HERE, NewRunnableFunction(AddEventsAndDrainGLib, injector()));
393 loop()->Run();
395 EXPECT_EQ(3, injector()->processed_events());
399 namespace {
401 #if defined(TOOLKIT_USES_GTK)
402 void AddEventsAndDrainGtk(EventInjector* injector) {
403 // Add a couple of dummy events
404 injector->AddEvent(0, NULL);
405 injector->AddEvent(0, NULL);
406 // Then add an event that will quit the main loop.
407 injector->AddEvent(0, NewQuitTask());
409 // Post a couple of dummy tasks
410 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(DoNothing));
411 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(DoNothing));
413 // Drain the events
414 while (gtk_events_pending()) {
415 gtk_main_iteration();
418 #endif
420 } // namespace
422 #if defined(TOOLKIT_USES_GTK)
423 TEST_F(MessagePumpGLibTest, TestDrainingGtk) {
424 // Tests that draining events using Gtk works.
425 loop()->PostTask(
426 FROM_HERE, NewRunnableFunction(AddEventsAndDrainGtk, injector()));
427 loop()->Run();
429 EXPECT_EQ(3, injector()->processed_events());
431 #endif
433 namespace {
435 // Helper class that lets us run the GLib message loop.
436 class GLibLoopRunner : public base::RefCounted<GLibLoopRunner> {
437 public:
438 GLibLoopRunner() : quit_(false) { }
440 void RunGLib() {
441 while (!quit_) {
442 g_main_context_iteration(NULL, TRUE);
446 void RunLoop() {
447 #if defined(TOOLKIT_USES_GTK)
448 while (!quit_) {
449 gtk_main_iteration();
451 #else
452 while (!quit_) {
453 g_main_context_iteration(NULL, TRUE);
455 #endif
458 void Quit() {
459 quit_ = true;
462 void Reset() {
463 quit_ = false;
466 private:
467 friend class base::RefCounted<GLibLoopRunner>;
469 ~GLibLoopRunner() {}
471 bool quit_;
474 void TestGLibLoopInternal(EventInjector* injector) {
475 // Allow tasks to be processed from 'native' event loops.
476 MessageLoop::current()->SetNestableTasksAllowed(true);
477 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
479 int task_count = 0;
480 // Add a couple of dummy events
481 injector->AddEvent(0, NULL);
482 injector->AddEvent(0, NULL);
483 // Post a couple of dummy tasks
484 MessageLoop::current()->PostTask(
485 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
486 MessageLoop::current()->PostTask(
487 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
488 // Delayed events
489 injector->AddEvent(10, NULL);
490 injector->AddEvent(10, NULL);
491 // Delayed work
492 MessageLoop::current()->PostDelayedTask(
493 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count), 30);
494 MessageLoop::current()->PostDelayedTask(
495 FROM_HERE, NewRunnableMethod(runner.get(), &GLibLoopRunner::Quit), 40);
497 // Run a nested, straight GLib message loop.
498 runner->RunGLib();
500 ASSERT_EQ(3, task_count);
501 EXPECT_EQ(4, injector->processed_events());
502 MessageLoop::current()->Quit();
505 void TestGtkLoopInternal(EventInjector* injector) {
506 // Allow tasks to be processed from 'native' event loops.
507 MessageLoop::current()->SetNestableTasksAllowed(true);
508 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
510 int task_count = 0;
511 // Add a couple of dummy events
512 injector->AddEvent(0, NULL);
513 injector->AddEvent(0, NULL);
514 // Post a couple of dummy tasks
515 MessageLoop::current()->PostTask(
516 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
517 MessageLoop::current()->PostTask(
518 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count));
519 // Delayed events
520 injector->AddEvent(10, NULL);
521 injector->AddEvent(10, NULL);
522 // Delayed work
523 MessageLoop::current()->PostDelayedTask(
524 FROM_HERE, NewRunnableFunction(IncrementInt, &task_count), 30);
525 MessageLoop::current()->PostDelayedTask(
526 FROM_HERE, NewRunnableMethod(runner.get(), &GLibLoopRunner::Quit), 40);
528 // Run a nested, straight Gtk message loop.
529 runner->RunLoop();
531 ASSERT_EQ(3, task_count);
532 EXPECT_EQ(4, injector->processed_events());
533 MessageLoop::current()->Quit();
536 } // namespace
538 TEST_F(MessagePumpGLibTest, TestGLibLoop) {
539 // Tests that events and posted tasks are correctly exectuted if the message
540 // loop is not run by MessageLoop::Run() but by a straight GLib loop.
541 // Note that in this case we don't make strong guarantees about niceness
542 // between events and posted tasks.
543 loop()->PostTask(FROM_HERE,
544 NewRunnableFunction(TestGLibLoopInternal, injector()));
545 loop()->Run();
548 TEST_F(MessagePumpGLibTest, TestGtkLoop) {
549 // Tests that events and posted tasks are correctly exectuted if the message
550 // loop is not run by MessageLoop::Run() but by a straight Gtk loop.
551 // Note that in this case we don't make strong guarantees about niceness
552 // between events and posted tasks.
553 loop()->PostTask(FROM_HERE,
554 NewRunnableFunction(TestGtkLoopInternal, injector()));
555 loop()->Run();