-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
mongodbhelper.go
62 lines (52 loc) · 1.78 KB
/
mongodbhelper.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
package mongodb
import (
"context"
"fmt"
"os"
"testing"
"time"
"github.com/hashicorp/vault/helper/testhelpers/docker"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
// PrepareTestContainer calls PrepareTestContainerWithDatabase without a
// database name value, which results in configuring a database named "test"
func PrepareTestContainer(t *testing.T, version string) (cleanup func(), retURL string) {
return PrepareTestContainerWithDatabase(t, version, "")
}
// PrepareTestContainerWithDatabase configures a test container with a given
// database name, to test non-test/admin database configurations
func PrepareTestContainerWithDatabase(t *testing.T, version, dbName string) (func(), string) {
if os.Getenv("MONGODB_URL") != "" {
return func() {}, os.Getenv("MONGODB_URL")
}
runner, err := docker.NewServiceRunner(docker.RunOptions{
ImageRepo: "mongo",
ImageTag: version,
Ports: []string{"27017/tcp"},
})
if err != nil {
t.Fatalf("could not start docker mongo: %s", err)
}
svc, err := runner.StartService(context.Background(), func(ctx context.Context, host string, port int) (docker.ServiceConfig, error) {
connURL := fmt.Sprintf("mongodb://%s:%d", host, port)
if dbName != "" {
connURL = fmt.Sprintf("%s/%s", connURL, dbName)
}
ctx, _ = context.WithTimeout(context.Background(), 1*time.Minute)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(connURL))
if err != nil {
return nil, err
}
err = client.Ping(ctx, readpref.Primary())
if err = client.Disconnect(ctx); err != nil {
t.Fatal()
}
return docker.NewServiceURLParse(connURL)
})
if err != nil {
t.Fatalf("could not start docker mongo: %s", err)
}
return svc.Cleanup, svc.Config.URL().String()
}