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

Function TestSetColumn

tests/hooks_test.go:325–407  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

323}
324
325func TestSetColumn(t *testing.T) {
326 DB.Migrator().DropTable(&Product3{})
327 DB.AutoMigrate(&Product3{})
328
329 product := Product3{Name: "Product", Price: 0}
330 DB.Create(&product)
331
332 if product.Price != 100 {
333 t.Errorf("invalid price after create, got %+v", product)
334 }
335
336 DB.Model(&product).Select("code", "price").Updates(map[string]interface{}{"code": "L1212"})
337
338 if product.Price != 150 || product.Code != "L1212" {
339 t.Errorf("invalid data after update, got %+v", product)
340 }
341
342 // Code not changed, price should not change
343 DB.Model(&product).Updates(map[string]interface{}{"Name": "Product New"})
344
345 if product.Name != "Product New" || product.Price != 160 || product.Code != "L1212" {
346 t.Errorf("invalid data after update, got %+v", product)
347 }
348
349 // Code changed, but not selected, price should not change
350 DB.Model(&product).Select("Name", "Price").Updates(map[string]interface{}{"Name": "Product New2", "code": "L1213"})
351
352 if product.Name != "Product New2" || product.Price != 170 || product.Code != "L1212" {
353 t.Errorf("invalid data after update, got %+v", product)
354 }
355
356 // Code changed, price should changed
357 DB.Model(&product).Select("Name", "Code", "Price").Updates(map[string]interface{}{"Name": "Product New3", "code": "L1213"})
358
359 if product.Name != "Product New3" || product.Price != 220 || product.Code != "L1213" {
360 t.Errorf("invalid data after update, got %+v", product)
361 }
362
363 var result Product3
364 DB.First(&result, product.ID)
365
366 AssertEqual(t, result, product)
367
368 // Select to change Code, but nothing updated, price should not change
369 DB.Model(&product).Select("code").Updates(Product3{Name: "L1214", Code: "L1213"})
370
371 if product.Price != 220 || product.Code != "L1213" || product.Name != "Product New3" {
372 t.Errorf("invalid data after update, got %+v", product)
373 }
374
375 DB.Model(&product).Updates(Product3{Code: "L1214"})
376 if product.Price != 270 || product.Code != "L1214" {
377 t.Errorf("invalid data after update, got %+v", product)
378 }
379
380 // Code changed, price should changed
381 DB.Model(&product).Select("Name", "Code", "Price").Updates(Product3{Name: "Product New4", Code: ""})
382 if product.Name != "Product New4" || product.Price != 320 || product.Code != "" {

Callers

nothing calls this directly

Calls 11

ModelMethod · 0.80
UpdateColumnsMethod · 0.80
SessionMethod · 0.80
DropTableMethod · 0.65
MigratorMethod · 0.65
AutoMigrateMethod · 0.65
CreateMethod · 0.65
UpdatesMethod · 0.65
SelectMethod · 0.65
FirstMethod · 0.65
AssertEqualFunction · 0.50

Tested by

no test coverage detected