Debian Codegraph @

tests/non_std_test.go

raw
1 package tests_test
2
3 import (
4 "testing"
5 "time"
6 )
7
8 type Animal struct {
9 Counter uint64 `gorm:"primary_key:yes"`
10 Name string `gorm:"DEFAULT:'galeone'"`
11 From string // test reserved sql keyword as field name
12 Age *time.Time
13 unexported string // unexported value
14 CreatedAt time.Time
15 UpdatedAt time.Time
16 }
17
18 func TestNonStdPrimaryKeyAndDefaultValues(t *testing.T) {
19 DB.Migrator().DropTable(&Animal{})
20 if err := DB.AutoMigrate(&Animal{}); err != nil {
21 t.Fatalf("no error should happen when migrate but got %v", err)
22 }
23
24 animal := Animal{Name: "Ferdinand"}
25 DB.Save(&animal)
26 updatedAt1 := animal.UpdatedAt
27
28 DB.Save(&animal).Update("name", "Francis")
29 if updatedAt1.Format(time.RFC3339Nano) == animal.UpdatedAt.Format(time.RFC3339Nano) {
30 t.Errorf("UpdatedAt should be updated")
31 }
32
33 var animals []Animal
34 DB.Find(&animals)
35 if count := DB.Model(Animal{}).Where("1=1").Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(animals)) {
36 t.Error("RowsAffected should be correct when do batch update")
37 }
38
39 animal = Animal{From: "somewhere"} // No name fields, should be filled with the default value (galeone)
40 DB.Save(&animal).Update("From", "a nice place") // The name field should be untouched
41 DB.First(&animal, animal.Counter)
42 if animal.Name != "galeone" {
43 t.Errorf("Name fields shouldn't be changed if untouched, but got %v", animal.Name)
44 }
45
46 // When changing a field with a default value, the change must occur
47 animal.Name = "amazing horse"
48 DB.Save(&animal)
49 DB.First(&animal, animal.Counter)
50 if animal.Name != "amazing horse" {
51 t.Errorf("Update a filed with a default value should occur. But got %v\n", animal.Name)
52 }
53
54 // When changing a field with a default value with blank value
55 animal.Name = ""
56 DB.Save(&animal)
57 DB.First(&animal, animal.Counter)
58 if animal.Name != "" {
59 t.Errorf("Update a filed to blank with a default value should occur. But got %v\n", animal.Name)
60 }
61 }