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 "base/message_pump_glib.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/callback.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/message_loop.h"
17 #include "base/threading/thread.h"
18 #include "testing/gtest/include/gtest/gtest.h"
20 #if defined(TOOLKIT_USES_GTK)
26 // This class injects dummy "events" into the GLib loop. When "handled" these
27 // events can run tasks. This is intended to mock gtk events (the corresponding
28 // GLib source runs at the same priority).
31 EventInjector() : processed_events_(0) {
32 source_
= static_cast<Source
*>(g_source_new(&SourceFuncs
, sizeof(Source
)));
33 source_
->injector
= this;
34 g_source_attach(source_
, NULL
);
35 g_source_set_can_recurse(source_
, TRUE
);
39 g_source_destroy(source_
);
40 g_source_unref(source_
);
44 // If the queue is empty, block.
47 base::TimeDelta delta
= events_
[0].time
- base::Time::NowFromSystemTime();
48 return std::max(0, static_cast<int>(ceil(delta
.InMillisecondsF())));
54 return events_
[0].time
<= base::Time::NowFromSystemTime();
57 void HandleDispatch() {
60 Event event
= events_
[0];
61 events_
.erase(events_
.begin());
63 if (!event
.callback
.is_null())
65 else if (!event
.task
.is_null())
69 // Adds an event to the queue. When "handled", executes |callback|.
70 // delay_ms is relative to the last event if any, or to Now() otherwise.
71 void AddEvent(int delay_ms
, const base::Closure
& callback
) {
72 AddEventHelper(delay_ms
, callback
, base::Closure());
75 void AddDummyEvent(int delay_ms
) {
76 AddEventHelper(delay_ms
, base::Closure(), base::Closure());
79 void AddEventAsTask(int delay_ms
, const base::Closure
& task
) {
80 AddEventHelper(delay_ms
, base::Closure(), task
);
84 processed_events_
= 0;
88 int processed_events() const { return processed_events_
; }
93 base::Closure callback
;
97 struct Source
: public GSource
{
98 EventInjector
* injector
;
102 int delay_ms
, const base::Closure
& callback
, const base::Closure
& task
) {
103 base::Time last_time
;
104 if (!events_
.empty())
105 last_time
= (events_
.end()-1)->time
;
107 last_time
= base::Time::NowFromSystemTime();
109 base::Time future
= last_time
+ base::TimeDelta::FromMilliseconds(delay_ms
);
110 EventInjector::Event event
= {future
, callback
, task
};
111 events_
.push_back(event
);
114 static gboolean
Prepare(GSource
* source
, gint
* timeout_ms
) {
115 *timeout_ms
= static_cast<Source
*>(source
)->injector
->HandlePrepare();
119 static gboolean
Check(GSource
* source
) {
120 return static_cast<Source
*>(source
)->injector
->HandleCheck();
123 static gboolean
Dispatch(GSource
* source
,
124 GSourceFunc unused_func
,
125 gpointer unused_data
) {
126 static_cast<Source
*>(source
)->injector
->HandleDispatch();
131 std::vector
<Event
> events_
;
132 int processed_events_
;
133 static GSourceFuncs SourceFuncs
;
134 DISALLOW_COPY_AND_ASSIGN(EventInjector
);
137 GSourceFuncs
EventInjector::SourceFuncs
= {
138 EventInjector::Prepare
,
139 EventInjector::Check
,
140 EventInjector::Dispatch
,
144 void IncrementInt(int *value
) {
148 // Checks how many events have been processed by the injector.
149 void ExpectProcessedEvents(EventInjector
* injector
, int count
) {
150 EXPECT_EQ(injector
->processed_events(), count
);
153 // Posts a task on the current message loop.
154 void PostMessageLoopTask(const tracked_objects::Location
& from_here
,
155 const base::Closure
& task
) {
156 MessageLoop::current()->PostTask(from_here
, task
);
160 class MessagePumpGLibTest
: public testing::Test
{
162 MessagePumpGLibTest() : loop_(NULL
), injector_(NULL
) { }
164 virtual void SetUp() {
165 loop_
= new MessageLoop(MessageLoop::TYPE_UI
);
166 injector_
= new EventInjector();
169 virtual void TearDown() {
176 MessageLoop
* loop() const { return loop_
; }
177 EventInjector
* injector() const { return injector_
; }
181 EventInjector
* injector_
;
182 DISALLOW_COPY_AND_ASSIGN(MessagePumpGLibTest
);
187 TEST_F(MessagePumpGLibTest
, TestQuit
) {
188 // Checks that Quit works and that the basic infrastructure is working.
191 loop()->PostTask(FROM_HERE
, MessageLoop::QuitClosure());
193 EXPECT_EQ(0, injector()->processed_events());
196 // Quit from an event
197 injector()->AddEvent(0, MessageLoop::QuitClosure());
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()->AddEventAsTask(0, base::Bind(&base::DoNothing
));
211 base::Closure check_task
=
212 base::Bind(&ExpectProcessedEvents
, base::Unretained(injector()), 2);
213 base::Closure posted_task
=
214 base::Bind(&PostMessageLoopTask
, FROM_HERE
, check_task
);
215 injector()->AddEventAsTask(0, posted_task
);
216 injector()->AddEventAsTask(0, base::Bind(&base::DoNothing
));
217 injector()->AddEvent(0, MessageLoop::QuitClosure());
219 EXPECT_EQ(4, injector()->processed_events());
222 injector()->AddEventAsTask(0, base::Bind(&base::DoNothing
));
224 base::Bind(&ExpectProcessedEvents
, base::Unretained(injector()), 2);
225 posted_task
= base::Bind(&PostMessageLoopTask
, FROM_HERE
, check_task
);
226 injector()->AddEventAsTask(0, posted_task
);
227 injector()->AddEventAsTask(10, base::Bind(&base::DoNothing
));
228 injector()->AddEvent(0, MessageLoop::QuitClosure());
230 EXPECT_EQ(4, injector()->processed_events());
233 TEST_F(MessagePumpGLibTest
, TestWorkWhileWaitingForEvents
) {
235 // Tests that we process tasks while waiting for new events.
236 // The event queue is empty at first.
237 for (int i
= 0; i
< 10; ++i
) {
238 loop()->PostTask(FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
240 // After all the previous tasks have executed, enqueue an event that will
244 base::Bind(&EventInjector::AddEvent
, base::Unretained(injector()), 0,
245 MessageLoop::QuitClosure()));
247 ASSERT_EQ(10, task_count
);
248 EXPECT_EQ(1, injector()->processed_events());
250 // Tests that we process delayed tasks while waiting for new events.
253 for (int i
= 0; i
< 10; ++i
) {
254 loop()->PostDelayedTask(
255 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
), 10*i
);
257 // After all the previous tasks have executed, enqueue an event that will
259 // This relies on the fact that delayed tasks are executed in delay order.
260 // That is verified in message_loop_unittest.cc.
261 loop()->PostDelayedTask(
263 base::Bind(&EventInjector::AddEvent
, base::Unretained(injector()), 10,
264 MessageLoop::QuitClosure()), 150);
266 ASSERT_EQ(10, task_count
);
267 EXPECT_EQ(1, injector()->processed_events());
270 TEST_F(MessagePumpGLibTest
, TestEventsWhileWaitingForWork
) {
271 // Tests that we process events while waiting for work.
272 // The event queue is empty at first.
273 for (int i
= 0; i
< 10; ++i
) {
274 injector()->AddDummyEvent(0);
276 // After all the events have been processed, post a task that will check that
277 // the events have been processed (note: the task executes after the event
278 // that posted it has been handled, so we expect 11 at that point).
279 base::Closure check_task
=
280 base::Bind(&ExpectProcessedEvents
, base::Unretained(injector()), 11);
281 base::Closure posted_task
=
282 base::Bind(&PostMessageLoopTask
, FROM_HERE
, check_task
);
283 injector()->AddEventAsTask(10, posted_task
);
285 // And then quit (relies on the condition tested by TestEventTaskInterleave).
286 injector()->AddEvent(10, MessageLoop::QuitClosure());
289 EXPECT_EQ(12, injector()->processed_events());
294 // This class is a helper for the concurrent events / posted tasks test below.
295 // It will quit the main loop once enough tasks and events have been processed,
296 // while making sure there is always work to do and events in the queue.
297 class ConcurrentHelper
: public base::RefCounted
<ConcurrentHelper
> {
299 explicit ConcurrentHelper(EventInjector
* injector
)
300 : injector_(injector
),
301 event_count_(kStartingEventCount
),
302 task_count_(kStartingTaskCount
) {
306 if (task_count_
> 0) {
309 if (task_count_
== 0 && event_count_
== 0) {
310 MessageLoop::current()->Quit();
312 MessageLoop::current()->PostTask(
313 FROM_HERE
, base::Bind(&ConcurrentHelper::FromTask
, this));
318 if (event_count_
> 0) {
321 if (task_count_
== 0 && event_count_
== 0) {
322 MessageLoop::current()->Quit();
324 injector_
->AddEventAsTask(
325 0, base::Bind(&ConcurrentHelper::FromEvent
, this));
329 int event_count() const { return event_count_
; }
330 int task_count() const { return task_count_
; }
333 friend class base::RefCounted
<ConcurrentHelper
>;
335 ~ConcurrentHelper() {}
337 static const int kStartingEventCount
= 20;
338 static const int kStartingTaskCount
= 20;
340 EventInjector
* injector_
;
347 TEST_F(MessagePumpGLibTest
, TestConcurrentEventPostedTask
) {
348 // Tests that posted tasks don't starve events, nor the opposite.
349 // We use the helper class above. We keep both event and posted task queues
350 // full, the helper verifies that both tasks and events get processed.
351 // If that is not the case, either event_count_ or task_count_ will not get
352 // to 0, and MessageLoop::Quit() will never be called.
353 scoped_refptr
<ConcurrentHelper
> helper
= new ConcurrentHelper(injector());
355 // Add 2 events to the queue to make sure it is always full (when we remove
356 // the event before processing it).
357 injector()->AddEventAsTask(
358 0, base::Bind(&ConcurrentHelper::FromEvent
, helper
.get()));
359 injector()->AddEventAsTask(
360 0, base::Bind(&ConcurrentHelper::FromEvent
, helper
.get()));
362 // Similarly post 2 tasks.
364 FROM_HERE
, base::Bind(&ConcurrentHelper::FromTask
, helper
.get()));
366 FROM_HERE
, base::Bind(&ConcurrentHelper::FromTask
, helper
.get()));
369 EXPECT_EQ(0, helper
->event_count());
370 EXPECT_EQ(0, helper
->task_count());
375 void AddEventsAndDrainGLib(EventInjector
* injector
) {
376 // Add a couple of dummy events
377 injector
->AddDummyEvent(0);
378 injector
->AddDummyEvent(0);
379 // Then add an event that will quit the main loop.
380 injector
->AddEvent(0, MessageLoop::QuitClosure());
382 // Post a couple of dummy tasks
383 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(&base::DoNothing
));
384 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(&base::DoNothing
));
387 while (g_main_context_pending(NULL
)) {
388 g_main_context_iteration(NULL
, FALSE
);
394 TEST_F(MessagePumpGLibTest
, TestDrainingGLib
) {
395 // Tests that draining events using GLib works.
398 base::Bind(&AddEventsAndDrainGLib
, base::Unretained(injector())));
401 EXPECT_EQ(3, injector()->processed_events());
407 #if defined(TOOLKIT_USES_GTK)
408 void AddEventsAndDrainGtk(EventInjector
* injector
) {
409 // Add a couple of dummy events
410 injector
->AddDummyEvent(0);
411 injector
->AddDummyEvent(0);
412 // Then add an event that will quit the main loop.
413 injector
->AddEvent(0, MessageLoop::QuitClosure());
415 // Post a couple of dummy tasks
416 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(&base::DoNothing
));
417 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(&base::DoNothing
));
420 while (gtk_events_pending()) {
421 gtk_main_iteration();
428 #if defined(TOOLKIT_USES_GTK)
429 TEST_F(MessagePumpGLibTest
, TestDrainingGtk
) {
430 // Tests that draining events using Gtk works.
433 base::Bind(&AddEventsAndDrainGtk
, base::Unretained(injector())));
436 EXPECT_EQ(3, injector()->processed_events());
442 // Helper class that lets us run the GLib message loop.
443 class GLibLoopRunner
: public base::RefCounted
<GLibLoopRunner
> {
445 GLibLoopRunner() : quit_(false) { }
449 g_main_context_iteration(NULL
, TRUE
);
454 #if defined(TOOLKIT_USES_GTK)
456 gtk_main_iteration();
460 g_main_context_iteration(NULL
, TRUE
);
474 friend class base::RefCounted
<GLibLoopRunner
>;
481 void TestGLibLoopInternal(EventInjector
* injector
) {
482 // Allow tasks to be processed from 'native' event loops.
483 MessageLoop::current()->SetNestableTasksAllowed(true);
484 scoped_refptr
<GLibLoopRunner
> runner
= new GLibLoopRunner();
487 // Add a couple of dummy events
488 injector
->AddDummyEvent(0);
489 injector
->AddDummyEvent(0);
490 // Post a couple of dummy tasks
491 MessageLoop::current()->PostTask(
492 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
493 MessageLoop::current()->PostTask(
494 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
496 injector
->AddDummyEvent(10);
497 injector
->AddDummyEvent(10);
499 MessageLoop::current()->PostDelayedTask(
500 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
), 30);
501 MessageLoop::current()->PostDelayedTask(
502 FROM_HERE
, base::Bind(&GLibLoopRunner::Quit
, runner
.get()), 40);
504 // Run a nested, straight GLib message loop.
507 ASSERT_EQ(3, task_count
);
508 EXPECT_EQ(4, injector
->processed_events());
509 MessageLoop::current()->Quit();
512 void TestGtkLoopInternal(EventInjector
* injector
) {
513 // Allow tasks to be processed from 'native' event loops.
514 MessageLoop::current()->SetNestableTasksAllowed(true);
515 scoped_refptr
<GLibLoopRunner
> runner
= new GLibLoopRunner();
518 // Add a couple of dummy events
519 injector
->AddDummyEvent(0);
520 injector
->AddDummyEvent(0);
521 // Post a couple of dummy tasks
522 MessageLoop::current()->PostTask(
523 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
524 MessageLoop::current()->PostTask(
525 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
527 injector
->AddDummyEvent(10);
528 injector
->AddDummyEvent(10);
530 MessageLoop::current()->PostDelayedTask(
531 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
), 30);
532 MessageLoop::current()->PostDelayedTask(
533 FROM_HERE
, base::Bind(&GLibLoopRunner::Quit
, runner
.get()), 40);
535 // Run a nested, straight Gtk message loop.
538 ASSERT_EQ(3, task_count
);
539 EXPECT_EQ(4, injector
->processed_events());
540 MessageLoop::current()->Quit();
545 TEST_F(MessagePumpGLibTest
, TestGLibLoop
) {
546 // Tests that events and posted tasks are correctly executed if the message
547 // loop is not run by MessageLoop::Run() but by a straight GLib loop.
548 // Note that in this case we don't make strong guarantees about niceness
549 // between events and posted tasks.
552 base::Bind(&TestGLibLoopInternal
, base::Unretained(injector())));
556 TEST_F(MessagePumpGLibTest
, TestGtkLoop
) {
557 // Tests that events and posted tasks are correctly executed if the message
558 // loop is not run by MessageLoop::Run() but by a straight Gtk loop.
559 // Note that in this case we don't make strong guarantees about niceness
560 // between events and posted tasks.
563 base::Bind(&TestGtkLoopInternal
, base::Unretained(injector())));