all repos — captcha @ d7cb604d49c3777d159741e1df389c6c540310f8

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
64
65func BenchmarkSetCollect(b *testing.B) {
66	b.StopTimer()
67	d := RandomDigits(10)
68	s := NewMemoryStore(9999, -1)
69	ids := make([]string, 1000)
70	for i := range ids {
71		ids[i] = randomId()
72	}
73	b.StartTimer()
74	for i := 0; i < b.N; i++ {
75		for j := 0; j < 1000; j++ {
76			s.Set(ids[j], d)
77		}
78		s.(*memoryStore).collect()
79	}
80}