forked from funny/link
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_test.go
More file actions
108 lines (82 loc) · 2.22 KB
/
Copy pathserver_test.go
File metadata and controls
108 lines (82 loc) · 2.22 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package link
import (
"bytes"
"github.com/funny/sync"
"github.com/funny/unitest"
"runtime/pprof"
"sync/atomic"
"testing"
)
func Test_Server(t *testing.T) {
server, err0 := Listen("tcp", "0.0.0.0:0")
unitest.NotError(t, err0)
var (
addr = server.Listener().Addr().String()
data = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
message = Bytes(data)
sessionStart sync.WaitGroup
sessionClose sync.WaitGroup
sessionRequest sync.WaitGroup
sessionStartCount int32
sessionRequestCount int32
sessionCloseCount int32
messageMatchFailed bool
)
go server.Serve(func(session *Session) {
atomic.AddInt32(&sessionStartCount, 1)
sessionStart.Done()
session.Process(func(msg *InBuffer) error {
if !bytes.Equal(msg.Data, data) {
messageMatchFailed = true
}
atomic.AddInt32(&sessionRequestCount, 1)
sessionRequest.Done()
return nil
})
atomic.AddInt32(&sessionCloseCount, 1)
sessionClose.Done()
})
// test session start
sessionStart.Add(1)
client1, err1 := Dial("tcp", addr)
unitest.NotError(t, err1)
sessionStart.Add(1)
client2, err2 := Dial("tcp", addr)
unitest.NotError(t, err2)
t.Log("check session start")
sessionStart.Wait()
unitest.Pass(t, sessionStartCount == 2)
// test session request
sessionRequest.Add(1)
unitest.NotError(t, client1.Send(message))
sessionRequest.Add(1)
unitest.NotError(t, client2.Send(message))
sessionRequest.Add(1)
unitest.NotError(t, client1.Send(message))
sessionRequest.Add(1)
unitest.NotError(t, client2.Send(message))
t.Log("check session request")
sessionRequest.Wait()
unitest.Pass(t, sessionRequestCount == 4)
unitest.Pass(t, messageMatchFailed == false)
// test session close
sessionClose.Add(1)
client1.Close()
sessionClose.Add(1)
client2.Close()
t.Log("check session close")
sessionClose.Wait()
unitest.Pass(t, sessionCloseCount == 2)
MakeSureSessionGoroutineExit(t)
}
func MakeSureSessionGoroutineExit(t *testing.T) {
buff := new(bytes.Buffer)
goroutines := pprof.Lookup("goroutine")
if err := goroutines.WriteTo(buff, 2); err != nil {
t.Fatalf("Dump goroutine failed: %v", err)
}
if n := bytes.Index(buff.Bytes(), []byte("sendLoop")); n >= 0 {
t.Log(buff.String())
t.Fatalf("Some session goroutine running")
}
}