This repository has been archived by the owner on Jan 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_helpers.go
65 lines (59 loc) · 1.87 KB
/
test_helpers.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
package internal
import (
"context"
"fmt"
"log"
"time"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/ory/dockertest/v3"
)
// StartDockerDB is a helper method to automatically start a postgres docker instance via dockertest.
// returns a pgxpool, a docker purge func, and/or error
func StartDockerDB(name string) (*pgxpool.Pool, func() error, error) {
var pgxPool *pgxpool.Pool
var pgURI string
// create dockertest pool
dockerPool, err := dockertest.NewPool("")
if err != nil {
return nil, nil, fmt.Errorf("StartDockerDB() error creating new pool: %v", err)
}
// start the postgres instance
resource, err := dockerPool.Run("postgres", "latest", []string{"POSTGRES_PASSWORD=secret"})
if err != nil {
return nil, nil, fmt.Errorf("StartDockerDB() error creating resource: %v", err)
}
// 10 second wait time to connect to the db
dockerPool.MaxWait = time.Second * 10
err = dockerPool.Retry(func() error {
pgURI = fmt.Sprintf(
"postgres://postgres:secret@localhost:%s/postgres?sslmode=disable",
resource.GetPort("5432/tcp"),
)
pgxPool, err = pgxpool.Connect(context.Background(), pgURI)
if err != nil {
return err
}
conn, err := pgxPool.Acquire(context.Background())
if err != nil {
return err
}
defer conn.Release()
return conn.Conn().Ping(context.Background())
})
if err != nil {
return nil, nil, fmt.Errorf("StartDockerDB() error connecting: %v", err)
}
// run migrations
mig, err := migrate.New("file://../../migrations", pgURI)
if err != nil {
log.Fatalf("couldn't create migrate struct : %v", err)
}
err = mig.Up()
if err != nil && err.Error() != "no change" {
log.Fatalf("couldn't run migrations: %v", err)
}
return pgxPool, func() error { return dockerPool.Purge(resource) }, nil
}