-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg.go
83 lines (69 loc) · 1.67 KB
/
pg.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
package testutils
import (
"context"
"errors"
"fmt"
"testing"
"github.com/bradenrayhorn/beans/beans"
"github.com/bradenrayhorn/beans/internal/sql/migrations"
"github.com/bradenrayhorn/beans/postgres"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/orlangure/gnomock"
pg "github.com/orlangure/gnomock/preset/postgres"
"github.com/stretchr/testify/require"
)
func StartPool(tb testing.TB) (*pgxpool.Pool, func()) {
p := pg.Preset(
pg.WithVersion("15.2"),
pg.WithDatabase("beans"),
pg.WithQueries(getMigrationQueries(tb)),
)
container, err := gnomock.Start(p)
if err != nil {
tb.Fatal(err)
}
pool, err := postgres.CreatePool(
fmt.Sprintf("postgres://%s:%s@%s:%d/%s",
"postgres",
"password",
"127.0.0.1",
container.DefaultPort(),
"beans",
))
if err != nil {
tb.Fatal(err)
}
return pool, func() {
err := gnomock.Stop(container)
if err != nil {
tb.Error("failed to stop container", err)
}
}
}
func getMigrationQueries(tb testing.TB) string {
queries := ""
files, err := migrations.MigrationsFS.ReadDir(".")
if err != nil {
tb.Fatal(err)
}
for _, file := range files {
content, err := migrations.MigrationsFS.ReadFile(file.Name())
if err != nil {
tb.Fatal(err)
}
queries += string(content)
}
return queries
}
func MustExec(t testing.TB, pool *pgxpool.Pool, sql string) {
_, err := pool.Exec(context.Background(), sql)
require.Nil(t, err)
}
func MustRollback(t testing.TB, tx beans.Tx) {
err := tx.Rollback(context.Background())
// Ignore ErrTxClosed as transaction may have already been committed.
if err != nil && !errors.Is(err, pgx.ErrTxClosed) {
t.Error("Failed to rollback tx", err)
}
}