package video import ( "context" "errors" "testing" "time" "feedsystem_video_go/internal/apierror" "feedsystem_video_go/internal/middleware/rabbitmq" rediscache "feedsystem_video_go/internal/middleware/redis" "github.com/alicebob/miniredis/v2" ) type fakeVideoExister struct { exists bool err error } func (f *fakeVideoExister) IsExist(_ context.Context, _ uint) (bool, error) { return f.exists, f.err } type fakeCommentStore struct { createCalls int created bool createErr error lastComment *Comment lastDelta int64 // 删除路径:byID 是 GetByID 的返回,deleteRow/deleted 是 DeleteWithPopularity 的返回。 byID *Comment deleteCalls int deleteRow *Comment deleted bool deleteErr error findNames []string ids map[string]uint findErr error mentions []Mention mentionsErr error } func (f *fakeCommentStore) CreateIdempotentWithPopularity(_ context.Context, c *Comment, delta int64) (bool, error) { f.createCalls++ f.lastComment = c f.lastDelta = delta return f.created, f.createErr } func (f *fakeCommentStore) GetByID(_ context.Context, _ uint) (*Comment, error) { return f.byID, nil } func (f *fakeCommentStore) DeleteWithPopularity(_ context.Context, _ uint) (*Comment, bool, error) { f.deleteCalls++ return f.deleteRow, f.deleted, f.deleteErr } func (f *fakeCommentStore) GetAllComments(_ context.Context, _ uint) ([]Comment, error) { return nil, nil } func (f *fakeCommentStore) CreateMentions(_ context.Context, m []Mention) error { f.mentions = append(f.mentions, m...) return f.mentionsErr } func (f *fakeCommentStore) FindAccountIDs(_ context.Context, names []string) (map[string]uint, error) { f.findNames = names return f.ids, f.findErr } type fakeCommentPublisher struct { events []rabbitmq.CommentEvent pubErr error delErr error } func (f *fakeCommentPublisher) Publish(_ context.Context, evt rabbitmq.CommentEvent) error { f.events = append(f.events, evt) return f.pubErr } func (f *fakeCommentPublisher) Delete(_ context.Context, _ uint, _ string) error { return f.delErr } type commentFixture struct { svc *CommentService store *fakeCommentStore comments *fakeCommentPublisher cache *rediscache.Client mr *miniredis.Miniredis } func newCommentFixture(t *testing.T) *commentFixture { t.Helper() store := &fakeCommentStore{created: true, ids: map[string]uint{}} comments := &fakeCommentPublisher{} cache, mr := newTestCache(t) svc := NewCommentService(store, &fakeVideoExister{exists: true}, cache, comments) return &commentFixture{svc: svc, store: store, comments: comments, cache: cache, mr: mr} } // hotScoreAt 返回某个视频在某一分钟桶里的分数;桶不存在时返回 0。 func (f *commentFixture) hotScoreAt(t *testing.T, videoID uint, at time.Time) float64 { t.Helper() score, err := f.mr.ZScore(f.cache.Key("hot:video:1m:%s", HotBucket(at)), HotMember(videoID)) if err != nil { return 0 } return score } func newComment(videoID, authorID uint, content string) *Comment { return &Comment{VideoID: videoID, AuthorID: authorID, Username: "alice", Content: content} } // 评论事件发出去之后,API 绝不能再写一次库:否则"MQ 正常"的常规路径 // 会稳定产生两条评论——这正是 P0-4 的核心症状之一。 func TestCommentService_Publish_Enqueued_SkipsLocalWriteAndHot(t *testing.T) { f := newCommentFixture(t) c := newComment(7, 1, "hello") if err := f.svc.Publish(context.Background(), c); err != nil { t.Fatalf("Publish: %v", err) } if f.store.createCalls != 0 { t.Fatalf("store.CreateIdempotentWithPopularity 调用 %d 次, want 0", f.store.createCalls) } if len(f.comments.events) != 1 || f.comments.events[0].EventID == "" { t.Fatalf("评论事件 = %+v, want 1 条且带 event_id", f.comments.events) } // 热榜由 worker 在事务提交后写:API 提前加一次就是双计。 if got := f.hotScoreAt(t, 7, c.CreatedAt); got != 0 { t.Fatalf("入队成功的路径不得改热榜,实际分数 %v", got) } } // 评论事件发不出去时才直写,且直写必须带着同一个意图键—— // 这样"消息其实进了队列、稍后被消费"与"API 已经直写"能收敛成一行。 func TestCommentService_Publish_CommentPublishFails_WritesLocallyWithIntentKey(t *testing.T) { f := newCommentFixture(t) f.comments.pubErr = errors.New("broker down") c := newComment(7, 1, "hello") if err := f.svc.Publish(context.Background(), c); err != nil { t.Fatalf("Publish: %v", err) } if f.store.createCalls != 1 { t.Fatalf("兜底写入 %d 次, want 1", f.store.createCalls) } written := f.store.lastComment.IdempotencyKey if written == nil || *written == "" { t.Fatal("兜底写入的评论必须带上意图键,否则 worker 侧无法判重") } if f.store.lastDelta != 1 { t.Fatalf("热度增量 = %d, want 1", f.store.lastDelta) } // 事务真的插入了行,热榜才 +1,且落在评论的 created_at 分钟。 if got := f.hotScoreAt(t, 7, f.store.lastComment.CreatedAt); got != 1 { t.Fatalf("兜底路径热榜分数 = %v, want 1", got) } } // 兜底写入命中唯一索引(created=false)说明这一行早就存在,计数与热榜 // 都已经被那次写驱动过:此时再加一次就是重复。 func TestCommentService_Publish_FallbackDedupeHit_DoesNotTouchHot(t *testing.T) { f := newCommentFixture(t) f.comments.pubErr = errors.New("broker down") f.store.created = false c := newComment(7, 1, "hello") if err := f.svc.Publish(context.Background(), c); err != nil { t.Fatalf("Publish: %v", err) } if f.store.createCalls != 1 { t.Fatalf("兜底写入 %d 次, want 1", f.store.createCalls) } if got := f.hotScoreAt(t, 7, c.CreatedAt); got != 0 { t.Fatalf("判重命中时热榜不得变化,实际分数 %v", got) } } // 删除入队成功时 API 不碰库:热度回退由 worker 在同一事务后做。 func TestCommentService_Delete_Enqueued_SkipsLocalWrite(t *testing.T) { f := newCommentFixture(t) f.store.byID = &Comment{ID: 5, VideoID: 7, AuthorID: 1} if err := f.svc.Delete(context.Background(), 5, 1); err != nil { t.Fatalf("Delete: %v", err) } if f.store.deleteCalls != 0 { t.Fatalf("删除已入队,不得直写库,实际调用 %d 次", f.store.deleteCalls) } } // 删除事件发不出去时走兜底:删行与热度 -1 都发生,且 -1 落回评论创建的那一分钟 // (P2-20:旧实现只删行、不减热度)。 func TestCommentService_Delete_FallbackRevertsHotAtOriginalBucket(t *testing.T) { f := newCommentFixture(t) f.comments.delErr = errors.New("broker down") createdAt := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Minute) f.store.byID = &Comment{ID: 5, VideoID: 7, AuthorID: 1} f.store.deleted = true f.store.deleteRow = &Comment{ID: 5, VideoID: 7, AuthorID: 1, CreatedAt: createdAt} if err := f.svc.Delete(context.Background(), 5, 1); err != nil { t.Fatalf("Delete: %v", err) } if f.store.deleteCalls != 1 { t.Fatalf("兜底删除 %d 次, want 1", f.store.deleteCalls) } if got := f.hotScoreAt(t, 7, createdAt); got != -1 { t.Fatalf("原桶分数 = %v, want -1(回退必须落回创建那一分钟)", got) } } // 重复删除是空操作:deleted=false 时不能再减一次热度。 func TestCommentService_Delete_RepeatIsNoop(t *testing.T) { f := newCommentFixture(t) f.comments.delErr = errors.New("broker down") f.store.byID = &Comment{ID: 5, VideoID: 7, AuthorID: 1} f.store.deleted = false if err := f.svc.Delete(context.Background(), 5, 1); err != nil { t.Fatalf("Delete: %v", err) } if got := f.hotScoreAt(t, 7, time.Now()); got != 0 { t.Fatalf("重复删除不得改热榜,实际分数 %v", got) } } // 同一个意图键重复提交是正常语义(客户端重试),不能报错、也不能新增行。 func TestCommentService_Publish_RepeatSameIntent_DoesNotError(t *testing.T) { f := newCommentFixture(t) f.comments.pubErr = errors.New("broker down") f.store.created = false // 第二次:唯一索引命中 first := newComment(7, 1, "hello") key := "intent-repeat-1" first.IdempotencyKey = &key if err := f.svc.Publish(context.Background(), first); err != nil { t.Fatalf("首次 Publish: %v", err) } second := newComment(7, 1, "hello") second.IdempotencyKey = &key if err := f.svc.Publish(context.Background(), second); err != nil { t.Fatalf("重复 Publish 不应报错: %v", err) } if f.store.createCalls != 2 { t.Fatalf("两次都应尝试写入(由唯一索引判重),实际 %d 次", f.store.createCalls) } } // 非法的 request_id 是客户端错误,必须落 400 而不是 500。 func TestCommentService_Publish_InvalidRequestID(t *testing.T) { f := newCommentFixture(t) bad := "bad key with spaces" c := newComment(7, 1, "hello") c.IdempotencyKey = &bad err := f.svc.Publish(context.Background(), c) if err == nil { t.Fatal("非法 request_id 必须报错") } if got := apierror.ClassifyHTTPStatus(err); got != 400 { t.Fatalf("HTTP 状态 = %d, want 400 (err=%v)", got, err) } if f.store.createCalls != 0 { t.Fatal("非法键不得写入任何一行") } } // 提及通知的去重键必须绑定到同一次意图,且只查一次库、跳过自己。 func TestCommentService_NotifyMentions_DedupeKeyBoundToIntent(t *testing.T) { f := newCommentFixture(t) f.store.ids = map[string]uint{"alice": 1, "bob": 2} c := newComment(7, 1, "@alice @bob @bob hi") key := "intent-mention-1" c.IdempotencyKey = &key if err := f.svc.Publish(context.Background(), c); err != nil { t.Fatalf("Publish: %v", err) } // 自己(alice)不进查询;@bob 出现两次只查一次。 if len(f.store.findNames) != 1 || f.store.findNames[0] != "bob" { t.Fatalf("用户名去重后应只查 [bob],实际 %v", f.store.findNames) } if len(f.store.mentions) != 1 { t.Fatalf("提及通知 = %+v, want 1 条(alice 是自己)", f.store.mentions) } m := f.store.mentions[0] if m.RecipientID != 2 || m.SenderID != 1 || m.TargetID != 7 { t.Fatalf("提及通知字段 = %+v", m) } if want := "mention:" + key + ":2"; m.DedupeKey != want { t.Fatalf("去重键 = %q, want %q", m.DedupeKey, want) } }