| 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 | |
| 5 | package captcha |
| 6 | |
| 7 | import ( |
| 8 | "bytes" |
| 9 | "testing" |
| 10 | ) |
| 11 | |
| 12 | func 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 | |
| 23 | func 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 | |
| 38 | func 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 | func BenchmarkSetCollect(b *testing.B) { |
| 65 | d := RandomDigits(10) |
| 66 | s := NewMemoryStore(9999, -1) |
| 67 | ids := make([]string, 1000) |
| 68 | for i := range ids { |
| 69 | ids[i] = randomID() |
| 70 | } |
| 71 | |
| 72 | for b.Loop() { |
| 73 | for j := range 1000 { |
| 74 | s.Set(ids[j], d) |
| 75 | } |
| 76 | s.(*memoryStore).collect() |
| 77 | } |
| 78 | } |