Files
VLoop/backend/internal/social/handler_test.go
huanghaosheng f658b7e76e fix(social): 关注与取关改为幂等写入
SocialRepository.Follow 和 Unfollow 返回本次是否真的写入。判重交给唯一索引 idx_social_follower_vlogger。

因此重复关注和重复取关返回 200。重复请求不再落成 500。

缓存失效与通知只在真的变更时发生。自关注返回 400。响应体新增 created 与 deleted 字段。

SocialWorker 的调用只适配新签名,职责不变。删除它由后续提交完成。

验证:go build ./... 通过,go test -count=1 ./internal/social/... ./internal/worker/... 全绿。
2026-11-11 16:18:49 +08:00

86 lines
2.4 KiB
Go
Raw Permalink 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.
package social
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func newTestHandler(t *testing.T) (*SocialHandler, *fakeStore) {
t.Helper()
gin.SetMode(gin.TestMode)
store := newFakeStore()
notifier := &fakeNotifier{}
return NewSocialHandler(newTestService(store, fakeAccounts{}, notifier)), store
}
func postSocial(t *testing.T, h *SocialHandler, accountID uint, action, body string) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/social/"+action, strings.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
c.Set("accountID", accountID)
if action == "follow" {
h.Follow(c)
} else {
h.Unfollow(c)
}
return w
}
func TestSocialHandler_Follow_SelfReturnsBadRequest(t *testing.T) {
h, _ := newTestHandler(t)
w := postSocial(t, h, 1, "follow", `{"vlogger_id":1}`)
if w.Code != http.StatusBadRequest {
t.Fatalf("自关注状态码 = %d,想要 %d", w.Code, http.StatusBadRequest)
}
if !strings.Contains(w.Body.String(), "can not follow self") {
t.Fatalf("响应体 = %s,想要包含 can not follow self", w.Body.String())
}
}
func TestSocialHandler_Follow_DuplicateReturnsOK(t *testing.T) {
h, store := newTestHandler(t)
store.rows[[2]uint{1, 2}] = true
w := postSocial(t, h, 1, "follow", `{"vlogger_id":2}`)
if w.Code != http.StatusOK {
t.Fatalf("重复关注状态码 = %d,想要 %d", w.Code, http.StatusOK)
}
var resp struct {
Message string `json:"message"`
Created bool `json:"created"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("解析响应体失败: %v", err)
}
if resp.Message != "followed" || resp.Created {
t.Fatalf("重复关注响应 = %+v,想要 message=followed created=false", resp)
}
}
func TestSocialHandler_Unfollow_DuplicateReturnsOK(t *testing.T) {
h, _ := newTestHandler(t)
w := postSocial(t, h, 1, "unfollow", `{"vlogger_id":2}`)
if w.Code != http.StatusOK {
t.Fatalf("重复取关状态码 = %d,想要 %d", w.Code, http.StatusOK)
}
var resp struct {
Message string `json:"message"`
Deleted bool `json:"deleted"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("解析响应体失败: %v", err)
}
if resp.Message != "unfollowed" || resp.Deleted {
t.Fatalf("重复取关响应 = %+v,想要 message=unfollowed deleted=false", resp)
}
}