callback_helper_unittest.cc revision 116680a4aac90f2aa7413d9095a592090648e557
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, FROM_HERE,
79          base::Bind(&VerifyCalledOnTaskRunner,
80                     ui_task_runner, &called)));
81  worker_task_runner->PostTask(
82      FROM_HERE,
83      RelayCallbackToTaskRunner(
84          ui_task_runner, FROM_HERE,
85          run_loop.QuitClosure()));
86  run_loop.Run();
87  EXPECT_TRUE(called);
88
89  thread.Stop();
90  base::RunLoop().RunUntilIdle();
91}
92
93TEST(DriveBackendCallbackHelperTest, PassNullFunctionTest) {
94  base::MessageLoop message_loop;
95  base::Closure closure = RelayCallbackToCurrentThread(
96      FROM_HERE,
97      base::Closure());
98  EXPECT_TRUE(closure.is_null());
99}
100
101}  // namespace drive_backend
102}  // namespace sync_file_system
103