-
Notifications
You must be signed in to change notification settings - Fork 18
/
redisfixture.go
108 lines (85 loc) · 2.2 KB
/
redisfixture.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
package redisfixture
import (
"context"
"hash/fnv"
"math/rand"
"strconv"
"sync"
"github.com/redis/go-redis/v9"
"gotest.tools/v3/assert"
"gotest.tools/v3/assert/cmp"
"github.com/circleci/ex/o11y"
"github.com/circleci/ex/testing/internal/types"
)
type Fixture struct {
*redis.Client
DB int
}
type Connection struct {
Addr string
}
var (
once sync.Once
databaseCount = uint32(0)
)
func Setup(ctx context.Context, t types.TestingTB, con Connection) *Fixture {
ctx, span := o11y.StartSpan(ctx, "redisfixture: setup")
defer span.End()
once.Do(func() {
readDatabasesCount(ctx, t, con)
})
switch {
case databaseCount == 0:
t.Skip("Redis not available")
case databaseCount < 1000000:
t.Fatal("not enough Redis databases a unique DB per test, add '--databases 1000000' to Redis setup command")
}
// Tests for different go packages are run in parallel by the go test runtime, so
// we try and use a unique DB for each test.
db := hash(t.Name(), databaseCount)
span.AddField("db", db)
fixClient := redis.NewClient(&redis.Options{
Addr: con.Addr,
DB: db,
})
t.Cleanup(func() {
assert.Check(t, fixClient.Close())
})
checkRedisConnection(ctx, t, fixClient)
err := fixClient.FlushDB(ctx).Err()
assert.Assert(t, err)
return &Fixture{
Client: fixClient,
DB: db,
}
}
func checkRedisConnection(ctx context.Context, t types.TestingTB, client *redis.Client) {
err := client.Ping(ctx).Err()
switch {
case err != nil && err.Error() == "ERR DB index is out of range":
assert.Assert(t, err)
case err != nil:
t.Skip("Redis not available")
}
}
func readDatabasesCount(ctx context.Context, t types.TestingTB, con Connection) {
t.Helper()
setupClient := redis.NewClient(&redis.Options{
Addr: con.Addr,
})
checkRedisConnection(ctx, t, setupClient)
res := setupClient.ConfigGet(ctx, "databases")
assert.Assert(t, res.Err())
v := res.Val()
assert.Assert(t, cmp.Len(v, 1))
dbs, err := strconv.ParseInt(v["databases"], 10, 64)
assert.Assert(t, err)
databaseCount = uint32(dbs)
}
func hash(s string, databaseCount uint32) int {
h := fnv.New32()
_, _ = h.Write([]byte(s))
//#nosec:G404 // this is fixture
r := rand.Uint32()
return int((h.Sum32()+r)%(databaseCount-1)) + 1
}