-
Notifications
You must be signed in to change notification settings - Fork 0
/
integration-dockertest_test.go
82 lines (71 loc) · 2.07 KB
/
integration-dockertest_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
73
74
75
76
77
78
79
80
81
82
//go:build integration
// +build integration
package function
import (
"context"
"fmt"
"log"
"os"
"testing"
"github.com/ory/dockertest/v3"
"github.com/ory/dockertest/v3/docker"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var dbClient *mongo.Client
var dbName = "url-shortener-test"
var urlCollName = "urls"
// TestMain will only run if the build tags include "integration". This TestMain will setup a mongoDB instance with dockertest and tear the container down when finished. This setup/teardown process can take 40 seconds or more.
func TestMain(m *testing.M) {
pool, err := dockertest.NewPool("")
if err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
// pull mongodb docker image for version 5.0
resource, err := pool.RunWithOptions(&dockertest.RunOptions{
Repository: "mongo",
Tag: "5.0",
Env: []string{
// username and password for mongodb superuser
"MONGO_INITDB_ROOT_USERNAME=root",
"MONGO_INITDB_ROOT_PASSWORD=password",
},
}, func(config *docker.HostConfig) {
// set AutoRemove to true so that stopped container goes away by itself
config.AutoRemove = true
config.RestartPolicy = docker.RestartPolicy{
Name: "no",
}
})
if err != nil {
log.Fatalf("Could not start resource: %s", err)
}
// exponential backoff-retry, because the application in the container might not be ready to accept connections yet
err = pool.Retry(func() error {
var err error
dbClient, err = mongo.Connect(
context.TODO(),
options.Client().ApplyURI(
fmt.Sprintf("mongodb://root:password@localhost:%s", resource.GetPort("27017/tcp")),
),
)
if err != nil {
return err
}
return dbClient.Ping(context.TODO(), nil)
})
if err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
// run tests
code := m.Run()
// When you're done, kill and remove the container
if err = pool.Purge(resource); err != nil {
log.Fatalf("Could not purge resource: %s", err)
}
// disconnect mongodb client
if err = dbClient.Disconnect(context.TODO()); err != nil {
panic(err)
}
os.Exit(code)
}