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