72 lines
2.0 KiB
Go
72 lines
2.0 KiB
Go
package response
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"go-sms/internal/pkg/errors"
|
|
)
|
|
|
|
// do 执行 handler 并解析 JSON。
|
|
func do(t *testing.T, handler func(c *gin.Context)) (int, map[string]any) {
|
|
t.Helper()
|
|
gin.SetMode(gin.TestMode)
|
|
w := httptest.NewRecorder()
|
|
c, _ := gin.CreateTestContext(w)
|
|
c.Request = httptest.NewRequest(http.MethodGet, "/t", nil)
|
|
handler(c)
|
|
var body map[string]any
|
|
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
|
return w.Code, body
|
|
}
|
|
|
|
// TestError_Blacklist 验收项:Error(c, codes.Blacklist) 返回
|
|
// {"code":"ISC:006","msg":"黑名单"}。
|
|
func TestError_Blacklist(t *testing.T) {
|
|
code, body := do(t, func(c *gin.Context) { Error(c, errors.Blacklist) })
|
|
if code != http.StatusForbidden {
|
|
t.Fatalf("HTTP 状态 = %d, 期望 403", code)
|
|
}
|
|
if body["code"] != "ISC:006" || body["msg"] != "黑名单" {
|
|
t.Fatalf("响应 = %v, 期望 {code:ISC:006, msg:黑名单}", body)
|
|
}
|
|
if _, has := body["data"]; has {
|
|
t.Error("错误响应不应包含 data 字段")
|
|
}
|
|
}
|
|
|
|
// TestSuccess 成功响应结构。
|
|
func TestSuccess(t *testing.T) {
|
|
code, body := do(t, func(c *gin.Context) { Success(c, gin.H{"id": 1}) })
|
|
if code != 200 || body["code"] != "ISC:000" || body["msg"] != "成功" {
|
|
t.Fatalf("Success 响应异常: %d %v", code, body)
|
|
}
|
|
data := body["data"].(map[string]any)
|
|
if data["id"] != float64(1) {
|
|
t.Errorf("data = %v", data)
|
|
}
|
|
}
|
|
|
|
// TestPage 分页结构。
|
|
func TestPage(t *testing.T) {
|
|
_, body := do(t, func(c *gin.Context) { Page(c, []int{1, 2}, 42, 3, 0) })
|
|
data := body["data"].(map[string]any)
|
|
if data["total"] != float64(42) || data["page"] != float64(3) || data["size"] != float64(20) {
|
|
t.Errorf("Page data = %v", data)
|
|
}
|
|
}
|
|
|
|
// TestErrorWithMsg 场景化消息。
|
|
func TestErrorWithMsg(t *testing.T) {
|
|
code, body := do(t, func(c *gin.Context) {
|
|
ErrorWithMsg(c, errors.InvalidParam, "mobile 不能为空")
|
|
})
|
|
if code != 400 || body["code"] != "ISC:400" || body["msg"] != "mobile 不能为空" {
|
|
t.Fatalf("ErrorWithMsg = %d %v", code, body)
|
|
}
|
|
}
|