scope_test.go 2.1 KB

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