all repos — captcha @ master

Go package captcha implements generation and verification of image and audio CAPTCHAs.

store_test.go (view raw)

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