gorm/orm_test.go

72 lines
1.5 KiB
Go
Raw Normal View History

2013-10-25 18:31:56 +04:00
package gorm
import "testing"
2013-10-25 18:31:56 +04:00
2013-10-26 03:14:57 +04:00
type User struct {
Name string
2013-10-26 13:28:52 +04:00
Id int64
2013-10-26 03:14:57 +04:00
}
2013-10-26 05:49:40 +04:00
func getDB() DB {
2013-10-26 11:47:30 +04:00
db, _ := Open("postgres", "user=gorm dbname=gorm sslmode=disable")
2013-10-26 05:49:40 +04:00
return db
}
func TestSaveAndFirst(t *testing.T) {
2013-10-26 07:48:07 +04:00
// create table "users" ("name" varchar(255));
2013-10-26 05:49:40 +04:00
db := getDB()
u := &User{Name: "jinzhu"}
2013-10-26 06:15:09 +04:00
db.Save(u)
2013-10-26 16:20:49 +04:00
if u.Id == 0 {
t.Errorf("Should have ID after create record")
}
2013-10-26 05:49:40 +04:00
user := &User{}
2013-10-26 07:48:07 +04:00
db.First(user)
2013-10-26 05:49:40 +04:00
if user.Name != "jinzhu" {
t.Errorf("User should be saved and fetched correctly")
2013-10-25 18:31:56 +04:00
}
2013-10-26 08:33:05 +04:00
users := []User{}
db.Find(&users)
for _, user := range users {
if user.Name != "jinzhu" {
t.Errorf("User should be saved and fetched correctly")
}
}
2013-10-26 05:49:40 +04:00
}
2013-10-26 03:14:57 +04:00
2013-10-26 05:49:40 +04:00
func TestWhere(t *testing.T) {
db := getDB()
2013-10-26 10:10:47 +04:00
u := &User{Name: "jinzhu"}
db.Save(u)
2013-10-26 03:14:57 +04:00
user := &User{}
2013-10-26 10:10:47 +04:00
db.Where("Name = ?", "jinzhu").First(user)
if user.Name != "jinzhu" {
t.Errorf("Should found out user with name 'jinzhu'")
}
2013-10-26 10:10:47 +04:00
user = &User{}
orm := db.Where("Name = ?", "jinzhu-noexisting").First(user)
if orm.Error == nil {
t.Errorf("Should return error when looking for unexist record, %+v", user)
}
users := &[]User{}
orm = db.Where("Name = ?", "jinzhu-noexisting").First(users)
if orm.Error != nil {
t.Errorf("Shouldn't return error when looking for unexist records, %+v", users)
}
2013-10-25 18:31:56 +04:00
}
2013-10-26 13:28:52 +04:00
func TestCreateTable(t *testing.T) {
db := getDB()
db.Exec("drop table users;")
orm := db.CreateTable(&User{})
if orm.Error != nil {
t.Errorf("No error should raise when create table, but got %+v", orm.Error)
}
}