fix(chat): 优化后台限流与 SSE 日志
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
package chathub
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zaptest/observer"
|
||||
)
|
||||
|
||||
func TestSSELifecycleLogsConnectionCountReasonAndLifetime(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
core, observed := observer.New(zap.InfoLevel)
|
||||
hub := NewHub(nil)
|
||||
handler := NewHandler(hub, zap.New(core))
|
||||
|
||||
requestContext, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/admin/chats/events", nil).WithContext(requestContext)
|
||||
request.RemoteAddr = "42.49.131.69:34567"
|
||||
recorder := httptest.NewRecorder()
|
||||
ginContext, _ := gin.CreateTestContext(recorder)
|
||||
ginContext.Request = request
|
||||
ginContext.Set(middleware.ContextAdminID, uint64(88))
|
||||
ginContext.Set(middleware.ContextRequestID, "sse-test-request")
|
||||
|
||||
handler.AdminEvents(ginContext)
|
||||
|
||||
connected := observed.FilterMessage("SSE 连接建立").All()
|
||||
if len(connected) != 1 {
|
||||
t.Fatalf("connection logs = %d, want 1", len(connected))
|
||||
}
|
||||
connectedFields := connected[0].ContextMap()
|
||||
if connectedFields["admin_id"] != uint64(88) || connectedFields["active_sse_connections"] != int64(1) {
|
||||
t.Fatalf("unexpected connection fields: %v", connectedFields)
|
||||
}
|
||||
|
||||
disconnected := observed.FilterMessage("SSE 连接断开").All()
|
||||
if len(disconnected) != 1 {
|
||||
t.Fatalf("disconnection logs = %d, want 1", len(disconnected))
|
||||
}
|
||||
disconnectedFields := disconnected[0].ContextMap()
|
||||
if disconnectedFields["disconnect_reason"] != "context_canceled" {
|
||||
t.Fatalf("disconnect reason = %v, want context_canceled", disconnectedFields["disconnect_reason"])
|
||||
}
|
||||
if disconnectedFields["active_sse_connections"] != int64(0) {
|
||||
t.Fatalf("active connections after disconnect = %v, want 0", disconnectedFields["active_sse_connections"])
|
||||
}
|
||||
if _, ok := disconnectedFields["lifetime_ms"]; !ok {
|
||||
t.Fatalf("missing lifetime_ms field: %v", disconnectedFields)
|
||||
}
|
||||
if got := hub.OnlineCount(); got != 0 {
|
||||
t.Fatalf("online connection count = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user