Files
VLoop/backend/internal/middleware/rabbitmq/integration_test.go
huanghaosheng ea134d6d71 test(rabbitmq): 集成测试的故障模拟命令兼容 Windows
两个集成用例原先用 exec.Command("sh", "-c", …) 执行 RABBITMQ_TEST_RESTART_CMD 与
RABBITMQ_TEST_DELETE_QUEUE_CMD,但 Windows 上 sh 不在 PATH,用例必然失败——而这套
故障模拟正是 P0-2 的核心验收手段,必须在开发者机器上也能跑。

改为按 runtime.GOOS 选择 shell(Windows 用 cmd /c,其余用 sh -c)。
2026-10-14 14:37:27 +08:00

278 lines
8.6 KiB
Go
Raw Permalink 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.
//go:build integration
package rabbitmq
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"os"
"os/exec"
"runtime"
"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
}
// runShell 执行由环境变量提供的"模拟故障"命令(重启 broker / 删除队列)。
// 这些命令在 Windows 开发机与 Unix CI 上都要能跑,因此按 GOOS 选择 shell——
// 硬编码 "sh -c" 会让本用例在 Windows 上直接失败。
func runShell(cmdline string) ([]byte, error) {
if runtime.GOOS == "windows" {
return exec.Command("cmd", "/c", cmdline).CombinedOutput()
}
return exec.Command("sh", "-c", cmdline).CombinedOutput()
}
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 := runShell(restartCmd); 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 := runShell(cmd); 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
}
}