-
-
Notifications
You must be signed in to change notification settings - Fork 434
/
container_test.go
102 lines (91 loc) · 2.56 KB
/
container_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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package e2e
import (
"context"
"fmt"
"testing"
"time"
"github.com/docker/go-connections/nat"
"github.com/stretchr/testify/require"
. "github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
_ "github.com/lib/pq"
)
func TestContainerWithWaitForSQL(t *testing.T) {
const dbname = "postgres"
ctx := context.Background()
var env = map[string]string{
"POSTGRES_PASSWORD": "password",
"POSTGRES_USER": "postgres",
"POSTGRES_DB": dbname,
}
var port = "5432/tcp"
dbURL := func(host string, port nat.Port) string {
return fmt.Sprintf("postgres://postgres:password@%s:%s/%s?sslmode=disable", host, port.Port(), dbname)
}
t.Run("default query", func(t *testing.T) {
req := ContainerRequest{
Image: "postgres:14.1-alpine",
ExposedPorts: []string{port},
Cmd: []string{"postgres", "-c", "fsync=off"},
Env: env,
WaitingFor: wait.ForSQL(nat.Port(port), "postgres", dbURL).
Timeout(time.Second * 5),
}
container, err := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
t.Fatal(err)
}
terminateContainerOnEnd(t, ctx, container)
})
t.Run("custom query", func(t *testing.T) {
req := ContainerRequest{
Image: "postgres:14.1-alpine",
ExposedPorts: []string{port},
Cmd: []string{"postgres", "-c", "fsync=off"},
Env: env,
WaitingFor: wait.ForSQL(nat.Port(port), "postgres", dbURL).
Timeout(time.Second * 5).
WithQuery("SELECT 10"),
}
container, err := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
t.Fatal(err)
}
terminateContainerOnEnd(t, ctx, container)
})
t.Run("custom bad query", func(t *testing.T) {
req := ContainerRequest{
Image: "postgres:14.1-alpine",
ExposedPorts: []string{port},
Cmd: []string{"postgres", "-c", "fsync=off"},
Env: env,
WaitingFor: wait.ForSQL(nat.Port(port), "postgres", dbURL).
Timeout(time.Second * 5).
WithQuery("SELECT 'a' from b"),
}
container, err := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err == nil {
t.Fatal("expected error, but got a nil")
}
terminateContainerOnEnd(t, ctx, container)
})
}
func terminateContainerOnEnd(tb testing.TB, ctx context.Context, ctr Container) {
tb.Helper()
if ctr == nil {
return
}
tb.Cleanup(func() {
tb.Log("terminating container")
require.NoError(tb, ctr.Terminate(ctx))
})
}