-
Notifications
You must be signed in to change notification settings - Fork 0
/
events_test.go
92 lines (70 loc) · 1.52 KB
/
events_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
82
83
84
85
86
87
88
89
90
91
92
// SPDX-FileCopyrightText: 2019-2024 caixw
//
// SPDX-License-Identifier: MIT
package events
import (
"bytes"
"testing"
"time"
"github.com/issue9/assert/v4"
)
var (
_ Publisher[int] = &Event[int]{}
_ Subscriber[int] = &Event[int]{}
)
func s1(data string) { println("s1") }
func s2(data string) { println("s2") }
func TestPublisher_Publish(t *testing.T) {
a := assert.New(t, false)
e := New[string]()
a.NotNil(e)
// 没有订阅者
e.Publish(true, "123")
buf1 := new(bytes.Buffer)
sub1 := func(data string) { buf1.WriteString(data) }
c1 := e.Subscribe(sub1)
a.NotNil(c1)
e.Publish(true, "p1")
time.Sleep(time.Microsecond * 500)
a.Equal(buf1.String(), "p1")
buf1.Reset()
buf2 := new(bytes.Buffer)
sub2 := func(data string) { buf2.WriteString(data) }
a.Empty(buf2.Bytes())
e.Subscribe(sub2)
e.Publish(false, "p2")
time.Sleep(time.Microsecond * 500)
a.Equal(buf1.String(), "p2").
Equal(buf2.String(), "p2")
buf1.Reset()
buf2.Reset()
c1()
e.Publish(false, "p3")
time.Sleep(time.Microsecond * 500)
a.Empty(buf1.String())
a.Equal(buf2.String(), "p3")
}
func TestPublisher_Reset(t *testing.T) {
a := assert.New(t, false)
e := New[string]()
a.NotNil(e)
a.Zero(e.Len())
e = New[string]()
a.NotNil(e)
e.Subscribe(s1)
a.Equal(e.Len(), 1)
e.Reset()
a.Zero(e.Len())
}
func TestSubscriber_Attach_Detach(t *testing.T) {
a := assert.New(t, false)
e := New[string]()
a.NotNil(e)
c1 := e.Subscribe(s1)
c2 := e.Subscribe(s2)
a.Equal(e.Len(), 2)
c1()
a.Equal(e.Len(), 1)
c2()
a.Equal(e.Len(), 0)
}