package main import ( "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" ) 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"}) }) 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) } expectedBody := `{"status":"ok"}` if w.Body.String() != expectedBody { t.Errorf("Expected body %s, got %s", expectedBody, w.Body.String()) } } func TestCORSHeaders(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New() r.Use(func(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization") if c.Request.Method == "OPTIONS" { c.AbortWithStatus(204) return } c.Next() }) w := httptest.NewRecorder() req, _ := http.NewRequest("OPTIONS", "/api/v1/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() // Setup routes like in main.go 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) } // Verify routes are registered 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) } } }