Files
VLoop/backend/internal/worker/commentworker_integration_test.go
huanghaosheng 49fc17c445 feat(worker): 五个消费者改用 ConsumeLoop 分派重试与停泊
每个 worker 的 Run 只保留参数校验。消费循环统一由 rabbitmq.ConsumeLoop 驱动。
因此重试、停泊、Ack 的规则只有一份实现。

坏消息一律标记 rabbitmq.Permanent。因此解析失败与未知 action 立即停泊。
未知 action 不再被静默 Ack 丢弃。

notification worker 改按队列与 body.action 分派。重试回源会把 routing key
改写成队列名。因此按 routing key 判断会让第二次投递立即停泊。

验证:go test -count=1 ./... 全绿
2026-10-30 15:20:15 +08:00

162 lines
5.2 KiB
Go
Raw 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 worker
import (
"context"
"os"
"strings"
"testing"
"feedsystem_video_go/internal/middleware/rabbitmq"
"feedsystem_video_go/internal/video"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// 评论消费者"只写一次评论、不再碰热度"这条不变式只能在真实 MySQL 上验证:
// 判重落在唯一索引 (author_id, idempotency_key) 上,没有数据库就没有被测对象。
//
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
// go test -tags integration -count=1 ./internal/worker/
func newCommentWorkerTestDB(t *testing.T) *gorm.DB {
t.Helper()
dsn := os.Getenv("MYSQL_TEST_DSN")
if dsn == "" {
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
}
if strings.Contains(dsn, "clientFoundRows") {
t.Fatalf("测试 DSN 不能带 clientFoundRows:它会让 RowsAffected 判重失效")
}
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
t.Fatalf("connect mysql: %v", err)
}
if err := db.Migrator().DropTable(&video.Comment{}, &video.Video{}); err != nil {
t.Fatalf("drop tables: %v", err)
}
if err := db.AutoMigrate(&video.Video{}, &video.Comment{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return db
}
func seedCommentVideo(t *testing.T, db *gorm.DB) *video.Video {
t.Helper()
v := &video.Video{
AuthorID: 99,
Username: "owner",
Title: "t",
PlayURL: "p",
CoverURL: "c",
Popularity: 0,
}
if err := db.Create(v).Error; err != nil {
t.Fatalf("seed video: %v", err)
}
return v
}
// 同一条评论事件被投递两次(假失败 + 兜底 + 重投的必然结果),只能落一行,
// 数据库热度也只能加一次。
//
// 两个断言分别钉住两件不同的事:行数 = 1 证明唯一索引吸收了重复;热度 = 1
// (而不是 2)证明"加热度"与"插入评论"在同一个事务里、且以 created 为门控。
// 热度写在这里而不是 Redis,是因为 videos.popularity 与 comments 必须原子
// 提交——Redis 那条轨由 popularity 事件单独负责。
func TestCommentWorker_ApplyPublish_DuplicateEventWritesOneRow(t *testing.T) {
db := newCommentWorkerTestDB(t)
v := seedCommentVideo(t, db)
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), "comment.events")
evt := &rabbitmq.CommentEvent{
EventID: "evt-comment-1",
Action: "publish",
Username: "alice",
VideoID: v.ID,
AuthorID: 1,
Content: "好看",
}
for i := 0; i < 2; i++ {
if err := w.applyPublish(context.Background(), evt); err != nil {
t.Fatalf("第 %d 次 applyPublish: %v", i+1, err)
}
}
var count int64
if err := db.Model(&video.Comment{}).Where("video_id = ?", v.ID).Count(&count).Error; err != nil {
t.Fatalf("count comments: %v", err)
}
if count != 1 {
t.Fatalf("评论行数 = %d, want 1(event_id 相同的重复投递必须被判重吸收)", count)
}
var got video.Video
if err := db.First(&got, v.ID).Error; err != nil {
t.Fatalf("reload video: %v", err)
}
if got.Popularity != 1 {
t.Fatalf("popularity = %d, want 1(重复投递不得再加一次)", got.Popularity)
}
}
// event_id 为空(老版本消息/手工构造)时不能去重:没有键就无法判断重复,
// 插入 NULL 键是唯一正确选择——用空字符串会撞唯一索引,把所有后续评论都吃掉。
func TestCommentWorker_ApplyPublish_EmptyEventIDStillWrites(t *testing.T) {
db := newCommentWorkerTestDB(t)
v := seedCommentVideo(t, db)
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), "comment.events")
evt := &rabbitmq.CommentEvent{
Action: "publish",
Username: "alice",
VideoID: v.ID,
AuthorID: 1,
Content: "第一条",
}
if err := w.applyPublish(context.Background(), evt); err != nil {
t.Fatalf("applyPublish: %v", err)
}
var c video.Comment
if err := db.Where("video_id = ?", v.ID).First(&c).Error; err != nil {
t.Fatalf("load comment: %v", err)
}
if c.IdempotencyKey != nil {
t.Fatalf("IdempotencyKey = %q, want NULL", *c.IdempotencyKey)
}
}
// 删除事件重投两次:第二次是空操作,不是错误(否则会被当成故障送去停泊)。
func TestCommentWorker_ApplyDelete_DuplicateIsNoop(t *testing.T) {
db := newCommentWorkerTestDB(t)
v := seedCommentVideo(t, db)
repo := video.NewCommentRepository(db)
w := NewCommentWorker(nil, nil, repo, video.NewVideoRepository(db), "comment.events")
c := &video.Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x"}
if _, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 0); err != nil {
t.Fatalf("seed comment: %v", err)
}
evt := &rabbitmq.CommentEvent{EventID: "evt-del-1", Action: "delete", CommentID: c.ID}
for i := 0; i < 2; i++ {
if err := w.applyDelete(context.Background(), evt); err != nil {
t.Fatalf("第 %d 次 applyDelete: %v", i+1, err)
}
}
var count int64
if err := db.Model(&video.Comment{}).Where("id = ?", c.ID).Count(&count).Error; err != nil {
t.Fatalf("count: %v", err)
}
if count != 0 {
t.Fatalf("评论行数 = %d, want 0", count)
}
}