store_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2011 Dmitry Chestnykh. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package captcha
  5. import (
  6. "bytes"
  7. "testing"
  8. )
  9. func TestSetGet(t *testing.T) {
  10. s := NewMemoryStore(CollectNum, Expiration)
  11. id := "captcha id"
  12. d := RandomDigits(10)
  13. s.Set(id, d)
  14. d2 := s.Get(id, false)
  15. if d2 == nil || !bytes.Equal(d, d2) {
  16. t.Errorf("saved %v, getDigits returned got %v", d, d2)
  17. }
  18. }
  19. func TestGetClear(t *testing.T) {
  20. s := NewMemoryStore(CollectNum, Expiration)
  21. id := "captcha id"
  22. d := RandomDigits(10)
  23. s.Set(id, d)
  24. d2 := s.Get(id, true)
  25. if d2 == nil || !bytes.Equal(d, d2) {
  26. t.Errorf("saved %v, getDigitsClear returned got %v", d, d2)
  27. }
  28. d2 = s.Get(id, false)
  29. if d2 != nil {
  30. t.Errorf("getDigitClear didn't clear (%q=%v)", id, d2)
  31. }
  32. }
  33. func TestCollect(t *testing.T) {
  34. //TODO(dchest): can't test automatic collection when saving, because
  35. //it's currently launched in a different goroutine.
  36. s := NewMemoryStore(10, -1)
  37. // create 10 ids
  38. ids := make([]string, 10)
  39. d := RandomDigits(10)
  40. for i := range ids {
  41. ids[i] = randomId()
  42. s.Set(ids[i], d)
  43. }
  44. s.(*memoryStore).collect()
  45. // Must be already collected
  46. nc := 0
  47. for i := range ids {
  48. d2 := s.Get(ids[i], false)
  49. if d2 != nil {
  50. t.Errorf("%d: not collected", i)
  51. nc++
  52. }
  53. }
  54. if nc > 0 {
  55. t.Errorf("= not collected %d out of %d captchas", nc, len(ids))
  56. }
  57. }
  58. func BenchmarkSetCollect(b *testing.B) {
  59. b.StopTimer()
  60. d := RandomDigits(10)
  61. s := NewMemoryStore(9999, -1)
  62. ids := make([]string, 1000)
  63. for i := range ids {
  64. ids[i] = randomId()
  65. }
  66. b.StartTimer()
  67. for i := 0; i < b.N; i++ {
  68. for j := 0; j < 1000; j++ {
  69. s.Set(ids[j], d)
  70. }
  71. s.(*memoryStore).collect()
  72. }
  73. }