This repository has been archived on 2026-04-03. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
core/server/main_test.go

107 lines
2.4 KiB
Go

package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"git.gobha.me/xcaliber/chat-switchboard/config"
"git.gobha.me/xcaliber/chat-switchboard/middleware"
)
func TestHealthEndpoint(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/health", func(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok", "database": false})
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/health", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
}
func TestCORSHeaders(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.CORS())
r.GET("/test", func(c *gin.Context) {
c.Status(200)
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("OPTIONS", "/test", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusNoContent {
t.Errorf("Expected status %d for OPTIONS, got %d", http.StatusNoContent, w.Code)
}
if w.Header().Get("Access-Control-Allow-Origin") != "*" {
t.Error("Missing or incorrect CORS header")
}
}
func TestRouterSetup(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/health", func(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok"})
})
api := r.Group("/api/v1")
{
api.POST("/auth/register", handleRegister)
api.POST("/auth/login", handleLogin)
api.GET("/chats", handleListChats)
api.POST("/chats", handleCreateChat)
}
routes := r.Routes()
routePaths := make(map[string]bool)
for _, route := range routes {
routePaths[route.Method+" "+route.Path] = true
}
expectedRoutes := []string{
"GET /health",
"POST /api/v1/auth/register",
"POST /api/v1/auth/login",
"GET /api/v1/chats",
"POST /api/v1/chats",
}
for _, expected := range expectedRoutes {
if !routePaths[expected] {
t.Errorf("Expected route %s to be registered", expected)
}
}
}
func TestAuthMiddlewareNoDatabase(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
cfg := &config.Config{JWTSecret: "test-secret"}
// No database connected — middleware should pass through
r.Use(middleware.Auth(cfg))
r.GET("/protected", func(c *gin.Context) {
c.JSON(200, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/protected", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected pass-through with no DB, got status %d", w.Code)
}
}