store_test.go 1.3 KB

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