-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_test.go
73 lines (56 loc) · 1.36 KB
/
test_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
package grocery
import (
"context"
"net"
"os"
"testing"
"github.com/redis/go-redis/v9"
)
var keys = map[string]bool{}
func TestMain(m *testing.M) {
// Create grocery client
Init(&redis.Options{
Addr: "localhost:6379",
})
// Add hook for saving keys
C.AddHook(testHook{})
// Run unit test
code := m.Run()
// Delete all keys saved to Redis while running unit tests
pip := C.Pipeline()
for id := range keys {
pip.Del(ctx, id)
}
pip.Exec(ctx)
// Exit from test
os.Exit(code)
}
// Hooks used to save keys stored during tests so we can delete them once tests complete
type testHook struct{}
func (testHook) DialHook(next redis.DialHook) redis.DialHook {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
return next(ctx, network, addr)
}
}
func (testHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
if err := next(ctx, cmd); err != nil {
return err
}
keys[cmd.Args()[1].(string)] = true
return nil
}
}
func (testHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return func(ctx context.Context, cmds []redis.Cmder) error {
if err := next(ctx, cmds); err != nil {
return err
}
for _, cmd := range cmds {
if len(cmd.Args()) >= 2 {
keys[cmd.Args()[1].(string)] = true
}
}
return nil
}
}