MCPcopy
hub / github.com/go-gorm/gorm / TestUpdates

Function TestUpdates

tests/update_test.go:135–186  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

133}
134
135func TestUpdates(t *testing.T) {
136 users := []*User{
137 GetUser("updates_01", Config{}),
138 GetUser("updates_02", Config{}),
139 }
140
141 DB.Create(&users)
142 lastUpdatedAt := users[0].UpdatedAt
143
144 // update with map
145 if res := DB.Model(users[0]).Updates(map[string]interface{}{"name": "updates_01_newname", "age": 100}); res.Error != nil || res.RowsAffected != 1 {
146 t.Errorf("Failed to update users")
147 }
148
149 if users[0].Name != "updates_01_newname" || users[0].Age != 100 {
150 t.Errorf("Record should be updated also with map")
151 }
152
153 if users[0].UpdatedAt.UnixNano() == lastUpdatedAt.UnixNano() {
154 t.Errorf("User's updated at should be changed, but got %v, was %v", users[0].UpdatedAt.UnixNano(), lastUpdatedAt)
155 }
156
157 // user2 should not be updated
158 var user1, user2 User
159 DB.First(&user1, users[0].ID)
160 DB.First(&user2, users[1].ID)
161 CheckUser(t, user1, *users[0])
162 CheckUser(t, user2, *users[1])
163
164 // update with struct
165 time.Sleep(1 * time.Second)
166 DB.Table("users").Where("name in ?", []string{users[1].Name}).Updates(User{Name: "updates_02_newname"})
167
168 var user3 User
169 if err := DB.First(&user3, "name = ?", "updates_02_newname").Error; err != nil {
170 t.Errorf("User2's name should be updated")
171 }
172
173 if user2.UpdatedAt.Format(time.RFC1123Z) == user3.UpdatedAt.Format(time.RFC1123Z) {
174 t.Errorf("User's updated at should be changed, old %v, new %v", user2.UpdatedAt.Format(time.RFC1123Z), user3.UpdatedAt.Format(time.RFC1123Z))
175 }
176
177 // update with gorm exprs
178 if err := DB.Model(&user3).Updates(map[string]interface{}{"age": gorm.Expr("age + ?", 100)}).Error; err != nil {
179 t.Errorf("Not error should happen when updating with gorm expr, but got %v", err)
180 }
181 var user4 User
182 DB.First(&user4, user3.ID)
183
184 user3.Age += 100
185 AssertObjEqual(t, user4, user3, "UpdatedAt", "Age")
186}
187
188func TestUpdateColumn(t *testing.T) {
189 users := []*User{

Callers

nothing calls this directly

Calls 10

ExprFunction · 0.92
GetUserFunction · 0.85
CheckUserFunction · 0.85
AssertObjEqualFunction · 0.85
ModelMethod · 0.80
CreateMethod · 0.65
UpdatesMethod · 0.65
FirstMethod · 0.65
WhereMethod · 0.65
TableMethod · 0.65

Tested by

no test coverage detected