-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathtesting.go
103 lines (88 loc) · 2.17 KB
/
testing.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package testing
import (
"io"
"os"
"strconv"
"testing"
"time"
dockertypes "github.com/docker/docker/api/types"
)
type IsReadyFunc func(Instance) bool
type TestFunc func(*testing.T, Instance)
type Version struct {
Image string
ENV []string
Cmd []string
}
func ParallelTest(t *testing.T, versions []Version, readyFn IsReadyFunc, testFn TestFunc) {
timeout, err := strconv.Atoi(os.Getenv("MIGRATE_TEST_CONTAINER_BOOT_TIMEOUT"))
if err != nil {
timeout = 60 // Cassandra docker image can take ~30s to start
}
for i, version := range versions {
version := version // capture range variable, see https://goo.gl/60w3p2
// Only test against one version in short mode
// TODO: order is random, maybe always pick first version instead?
if i > 0 && testing.Short() {
t.Logf("Skipping %v in short mode", version)
} else {
t.Run(version.Image, func(t *testing.T) {
t.Parallel()
// create new container
container, err := NewDockerContainer(t, version.Image, version.ENV, version.Cmd)
if err != nil {
t.Fatalf("%v\n%s", err, containerLogs(t, container))
}
// make sure to remove container once done
defer func() {
if err := container.Remove(); err != nil {
t.Error(err)
}
}()
// wait until database is ready
tick := time.NewTicker(1000 * time.Millisecond)
defer tick.Stop()
timeout := time.NewTimer(time.Duration(timeout) * time.Second)
defer timeout.Stop()
outer:
for {
select {
case <-tick.C:
if readyFn(container) {
break outer
}
case <-timeout.C:
t.Fatalf("Docker: Container not ready, timeout for %v.\n%s", version, containerLogs(t, container))
}
}
// we can now run the tests
testFn(t, container)
})
}
}
}
func containerLogs(t *testing.T, c *DockerContainer) []byte {
r, err := c.Logs()
if err != nil {
t.Error(err)
return nil
}
defer func() {
if err := r.Close(); err != nil {
t.Error(err)
}
}()
b, err := io.ReadAll(r)
if err != nil {
t.Error(err)
return nil
}
return b
}
type Instance interface {
Host() string
Port() uint
PortFor(int) uint
NetworkSettings() dockertypes.NetworkSettings
KeepForDebugging()
}