forked from btubbs/pgq
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pgq_test.go
95 lines (85 loc) · 1.73 KB
/
pgq_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
package pgq
import (
"fmt"
"math/rand"
"os"
"testing"
"time"
"github.com/jmoiron/sqlx"
)
func getTestDB() *sqlx.DB {
db, err := sqlx.Open("postgres", "postgres://postgres@/pgq_test?sslmode=disable")
if err != nil {
panic(err)
}
if err != nil {
panic(err)
}
return db
}
func cleanDB() {
masterDB := getMasterDB()
defer masterDB.Close()
_, err := masterDB.Exec("DROP DATABASE IF EXISTS pgq_test;")
if err != nil {
panic(err)
}
_, err = masterDB.Exec("CREATE DATABASE pgq_test;")
if err != nil {
panic(err)
}
db := getTestDB()
defer db.Close()
_, err = db.Exec(createTableSQL)
if err != nil {
panic(err)
}
}
// creates a random DB, runs a function with it, then destroys the random DB
func withFreshDB(testFunc func(*sqlx.DB)) {
masterDB := getMasterDB()
defer masterDB.Close()
dbName := "pgq_test_" + randString(12)
_, err := masterDB.Exec("CREATE DATABASE " + dbName)
if err != nil {
panic(err)
}
dbURL := fmt.Sprintf("postgres://postgres@/%s?sslmode=disable", dbName)
db, err := sqlx.Open("postgres", dbURL)
if err != nil {
panic(err)
}
defer func() {
// close DB
db.Close()
// delete DB
masterDB.Exec("DROP DATABASE " + dbName)
}()
_, err = db.Exec(createTableSQL)
if err != nil {
panic(err)
}
testFunc(db)
}
func getMasterDB() *sqlx.DB {
masterDB, err := sqlx.Open("postgres", "postgres://postgres@/postgres?sslmode=disable")
if err != nil {
panic(err)
}
return masterDB
}
func TestMain(m *testing.M) {
cleanDB()
os.Exit(m.Run())
}
func init() {
rand.Seed(time.Now().UnixNano())
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz")
func randString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}