store_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package captcha
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "testing"
  6. "time"
  7. "github.com/mojocn/base64Captcha"
  8. "gogs.baozhida.cn/zoie/OAuth-core/storage"
  9. "gogs.baozhida.cn/zoie/OAuth-core/storage/cache"
  10. )
  11. var _expiration = 6000
  12. func getStore(_ *testing.T) storage.AdapterCache {
  13. return cache.NewMemory()
  14. }
  15. func TestSetGet(t *testing.T) {
  16. s := NewCacheStore(getStore(t), _expiration)
  17. id := "captcha id"
  18. d := "random-string"
  19. s.Set(id, d)
  20. d2 := s.Get(id, false)
  21. if d2 != d {
  22. t.Errorf("saved %v, getDigits returned got %v", d, d2)
  23. }
  24. }
  25. func TestGetClear(t *testing.T) {
  26. s := NewCacheStore(getStore(t), _expiration)
  27. id := "captcha id"
  28. d := "932839jfffjkdss"
  29. s.Set(id, d)
  30. d2 := s.Get(id, true)
  31. if d != d2 {
  32. t.Errorf("saved %v, getDigitsClear returned got %v", d, d2)
  33. }
  34. d2 = s.Get(id, false)
  35. if d2 != "" {
  36. t.Errorf("getDigitClear didn't clear (%q=%v)", id, d2)
  37. }
  38. }
  39. func BenchmarkSetCollect(b *testing.B) {
  40. store := cache.NewMemory()
  41. b.StopTimer()
  42. d := "fdskfew9832232r"
  43. s := NewCacheStore(store, -1)
  44. ids := make([]string, 1000)
  45. for i := range ids {
  46. ids[i] = fmt.Sprintf("%d", rand.Int63())
  47. }
  48. b.StartTimer()
  49. for i := 0; i < b.N; i++ {
  50. for j := 0; j < 1000; j++ {
  51. s.Set(ids[j], d)
  52. }
  53. }
  54. }
  55. func TestStore_SetGoCollect(t *testing.T) {
  56. s := NewCacheStore(getStore(t), -1)
  57. for i := 0; i <= 100; i++ {
  58. s.Set(fmt.Sprint(i), fmt.Sprint(i))
  59. }
  60. }
  61. func TestStore_CollectNotExpire(t *testing.T) {
  62. s := NewCacheStore(getStore(t), 36000)
  63. for i := 0; i < 50; i++ {
  64. s.Set(fmt.Sprint(i), fmt.Sprint(i))
  65. }
  66. // let background goroutine to go
  67. time.Sleep(time.Second)
  68. if v := s.Get("0", false); v != "0" {
  69. t.Error("cache store get failed")
  70. }
  71. }
  72. func TestNewCacheStore(t *testing.T) {
  73. type args struct {
  74. store storage.AdapterCache
  75. expiration int
  76. }
  77. tests := []struct {
  78. name string
  79. args args
  80. want base64Captcha.Store
  81. }{
  82. {"", args{getStore(t), 36000}, nil},
  83. {"", args{getStore(t), 180000}, nil},
  84. }
  85. for _, tt := range tests {
  86. t.Run(tt.name, func(t *testing.T) {
  87. if got := NewCacheStore(tt.args.store, tt.args.expiration); got == nil {
  88. t.Errorf("NewMemoryStore() = %v, want %v", got, tt.want)
  89. }
  90. })
  91. }
  92. }