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

Function TestFind

tests/query_test.go:20–248  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

18)
19
20func TestFind(t *testing.T) {
21 users := []User{
22 *GetUser("find", Config{}),
23 *GetUser("find", Config{}),
24 *GetUser("find", Config{}),
25 }
26
27 if err := DB.Create(&users).Error; err != nil {
28 t.Fatalf("errors happened when create users: %v", err)
29 }
30
31 t.Run("First", func(t *testing.T) {
32 var first User
33 if err := DB.Where("name = ?", "find").First(&first).Error; err != nil {
34 t.Errorf("errors happened when query first: %v", err)
35 } else {
36 CheckUser(t, first, users[0])
37 }
38 })
39
40 t.Run("Last", func(t *testing.T) {
41 var last User
42 if err := DB.Where("name = ?", "find").Last(&last).Error; err != nil {
43 t.Errorf("errors happened when query last: %v", err)
44 } else {
45 CheckUser(t, last, users[2])
46 }
47 })
48
49 var all []User
50 if err := DB.Where("name = ?", "find").Find(&all).Error; err != nil || len(all) != 3 {
51 t.Errorf("errors happened when query find: %v, length: %v", err, len(all))
52 } else {
53 for idx, user := range users {
54 t.Run("FindAll#"+strconv.Itoa(idx+1), func(t *testing.T) {
55 CheckUser(t, all[idx], user)
56 })
57 }
58 }
59
60 t.Run("FirstMap", func(t *testing.T) {
61 first := map[string]interface{}{}
62 if err := DB.Model(&User{}).Where("name = ?", "find").First(first).Error; err != nil {
63 t.Errorf("errors happened when query first: %v", err)
64 } else {
65 for _, name := range []string{"Name", "Age", "Birthday"} {
66 t.Run(name, func(t *testing.T) {
67 dbName := DB.NamingStrategy.ColumnName("", name)
68
69 switch name {
70 case "Name":
71 if _, ok := first[dbName].(string); !ok {
72 t.Errorf("invalid data type for %v, got %#v", dbName, first[dbName])
73 }
74 case "Age":
75 if _, ok := first[dbName].(uint); !ok {
76 t.Errorf("invalid data type for %v, got %#v", dbName, first[dbName])
77 }

Callers

nothing calls this directly

Calls 14

GetUserFunction · 0.85
CheckUserFunction · 0.85
ModelMethod · 0.80
ContainsMethod · 0.80
CreateMethod · 0.65
FirstMethod · 0.65
WhereMethod · 0.65
LastMethod · 0.65
FindMethod · 0.65
ColumnNameMethod · 0.65
TableMethod · 0.65
NameMethod · 0.65

Tested by

no test coverage detected