Add tests package

This commit is contained in:
Jinzhu 2018-03-18 21:39:58 +08:00
parent 7065ea8c97
commit 7ee0af3283
3 changed files with 78 additions and 26 deletions

View File

@ -4,10 +4,10 @@ import (
"fmt"
"os"
"path/filepath"
"reflect"
"testing"
"github.com/jinzhu/gorm"
"github.com/jinzhu/gorm/tests"
)
var DB *gorm.DB
@ -20,29 +20,6 @@ func init() {
}
}
func TestBatchInsert(t *testing.T) {
type User struct {
gorm.Model
Name string
Age int
}
users := []*User{{Name: "name1", Age: 10}, {Name: "name2", Age: 20}, {Name: "name3", Age: 30}}
DB.Create(users)
for _, user := range users {
if user.ID == 0 {
t.Errorf("User should have primary key")
}
var newUser User
if err := DB.Find(&newUser, "id = ?", user.ID).Error; err != nil {
t.Error(err)
}
if !reflect.DeepEqual(&newUser, user) {
t.Errorf("User should be equal, but got %#v, should be %#v", newUser, user)
}
}
func TestAll(t *testing.T) {
tests.RunCreateSuit(DB, t)
}

62
tests/create.go Normal file
View File

@ -0,0 +1,62 @@
package tests
import (
"reflect"
"testing"
"github.com/jinzhu/gorm"
)
// RunCreateSuit run create suit
func RunCreateSuit(db *gorm.DB, t *testing.T) {
testInsert(db, t, FormatWithMsg("Insert"))
testBatchInsert(db, t, FormatWithMsg("BatchInsert"))
}
func testInsert(db *gorm.DB, t *testing.T, format Format) {
type User struct {
gorm.Model
Name string
Age int
}
user := User{Name: "name1", Age: 10}
db.Create(&user)
var newUser User
if err := db.Find(&newUser, "id = ?", user.ID).Error; err != nil {
t.Error(format(err))
}
if !reflect.DeepEqual(newUser, user) {
t.Error(format("User should be equal, but got %#v, should be %#v", newUser, user))
}
}
func testBatchInsert(db *gorm.DB, t *testing.T, format Format) {
type User struct {
gorm.Model
Name string
Age int
}
users := []*User{{Name: "name1", Age: 10}, {Name: "name2", Age: 20}, {Name: "name3", Age: 30}}
db.Create(users)
for _, user := range users {
if user.ID == 0 {
t.Error(format("User should have primary key"))
}
var newUser User
if err := db.Find(&newUser, "id = ?", user.ID).Error; err != nil {
t.Error(format(err))
}
if !reflect.DeepEqual(&newUser, user) {
t.Errorf(format("User should be equal, but got %#v, should be %#v", newUser, user))
}
}
}

13
tests/utils.go Normal file
View File

@ -0,0 +1,13 @@
package tests
import "fmt"
// Format format test message
type Format func(value interface{}, args ...interface{}) string
// FormatWithMsg format test messages
func FormatWithMsg(msg string) Format {
return func(value interface{}, args ...interface{}) string {
return fmt.Sprintf("[%v] %v", msg, fmt.Sprintf(fmt.Sprint(value), args...))
}
}