-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
81 lines (71 loc) · 1.83 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
package pgxschema
import (
"context"
"log"
"os"
"sync"
"testing"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/ory/dockertest/v3"
)
// TestMain replaces the normal test runner for this package. It connects to
// Docker running on the local machine and launches testing database
// containers to which we then connect and store the connection in a package
// global variable
//
func TestMain(m *testing.M) {
pool, err := dockertest.NewPool("")
if err != nil {
log.Fatalf("Can't run pgxschema tests. Docker is not running: %s", err)
}
var wg sync.WaitGroup
for name := range TestDBs {
testDB := TestDBs[name]
wg.Add(1)
go func() {
testDB.Init(pool)
wg.Done()
}()
}
wg.Wait()
code := m.Run()
// Purge all the containers we created
// You can't defer this because os.Exit doesn't execute defers
for _, info := range TestDBs {
info.Cleanup(pool)
}
os.Exit(code)
}
// withLatestDB runs the provided function with a connection to the most recent
// version of PostgreSQL
func withLatestDB(t *testing.T, f func(db *pgxpool.Pool)) {
db := connectDB(t, "postgres:latest")
defer db.Close()
f(db)
}
// withEachDB runs the provided function with a connection to all PostgreSQL
// versions defined in the TestDBs map
func withEachDB(t *testing.T, f func(db *pgxpool.Pool)) {
t.Helper()
for dbName := range TestDBs {
t.Run(dbName, func(t *testing.T) {
db := connectDB(t, dbName)
defer db.Close()
f(db)
})
}
}
// connectDB opens a connection to the PostgreSQL docker container with the
// provided key name.
func connectDB(t *testing.T, name string) *pgxpool.Pool {
t.Helper()
info, exists := TestDBs[name]
if !exists {
t.Errorf("Database '%s' doesn't exist.", name)
}
db, err := pgxpool.Connect(context.Background(), info.DSN())
if err != nil {
t.Fatalf("Failed to connect to %s: %s", name, err)
}
return db
}