srpcgen: Use 'const char*' for string parameters
[chromium-blink-merge.git] / base / message_pump_glib_unittest.cc
blob467088c06b2451e7fa338842c31c83aa08a4390b
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"
7 #include <math.h>
9 #include <algorithm>
10 #include <vector>
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)
21 #include <gtk/gtk.h>
22 #endif
24 namespace {
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).
29 class EventInjector {
30 public:
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);
38 ~EventInjector() {
39 g_source_destroy(source_);
40 g_source_unref(source_);
43 int HandlePrepare() {
44 // If the queue is empty, block.
45 if (events_.empty())
46 return -1;
47 base::TimeDelta delta = events_[0].time - base::Time::NowFromSystemTime();
48 return std::max(0, static_cast<int>(ceil(delta.InMillisecondsF())));
51 bool HandleCheck() {
52 if (events_.empty())
53 return false;
54 return events_[0].time <= base::Time::NowFromSystemTime();
57 void HandleDispatch() {
58 if (events_.empty())
59 return;
60 Event event = events_[0];
61 events_.erase(events_.begin());
62 ++processed_events_;
63 if (!event.callback.is_null())
64 event.callback.Run();
65 else if (!event.task.is_null())
66 event.task.Run();
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);
83 void Reset() {
84 processed_events_ = 0;
85 events_.clear();
88 int processed_events() const { return processed_events_; }
90 private:
91 struct Event {
92 base::Time time;
93 base::Closure callback;
94 base::Closure task;
97 struct Source : public GSource {
98 EventInjector* injector;
101 void AddEventHelper(
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;
106 else
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();
116 return FALSE;
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();
127 return TRUE;
130 Source* source_;
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,
141 NULL
144 // Does nothing. This function can be called from a task.
145 void DoNothing() {
148 void IncrementInt(int *value) {
149 ++*value;
152 // Checks how many events have been processed by the injector.
153 void ExpectProcessedEvents(EventInjector* injector, int count) {
154 EXPECT_EQ(injector->processed_events(), count);
157 // Posts a task on the current message loop.
158 void PostMessageLoopTask(const tracked_objects::Location& from_here,
159 const base::Closure& task) {
160 MessageLoop::current()->PostTask(from_here, task);
163 // Test fixture.
164 class MessagePumpGLibTest : public testing::Test {
165 public:
166 MessagePumpGLibTest() : loop_(NULL), injector_(NULL) { }
168 virtual void SetUp() {
169 loop_ = new MessageLoop(MessageLoop::TYPE_UI);
170 injector_ = new EventInjector();
173 virtual void TearDown() {
174 delete injector_;
175 injector_ = NULL;
176 delete loop_;
177 loop_ = NULL;
180 MessageLoop* loop() const { return loop_; }
181 EventInjector* injector() const { return injector_; }
183 private:
184 MessageLoop* loop_;
185 EventInjector* injector_;
186 DISALLOW_COPY_AND_ASSIGN(MessagePumpGLibTest);
189 } // namespace
191 TEST_F(MessagePumpGLibTest, TestQuit) {
192 // Checks that Quit works and that the basic infrastructure is working.
194 // Quit from a task
195 loop()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
196 loop()->Run();
197 EXPECT_EQ(0, injector()->processed_events());
199 injector()->Reset();
200 // Quit from an event
201 injector()->AddEvent(0, MessageLoop::QuitClosure());
202 loop()->Run();
203 EXPECT_EQ(1, injector()->processed_events());
206 TEST_F(MessagePumpGLibTest, TestEventTaskInterleave) {
207 // Checks that tasks posted by events are executed before the next event if
208 // the posted task queue is empty.
209 // MessageLoop doesn't make strong guarantees that it is the case, but the
210 // current implementation ensures it and the tests below rely on it.
211 // If changes cause this test to fail, it is reasonable to change it, but
212 // TestWorkWhileWaitingForEvents and TestEventsWhileWaitingForWork have to be
213 // changed accordingly, otherwise they can become flaky.
214 injector()->AddEventAsTask(0, base::Bind(&DoNothing));
215 base::Closure check_task =
216 base::Bind(&ExpectProcessedEvents, base::Unretained(injector()), 2);
217 base::Closure posted_task =
218 base::Bind(&PostMessageLoopTask, FROM_HERE, check_task);
219 injector()->AddEventAsTask(0, posted_task);
220 injector()->AddEventAsTask(0, base::Bind(&DoNothing));
221 injector()->AddEvent(0, MessageLoop::QuitClosure());
222 loop()->Run();
223 EXPECT_EQ(4, injector()->processed_events());
225 injector()->Reset();
226 injector()->AddEventAsTask(0, base::Bind(&DoNothing));
227 check_task =
228 base::Bind(&ExpectProcessedEvents, base::Unretained(injector()), 2);
229 posted_task = base::Bind(&PostMessageLoopTask, FROM_HERE, check_task);
230 injector()->AddEventAsTask(0, posted_task);
231 injector()->AddEventAsTask(10, base::Bind(&DoNothing));
232 injector()->AddEvent(0, MessageLoop::QuitClosure());
233 loop()->Run();
234 EXPECT_EQ(4, injector()->processed_events());
237 TEST_F(MessagePumpGLibTest, TestWorkWhileWaitingForEvents) {
238 int task_count = 0;
239 // Tests that we process tasks while waiting for new events.
240 // The event queue is empty at first.
241 for (int i = 0; i < 10; ++i) {
242 loop()->PostTask(FROM_HERE, base::Bind(&IncrementInt, &task_count));
244 // After all the previous tasks have executed, enqueue an event that will
245 // quit.
246 loop()->PostTask(
247 FROM_HERE,
248 base::Bind(&EventInjector::AddEvent, base::Unretained(injector()), 0,
249 MessageLoop::QuitClosure()));
250 loop()->Run();
251 ASSERT_EQ(10, task_count);
252 EXPECT_EQ(1, injector()->processed_events());
254 // Tests that we process delayed tasks while waiting for new events.
255 injector()->Reset();
256 task_count = 0;
257 for (int i = 0; i < 10; ++i) {
258 loop()->PostDelayedTask(
259 FROM_HERE, base::Bind(&IncrementInt, &task_count), 10*i);
261 // After all the previous tasks have executed, enqueue an event that will
262 // quit.
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(
266 FROM_HERE,
267 base::Bind(&EventInjector::AddEvent, base::Unretained(injector()), 10,
268 MessageLoop::QuitClosure()), 150);
269 loop()->Run();
270 ASSERT_EQ(10, task_count);
271 EXPECT_EQ(1, injector()->processed_events());
274 TEST_F(MessagePumpGLibTest, TestEventsWhileWaitingForWork) {
275 // Tests that we process events while waiting for work.
276 // The event queue is empty at first.
277 for (int i = 0; i < 10; ++i) {
278 injector()->AddDummyEvent(0);
280 // After all the events have been processed, post a task that will check that
281 // the events have been processed (note: the task executes after the event
282 // that posted it has been handled, so we expect 11 at that point).
283 base::Closure check_task =
284 base::Bind(&ExpectProcessedEvents, base::Unretained(injector()), 11);
285 base::Closure posted_task =
286 base::Bind(&PostMessageLoopTask, FROM_HERE, check_task);
287 injector()->AddEventAsTask(10, posted_task);
289 // And then quit (relies on the condition tested by TestEventTaskInterleave).
290 injector()->AddEvent(10, MessageLoop::QuitClosure());
291 loop()->Run();
293 EXPECT_EQ(12, injector()->processed_events());
296 namespace {
298 // This class is a helper for the concurrent events / posted tasks test below.
299 // It will quit the main loop once enough tasks and events have been processed,
300 // while making sure there is always work to do and events in the queue.
301 class ConcurrentHelper : public base::RefCounted<ConcurrentHelper> {
302 public:
303 explicit ConcurrentHelper(EventInjector* injector)
304 : injector_(injector),
305 event_count_(kStartingEventCount),
306 task_count_(kStartingTaskCount) {
309 void FromTask() {
310 if (task_count_ > 0) {
311 --task_count_;
313 if (task_count_ == 0 && event_count_ == 0) {
314 MessageLoop::current()->Quit();
315 } else {
316 MessageLoop::current()->PostTask(
317 FROM_HERE, base::Bind(&ConcurrentHelper::FromTask, this));
321 void FromEvent() {
322 if (event_count_ > 0) {
323 --event_count_;
325 if (task_count_ == 0 && event_count_ == 0) {
326 MessageLoop::current()->Quit();
327 } else {
328 injector_->AddEventAsTask(
329 0, base::Bind(&ConcurrentHelper::FromEvent, this));
333 int event_count() const { return event_count_; }
334 int task_count() const { return task_count_; }
336 private:
337 friend class base::RefCounted<ConcurrentHelper>;
339 ~ConcurrentHelper() {}
341 static const int kStartingEventCount = 20;
342 static const int kStartingTaskCount = 20;
344 EventInjector* injector_;
345 int event_count_;
346 int task_count_;
349 } // namespace
351 TEST_F(MessagePumpGLibTest, TestConcurrentEventPostedTask) {
352 // Tests that posted tasks don't starve events, nor the opposite.
353 // We use the helper class above. We keep both event and posted task queues
354 // full, the helper verifies that both tasks and events get processed.
355 // If that is not the case, either event_count_ or task_count_ will not get
356 // to 0, and MessageLoop::Quit() will never be called.
357 scoped_refptr<ConcurrentHelper> helper = new ConcurrentHelper(injector());
359 // Add 2 events to the queue to make sure it is always full (when we remove
360 // the event before processing it).
361 injector()->AddEventAsTask(
362 0, base::Bind(&ConcurrentHelper::FromEvent, helper.get()));
363 injector()->AddEventAsTask(
364 0, base::Bind(&ConcurrentHelper::FromEvent, helper.get()));
366 // Similarly post 2 tasks.
367 loop()->PostTask(
368 FROM_HERE, base::Bind(&ConcurrentHelper::FromTask, helper.get()));
369 loop()->PostTask(
370 FROM_HERE, base::Bind(&ConcurrentHelper::FromTask, helper.get()));
372 loop()->Run();
373 EXPECT_EQ(0, helper->event_count());
374 EXPECT_EQ(0, helper->task_count());
377 namespace {
379 void AddEventsAndDrainGLib(EventInjector* injector) {
380 // Add a couple of dummy events
381 injector->AddDummyEvent(0);
382 injector->AddDummyEvent(0);
383 // Then add an event that will quit the main loop.
384 injector->AddEvent(0, MessageLoop::QuitClosure());
386 // Post a couple of dummy tasks
387 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&DoNothing));
388 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&DoNothing));
390 // Drain the events
391 while (g_main_context_pending(NULL)) {
392 g_main_context_iteration(NULL, FALSE);
396 } // namespace
398 TEST_F(MessagePumpGLibTest, TestDrainingGLib) {
399 // Tests that draining events using GLib works.
400 loop()->PostTask(
401 FROM_HERE,
402 base::Bind(&AddEventsAndDrainGLib, base::Unretained(injector())));
403 loop()->Run();
405 EXPECT_EQ(3, injector()->processed_events());
409 namespace {
411 #if defined(TOOLKIT_USES_GTK)
412 void AddEventsAndDrainGtk(EventInjector* injector) {
413 // Add a couple of dummy events
414 injector->AddDummyEvent(0);
415 injector->AddDummyEvent(0);
416 // Then add an event that will quit the main loop.
417 injector->AddEvent(0, MessageLoop::QuitClosure());
419 // Post a couple of dummy tasks
420 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&DoNothing));
421 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&DoNothing));
423 // Drain the events
424 while (gtk_events_pending()) {
425 gtk_main_iteration();
428 #endif
430 } // namespace
432 #if defined(TOOLKIT_USES_GTK)
433 TEST_F(MessagePumpGLibTest, TestDrainingGtk) {
434 // Tests that draining events using Gtk works.
435 loop()->PostTask(
436 FROM_HERE,
437 base::Bind(&AddEventsAndDrainGtk, base::Unretained(injector())));
438 loop()->Run();
440 EXPECT_EQ(3, injector()->processed_events());
442 #endif
444 namespace {
446 // Helper class that lets us run the GLib message loop.
447 class GLibLoopRunner : public base::RefCounted<GLibLoopRunner> {
448 public:
449 GLibLoopRunner() : quit_(false) { }
451 void RunGLib() {
452 while (!quit_) {
453 g_main_context_iteration(NULL, TRUE);
457 void RunLoop() {
458 #if defined(TOOLKIT_USES_GTK)
459 while (!quit_) {
460 gtk_main_iteration();
462 #else
463 while (!quit_) {
464 g_main_context_iteration(NULL, TRUE);
466 #endif
469 void Quit() {
470 quit_ = true;
473 void Reset() {
474 quit_ = false;
477 private:
478 friend class base::RefCounted<GLibLoopRunner>;
480 ~GLibLoopRunner() {}
482 bool quit_;
485 void TestGLibLoopInternal(EventInjector* injector) {
486 // Allow tasks to be processed from 'native' event loops.
487 MessageLoop::current()->SetNestableTasksAllowed(true);
488 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
490 int task_count = 0;
491 // Add a couple of dummy events
492 injector->AddDummyEvent(0);
493 injector->AddDummyEvent(0);
494 // Post a couple of dummy tasks
495 MessageLoop::current()->PostTask(
496 FROM_HERE, base::Bind(&IncrementInt, &task_count));
497 MessageLoop::current()->PostTask(
498 FROM_HERE, base::Bind(&IncrementInt, &task_count));
499 // Delayed events
500 injector->AddDummyEvent(10);
501 injector->AddDummyEvent(10);
502 // Delayed work
503 MessageLoop::current()->PostDelayedTask(
504 FROM_HERE, base::Bind(&IncrementInt, &task_count), 30);
505 MessageLoop::current()->PostDelayedTask(
506 FROM_HERE, base::Bind(&GLibLoopRunner::Quit, runner.get()), 40);
508 // Run a nested, straight GLib message loop.
509 runner->RunGLib();
511 ASSERT_EQ(3, task_count);
512 EXPECT_EQ(4, injector->processed_events());
513 MessageLoop::current()->Quit();
516 void TestGtkLoopInternal(EventInjector* injector) {
517 // Allow tasks to be processed from 'native' event loops.
518 MessageLoop::current()->SetNestableTasksAllowed(true);
519 scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();
521 int task_count = 0;
522 // Add a couple of dummy events
523 injector->AddDummyEvent(0);
524 injector->AddDummyEvent(0);
525 // Post a couple of dummy tasks
526 MessageLoop::current()->PostTask(
527 FROM_HERE, base::Bind(&IncrementInt, &task_count));
528 MessageLoop::current()->PostTask(
529 FROM_HERE, base::Bind(&IncrementInt, &task_count));
530 // Delayed events
531 injector->AddDummyEvent(10);
532 injector->AddDummyEvent(10);
533 // Delayed work
534 MessageLoop::current()->PostDelayedTask(
535 FROM_HERE, base::Bind(&IncrementInt, &task_count), 30);
536 MessageLoop::current()->PostDelayedTask(
537 FROM_HERE, base::Bind(&GLibLoopRunner::Quit, runner.get()), 40);
539 // Run a nested, straight Gtk message loop.
540 runner->RunLoop();
542 ASSERT_EQ(3, task_count);
543 EXPECT_EQ(4, injector->processed_events());
544 MessageLoop::current()->Quit();
547 } // namespace
549 TEST_F(MessagePumpGLibTest, TestGLibLoop) {
550 // Tests that events and posted tasks are correctly executed if the message
551 // loop is not run by MessageLoop::Run() but by a straight GLib loop.
552 // Note that in this case we don't make strong guarantees about niceness
553 // between events and posted tasks.
554 loop()->PostTask(
555 FROM_HERE,
556 base::Bind(&TestGLibLoopInternal, base::Unretained(injector())));
557 loop()->Run();
560 TEST_F(MessagePumpGLibTest, TestGtkLoop) {
561 // Tests that events and posted tasks are correctly executed if the message
562 // loop is not run by MessageLoop::Run() but by a straight Gtk loop.
563 // Note that in this case we don't make strong guarantees about niceness
564 // between events and posted tasks.
565 loop()->PostTask(
566 FROM_HERE,
567 base::Bind(&TestGtkLoopInternal, base::Unretained(injector())));
568 loop()->Run();