Add partial pre-read functionality to browser startup (Windows).
[chromium-blink-merge.git] / base / message_pump_glib_unittest.cc
blobc70935585427df7943459e31b21b037af4dec682
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 void IncrementInt(int *value) {
145 ++*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);
159 // Test fixture.
160 class MessagePumpGLibTest : public testing::Test {
161 public:
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() {
170 delete injector_;
171 injector_ = NULL;
172 delete loop_;
173 loop_ = NULL;
176 MessageLoop* loop() const { return loop_; }
177 EventInjector* injector() const { return injector_; }
179 private:
180 MessageLoop* loop_;
181 EventInjector* injector_;
182 DISALLOW_COPY_AND_ASSIGN(MessagePumpGLibTest);
185 } // namespace
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, MessageLoop::QuitClosure());
192 loop()->Run();
193 EXPECT_EQ(0, injector()->processed_events());
195 injector()->Reset();
196 // Quit from an event
197 injector()->AddEvent(0, MessageLoop::QuitClosure());
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()->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());
218 loop()->Run();
219 EXPECT_EQ(4, injector()->processed_events());
221 injector()->Reset();
222 injector()->AddEventAsTask(0, base::Bind(&base::DoNothing));
223 check_task =
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());
229 loop()->Run();
230 EXPECT_EQ(4, injector()->processed_events());
233 TEST_F(MessagePumpGLibTest, TestWorkWhileWaitingForEvents) {
234 int task_count = 0;
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
241 // quit.
242 loop()->PostTask(
243 FROM_HERE,
244 base::Bind(&EventInjector::AddEvent, base::Unretained(injector()), 0,
245 MessageLoop::QuitClosure()));
246 loop()->Run();
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.
251 injector()->Reset();
252 task_count = 0;
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
258 // quit.
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(
262 FROM_HERE,
263 base::Bind(&EventInjector::AddEvent, base::Unretained(injector()), 10,
264 MessageLoop::QuitClosure()), 150);
265 loop()->Run();
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());
287 loop()->Run();
289 EXPECT_EQ(12, injector()->processed_events());
292 namespace {
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> {
298 public:
299 explicit ConcurrentHelper(EventInjector* injector)
300 : injector_(injector),
301 event_count_(kStartingEventCount),
302 task_count_(kStartingTaskCount) {
305 void FromTask() {
306 if (task_count_ > 0) {
307 --task_count_;
309 if (task_count_ == 0 && event_count_ == 0) {
310 MessageLoop::current()->Quit();
311 } else {
312 MessageLoop::current()->PostTask(
313 FROM_HERE, base::Bind(&ConcurrentHelper::FromTask, this));
317 void FromEvent() {
318 if (event_count_ > 0) {
319 --event_count_;
321 if (task_count_ == 0 && event_count_ == 0) {
322 MessageLoop::current()->Quit();
323 } else {
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_; }
332 private:
333 friend class base::RefCounted<ConcurrentHelper>;
335 ~ConcurrentHelper() {}
337 static const int kStartingEventCount = 20;
338 static const int kStartingTaskCount = 20;
340 EventInjector* injector_;
341 int event_count_;
342 int task_count_;
345 } // namespace
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.
363 loop()->PostTask(
364 FROM_HERE, base::Bind(&ConcurrentHelper::FromTask, helper.get()));
365 loop()->PostTask(
366 FROM_HERE, base::Bind(&ConcurrentHelper::FromTask, helper.get()));
368 loop()->Run();
369 EXPECT_EQ(0, helper->event_count());
370 EXPECT_EQ(0, helper->task_count());
373 namespace {
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));
386 // Drain the events
387 while (g_main_context_pending(NULL)) {
388 g_main_context_iteration(NULL, FALSE);
392 } // namespace
394 TEST_F(MessagePumpGLibTest, TestDrainingGLib) {
395 // Tests that draining events using GLib works.
396 loop()->PostTask(
397 FROM_HERE,
398 base::Bind(&AddEventsAndDrainGLib, base::Unretained(injector())));
399 loop()->Run();
401 EXPECT_EQ(3, injector()->processed_events());
405 namespace {
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));
419 // Drain the events
420 while (gtk_events_pending()) {
421 gtk_main_iteration();
424 #endif
426 } // namespace
428 #if defined(TOOLKIT_USES_GTK)
429 TEST_F(MessagePumpGLibTest, TestDrainingGtk) {
430 // Tests that draining events using Gtk works.
431 loop()->PostTask(
432 FROM_HERE,
433 base::Bind(&AddEventsAndDrainGtk, base::Unretained(injector())));
434 loop()->Run();
436 EXPECT_EQ(3, injector()->processed_events());
438 #endif
440 namespace {
442 // Helper class that lets us run the GLib message loop.
443 class GLibLoopRunner : public base::RefCounted<GLibLoopRunner> {
444 public:
445 GLibLoopRunner() : quit_(false) { }
447 void RunGLib() {
448 while (!quit_) {
449 g_main_context_iteration(NULL, TRUE);
453 void RunLoop() {
454 #if defined(TOOLKIT_USES_GTK)
455 while (!quit_) {
456 gtk_main_iteration();
458 #else
459 while (!quit_) {
460 g_main_context_iteration(NULL, TRUE);
462 #endif
465 void Quit() {
466 quit_ = true;
469 void Reset() {
470 quit_ = false;
473 private:
474 friend class base::RefCounted<GLibLoopRunner>;
476 ~GLibLoopRunner() {}
478 bool quit_;
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();
486 int task_count = 0;
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));
495 // Delayed events
496 injector->AddDummyEvent(10);
497 injector->AddDummyEvent(10);
498 // Delayed work
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.
505 runner->RunGLib();
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();
517 int task_count = 0;
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));
526 // Delayed events
527 injector->AddDummyEvent(10);
528 injector->AddDummyEvent(10);
529 // Delayed work
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.
536 runner->RunLoop();
538 ASSERT_EQ(3, task_count);
539 EXPECT_EQ(4, injector->processed_events());
540 MessageLoop::current()->Quit();
543 } // namespace
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.
550 loop()->PostTask(
551 FROM_HERE,
552 base::Bind(&TestGLibLoopInternal, base::Unretained(injector())));
553 loop()->Run();
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.
561 loop()->PostTask(
562 FROM_HERE,
563 base::Bind(&TestGtkLoopInternal, base::Unretained(injector())));
564 loop()->Run();