Files
gochat/internal/middleware/session_test.go
T
2026-06-04 15:44:48 +08:00

49 lines
1.4 KiB
Go

package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/gochat/gochat/internal/auth"
)
func TestSessionMiddleware_SkipPath(t *testing.T) {
gin.SetMode(gin.TestMode)
store := &auth.SessionStore{}
cfg := DefaultSessionMiddlewareConfig()
r := gin.New()
r.Use(SessionMiddleware(store, cfg))
r.GET("/health", func(c *gin.Context) { c.JSON(200, gin.H{"ok": true}) })
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/health", nil)
r.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
}
func TestSessionMiddleware_NoSessionHeader(t *testing.T) {
gin.SetMode(gin.TestMode)
store := &auth.SessionStore{}
cfg := DefaultSessionMiddlewareConfig()
r := gin.New()
r.Use(func(c *gin.Context) { c.Set("user_id", uint(1)); c.Next() })
r.Use(SessionMiddleware(store, cfg))
r.GET("/api/v1/test", func(c *gin.Context) { c.JSON(200, gin.H{"ok": true}) })
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/test", nil)
r.ServeHTTP(w, req)
// No session header — middleware should pass through (session enrichment is optional)
assert.Equal(t, 200, w.Code)
}
func TestDefaultSessionMiddlewareConfig(t *testing.T) {
cfg := DefaultSessionMiddlewareConfig()
assert.Equal(t, "X-Session-ID", cfg.SessionHeader)
assert.Contains(t, cfg.SkipPaths, "/health")
assert.Contains(t, cfg.SkipPaths, "/api/v1/auth/login")
}