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"
13 #include "base/bind.h"
14 #include "base/bind_helpers.h"
15 #include "base/callback.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/message_loop.h"
18 #include "base/run_loop.h"
19 #include "base/threading/thread.h"
20 #include "testing/gtest/include/gtest/gtest.h"
22 #if defined(TOOLKIT_GTK)
29 // This class injects dummy "events" into the GLib loop. When "handled" these
30 // events can run tasks. This is intended to mock gtk events (the corresponding
31 // GLib source runs at the same priority).
34 EventInjector() : processed_events_(0) {
35 source_
= static_cast<Source
*>(g_source_new(&SourceFuncs
, sizeof(Source
)));
36 source_
->injector
= this;
37 g_source_attach(source_
, NULL
);
38 g_source_set_can_recurse(source_
, TRUE
);
42 g_source_destroy(source_
);
43 g_source_unref(source_
);
47 // If the queue is empty, block.
50 base::TimeDelta delta
= events_
[0].time
- base::Time::NowFromSystemTime();
51 return std::max(0, static_cast<int>(ceil(delta
.InMillisecondsF())));
57 return events_
[0].time
<= base::Time::NowFromSystemTime();
60 void HandleDispatch() {
63 Event event
= events_
[0];
64 events_
.erase(events_
.begin());
66 if (!event
.callback
.is_null())
68 else if (!event
.task
.is_null())
72 // Adds an event to the queue. When "handled", executes |callback|.
73 // delay_ms is relative to the last event if any, or to Now() otherwise.
74 void AddEvent(int delay_ms
, const base::Closure
& callback
) {
75 AddEventHelper(delay_ms
, callback
, base::Closure());
78 void AddDummyEvent(int delay_ms
) {
79 AddEventHelper(delay_ms
, base::Closure(), base::Closure());
82 void AddEventAsTask(int delay_ms
, const base::Closure
& task
) {
83 AddEventHelper(delay_ms
, base::Closure(), task
);
87 processed_events_
= 0;
91 int processed_events() const { return processed_events_
; }
96 base::Closure callback
;
100 struct Source
: public GSource
{
101 EventInjector
* injector
;
105 int delay_ms
, const base::Closure
& callback
, const base::Closure
& task
) {
106 base::Time last_time
;
107 if (!events_
.empty())
108 last_time
= (events_
.end()-1)->time
;
110 last_time
= base::Time::NowFromSystemTime();
112 base::Time future
= last_time
+ base::TimeDelta::FromMilliseconds(delay_ms
);
113 EventInjector::Event event
= {future
, callback
, task
};
114 events_
.push_back(event
);
117 static gboolean
Prepare(GSource
* source
, gint
* timeout_ms
) {
118 *timeout_ms
= static_cast<Source
*>(source
)->injector
->HandlePrepare();
122 static gboolean
Check(GSource
* source
) {
123 return static_cast<Source
*>(source
)->injector
->HandleCheck();
126 static gboolean
Dispatch(GSource
* source
,
127 GSourceFunc unused_func
,
128 gpointer unused_data
) {
129 static_cast<Source
*>(source
)->injector
->HandleDispatch();
134 std::vector
<Event
> events_
;
135 int processed_events_
;
136 static GSourceFuncs SourceFuncs
;
137 DISALLOW_COPY_AND_ASSIGN(EventInjector
);
140 GSourceFuncs
EventInjector::SourceFuncs
= {
141 EventInjector::Prepare
,
142 EventInjector::Check
,
143 EventInjector::Dispatch
,
147 void IncrementInt(int *value
) {
151 // Checks how many events have been processed by the injector.
152 void ExpectProcessedEvents(EventInjector
* injector
, int count
) {
153 EXPECT_EQ(injector
->processed_events(), count
);
156 // Posts a task on the current message loop.
157 void PostMessageLoopTask(const tracked_objects::Location
& from_here
,
158 const base::Closure
& task
) {
159 MessageLoop::current()->PostTask(from_here
, task
);
163 class MessagePumpGLibTest
: public testing::Test
{
165 MessagePumpGLibTest() : loop_(NULL
), injector_(NULL
) { }
167 // Overridden from testing::Test:
168 virtual void SetUp() OVERRIDE
{
169 loop_
= new MessageLoop(MessageLoop::TYPE_UI
);
170 injector_
= new EventInjector();
172 virtual void TearDown() OVERRIDE
{
179 MessageLoop
* loop() const { return loop_
; }
180 EventInjector
* injector() const { return injector_
; }
184 EventInjector
* injector_
;
185 DISALLOW_COPY_AND_ASSIGN(MessagePumpGLibTest
);
190 TEST_F(MessagePumpGLibTest
, TestQuit
) {
191 // Checks that Quit works and that the basic infrastructure is working.
194 RunLoop().RunUntilIdle();
195 EXPECT_EQ(0, injector()->processed_events());
198 // Quit from an event
199 injector()->AddEvent(0, MessageLoop::QuitWhenIdleClosure());
201 EXPECT_EQ(1, injector()->processed_events());
204 TEST_F(MessagePumpGLibTest
, TestEventTaskInterleave
) {
205 // Checks that tasks posted by events are executed before the next event if
206 // the posted task queue is empty.
207 // MessageLoop doesn't make strong guarantees that it is the case, but the
208 // current implementation ensures it and the tests below rely on it.
209 // If changes cause this test to fail, it is reasonable to change it, but
210 // TestWorkWhileWaitingForEvents and TestEventsWhileWaitingForWork have to be
211 // changed accordingly, otherwise they can become flaky.
212 injector()->AddEventAsTask(0, base::Bind(&base::DoNothing
));
213 base::Closure check_task
=
214 base::Bind(&ExpectProcessedEvents
, base::Unretained(injector()), 2);
215 base::Closure posted_task
=
216 base::Bind(&PostMessageLoopTask
, FROM_HERE
, check_task
);
217 injector()->AddEventAsTask(0, posted_task
);
218 injector()->AddEventAsTask(0, base::Bind(&base::DoNothing
));
219 injector()->AddEvent(0, MessageLoop::QuitWhenIdleClosure());
221 EXPECT_EQ(4, injector()->processed_events());
224 injector()->AddEventAsTask(0, base::Bind(&base::DoNothing
));
226 base::Bind(&ExpectProcessedEvents
, base::Unretained(injector()), 2);
227 posted_task
= base::Bind(&PostMessageLoopTask
, FROM_HERE
, check_task
);
228 injector()->AddEventAsTask(0, posted_task
);
229 injector()->AddEventAsTask(10, base::Bind(&base::DoNothing
));
230 injector()->AddEvent(0, MessageLoop::QuitWhenIdleClosure());
232 EXPECT_EQ(4, injector()->processed_events());
235 TEST_F(MessagePumpGLibTest
, TestWorkWhileWaitingForEvents
) {
237 // Tests that we process tasks while waiting for new events.
238 // The event queue is empty at first.
239 for (int i
= 0; i
< 10; ++i
) {
240 loop()->PostTask(FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
242 // After all the previous tasks have executed, enqueue an event that will
246 base::Bind(&EventInjector::AddEvent
, base::Unretained(injector()), 0,
247 MessageLoop::QuitWhenIdleClosure()));
249 ASSERT_EQ(10, task_count
);
250 EXPECT_EQ(1, injector()->processed_events());
252 // Tests that we process delayed tasks while waiting for new events.
255 for (int i
= 0; i
< 10; ++i
) {
256 loop()->PostDelayedTask(
258 base::Bind(&IncrementInt
, &task_count
),
259 base::TimeDelta::FromMilliseconds(10*i
));
261 // After all the previous tasks have executed, enqueue an event that will
263 // This relies on the fact that delayed tasks are executed in delay order.
264 // That is verified in message_loop_unittest.cc.
265 loop()->PostDelayedTask(
267 base::Bind(&EventInjector::AddEvent
, base::Unretained(injector()), 10,
268 MessageLoop::QuitWhenIdleClosure()),
269 base::TimeDelta::FromMilliseconds(150));
271 ASSERT_EQ(10, task_count
);
272 EXPECT_EQ(1, injector()->processed_events());
275 TEST_F(MessagePumpGLibTest
, TestEventsWhileWaitingForWork
) {
276 // Tests that we process events while waiting for work.
277 // The event queue is empty at first.
278 for (int i
= 0; i
< 10; ++i
) {
279 injector()->AddDummyEvent(0);
281 // After all the events have been processed, post a task that will check that
282 // the events have been processed (note: the task executes after the event
283 // that posted it has been handled, so we expect 11 at that point).
284 base::Closure check_task
=
285 base::Bind(&ExpectProcessedEvents
, base::Unretained(injector()), 11);
286 base::Closure posted_task
=
287 base::Bind(&PostMessageLoopTask
, FROM_HERE
, check_task
);
288 injector()->AddEventAsTask(10, posted_task
);
290 // And then quit (relies on the condition tested by TestEventTaskInterleave).
291 injector()->AddEvent(10, MessageLoop::QuitWhenIdleClosure());
294 EXPECT_EQ(12, injector()->processed_events());
299 // This class is a helper for the concurrent events / posted tasks test below.
300 // It will quit the main loop once enough tasks and events have been processed,
301 // while making sure there is always work to do and events in the queue.
302 class ConcurrentHelper
: public base::RefCounted
<ConcurrentHelper
> {
304 explicit ConcurrentHelper(EventInjector
* injector
)
305 : injector_(injector
),
306 event_count_(kStartingEventCount
),
307 task_count_(kStartingTaskCount
) {
311 if (task_count_
> 0) {
314 if (task_count_
== 0 && event_count_
== 0) {
315 MessageLoop::current()->QuitWhenIdle();
317 MessageLoop::current()->PostTask(
318 FROM_HERE
, base::Bind(&ConcurrentHelper::FromTask
, this));
323 if (event_count_
> 0) {
326 if (task_count_
== 0 && event_count_
== 0) {
327 MessageLoop::current()->QuitWhenIdle();
329 injector_
->AddEventAsTask(
330 0, base::Bind(&ConcurrentHelper::FromEvent
, this));
334 int event_count() const { return event_count_
; }
335 int task_count() const { return task_count_
; }
338 friend class base::RefCounted
<ConcurrentHelper
>;
340 ~ConcurrentHelper() {}
342 static const int kStartingEventCount
= 20;
343 static const int kStartingTaskCount
= 20;
345 EventInjector
* injector_
;
352 TEST_F(MessagePumpGLibTest
, TestConcurrentEventPostedTask
) {
353 // Tests that posted tasks don't starve events, nor the opposite.
354 // We use the helper class above. We keep both event and posted task queues
355 // full, the helper verifies that both tasks and events get processed.
356 // If that is not the case, either event_count_ or task_count_ will not get
357 // to 0, and MessageLoop::QuitWhenIdle() will never be called.
358 scoped_refptr
<ConcurrentHelper
> helper
= new ConcurrentHelper(injector());
360 // Add 2 events to the queue to make sure it is always full (when we remove
361 // the event before processing it).
362 injector()->AddEventAsTask(
363 0, base::Bind(&ConcurrentHelper::FromEvent
, helper
.get()));
364 injector()->AddEventAsTask(
365 0, base::Bind(&ConcurrentHelper::FromEvent
, helper
.get()));
367 // Similarly post 2 tasks.
369 FROM_HERE
, base::Bind(&ConcurrentHelper::FromTask
, helper
.get()));
371 FROM_HERE
, base::Bind(&ConcurrentHelper::FromTask
, helper
.get()));
374 EXPECT_EQ(0, helper
->event_count());
375 EXPECT_EQ(0, helper
->task_count());
380 void AddEventsAndDrainGLib(EventInjector
* injector
) {
381 // Add a couple of dummy events
382 injector
->AddDummyEvent(0);
383 injector
->AddDummyEvent(0);
384 // Then add an event that will quit the main loop.
385 injector
->AddEvent(0, MessageLoop::QuitWhenIdleClosure());
387 // Post a couple of dummy tasks
388 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(&base::DoNothing
));
389 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(&base::DoNothing
));
392 while (g_main_context_pending(NULL
)) {
393 g_main_context_iteration(NULL
, FALSE
);
399 TEST_F(MessagePumpGLibTest
, TestDrainingGLib
) {
400 // Tests that draining events using GLib works.
403 base::Bind(&AddEventsAndDrainGLib
, base::Unretained(injector())));
406 EXPECT_EQ(3, injector()->processed_events());
412 #if defined(TOOLKIT_GTK)
413 void AddEventsAndDrainGtk(EventInjector
* injector
) {
414 // Add a couple of dummy events
415 injector
->AddDummyEvent(0);
416 injector
->AddDummyEvent(0);
417 // Then add an event that will quit the main loop.
418 injector
->AddEvent(0, MessageLoop::QuitWhenIdleClosure());
420 // Post a couple of dummy tasks
421 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(&base::DoNothing
));
422 MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(&base::DoNothing
));
425 while (gtk_events_pending()) {
426 gtk_main_iteration();
433 #if defined(TOOLKIT_GTK)
434 TEST_F(MessagePumpGLibTest
, TestDrainingGtk
) {
435 // Tests that draining events using Gtk works.
438 base::Bind(&AddEventsAndDrainGtk
, base::Unretained(injector())));
441 EXPECT_EQ(3, injector()->processed_events());
447 // Helper class that lets us run the GLib message loop.
448 class GLibLoopRunner
: public base::RefCounted
<GLibLoopRunner
> {
450 GLibLoopRunner() : quit_(false) { }
454 g_main_context_iteration(NULL
, TRUE
);
459 #if defined(TOOLKIT_GTK)
461 gtk_main_iteration();
465 g_main_context_iteration(NULL
, TRUE
);
479 friend class base::RefCounted
<GLibLoopRunner
>;
486 void TestGLibLoopInternal(EventInjector
* injector
) {
487 // Allow tasks to be processed from 'native' event loops.
488 MessageLoop::current()->SetNestableTasksAllowed(true);
489 scoped_refptr
<GLibLoopRunner
> runner
= new GLibLoopRunner();
492 // Add a couple of dummy events
493 injector
->AddDummyEvent(0);
494 injector
->AddDummyEvent(0);
495 // Post a couple of dummy tasks
496 MessageLoop::current()->PostTask(
497 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
498 MessageLoop::current()->PostTask(
499 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
501 injector
->AddDummyEvent(10);
502 injector
->AddDummyEvent(10);
504 MessageLoop::current()->PostDelayedTask(
506 base::Bind(&IncrementInt
, &task_count
),
507 base::TimeDelta::FromMilliseconds(30));
508 MessageLoop::current()->PostDelayedTask(
510 base::Bind(&GLibLoopRunner::Quit
, runner
.get()),
511 base::TimeDelta::FromMilliseconds(40));
513 // Run a nested, straight GLib message loop.
516 ASSERT_EQ(3, task_count
);
517 EXPECT_EQ(4, injector
->processed_events());
518 MessageLoop::current()->QuitWhenIdle();
521 void TestGtkLoopInternal(EventInjector
* injector
) {
522 // Allow tasks to be processed from 'native' event loops.
523 MessageLoop::current()->SetNestableTasksAllowed(true);
524 scoped_refptr
<GLibLoopRunner
> runner
= new GLibLoopRunner();
527 // Add a couple of dummy events
528 injector
->AddDummyEvent(0);
529 injector
->AddDummyEvent(0);
530 // Post a couple of dummy tasks
531 MessageLoop::current()->PostTask(
532 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
533 MessageLoop::current()->PostTask(
534 FROM_HERE
, base::Bind(&IncrementInt
, &task_count
));
536 injector
->AddDummyEvent(10);
537 injector
->AddDummyEvent(10);
539 MessageLoop::current()->PostDelayedTask(
541 base::Bind(&IncrementInt
, &task_count
),
542 base::TimeDelta::FromMilliseconds(30));
543 MessageLoop::current()->PostDelayedTask(
545 base::Bind(&GLibLoopRunner::Quit
, runner
.get()),
546 base::TimeDelta::FromMilliseconds(40));
548 // Run a nested, straight Gtk message loop.
551 ASSERT_EQ(3, task_count
);
552 EXPECT_EQ(4, injector
->processed_events());
553 MessageLoop::current()->QuitWhenIdle();
558 TEST_F(MessagePumpGLibTest
, TestGLibLoop
) {
559 // Tests that events and posted tasks are correctly executed if the message
560 // loop is not run by MessageLoop::Run() but by a straight GLib loop.
561 // Note that in this case we don't make strong guarantees about niceness
562 // between events and posted tasks.
565 base::Bind(&TestGLibLoopInternal
, base::Unretained(injector())));
569 TEST_F(MessagePumpGLibTest
, TestGtkLoop
) {
570 // Tests that events and posted tasks are correctly executed if the message
571 // loop is not run by MessageLoop::Run() but by a straight Gtk loop.
572 // Note that in this case we don't make strong guarantees about niceness
573 // between events and posted tasks.
576 base::Bind(&TestGtkLoopInternal
, base::Unretained(injector())));