-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache_test.go
119 lines (100 loc) · 2.42 KB
/
cache_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
package conncache
import (
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
"inet.af/netaddr"
"log"
"net"
"testing"
"time"
)
func TestGrpcClientCache(t *testing.T) {
var addresses []string
for i := 10000; i < 10100; i++ {
addresses = append(addresses, fmt.Sprintf("127.0.0.1:%d", i))
}
var servers []*grpc.Server
for _, address := range addresses {
lis, err := net.Listen("tcp", address)
if err != nil {
log.Fatalf("failed to listen: %s", err)
}
var opts []grpc.ServerOption
opts = append(opts, grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: 5 * time.Second, // Ample time for iterations
}))
grpcServer := grpc.NewServer(opts...)
servers = append(servers, grpcServer)
go func() {
err := grpcServer.Serve(lis)
if err != nil {
t.Errorf("unable to bind: %s", err)
return
}
}()
}
c := DefaultClientConnCache
c.l.RLock()
clength := len(c.conns)
c.l.RUnlock()
if clength != 0 {
t.Fatalf("connections should be 0, got %d", clength)
}
for _, address := range addresses {
ad, _ := netaddr.ParseIPPort(address)
for i := 0; i < 50; i++ {
ctx, _ := context.WithTimeout(context.Background(), 20*time.Millisecond)
conn, err := c.Get(ctx, ad)
if err != nil {
t.Fatalf("failed to get a connection: %s", err)
}
if conn == nil {
t.Fatalf("connection is nil")
}
}
}
c.l.RLock()
clength = len(c.conns)
c.l.RUnlock()
if clength != 100 {
t.Fatalf("connections should be 100, got %d", clength)
}
time.Sleep(6 * time.Second) // Let server send GOAWAY
c.l.RLock()
clength = len(c.conns)
c.l.RUnlock()
if clength != 0 {
t.Fatalf("connections should be 0, got %d", clength)
}
for _, address := range addresses {
ad, _ := netaddr.ParseIPPort(address)
for i := 0; i < 50; i++ {
ctx, _ := context.WithTimeout(context.Background(), 20*time.Millisecond)
conn, err := c.Get(ctx, ad)
if err != nil {
t.Fatalf("failed to get a connection: %s", err)
}
if conn == nil {
t.Fatalf("connection is nil")
}
}
}
c.l.RLock()
clength = len(c.conns)
c.l.RUnlock()
if clength != 100 {
t.Fatalf("connections should be 100, got %d", clength)
}
c.Close() // Clean up the cache and all connections
c.l.RLock()
clength = len(c.conns)
c.l.RUnlock()
if clength != 0 {
t.Fatalf("connections should be 0, got %d", clength)
}
for _, server := range servers {
server.Stop()
}
}