Files
VLoop/backend/internal/http/router_test.go
huanghaosheng 101f46f927 feat(api): 接进程 ctx 并停止启动异步链路
API 只装配 HTTP 入口。SetRouter 增加 ctx,删除 Outbox 轮询、Timeline 消费者与三个通知消费者的启动,改调 StartNotificationSubscriber。

SSEHub 记录进程 ctx。ctx 结束时 SSEHandler 主动断开。Shutdown 只关空闲连接、不取消在途请求,而 SSE 响应永不结束。少了这条路径,每次停机都要耗满 10 秒超时。

cmd/main 改用 signal.NotifyContext 与 http.Server。ListenAndServe 放进 goroutine,主协程等信号或启动失败,再以 10 秒上界 Shutdown,超时才 Close 兜底。

router_test 适配新签名,并新增用例守住四条通知路由仍注册。
2026-11-08 14:44:32 +08:00

108 lines
3.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package http
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"feedsystem_video_go/internal/config"
mqrabbit "feedsystem_video_go/internal/middleware/rabbitmq"
"github.com/gin-gonic/gin"
)
func doGet(t *testing.T, r *gin.Engine, path string) (int, map[string]any) {
t.Helper()
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
var body map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("%s: cannot parse body %q: %v", path, w.Body.String(), err)
}
return w.Code, body
}
func newRouterForTest(t *testing.T, rmq *mqrabbit.RabbitMQ) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
return SetRouter(context.Background(), nil, nil, rmq)
}
// 通知路由属于 API 进程:消费者搬到 Worker 之后,SSE 与列表/已读接口必须还在。
// 这条回归挡的是"搬家时顺手把整个 notification 域一起删掉"。
func TestRouter_NotificationRoutesRegistered(t *testing.T) {
r := newRouterForTest(t, nil)
want := []string{
"GET /notification/stream",
"POST /notification/list",
"POST /notification/markRead",
"POST /notification/unreadCount",
}
registered := make(map[string]bool, len(want))
for _, route := range r.Routes() {
registered[route.Method+" "+route.Path] = true
}
for _, route := range want {
if !registered[route] {
t.Errorf("route %q is not registered", route)
}
}
}
// 这是 /readyz 存在的全部意义所在,也是最容易被后人"顺手合并"掉的不变式:
// MQ 断连时 /healthz 必须仍然是 200,否则容器编排会在 broker 故障期间反复重启
// 仍然健康的实例,把"异步能力降级"放大成"整站不可用"。
func TestReadyz_MQDisabled_HealthzStaysOK(t *testing.T) {
r := newRouterForTest(t, nil)
code, body := doGet(t, r, "/healthz")
if code != http.StatusOK {
t.Fatalf("/healthz must stay 200 regardless of MQ state, got %d (%v)", code, body)
}
code, body = doGet(t, r, "/readyz")
if code != http.StatusServiceUnavailable {
t.Fatalf("/readyz must be 503 when MQ is not connected, got %d (%v)", code, body)
}
if body["mq_enabled"] != false || body["mq_connected"] != false {
t.Fatalf("disabled MQ must report mq_enabled=false, mq_connected=false: %v", body)
}
}
// "已启用但当前断开"必须与"根本没启用"可区分——两者的处置动作完全不同。
//
// 注意本用例约需 5 秒:SetRouter 末尾的启动期 EnsureTopology 有 5 秒超时
// (避免连接恰在启动时断开把 API 启动挂住),而这里的管理器连不上,
// 因此会等满这 5 秒。这 5 秒本身就是该护栏生效的证据,不要为此改短生产超时。
func TestReadyz_MQEnabledButDisconnected_IsDistinguishable(t *testing.T) {
// 指向必然连不上的端口:管理器会持续重连,当前状态即"已启用、未连接"。
mgr := mqrabbit.NewRabbitMQLazy(&config.RabbitMQConfig{
Host: "127.0.0.1", Port: 1, Username: "u", Password: "p",
})
if mgr == nil {
t.Fatal("lazy manager must not be nil for a valid config")
}
t.Cleanup(func() { _ = mgr.Close() })
r := newRouterForTest(t, mgr)
if code, _ := doGet(t, r, "/healthz"); code != http.StatusOK {
t.Fatalf("/healthz must stay 200 while MQ is down, got %d", code)
}
code, body := doGet(t, r, "/readyz")
if code != http.StatusServiceUnavailable {
t.Fatalf("/readyz must be 503 while disconnected, got %d (%v)", code, body)
}
if body["mq_enabled"] != true {
t.Fatalf("mq_enabled must distinguish disabled from disconnected: %v", body)
}
if body["mq_reconnects"] != float64(0) {
t.Fatalf("a manager that never connected must report 0 reconnects: %v", body)
}
}