OSDN Git Service

feat: init cross_tx keepers (#146)
[bytom/vapor.git] / vendor / github.com / jinzhu / gorm / create_test.go
1 package gorm_test
2
3 import (
4         "os"
5         "reflect"
6         "testing"
7         "time"
8
9         "github.com/jinzhu/now"
10 )
11
12 func TestCreate(t *testing.T) {
13         float := 35.03554004971999
14         now := time.Now()
15         user := User{Name: "CreateUser", Age: 18, Birthday: &now, UserNum: Num(111), PasswordHash: []byte{'f', 'a', 'k', '4'}, Latitude: float}
16
17         if !DB.NewRecord(user) || !DB.NewRecord(&user) {
18                 t.Error("User should be new record before create")
19         }
20
21         if count := DB.Save(&user).RowsAffected; count != 1 {
22                 t.Error("There should be one record be affected when create record")
23         }
24
25         if DB.NewRecord(user) || DB.NewRecord(&user) {
26                 t.Error("User should not new record after save")
27         }
28
29         var newUser User
30         if err := DB.First(&newUser, user.Id).Error; err != nil {
31                 t.Errorf("No error should happen, but got %v", err)
32         }
33
34         if !reflect.DeepEqual(newUser.PasswordHash, []byte{'f', 'a', 'k', '4'}) {
35                 t.Errorf("User's PasswordHash should be saved ([]byte)")
36         }
37
38         if newUser.Age != 18 {
39                 t.Errorf("User's Age should be saved (int)")
40         }
41
42         if newUser.UserNum != Num(111) {
43                 t.Errorf("User's UserNum should be saved (custom type), but got %v", newUser.UserNum)
44         }
45
46         if newUser.Latitude != float {
47                 t.Errorf("Float64 should not be changed after save")
48         }
49
50         if user.CreatedAt.IsZero() {
51                 t.Errorf("Should have created_at after create")
52         }
53
54         if newUser.CreatedAt.IsZero() {
55                 t.Errorf("Should have created_at after create")
56         }
57
58         DB.Model(user).Update("name", "create_user_new_name")
59         DB.First(&user, user.Id)
60         if user.CreatedAt.Format(time.RFC3339Nano) != newUser.CreatedAt.Format(time.RFC3339Nano) {
61                 t.Errorf("CreatedAt should not be changed after update")
62         }
63 }
64
65 func TestCreateEmptyStrut(t *testing.T) {
66         type EmptyStruct struct {
67                 ID uint
68         }
69         DB.AutoMigrate(&EmptyStruct{})
70
71         if err := DB.Create(&EmptyStruct{}).Error; err != nil {
72                 t.Errorf("No error should happen when creating user, but got %v", err)
73         }
74 }
75
76 func TestCreateWithExistingTimestamp(t *testing.T) {
77         user := User{Name: "CreateUserExistingTimestamp"}
78
79         timeA := now.MustParse("2016-01-01")
80         user.CreatedAt = timeA
81         user.UpdatedAt = timeA
82         DB.Save(&user)
83
84         if user.CreatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
85                 t.Errorf("CreatedAt should not be changed")
86         }
87
88         if user.UpdatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
89                 t.Errorf("UpdatedAt should not be changed")
90         }
91
92         var newUser User
93         DB.First(&newUser, user.Id)
94
95         if newUser.CreatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
96                 t.Errorf("CreatedAt should not be changed")
97         }
98
99         if newUser.UpdatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
100                 t.Errorf("UpdatedAt should not be changed")
101         }
102 }
103
104 type AutoIncrementUser struct {
105         User
106         Sequence uint `gorm:"AUTO_INCREMENT"`
107 }
108
109 func TestCreateWithAutoIncrement(t *testing.T) {
110         if dialect := os.Getenv("GORM_DIALECT"); dialect != "postgres" {
111                 t.Skip("Skipping this because only postgres properly support auto_increment on a non-primary_key column")
112         }
113
114         DB.AutoMigrate(&AutoIncrementUser{})
115
116         user1 := AutoIncrementUser{}
117         user2 := AutoIncrementUser{}
118
119         DB.Create(&user1)
120         DB.Create(&user2)
121
122         if user2.Sequence-user1.Sequence != 1 {
123                 t.Errorf("Auto increment should apply on Sequence")
124         }
125 }
126
127 func TestCreateWithNoGORMPrimayKey(t *testing.T) {
128         if dialect := os.Getenv("GORM_DIALECT"); dialect == "mssql" {
129                 t.Skip("Skipping this because MSSQL will return identity only if the table has an Id column")
130         }
131
132         jt := JoinTable{From: 1, To: 2}
133         err := DB.Create(&jt).Error
134         if err != nil {
135                 t.Errorf("No error should happen when create a record without a GORM primary key. But in the database this primary key exists and is the union of 2 or more fields\n But got: %s", err)
136         }
137 }
138
139 func TestCreateWithNoStdPrimaryKeyAndDefaultValues(t *testing.T) {
140         animal := Animal{Name: "Ferdinand"}
141         if DB.Save(&animal).Error != nil {
142                 t.Errorf("No error should happen when create a record without std primary key")
143         }
144
145         if animal.Counter == 0 {
146                 t.Errorf("No std primary key should be filled value after create")
147         }
148
149         if animal.Name != "Ferdinand" {
150                 t.Errorf("Default value should be overrided")
151         }
152
153         // Test create with default value not overrided
154         an := Animal{From: "nerdz"}
155
156         if DB.Save(&an).Error != nil {
157                 t.Errorf("No error should happen when create an record without std primary key")
158         }
159
160         // We must fetch the value again, to have the default fields updated
161         // (We can't do this in the update statements, since sql default can be expressions
162         // And be different from the fields' type (eg. a time.Time fields has a default value of "now()"
163         DB.Model(Animal{}).Where(&Animal{Counter: an.Counter}).First(&an)
164
165         if an.Name != "galeone" {
166                 t.Errorf("Default value should fill the field. But got %v", an.Name)
167         }
168 }
169
170 func TestAnonymousScanner(t *testing.T) {
171         user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}}
172         DB.Save(&user)
173
174         var user2 User
175         DB.First(&user2, "name = ?", "anonymous_scanner")
176         if user2.Role.Name != "admin" {
177                 t.Errorf("Should be able to get anonymous scanner")
178         }
179
180         if !user2.Role.IsAdmin() {
181                 t.Errorf("Should be able to get anonymous scanner")
182         }
183 }
184
185 func TestAnonymousField(t *testing.T) {
186         user := User{Name: "anonymous_field", Company: Company{Name: "company"}}
187         DB.Save(&user)
188
189         var user2 User
190         DB.First(&user2, "name = ?", "anonymous_field")
191         DB.Model(&user2).Related(&user2.Company)
192         if user2.Company.Name != "company" {
193                 t.Errorf("Should be able to get anonymous field")
194         }
195 }
196
197 func TestSelectWithCreate(t *testing.T) {
198         user := getPreparedUser("select_user", "select_with_create")
199         DB.Select("Name", "BillingAddress", "CreditCard", "Company", "Emails").Create(user)
200
201         var queryuser User
202         DB.Preload("BillingAddress").Preload("ShippingAddress").
203                 Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryuser, user.Id)
204
205         if queryuser.Name != user.Name || queryuser.Age == user.Age {
206                 t.Errorf("Should only create users with name column")
207         }
208
209         if queryuser.BillingAddressID.Int64 == 0 || queryuser.ShippingAddressId != 0 ||
210                 queryuser.CreditCard.ID == 0 || len(queryuser.Emails) == 0 {
211                 t.Errorf("Should only create selected relationships")
212         }
213 }
214
215 func TestOmitWithCreate(t *testing.T) {
216         user := getPreparedUser("omit_user", "omit_with_create")
217         DB.Omit("Name", "BillingAddress", "CreditCard", "Company", "Emails").Create(user)
218
219         var queryuser User
220         DB.Preload("BillingAddress").Preload("ShippingAddress").
221                 Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryuser, user.Id)
222
223         if queryuser.Name == user.Name || queryuser.Age != user.Age {
224                 t.Errorf("Should only create users with age column")
225         }
226
227         if queryuser.BillingAddressID.Int64 != 0 || queryuser.ShippingAddressId == 0 ||
228                 queryuser.CreditCard.ID != 0 || len(queryuser.Emails) != 0 {
229                 t.Errorf("Should not create omitted relationships")
230         }
231 }