genofire/hs_monolith
genofire
/
hs_monolith
Archived
1
0
Fork 0

[TASK] add test to database lib

This commit is contained in:
Martin Geno 2017-03-30 18:44:09 +02:00
parent 19be8eb253
commit 07eb1e384b
No known key found for this signature in database
GPG Key ID: F0D39A37E925E941
2 changed files with 81 additions and 0 deletions

View File

@ -22,11 +22,17 @@ type Config struct {
func Open(c Config) (err error) { func Open(c Config) (err error) {
config = &c config = &c
Write, err = gorm.Open(config.Type, config.Connection) Write, err = gorm.Open(config.Type, config.Connection)
Write.SingularTable(true)
Write.Callback().Create().Remove("gorm:update_time_stamp")
Write.Callback().Update().Remove("gorm:update_time_stamp")
if err != nil { if err != nil {
return return
} }
if len(config.ReadConnection) > 0 { if len(config.ReadConnection) > 0 {
Read, err = gorm.Open(config.Type, config.ReadConnection) Read, err = gorm.Open(config.Type, config.ReadConnection)
Read.SingularTable(true)
Read.Callback().Create().Remove("gorm:update_time_stamp")
Read.Callback().Update().Remove("gorm:update_time_stamp")
} else { } else {
Read = Write Read = Write
} }
@ -36,9 +42,12 @@ func Open(c Config) (err error) {
func Close() { func Close() {
Write.Close() Write.Close()
Write = nil
if len(config.ReadConnection) > 0 { if len(config.ReadConnection) > 0 {
Read.Close() Read.Close()
} }
Read = nil
} }
func AddModel(m interface{}) { func AddModel(m interface{}) {

View File

@ -1 +1,73 @@
package database package database
import (
"testing"
"github.com/stretchr/testify/assert"
)
type TestModel struct {
ID int64
Value string `gorm:"type:varchar(255);column:value" json:"value"`
}
func TestOpenNoDB(t *testing.T) {
assert := assert.New(t)
c := Config{}
err := Open(c)
assert.Error(err, "error")
}
func TestOpenOneDB(t *testing.T) {
assert := assert.New(t)
AddModel(&TestModel{})
c := Config{
Type: "sqlite3",
Connection: "file:database?mode=memory",
}
var count int64
err := Open(c)
assert.NoError(err, "no error")
Write.LogMode(true)
Read.LogMode(true)
Write.Create(&TestModel{Value: "first"})
Write.Create(&TestModel{Value: "secound"})
var list []*TestModel
Read.Find(&list).Count(&count)
assert.Equal(int64(2), count, "not enought entries")
Close()
}
func TestOpenTwoDB(t *testing.T) {
assert := assert.New(t)
AddModel(&TestModel{})
c := Config{
Type: "sqlite3",
Connection: "file:database?mode=memory",
ReadConnection: "file:database2?mode=memory",
}
var count int64
err := Open(c)
assert.NoError(err, "no error")
Write.LogMode(true)
Read.LogMode(true)
Write.Create(&TestModel{Value: "first"})
Write.Create(&TestModel{Value: "secound"})
var list []*TestModel
Write.Find(&list).Count(&count)
assert.Equal(int64(2), count, "not enought entries")
result := Read.Find(&list)
assert.Error(result.Error, "error, because it is the wrong database")
Close()
}