antispam_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package antispam
  2. import (
  3. "context"
  4. "io/ioutil"
  5. "net/http"
  6. "strconv"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "go-common/library/cache/redis"
  11. "go-common/library/container/pool"
  12. bm "go-common/library/net/http/blademaster"
  13. xtime "go-common/library/time"
  14. )
  15. func TestAntiSpamHandler(t *testing.T) {
  16. anti := New(
  17. &Config{
  18. On: true,
  19. Second: 1,
  20. N: 1,
  21. Hour: 1,
  22. M: 1,
  23. Redis: &redis.Config{
  24. Config: &pool.Config{
  25. Active: 10,
  26. Idle: 10,
  27. IdleTimeout: xtime.Duration(time.Second * 60),
  28. },
  29. Name: "test",
  30. Proto: "tcp",
  31. Addr: "172.18.33.60:6889",
  32. DialTimeout: xtime.Duration(time.Second),
  33. ReadTimeout: xtime.Duration(time.Second),
  34. WriteTimeout: xtime.Duration(time.Second),
  35. },
  36. },
  37. )
  38. engine := bm.New()
  39. engine.UseFunc(func(c *bm.Context) {
  40. mid, _ := strconv.ParseInt(c.Request.Form.Get("mid"), 10, 64)
  41. c.Set("mid", mid)
  42. c.Next()
  43. })
  44. engine.Use(anti.Handler())
  45. engine.GET("/antispam", func(c *bm.Context) {
  46. c.String(200, "pass")
  47. })
  48. go engine.Run(":18080")
  49. time.Sleep(time.Millisecond * 50)
  50. code, content, err := httpGet("http://127.0.0.1:18080/antispam?mid=11")
  51. if err != nil {
  52. t.Logf("http get failed, err:=%v", err)
  53. t.FailNow()
  54. }
  55. if code != 200 || string(content) != "pass" {
  56. t.Logf("request should pass by limiter, but blocked: %d, %v", code, content)
  57. t.FailNow()
  58. }
  59. _, content, err = httpGet("http://127.0.0.1:18080/antispam?mid=11")
  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 TestConfigValidate(t *testing.T) {
  84. var conf *Config
  85. assert.Contains(t, conf.validate().Error(), "empty config")
  86. conf = &Config{
  87. Second: 0,
  88. }
  89. assert.Contains(t, conf.validate().Error(), "invalid Second")
  90. conf = &Config{
  91. Second: 1,
  92. Hour: 0,
  93. }
  94. assert.Contains(t, conf.validate().Error(), "invalid Hour")
  95. }