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