package handlers import ( "context" "html/template" "net/http" "net/http/httptest" "testing" "custom-start-page/internal/middleware" ) // createMockDashboardTemplate creates a simple mock template for testing func createMockDashboardTemplate() *template.Template { tmpl := template.New("dashboard.html") template.Must(tmpl.Parse(`

Dashboard

User: {{.UserID}}
`)) return tmpl } // TestHandleDashboard_WithAuthenticatedUser tests that authenticated users see the dashboard func TestHandleDashboard_WithAuthenticatedUser(t *testing.T) { // Setup mockTemplate := createMockDashboardTemplate() handler := &DashboardHandler{ templates: mockTemplate, } // Create request with user ID in context req := httptest.NewRequest(http.MethodGet, "/dashboard", nil) ctx := context.WithValue(req.Context(), middleware.GetUserIDContextKey(), "test-user-123") req = req.WithContext(ctx) w := httptest.NewRecorder() // Execute handler.HandleDashboard(w, req) // Assert if w.Code != http.StatusOK { t.Errorf("Expected status 200, got %d", w.Code) } // Check that response contains dashboard content body := w.Body.String() if body == "" { t.Error("Expected non-empty response body") } } // TestHandleDashboard_WithoutUserID tests that requests without user ID fail func TestHandleDashboard_WithoutUserID(t *testing.T) { // Setup mockTemplate := createMockDashboardTemplate() handler := &DashboardHandler{ templates: mockTemplate, } // Create request without user ID in context req := httptest.NewRequest(http.MethodGet, "/dashboard", nil) w := httptest.NewRecorder() // Execute handler.HandleDashboard(w, req) // Assert if w.Code != http.StatusInternalServerError { t.Errorf("Expected status 500, got %d", w.Code) } }