package queue import ( "context" "errors" "sync" "testing" "time" "github.com/IBM/sarama" "go.uber.org/zap" ) // mockDLQ 记录死信转投。 type mockDLQ struct { mu sync.Mutex sent []string // topic:key } func (m *mockDLQ) Send(topic string, key, value []byte) error { m.mu.Lock() defer m.mu.Unlock() m.sent = append(m.sent, topic+":"+string(key)) return nil } // newTestGroup 直接构造(绕过 broker 连接;wrap/gate 不依赖 Consumer 连接)。 func newTestGroup(maxRetry int, dlq DLQSender) *ConsumerGroup { g := &ConsumerGroup{log: zap.NewNop(), dlq: dlq, maxRetry: maxRetry, gate: make(chan struct{})} close(g.gate) return g } // TestWrap_RetryThenDeadLetter 验收:失败达上限转投 .dlq。 func TestWrap_RetryThenDeadLetter(t *testing.T) { dlq := &mockDLQ{} g := newTestGroup(3, dlq) msg := &sarama.ConsumerMessage{Topic: "t-dlq", Partition: 0, Offset: 7, Key: []byte("poison"), Value: []byte("payload-1")} boom := errors.New("biz fail") calls := 0 // 恒败 handler:一次 wrap 内同步重试 3 次,耗尽后转死信并返回 nil err := g.wrap(func(context.Context, *sarama.ConsumerMessage) error { calls++ return boom })(context.Background(), msg) if err != nil { t.Fatalf("重试耗尽应转死信返回 nil, 实际: %v", err) } if calls != 3 { t.Errorf("handler 调用次数 = %d, 期望 3", calls) } dlq.mu.Lock() defer dlq.mu.Unlock() if len(dlq.sent) != 1 || dlq.sent[0] != "t-dlq.dlq:poison" { t.Fatalf("死信记录 = %v, 期望 [t-dlq.dlq:poison]", dlq.sent) } } // TestWrap_SecondAttemptSucceeds 第二次尝试成功即不转投(瞬时故障自愈)。 func TestWrap_SecondAttemptSucceeds(t *testing.T) { dlq := &mockDLQ{} g := newTestGroup(3, dlq) msg := &sarama.ConsumerMessage{Topic: "t2", Partition: 0, Offset: 1} calls := 0 if err := g.wrap(func(context.Context, *sarama.ConsumerMessage) error { calls++ if calls < 2 { return errors.New("transient") } return nil })(context.Background(), msg); err != nil { t.Fatalf("瞬时失败应重试成功: %v", err) } if calls != 2 || len(dlq.sent) != 0 { t.Errorf("calls=%d dlq=%d, 期望 2 次成功且无死信", calls, len(dlq.sent)) } } // TestPauseResumeGate 暂停/恢复门语义。 func TestPauseResumeGate(t *testing.T) { g := newTestGroup(3, nil) ctx := context.Background() if g.Paused() { t.Fatal("初始应为恢复态") } if err := g.waitGate(ctx); err != nil { t.Fatal(err) } g.Pause() if !g.Paused() { t.Fatal("Pause 后应为暂停态") } // 暂停中 waitGate 阻塞,ctx 取消可释放 cctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() if err := g.waitGate(cctx); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("暂停中应阻塞至 ctx 超时, 实际: %v", err) } g.Resume() if g.Paused() { t.Fatal("Resume 后应为恢复态") } if err := g.waitGate(ctx); err != nil { t.Fatal(err) } // 幂等:重复 Pause/Resume 不 panic g.Resume() g.Pause() g.Pause() g.Resume() } // TestDeadLetterValue 死信载荷含元信息与原值。 func TestDeadLetterValue(t *testing.T) { m := &sarama.ConsumerMessage{Value: []byte("BODY")} v := deadLetterValue(m, errors.New("x"), 3) if string(v[:3]) != "dlq" || string(v[len(v)-4:]) != "BODY" { t.Fatalf("死信载荷 = %q", v) } }