* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / test / test_observer.rb
blob8f8f24b3c59579ad796dc1789b9cd5a4688dd5b7
1 # frozen_string_literal: true
2 require 'test/unit'
3 require 'observer'
5 class TestObserver < Test::Unit::TestCase
6   class TestObservable
7     include Observable
9     def notify(*args)
10       changed
11       notify_observers(*args)
12     end
13   end
15   class TestWatcher
16     def initialize(observable)
17       @notifications = []
18       observable.add_observer(self)
19     end
21     attr_reader :notifications
23     def update(*args)
24       @notifications << args
25     end
26   end
28   def test_observers
29     observable = TestObservable.new
31     assert_equal(0, observable.count_observers)
33     watcher1 = TestWatcher.new(observable)
35     assert_equal(1, observable.count_observers)
37     observable.notify("test", 123)
39     watcher2 = TestWatcher.new(observable)
41     assert_equal(2, observable.count_observers)
43     observable.notify(42)
45     assert_equal([["test", 123], [42]], watcher1.notifications)
46     assert_equal([[42]], watcher2.notifications)
48     observable.delete_observer(watcher1)
50     assert_equal(1, observable.count_observers)
52     observable.notify(:cats)
54     assert_equal([["test", 123], [42]], watcher1.notifications)
55     assert_equal([[42], [:cats]], watcher2.notifications)
57     observable.delete_observers
59     assert_equal(0, observable.count_observers)
61     observable.notify("nope")
63     assert_equal([["test", 123], [42]], watcher1.notifications)
64     assert_equal([[42], [:cats]], watcher2.notifications)
65   end
66 end