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
|
||||
}
|
||||
}
|
||||
450
backend/internal/middleware/rabbitmq/rabbitmq_test.go
Normal file
450
backend/internal/middleware/rabbitmq/rabbitmq_test.go
Normal file
@@ -0,0 +1,450 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// —— 测试替身 ——
|
||||
|
||||
// fakeConn 实现 connection 接口,让连接代状态机可以脱离 broker 被测试。
|
||||
// 它不参与任何网络 I/O:Channel() 只在"健康"时返回 (nil, nil)。
|
||||
type fakeConn struct {
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (f *fakeConn) Channel() (*amqp.Channel, error) {
|
||||
if f.IsClosed() {
|
||||
return nil, amqp.ErrClosed
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeConn) NotifyClose(c chan *amqp.Error) chan *amqp.Error { return c }
|
||||
|
||||
func (f *fakeConn) IsClosed() bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.closed
|
||||
}
|
||||
|
||||
func (f *fakeConn) Close() error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.closed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeConn) markClosed() {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.closed = true
|
||||
}
|
||||
|
||||
// newTestManager 构造一个不建立任何连接的裸管理器(只用于状态机测试)。
|
||||
func newTestManager() *RabbitMQ {
|
||||
return &RabbitMQ{
|
||||
opts: DefaultReconnectOptions(),
|
||||
gen: make(chan struct{}),
|
||||
ready: make(chan struct{}),
|
||||
closed: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func isClosed(ch chan struct{}) bool {
|
||||
select {
|
||||
case <-ch:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// —— 退避策略 ——
|
||||
|
||||
func TestNextBackoff_ExponentialCappedJittered(t *testing.T) {
|
||||
opts := ReconnectOptions{MinBackoff: 500 * time.Millisecond, MaxBackoff: 4 * time.Second, Jitter: 0.2}
|
||||
|
||||
d := opts.MinBackoff
|
||||
for i := 0; i < 20; i++ {
|
||||
d = nextBackoff(d, opts)
|
||||
if d <= 0 {
|
||||
t.Fatalf("backoff must stay positive, got %v", d)
|
||||
}
|
||||
// 抖动上限:不超过 MaxBackoff * (1+Jitter)
|
||||
if max := time.Duration(float64(opts.MaxBackoff) * (1 + opts.Jitter)); d > max {
|
||||
t.Fatalf("backoff %v exceeds jittered cap %v", d, max)
|
||||
}
|
||||
}
|
||||
if d < opts.MaxBackoff/2 {
|
||||
t.Fatalf("backoff must converge to MaxBackoff, got %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextBackoff_NoJitterIsExact(t *testing.T) {
|
||||
opts := ReconnectOptions{MinBackoff: time.Second, MaxBackoff: 8 * time.Second}
|
||||
want := []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second, 8 * time.Second}
|
||||
|
||||
d := opts.MinBackoff
|
||||
for i, w := range want {
|
||||
d = nextBackoff(d, opts)
|
||||
if d != w {
|
||||
t.Fatalf("step %d: want %v, got %v", i, w, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// —— 连接代状态机(P0-2 的核心) ——
|
||||
|
||||
// 断连期间 WaitReady 必须"阻塞",而不是空转返回——这是 96 行/分钟日志噪声的根源。
|
||||
func TestWaitReady_BlocksWhileDisconnected_ReturnsWhenConnected(t *testing.T) {
|
||||
r := newTestManager()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := r.WaitReady(ctx); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("disconnected: want DeadlineExceeded, got %v", err)
|
||||
}
|
||||
|
||||
r.install(&fakeConn{})
|
||||
if err := r.WaitReady(context.Background()); err != nil {
|
||||
t.Fatalf("connected: want nil, got %v", err)
|
||||
}
|
||||
|
||||
r.markDown()
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel2()
|
||||
if err := r.WaitReady(ctx2); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("after markDown: want DeadlineExceeded, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 最危险的一类回归:install 忘记唤醒等待者 → 消费者永久挂起,
|
||||
// 症状与"根本没修"无法区分。
|
||||
func TestInstall_WakesConsumersBlockedInWaitReady(t *testing.T) {
|
||||
r := newTestManager()
|
||||
r.markDown()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- r.WaitReady(context.Background()) }()
|
||||
time.Sleep(20 * time.Millisecond) // 让 goroutine 进入 select
|
||||
|
||||
r.install(&fakeConn{})
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("waiter must be woken by install: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("P0-2: install must wake consumers blocked in WaitReady (they would hang forever)")
|
||||
}
|
||||
}
|
||||
|
||||
// markDown 必须结束当前代(唤醒持有旧 channel 的消费者)并广播状态变化。
|
||||
func TestMarkDown_ClosesGenerationAndBroadcastsStateChange(t *testing.T) {
|
||||
r := newTestManager()
|
||||
r.install(&fakeConn{})
|
||||
|
||||
r.mu.Lock()
|
||||
genBefore, readyBefore := r.gen, r.ready
|
||||
r.mu.Unlock()
|
||||
|
||||
r.markDown()
|
||||
|
||||
if !isClosed(genBefore) {
|
||||
t.Fatal("P0-2: markDown must close the current generation to wake consumers")
|
||||
}
|
||||
r.mu.Lock()
|
||||
genAfter, readyAfter := r.gen, r.ready
|
||||
r.mu.Unlock()
|
||||
|
||||
if genAfter == genBefore {
|
||||
t.Fatal("markDown must install a fresh generation channel")
|
||||
}
|
||||
if !isClosed(readyBefore) {
|
||||
t.Fatal("markDown must broadcast a state change so WaitReady re-evaluates")
|
||||
}
|
||||
if readyAfter == readyBefore {
|
||||
t.Fatal("markDown must install a fresh ready channel")
|
||||
}
|
||||
}
|
||||
|
||||
// 代令牌必须与 channel 配对:连接代结束时 sess.Done 必须关闭,
|
||||
// 否则消费者无法区分"连接级失效"与"channel 级异常"。
|
||||
func TestSession_GenerationTokenClosesWhenItsConnectionEnds(t *testing.T) {
|
||||
r := newTestManager()
|
||||
r.install(&fakeConn{})
|
||||
|
||||
sess, err := r.Session(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Session: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-sess.Done:
|
||||
t.Fatal("generation token must not be closed while the connection is alive")
|
||||
default:
|
||||
}
|
||||
|
||||
r.markDown()
|
||||
|
||||
select {
|
||||
case <-sess.Done:
|
||||
default:
|
||||
t.Fatal("P0-2: session token must close when its own connection generation ends")
|
||||
}
|
||||
}
|
||||
|
||||
// 连接已失效但 manager 尚未感知(NotifyClose 还没派发)时,
|
||||
// Session 不允许返回一个死连接上的 channel,必须等到下一代。
|
||||
func TestSession_WaitsForNextGenerationWhenConnectionIsAlreadyClosed(t *testing.T) {
|
||||
r := newTestManager()
|
||||
conn := &fakeConn{}
|
||||
r.install(conn)
|
||||
conn.markClosed() // manager 尚未 markDown
|
||||
|
||||
got := make(chan *Session, 1)
|
||||
go func() {
|
||||
s, err := r.Session(context.Background())
|
||||
if err != nil {
|
||||
got <- nil
|
||||
return
|
||||
}
|
||||
got <- s
|
||||
}()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
select {
|
||||
case <-got:
|
||||
t.Fatal("Session must not hand out a channel from a dead connection")
|
||||
default:
|
||||
}
|
||||
|
||||
// 新的一代到来:Session 必须恢复
|
||||
r.markDown()
|
||||
r.install(&fakeConn{})
|
||||
|
||||
select {
|
||||
case s := <-got:
|
||||
if s == nil {
|
||||
t.Fatal("Session must succeed on the next generation")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("P0-2: Session must resume once a new generation is installed")
|
||||
}
|
||||
}
|
||||
|
||||
// 重复 close 会 panic 并杀掉进程:install / markDown 必须可重入。
|
||||
func TestInstallAndMarkDown_DoNotDoubleCloseChannels(t *testing.T) {
|
||||
r := newTestManager()
|
||||
|
||||
r.install(&fakeConn{})
|
||||
r.install(&fakeConn{}) // 重复 install 不得 panic
|
||||
r.markDown()
|
||||
r.markDown() // 重复 markDown 不得 panic
|
||||
r.install(&fakeConn{})
|
||||
}
|
||||
|
||||
func TestClose_IsIdempotentAndUnblocksWaiters(t *testing.T) {
|
||||
r := newTestManager()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- r.WaitReady(context.Background()) }()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
|
||||
if err := r.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
t.Fatalf("Close must be idempotent: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, ErrManagerClosed) {
|
||||
t.Fatalf("want ErrManagerClosed, got %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close must unblock WaitReady")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewChannel_RequiresActiveConnection(t *testing.T) {
|
||||
r := newTestManager()
|
||||
|
||||
if _, err := r.NewChannel(); !errors.Is(err, ErrNotConnected) {
|
||||
t.Fatalf("disconnected: want ErrNotConnected, got %v", err)
|
||||
}
|
||||
|
||||
r.install(&fakeConn{})
|
||||
if _, err := r.NewChannel(); err != nil {
|
||||
t.Fatalf("connected: want nil, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilManager_DoesNotPanic(t *testing.T) {
|
||||
var r *RabbitMQ
|
||||
|
||||
if r.Healthy() {
|
||||
t.Fatal("nil manager must not report healthy")
|
||||
}
|
||||
if (r.Stats() != Stats{}) {
|
||||
t.Fatal("nil manager must return zero stats")
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
t.Fatalf("nil manager Close must be a no-op, got %v", err)
|
||||
}
|
||||
if err := r.PublishJSON(context.Background(), "e", "k", nil); err == nil {
|
||||
t.Fatal("nil manager PublishJSON must return an error")
|
||||
}
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "q", BindingKey: "k"}) // 不得 panic
|
||||
}
|
||||
|
||||
// —— 拓扑登记 ——
|
||||
|
||||
func TestRegisterTopology_DedupAndValidate(t *testing.T) {
|
||||
r := newTestManager()
|
||||
good := Topology{Exchange: "e", Queue: "q", BindingKey: "k"}
|
||||
|
||||
r.RegisterTopology(good, good)
|
||||
if got := r.Stats().Topology; got != 1 {
|
||||
t.Fatalf("duplicate topology must be deduped, got %d", got)
|
||||
}
|
||||
|
||||
r.RegisterTopology(Topology{Exchange: "", Queue: "q", BindingKey: "k"})
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "", BindingKey: "k"})
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "q", BindingKey: ""})
|
||||
if got := r.Stats().Topology; got != 1 {
|
||||
t.Fatalf("invalid topology must be ignored, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTopology_ReturnsCopyNotInternalSlice(t *testing.T) {
|
||||
r := newTestManager()
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "q", BindingKey: "k"})
|
||||
|
||||
got := r.Topology()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("want 1 topology, got %d", len(got))
|
||||
}
|
||||
got[0].Exchange = "mutated"
|
||||
|
||||
if again := r.Topology(); again[0].Exchange != "e" {
|
||||
t.Fatal("Topology() must return a copy; internal state was mutated")
|
||||
}
|
||||
}
|
||||
|
||||
// —— 拓扑声明(假 declarer,无需 broker) ——
|
||||
|
||||
type queueDecl struct {
|
||||
name string
|
||||
args amqp.Table
|
||||
}
|
||||
|
||||
type fakeDeclarer struct {
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
queues []queueDecl
|
||||
}
|
||||
|
||||
func (f *fakeDeclarer) ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, "exchange:"+name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeDeclarer) QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args amqp.Table) (amqp.Queue, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, "queue:"+name)
|
||||
f.queues = append(f.queues, queueDecl{name: name, args: args})
|
||||
return amqp.Queue{Name: name}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDeclarer) QueueBind(name, key, exchange string, noWait bool, args amqp.Table) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, "bind:"+name+"<-"+exchange+"/"+key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// queueArgs 返回指定队列被声明时使用的参数。
|
||||
func (f *fakeDeclarer) queueArgs(name string) (amqp.Table, bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for _, q := range f.queues {
|
||||
if q.name == name {
|
||||
return q.args, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func TestDeclareTopologies_OrderAndDeadLetterExchange(t *testing.T) {
|
||||
f := &fakeDeclarer{}
|
||||
err := DeclareTopologies(f, []Topology{
|
||||
{Exchange: "like.events", Queue: "like.events", BindingKey: "like.*"},
|
||||
{Exchange: "comment.events", Queue: "comment.events", BindingKey: "comment.*"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DeclareTopologies: %v", err)
|
||||
}
|
||||
|
||||
joined := strings.Join(f.calls, " ")
|
||||
// 交换机必须先于队列,队列必须先于绑定
|
||||
if !strings.HasPrefix(joined, "exchange:like.events queue:like.events bind:like.events<-like.events/like.*") {
|
||||
t.Fatalf("unexpected declare order: %v", f.calls)
|
||||
}
|
||||
|
||||
// 业务队列必须带 DLX 参数,否则 P0-3 的死信链路会静默失效
|
||||
for _, q := range []string{"like.events", "comment.events"} {
|
||||
args, ok := f.queueArgs(q)
|
||||
if !ok {
|
||||
t.Fatalf("queue %s was never declared", q)
|
||||
}
|
||||
if args == nil || args["x-dead-letter-exchange"] != DLXExchange {
|
||||
t.Fatalf("queue %s missing dead-letter exchange (P0-3 wiring regression): %v", q, args)
|
||||
}
|
||||
// 死信队列自身不能再带 DLX(否则会形成环)
|
||||
dlxArgs, ok := f.queueArgs(q + ".dlx")
|
||||
if !ok {
|
||||
t.Fatalf("dead-letter queue %s.dlx was never declared", q)
|
||||
}
|
||||
if len(dlxArgs) != 0 {
|
||||
t.Fatalf("dead-letter queue %s.dlx must not carry a DLX itself: %v", q, dlxArgs)
|
||||
}
|
||||
}
|
||||
|
||||
// 死信队列必须绑定到死信交换机
|
||||
if !strings.Contains(joined, "bind:like.events.dlx<-dlx.events/#") {
|
||||
t.Fatalf("dead-letter queue not bound to DLX exchange: %v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclareTopology_ValidatesInput(t *testing.T) {
|
||||
f := &fakeDeclarer{}
|
||||
|
||||
if err := DeclareTopology(nil, Topology{Exchange: "e", Queue: "q", BindingKey: "k"}); err == nil {
|
||||
t.Fatal("nil declarer must be rejected")
|
||||
}
|
||||
if err := DeclareTopology(f, Topology{Exchange: "", Queue: "q", BindingKey: "k"}); err == nil {
|
||||
t.Fatal("empty exchange must be rejected")
|
||||
}
|
||||
// 类型化的 nil channel 无法被接口判断拦住,因此入口保留了自己的检查
|
||||
if err := DeclareTopic(nil, "e", "q", "k"); err == nil {
|
||||
t.Fatal("DeclareTopic(nil channel) must be rejected, not panic")
|
||||
}
|
||||
// 合法输入必须通过,并经 fakeDeclarer 观察到声明动作
|
||||
if err := DeclareTopic(nil, "e", "q", "k"); err == nil {
|
||||
t.Fatal("DeclareTopic must validate before touching the channel")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user