2013-10-25 18:31:56 +04:00
|
|
|
package gorm
|
|
|
|
|
2013-10-26 11:02:14 +04:00
|
|
|
import "testing"
|
2013-10-25 18:31:56 +04:00
|
|
|
|
2013-10-26 03:14:57 +04:00
|
|
|
type User struct {
|
2013-10-26 13:28:52 +04:00
|
|
|
Id int64
|
2013-10-26 17:05:54 +04:00
|
|
|
Name string
|
|
|
|
}
|
|
|
|
|
|
|
|
var db DB
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
db, _ = Open("postgres", "user=gorm dbname=gorm sslmode=disable")
|
|
|
|
db.Exec("drop table users;")
|
2013-10-26 03:14:57 +04:00
|
|
|
}
|
|
|
|
|
2013-10-26 17:05:54 +04:00
|
|
|
func TestCreateTable(t *testing.T) {
|
|
|
|
orm := db.CreateTable(&User{})
|
|
|
|
if orm.Error != nil {
|
|
|
|
t.Errorf("No error should raise when create table, but got %+v", orm.Error)
|
|
|
|
}
|
2013-10-26 05:49:40 +04:00
|
|
|
}
|
|
|
|
|
2013-10-26 17:05:54 +04:00
|
|
|
func TestSaveAndFind(t *testing.T) {
|
|
|
|
name := "save_and_find"
|
|
|
|
u := &User{Name: name}
|
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 17:05:54 +04:00
|
|
|
if user.Name != name {
|
2013-10-26 05:49:40 +04:00
|
|
|
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)
|
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) {
|
2013-10-26 17:05:54 +04:00
|
|
|
name := "where"
|
|
|
|
db.Save(&User{Name: name})
|
2013-10-26 10:10:47 +04:00
|
|
|
|
2013-10-26 03:14:57 +04:00
|
|
|
user := &User{}
|
2013-10-26 17:05:54 +04:00
|
|
|
db.Where("Name = ?", name).First(user)
|
|
|
|
if user.Name != name {
|
|
|
|
t.Errorf("Should found out user with name '%v'", name)
|
2013-10-26 11:02:14 +04:00
|
|
|
}
|
2013-10-26 10:10:47 +04:00
|
|
|
|
2013-10-26 11:02:14 +04:00
|
|
|
user = &User{}
|
2013-10-26 17:05:54 +04:00
|
|
|
orm := db.Where("Name = ?", "noexisting-user").First(user)
|
2013-10-26 11:02:14 +04:00
|
|
|
if orm.Error == nil {
|
2013-10-26 17:05:54 +04:00
|
|
|
t.Errorf("Should return error when looking for none existing record, %+v", user)
|
2013-10-26 11:02:14 +04:00
|
|
|
}
|
|
|
|
|
2013-10-26 17:05:54 +04:00
|
|
|
users := []User{}
|
|
|
|
orm = db.Where("Name = ?", "none-noexisting").Find(&users)
|
2013-10-26 11:02:14 +04:00
|
|
|
if orm.Error != nil {
|
2013-10-26 17:05:54 +04:00
|
|
|
t.Errorf("Shouldn't return error when looking for none existing records, %+v", users)
|
2013-10-26 11:02:14 +04:00
|
|
|
}
|
2013-10-26 17:05:54 +04:00
|
|
|
if len(users) != 0 {
|
|
|
|
t.Errorf("Shouldn't find anything when looking for none existing records, %+v", users)
|
2013-10-26 13:28:52 +04:00
|
|
|
}
|
|
|
|
}
|