test_utils.cc revision a1401311d1ab56c4ed0a474bd38c108f75cb0cd9
1// Copyright 2013 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.
4
5#include "mojo/system/test_utils.h"
6
7#include "base/bind.h"
8#include "base/callback.h"
9#include "base/synchronization/waitable_event.h"
10
11namespace mojo {
12namespace system {
13namespace test {
14
15namespace {
16
17void PostTaskAndWaitHelper(base::WaitableEvent* event,
18                           const base::Closure& task) {
19  task.Run();
20  event->Signal();
21}
22
23}  // namespace
24
25void PostTaskAndWait(scoped_refptr<base::TaskRunner> task_runner,
26                     const tracked_objects::Location& from_here,
27                     const base::Closure& task) {
28  base::WaitableEvent event(false, false);
29  task_runner->PostTask(from_here,
30                        base::Bind(&PostTaskAndWaitHelper, &event, task));
31  event.Wait();
32}
33
34// TestIOThread ----------------------------------------------------------------
35
36TestIOThread::TestIOThread(Mode mode)
37    : io_thread_("test_io_thread"),
38      io_thread_started_(false) {
39  switch (mode) {
40    case kAutoStart:
41      Start();
42      return;
43    case kManualStart:
44      return;
45  }
46  CHECK(false) << "Invalid mode";
47}
48
49TestIOThread::~TestIOThread() {
50  Stop();
51}
52
53void TestIOThread::Start() {
54  CHECK(!io_thread_started_);
55  io_thread_started_ = true;
56  CHECK(io_thread_.StartWithOptions(
57      base::Thread::Options(base::MessageLoop::TYPE_IO, 0)));
58}
59
60void TestIOThread::Stop() {
61  // Note: It's okay to call |Stop()| even if the thread isn't running.
62  io_thread_.Stop();
63  io_thread_started_ = false;
64}
65
66void TestIOThread::PostTask(const tracked_objects::Location& from_here,
67                            const base::Closure& task) {
68  task_runner()->PostTask(from_here, task);
69}
70
71void TestIOThread::PostTaskAndWait(const tracked_objects::Location& from_here,
72                                   const base::Closure& task) {
73  ::mojo::system::test::PostTaskAndWait(task_runner(), from_here, task);
74}
75
76}  // namespace test
77}  // namespace system
78}  // namespace mojo
79