forked from qiangxue/go-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
54 lines (48 loc) · 1.2 KB
/
db.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
package test
import (
"path"
"runtime"
"testing"
dbx "github.com/go-ozzo/ozzo-dbx"
_ "github.com/lib/pq" // initialize posgresql for test
"github.com/omid9h/go-rest-api/internal/config"
"github.com/omid9h/go-rest-api/pkg/dbcontext"
"github.com/omid9h/go-rest-api/pkg/log"
)
var db *dbcontext.DB
// DB returns the database connection for testing purpose.
func DB(t *testing.T) *dbcontext.DB {
if db != nil {
return db
}
logger, _ := log.NewForTest()
dir := getSourcePath()
cfg, err := config.Load(dir+"/../../config/local.yml", logger)
if err != nil {
t.Error(err)
t.FailNow()
}
dbc, err := dbx.MustOpen("postgres", cfg.DSN)
if err != nil {
t.Error(err)
t.FailNow()
}
dbc.LogFunc = logger.Infof
db = dbcontext.New(dbc)
return db
}
// ResetTables truncates all data in the specified tables.
func ResetTables(t *testing.T, db *dbcontext.DB, tables ...string) {
for _, table := range tables {
_, err := db.DB().TruncateTable(table).Execute()
if err != nil {
t.Error(err)
t.FailNow()
}
}
}
// getSourcePath returns the directory containing the source code that is calling this function.
func getSourcePath() string {
_, filename, _, _ := runtime.Caller(1)
return path.Dir(filename)
}