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

Function TestCount

tests/count_test.go:39–190  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

37}
38
39func TestCount(t *testing.T) {
40 var (
41 user1 = *GetUser("count-1", Config{})
42 user2 = *GetUser("count-2", Config{})
43 user3 = *GetUser("count-3", Config{})
44 users []User
45 count, count1, count2 int64
46 )
47
48 DB.Save(&user1).Save(&user2).Save(&user3)
49
50 if err := DB.Where("name = ?", user1.Name).Or("name = ?", user3.Name).Find(&users).Count(&count).Error; err != nil {
51 t.Errorf("Count should work, but got err %v", err)
52 }
53
54 if count != int64(len(users)) {
55 t.Errorf("Count() method should get correct value, expect: %v, got %v", count, len(users))
56 }
57
58 if err := DB.Model(&User{}).Where("name = ?", user1.Name).Or("name = ?", user3.Name).Count(&count).Find(&users).Error; err != nil {
59 t.Errorf("Count should work, but got err %v", err)
60 }
61
62 if count != int64(len(users)) {
63 t.Errorf("Count() method should get correct value, expect: %v, got %v", count, len(users))
64 }
65
66 DB.Model(&User{}).Where("name = ?", user1.Name).Count(&count1).Or("name in ?", []string{user2.Name, user3.Name}).Count(&count2)
67 if count1 != 1 || count2 != 3 {
68 t.Errorf("multiple count in chain should works")
69 }
70
71 tx := DB.Model(&User{}).Where("name = ?", user1.Name).Session(&gorm.Session{})
72 tx.Count(&count1)
73 tx.Or("name in ?", []string{user2.Name, user3.Name}).Count(&count2)
74 if count1 != 1 || count2 != 3 {
75 t.Errorf("count after new session should works")
76 }
77
78 var count3 int64
79 if err := DB.Model(&User{}).Where("name in ?", []string{user2.Name, user2.Name, user3.Name}).Group("id").Count(&count3).Error; err != nil {
80 t.Errorf("Error happened when count with group, but got %v", err)
81 }
82
83 if count3 != 2 {
84 t.Errorf("Should get correct count for count with group, but got %v", count3)
85 }
86
87 dryDB := DB.Session(&gorm.Session{DryRun: true})
88 result := dryDB.Table("users").Select("name").Count(&count)
89 if !regexp.MustCompile(`SELECT COUNT\(.name.\) FROM .*users.*`).MatchString(result.Statement.SQL.String()) {
90 t.Fatalf("Build count with select, but got %v", result.Statement.SQL.String())
91 }
92
93 result = dryDB.Table("users").Distinct("name").Count(&count)
94 if !regexp.MustCompile(`SELECT COUNT\(DISTINCT\(.name.\)\) FROM .*users.*`).MatchString(result.Statement.SQL.String()) {
95 t.Fatalf("Build count with select, but got %v", result.Statement.SQL.String())
96 }

Callers

nothing calls this directly

Calls 15

GetUserFunction · 0.85
SaveMethod · 0.80
ModelMethod · 0.80
SessionMethod · 0.80
CountMethod · 0.65
FindMethod · 0.65
OrMethod · 0.65
WhereMethod · 0.65
GroupMethod · 0.65
SelectMethod · 0.65
TableMethod · 0.65
DistinctMethod · 0.65

Tested by

no test coverage detected