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

Function TestScopes

tests/scopes_test.go:25–74  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

23}
24
25func TestScopes(t *testing.T) {
26 users := []*User{
27 GetUser("ScopeUser1", Config{}),
28 GetUser("ScopeUser2", Config{}),
29 GetUser("ScopeUser3", Config{}),
30 }
31
32 DB.Create(&users)
33
34 var users1, users2, users3 []User
35 DB.Scopes(NameIn1And2).Find(&users1)
36 if len(users1) != 2 {
37 t.Errorf("Should found two users's name in 1, 2, but got %v", len(users1))
38 }
39
40 DB.Scopes(NameIn1And2, NameIn2And3).Find(&users2)
41 if len(users2) != 1 {
42 t.Errorf("Should found one user's name is 2, but got %v", len(users2))
43 }
44
45 DB.Scopes(NameIn([]string{users[0].Name, users[2].Name})).Find(&users3)
46 if len(users3) != 2 {
47 t.Errorf("Should found two users's name in 1, 3, but got %v", len(users3))
48 }
49
50 db := DB.Scopes(func(tx *gorm.DB) *gorm.DB {
51 return tx.Table("custom_table")
52 }).Session(&gorm.Session{})
53
54 db.AutoMigrate(&User{})
55 if db.Find(&User{}).Statement.Table != "custom_table" {
56 t.Errorf("failed to call Scopes")
57 }
58
59 result := DB.Scopes(NameIn1And2, func(tx *gorm.DB) *gorm.DB {
60 return tx.Session(&gorm.Session{})
61 }).Find(&users1)
62
63 if result.RowsAffected != 2 {
64 t.Errorf("Should found two users's name in 1, 2, but got %v", result.RowsAffected)
65 }
66
67 var maxId int64
68 userTable := func(db *gorm.DB) *gorm.DB {
69 return db.WithContext(context.Background()).Table("users")
70 }
71 if err := DB.Scopes(userTable).Select("max(id)").Scan(&maxId).Error; err != nil {
72 t.Errorf("select max(id)")
73 }
74}
75
76func TestComplexScopes(t *testing.T) {
77 tests := []struct {

Callers

nothing calls this directly

Calls 11

GetUserFunction · 0.85
NameInFunction · 0.85
SessionMethod · 0.80
WithContextMethod · 0.80
CreateMethod · 0.65
FindMethod · 0.65
ScopesMethod · 0.65
TableMethod · 0.65
AutoMigrateMethod · 0.65
ScanMethod · 0.65
SelectMethod · 0.65

Tested by

no test coverage detected