Files

86 lines
2.4 KiB
Go
Raw Permalink Normal View History

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)
}
}