-
Notifications
You must be signed in to change notification settings - Fork 14
/
net_test.go
121 lines (115 loc) · 2.29 KB
/
net_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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Copyright (c) 2020 Meng Huang ([email protected])
// This package is licensed under a MIT license that can be found in the LICENSE file.
package netpoll
import (
"net"
"strings"
"sync"
"testing"
"time"
)
func TestListenAndServe(t *testing.T) {
var handler = &DataHandler{
NoShared: false,
NoCopy: false,
BufferSize: 1024,
HandlerFunc: func(req []byte) (res []byte) {
res = req
return
},
}
err := ListenAndServe("", "", handler)
if err == nil {
t.Error("Unexpected")
}
network := "tcp"
addr := ":8888"
go ListenAndServe(network, addr, handler)
time.Sleep(time.Millisecond * 10)
}
func TestServe(t *testing.T) {
var handler = &DataHandler{
NoShared: false,
NoCopy: false,
BufferSize: 1024,
HandlerFunc: func(req []byte) (res []byte) {
res = req
return
},
}
err := Serve(nil, handler)
if err == nil {
t.Error("Unexpected")
}
network := "tcp"
addr := ":8889"
l, _ := net.Listen(network, addr)
go Serve(l, handler)
time.Sleep(time.Millisecond * 10)
}
func TestNetServer(t *testing.T) {
var handler = &DataHandler{
NoShared: true,
NoCopy: true,
BufferSize: 1024,
HandlerFunc: func(req []byte) (res []byte) {
res = req
return
},
}
server := &netServer{
Handler: handler,
}
network := "tcp"
addr := ":9999"
l, _ := net.Listen(network, addr)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
if err := server.Serve(l); err == nil {
t.Error(err)
}
}()
conn, _ := net.Dial(network, addr)
msg := "Hello World"
msg = strings.Repeat(msg, 50)
if n, err := conn.Write([]byte(msg)); err != nil {
t.Error(err)
} else if n != len(msg) {
t.Error(n)
}
buf := make([]byte, len(msg))
if n, err := conn.Read(buf); err != nil {
t.Error(err)
} else if n != len(msg) {
t.Error(n)
} else if string(buf) != msg {
t.Error(string(buf))
}
conn.Close()
server.Close()
wg.Wait()
}
func TestNetServerUpgrade(t *testing.T) {
var handler = &ConnHandler{}
server := &netServer{
Handler: handler,
}
network := "tcp"
addr := ":9999"
l, _ := net.Listen(network, addr)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
if err := server.Serve(l); err == nil {
t.Error(err)
}
}()
conn, _ := net.Dial(network, addr)
time.Sleep(time.Millisecond * 10)
conn.Close()
server.Close()
wg.Wait()
}