-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongodb.go
54 lines (41 loc) · 1.09 KB
/
mongodb.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
package testing
import (
"context"
"strconv"
"strings"
"sync"
"testing"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoOptions interface {
GetOptions() *options.ClientOptions
}
var (
client *mongo.Client
clientOnce sync.Once
)
const mongoTimeout = 5 * time.Second
func CreateMongoDBWithDBName(t testing.TB, optMaker MongoOptions) (*mongo.Client, string) {
t.Helper()
database := strings.ReplaceAll(t.Name(), "/", "_") + "_" + strconv.FormatInt(time.Now().UTC().UnixMilli(), 10)
clientOnce.Do(func() {
var err error
opt := optMaker.GetOptions()
ctx, cancel := context.WithTimeout(context.Background(), mongoTimeout)
defer cancel()
client, err = mongo.Connect(ctx, opt)
if err != nil {
t.Fatalf("Failed to connect to Mongo. Error %v", err)
}
})
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), mongoTimeout)
defer cancel()
if err := client.Database(database).Drop(ctx); err != nil {
t.Errorf("Failed to drop Mongo database. Error: %v", err)
}
})
return client, database
}