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 {
|
|
|
|
Name string
|
|
|
|
}
|
|
|
|
|
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 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)
|
2013-10-26 11:02:14 +04:00
|
|
|
if user.Name != "jinzhu" {
|
|
|
|
t.Errorf("Should found out user with name 'jinzhu'")
|
|
|
|
}
|
2013-10-26 10:10:47 +04:00
|
|
|
|
2013-10-26 11:02:14 +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
|
|
|
}
|