-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
87 lines (76 loc) · 2.08 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package sequel
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
)
const (
dbName = "sequel"
dbUser = "test"
dbPassword = "password"
postgresImage = "docker.io/postgres:16.0-alpine"
)
var postgresDataSource string
func withSchemaSQL() testcontainers.CustomizeRequestOption {
return func(req *testcontainers.GenericContainerRequest) error {
req.Files = append(req.Files, testcontainers.ContainerFile{
HostFilePath: filepath.Join("testdata", "schema.sql"),
ContainerFilePath: "/tmp/schema.sql",
FileMode: 0644,
})
return nil
}
}
func TestMain(m *testing.M) {
var cleanups []func()
cleanup := func(fn func()) {
cleanups = append(cleanups, fn)
}
fatal := func(args ...any) {
fmt.Fprintln(os.Stderr, args...)
for _, fn := range cleanups {
fn()
}
os.Exit(1)
}
ctx := context.Background()
postgresContainer, err := postgres.Run(ctx, postgresImage,
postgres.WithDatabase(dbName),
postgres.WithUsername(dbUser),
postgres.WithPassword(dbPassword),
postgres.WithInitScripts(filepath.Join("testdata", "init-db.sh")),
withSchemaSQL(),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(5*time.Second),
),
)
if err != nil {
fatal("error creating postgres container:", err)
}
cleanup(func() {
if err := postgresContainer.Terminate(ctx); err != nil {
fmt.Fprintln(os.Stderr, "error terminating postgres:", err)
}
})
postgresState, err := postgresContainer.State(ctx)
if err != nil {
fatal(err)
}
if !postgresState.Running {
fatal("Postgres status:", postgresState.Status)
}
postgresPort, err := postgresContainer.MappedPort(ctx, "5432/tcp")
if err != nil {
fatal(err)
}
postgresDataSource = fmt.Sprintf("postgres://%s:%s@localhost:%s/%s?sslmode=disable&application_name=test", dbUser, dbPassword, postgresPort.Port(), dbName)
os.Exit(m.Run())
}