76 lines
1.7 KiB
Go
76 lines
1.7 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func TestDynamicCORS(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
t.Setenv("CORS_ALLOW_ORIGIN", "http://example.com")
|
|
|
|
r := gin.New()
|
|
r.Use(DynamicCORS())
|
|
r.GET("/ping", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/ping", nil)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d", w.Code)
|
|
}
|
|
if got := w.Header().Get("Access-Control-Allow-Origin"); got != "http://example.com" {
|
|
t.Fatalf("unexpected allow origin: %q", got)
|
|
}
|
|
}
|
|
|
|
func TestDynamicCORSOptions(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
t.Setenv("CORS_ALLOW_ORIGIN", "*")
|
|
|
|
r := gin.New()
|
|
r.Use(DynamicCORS())
|
|
r.OPTIONS("/ping", func(c *gin.Context) {
|
|
c.Status(http.StatusOK)
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodOptions, "/ping", nil)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusNoContent {
|
|
t.Fatalf("expected 204, got %d", w.Code)
|
|
}
|
|
}
|
|
|
|
func TestDynamicRateLimit(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
t.Setenv("RATE_LIMIT_RPM", "2")
|
|
|
|
r := gin.New()
|
|
r.Use(DynamicRateLimit())
|
|
r.GET("/limited", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
|
})
|
|
|
|
for i := 1; i <= 3; i++ {
|
|
req := httptest.NewRequest(http.MethodGet, "/limited", nil)
|
|
req.RemoteAddr = "127.0.0.1:12345"
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
|
|
if i < 3 && w.Code != http.StatusOK {
|
|
t.Fatalf("request %d expected 200, got %d", i, w.Code)
|
|
}
|
|
if i == 3 && w.Code != http.StatusTooManyRequests {
|
|
t.Fatalf("request %d expected 429, got %d", i, w.Code)
|
|
}
|
|
}
|
|
}
|