-
Notifications
You must be signed in to change notification settings - Fork 18
/
mongofixture.go
77 lines (63 loc) · 1.4 KB
/
mongofixture.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
/*
Package mongofixture will setup an isolated Mongo DB for your tests, so they don't interfere.
*/
package mongofixture
import (
"context"
"encoding/hex"
"fmt"
"math/rand"
"strings"
"testing"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"gotest.tools/v3/assert"
"github.com/circleci/ex/o11y"
)
type Fixture struct {
DB *mongo.Database
Name string
URI string
}
type Connection struct {
URI string
}
func Setup(ctx context.Context, t testing.TB, con Connection) *Fixture {
t.Helper()
ctx, span := o11y.StartSpan(ctx, "mongofixture: setup")
defer span.End()
opts := options.Client().
ApplyURI(con.URI).
SetAppName("test")
client, err := mongo.Connect(ctx, opts)
assert.Assert(t, err)
t.Cleanup(func() {
assert.Check(t, client.Disconnect(ctx))
})
name := fmt.Sprintf("%s-%s", randomSuffix(), strings.ReplaceAll(t.Name(), "/", "_"))
name = truncate(name)
span.AddField("name", name)
db := client.Database(name)
t.Cleanup(func() {
assert.Check(t, db.Drop(ctx))
})
return &Fixture{
DB: db,
Name: name,
URI: con.URI,
}
}
func randomSuffix() string {
bytes := make([]byte, 3)
//#nosec:G404 - this is just a name for a test database
if _, err := rand.Read(bytes); err != nil {
return "not-random--i-hope-thats-ok"
}
return hex.EncodeToString(bytes)
}
func truncate(s string) string {
if len(s) >= 64 {
return s[:63]
}
return s
}