-
Notifications
You must be signed in to change notification settings - Fork 22
/
setup_test.go
85 lines (67 loc) · 1.86 KB
/
setup_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
package migrations
import (
"os"
"testing"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"github.com/stretchr/testify/assert"
)
func TestEnsureMigrationTables(t *testing.T) {
db := pg.Connect(&pg.Options{
Addr: "localhost:5432",
User: os.Getenv("TEST_DATABASE_USER"),
Database: os.Getenv("TEST_DATABASE_NAME"),
})
m := newMigrator(db, RunOptions{})
// drop tables to start from a clean database
dropMigrationTables(t, db)
err := m.ensureMigrationTables()
assert.Nil(t, err)
tables := []string{"migrations", "migration_lock"}
for _, table := range tables {
assertTable(t, db, table, true)
}
assertOneLock(t, db)
// with existing tables, ensureMigrationTables should do anything
err = m.ensureMigrationTables()
assert.Nil(t, err)
for _, table := range tables {
assertTable(t, db, table, true)
}
assertOneLock(t, db)
}
func dropMigrationTables(t *testing.T, db *pg.DB) {
t.Helper()
_, err := db.Exec("DROP TABLE IF EXISTS migrations")
assert.Nil(t, err)
_, err = db.Exec("DROP TABLE IF EXISTS migration_lock")
assert.Nil(t, err)
_, err = db.Exec("DROP TABLE IF EXISTS custom_migrations")
assert.Nil(t, err)
_, err = db.Exec("DROP TABLE IF EXISTS custom_migration_lock")
assert.Nil(t, err)
}
func assertTable(t *testing.T, db *pg.DB, table string, exists bool) {
t.Helper()
want := 0
msg := "expected %q table to not exist"
if exists {
want = 1
msg = "expected %q table to exist"
}
count, err := orm.NewQuery(db).
Table("information_schema.tables").
Where("table_name = ?", table).
Where("table_schema = current_schema").
Count()
assert.Nil(t, err)
assert.Equalf(t, want, count, msg, table)
}
func assertOneLock(t *testing.T, db *pg.DB) {
t.Helper()
count, err := orm.NewQuery(db).
Table("migration_lock").
Count()
assert.Nil(t, err)
assert.Equal(t, 1, count, "expected migraions_lock to have a row")
}