-
Notifications
You must be signed in to change notification settings - Fork 19
/
connpool_test.go
134 lines (111 loc) · 2.26 KB
/
connpool_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
package mongonet
import "fmt"
import "net"
import "testing"
import "time"
type FakeServer struct {
numAccepted int
}
func (fs *FakeServer) doThread(conn net.Conn, threadNumber int) {
defer conn.Close()
fmt.Printf("connection from %s\n", conn.RemoteAddr())
}
func (fs *FakeServer) run(ln net.Listener) {
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
fs.numAccepted++
go fs.doThread(conn, fs.numAccepted)
}
}
func (fs *FakeServer) start(port int) error {
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
return err
}
go fs.run(ln)
return nil
}
func fun(cp *ConnectionPool) error {
conn, err := cp.Get()
if err != nil {
return err
}
defer conn.Close()
return nil
}
func funBad(cp *ConnectionPool) error {
conn, err := cp.Get()
if err != nil {
return err
}
conn.bad = true
defer conn.Close()
return nil
}
func TestConnectionPool1(t *testing.T) {
port := 12349
fs := FakeServer{}
err := fs.start(port)
if err != nil {
t.Errorf("can't start %s", err)
}
cp := NewConnectionPool(fmt.Sprintf("127.0.0.1:%d", port), false, nil)
cp.timeoutSeconds = 1
// first loop
err = fun(cp)
if err != nil {
t.Errorf("error funning %s", err)
return
}
if cp.LoadTotalCreated() != 1 {
t.Errorf("why is total created %d", cp.LoadTotalCreated())
return
}
// 2nd loop, should re-use connection
err = fun(cp)
if err != nil {
t.Errorf("error funning %s", err)
return
}
if cp.LoadTotalCreated() != 1 {
t.Errorf("why is total created %d", cp.LoadTotalCreated())
return
}
garbage, err := cp.Get()
if err != nil {
panic(err)
}
defer garbage.Close()
err = fun(cp)
if err != nil {
t.Errorf("error funning %s", err)
return
}
if cp.LoadTotalCreated() != 2 {
t.Errorf("why is total created %d", cp.LoadTotalCreated())
return
}
time.Sleep(time.Duration(int64(time.Second) * (cp.timeoutSeconds + 1)))
err = fun(cp)
if err != nil {
t.Errorf("error funning %s", err)
return
}
if cp.LoadTotalCreated() != 3 {
t.Errorf("why is total created %d", cp.LoadTotalCreated())
return
}
before := cp.CurrentInPool()
err = funBad(cp)
if err != nil {
panic(err)
}
after := cp.CurrentInPool()
if after != before-1 {
t.Errorf("bad didn't work %d -> %d", before, after)
return
}
}