-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool_test.go
129 lines (121 loc) · 2.19 KB
/
pool_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
package cpool
import (
"fmt"
"sync"
"testing"
"time"
)
type DummyConn struct {
val string
}
func Dial(addr string) (Conn, error) {
return &DummyConn{}, nil
}
func Heartbeat(c Conn) error {
return nil
}
func Close(c Conn) error {
return nil
}
func Test_NewClose(t *testing.T) {
p, err := New(
"0.0.0.0",
Dial,
Heartbeat,
Close,
10, 5, time.Second,
)
if err != nil {
t.Fatal("Unable to create new pool")
}
if p.opened != 1 || p.idle != 1 {
t.Fatal("Incorrect state on start")
}
err = p.Close()
if err != nil {
t.Fatal("Failed on close")
}
if p.opened != 0 || p.idle != 0 {
t.Fatal("Incorrect state on stop")
}
select {
case <-p.connChan:
default:
t.Fatal("Channel was not closed")
}
}
func Test_Get(t *testing.T) {
p, err := New(
"0.0.0.0",
Dial,
Heartbeat,
Close,
10, 5, time.Second,
)
if err != nil {
t.Fatal("Unable to create new pool")
}
wg := sync.WaitGroup{}
for i := 0; i < 11; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, done, err := p.Get()
if err != nil {
t.Fatal("Failed getting new connection", err.Error())
}
defer done()
<-time.After(time.Second)
}()
}
wg.Wait()
if p.opened != 5 || p.idle != 5 {
t.Fatal("Incorrect state on tasks done")
}
}
func Test_Heartbeat(t *testing.T) {
hb, dials, closes := 0, 0, 0
p, err := New(
"0.0.0.0",
func(addr string) (Conn, error) {
dials++
return &DummyConn{val: fmt.Sprintf("%d", dials)}, nil
},
func(c Conn) error {
hb++
return nil
},
func(c Conn) error {
closes++
return nil
},
10, 5, time.Millisecond,
)
if err != nil {
t.Fatal("Unable to create new pool")
}
wg := sync.WaitGroup{}
for i := 0; i < 11; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, done, err := p.Get()
if err != nil {
t.Fatal("Failed getting new connection", err.Error())
}
defer done()
<-time.After(time.Second)
}()
}
wg.Wait()
if p.opened != 5 || p.idle != 5 {
t.Fatal("Incorrect state on tasks done")
}
<-time.After(time.Second)
if dials != 10 || closes != 5 || hb != 1 {
t.Fatal("Dial, closes, heartbeat no incorrect", dials, closes, hb)
}
if len(p.heartbeatMap) != 5 {
t.Fatal("Map size incorrect", len(p.heartbeatMap))
}
}