Some checks failed
CI Pipeline / Lint (push) Failing after 5m12s
CI Pipeline / Test (push) Has been skipped
CI Pipeline / Security Scan (push) Successful in 6m3s
CI Pipeline / Build (push) Has been skipped
CI Pipeline / Security Scan (pull_request) Successful in 2m36s
CI Pipeline / Notification (push) Successful in 2s
CI Pipeline / Lint (pull_request) Failing after 2m38s
CI Pipeline / Test (pull_request) Has been skipped
CI Pipeline / Build (pull_request) Has been skipped
CI Pipeline / Notification (pull_request) Successful in 1s
71 lines
1.6 KiB
Go
71 lines
1.6 KiB
Go
package middleware_test
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/stretchr/testify/assert"
|
|
"starter-kit/internal/transport/http/middleware"
|
|
)
|
|
|
|
func TestCORS(t *testing.T) {
|
|
// Tạo router mới
|
|
r := gin.New()
|
|
|
|
// Lấy cấu hình mặc định
|
|
config := middleware.DefaultSecurityConfig()
|
|
|
|
// Tùy chỉnh cấu hình CORS
|
|
config.CORS.AllowOrigins = []string{"https://example.com"}
|
|
|
|
// Áp dụng middleware
|
|
config.Apply(r)
|
|
|
|
|
|
// Thêm route test
|
|
r.GET("/test", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"message": "Hello, World!"})
|
|
})
|
|
|
|
// Tạo test server
|
|
ts := httptest.NewServer(r)
|
|
defer ts.Close()
|
|
|
|
// Test CORS
|
|
t.Run("Test CORS", func(t *testing.T) {
|
|
req, _ := http.NewRequest("GET", ts.URL+"/test", nil)
|
|
req.Header.Set("Origin", "https://example.com")
|
|
|
|
client := &http.Client{}
|
|
resp, err := client.Do(req)
|
|
assert.NoError(t, err)
|
|
defer resp.Body.Close()
|
|
|
|
assert.Equal(t, "*", resp.Header.Get("Access-Control-Allow-Origin"), "CORS header not set correctly")
|
|
})
|
|
}
|
|
|
|
func TestRateLimit(t *testing.T) {
|
|
// Test rate limiting (chỉ kiểm tra xem middleware có được áp dụng không)
|
|
config := middleware.DefaultSecurityConfig()
|
|
config.RateLimit.Rate = 10 // 10 requests per minute
|
|
|
|
r := gin.New()
|
|
config.Apply(r)
|
|
|
|
r.GET("/", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
|
})
|
|
|
|
ts := httptest.NewServer(r)
|
|
defer ts.Close()
|
|
|
|
// Gửi một request để kiểm tra xem server có chạy không
|
|
resp, err := http.Get(ts.URL)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
|
resp.Body.Close()
|
|
}
|