github.com/TeaOSLab/EdgeNode@v1.3.8/internal/waf/captcha_generator_test.go (about) 1 // Copyright 2023 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn . 2 3 package waf_test 4 5 import ( 6 "github.com/TeaOSLab/EdgeNode/internal/utils/testutils" 7 "github.com/TeaOSLab/EdgeNode/internal/waf" 8 "github.com/iwind/TeaGo/assert" 9 "github.com/iwind/TeaGo/types" 10 "runtime" 11 "strings" 12 "testing" 13 "time" 14 ) 15 16 func TestCaptchaGenerator_NewCaptcha(t *testing.T) { 17 var a = assert.NewAssertion(t) 18 19 var generator = waf.NewCaptchaGenerator() 20 var captchaId = generator.NewCaptcha(6) 21 t.Log("captchaId:", captchaId) 22 23 var digits = generator.Get(captchaId) 24 var s []string 25 for _, digit := range digits { 26 s = append(s, types.String(digit)) 27 } 28 t.Log(strings.Join(s, " ")) 29 30 a.IsTrue(generator.Verify(captchaId, strings.Join(s, ""))) 31 a.IsFalse(generator.Verify(captchaId, strings.Join(s, ""))) 32 } 33 34 func TestCaptchaGenerator_NewCaptcha_UTF8(t *testing.T) { 35 var a = assert.NewAssertion(t) 36 37 var generator = waf.NewCaptchaGenerator() 38 var captchaId = generator.NewCaptcha(6) 39 t.Log("captchaId:", captchaId) 40 41 var digits = generator.Get(captchaId) 42 var s []string 43 for _, digit := range digits { 44 s = append(s, types.String(digit)) 45 } 46 t.Log(strings.Join(s, " ")) 47 48 a.IsFalse(generator.Verify(captchaId, "中文真的很长")) 49 } 50 51 func TestCaptchaGenerator_NewCaptcha_Memory(t *testing.T) { 52 runtime.GC() 53 54 var stat1 = &runtime.MemStats{} 55 runtime.ReadMemStats(stat1) 56 57 var generator = waf.NewCaptchaGenerator() 58 for i := 0; i < 1_000_000; i++ { 59 generator.NewCaptcha(6) 60 } 61 62 if testutils.IsSingleTesting() { 63 time.Sleep(1 * time.Second) 64 } 65 66 runtime.GC() 67 68 var stat2 = &runtime.MemStats{} 69 runtime.ReadMemStats(stat2) 70 71 t.Log((stat2.HeapInuse-stat1.HeapInuse)>>10, "KiB") 72 73 _ = generator 74 } 75 76 func BenchmarkNewCaptchaGenerator(b *testing.B) { 77 runtime.GOMAXPROCS(4) 78 79 var generator = waf.NewCaptchaGenerator() 80 b.ResetTimer() 81 82 b.RunParallel(func(pb *testing.PB) { 83 for pb.Next() { 84 generator.NewCaptcha(6) 85 } 86 }) 87 }