Files

104 lines
3.0 KiB
Go

package v1
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/model/entity"
"go-sms/internal/service/account"
)
// newTestRouter 内存库 + v1 路由。
func newTestRouter(t *testing.T) (*gin.Engine, *gorm.DB) {
t.Helper()
gin.SetMode(gin.TestMode)
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&entity.AccountUser{}, &entity.AccountConfig{}, &entity.AccountBalanceLog{}); err != nil {
t.Fatal(err)
}
r := gin.New()
Register(r.Group("/api/v1"), Deps{Account: account.NewService(db, account.BcryptMinCost)})
return r, db
}
func postJSON(r *gin.Engine, path string, body any) *httptest.ResponseRecorder {
raw, _ := json.Marshal(body)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(raw))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
return w
}
// TestAPI_CreateAccount 验收:POST /api/v1/accounts 创建成功,库内记录正确。
func TestAPI_CreateAccount(t *testing.T) {
r, db := newTestRouter(t)
w := postJSON(r, "/api/v1/accounts", map[string]any{
"username": "api-cust", "password": "secret66", "role": "customer",
"business": 1, "credit_balance": 500,
})
if w.Code != http.StatusOK {
t.Fatalf("状态码 = %d, body=%s", w.Code, w.Body.String())
}
var resp struct {
Code string `json:"code"`
Data struct {
ID int64 `json:"id"`
} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if resp.Code != "ISC:000" || resp.Data.ID == 0 {
t.Fatalf("响应 = %s", w.Body.String())
}
// DB 记录:密码哈希非明文 + 配置行存在
var u entity.AccountUser
if err := db.First(&u, resp.Data.ID).Error; err != nil {
t.Fatal(err)
}
if u.PasswordHash == "secret66" || !account.VerifyPassword(u.PasswordHash, "secret66") {
t.Fatalf("密码未 bcrypt: %q", u.PasswordHash)
}
var n int64
db.Model(&entity.AccountConfig{}).Where("account_id = ?", u.ID).Count(&n)
if n != 1 {
t.Fatalf("配置行 = %d", n)
}
}
// TestAPI_CreateAccount_Duplicate 重复创建返回 ISC:400。
func TestAPI_CreateAccount_Duplicate(t *testing.T) {
r, _ := newTestRouter(t)
body := map[string]any{"username": "dup", "password": "secret66", "role": "customer", "business": 1}
if w := postJSON(r, "/api/v1/accounts", body); w.Code != 200 {
t.Fatalf("首次创建应 200, got %d", w.Code)
}
w := postJSON(r, "/api/v1/accounts", body)
if w.Code != http.StatusBadRequest {
t.Fatalf("重复创建应 400, got %d", w.Code)
}
if !bytes.Contains(w.Body.Bytes(), []byte("ISC:400")) {
t.Fatalf("响应应含 ISC:400: %s", w.Body.String())
}
}
// TestAPI_CreateAccount_BadPayload 参数缺失 400。
func TestAPI_CreateAccount_BadPayload(t *testing.T) {
r, _ := newTestRouter(t)
w := postJSON(r, "/api/v1/accounts", map[string]any{"username": "x"}) // 缺 password/role/business
if w.Code != http.StatusBadRequest {
t.Fatalf("缺参应 400, got %d", w.Code)
}
}