//go:build integration package worker import ( "context" "errors" "testing" "feedsystem_video_go/internal/middleware/rabbitmq" "feedsystem_video_go/internal/video" "gorm.io/gorm" ) // 这两个 publisher 永远失败,用来迫使 CommentService 走"直写数据库"的兜底路径。 // 它模拟的是 P0-4 的起点:发布返回 error,但消息其实已经到了 broker。 type failingCommentPublisher struct{} func (failingCommentPublisher) Publish(context.Context, rabbitmq.CommentEvent) error { return errors.New("mq publish failed") } func (failingCommentPublisher) Delete(context.Context, uint, string) error { return errors.New("mq publish failed") } // P0-4 的原始缺陷是"兜底直写一次 + 消费者再写一次",结果是两条评论、双倍热度。 // 这个用例把两条路径接起来跑:先让服务层兜底写入,再让同一个意图键的事件到达 // worker。断言收敛到一行评论、热度恰为 1。 // // 行数 = 1 证明唯一索引 (author_id, idempotency_key) 吸收了第二次插入; // 热度 = 1(而不是 2)证明"加热度"与"插评论"同事务、且以 created 为门控。 // 只跑其中一侧都发现不了这个缺陷——这正是它必须写成端到端用例的原因。 func TestP0_4_FallbackAndWorkerConvergeToOneComment(t *testing.T) { db := newCommentWorkerTestDB(t) ctx := context.Background() v := seedCommentVideo(t, db) commentRepo := video.NewCommentRepository(db) videoRepo := video.NewVideoRepository(db) // cache 传 nil:热榜是 best-effort 派生数据,本用例只断言 DB 侧的收敛。 svc := video.NewCommentService(commentRepo, videoRepo, nil, failingCommentPublisher{}) intentKey := "converge-intent-0001" comment := &video.Comment{ Username: "alice", VideoID: v.ID, AuthorID: 7, Content: "好看", IdempotencyKey: &intentKey, } if err := svc.Publish(ctx, comment); err != nil { t.Fatalf("publish(两条事件都失败,应走兜底): %v", err) } if got := countComments(t, db, v.ID); got != 1 { t.Fatalf("兜底之后 comments = %d, want 1", got) } // 消息其实已到 broker,稍后由消费者处理同一个意图键。 w := NewCommentWorker(nil, nil, commentRepo, videoRepo, nil, rabbitmq.CommentQueue) evt := &rabbitmq.CommentEvent{ EventID: intentKey, Action: "publish", Username: "alice", VideoID: v.ID, AuthorID: 7, Content: "好看", } if err := w.applyPublish(ctx, evt); err != nil { t.Fatalf("applyPublish: %v", err) } if got := countComments(t, db, v.ID); got != 1 { t.Fatalf("消费者处理后 comments = %d, want 1(兜底与消费端必须收敛到同一行)", got) } var popularity int64 if err := db.Model(&video.Video{}).Where("id = ?", v.ID).Select("popularity").Scan(&popularity).Error; err != nil { t.Fatalf("read popularity: %v", err) } if popularity != 1 { t.Fatalf("popularity = %d, want 1(重复插入不得重复加热度)", popularity) } } func countComments(t *testing.T, db *gorm.DB, videoID uint) int64 { t.Helper() var got int64 if err := db.Model(&video.Comment{}).Where("video_id = ?", videoID).Count(&got).Error; err != nil { t.Fatalf("count comments: %v", err) } return got }