每个 worker 的 Run 只保留参数校验。消费循环统一由 rabbitmq.ConsumeLoop 驱动。 因此重试、停泊、Ack 的规则只有一份实现。 坏消息一律标记 rabbitmq.Permanent。因此解析失败与未知 action 立即停泊。 未知 action 不再被静默 Ack 丢弃。 notification worker 改按队列与 body.action 分派。重试回源会把 routing key 改写成队列名。因此按 routing key 判断会让第二次投递立即停泊。 验证:go test -count=1 ./... 全绿
67 lines
2.3 KiB
Go
67 lines
2.3 KiB
Go
package worker
|
||
|
||
import (
|
||
"context"
|
||
"testing"
|
||
|
||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||
|
||
amqp "github.com/rabbitmq/amqp091-go"
|
||
)
|
||
|
||
// 分派依据必须是队列 + body 里的 action。
|
||
//
|
||
// 重试链路回源时会把 routing key 改写成队列名(`like.like` → `notification.like`)。
|
||
// 若按 routing key 判断事件类型,第二次投递就会变成"未知事件"并被立即停泊,
|
||
// 重试预算白丢,而用户只会觉得"通知丢了"。
|
||
//
|
||
// 这些用例停在 Permanent 判断之前,不需要数据库。
|
||
func TestNotificationWorker_RejectsWrongActionAsPermanent(t *testing.T) {
|
||
w := NewNotificationWorker(nil, nil, nil, rabbitmq.NotificationLikeQueue, nil)
|
||
d := amqp.Delivery{Body: []byte(`{"action":"follow"}`), RoutingKey: rabbitmq.LikeLikeRK}
|
||
|
||
err := w.process(context.Background(), d)
|
||
if err == nil {
|
||
t.Fatal("队列 notification.like 收到 action=follow 时必须报错,否则会被当成正常事件处理")
|
||
}
|
||
if !rabbitmq.IsPermanent(err) {
|
||
t.Fatalf("err = %v, want permanent(坏消息重投多少次都是坏的)", err)
|
||
}
|
||
}
|
||
|
||
func TestNotificationWorker_RejectsUnknownQueueAsPermanent(t *testing.T) {
|
||
w := NewNotificationWorker(nil, nil, nil, "some.other.queue", nil)
|
||
d := amqp.Delivery{Body: []byte(`{"action":"like"}`)}
|
||
|
||
err := w.process(context.Background(), d)
|
||
if err == nil {
|
||
t.Fatal("未登记的队列必须报错:继续处理会用错的通知类型写库")
|
||
}
|
||
if !rabbitmq.IsPermanent(err) {
|
||
t.Fatalf("err = %v, want permanent", err)
|
||
}
|
||
}
|
||
|
||
func TestNotificationWorker_RejectsEmptyBodyAsPermanent(t *testing.T) {
|
||
w := NewNotificationWorker(nil, nil, nil, rabbitmq.NotificationLikeQueue, nil)
|
||
|
||
err := w.process(context.Background(), amqp.Delivery{})
|
||
if err == nil {
|
||
t.Fatal("空消息体必须报错")
|
||
}
|
||
if !rabbitmq.IsPermanent(err) {
|
||
t.Fatalf("err = %v, want permanent", err)
|
||
}
|
||
}
|
||
|
||
// 空消息体与非法 action 都是"不可重试"的,但要确认判定顺序:
|
||
// 队列未知时先报队列错误,避免把配置问题误判成消息问题。
|
||
func TestNotificationWorker_UnknownQueueCheckedBeforeAction(t *testing.T) {
|
||
w := NewNotificationWorker(nil, nil, nil, "some.other.queue", nil)
|
||
|
||
err := w.process(context.Background(), amqp.Delivery{Body: []byte(`not json`)})
|
||
if err == nil || !rabbitmq.IsPermanent(err) {
|
||
t.Fatalf("err = %v, want permanent", err)
|
||
}
|
||
}
|