forked from dchest/captcha
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store_test.go
105 lines (99 loc) · 2.48 KB
/
store_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright 2011 Dmitry Chestnykh. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package captcha
import (
"bytes"
"strconv"
"testing"
)
func TestSetGet(t *testing.T) {
s := NewMemoryStore(CollectNum, Expiration)
id := "captcha id"
d := RandomDigits(10)
max := 2
databind := "123"
s.Set(id, d, max, databind)
d2, qmax, wantdatabind := s.Get(id, false)
if d2 == nil || !bytes.Equal(d, d2) || max != qmax || wantdatabind != databind {
t.Errorf("saved %v(%d:%v), getDigits returned got %v(%d:%v)", d, max, databind, d2, qmax, wantdatabind)
}
}
func TestGetClear(t *testing.T) {
s := NewMemoryStore(CollectNum, Expiration)
id := "captcha id"
d := RandomDigits(10)
max := 1
s.Set(id, d, max, "")
d2, _, _ := s.Get(id, true)
if d2 == nil || !bytes.Equal(d, d2) {
t.Errorf("saved %v, getDigitsClear returned got %v", d, d2)
}
d2, _, _ = s.Get(id, false)
if d2 != nil {
t.Errorf("getDigitClear didn't clear (%q=%v)", id, d2)
}
}
func TestGetClearForNum(t *testing.T) {
s := NewMemoryStore(CollectNum, Expiration)
id := "captcha id"
d := RandomDigits(10)
max := 5
binddata := "12345"
s.Set(id, d, max, binddata)
for i := 0; i < max; i++ {
d2, _, _ := s.Get(id, true)
if d2 == nil || !bytes.Equal(d, d2) {
t.Errorf("saved %v, getDigitsClear returned got %v", d, d2)
}
}
d2, _, _ := s.Get(id, true)
if d2 != nil {
t.Errorf("getDigitClear didn't clear (%q=%v)", id, d2)
}
d2, _, _ = s.Get(id, false)
if d2 != nil {
t.Errorf("getDigitClear didn't clear (%q=%v)", id, d2)
}
}
func TestCollect(t *testing.T) {
//TODO(dchest): can't test automatic collection when saving, because
//it's currently launched in a different goroutine.
s := NewMemoryStore(10, -1)
// create 10 ids
ids := make([]string, 10)
d := RandomDigits(10)
for i := range ids {
ids[i] = randomId()
s.Set(ids[i], d, 1, strconv.Itoa(i))
}
s.(*memoryStore).collect()
// Must be already collected
nc := 0
for i := range ids {
d2, _, _ := s.Get(ids[i], false)
if d2 != nil {
t.Errorf("%d: not collected", i)
nc++
}
}
if nc > 0 {
t.Errorf("= not collected %d out of %d captchas", nc, len(ids))
}
}
func BenchmarkSetCollect(b *testing.B) {
b.StopTimer()
d := RandomDigits(10)
s := NewMemoryStore(9999, -1)
ids := make([]string, 1000)
for i := range ids {
ids[i] = randomId()
}
b.StartTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < 1000; j++ {
s.Set(ids[j], d, 1, "")
}
s.(*memoryStore).collect()
}
}