blob: 1fea3152fa7c34c010f926cb641ac53a59260e51 [file] [log] [blame]
license.botf003cfe2008-08-24 09:55:55 +09001// Copyright (c) 2006-2008 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.
initial.commit3f4a7322008-07-27 06:49:38 +09004
5#include "base/observer_list.h"
6#include "testing/gtest/include/gtest/gtest.h"
7
8namespace {
9
10class ObserverListTest : public testing::Test {
11};
12
13class Foo {
14 public:
15 virtual void Observe(int x) = 0;
pinkerton@google.com15f4b112008-08-09 01:37:43 +090016 virtual ~Foo() {}
initial.commit3f4a7322008-07-27 06:49:38 +090017};
18
19class Adder : public Foo {
20 public:
pinkerton@google.com15f4b112008-08-09 01:37:43 +090021 Adder(int scaler) : total(0), scaler_(scaler) {}
initial.commit3f4a7322008-07-27 06:49:38 +090022 virtual void Observe(int x) {
23 total += x * scaler_;
24 }
pinkerton@google.com15f4b112008-08-09 01:37:43 +090025 virtual ~Adder() { }
initial.commit3f4a7322008-07-27 06:49:38 +090026 int total;
27 private:
28 int scaler_;
29};
30
31class Disrupter : public Foo {
32 public:
33 Disrupter(ObserverList<Foo>& list, Foo* doomed) : list_(list), doomed_(doomed) {
34 }
pinkerton@google.com15f4b112008-08-09 01:37:43 +090035 virtual ~Disrupter() { }
initial.commit3f4a7322008-07-27 06:49:38 +090036 virtual void Observe(int x) {
37 list_.RemoveObserver(doomed_);
38 }
39 private:
40 ObserverList<Foo>& list_;
41 Foo* doomed_;
42};
43
44} // namespace
45
46TEST(ObserverListTest, BasicTest) {
47 ObserverList<Foo> observer_list;
48 Adder a(1), b(-1), c(1), d(-1);
49 Disrupter evil(observer_list, &c);
50
51 observer_list.AddObserver(&a);
52 observer_list.AddObserver(&b);
53
54 FOR_EACH_OBSERVER(Foo, observer_list, Observe(10));
55
56 observer_list.AddObserver(&evil);
57 observer_list.AddObserver(&c);
58 observer_list.AddObserver(&d);
59
60 FOR_EACH_OBSERVER(Foo, observer_list, Observe(10));
61
62 EXPECT_EQ(a.total, 20);
63 EXPECT_EQ(b.total, -20);
64 EXPECT_EQ(c.total, 0);
65 EXPECT_EQ(d.total, -10);
66}
license.botf003cfe2008-08-24 09:55:55 +090067