-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_test.go
69 lines (57 loc) · 1.78 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
package redispubsub_test
import (
"context"
"fmt"
"os"
"testing"
"time"
"github.com/go-redis/redis/v9"
"github.com/ory/dockertest/v3"
"github.com/ory/dockertest/v3/docker"
log "github.com/sirupsen/logrus"
)
var redisCli *redis.Client
func TestMain(m *testing.M) {
// uses a sensible default on windows (tcp/http) and linux/osx (socket)
pool, err := dockertest.NewPool("")
if err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
// pulls an image, creates a container based on it and runs it
resource, err := pool.RunWithOptions(&dockertest.RunOptions{
Repository: "redis", // image name
Tag: "7", // version tag
}, 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)
}
resource.Expire(120) // Tell docker to hard kill the container in 120 seconds
// exponential backoff-retry, because the application in the container might not be ready to accept connections yet
pool.MaxWait = 120 * time.Second
hostAndPort := resource.GetHostPort("6379/tcp")
databaseUrl := fmt.Sprintf("redis://%s/0", hostAndPort)
os.Setenv("REDIS_URL", databaseUrl)
if err = pool.Retry(func() error {
opt, err := redis.ParseURL(databaseUrl)
if err != nil {
return err
}
rdb := redis.NewClient(opt)
redisCli = rdb
_, err = rdb.Ping(context.Background()).Result()
return err
}); err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
// Run tests
code := m.Run()
// You can't defer this because os.Exit doesn't care for defer
if err := pool.Purge(resource); err != nil {
log.Fatalf("Could not purge resource: %s", err)
}
os.Exit(code)
}