summaryrefslogtreecommitdiffstats
path: root/base/task_runner_util_unittest.cc
blob: 2d0cefe150011196023f78013e68f542d1d60d2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/task_runner_util.h"

#include "base/bind.h"
#include "base/message_loop.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {

namespace {

int ReturnFourtyTwo() {
  return 42;
}

void StoreValue(int* destination, int value) {
  *destination = value;
}

int g_foo_destruct_count = 0;
int g_foo_free_count = 0;

struct Foo {
  ~Foo() {
    ++g_foo_destruct_count;
  }
};

scoped_ptr<Foo> CreateFoo() {
  return scoped_ptr<Foo>(new Foo);
}

void ExpectFoo(scoped_ptr<Foo> foo) {
  EXPECT_TRUE(foo.get());
  scoped_ptr<Foo> local_foo(foo.Pass());
  EXPECT_TRUE(local_foo.get());
  EXPECT_FALSE(foo.get());
}

struct FreeFooFunctor {
  void operator()(Foo* foo) const {
    ++g_foo_free_count;
    delete foo;
  };
};

scoped_ptr_malloc<Foo, FreeFooFunctor> CreateScopedFoo() {
  return scoped_ptr_malloc<Foo, FreeFooFunctor>(new Foo);
}

void ExpectScopedFoo(scoped_ptr_malloc<Foo, FreeFooFunctor> foo) {
  EXPECT_TRUE(foo.get());
  scoped_ptr_malloc<Foo, FreeFooFunctor> local_foo(foo.Pass());
  EXPECT_TRUE(local_foo.get());
  EXPECT_FALSE(foo.get());
}

}  // namespace

TEST(TaskRunnerHelpersTest, PostTaskAndReplyWithResult) {
  MessageLoop message_loop;
  int result = 0;

  PostTaskAndReplyWithResult(
      message_loop.message_loop_proxy(),
      FROM_HERE,
      Bind(&ReturnFourtyTwo),
      Bind(&StoreValue, &result));

  message_loop.RunAllPending();

  EXPECT_EQ(42, result);
}

TEST(TaskRunnerHelpersTest, PostTaskAndReplyWithResultPassed) {
  g_foo_destruct_count = 0;
  g_foo_free_count = 0;

  MessageLoop message_loop;

  PostTaskAndReplyWithResult(
      message_loop.message_loop_proxy(),
      FROM_HERE,
      Bind(&CreateFoo),
      Bind(&ExpectFoo));

  message_loop.RunAllPending();

  EXPECT_EQ(1, g_foo_destruct_count);
  EXPECT_EQ(0, g_foo_free_count);
}

TEST(TaskRunnerHelpersTest, PostTaskAndReplyWithResultPassedFreeProc) {
  g_foo_destruct_count = 0;
  g_foo_free_count = 0;

  MessageLoop message_loop;

  PostTaskAndReplyWithResult(
      message_loop.message_loop_proxy(),
      FROM_HERE,
      Bind(&CreateScopedFoo),
      Bind(&ExpectScopedFoo));

  message_loop.RunAllPending();

  EXPECT_EQ(1, g_foo_destruct_count);
  EXPECT_EQ(1, g_foo_free_count);
}

}  // namespace base