callback_helper_unittest.cc revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
1// Copyright 2014 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 "chrome/browser/sync_file_system/drive_backend/callback_helper.h"
6
7#include "base/message_loop/message_loop.h"
8#include "base/run_loop.h"
9#include "base/thread_task_runner_handle.h"
10#include "base/threading/thread.h"
11#include "testing/gtest/include/gtest/gtest.h"
12
13namespace sync_file_system {
14namespace drive_backend {
15
16namespace {
17
18void SimpleCallback(bool* called, int) {
19  ASSERT_TRUE(called);
20  EXPECT_FALSE(*called);
21  *called = true;
22}
23
24void CallbackWithPassed(bool* called, scoped_ptr<int>) {
25  ASSERT_TRUE(called);
26  EXPECT_FALSE(*called);
27  *called = true;
28}
29
30void VerifyCalledOnTaskRunner(base::TaskRunner* task_runner,
31                              bool* called) {
32  ASSERT_TRUE(called);
33  ASSERT_TRUE(task_runner);
34
35  EXPECT_TRUE(task_runner->RunsTasksOnCurrentThread());
36  EXPECT_FALSE(*called);
37  *called = true;
38}
39
40}  // namespace
41
42TEST(DriveBackendCallbackHelperTest, BasicTest) {
43  base::MessageLoop message_loop;
44
45  bool called = false;
46  RelayCallbackToCurrentThread(
47      FROM_HERE,
48      base::Bind(&SimpleCallback, &called)).Run(0);
49  EXPECT_FALSE(called);
50  base::RunLoop().RunUntilIdle();
51  EXPECT_TRUE(called);
52
53  called = false;
54  RelayCallbackToCurrentThread(
55      FROM_HERE,
56      base::Bind(&CallbackWithPassed, &called))
57      .Run(scoped_ptr<int>(new int));
58  EXPECT_FALSE(called);
59  base::RunLoop().RunUntilIdle();
60  EXPECT_TRUE(called);
61}
62
63TEST(DriveBackendCallbackHelperTest, RunOnOtherThreadTest) {
64  base::MessageLoop message_loop;
65  base::Thread thread("WorkerThread");
66  thread.Start();
67
68  scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner =
69      base::ThreadTaskRunnerHandle::Get();
70  scoped_refptr<base::SequencedTaskRunner> worker_task_runner =
71      thread.message_loop_proxy();
72
73  bool called = false;
74  base::RunLoop run_loop;
75  worker_task_runner->PostTask(
76      FROM_HERE,
77      RelayCallbackToTaskRunner(
78          ui_task_runner.get(),
79          FROM_HERE,
80          base::Bind(&VerifyCalledOnTaskRunner, ui_task_runner, &called)));
81  worker_task_runner->PostTask(
82      FROM_HERE,
83      RelayCallbackToTaskRunner(
84          ui_task_runner.get(), FROM_HERE, run_loop.QuitClosure()));
85  run_loop.Run();
86  EXPECT_TRUE(called);
87
88  thread.Stop();
89  base::RunLoop().RunUntilIdle();
90}
91
92TEST(DriveBackendCallbackHelperTest, PassNullFunctionTest) {
93  base::MessageLoop message_loop;
94  base::Closure closure = RelayCallbackToCurrentThread(
95      FROM_HERE,
96      base::Closure());
97  EXPECT_TRUE(closure.is_null());
98}
99
100}  // namespace drive_backend
101}  // namespace sync_file_system
102