license.bot | f003cfe | 2008-08-24 09:55:55 +0900 | [diff] [blame^] | 1 | // 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.commit | 3f4a732 | 2008-07-27 06:49:38 +0900 | [diff] [blame] | 4 | |
| 5 | #include "base/observer_list.h" |
| 6 | #include "testing/gtest/include/gtest/gtest.h" |
| 7 | |
| 8 | namespace { |
| 9 | |
| 10 | class ObserverListTest : public testing::Test { |
| 11 | }; |
| 12 | |
| 13 | class Foo { |
| 14 | public: |
| 15 | virtual void Observe(int x) = 0; |
pinkerton@google.com | 15f4b11 | 2008-08-09 01:37:43 +0900 | [diff] [blame] | 16 | virtual ~Foo() {} |
initial.commit | 3f4a732 | 2008-07-27 06:49:38 +0900 | [diff] [blame] | 17 | }; |
| 18 | |
| 19 | class Adder : public Foo { |
| 20 | public: |
pinkerton@google.com | 15f4b11 | 2008-08-09 01:37:43 +0900 | [diff] [blame] | 21 | Adder(int scaler) : total(0), scaler_(scaler) {} |
initial.commit | 3f4a732 | 2008-07-27 06:49:38 +0900 | [diff] [blame] | 22 | virtual void Observe(int x) { |
| 23 | total += x * scaler_; |
| 24 | } |
pinkerton@google.com | 15f4b11 | 2008-08-09 01:37:43 +0900 | [diff] [blame] | 25 | virtual ~Adder() { } |
initial.commit | 3f4a732 | 2008-07-27 06:49:38 +0900 | [diff] [blame] | 26 | int total; |
| 27 | private: |
| 28 | int scaler_; |
| 29 | }; |
| 30 | |
| 31 | class Disrupter : public Foo { |
| 32 | public: |
| 33 | Disrupter(ObserverList<Foo>& list, Foo* doomed) : list_(list), doomed_(doomed) { |
| 34 | } |
pinkerton@google.com | 15f4b11 | 2008-08-09 01:37:43 +0900 | [diff] [blame] | 35 | virtual ~Disrupter() { } |
initial.commit | 3f4a732 | 2008-07-27 06:49:38 +0900 | [diff] [blame] | 36 | virtual void Observe(int x) { |
| 37 | list_.RemoveObserver(doomed_); |
| 38 | } |
| 39 | private: |
| 40 | ObserverList<Foo>& list_; |
| 41 | Foo* doomed_; |
| 42 | }; |
| 43 | |
| 44 | } // namespace |
| 45 | |
| 46 | TEST(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.bot | f003cfe | 2008-08-24 09:55:55 +0900 | [diff] [blame^] | 67 | |