-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_utils.go
89 lines (72 loc) · 1.79 KB
/
test_utils.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
package utils
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/spf13/viper"
"github.com/Bnei-Baruch/archive-backend/migrations"
)
type TestDBManager struct {
DB *sql.DB
testDB string
}
func (m *TestDBManager) InitTestDB() error {
m.testDB = fmt.Sprintf("test_%s", strings.ToLower(GenerateName(10)))
// Open connection to RDBMS
db, err := sql.Open("postgres", viper.GetString("test.mdb-url"))
if err != nil {
return err
}
// Create a new temporary test database
if _, err := db.Exec("CREATE DATABASE " + m.testDB); err != nil {
return err
}
// Close first connection and connect to temp database
db.Close()
db, err = sql.Open("postgres", fmt.Sprintf(viper.GetString("test.url-template"), m.testDB))
if err != nil {
return err
}
m.DB = db
// Run migrations
return m.runMigrations(db)
}
func (m *TestDBManager) DestroyTestDB() error {
// Close temp DB
err := m.DB.Close()
if err != nil {
return err
}
// Connect to MDB
db, err := sql.Open("postgres", viper.GetString("test.mdb-url"))
if err != nil {
return err
}
// Drop test DB
_, err = db.Exec("DROP DATABASE " + m.testDB)
return err
}
func (m *TestDBManager) runMigrations(db *sql.DB) error {
var visit = func(path string, f os.FileInfo, err error) error {
match, _ := regexp.MatchString(".*\\.sql$", path)
if !match {
return nil
}
//fmt.Printf("Applying migration %s\n", path)
m, err := migrations.NewMigration(path)
if err != nil {
fmt.Printf("Error migrating %s, %s", path, err.Error())
return err
}
for _, statement := range m.Up() {
if _, err := db.Exec(statement); err != nil {
return fmt.Errorf("Unable to apply migration %s: %s\nStatement: %s\n", m.Name, err, statement)
}
}
return nil
}
return filepath.Walk("../migrations", visit)
}