store_test.go 1.5 KB

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