gorm/embedded_struct_test.go

49 lines
1.3 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
}
2015-02-25 05:56:05 +03:00
2015-03-11 06:28:30 +03:00
if DB.NewScope(&HNPost{}).PrimaryField() == nil {
2015-02-25 05:56:05 +03:00
t.Errorf("primary key with embedded struct should works")
}
2015-02-25 06:17:33 +03:00
for _, field := range DB.NewScope(&HNPost{}).Fields() {
if field.Name == "BasePost" {
t.Errorf("scope Fields should not contain embedded struct")
}
}
2014-08-28 11:33:43 +04:00
}