Feat: memory database for testing

pull/247/head
HFO4 5 years ago
parent f46b52b6ba
commit 8dd411f5d4

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"github.com/HFO4/cloudreve/pkg/conf" "github.com/HFO4/cloudreve/pkg/conf"
"github.com/HFO4/cloudreve/pkg/util" "github.com/HFO4/cloudreve/pkg/util"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"time" "time"
@ -22,7 +23,13 @@ func Init() {
db *gorm.DB db *gorm.DB
err error err error
) )
if gin.Mode() == gin.TestMode {
// 测试模式下,使用内存数据库
db, err = gorm.Open("sqlite3", ":memory:")
} else {
if conf.DatabaseConfig.Type == "UNSET" { if conf.DatabaseConfig.Type == "UNSET" {
// 未指定数据库时使用Sqlite
db, err = gorm.Open("sqlite3", "cloudreve.db") db, err = gorm.Open("sqlite3", "cloudreve.db")
} else { } else {
db, err = gorm.Open(conf.DatabaseConfig.Type, fmt.Sprintf("%s:%s@(%s)/%s?charset=utf8&parseTime=True&loc=Local", db, err = gorm.Open(conf.DatabaseConfig.Type, fmt.Sprintf("%s:%s@(%s)/%s?charset=utf8&parseTime=True&loc=Local",
@ -31,6 +38,7 @@ func Init() {
conf.DatabaseConfig.Host, conf.DatabaseConfig.Host,
conf.DatabaseConfig.Name)) conf.DatabaseConfig.Name))
} }
}
// 处理表前缀 // 处理表前缀
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string { gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {

@ -22,6 +22,9 @@ var mock sqlmock.Sqlmock
// TestMain 初始化数据库Mock // TestMain 初始化数据库Mock
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
// 设置gin为测试模式
gin.SetMode(gin.TestMode)
var db *sql.DB var db *sql.DB
var err error var err error
db, mock, err = sqlmock.New() db, mock, err = sqlmock.New()
@ -31,8 +34,6 @@ func TestMain(m *testing.M) {
model.DB, _ = gorm.Open("mysql", db) model.DB, _ = gorm.Open("mysql", db)
defer db.Close() defer db.Close()
// 设置gin为测试模式
gin.SetMode(gin.TestMode)
m.Run() m.Run()
} }

Loading…
Cancel
Save