1/*
2 *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 *  Use of this source code is governed by a BSD-style license
5 *  that can be found in the LICENSE file in the root of the source
6 *  tree. An additional intellectual property rights grant can be found
7 *  in the file PATENTS.  All contributing project authors may
8 *  be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/base/bind.h"
12#include "webrtc/base/callback.h"
13#include "webrtc/base/gunit.h"
14
15namespace rtc {
16
17namespace {
18
19void f() {}
20int g() { return 42; }
21int h(int x) { return x * x; }
22void i(int& x) { x *= x; }  // NOLINT: Testing refs
23
24struct BindTester {
25  int a() { return 24; }
26  int b(int x) const { return x * x; }
27};
28
29}  // namespace
30
31TEST(CallbackTest, VoidReturn) {
32  Callback0<void> cb;
33  EXPECT_TRUE(cb.empty());
34  cb();  // Executing an empty callback should not crash.
35  cb = Callback0<void>(&f);
36  EXPECT_FALSE(cb.empty());
37  cb();
38}
39
40TEST(CallbackTest, IntReturn) {
41  Callback0<int> cb;
42  EXPECT_TRUE(cb.empty());
43  cb = Callback0<int>(&g);
44  EXPECT_FALSE(cb.empty());
45  EXPECT_EQ(42, cb());
46  EXPECT_EQ(42, cb());
47}
48
49TEST(CallbackTest, OneParam) {
50  Callback1<int, int> cb1(&h);
51  EXPECT_FALSE(cb1.empty());
52  EXPECT_EQ(9, cb1(-3));
53  EXPECT_EQ(100, cb1(10));
54
55  // Try clearing a callback.
56  cb1 = Callback1<int, int>();
57  EXPECT_TRUE(cb1.empty());
58
59  // Try a callback with a ref parameter.
60  Callback1<void, int&> cb2(&i);
61  int x = 3;
62  cb2(x);
63  EXPECT_EQ(9, x);
64  cb2(x);
65  EXPECT_EQ(81, x);
66}
67
68TEST(CallbackTest, WithBind) {
69  BindTester t;
70  Callback0<int> cb1 = Bind(&BindTester::a, &t);
71  EXPECT_EQ(24, cb1());
72  EXPECT_EQ(24, cb1());
73  cb1 = Bind(&BindTester::b, &t, 10);
74  EXPECT_EQ(100, cb1());
75  EXPECT_EQ(100, cb1());
76  cb1 = Bind(&BindTester::b, &t, 5);
77  EXPECT_EQ(25, cb1());
78  EXPECT_EQ(25, cb1());
79}
80
81}  // namespace rtc
82