antispam_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package antispam
  2. import (
  3. "context"
  4. "io/ioutil"
  5. "math/rand"
  6. "net/http"
  7. "strconv"
  8. "testing"
  9. "time"
  10. "go-common/app/interface/main/upload/model"
  11. "go-common/library/cache/redis"
  12. "go-common/library/container/pool"
  13. bm "go-common/library/net/http/blademaster"
  14. xtime "go-common/library/time"
  15. )
  16. func TestAntiSpamHandler(t *testing.T) {
  17. anti := New(
  18. &Config{
  19. On: true,
  20. Second: 1,
  21. N: 1,
  22. Hour: 1,
  23. M: 1,
  24. Redis: &redis.Config{
  25. Config: &pool.Config{
  26. Active: 10,
  27. Idle: 10,
  28. IdleTimeout: xtime.Duration(time.Second * 60),
  29. },
  30. Name: "test",
  31. Proto: "tcp",
  32. Addr: "172.16.33.54:6380",
  33. DialTimeout: xtime.Duration(time.Second),
  34. ReadTimeout: xtime.Duration(time.Second),
  35. WriteTimeout: xtime.Duration(time.Second),
  36. }}, GetGetRateLimit)
  37. engine := bm.New()
  38. engine.UseFunc(func(c *bm.Context) {
  39. mid, _ := strconv.ParseInt(c.Request.Form.Get("mid"), 10, 64)
  40. c.Set("mid", mid)
  41. c.Next()
  42. })
  43. engine.Use(anti.Handler())
  44. engine.GET("/antispam", func(c *bm.Context) {
  45. c.String(200, "pass")
  46. })
  47. go engine.Run(":18080")
  48. time.Sleep(time.Millisecond * 50)
  49. mid := rand.Int()
  50. _, content, err := httpGet("http://127.0.0.1:18080/antispam?mid=" + strconv.Itoa(mid) + "&bucket=a&dir=b")
  51. if err != nil {
  52. t.Logf("http get failed, err:=%v", err)
  53. t.FailNow()
  54. }
  55. if string(content) != "pass" {
  56. t.Logf("request should block by limiter, but passed")
  57. t.FailNow()
  58. }
  59. _, content, err = httpGet("http://127.0.0.1:18080/antispam?mid=" + strconv.Itoa(mid) + "&bucket=a&dir=b")
  60. if err != nil {
  61. t.Logf("http get failed, err:=%v", err)
  62. t.FailNow()
  63. }
  64. if string(content) == "pass" {
  65. t.Logf("request should block by limiter, but passed")
  66. t.FailNow()
  67. }
  68. engine.Server().Shutdown(context.TODO())
  69. }
  70. func httpGet(url string) (code int, content []byte, err error) {
  71. resp, err := http.Get(url)
  72. if err != nil {
  73. return
  74. }
  75. defer resp.Body.Close()
  76. content, err = ioutil.ReadAll(resp.Body)
  77. if err != nil {
  78. return
  79. }
  80. code = resp.StatusCode
  81. return
  82. }
  83. func GetGetRateLimit(bucket, dir string) (model.DirRateConfig, bool) {
  84. return model.DirRateConfig{
  85. SecondQPS: 1,
  86. CountQPS: 1,
  87. }, true
  88. }