gorm/embedded_struct_test.go

39 lines
1.0 KiB
Go
Raw Normal View History

2014-08-28 11:33:43 +04:00
package gorm_test
import "testing"
type BasePost struct {
2014-08-28 14:53:27 +04:00
Id int64
2014-08-28 11:33:43 +04:00
Title string
URL string
2014-08-28 11:33:43 +04:00
}
type HNPost struct {
2014-08-30 19:08:58 +04:00
BasePost
Upvotes int32
2014-08-28 11:33:43 +04:00
}
type EngadgetPost struct {
2014-08-28 15:14:58 +04:00
BasePost BasePost `gorm:"embedded"`
2014-08-28 11:33:43 +04:00
ImageUrl string
}
2014-08-28 13:21:43 +04:00
func TestSaveAndQueryEmbeddedStruct(t *testing.T) {
2014-08-28 15:14:58 +04:00
DB.Save(&HNPost{BasePost: BasePost{Title: "news"}})
2014-08-28 14:25:05 +04:00
DB.Save(&HNPost{BasePost: BasePost{Title: "hn_news"}})
2014-08-28 11:33:43 +04:00
var news HNPost
2014-08-28 13:21:43 +04:00
if err := DB.First(&news, "title = ?", "hn_news").Error; err != nil {
t.Errorf("no error should happen when query with embedded struct, but got %v", err)
} else if news.Title != "hn_news" {
t.Errorf("embedded struct's value should be scanned correctly")
2014-08-28 13:21:43 +04:00
}
2014-08-28 15:14:58 +04:00
DB.Save(&EngadgetPost{BasePost: BasePost{Title: "engadget_news"}})
var egNews EngadgetPost
if err := DB.First(&egNews, "title = ?", "engadget_news").Error; err != nil {
t.Errorf("no error should happen when query with embedded struct, but got %v", err)
} else if egNews.BasePost.Title != "engadget_news" {
t.Errorf("embedded struct's value should be scanned correctly")
2014-08-28 15:14:58 +04:00
}
2014-08-28 11:33:43 +04:00
}