-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongodb.go
More file actions
93 lines (74 loc) · 2.27 KB
/
mongodb.go
File metadata and controls
93 lines (74 loc) · 2.27 KB
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
package testdock
import (
"context"
"fmt"
"testing"
mongov1 "go.mongodb.org/mongo-driver/mongo"
optionsv1 "go.mongodb.org/mongo-driver/mongo/options"
)
// GetMongoDatabase initializes a test MongoDB database, applies migrations, and returns a database connection.
func GetMongoDatabase(tb testing.TB, dsn string, opt ...Option) (*mongov1.Database, Informer) {
tb.Helper()
ctx := context.Background()
url, err := parseURL(dsn)
if err != nil {
tb.Fatalf("failed to parse dsn: %v", err)
}
optPrepared := make([]Option, 0, len(opt))
optPrepared = append(optPrepared,
WithDockerRepository("mongo"),
WithDockerImage("latest"),
)
if url.User != "" {
optPrepared = append(optPrepared,
WithDockerEnv([]string{
fmt.Sprintf("MONGO_INITDB_ROOT_USERNAME=%s", url.User),
fmt.Sprintf("MONGO_INITDB_ROOT_PASSWORD=%s", url.Password),
}))
}
optPrepared = append(optPrepared, opt...)
tDB := newTDB(ctx, tb, mongoDriverName, dsn, optPrepared)
client, err := tDB.connectMongoDB(ctx)
if err != nil {
tb.Fatalf("cannot connect to mongo: %v", err)
}
tb.Cleanup(func() {
if tDB.mode != RunModeDocker {
// protect against closing connection during tests
clientClean, err := tDB.connectMongoDB(ctx)
if err != nil {
tb.Logf("cannot connect to mongo for cleanup: %v", err)
return
}
defer clientClean.Disconnect(ctx)
dbClean := clientClean.Database(tDB.databaseName)
if err := dbClean.Drop(ctx); err != nil {
tb.Logf("failed to drop database %s: %v", tDB.databaseName, err)
}
}
_ = client.Disconnect(context.Background())
})
return client.Database(tDB.databaseName), tDB
}
// connectMongoDB connects to MongoDB with retries
func (d *testDB) connectMongoDB(ctx context.Context) (*mongov1.Client, error) {
var (
client *mongov1.Client
err error
)
url := d.url.replaceDatabase(d.databaseName)
err = d.retryConnect(ctx, url.string(true), func() error {
client, err = mongov1.Connect(ctx, optionsv1.Client().ApplyURI(url.string(false)))
if err != nil {
return fmt.Errorf("mongo connect: %w", err)
}
if err = client.Ping(ctx, nil); err != nil {
return fmt.Errorf("mongo ping: %w", err)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("connect mongo url (%s): %w", url.string(false), err)
}
return client, nil
}