gitcat
1package captcha
2
3import (
4 "bytes"
5 "strings"
6 "testing"
7 "time"
8)
9
10func TestStoreVerifyOnce(t *testing.T) {
11 s := NewStore(5 * time.Minute)
12 id, err := s.New()
13 if err != nil {
14 t.Fatalf("New 失败: %v", err)
15 }
16 code, ok := s.Code(id)
17 if !ok || len(code) != 5 || strings.Trim(code, "0123456789") != "" {
18 t.Fatalf("验证码应为 5 位数字,实际 %q ok=%v", code, ok)
19 }
20 // 错误输入:销毁且不通过
21 if s.Verify(id, "99999") {
22 t.Error("错误验证码不应通过")
23 }
24 if _, ok := s.Code(id); ok {
25 t.Error("校验失败后验证码也应销毁(一次性)")
26 }
27}
28
29func TestStoreSingleUse(t *testing.T) {
30 s := NewStore(5 * time.Minute)
31 id, _ := s.New()
32 code, _ := s.Code(id)
33 if !s.Verify(id, code) {
34 t.Fatal("正确验证码应通过")
35 }
36 if s.Verify(id, code) {
37 t.Error("同一验证码不能使用第二次(防重放)")
38 }
39}
40
41func TestStoreExpired(t *testing.T) {
42 s := NewStore(10 * time.Millisecond)
43 id, _ := s.New()
44 code, _ := s.Code(id)
45 time.Sleep(30 * time.Millisecond)
46 if s.Verify(id, code) {
47 t.Error("过期验证码不应通过")
48 }
49 if _, err := s.PNG(id); err == nil {
50 t.Error("过期验证码不应能渲染图片")
51 }
52}
53
54func TestStoreVerifyNormalizesInput(t *testing.T) {
55 s := NewStore(5 * time.Minute)
56 id, _ := s.New()
57 code, _ := s.Code(id)
58 spaced := strings.Join(strings.Split(code, ""), " ")
59 if !s.Verify(id, spaced) {
60 t.Errorf("带空格输入 %q 应被宽容处理", spaced)
61 }
62}
63
64func TestStoreUnknownID(t *testing.T) {
65 s := NewStore(5 * time.Minute)
66 if s.Verify("no-such-id", "12345") {
67 t.Error("未知 id 不应通过")
68 }
69 if s.Verify("", "12345") {
70 t.Error("空 id 不应通过")
71 }
72}
73
74func TestPNGRender(t *testing.T) {
75 png, err := PNG("0123456789"[2:7]) // "23456"
76 if err != nil {
77 t.Fatalf("PNG 渲染失败: %v", err)
78 }
79 // PNG 文件签名
80 if !bytes.HasPrefix(png, []byte{0x89, 'P', 'N', 'G'}) {
81 t.Fatal("产物不是合法 PNG")
82 }
83 if len(png) < 500 {
84 t.Fatalf("图片过小(%d 字节),疑似内容异常", len(png))
85 }
86 // 每位数字都必须有字形定义,避免渲染出空白图
87 for _, d := range []byte("0123456789") {
88 if _, ok := segDigits[d]; !ok {
89 t.Errorf("数字 %q 缺少字形定义", d)
90 }
91 }
92}
93
94func TestSweepRemovesExpired(t *testing.T) {
95 s := NewStore(10 * time.Millisecond)
96 id, _ := s.New()
97 time.Sleep(30 * time.Millisecond)
98 s.mu.Lock()
99 s.sweep(time.Now())
100 s.mu.Unlock()
101 if _, ok := s.Code(id); ok {
102 t.Error("sweep 后过期项应被清除")
103 }
104}