forked from redis/rueidis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rueidis_test.go
382 lines (333 loc) · 8.98 KB
/
rueidis_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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package rueidis
import (
"bufio"
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"testing"
"time"
"go.uber.org/goleak"
)
func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}
func accept(t *testing.T, ln net.Listener) (*redisMock, error) {
conn, err := ln.Accept()
if err != nil {
t.Error(err)
return nil, err
}
mock := &redisMock{
t: t,
buf: bufio.NewReader(conn),
conn: conn,
}
mock.Expect("HELLO", "3").
Reply(RedisMessage{
typ: '%',
values: []RedisMessage{
{typ: '+', string: "key"},
{typ: '+', string: "value"},
},
})
mock.Expect("CLIENT", "TRACKING", "ON", "OPTIN").
ReplyString("OK")
return mock, nil
}
func TestNewClusterClient(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
done := make(chan struct{})
go func() {
mock, err := accept(t, ln)
if err != nil {
return
}
slots, _ := slotsResp.ToMessage()
mock.Expect("CLUSTER", "SLOTS").Reply(slots)
mock.Close()
close(done)
}()
_, port, _ := net.SplitHostPort(ln.Addr().String())
client, err := NewClient(ClientOption{
InitAddress: []string{"127.0.0.1:" + port},
})
if err != nil {
t.Fatal(err)
}
defer client.Close()
if _, ok := client.(*clusterClient); !ok {
t.Fatal("client should be a clusterClient")
}
<-done
}
func TestNewClusterClientError(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
done := make(chan struct{})
go func() {
mock, err := accept(t, ln)
if err != nil {
return
}
mock.Expect("CLUSTER", "SLOTS").Reply(RedisMessage{typ: '-', string: "other error"})
mock.Expect("QUIT").ReplyString("OK")
mock.Close()
close(done)
}()
_, port, _ := net.SplitHostPort(ln.Addr().String())
client, err := NewClient(ClientOption{
InitAddress: []string{"127.0.0.1:" + port},
})
if client != nil || err == nil {
t.Errorf("unexpected return %v %v", client, err)
}
<-done
}
func TestFallBackSingleClient(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
done := make(chan struct{})
go func() {
mock, err := accept(t, ln)
if err != nil {
return
}
mock.Expect("CLUSTER", "SLOTS").Reply(RedisMessage{typ: '-', string: redisErrMsgClusterDisabled})
mock.Expect("QUIT").ReplyString("OK")
mock.Close()
close(done)
}()
_, port, _ := net.SplitHostPort(ln.Addr().String())
client, err := NewClient(ClientOption{
InitAddress: []string{"127.0.0.1:" + port},
})
if err != nil {
t.Fatal(err)
}
if _, ok := client.(*singleClient); !ok {
t.Fatal("client should be a singleClient")
}
client.Close()
<-done
}
func TestTLSClient(t *testing.T) {
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("Failed to generate private key: %v", err)
}
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
t.Fatalf("Failed to generate serial number: %v", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
DNSNames: []string{"localhost"},
Subject: pkix.Name{Organization: []string{"Acme Co"}},
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, priv)
if err != nil {
t.Fatalf("Failed to create certificate: %v", err)
}
certPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
t.Fatalf("Unable to marshal private key: %v", err)
}
privPem := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
cert, err := tls.X509KeyPair(certPem, privPem)
if err != nil {
t.Fatalf("Fail to load X509KeyPair: %v", err)
}
config := &tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
}
ln, err := tls.Listen("tcp", "127.0.0.1:0", config)
if err != nil {
t.Fatal(err)
}
defer ln.Close()
done := make(chan struct{})
go func() {
mock, err := accept(t, ln)
if err != nil {
return
}
mock.Expect("CLUSTER", "SLOTS").Reply(RedisMessage{typ: '-', string: redisErrMsgClusterDisabled})
mock.Expect("QUIT").ReplyString("OK")
mock.Close()
close(done)
}()
_, port, _ := net.SplitHostPort(ln.Addr().String())
client, err := NewClient(ClientOption{
InitAddress: []string{"127.0.0.1:" + port},
TLSConfig: config,
})
if err != nil {
t.Fatal(err)
}
if _, ok := client.(*singleClient); !ok {
t.Fatal("client should be a singleClient")
}
client.Close()
<-done
}
func TestSingleClientMultiplex(t *testing.T) {
option := ClientOption{}
if v := singleClientMultiplex(option.PipelineMultiplex); v != 2 {
t.Fatalf("unexpected value %v", v)
}
option.PipelineMultiplex = -1
if v := singleClientMultiplex(option.PipelineMultiplex); v != 0 {
t.Fatalf("unexpected value %v", v)
}
}
func ExampleIsRedisNil() {
client, err := NewClient(ClientOption{InitAddress: []string{"127.0.0.1:6379"}})
if err != nil {
panic(err)
}
defer client.Close()
_, err = client.Do(context.Background(), client.B().Get().Key("not_exists").Build()).ToString()
if err != nil && IsRedisNil(err) {
fmt.Printf("it is a nil response")
}
}
func ExampleClient_do() {
client, err := NewClient(ClientOption{InitAddress: []string{"127.0.0.1:6379"}})
if err != nil {
panic(err)
}
defer client.Close()
ctx := context.Background()
client.Do(ctx, client.B().Set().Key("k").Value("1").Build()).Error()
client.Do(ctx, client.B().Get().Key("k").Build()).ToString()
client.Do(ctx, client.B().Get().Key("k").Build()).AsInt64()
client.Do(ctx, client.B().Hmget().Key("h").Field("a", "b").Build()).ToArray()
client.Do(ctx, client.B().Scard().Key("s").Build()).ToInt64()
client.Do(ctx, client.B().Smembers().Key("s").Build()).AsStrSlice()
}
func ExampleClient_doCache() {
client, err := NewClient(ClientOption{InitAddress: []string{"127.0.0.1:6379"}})
if err != nil {
panic(err)
}
defer client.Close()
ctx := context.Background()
client.DoCache(ctx, client.B().Get().Key("k").Cache(), time.Minute).ToString()
client.DoCache(ctx, client.B().Get().Key("k").Cache(), time.Minute).AsInt64()
client.DoCache(ctx, client.B().Hmget().Key("h").Field("a", "b").Cache(), time.Minute).ToArray()
client.DoCache(ctx, client.B().Scard().Key("s").Cache(), time.Minute).ToInt64()
client.DoCache(ctx, client.B().Smembers().Key("s").Cache(), time.Minute).AsStrSlice()
}
func ExampleClient_dedicatedCAS() {
client, err := NewClient(ClientOption{InitAddress: []string{"127.0.0.1:6379"}})
if err != nil {
panic(err)
}
defer client.Close()
ctx := context.Background()
client.Dedicated(func(client DedicatedClient) error {
// watch keys first
if err := client.Do(ctx, client.B().Watch().Key("k1", "k2").Build()).Error(); err != nil {
return err
}
// perform read here
values, err := client.Do(ctx, client.B().Mget().Key("k1", "k2").Build()).ToArray()
if err != nil {
return err
}
v1, _ := values[0].ToString()
v2, _ := values[1].ToString()
// perform write with MULTI EXEC
for _, resp := range client.DoMulti(
ctx,
client.B().Multi().Build(),
client.B().Set().Key("k1").Value(v1+"1").Build(),
client.B().Set().Key("k2").Value(v2+"2").Build(),
client.B().Exec().Build(),
) {
if err := resp.Error(); err != nil {
return err
}
}
return nil
})
}
func ExampleClient_dedicateCAS() {
client, err := NewClient(ClientOption{InitAddress: []string{"127.0.0.1:6379"}})
if err != nil {
panic(err)
}
defer client.Close()
c, cancel := client.Dedicate()
defer cancel()
ctx := context.Background()
// watch keys first
if err := c.Do(ctx, c.B().Watch().Key("k1", "k2").Build()).Error(); err != nil {
panic(err)
}
// perform read here
values, err := c.Do(ctx, c.B().Mget().Key("k1", "k2").Build()).ToArray()
if err != nil {
panic(err)
}
v1, _ := values[0].ToString()
v2, _ := values[1].ToString()
// perform write with MULTI EXEC
for _, resp := range c.DoMulti(
ctx,
c.B().Multi().Build(),
c.B().Set().Key("k1").Value(v1+"1").Build(),
c.B().Set().Key("k2").Value(v2+"2").Build(),
c.B().Exec().Build(),
) {
if err := resp.Error(); err != nil {
panic(err)
}
}
}
func ExampleNewClient_cluster() {
client, _ := NewClient(ClientOption{
InitAddress: []string{"127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003"},
ShuffleInit: true,
})
defer client.Close()
}
func ExampleNewClient_single() {
client, _ := NewClient(ClientOption{
InitAddress: []string{"127.0.0.1:6379"},
})
defer client.Close()
}
func ExampleNewClient_sentinel() {
client, _ := NewClient(ClientOption{
InitAddress: []string{"127.0.0.1:26379", "127.0.0.1:26380", "127.0.0.1:26381"},
Sentinel: SentinelOption{
MasterSet: "my_master",
},
})
defer client.Close()
}