Files
VLoop/backend/internal/middleware/rabbitmq/rabbitmq_test.go

451 lines
12 KiB
Go
Raw Normal View History

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")
}
}