-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
72 lines (59 loc) · 1.25 KB
/
main_test.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
package mgs_test
import (
"context"
"fmt"
"log"
"os"
"strings"
"testing"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
client *mongo.Client
dbName = "mgs_test"
)
func setup() func(context.Context) {
url := os.Getenv("DATABASE_URL")
if url == "" {
url = "mongodb://localhost:27017"
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var err error
client, err = mongo.Connect(ctx, options.Client().ApplyURI(url))
if err != nil {
log.Fatal(err)
}
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
host := "localhost db"
if !strings.Contains(url, "localhost") {
host = "remote db"
}
fmt.Printf("db client connected to %s successfully \n", host)
return func(ctx context.Context) {
if err := client.Database(dbName).Drop(ctx); err != nil {
panic(err)
}
if err := client.Disconnect(ctx); err != nil {
panic(err)
}
}
}
func getDb(ctx context.Context) (*mongo.Database, func(context.Context)) {
db := client.Database(dbName)
return db, func(ctx context.Context) {
if err := db.Drop(ctx); err != nil {
panic(err)
}
}
}
func TestMain(m *testing.M) {
teardown := setup()
defer teardown(context.Background())
m.Run()
}