validator_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package vmess_test
  2. import (
  3. "testing"
  4. "time"
  5. "v2ray.com/core/common"
  6. "v2ray.com/core/common/protocol"
  7. "v2ray.com/core/common/serial"
  8. "v2ray.com/core/common/uuid"
  9. . "v2ray.com/core/proxy/vmess"
  10. )
  11. func TestUserValidator(t *testing.T) {
  12. hasher := protocol.DefaultIDHash
  13. v := NewTimedUserValidator(hasher)
  14. defer common.Close(v)
  15. toAccount := func(a *Account) protocol.Account {
  16. account, err := a.AsAccount()
  17. common.Must(err)
  18. return account
  19. }
  20. id := uuid.New()
  21. user := &protocol.MemoryUser{
  22. Email: "test",
  23. Account: toAccount(&Account{
  24. Id: id.String(),
  25. AlterId: 8,
  26. }),
  27. }
  28. common.Must(v.Add(user))
  29. {
  30. testSmallLag := func(lag time.Duration) {
  31. ts := protocol.Timestamp(time.Now().Add(time.Second * lag).Unix())
  32. idHash := hasher(id.Bytes())
  33. common.Must2(serial.WriteUint64(idHash, uint64(ts)))
  34. userHash := idHash.Sum(nil)
  35. euser, ets, found := v.Get(userHash)
  36. if !found {
  37. t.Fatal("user not found")
  38. }
  39. if euser.Email != user.Email {
  40. t.Error("unexpected user email: ", euser.Email, " want ", user.Email)
  41. }
  42. if ets != ts {
  43. t.Error("unexpected timestamp: ", ets, " want ", ts)
  44. }
  45. }
  46. testSmallLag(0)
  47. testSmallLag(40)
  48. testSmallLag(-40)
  49. testSmallLag(80)
  50. testSmallLag(-80)
  51. testSmallLag(120)
  52. testSmallLag(-120)
  53. }
  54. {
  55. testBigLag := func(lag time.Duration) {
  56. ts := protocol.Timestamp(time.Now().Add(time.Second * lag).Unix())
  57. idHash := hasher(id.Bytes())
  58. common.Must2(serial.WriteUint64(idHash, uint64(ts)))
  59. userHash := idHash.Sum(nil)
  60. euser, _, found := v.Get(userHash)
  61. if found || euser != nil {
  62. t.Error("unexpected user")
  63. }
  64. }
  65. testBigLag(121)
  66. testBigLag(-121)
  67. testBigLag(310)
  68. testBigLag(-310)
  69. testBigLag(500)
  70. testBigLag(-500)
  71. }
  72. if v := v.Remove(user.Email); !v {
  73. t.Error("unable to remove user")
  74. }
  75. if v := v.Remove(user.Email); v {
  76. t.Error("remove user twice")
  77. }
  78. }