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"
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)
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).
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
);
36 g_source_destroy(source_
);
37 g_source_unref(source_
);
41 // If the queue is empty, block.
44 base::TimeDelta delta
= events_
[0].time
- base::Time::NowFromSystemTime();
45 return std::max(0, static_cast<int>(ceil(delta
.InMillisecondsF())));
51 return events_
[0].time
<= base::Time::NowFromSystemTime();
54 void HandleDispatch() {
57 Event event
= events_
[0];
58 events_
.erase(events_
.begin());
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
) {
70 if (!events_
.empty()) {
71 last_time
= (events_
.end()-1)->time
;
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
);
81 processed_events_
= 0;
85 int processed_events() const { return processed_events_
; }
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();
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();
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
,
127 // Does nothing. This function can be called from a task.
131 void IncrementInt(int *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
,
153 MessageLoop::current()->PostTask(from_here
, task
);
157 class MessagePumpGLibTest
: public testing::Test
{
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() {
173 MessageLoop
* loop() const { return loop_
; }
174 EventInjector
* injector() const { return injector_
; }
178 EventInjector
* injector_
;
179 DISALLOW_COPY_AND_ASSIGN(MessagePumpGLibTest
);
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.
191 loop()->PostTask(FROM_HERE
, NewQuitTask());
193 EXPECT_EQ(0, injector()->processed_events());
196 // Quit from an event
197 injector()->AddEvent(0, NewQuitTask());
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());
218 EXPECT_EQ(4, injector()->processed_events());
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());
228 EXPECT_EQ(4, injector()->processed_events());
231 TEST_F(MessagePumpGLibTest
, TestWorkWhileWaitingForEvents
) {
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
241 FROM_HERE
, NewRunnableMethod(injector(), &EventInjector::AddEvent
,
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.
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
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);
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());
284 EXPECT_EQ(12, injector()->processed_events());
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
> {
294 explicit ConcurrentHelper(EventInjector
* injector
)
295 : injector_(injector
),
296 event_count_(kStartingEventCount
),
297 task_count_(kStartingTaskCount
) {
301 if (task_count_
> 0) {
304 if (task_count_
== 0 && event_count_
== 0) {
305 MessageLoop::current()->Quit();
307 MessageLoop::current()->PostTask(
308 FROM_HERE
, NewRunnableMethod(this, &ConcurrentHelper::FromTask
));
313 if (event_count_
> 0) {
316 if (task_count_
== 0 && event_count_
== 0) {
317 MessageLoop::current()->Quit();
320 0, NewRunnableMethod(this, &ConcurrentHelper::FromEvent
));
324 int event_count() const { return event_count_
; }
325 int task_count() const { return task_count_
; }
328 friend class base::RefCounted
<ConcurrentHelper
>;
330 ~ConcurrentHelper() {}
332 static const int kStartingEventCount
= 20;
333 static const int kStartingTaskCount
= 20;
335 EventInjector
* injector_
;
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.
359 FROM_HERE
, NewRunnableMethod(helper
.get(), &ConcurrentHelper::FromTask
));
361 FROM_HERE
, NewRunnableMethod(helper
.get(), &ConcurrentHelper::FromTask
));
364 EXPECT_EQ(0, helper
->event_count());
365 EXPECT_EQ(0, helper
->task_count());
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
));
382 while (g_main_context_pending(NULL
)) {
383 g_main_context_iteration(NULL
, FALSE
);
389 TEST_F(MessagePumpGLibTest
, TestDrainingGLib
) {
390 // Tests that draining events using GLib works.
392 FROM_HERE
, NewRunnableFunction(AddEventsAndDrainGLib
, injector()));
395 EXPECT_EQ(3, injector()->processed_events());
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
));
414 while (gtk_events_pending()) {
415 gtk_main_iteration();
422 #if defined(TOOLKIT_USES_GTK)
423 TEST_F(MessagePumpGLibTest
, TestDrainingGtk
) {
424 // Tests that draining events using Gtk works.
426 FROM_HERE
, NewRunnableFunction(AddEventsAndDrainGtk
, injector()));
429 EXPECT_EQ(3, injector()->processed_events());
435 // Helper class that lets us run the GLib message loop.
436 class GLibLoopRunner
: public base::RefCounted
<GLibLoopRunner
> {
438 GLibLoopRunner() : quit_(false) { }
442 g_main_context_iteration(NULL
, TRUE
);
447 #if defined(TOOLKIT_USES_GTK)
449 gtk_main_iteration();
453 g_main_context_iteration(NULL
, TRUE
);
467 friend class base::RefCounted
<GLibLoopRunner
>;
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();
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
));
489 injector
->AddEvent(10, NULL
);
490 injector
->AddEvent(10, NULL
);
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.
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();
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
));
520 injector
->AddEvent(10, NULL
);
521 injector
->AddEvent(10, NULL
);
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.
531 ASSERT_EQ(3, task_count
);
532 EXPECT_EQ(4, injector
->processed_events());
533 MessageLoop::current()->Quit();
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()));
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()));