package server import ( "net/http" "net/http/httptest" "testing" "chat-agent-system/internal/config" ) func TestServer_WebAssetsHostingAndFallback(t *testing.T) { cfg, err := config.Load("") if err != nil { t.Fatalf("加载配置失败: %v", err) } cfg.HTTPPort = 8089 srv := NewServer(cfg, nil) handler := srv.Routes() // 1. 测试访问根路径 "/" 应返回前端 SPA index.html reqRoot := httptest.NewRequest(http.MethodGet, "/", nil) wRoot := httptest.NewRecorder() handler.ServeHTTP(wRoot, reqRoot) if wRoot.Code != http.StatusOK { t.Errorf("expected status 200 for root SPA, got %d", wRoot.Code) } bodyStr := wRoot.Body.String() if bodyStr == "" { t.Errorf("expected non-empty SPA body") } // 2. 测试 SPA 客户端路由回退 (如访问 /sessions/sess-001 应返回 index.html 而不是 404) reqClientRoute := httptest.NewRequest(http.MethodGet, "/sessions/sess-001", nil) wClient := httptest.NewRecorder() handler.ServeHTTP(wClient, reqClientRoute) if wClient.Code != http.StatusOK { t.Errorf("expected status 200 for client route fallback, got %d", wClient.Code) } // 3. 测试 API 路由不受静态路由影响 (GET /api/v1/chat/sessions 依然正常工作) reqAPI := httptest.NewRequest(http.MethodGet, "/api/v1/chat/sessions", nil) wAPI := httptest.NewRecorder() handler.ServeHTTP(wAPI, reqAPI) if wAPI.Code != http.StatusOK { t.Errorf("expected status 200 for /api/v1/chat/sessions, got %d", wAPI.Code) } }