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

Function TestFindOrInitialize

tests/upsert_test.go:247–292  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

245}
246
247func TestFindOrInitialize(t *testing.T) {
248 var user1, user2, user3, user4, user5, user6 User
249 if err := DB.Where(&User{Name: "find or init", Age: 33}).FirstOrInit(&user1).Error; err != nil {
250 t.Errorf("no error should happen when FirstOrInit, but got %v", err)
251 }
252
253 if user1.Name != "find or init" || user1.ID != 0 || user1.Age != 33 {
254 t.Errorf("user should be initialized with search value")
255 }
256
257 DB.Where(User{Name: "find or init", Age: 33}).FirstOrInit(&user2)
258 if user2.Name != "find or init" || user2.ID != 0 || user2.Age != 33 {
259 t.Errorf("user should be initialized with search value")
260 }
261
262 DB.FirstOrInit(&user3, map[string]interface{}{"name": "find or init 2"})
263 if user3.Name != "find or init 2" || user3.ID != 0 {
264 t.Errorf("user should be initialized with inline search value")
265 }
266
267 DB.Where(&User{Name: "find or init"}).Attrs(User{Age: 44}).FirstOrInit(&user4)
268 if user4.Name != "find or init" || user4.ID != 0 || user4.Age != 44 {
269 t.Errorf("user should be initialized with search value and attrs")
270 }
271
272 DB.Where(&User{Name: "find or init"}).Assign("age", 44).FirstOrInit(&user4)
273 if user4.Name != "find or init" || user4.ID != 0 || user4.Age != 44 {
274 t.Errorf("user should be initialized with search value and assign attrs")
275 }
276
277 DB.Save(&User{Name: "find or init", Age: 33})
278 DB.Where(&User{Name: "find or init"}).Attrs("age", 44).FirstOrInit(&user5)
279 if user5.Name != "find or init" || user5.ID == 0 || user5.Age != 33 {
280 t.Errorf("user should be found and not initialized by Attrs")
281 }
282
283 DB.Where(&User{Name: "find or init", Age: 33}).FirstOrInit(&user6)
284 if user6.Name != "find or init" || user6.ID == 0 || user6.Age != 33 {
285 t.Errorf("user should be found with FirstOrInit")
286 }
287
288 DB.Where(&User{Name: "find or init"}).Assign(User{Age: 44}).FirstOrInit(&user6)
289 if user6.Name != "find or init" || user6.ID == 0 || user6.Age != 44 {
290 t.Errorf("user should be found and updated with assigned attrs")
291 }
292}
293
294func TestFindOrCreate(t *testing.T) {
295 var user1, user2, user3, user4, user5, user6, user7, user8 User

Callers

nothing calls this directly

Calls 5

FirstOrInitMethod · 0.80
AttrsMethod · 0.80
AssignMethod · 0.80
SaveMethod · 0.80
WhereMethod · 0.65

Tested by

no test coverage detected