test(rabbitmq): 补充连接代状态机与拓扑声明回归测试
该包此前没有任何测试文件。新增 15 个无需 broker 的单元测试(用 fakeConn 替身驱动 连接代状态机)与 2 个集成测试(//go:build integration,需真实 broker)。 重点覆盖两类"看起来修好了、实际仍会永久挂起"的缺陷: - install / markDown 忘记唤醒等待者——症状与原始缺陷无法区分,极难定位; - Session 的代令牌与 channel 不配对——消费者会拿着旧 channel 等在新代上。 其余覆盖:退避的指数增长/上限/抖动、Close 幂等且能唤醒等待者、重复 install 与 markDown 不得 panic(重复 close 会杀进程)、拓扑去重与 Topology() 返回副本、 声明顺序以及每个业务队列都必须带 x-dead-letter-exchange(防止重构静默丢掉 P0-3 的死信链路)、nil 管理器各方法不得 panic(defer rmq.Close() 在 rmq == nil 时成立)。 集成测试按需 SKIP:未设置 RABBITMQ_TEST_RESTART_CMD / RABBITMQ_TEST_DELETE_QUEUE_CMD 时跳过,两者分别对应"MQ 重启后自愈"与"连接健康但队列被删"。 实施中该测试抓到一处真实错误:DLX 断言最初写成"恰好 2 次队列声明",实测为 4 次 ——每个拓扑还会声明自己的 <queue>.dlx。
This commit is contained in:
266
backend/internal/middleware/rabbitmq/integration_test.go
Normal file
266
backend/internal/middleware/rabbitmq/integration_test.go
Normal file
@@ -0,0 +1,266 @@
|
||||
//go:build integration
|
||||
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/config"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// 这些用例需要真实 broker,因此用 integration 构建标签隔离:
|
||||
//
|
||||
// docker compose up -d rabbitmq
|
||||
// go test -tags integration -count=1 -timeout 300s -v ./internal/middleware/rabbitmq/
|
||||
//
|
||||
// 环境变量:
|
||||
//
|
||||
// RABBITMQ_TEST_URL 默认 amqp://guest:guest@127.0.0.1:5672/
|
||||
// RABBITMQ_TEST_RESTART_CMD 重启 broker 的命令(如 "docker compose restart rabbitmq")。
|
||||
// 未设置时跳过"重启恢复"用例——无法模拟重启就没有验证价值。
|
||||
// RABBITMQ_TEST_DELETE_QUEUE_CMD
|
||||
// 删除指定队列的命令模板,%s 会被替换为队列名。
|
||||
// 如:docker compose exec -T rabbitmq rabbitmqctl delete_queue %s
|
||||
func integrationTestManager(t *testing.T) (*RabbitMQ, config.RabbitMQConfig) {
|
||||
t.Helper()
|
||||
|
||||
raw := os.Getenv("RABBITMQ_TEST_URL")
|
||||
if raw == "" {
|
||||
raw = "amqp://guest:guest@127.0.0.1:5672/"
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("bad RABBITMQ_TEST_URL %q: %v", raw, err)
|
||||
}
|
||||
port := 5672
|
||||
if u.Port() != "" {
|
||||
if port, err = strconv.Atoi(u.Port()); err != nil {
|
||||
t.Fatalf("bad port in RABBITMQ_TEST_URL: %v", err)
|
||||
}
|
||||
}
|
||||
cfg := config.RabbitMQConfig{Host: u.Hostname(), Port: port}
|
||||
if u.User != nil {
|
||||
cfg.Username = u.User.Username()
|
||||
cfg.Password, _ = u.User.Password()
|
||||
}
|
||||
|
||||
// 测试用更激进的退避,避免等待时间过长
|
||||
opts := ReconnectOptions{
|
||||
MinBackoff: 200 * time.Millisecond,
|
||||
MaxBackoff: 2 * time.Second,
|
||||
Jitter: 0.1,
|
||||
DialTimeout: 3 * time.Second,
|
||||
}
|
||||
mgr, err := newManager(&cfg, opts, true)
|
||||
if err != nil {
|
||||
t.Fatalf("cannot connect to broker at %s: %v", raw, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
return mgr, cfg
|
||||
}
|
||||
|
||||
func randSuffix(t *testing.T) string {
|
||||
t.Helper()
|
||||
b := make([]byte, 6)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
t.Fatalf("rand: %v", err)
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// TestIntegration_ConsumerRecoversAfterBrokerRestart 是 P0-2 的核心验收用例:
|
||||
//
|
||||
// broker 重启后,消费者必须在退避窗口内自动恢复消费,且不需要人工重启进程。
|
||||
//
|
||||
// 修复前的行为:conn 永久 closed,conn.Channel() 永远返回 ErrClosed,
|
||||
// 消费者每 5 秒刷一行日志、永不恢复——本用例会一直等到超时并失败。
|
||||
func TestIntegration_ConsumerRecoversAfterBrokerRestart(t *testing.T) {
|
||||
restartCmd := os.Getenv("RABBITMQ_TEST_RESTART_CMD")
|
||||
if restartCmd == "" {
|
||||
t.Skip("RABBITMQ_TEST_RESTART_CMD not set: cannot simulate a broker restart")
|
||||
}
|
||||
|
||||
mgr, _ := integrationTestManager(t)
|
||||
suffix := randSuffix(t)
|
||||
topo := Topology{Exchange: "p0-2.test.events", Queue: "p0-2.test." + suffix, BindingKey: "p0-2.test.*"}
|
||||
mgr.RegisterTopology(topo)
|
||||
if err := mgr.EnsureTopology(context.Background()); err != nil {
|
||||
t.Fatalf("EnsureTopology: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if sess, err := mgr.Session(context.Background()); err == nil {
|
||||
_, _ = sess.Ch.QueueDelete(topo.Queue, false, false, false)
|
||||
_ = sess.Ch.Close()
|
||||
}
|
||||
})
|
||||
|
||||
received := make(chan string, 64)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go RunConsumer(ctx, mgr, "integration-consumer", 10, func(ch *amqp.Channel) error {
|
||||
msgs, err := ch.Consume(topo.Queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case m, ok := <-msgs:
|
||||
if !ok {
|
||||
return fmt.Errorf("deliveries closed")
|
||||
}
|
||||
received <- string(m.Body)
|
||||
_ = m.Ack(false)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 基线:重启前必须能正常消费
|
||||
publishAndExpect(t, mgr, topo, received, "before-restart")
|
||||
|
||||
// —— 制造故障:重启 broker ——
|
||||
genBefore := mgr.Stats().Generation
|
||||
t.Logf("restarting broker: %s", restartCmd)
|
||||
if out, err := exec.Command("sh", "-c", restartCmd).CombinedOutput(); err != nil {
|
||||
t.Fatalf("restart command failed: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// —— 必须在退避窗口内自愈 ——
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
for {
|
||||
if mgr.Stats().Generation > genBefore {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("P0-2: consumer did not reconnect within 90s (generation stuck at %d)", genBefore)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
t.Logf("reconnected: generation=%d reconnects=%d", mgr.Stats().Generation, mgr.Stats().Reconnects)
|
||||
|
||||
// 恢复后必须真的能继续消费(不只是日志好看)
|
||||
publishAndExpect(t, mgr, topo, received, "after-restart")
|
||||
}
|
||||
|
||||
// TestIntegration_TopologyIsRedeclaredAfterQueueDeleted 覆盖报告未提及的第二种卡死模式:
|
||||
// 连接始终健康,但队列没了。此时永远不会触发连接重连,
|
||||
// 只有"channel 级异常 → 重放拓扑"这条路能救回来。
|
||||
func TestIntegration_TopologyIsRedeclaredAfterQueueDeleted(t *testing.T) {
|
||||
deleteCmd := os.Getenv("RABBITMQ_TEST_DELETE_QUEUE_CMD")
|
||||
if deleteCmd == "" {
|
||||
t.Skip("RABBITMQ_TEST_DELETE_QUEUE_CMD not set: cannot simulate topology loss")
|
||||
}
|
||||
|
||||
mgr, _ := integrationTestManager(t)
|
||||
suffix := randSuffix(t)
|
||||
topo := Topology{Exchange: "p0-2.test.events", Queue: "p0-2.topology." + suffix, BindingKey: "p0-2.test.*"}
|
||||
mgr.RegisterTopology(topo)
|
||||
if err := mgr.EnsureTopology(context.Background()); err != nil {
|
||||
t.Fatalf("EnsureTopology: %v", err)
|
||||
}
|
||||
|
||||
received := make(chan string, 64)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go RunConsumer(ctx, mgr, "integration-topology-consumer", 10, func(ch *amqp.Channel) error {
|
||||
msgs, err := ch.Consume(topo.Queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case m, ok := <-msgs:
|
||||
if !ok {
|
||||
return fmt.Errorf("deliveries closed")
|
||||
}
|
||||
received <- string(m.Body)
|
||||
_ = m.Ack(false)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
publishAndExpect(t, mgr, topo, received, "before-delete")
|
||||
|
||||
// —— 在连接健康的情况下删掉队列 ——
|
||||
genBefore := mgr.Stats().Generation
|
||||
cmd := fmt.Sprintf(deleteCmd, topo.Queue)
|
||||
t.Logf("deleting queue: %s", cmd)
|
||||
if out, err := exec.Command("sh", "-c", cmd).CombinedOutput(); err != nil {
|
||||
t.Fatalf("delete command failed: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// 删除队列会让 broker 取消消费者;连接本身仍然健康,
|
||||
// 因此修复后的行为是"重放拓扑 + 重新 Consume",而不是重连。
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
for {
|
||||
if err := mgr.EnsureTopology(context.Background()); err == nil {
|
||||
// 拓扑重放成功后,确认队列真的可以消费了
|
||||
if canConsume(t, mgr, topo, received, "after-delete") {
|
||||
break
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("P0-2: consumer did not recover after queue deletion (generation=%d, was %d)",
|
||||
mgr.Stats().Generation, genBefore)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func publishAndExpect(t *testing.T, mgr *RabbitMQ, topo Topology, received <-chan string, payload string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := mgr.PublishJSON(ctx, topo.Exchange, "p0-2.test.msg", map[string]string{"payload": payload}); err != nil {
|
||||
t.Fatalf("PublishJSON(%s): %v", payload, err)
|
||||
}
|
||||
select {
|
||||
case got := <-received:
|
||||
var env map[string]string
|
||||
if err := json.Unmarshal([]byte(got), &env); err != nil {
|
||||
t.Fatalf("unmarshal %q: %v", got, err)
|
||||
}
|
||||
if env["payload"] != payload {
|
||||
t.Fatalf("payload mismatch: want %q, got %q", payload, env["payload"])
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatalf("P0-2: message %q was never consumed", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func canConsume(t *testing.T, mgr *RabbitMQ, topo Topology, received <-chan string, payload string) bool {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := mgr.PublishJSON(ctx, topo.Exchange, "p0-2.test.msg", map[string]string{"payload": payload}); err != nil {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case <-received:
|
||||
return true
|
||||
case <-time.After(5 * time.Second):
|
||||
// 消费掉可能残留的旧消息,避免影响后续判定
|
||||
select {
|
||||
case <-received:
|
||||
default:
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user