-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
migtest.go
93 lines (78 loc) · 2.02 KB
/
migtest.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
package migtest
import (
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/lightningnetwork/lnd/channeldb/kvdb"
)
// MakeDB creates a new instance of the ChannelDB for testing purposes. A
// callback which cleans up the created temporary directories is also returned
// and intended to be executed after the test completes.
func MakeDB() (kvdb.Backend, func(), error) {
// Create temporary database for mission control.
file, err := ioutil.TempFile("", "*.db")
if err != nil {
return nil, nil, err
}
dbPath := file.Name()
db, err := kvdb.Open(
kvdb.BoltBackendName, dbPath, true, kvdb.DefaultDBTimeout,
)
if err != nil {
return nil, nil, err
}
cleanUp := func() {
db.Close()
os.RemoveAll(dbPath)
}
return db, cleanUp, nil
}
// ApplyMigration is a helper test function that encapsulates the general steps
// which are needed to properly check the result of applying migration function.
func ApplyMigration(t *testing.T,
beforeMigration, afterMigration, migrationFunc func(tx kvdb.RwTx) error,
shouldFail bool) {
cdb, cleanUp, err := MakeDB()
defer cleanUp()
if err != nil {
t.Fatal(err)
}
// beforeMigration usually used for populating the database
// with test data.
err = kvdb.Update(cdb, beforeMigration, func() {})
if err != nil {
t.Fatal(err)
}
defer func() {
if r := recover(); r != nil {
err = newError(r)
}
if err == nil && shouldFail {
t.Fatal("error wasn't received on migration stage")
} else if err != nil && !shouldFail {
t.Fatalf("error was received on migration stage: %v", err)
}
// afterMigration usually used for checking the database state and
// throwing the error if something went wrong.
err = kvdb.Update(cdb, afterMigration, func() {})
if err != nil {
t.Fatal(err)
}
}()
// Apply migration.
err = kvdb.Update(cdb, migrationFunc, func() {})
if err != nil {
t.Logf("migration error: %v", err)
}
}
func newError(e interface{}) error {
var err error
switch e := e.(type) {
case error:
err = e
default:
err = fmt.Errorf("%v", e)
}
return err
}