-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestpostgresconn.go
88 lines (76 loc) · 2.21 KB
/
testpostgresconn.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
package testserver
import (
"fmt"
"log"
"net/url"
"testing"
"time"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/ory/dockertest"
"github.com/rsachdeva/illuminatingdeposits-rest/tools/dbcli/schema"
)
func PostgresConnect(t *testing.T, allowPurge bool) *sqlx.DB {
db, pool, resource := StartPostgresAndMigrate()
t.Cleanup(func() {
t.Logf("Purge allowed is %v", allowPurge)
if allowPurge {
t.Log("Purging dockertest for postgres")
err := pool.Purge(resource)
if err != nil {
t.Fatalf("Could not purge container: %v", err)
}
}
log.Println("End of program")
})
return db
}
func StartPostgresAndMigrate() (*sqlx.DB, *dockertest.Pool, *dockertest.Resource) {
q := make(url.Values)
q.Set("sslmode", "disable")
q.Set("timezone", "utc")
// Construct url.
pgURL := url.URL{
Scheme: "postgres",
User: url.UserPassword("postgres", "postgres"),
Path: "postgres",
RawQuery: q.Encode(),
}
var err error
pool, err := dockertest.NewPool("")
if err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
pw, _ := pgURL.User.Password()
env := []string{
"POSTGRES_USER=" + pgURL.User.Username(),
"POSTGRES_PASSWORD=" + pw,
"POSTGRES_DB=" + pgURL.Path,
}
resource, err := pool.Run("postgres", "13-alpine", env)
if err != nil {
log.Fatalf("Could not start resource: %s", err)
}
var db *sqlx.DB
pool.MaxWait = 115 * time.Second
if err = pool.Retry(func() error {
var err error
// sql.Open("postgres", fmt.Sprintf("postgres://postgres:secret@localhost:%s/%s?sslmode=disable", resource.GetPort("5432/tcp"), "postgres"))
// postgres://postgres:postgres@db/postgres?sslmode=disable&timezone=utc
connStr := fmt.Sprintf("postgres://postgres:postgres@localhost:%s/postgres?sslmode=disable&timezone=utc", resource.GetPort("5432/tcp"))
log.Println("connStr is ", connStr)
db, err = sqlx.Open("postgres", connStr)
if err != nil {
log.Printf(" sql open connection err is %v", err)
return err
}
return db.Ping()
}); err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
err = schema.Migrate(db)
if err != nil {
log.Fatalf("Could not bring the schema for db up to date with schema migrations: %v", err)
}
return db, pool, resource
}