/
policy_test.go
149 lines (124 loc) · 2.45 KB
/
policy_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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package policy
import (
"bytes"
"net"
"sync"
"testing"
"time"
"github.com/simonz05/util/assert"
"github.com/simonz05/util/log"
)
func init() {
log.Severity = log.LevelError
Timeout = time.Second
}
var policyTests = []struct {
send []byte
exp []byte
failWrite bool
failRead bool
}{
{
send: protocolPing,
exp: protocolPingResponse,
},
{
send: protocolPolicy,
exp: protocolPolicyResponse,
},
{
send: []byte(""),
exp: []byte(""),
failRead: true,
},
{
send: protocolPolicy[:len(protocolPolicy)-1],
exp: protocolPolicyResponse,
failRead: true,
},
}
const testBufSize = 8 << 4
func TestPolicy(t *testing.T) {
ast := assert.NewAssert(t)
var wg sync.WaitGroup
l, err := net.Listen("tcp", ":9001")
defer l.Close()
ast.Nil(err)
log.Printf("Listen on %v", l.Addr())
wg.Add(1)
go func() {
serve(l)
wg.Done()
}()
for _, p := range policyTests {
conn, err := net.Dial("tcp", ":9001")
ast.Nil(err)
n, err := conn.Write(p.send)
if !p.failWrite {
ast.Nil(err)
ast.Equal(len(p.send), n)
} else {
ast.NotNil(err)
continue
}
buf := make([]byte, testBufSize)
n, err = conn.Read(buf)
if !p.failRead {
ast.Nil(err)
ast.Equal(len(p.exp), n)
ast.True(bytes.Equal(p.exp, buf[:n]))
} else {
ast.NotNil(err)
continue
}
}
l.Close()
wg.Wait()
}
func BenchmarkPolicy(b *testing.B) {
b.StopTimer()
var wg sync.WaitGroup
l, err := net.Listen("tcp", ":9001")
defer l.Close()
if err != nil {
b.Fatal(err)
}
log.Printf("Listen on %v", l.Addr())
wg.Add(1)
go func() {
serve(l)
wg.Done()
}()
b.StartTimer()
k := 8 << 2
for i := 0; i < b.N; i += k {
var wg2 sync.WaitGroup
for j := 0; j < k; j++ {
wg2.Add(1)
go func() {
conn, err := net.Dial("tcp", ":9001")
if err != nil {
b.Errorf("error dialing: %v", err)
}
n, err := conn.Write(protocolPolicy)
if err != nil || n != len(protocolPolicy) {
b.Errorf("error sending: %v, %d == %d", err, n, len(protocolPolicy))
}
buf := make([]byte, testBufSize)
n, err = conn.Read(buf)
if err != nil || n != len(protocolPolicyResponse) {
b.Errorf("error reading: %v, %d == %d", err, n, len(protocolPolicyResponse))
}
if !bytes.Equal(protocolPolicyResponse, buf[:n]) {
b.Errorf("unexpected response value, exp: %+q, got %+q", protocolPolicyResponse, buf[:n])
}
wg2.Done()
}()
}
wg2.Wait()
}
b.StopTimer()
l.Close()
wg.Wait()
b.StartTimer()
}