forked from archeryue/godis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ae_test.go
79 lines (71 loc) · 1.77 KB
/
ae_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
package main
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func WriteProc(loop *AeLoop, fd int, extra interface{}) {
buf := extra.([]byte)
n, err := Write(fd, buf)
if err != nil {
fmt.Printf("write err: %v\n", err)
return
}
fmt.Printf("ae write %v bytes\n", n)
loop.RemoveFileEvent(fd, AE_WRITABLE)
}
func ReadProc(loop *AeLoop, fd int, extra interface{}) {
buf := make([]byte, 10)
n, err := Read(fd, buf)
if err != nil {
fmt.Printf("read err: %v\n", err)
return
}
fmt.Printf("ae read %v bytes\n", n)
loop.AddFileEvent(fd, AE_WRITABLE, WriteProc, buf)
}
func AcceptProc(loop *AeLoop, fd int, extra interface{}) {
cfd, err := Accept(fd)
if err != nil {
fmt.Printf("accept err: %v\n", err)
return
}
loop.AddFileEvent(cfd, AE_READABLE, ReadProc, nil)
}
func OnceProc(loop *AeLoop, id int, extra interface{}) {
t := extra.(*testing.T)
assert.Equal(t, 1, id)
fmt.Printf("time event %v done\n", id)
}
func NormalProc(loop *AeLoop, id int, extra interface{}) {
end := extra.(chan struct{})
fmt.Printf("time event %v done\n", id)
end <- struct{}{}
}
func TestAe(t *testing.T) {
loop, err := AeLoopCreate()
assert.Nil(t, err)
sfd, err := TcpServer(6666)
loop.AddFileEvent(sfd, AE_READABLE, AcceptProc, nil)
go loop.AeMain()
// init client & test file events
host := [4]byte{0, 0, 0, 0}
cfd, err := Connect(host, 6666)
assert.Nil(t, err)
msg := "helloworld"
n, err := Write(cfd, []byte(msg))
assert.Nil(t, err)
assert.Equal(t, 10, n)
buf := make([]byte, 10)
n, err = Read(cfd, buf)
assert.Nil(t, err)
assert.Equal(t, 10, n)
assert.Equal(t, msg, string(buf))
// test time events
loop.AddTimeEvent(AE_ONCE, 10, OnceProc, t)
end := make(chan struct{}, 2)
loop.AddTimeEvent(AE_NORMAL, 10, NormalProc, end)
<-end
<-end
loop.stop = true
}