callback_helpers_unittest.cc 1.42 KB
Newer Older
gejun's avatar
gejun committed
1 2 3 4
// Copyright 2013 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.

5
#include "butil/callback_helpers.h"
gejun's avatar
gejun committed
6

7 8
#include "butil/bind.h"
#include "butil/callback.h"
gejun's avatar
gejun committed
9 10 11 12 13 14 15 16 17 18 19
#include <gtest/gtest.h>

namespace {

void Increment(int* value) {
  (*value)++;
}

TEST(BindHelpersTest, TestScopedClosureRunnerExitScope) {
  int run_count = 0;
  {
20
    butil::ScopedClosureRunner runner(butil::Bind(&Increment, &run_count));
gejun's avatar
gejun committed
21 22 23 24 25 26 27
    EXPECT_EQ(0, run_count);
  }
  EXPECT_EQ(1, run_count);
}

TEST(BindHelpersTest, TestScopedClosureRunnerRelease) {
  int run_count = 0;
28
  butil::Closure c;
gejun's avatar
gejun committed
29
  {
30
    butil::ScopedClosureRunner runner(butil::Bind(&Increment, &run_count));
gejun's avatar
gejun committed
31 32 33 34 35 36 37 38 39 40 41 42
    c = runner.Release();
    EXPECT_EQ(0, run_count);
  }
  EXPECT_EQ(0, run_count);
  c.Run();
  EXPECT_EQ(1, run_count);
}

TEST(BindHelpersTest, TestScopedClosureRunnerReset) {
  int run_count_1 = 0;
  int run_count_2 = 0;
  {
43 44 45
    butil::ScopedClosureRunner runner;
    runner.Reset(butil::Bind(&Increment, &run_count_1));
    runner.Reset(butil::Bind(&Increment, &run_count_2));
gejun's avatar
gejun committed
46 47 48 49 50 51 52
    EXPECT_EQ(1, run_count_1);
    EXPECT_EQ(0, run_count_2);
  }
  EXPECT_EQ(1, run_count_2);

  int run_count_3 = 0;
  {
53
    butil::ScopedClosureRunner runner(butil::Bind(&Increment, &run_count_3));
gejun's avatar
gejun committed
54 55 56 57 58 59 60 61
    EXPECT_EQ(0, run_count_3);
    runner.Reset();
    EXPECT_EQ(1, run_count_3);
  }
  EXPECT_EQ(1, run_count_3);
}

}  // namespace