OSDN Git Service

feat: init cross_tx keepers (#146)
[bytom/vapor.git] / vendor / github.com / jinzhu / gorm / scope_test.go
1 package gorm_test
2
3 import (
4         "encoding/hex"
5         "math/rand"
6         "strings"
7         "testing"
8
9         "github.com/jinzhu/gorm"
10 )
11
12 func NameIn1And2(d *gorm.DB) *gorm.DB {
13         return d.Where("name in (?)", []string{"ScopeUser1", "ScopeUser2"})
14 }
15
16 func NameIn2And3(d *gorm.DB) *gorm.DB {
17         return d.Where("name in (?)", []string{"ScopeUser2", "ScopeUser3"})
18 }
19
20 func NameIn(names []string) func(d *gorm.DB) *gorm.DB {
21         return func(d *gorm.DB) *gorm.DB {
22                 return d.Where("name in (?)", names)
23         }
24 }
25
26 func TestScopes(t *testing.T) {
27         user1 := User{Name: "ScopeUser1", Age: 1}
28         user2 := User{Name: "ScopeUser2", Age: 1}
29         user3 := User{Name: "ScopeUser3", Age: 2}
30         DB.Save(&user1).Save(&user2).Save(&user3)
31
32         var users1, users2, users3 []User
33         DB.Scopes(NameIn1And2).Find(&users1)
34         if len(users1) != 2 {
35                 t.Errorf("Should found two users's name in 1, 2")
36         }
37
38         DB.Scopes(NameIn1And2, NameIn2And3).Find(&users2)
39         if len(users2) != 1 {
40                 t.Errorf("Should found one user's name is 2")
41         }
42
43         DB.Scopes(NameIn([]string{user1.Name, user3.Name})).Find(&users3)
44         if len(users3) != 2 {
45                 t.Errorf("Should found two users's name in 1, 3")
46         }
47 }
48
49 func randName() string {
50         data := make([]byte, 8)
51         rand.Read(data)
52
53         return "n-" + hex.EncodeToString(data)
54 }
55
56 func TestValuer(t *testing.T) {
57         name := randName()
58
59         origUser := User{Name: name, Age: 1, Password: EncryptedData("pass1"), PasswordHash: []byte("abc")}
60         if err := DB.Save(&origUser).Error; err != nil {
61                 t.Errorf("No error should happen when saving user, but got %v", err)
62         }
63
64         var user2 User
65         if err := DB.Where("name = ? AND password = ? AND password_hash = ?", name, EncryptedData("pass1"), []byte("abc")).First(&user2).Error; err != nil {
66                 t.Errorf("No error should happen when querying user with valuer, but got %v", err)
67         }
68 }
69
70 func TestFailedValuer(t *testing.T) {
71         name := randName()
72
73         err := DB.Exec("INSERT INTO users(name, password) VALUES(?, ?)", name, EncryptedData("xpass1")).Error
74
75         if err == nil {
76                 t.Errorf("There should be an error should happen when insert data")
77         } else if !strings.HasPrefix(err.Error(), "Should not start with") {
78                 t.Errorf("The error should be returned from Valuer, but get %v", err)
79         }
80 }