-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup_test.go
99 lines (87 loc) · 2.32 KB
/
setup_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
package gooauth2gorm_test
import (
"context"
"fmt"
"log"
"os"
"testing"
"time"
"github.com/docker/go-connections/nat"
_ "github.com/lib/pq"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
const (
image = "postgres:latest"
logMsg = "database system is ready to accept connections"
)
type PGConfig struct {
User string
Password string
Database string
Port int
}
var dbPort int
var dbHost string
var cfg = PGConfig{User: "test", Database: "test", Password: "test", Port: 5432}
var db *gorm.DB
func TestMain(m *testing.M) {
log.Println("==== TEST MAIN ====")
ctx := context.Background()
natPort := "5432/tcp"
dbURL := func(port nat.Port) string {
return fmt.Sprintf("postgres://test:test@localhost:%s/%s?sslmode=disable", port.Port(), cfg.Database)
}
// Setup and startup container
req := testcontainers.ContainerRequest{
Image: image,
ExposedPorts: []string{natPort},
Env: map[string]string{
"POSTGRES_USER": cfg.User,
"POSTGRES_PASSWORD": cfg.Password,
"POSTGRES_DATABASE": cfg.Database,
},
WaitingFor: wait.ForAll(
wait.ForSQL(nat.Port(natPort), "postgres", dbURL),
wait.ForLog(logMsg),
).WithStartupTimeout(time.Minute * 10),
}
pg, err := testcontainers.GenericContainer(
ctx,
testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
},
)
if err != nil {
fmt.Fprintf(os.Stderr, "testcontainers.GenericContainer %v\n", err)
os.Exit(1)
}
// Even after log message found Postgres needs a touch more...
time.Sleep(200 * time.Millisecond)
containerPort, err := pg.MappedPort(ctx, nat.Port(natPort))
if err != nil {
fmt.Fprintf(os.Stderr, "could not get the port %v\n", err)
os.Exit(1)
}
containerHost, err := pg.Host(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "could not get the host %v\n", err)
os.Exit(1)
}
dbHost = containerHost
dbPort = containerPort.Int()
dsn := fmt.Sprintf("host=%s user=test password=test dbname=test port=%d sslmode=disable", containerHost, containerPort.Int())
gdb, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Fprintf(os.Stderr, "gorm.Open %v\n", err)
os.Exit(1)
}
db = gdb
code := m.Run()
_ = pg.Terminate(ctx)
log.Println("==== TEST MAIN END ====")
os.Exit(code)
}