-
Notifications
You must be signed in to change notification settings - Fork 0
/
topics_test.go
81 lines (66 loc) · 1.83 KB
/
topics_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package emitter
import (
"errors"
"sync"
"testing"
)
// mockListener simulates a listener function for testing.
func mockListener(id string, shouldError bool) Listener {
return func(e Event) error {
if shouldError {
return errors.New("listener error " + id)
}
return nil
}
}
func TestNewTopic(t *testing.T) {
topic := NewTopic()
if topic == nil {
t.Error("NewTopic() should not return nil")
}
}
func TestAddRemoveListener(t *testing.T) {
topic := NewTopic()
listener1 := mockListener("1", false)
listener2 := mockListener("2", false)
id1 := "1"
topic.AddListener(id1, listener1)
if len(topic.listeners) != 1 {
t.Error("AddListener() failed to add listener 1")
}
id2 := "2"
topic.AddListener(id2, listener2)
if len(topic.listeners) != 2 {
t.Error("AddListener() failed to add listener 2")
}
topic.RemoveListener(id1)
if len(topic.listeners) != 1 {
t.Errorf("RemoveListener() failed to remove listener 1, remaining listeners: %d", len(topic.listeners))
}
topic.RemoveListener(id2)
if len(topic.listeners) != 0 {
t.Errorf("RemoveListener() failed to remove listener 2, remaining listeners: %d", len(topic.listeners))
}
}
func TestTriggerListeners(t *testing.T) {
topic := NewTopic()
type Payload struct {
Data string
}
event := NewBaseEvent("test", Payload{Data: "value"}) // Assumes NewBaseEvent is modified to work without generics
// Add listeners
topic.AddListener("1", mockListener("1", false))
topic.AddListener("2", mockListener("2", true))
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
errors := topic.Trigger(event)
if len(errors) != 1 {
t.Errorf("Trigger() should return exactly 1 error, got: %d", len(errors))
} else if errors[0].Error() != "listener error 2" {
t.Errorf("Trigger() should return 'listener error 2', got: %s", errors[0].Error())
}
}()
wg.Wait()
}