重构:完成架构一致性整改与生命周期收口

This commit is contained in:
Christ committed 2026-08-18 14:05:08 +08:00
1 parent 55904cc409
commit 9eb6be2875
344 files changed
+15961 -13926

No files matched your search

+15 -15
View File
@@ -10,7 +10,7 @@ import (
automationapp "xianyu-go/internal/application/automation"
)
// mountAccountTasks 负责mount账号任务列表相关处理。
// mountAccountTasks 封装mount账号任务列表业务协调。
func (s *Server) mountAccountTasks(r chi.Router) {
r.Get("/api/account-tasks/{cid}", s.getAccountTaskSettings)
r.Put("/api/account-tasks/{cid}", s.updateAccountTaskSettings)
@@ -18,15 +18,15 @@ func (s *Server) mountAccountTasks(r chi.Router) {
r.Post("/api/account-tasks/{cid}/run", s.runAccountTask)
}
// getAccountTaskSettings 负责get账号任务设置相关处理。
// getAccountTaskSettings 封装get账号任务设置业务协调。
func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
if !s.ownsAccount(r, cid) {
writeErr(w, http.StatusForbidden, "无权访问该账号")
return
}
// settings、err 保存settings、err,供当前处理流程使用
// settings、err 用于本次流程后续判断的settings、err
settings, err := s.accountTaskApplication().GetSettings(r.Context(), cid)
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取账号任务配置失败")
@@ -35,21 +35,21 @@ func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, newApplicationAccountTaskSettingsResponse(settings))
}
// updateAccountTaskSettings 负责update账号任务设置相关处理。
// updateAccountTaskSettings 封装update账号任务设置业务协调。
func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
if !s.ownsAccount(r, cid) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
// input 保存input,供当前处理流程使用
// input 用于本次流程后续判断的input
var input automationapp.AccountTaskSettings
if decodeJSON(r, &input) != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// stored、err 保存stored、err,供当前处理流程使用
// stored、err 用于本次流程后续判断的stored、err
input.CookieID = cid
// stored、err 保存应用服务规范化后的设置及写入错误。
stored, err := s.accountTaskApplication().UpdateSettings(r.Context(), input)
@@ -64,15 +64,15 @@ func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Reques
writeJSON(w, http.StatusOK, newApplicationAccountTaskSettingsResponse(stored))
}
// listAccountTaskRuns 负责list账号任务运行记录相关处理。
// listAccountTaskRuns 封装list账号任务运行记录业务协调。
func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
if !s.ownsAccount(r, cid) {
writeErr(w, http.StatusForbidden, "无权访问该账号")
return
}
// runs、err 保存runs、err,供当前处理流程使用
// runs、err 用于本次流程后续判断的runs、err
runs, err := s.accountTaskApplication().ListRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20))
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取任务记录失败")
@@ -81,9 +81,9 @@ func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, accountTaskRunsResponse{Runs: newApplicationAccountTaskRunResponses(runs)})
}
// runAccountTask 负责运行账号任务相关处理。
// runAccountTask 封装运行账号任务业务协调。
func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
if s.automation == nil {
writeErr(w, http.StatusServiceUnavailable, "自动化中心未启用")
@@ -93,13 +93,13 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
// input 保存input,供当前处理流程使用
// input 用于本次流程后续判断的input
var input accountTaskRunRequest
if decodeJSON(r, &input) != nil || (input.TaskType != automationapp.TaskAutoRate && input.TaskType != automationapp.TaskAutoPolish) {
writeErr(w, http.StatusBadRequest, "不支持的任务类型")
return
}
// summary、err 保存summary、err,供当前处理流程使用
// summary、err 用于本次流程后续判断的summary、err
summary, err := s.accountTaskApplication().Run(r.Context(), cid, input.TaskType)
if err != nil {
if errors.Is(err, automationapp.ErrUnavailable) {
+141 -141
View File
@@ -11,24 +11,24 @@ import (
// TestAdminListCookies 管理员列出所有账号。
func TestAdminListCookies(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/admin/cookies", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["id"] != "acc1" {
@@ -38,23 +38,23 @@ func TestAdminListCookies(t *testing.T) {
// TestAdminDeleteUser 删除其他用户。
func TestAdminDeleteUser(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
store.Users.Create(ctx, "user-del", "[email protected]", "pw")
// u 保存u,供当前处理流程使用
// u 用于本次流程后续判断的u
u, _ := store.Users.GetByUsername(ctx, "user-del")
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/admin/users/"+itoa(u.ID), nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -62,57 +62,57 @@ func TestAdminDeleteUser(t *testing.T) {
}
}
// TestAdminDeleteUserRevokesSessions 负责TestAdminDelete用户RevokesSessions相关处理。
// TestAdminDeleteUserRevokesSessions 封装TestAdminDelete用户RevokesSessions业务协调。
func TestAdminDeleteUserRevokesSessions(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.Users.Create(ctx, "session-del", "[email protected]", "pw"); err != nil {
t.Fatalf("create user: %v", err)
}
// u、err 保存u、err,供当前处理流程使用
// u、err 用于本次流程后续判断的u、err
u, err := store.Users.GetByUsername(ctx, "session-del")
if err != nil {
t.Fatalf("get user: %v", err)
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// userLogin 保存用户登录,供当前处理流程使用
// userLogin 用于本次流程后续判断的用户登录
userLogin := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"session-del","password":"pw"}`))
// userLoginRec 保存用户登录Rec,供当前处理流程使用
// userLoginRec 用于本次流程后续判断的用户登录Rec
userLoginRec := httptest.NewRecorder()
h.ServeHTTP(userLoginRec, userLogin)
if userLoginRec.Code != http.StatusOK || len(userLoginRec.Result().Cookies()) == 0 {
t.Fatalf("user login status=%d body=%s", userLoginRec.Code, userLoginRec.Body.String())
}
// userCookie 保存用户登录凭证,供当前处理流程使用
// userCookie 用于本次流程后续判断的用户登录凭证
userCookie := userLoginRec.Result().Cookies()[0]
// adminCookie 保存admin登录凭证,供当前处理流程使用
// adminCookie 用于本次流程后续判断的admin登录凭证
adminCookie := loginHelper(t, h)
// delReq 保存delReq,供当前处理流程使用
// delReq 用于本次流程后续判断的delReq
delReq := httptest.NewRequest(http.MethodDelete, "/admin/users/"+itoa(u.ID), nil)
delReq.AddCookie(adminCookie)
// delRec 保存delRec,供当前处理流程使用
// delRec 用于本次流程后续判断的delRec
delRec := httptest.NewRecorder()
h.ServeHTTP(delRec, delReq)
if delRec.Code != http.StatusOK {
t.Fatalf("delete status=%d body=%s", delRec.Code, delRec.Body.String())
}
// verifyReq 保存verifyReq,供当前处理流程使用
// verifyReq 用于本次流程后续判断的verifyReq
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(userCookie)
// verifyRec 保存verifyRec,供当前处理流程使用
// verifyRec 用于本次流程后续判断的verifyRec
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verify 保存verify,供当前处理流程使用
// verify 用于本次流程后续判断的verify
var verify map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(verifyRec.Body.Bytes(), &verify); err != nil {
t.Fatalf("decode verify: %v", err)
}
@@ -123,20 +123,20 @@ func TestAdminDeleteUserRevokesSessions(t *testing.T) {
// TestAdminDeleteUserSelf 不能删除自己 400。
func TestAdminDeleteUserSelf(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// admin 保存admin,供当前处理流程使用
// admin 用于本次流程后续判断的admin
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/admin/users/"+itoa(admin.ID), nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -146,18 +146,18 @@ func TestAdminDeleteUserSelf(t *testing.T) {
// TestAdminDeleteUserBadID 无效 ID 400。
func TestAdminDeleteUserBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/admin/users/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -167,28 +167,28 @@ func TestAdminDeleteUserBadID(t *testing.T) {
// TestAdminStatsWithOrders 带订单的统计。
func TestAdminStatsWithOrders(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id, order_status) VALUES ('s1','i1','acc1','2')`)
store.DB.ExecContext(ctx, `INSERT INTO cards (name, type, user_id) VALUES ('卡1','text',1)`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d", rec.Code)
}
// stats 保存stats,供当前处理流程使用
// stats 用于本次流程后续判断的stats
var stats map[string]any
json.Unmarshal(rec.Body.Bytes(), &stats)
if stats["total_orders"] != float64(1) || stats["total_cards"] != float64(1) {
@@ -198,26 +198,26 @@ func TestAdminStatsWithOrders(t *testing.T) {
// TestChangeAdminPassword 修改管理员密码成功。
func TestChangeAdminPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"current_password":"pw","new_password":"newpw123"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != true {
@@ -227,23 +227,23 @@ func TestChangeAdminPassword(t *testing.T) {
// TestChangeAdminPasswordWrongCurrent 当前密码错误。
func TestChangeAdminPasswordWrongCurrent(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"current_password":"wrong","new_password":"newpw123"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] == true {
@@ -253,18 +253,18 @@ func TestChangeAdminPasswordWrongCurrent(t *testing.T) {
// TestChangeAdminPasswordBadJSON 非法 JSON 400。
func TestChangeAdminPasswordBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -272,20 +272,20 @@ func TestChangeAdminPasswordBadJSON(t *testing.T) {
}
}
// TestChangeAdminPasswordShortNewPassword 负责TestChangeAdmin密码ShortNew密码相关处理。
// TestChangeAdminPasswordShortNewPassword 封装TestChangeAdmin密码ShortNew密码业务协调。
func TestChangeAdminPasswordShortNewPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(`{"current_password":"pw","new_password":"123"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -295,26 +295,26 @@ func TestChangeAdminPasswordShortNewPassword(t *testing.T) {
// TestChangeAdminPasswordNonAdmin 非 admin 403。
func TestChangeAdminPasswordNonAdmin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"username":"user2","password":"pw"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := rec.Result().Cookies()[0]
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodPost, "/change-admin-password", strings.NewReader(`{"current_password":"pw","new_password":"newpw123"}`))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusForbidden {
@@ -324,26 +324,26 @@ func TestChangeAdminPasswordNonAdmin(t *testing.T) {
// TestChangePassword 修改当前用户密码。
func TestChangePassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"current_password":"pw","new_password":"newpw123"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != true {
@@ -351,28 +351,28 @@ func TestChangePassword(t *testing.T) {
}
}
// TestChangePasswordRevokesCurrentSession 负责TestChange密码RevokesCurrent会话相关处理。
// TestChangePasswordRevokesCurrentSession 封装TestChange密码RevokesCurrent会话业务协调。
func TestChangePasswordRevokesCurrentSession(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(`{"current_password":"pw","new_password":"newpw123"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("change status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode change response: %v", err)
}
@@ -380,15 +380,15 @@ func TestChangePasswordRevokesCurrentSession(t *testing.T) {
t.Fatalf("change response should require relogin: %+v", res)
}
// verifyReq 保存verifyReq,供当前处理流程使用
// verifyReq 用于本次流程后续判断的verifyReq
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(cookie)
// verifyRec 保存verifyRec,供当前处理流程使用
// verifyRec 用于本次流程后续判断的verifyRec
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verify 保存verify,供当前处理流程使用
// verify 用于本次流程后续判断的verify
var verify map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(verifyRec.Body.Bytes(), &verify); err != nil {
t.Fatalf("decode verify: %v", err)
}
@@ -399,23 +399,23 @@ func TestChangePasswordRevokesCurrentSession(t *testing.T) {
// TestChangePasswordWrongCurrent 当前密码错误。
func TestChangePasswordWrongCurrent(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"current_password":"wrong","new_password":"newpw123"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] == true {
@@ -425,18 +425,18 @@ func TestChangePasswordWrongCurrent(t *testing.T) {
// TestChangePasswordBadJSON 非法 JSON 400。
func TestChangePasswordBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -444,20 +444,20 @@ func TestChangePasswordBadJSON(t *testing.T) {
}
}
// TestChangePasswordShortNewPassword 负责TestChange密码ShortNew密码相关处理。
// TestChangePasswordShortNewPassword 封装TestChange密码ShortNew密码业务协调。
func TestChangePasswordShortNewPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/change-password", strings.NewReader(`{"current_password":"pw","new_password":"123"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -467,20 +467,20 @@ func TestChangePasswordShortNewPassword(t *testing.T) {
// TestUpdateCredentialsBadUsername 用户名长度不足 400。
func TestUpdateCredentialsBadUsername(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"current_password":"pw","new_username":"ab"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -490,20 +490,20 @@ func TestUpdateCredentialsBadUsername(t *testing.T) {
// TestUpdateCredentialsMissingCurrentPassword 缺当前密码 400。
func TestUpdateCredentialsMissingCurrentPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"new_username":"newname"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -513,20 +513,20 @@ func TestUpdateCredentialsMissingCurrentPassword(t *testing.T) {
// TestUpdateCredentialsShortNewPassword 新密码过短 400。
func TestUpdateCredentialsShortNewPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"current_password":"pw","new_password":"123"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -536,20 +536,20 @@ func TestUpdateCredentialsShortNewPassword(t *testing.T) {
// TestUpdateCredentialsNothingChanged 用户名密码均未修改 400。
func TestUpdateCredentialsNothingChanged(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"current_password":"pw","new_username":"admin"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
+8 -8
View File
@@ -17,15 +17,15 @@ func (s *Server) mountAdminReal(r chi.Router) {
r.Get("/admin/stats", s.adminStats)
}
// adminListUsers 负责adminList用户列表相关处理。
// adminListUsers 封装adminList用户列表业务协调。
func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) {
// rows、err 保存rows、err,供当前处理流程使用
// rows、err 用于本次流程后续判断的rows、err
rows, err := s.applicationServiceSet().admin.ListUsers(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
var out []adminUserResponse
// row 表示当前遍历过程中的row
for _, row := range rows {
@@ -38,9 +38,9 @@ func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, out)
}
// adminDeleteUser 负责adminDelete用户相关处理。
// adminDeleteUser 封装adminDelete用户业务协调。
func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
// uid、err 保存uid、err,供当前处理流程使用
// uid、err 用于本次流程后续判断的uid、err
uid, err := strconv.ParseInt(chi.URLParam(r, "user_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效用户ID")
@@ -60,7 +60,7 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// adminListCookies 负责adminListCookies相关处理。
// adminListCookies 封装adminListCookies业务协调。
func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
// rows、err 保存应用服务返回的管理员账号摘要及查询错误。
rows, err := s.accountSummaryApplication().ListAdminSummaries(r.Context())
@@ -68,7 +68,7 @@ func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
var out []adminCookieResponse
// row 表示当前遍历过程中的row
for _, row := range rows {
@@ -81,7 +81,7 @@ func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, out)
}
// adminStats 负责adminStats相关处理。
// adminStats 封装adminStats业务协调。
func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) {
// stats 是管理员仪表盘的数据库聚合结果。
stats, err := s.applicationServiceSet().admin.Stats(r.Context())
+73 -73
View File
@@ -11,12 +11,12 @@ import (
"time"
)
// TestValidOrdersMatchesAnalyticsScope 负责Test有效订单列表MatchesAnalyticsScope相关处理。
// TestValidOrdersMatchesAnalyticsScope 封装Test有效订单列表MatchesAnalyticsScope业务协调。
func TestValidOrdersMatchesAnalyticsScope(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `
@@ -27,28 +27,28 @@ func TestValidOrdersMatchesAnalyticsScope(t *testing.T) {
`)
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_detail) VALUES ('acc1','item1','测试商品','{"pic_info":{"picUrl":"https://img.example/item.png"}}')`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-06-28&end_date=2026-06-28", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("analytics status=%d body=%s", rec.Code, rec.Body.String())
}
// analytics 保存analytics,供当前处理流程使用
// analytics 用于本次流程后续判断的analytics
var analytics struct {
RevenueStats struct {
TotalOrders int `json:"total_orders"`
TotalAmount float64 `json:"total_amount"`
} `json:"revenue_stats"`
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &analytics); err != nil {
t.Fatal(err)
}
@@ -56,27 +56,27 @@ func TestValidOrdersMatchesAnalyticsScope(t *testing.T) {
t.Fatalf("统计口径异常: %+v", analytics.RevenueStats)
}
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-06-28&end_date=2026-06-28", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("valid orders status=%d body=%s", rec2.Code, rec2.Body.String())
}
// valid 保存有效,供当前处理流程使用
// valid 用于本次流程后续判断的有效
var valid struct {
Orders []map[string]any `json:"orders"`
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec2.Body.Bytes(), &valid); err != nil {
t.Fatal(err)
}
if len(valid.Orders) != 1 {
t.Fatalf("有效订单明细数量应与统计订单数一致,got %d body=%s", len(valid.Orders), rec2.Body.String())
}
// order 保存订单,供当前处理流程使用
// order 用于本次流程后续判断的订单
order := valid.Orders[0]
if order["order_id"] != "ord-valid" || order["item_title"] != "测试商品" || !strings.Contains(order["item_image"].(string), "img.example") {
t.Fatalf("有效订单明细字段异常: %+v", order)
@@ -86,36 +86,36 @@ func TestValidOrdersMatchesAnalyticsScope(t *testing.T) {
}
}
// TestValidOrdersIncludesPaidAndReportsPagination 负责Test有效订单列表IncludesPaidAndReportsPagination相关处理。
// TestValidOrdersIncludesPaidAndReportsPagination 封装Test有效订单列表IncludesPaidAndReportsPagination业务协调。
func TestValidOrdersIncludesPaidAndReportsPagination(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,amount,order_status,cookie_id,created_at) VALUES
('paid-1','10','paid','acc1','2026-06-28 10:00:00'),
('paid-2','20','pending_ship','acc1','2026-06-28 11:00:00')`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-06-28&end_date=2026-06-28&page_size=1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// result 保存结果,供当前处理流程使用
// result 用于本次流程后续判断的结果
var result struct {
Orders []map[string]any `json:"orders"`
Total int `json:"total"`
Truncated bool `json:"truncated"`
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
@@ -124,24 +124,24 @@ func TestValidOrdersIncludesPaidAndReportsPagination(t *testing.T) {
}
}
// TestDashboardStatsAreAvailableAndScopedToCurrentUser 负责TestDashboardStatsAreAvailableAndScopedToCurrent用户相关处理。
// TestDashboardStatsAreAvailableAndScopedToCurrentUser 封装TestDashboardStatsAreAvailableAndScopedToCurrent用户业务协调。
func TestDashboardStatsAreAvailableAndScopedToCurrentUser(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
if // ok、err 保存ok、err,供当前处理流程使用
if // ok、err 用于本次流程后续判断的ok、err
ok, err := store.Users.Create(ctx, "member", "[email protected]", "pw"); err != nil || !ok {
t.Fatalf("create member: ok=%v err=%v", ok, err)
}
// member、err 保存member、err,供当前处理流程使用
// member、err 用于本次流程后续判断的member、err
member, err := store.Users.GetByUsername(ctx, "member")
if err != nil {
t.Fatal(err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.Cookies.Save(ctx, "member-acc", "unb=456", member.ID); err != nil {
t.Fatal(err)
}
@@ -153,29 +153,29 @@ func TestDashboardStatsAreAvailableAndScopedToCurrentUser(t *testing.T) {
_, _ = store.DB.ExecContext(ctx, `INSERT INTO cards (name,type,user_id) VALUES ('admin-card','text',1)`)
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,cookie_id,order_status) VALUES ('admin-order','acc1','completed')`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// loginReq 保存登录Req,供当前处理流程使用
// loginReq 用于本次流程后续判断的登录Req
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"member","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
// loginRec 用于本次流程后续判断的登录Rec
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
if loginRec.Code != http.StatusOK || len(loginRec.Result().Cookies()) == 0 {
t.Fatalf("login status=%d body=%s", loginRec.Code, loginRec.Body.String())
}
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/dashboard/stats", nil)
req.AddCookie(loginRec.Result().Cookies()[0])
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// stats 保存stats,供当前处理流程使用
// stats 用于本次流程后续判断的stats
var stats map[string]int64
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &stats); err != nil {
t.Fatal(err)
}
@@ -189,10 +189,10 @@ func TestDashboardStatsAreAvailableAndScopedToCurrentUser(t *testing.T) {
t.Fatalf("available_card_stock=%d want 2; stats=%+v", stats["available_card_stock"], stats)
}
// adminReq 保存adminReq,供当前处理流程使用
// adminReq 用于本次流程后续判断的adminReq
adminReq := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
adminReq.AddCookie(loginRec.Result().Cookies()[0])
// adminRec 保存adminRec,供当前处理流程使用
// adminRec 用于本次流程后续判断的adminRec
adminRec := httptest.NewRecorder()
h.ServeHTTP(adminRec, adminReq)
if adminRec.Code != http.StatusForbidden {
@@ -200,45 +200,45 @@ func TestDashboardStatsAreAvailableAndScopedToCurrentUser(t *testing.T) {
}
}
// TestAnalyticsIncludesLegacyNumericValidStatuses 负责TestAnalyticsIncludesLegacyNumeric有效Statuses相关处理。
// TestAnalyticsIncludesLegacyNumericValidStatuses 封装TestAnalyticsIncludesLegacyNumeric有效Statuses业务协调。
func TestAnalyticsIncludesLegacyNumericValidStatuses(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,amount,order_status,cookie_id,created_at)
VALUES ('legacy-shipped','8.50','3','acc1','2026-06-28 12:00:00')`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-06-28&end_date=2026-06-28", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// response 保存响应,供当前处理流程使用
// response 用于本次流程后续判断的响应
var response struct {
RevenueStats struct {
TotalOrders int `json:"total_orders"`
} `json:"revenue_stats"`
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response.RevenueStats.TotalOrders != 1 {
t.Fatalf("legacy numeric valid status was excluded: %+v", response)
}
// validReq 保存有效Req,供当前处理流程使用
// validReq 用于本次流程后续判断的有效Req
validReq := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-06-28&end_date=2026-06-28", nil)
validReq.AddCookie(cookie)
// validRec 保存有效Rec,供当前处理流程使用
// validRec 用于本次流程后续判断的有效Rec
validRec := httptest.NewRecorder()
h.ServeHTTP(validRec, validReq)
if !strings.Contains(validRec.Body.String(), `"order_status":"shipped"`) {
@@ -246,79 +246,79 @@ func TestAnalyticsIncludesLegacyNumericValidStatuses(t *testing.T) {
}
}
// TestAnalyticsCustomRangeDoesNotSilentlyDropDays 负责TestAnalyticsCustomRangeDoesNotSilentlyDropDays相关处理。
// TestAnalyticsCustomRangeDoesNotSilentlyDropDays 封装TestAnalyticsCustomRangeDoesNotSilentlyDropDays业务协调。
func TestAnalyticsCustomRangeDoesNotSilentlyDropDays(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
for // day 保存day,供当前处理流程使用
for // day 用于本次流程后续判断的day
day := 1; day <= 31; day++ {
// date 保存日期,供当前处理流程使用
// date 用于本次流程后续判断的日期
date := time.Date(2026, 1, day, 12, 0, 0, 0, time.UTC).Format("2006-01-02 15:04:05")
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,amount,order_status,cookie_id,created_at) VALUES (?,?,?,?,?)`, fmt.Sprintf("day-%02d", day), "1", "completed", "acc1", date)
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-01-01&end_date=2026-01-31", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// response 保存响应,供当前处理流程使用
// response 用于本次流程后续判断的响应
var response struct {
Daily []map[string]any `json:"daily_stats"`
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil || len(response.Daily) != 31 {
t.Fatalf("daily range len=%d err=%v body=%s", len(response.Daily), err, rec.Body.String())
}
}
// TestAnalyticsDateBoundaryConvertsLocalDayToUTC 负责TestAnalytics日期BoundaryConvertsLocalDayToUTC相关处理。
// TestAnalyticsDateBoundaryConvertsLocalDayToUTC 封装TestAnalytics日期BoundaryConvertsLocalDayToUTC业务协调。
func TestAnalyticsDateBoundaryConvertsLocalDayToUTC(t *testing.T) {
// previous 保存previous,供当前处理流程使用
// previous 用于本次流程后续判断的previous
previous := time.Local
time.Local = time.FixedZone("UTC+8", 8*60*60)
defer func() { time.Local = previous }()
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := analyticsDateBoundary("2026-06-28", false, time.Local); got != "2026-06-27 16:00:00" {
t.Fatalf("start boundary=%q", got)
}
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := analyticsDateBoundary("2026-06-28", true, time.Local); got != "2026-06-28 16:00:00" {
t.Fatalf("end boundary=%q", got)
}
}
// TestAnalyticsUsesBrowserTimezoneAndSkipsInvalidAmounts 负责TestAnalyticsUses浏览器TimezoneAndSkipsInvalidAmounts相关处理。
// TestAnalyticsUsesBrowserTimezoneAndSkipsInvalidAmounts 封装TestAnalyticsUses浏览器TimezoneAndSkipsInvalidAmounts业务协调。
func TestAnalyticsUsesBrowserTimezoneAndSkipsInvalidAmounts(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,amount,order_status,cookie_id,created_at) VALUES
('tz-valid','10.50','completed','acc1','2026-06-27 16:30:00'),
('tz-invalid','abc','completed','acc1','2026-06-27 17:00:00')`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-06-28&end_date=2026-06-28&timezone_offset_minutes=480", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// response 保存响应,供当前处理流程使用
// response 用于本次流程后续判断的响应
var response struct {
Revenue struct {
TotalOrders int `json:"total_orders"`
@@ -326,7 +326,7 @@ func TestAnalyticsUsesBrowserTimezoneAndSkipsInvalidAmounts(t *testing.T) {
} `json:"revenue_stats"`
Daily []map[string]any `json:"daily_stats"`
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
+1 -1
View File
@@ -134,7 +134,7 @@ func assertUnifiedAPIError(t *testing.T, handler http.Handler, method, path, bod
}
// response 是统一错误响应 DTO。
var response httpapi.ErrorResponse
// decodeErr 表示错误响应 JSON 反序列化失败的原因。
// decodeErr 记录当前操作失败原因响应 JSON 反序列化失败的原因。
if decodeErr := json.Unmarshal(rec.Body.Bytes(), &response); decodeErr != nil {
t.Fatalf("%s %s decode error: %v", method, path, decodeErr)
}
+61 -70
View File
@@ -2,6 +2,7 @@ package server
import (
"context"
"fmt"
"xianyu-go/internal/adapter"
accountapp "xianyu-go/internal/application/account"
@@ -99,6 +100,10 @@ type applicationServices struct {
admin *adminapp.Service
}
// emptyApplicationServices 是零值 Server 和隔离 handler 测试共享的只读空服务集合。
// 它不包含任何生产依赖,禁止写入;生产 Server 必须在 New 阶段注入完整集合。
var emptyApplicationServices = &applicationServices{accountLogin: &accountLoginService{}}
// ApplicationLifecycleComponents 返回 Server 装配的应用 worker 生命周期组件。
// 组件只暴露 Start/Close 端口,启动顺序与进程取消责任由 cmd 的协调器拥有。
func (s *Server) ApplicationLifecycleComponents() []lifecycleapp.NamedComponent {
@@ -143,19 +148,14 @@ func (s *Server) ApplicationLifecycleComponents() []lifecycleapp.NamedComponent
return components
}
// newApplicationServices 为指定 Server 装配全部应用服务实例。
func newApplicationServices(server *Server) *applicationServices {
// newApplicationServices 为指定 Server 装配全部应用服务实例,并把任何依赖构造错误交给上层启动流程处理。
func newApplicationServices(server *Server) (*applicationServices, error) {
// orderRepository 保存订单应用服务共享的基础设施适配器。
orderRepository := server.orderDependencies.NewOrderRepository()
// orderReconciliation 保存订单补偿写入应用 Port 的数据库适配器。
orderReconciliation := server.orderDependencies.NewOrderReconciliationRepository()
// orderRuntime 保存订单服务共享的运行时能力适配器。
orderRuntime := newServerOrderRuntime(server, orderReconciliation)
// orderReconciliationRecovery 将补偿扫描器的启动、取消和等待收口到订单应用边界。
orderReconciliationRecovery, orderReconciliationRecoveryErr := orderapp.NewReconciliationRecoveryCoordinator(server.systemDependencies.NewReconciliationService(server.Logger))
if orderReconciliationRecoveryErr != nil {
panic(orderReconciliationRecoveryErr)
}
// orderServices 保存应用层统一构造的订单业务服务集合。
orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, server.orderDependencies.NewOrderRefreshJobRepository(), refreshOrderChunkSize)
// orderRefreshRunner 是订单刷新后台 worker 与恢复扫描的生命周期拥有者。
@@ -176,7 +176,7 @@ func newApplicationServices(server *Server) *applicationServices {
},
)
if orderRefreshRunnerErr != nil {
panic(orderRefreshRunnerErr)
return nil, fmt.Errorf("构造订单刷新运行器失败: %w", orderRefreshRunnerErr)
}
// orderRefreshJobs 是订单刷新任务应用 facade,封装归属、租约和 worker 启动编排。
orderRefreshJobs, orderRefreshJobsErr := orderapp.NewRefreshJobService(
@@ -186,7 +186,7 @@ func newApplicationServices(server *Server) *applicationServices {
orderapp.RefreshJobServiceOptions{},
)
if orderRefreshJobsErr != nil {
panic(orderRefreshJobsErr)
return nil, fmt.Errorf("构造订单刷新应用服务失败: %w", orderRefreshJobsErr)
}
// accountProfile 保存账号资料刷新用例的构造结果。
// accountRepository 提供账号登录、资料摘要和删除共用的数据库适配器。
@@ -194,7 +194,7 @@ func newApplicationServices(server *Server) *applicationServices {
// platformCredentials 将账号凭证读取限制在消费者定义的只读应用端口。
platformCredentials, platformCredentialsErr := accountapp.NewPlatformCredentialService(accountRepository)
if platformCredentialsErr != nil {
panic(platformCredentialsErr)
return nil, fmt.Errorf("构造平台凭证服务失败: %w", platformCredentialsErr)
}
// cookieWriterFactory 将明文 Cookie 封装在 adapter 的请求范围实例中,Server 不持有凭证仓储。
cookieWriterFactory := func(cookies string) accountapp.CookieWriter {
@@ -209,7 +209,7 @@ func newApplicationServices(server *Server) *applicationServices {
// accountProfile 由应用层服务编排平台资料刷新与非敏感摘要持久化。
accountProfile, profileErr := accountapp.NewProfileService(accountRepository, adapter.NewAccountProfilePort(accountRepository, server.mtopClient, server.updateRunningCookie, sessionRecovery, server.Logger))
if profileErr != nil {
panic(profileErr)
return nil, fmt.Errorf("构造账号资料服务失败: %w", profileErr)
}
// accountLongLogin 由适配器承载平台调用、Cookie 快照合并和凭证写回。
accountLongLogin, longLoginErr := accountapp.NewLongLoginService(
@@ -217,7 +217,7 @@ func newApplicationServices(server *Server) *applicationServices {
adapter.NewLongLoginAdapter(accountRepository, server.longLoginClient, server.updateRunningCookie, server.Logger),
)
if longLoginErr != nil {
panic(longLoginErr)
return nil, fmt.Errorf("构造账号长登录服务失败: %w", longLoginErr)
}
// accountSettings 由独立适配器承载账号设置写入与敏感登录信息更新。
var settingsRuntime accountapp.SettingsRuntime
@@ -227,25 +227,25 @@ func newApplicationServices(server *Server) *applicationServices {
// accountSettings、accountSettingsErr 保存账号设置应用服务及其装配错误。
accountSettings, accountSettingsErr := accountapp.NewSettingsService(server.accountDependencies.NewAccountSettingsRepository(), settingsRuntime)
if accountSettingsErr != nil {
panic(accountSettingsErr)
return nil, fmt.Errorf("构造账号设置服务失败: %w", accountSettingsErr)
}
// accountSummaryRepository 保存普通用户与管理员共用的摘要查询适配器。
accountSummaryRepository := server.accountDependencies.NewAccountSummaryRepository()
// accountSummaries、accountSummariesErr 保存账号摘要应用服务及其装配错误。
accountSummaries, accountSummariesErr := accountapp.NewSummaryService(accountSummaryRepository, accountSummaryRepository)
if accountSummariesErr != nil {
panic(accountSummariesErr)
return nil, fmt.Errorf("构造账号摘要服务失败: %w", accountSummariesErr)
}
// credentialWake 负责将凭证恢复后的任务唤醒写入收口到适配器。
// automationDependencies 提供自动化、默认回复和关键词用例的显式适配器工厂。
automationDependencies := server.automationDependencies
if automationDependencies == nil {
panic("自动化专用依赖未装配")
return nil, fmt.Errorf("自动化专用依赖未装配")
}
// credentialWake、credentialWakeErr 保存凭证恢复后的自动化唤醒应用服务及装配错误。
credentialWake, credentialWakeErr := automationapp.NewCredentialWakeService(automationDependencies.NewAutomationCredentialWakeRepository())
if credentialWakeErr != nil {
panic(credentialWakeErr)
return nil, fmt.Errorf("构造凭证恢复唤醒服务失败: %w", credentialWakeErr)
}
// accountRuntime 将 Manager 与凭证恢复后的自动化唤醒收口到账号应用端口。
accountRuntime := accountapp.NewRuntimeService(adapter.NewAccountRuntimePort(server.Manager), credentialWake)
@@ -267,7 +267,7 @@ func newApplicationServices(server *Server) *applicationServices {
// accountDelete 是账号删除用例的构造结果,运行时端口可为空以兼容无 Manager 的测试 Server。
accountDelete, deleteErr := accountapp.NewDeleteService(accountRepository, deleteRuntime)
if deleteErr != nil {
panic(deleteErr)
return nil, fmt.Errorf("构造账号删除服务失败: %w", deleteErr)
}
// itemBatchPublish 是批量远端发布适配器,图片安全回调由 Server 装配时注入。
itemBatchPublish := server.itemDependencies.NewItemBatchPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) {
@@ -282,12 +282,12 @@ func newApplicationServices(server *Server) *applicationServices {
automationDependencies.NewAutomationRepository(),
)
if itemBatchLocalPublishErr != nil {
panic(itemBatchLocalPublishErr)
return nil, fmt.Errorf("构造批量发布本地收口服务失败: %w", itemBatchLocalPublishErr)
}
// itemBatchRunner 是批量发布 worker 的构造结果,失败表示必需端口装配错误。
itemBatchRunner, batchRunnerErr := newItemBatchRunnerApplication(server, itemBatchPublish, itemBatchLocalPublish)
if batchRunnerErr != nil {
panic(batchRunnerErr)
return nil, fmt.Errorf("构造批量发布运行器失败: %w", batchRunnerErr)
}
// itemBatchRecovery 负责恢复扫描的批次状态编排;worker 生命周期由协调器拥有。
itemBatchRecovery, batchRecoveryErr := itemapp.NewBatchRecoveryService(
@@ -295,7 +295,7 @@ func newApplicationServices(server *Server) *applicationServices {
itemapp.BatchRecoveryOptions{LeaseDuration: publishBatchLease},
)
if batchRecoveryErr != nil {
panic(batchRecoveryErr)
return nil, fmt.Errorf("构造批量发布恢复服务失败: %w", batchRecoveryErr)
}
// itemBatchCoordinator 负责批次 worker 的超时、恢复扫描和停止等待。
itemBatchCoordinator, batchCoordinatorErr := itemapp.NewBatchWorkerCoordinator(itemBatchRunner, itemBatchRecovery, itemapp.BatchWorkerCoordinatorOptions{
@@ -311,24 +311,24 @@ func newApplicationServices(server *Server) *applicationServices {
},
})
if batchCoordinatorErr != nil {
panic(batchCoordinatorErr)
return nil, fmt.Errorf("构造批量发布协调器失败: %w", batchCoordinatorErr)
}
// itemBatchPreviewPort 提供批量预检所需的非敏感归属与本地图片校验能力。
itemBatchPreviewPort := server.itemDependencies.NewItemBatchPreviewPort()
// itemBatchPreview 是批量发布预检应用服务的构造结果。
itemBatchPreview, itemBatchPreviewErr := itemapp.NewBatchPreviewService(itemBatchPreviewPort, itemBatchPreviewPort)
if itemBatchPreviewErr != nil {
panic(itemBatchPreviewErr)
return nil, fmt.Errorf("构造批量发布预检服务失败: %w", itemBatchPreviewErr)
}
// itemBatchManagement 是批次管理应用服务的构造结果。
itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(server.itemDependencies.NewItemBatchRepository(), serverBatchManagementRuntime{server: server, coordinator: itemBatchCoordinator})
if itemBatchManagementErr != nil {
panic(itemBatchManagementErr)
return nil, fmt.Errorf("构造批量发布管理服务失败: %w", itemBatchManagementErr)
}
// accountLoginCreate 是手动 Cookie 登录应用服务的构造结果。
accountLoginCreate, accountLoginCreateErr := newAccountLoginCreateApplication(loginLifecycle)
if accountLoginCreateErr != nil {
panic(accountLoginCreateErr)
return nil, fmt.Errorf("构造账号登录创建服务失败: %w", accountLoginCreateErr)
}
// accountQRLogin 是扫码成功凭证持久化应用服务的构造结果;零值测试 Server 暂不装配数据库端口。
var accountQRLogin *accountapp.QRLoginService
@@ -337,33 +337,22 @@ func newApplicationServices(server *Server) *applicationServices {
var accountQRLoginErr error
accountQRLogin, accountQRLoginErr = accountapp.NewQRLoginService(server.accountDependencies.NewQRLoginRepository(), loginLifecycle)
if accountQRLoginErr != nil {
panic(accountQRLoginErr)
return nil, fmt.Errorf("构造扫码登录服务失败: %w", accountQRLoginErr)
}
}
// qrSessionRegistry 将扫码会话所有权、过期回收和幂等结果放在应用边界内。
qrSessionRegistry := accountapp.NewQRLoginSessionRegistry()
// automationRepository 复用同一个数据库适配器,保持自动化异常与规则查询的基础设施边界一致。
automationRepository := automationDependencies.NewAutomationRepository()
// settingsService 统一装配设置数据库与远端模型目录适配器。
settingsService := settingsapp.NewService(server.adminSettingsDependencies.NewSettingsRepository(), adapter.NewAIModelClient())
// adminRuntime 是管理员删除用户前收束账号运行实例的窄端口;无 Manager 的离线测试保持为空。
var adminRuntime adminapp.Runtime
if server.Manager != nil {
adminRuntime = server.Manager
}
// adminService 负责管理员用户与仪表盘查询及删除前的账号运行时收束,HTTP 层只做 DTO 映射。
adminService := adminapp.NewServiceWithRuntime(server.adminSettingsDependencies.NewAdminRepository(), adminRuntime)
// itemCatalogRepository 是商品读写用例共用的数据库适配器。
itemCatalogRepository := server.itemDependencies.NewItemCatalogRepository()
// itemCatalog 是商品列表和详情读取用例的应用服务。
itemCatalog, itemCatalogErr := itemapp.NewCatalogService(itemCatalogRepository)
if itemCatalogErr != nil {
panic(itemCatalogErr)
return nil, fmt.Errorf("构造商品目录服务失败: %w", itemCatalogErr)
}
// itemCatalogMutation 是商品写入用例的应用服务。
itemCatalogMutation, itemCatalogMutationErr := itemapp.NewCatalogMutationService(itemCatalogRepository)
if itemCatalogMutationErr != nil {
panic(itemCatalogMutationErr)
return nil, fmt.Errorf("构造商品目录写入服务失败: %w", itemCatalogMutationErr)
}
// itemPublishPort 是单商品与批量发布共享的平台凭证适配器。
itemPublishPort := server.itemDependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) bool {
@@ -372,12 +361,12 @@ func newApplicationServices(server *Server) *applicationServices {
// itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。
itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort)
if itemCategoryRecommendationErr != nil {
panic(itemCategoryRecommendationErr)
return nil, fmt.Errorf("构造商品类目推荐服务失败: %w", itemCategoryRecommendationErr)
}
// itemBatchPreviewPersistence 将预检结果持久化到批次仓储,隔离数据库模型转换。
itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(server.itemDependencies.NewItemBatchRepository())
if itemBatchPreviewPersistenceErr != nil {
panic(itemBatchPreviewPersistenceErr)
return nil, fmt.Errorf("构造批量预检持久化服务失败: %w", itemBatchPreviewPersistenceErr)
}
// itemSinglePublish 是单商品发布应用服务及其基础设施端口的构造结果。
itemSinglePublish, itemSinglePublishErr := itemapp.NewService(
@@ -385,13 +374,14 @@ func newApplicationServices(server *Server) *applicationServices {
server.itemDependencies.NewItemPublishRepository(),
)
if itemSinglePublishErr != nil {
panic(itemSinglePublishErr)
return nil, fmt.Errorf("构造单商品发布服务失败: %w", itemSinglePublishErr)
}
return &applicationServices{
// services 是完成构造后只读注入 Server 的应用服务集合。
services := &applicationServices{
platformCredentials: platformCredentials,
orders: &orderHTTPAdapter{services: orderServices},
orderRefreshJobs: orderRefreshJobs,
orderReconciliationRecovery: orderReconciliationRecovery,
orderReconciliationRecovery: server.orderReconciliationRecovery,
itemSinglePublish: itemSinglePublish,
itemBatchCoordinator: itemBatchCoordinator,
itemBatchPreview: itemBatchPreview,
@@ -407,7 +397,7 @@ func newApplicationServices(server *Server) *applicationServices {
itemCatalog: itemCatalog,
itemCatalogMutation: itemCatalogMutation,
accountLogin: &accountLoginService{cookieWriterFactory: cookieWriterFactory, cookieUpdaterFactory: cookieUpdaterFactory, sessionPort: accountRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin, qrSessions: qrSessionRegistry},
authentication: newAuthenticationApplication(server),
authentication: nil,
loginAudit: loginAudit,
passwordLogin: accountapp.NewPasswordLoginService(),
accountDelete: accountDelete,
@@ -416,21 +406,28 @@ func newApplicationServices(server *Server) *applicationServices {
accountSettings: accountSettings,
accountRuntime: accountRuntime,
accountSummaries: accountSummaries,
accountTasks: automationapp.NewService(automationDependencies.NewAccountTaskRepository(), adapter.NewAccountTaskRunner(server.automation)),
accountTasks: server.transportApplications.AccountTasks,
credentialWake: credentialWake,
chat: newChatSendingApplication(server),
uncertainNotifications: notificationsapp.New(server.miscDependencies.NewNotificationUncertainRepository()),
notificationChannels: notificationsapp.NewChannelService(server.miscDependencies.NewNotificationChannelRepository(), server.notifier),
analytics: analyticsapp.NewService(server.miscDependencies.NewAnalyticsRepository()),
automationRules: automationapp.NewRuleService(automationRepository, automationRepository),
cards: cardsapp.NewService(server.miscDependencies.NewCardsRepository()),
publishAutomationRules: automationapp.NewPublishRuleService(automationRepository),
automationIssues: automationapp.NewIssueService(automationRepository),
defaultReplies: defaultreplyapp.NewService(automationDependencies.NewDefaultReplyRepository()),
keywords: keywordsapp.NewService(automationDependencies.NewKeywordRepository()),
settings: settingsService,
admin: adminService,
uncertainNotifications: server.transportApplications.UncertainNotifications,
notificationChannels: server.transportApplications.NotificationChannels,
analytics: server.transportApplications.Analytics,
automationRules: server.transportApplications.AutomationRules,
cards: server.transportApplications.Cards,
publishAutomationRules: server.transportApplications.PublishAutomationRules,
automationIssues: server.transportApplications.AutomationIssues,
defaultReplies: server.transportApplications.DefaultReplies,
keywords: server.transportApplications.Keywords,
settings: server.transportApplications.Settings,
admin: server.transportApplications.Admin,
}
// authentication、authenticationErr 分别是认证应用服务及其构造错误。
authentication, authenticationErr := newAuthenticationApplication(server)
if authenticationErr != nil {
return nil, authenticationErr
}
services.authentication = authentication
return services, nil
}
// accountRuntimeApplication 返回当前 Server 绑定的账号运行时应用服务。
@@ -439,13 +436,13 @@ func (s *Server) accountRuntimeApplication() *accountapp.RuntimeService {
}
// newAuthenticationApplication 构造用户认证应用服务及其数据库适配器。
func newAuthenticationApplication(server *Server) *accountapp.AuthenticationService {
func newAuthenticationApplication(server *Server) (*accountapp.AuthenticationService, error) {
// authentication、authenticationErr 保存认证应用服务及其装配错误。
authentication, authenticationErr := accountapp.NewAuthenticationService(server.accountDependencies.NewAuthenticationRepository())
if authenticationErr != nil {
panic(authenticationErr)
return nil, fmt.Errorf("构造认证应用服务失败: %w", authenticationErr)
}
return authentication
return authentication, nil
}
// orderRefreshJobsApplication 返回当前 Server 绑定的订单刷新任务应用服务。
@@ -561,17 +558,11 @@ func (s *Server) settingsApplication() *settingsapp.Service {
return s.applicationServiceSet().settings
}
// applicationServiceSet 返回当前 Server 的应用服务集合,并兼容测试 Server。
// applicationServiceSet 返回当前 Server 构造阶段注入的不可变应用服务集合。
// 零值 Server 返回共享空集合以支持防御性测试,绝不在请求期构造或缓存业务服务。
func (s *Server) applicationServiceSet() *applicationServices {
if s == nil {
return &applicationServices{}
if s == nil || s.applications == nil {
return emptyApplicationServices
}
if s.applications != nil {
return s.applications
}
if s.orderDependencies == nil || s.accountDependencies == nil || s.itemDependencies == nil || s.chatDependencies == nil || s.systemDependencies == nil || s.automationDependencies == nil || s.miscDependencies == nil || s.adminSettingsDependencies == nil {
// accountLogin 仅用于零值 Server 的输入校验测试,不触发任何持久化访问。
return &applicationServices{accountLogin: &accountLoginService{}}
}
return newApplicationServices(s)
return s.applications
}
+38 -1
View File
@@ -1,6 +1,9 @@
package server
import "testing"
import (
"sync"
"testing"
)
// TestNewServerAssemblesApplicationServices 验证 Server 构造时统一装配全部应用服务。
func TestNewServerAssemblesApplicationServices(t *testing.T) {
@@ -54,3 +57,37 @@ func TestApplicationLifecycleComponentsExposeWorkerOwnership(t *testing.T) {
}
}
}
// TestApplicationServiceSetUsesStableZeroValueSet 验证零值 Server 不会在请求期创建服务集合,并支持并发防御性读取。
func TestApplicationServiceSetUsesStableZeroValueSet(t *testing.T) {
// srv 是未注入依赖的零值 Server,仅用于验证防御性访问不触发隐式装配。
var srv Server
// first 是首次读取到的共享空服务集合。
first := srv.applicationServiceSet()
if first != emptyApplicationServices {
t.Fatal("零值 Server 应返回共享空服务集合")
}
// readers 是并发读取服务集合的工作数,用于覆盖请求期读路径的数据竞争风险。
const readers = 32
// group 等待全部并发读取完成后再检查结果。
var group sync.WaitGroup
// failures 记录任何一次读取没有返回同一只读集合的情况。
failures := make(chan *applicationServices, readers)
for range readers {
group.Add(1)
go func() {
defer group.Done()
// services 是当前 goroutine 读取到的应用服务集合。
services := srv.applicationServiceSet()
if services != first {
failures <- services
}
}()
}
group.Wait()
close(failures)
// services 是未满足稳定集合约束的错误读取结果,仅用于在失败时提供诊断。
for services := range failures {
t.Fatalf("并发读取返回了不同服务集合: %p", services)
}
}
+63 -51
View File
@@ -30,15 +30,37 @@ type loginResponse struct {
IsAdmin bool `json:"is_admin"`
}
// initializeRequest 是首次启动创建管理员的 HTTP 请求 DTO。
type initializeRequest struct {
// Password 是首次管理员账户必须设置的明文密码,仅在本次请求作用域内使用。
Password string `json:"password"`
}
// passwordChangeRequest 是已登录用户修改密码的 HTTP 请求 DTO。
type passwordChangeRequest struct {
// CurrentPassword 是确认当前会话所有权所需的现有密码。
CurrentPassword string `json:"current_password"`
// NewPassword 是长度校验后替换现有秘密的新密码。
NewPassword string `json:"new_password"`
}
// credentialUpdateRequest 是当前用户修改用户名或密码的 HTTP 请求 DTO。
type credentialUpdateRequest struct {
// CurrentPassword 是敏感凭证变更前的身份确认密码。
CurrentPassword string `json:"current_password"`
// NewUsername 是可选的新登录用户名。
NewUsername string `json:"new_username"`
// NewPassword 是可选的新登录密码。
NewPassword string `json:"new_password"`
}
// initialize 首次启动时通过 Web UI 创建管理员账号。
// 该接口只允许在系统尚未存在管理员时调用,避免把初始化能力变成重置密码入口。
// initialize 负责initialize相关处理。
// initialize 封装initialize业务协调。
func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
Password string `json:"password"`
}
if // err 保存err,供当前处理流程使用
// req 是首次管理员初始化请求的具名传输 DTO。
var req initializeRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -52,7 +74,7 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
s.initializationMu.Lock()
defer s.initializationMu.Unlock()
// initialized、err 保存initialized、err,供当前处理流程使用
// initialized、err 用于本次流程后续判断的initialized、err
initialized, err := s.authenticationApplication().IsSystemInitialized(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "检查系统初始化状态失败")
@@ -63,7 +85,7 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
return
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := s.authenticationApplication().InitializeAdmin(r.Context(), "[email protected]", req.Password); err != nil {
writeErr(w, http.StatusInternalServerError, "初始化管理员失败")
return
@@ -84,30 +106,30 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) {
// login 用户名密码登录(邮箱登录同走此接口,按字段判断)。
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
var req loginRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// clientIP 保存clientIP,供当前处理流程使用
// clientIP 用于本次流程后续判断的clientIP
clientIP := loginClientIP(r)
// principal 保存principal,供当前处理流程使用
// principal 用于本次流程后续判断的principal
principal := loginPrincipal(req.Username, req.Email)
if // allowed、retry 保存allowed、retry,供当前处理流程使用
if // allowed、retry 用于本次流程后续判断的allowed、retry
allowed, retry := s.loginLimiter.allow(clientIP, principal, time.Now()); !allowed {
w.Header().Set("Retry-After", strconv.Itoa(max(1, int(retry.Round(time.Second)/time.Second))))
writeErr(w, http.StatusTooManyRequests, "登录尝试过于频繁,请稍后再试")
return
}
// resp 保存resp,供当前处理流程使用
// resp 用于本次流程后续判断的resp
var resp loginResponse
switch {
case req.Username != "" && req.Password != "":
// sid、user、err 保存sid、user、err,供当前处理流程使用
// sid、user、err 用于本次流程后续判断的sid、user、err
sid, user, err := s.authenticationApplication().Login(r.Context(), req.Username, req.Password)
if err != nil || user == nil || sid == "" {
s.loginLimiter.failure(clientIP, principal, time.Now())
@@ -125,7 +147,7 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
return
case req.Email != "" && req.Password != "":
// username、err 保存邮箱映射得到的登录用户名和查询错误,供当前处理流程使用
// username、err 用于本次流程后续判断的邮箱映射得到的登录用户名和查询错误
username, err := s.authenticationApplication().UsernameByEmail(r.Context(), req.Email)
if err != nil || username == "" {
s.loginLimiter.failure(clientIP, principal, time.Now())
@@ -133,7 +155,7 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
"邮箱或密码错误", "")
return
}
// sid、loginUser、lerr 保存sid、loginUser、lerr,供当前处理流程使用
// sid、loginUser、lerr 用于本次流程后续判断的sid、loginUser、lerr
sid, loginUser, lerr := s.authenticationApplication().Login(r.Context(), username, req.Password)
if lerr != nil || loginUser == nil || sid == "" {
s.loginLimiter.failure(clientIP, principal, time.Now())
@@ -157,11 +179,11 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
// verify 校验会话有效性。返回 authenticated / initialized / is_admin。
func (s *Server) verify(w http.ResponseWriter, r *http.Request) {
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := r.Context()
// initialized 保存initialized,供当前处理流程使用
// initialized 用于本次流程后续判断的initialized
initialized, _ := s.authenticationApplication().IsSystemInitialized(ctx)
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(ctx)
if sess != nil {
writeJSON(w, http.StatusOK, sessionVerificationResponse{
@@ -181,7 +203,7 @@ func (s *Server) verify(w http.ResponseWriter, r *http.Request) {
// logout 登出。
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if sess != nil {
s.Auth.Logout(r.Context(), sess.SessionID)
@@ -192,12 +214,9 @@ func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
// changeAdminPassword 修改管理员密码。
func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
}
if // err 保存err,供当前处理流程使用
// req 是管理员密码修改请求的具名传输 DTO。
var req passwordChangeRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -206,9 +225,9 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "新密码至少需要 8 个字符")
return
}
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := r.Context()
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(ctx)
if sess == nil || !sess.IsAdmin {
writeErr(w, http.StatusForbidden, "仅管理员可执行此操作")
@@ -220,7 +239,7 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := s.authenticationApplication().UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
@@ -231,12 +250,9 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
// changePassword 修改当前用户密码。
func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
}
if // err 保存err,供当前处理流程使用
// req 是当前用户密码修改请求的具名传输 DTO。
var req passwordChangeRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -245,9 +261,9 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "新密码至少需要 8 个字符")
return
}
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := r.Context()
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(ctx)
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
@@ -259,7 +275,7 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := s.authenticationApplication().UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
@@ -270,26 +286,22 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
// updateCredentials 修改当前登录用户的用户名和/或密码,并撤销全部旧会话。
func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
CurrentPassword string `json:"current_password"`
NewUsername string `json:"new_username"`
NewPassword string `json:"new_password"`
}
if // err 保存err,供当前处理流程使用
// req 是当前用户登录凭证修改请求的具名传输 DTO。
var req credentialUpdateRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// username 保存username,供当前处理流程使用
// username 用于本次流程后续判断的username
username := strings.TrimSpace(req.NewUsername)
// usernameLength 保存usernameLength,供当前处理流程使用
// usernameLength 用于本次流程后续判断的usernameLength
usernameLength := utf8.RuneCountInString(username)
if usernameLength < 3 || usernameLength > 64 {
writeErr(w, http.StatusBadRequest, "用户名长度必须为 3 到 64 个字符")
@@ -307,7 +319,7 @@ func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "用户名和密码均未修改")
return
}
// user、ok、err 保存user、ok、err,供当前处理流程使用
// user、ok、err 用于本次流程后续判断的user、ok、err
user, ok, err := s.authenticationApplication().VerifyPassword(r.Context(), sess.Username, req.CurrentPassword)
if err != nil {
writeCredentialVerificationError(w, err)
@@ -317,7 +329,7 @@ func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) {
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
return
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.authenticationApplication().UpdateCredentials(r.Context(), sess.UserID, username, req.NewPassword); err != nil {
if errors.Is(err, accountapp.ErrUsernameTaken) {
writeErrCode(w, http.StatusConflict, "username_taken", "用户名已被占用", "")
+124 -124
View File
@@ -14,51 +14,51 @@ import (
// TestAutomationRulesCRUD 自动化规则增删查 + 校验分支。
func TestAutomationRulesCRUD(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// 准备一个卡密组用于 send_card 动作。
cardID, _ := store.Cards.Create(ctx, &db.CardFull{Name: "卡密组1", Type: "text", TextContent: "卡密ABC", Enabled: true, UserID: 1})
// 准备一个商品。
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it-auto','商品A')`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 创建规则:付款后自动发货(send_card)。
body := `{"cookie_id":"acc1","item_id":"it-auto","trigger_type":"order_paid","enabled":true,` +
`"actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `,"delivery_count":1,"delay_seconds":0}]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
}
// cr 保存cr,供当前处理流程使用
// cr 用于本次流程后续判断的cr
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
if cr["success"] != true {
t.Fatalf("创建失败: %+v", cr)
}
// ruleID 保存规则ID,供当前处理流程使用
// ruleID 用于本次流程后续判断的规则ID
ruleID := itoa(int64(cr["id"].(float64)))
// 列表。
req2 := httptest.NewRequest(http.MethodGet, "/automation-rules", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("list status=%d", rec2.Code)
}
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 {
@@ -68,10 +68,10 @@ func TestAutomationRulesCRUD(t *testing.T) {
// 更新规则(改名为自定义)。
updBody := `{"cookie_id":"acc1","item_id":"it-auto","name":"自定义规则","trigger_type":"order_paid","enabled":false,` +
`"actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `,"delivery_count":2}]}`
// req3 保存req3,供当前处理流程使用
// req3 用于本次流程后续判断的req3
req3 := httptest.NewRequest(http.MethodPut, "/automation-rules/"+ruleID, strings.NewReader(updBody))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -81,7 +81,7 @@ func TestAutomationRulesCRUD(t *testing.T) {
// 删除。
req4 := httptest.NewRequest(http.MethodDelete, "/automation-rules/"+ruleID, nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != 200 {
@@ -89,12 +89,12 @@ func TestAutomationRulesCRUD(t *testing.T) {
}
}
// TestAutomationRulesListFiltersAndPagination 负责Test自动化规则列表ListFiltersAndPagination相关处理。
// TestAutomationRulesListFiltersAndPagination 封装Test自动化规则列表ListFiltersAndPagination业务协调。
func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','item-blue','蓝色会员')`)
// input 表示当前遍历过程中的input
@@ -103,29 +103,29 @@ func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
{UserID: 1, CookieID: "acc1", Name: "评价赠品", TriggerType: automation.TriggerBuyerReviewed, Enabled: false, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "gift", Enabled: true}}},
{UserID: 1, CookieID: "acc1", Name: "求评价", TriggerType: automation.TriggerReviewMissingTimeout, Enabled: true, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "review", Enabled: true}}},
} {
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.Automation.Create(ctx, input); err != nil {
t.Fatalf("create rule: %v", err)
}
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// request 保存请求,供当前处理流程使用
// request 用于本次流程后续判断的请求
request := func(path string) (int, map[string]any) {
t.Helper()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
var body map[string]any
if rec.Code == http.StatusOK {
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
@@ -133,32 +133,32 @@ func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
return rec.Code, body
}
// status、filtered 保存status、filtered,供当前处理流程使用
// status、filtered 用于本次流程后续判断的status、filtered
status, filtered := request("/automation-rules?page=1&page_size=10&cookie_id=acc1&trigger_type=order_paid&enabled=true&search=%E8%93%9D%E8%89%B2")
if status != http.StatusOK || filtered["total"] != float64(1) || filtered["total_pages"] != float64(1) {
t.Fatalf("filtered status=%d body=%+v", status, filtered)
}
// filteredCounts、ok 保存filteredCounts、ok,供当前处理流程使用
// filteredCounts、ok 用于本次流程后续判断的filteredCounts、ok
filteredCounts, ok := filtered["trigger_counts"].(map[string]any)
if !ok || filteredCounts[automation.TriggerOrderPaid] != float64(1) || len(filteredCounts) != 1 {
t.Fatalf("filtered trigger counts=%+v", filtered["trigger_counts"])
}
// data、ok 保存data、ok,供当前处理流程使用
// data、ok 用于本次流程后续判断的data、ok
data, ok := filtered["data"].([]any)
if !ok || len(data) != 1 || data[0].(map[string]any)["name"] != "付款规则" {
t.Fatalf("filtered data=%+v", filtered["data"])
}
// status、lastPage 保存status、last页码,供当前处理流程使用
// status、lastPage 用于本次流程后续判断的status、last页码
status, lastPage := request("/automation-rules?page=99&page_size=1")
if status != http.StatusOK || lastPage["total"] != float64(3) || lastPage["page"] != float64(3) {
t.Fatalf("last page status=%d body=%+v", status, lastPage)
}
if // data、ok 保存data、ok,供当前处理流程使用
if // data、ok 用于本次流程后续判断的data、ok
data, ok := lastPage["data"].([]any); !ok || len(data) != 1 {
t.Fatalf("last page data=%+v", lastPage["data"])
}
// lastPageCounts、ok 保存last页码Counts、ok,供当前处理流程使用
// lastPageCounts、ok 用于本次流程后续判断的last页码Counts、ok
lastPageCounts, ok := lastPage["trigger_counts"].(map[string]any)
if !ok || lastPageCounts[automation.TriggerOrderPaid] != float64(1) ||
lastPageCounts[automation.TriggerBuyerReviewed] != float64(1) ||
@@ -174,20 +174,20 @@ func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
// TestAutomationRuleBadTriggerType 不支持的触发类型 400。
func TestAutomationRuleBadTriggerType(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"cookie_id":"acc1","trigger_type":"bogus","actions":[{"action_type":"confirm_shipment"}]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -197,20 +197,20 @@ func TestAutomationRuleBadTriggerType(t *testing.T) {
// TestAutomationRuleBadCookie 账号不属于当前用户 400。
func TestAutomationRuleBadCookie(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"cookie_id":"other-account","trigger_type":"order_paid","actions":[{"action_type":"confirm_shipment"}]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -220,20 +220,20 @@ func TestAutomationRuleBadCookie(t *testing.T) {
// TestAutomationRuleBadActionType 不支持的动作类型 400。
func TestAutomationRuleBadActionType(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"bogus"}]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -241,28 +241,28 @@ func TestAutomationRuleBadActionType(t *testing.T) {
}
}
// TestAutomationRuleRejectsAPICard 负责Test自动化规则RejectsAPI卡密相关处理。
// TestAutomationRuleRejectsAPICard 封装Test自动化规则RejectsAPI卡密业务协调。
func TestAutomationRuleRejectsAPICard(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// cardID、err 保存卡密ID、err,供当前处理流程使用
// cardID、err 用于本次流程后续判断的卡密ID、err
cardID, err := store.Cards.Create(context.Background(), &db.CardFull{
Name: "旧 API 卡密", Type: "api", APIConfig: `{"url":"https://example.com"}`, Enabled: true, UserID: 1,
})
if err != nil {
t.Fatal(err)
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `}]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "API 卡密暂不支持") {
@@ -272,20 +272,20 @@ func TestAutomationRuleRejectsAPICard(t *testing.T) {
// TestAutomationRuleSendCardMissingCardID send_card 缺 card_id 400。
func TestAutomationRuleSendCardMissingCardID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_card","card_id":0}]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -295,20 +295,20 @@ func TestAutomationRuleSendCardMissingCardID(t *testing.T) {
// TestAutomationRuleSendTextMissingTemplate send_text 缺文案 400。
func TestAutomationRuleSendTextMissingTemplate(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_text","message_template":""}]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -316,56 +316,56 @@ func TestAutomationRuleSendTextMissingTemplate(t *testing.T) {
}
}
// TestAutomationIssueEndpointsAndActiveDeleteConflict 负责Test自动化问题EndpointsAndActiveDeleteConflict相关处理。
// TestAutomationIssueEndpointsAndActiveDeleteConflict 封装Test自动化问题EndpointsAndActiveDeleteConflict业务协调。
func TestAutomationIssueEndpointsAndActiveDeleteConflict(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// admin 保存admin,供当前处理流程使用
// admin 用于本次流程后续判断的admin
admin, _ := store.Users.GetByUsername(ctx, "admin")
// ruleID、err 保存规则ID、err,供当前处理流程使用
// ruleID、err 用于本次流程后续判断的规则ID、err
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{UserID: admin.ID, CookieID: "acc1", Name: "issue",
TriggerType: automation.TriggerBuyerReviewed, Enabled: true,
Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "x", Enabled: true}}})
if err != nil {
t.Fatal(err)
}
// runID 保存运行ID,供当前处理流程使用
// runID 用于本次流程后续判断的运行ID
runID, _, _ := store.Automation.TryStartRun(ctx, db.AutomationRun{RuleID: ruleID, CookieID: "acc1", OrderID: "o",
TriggerType: automation.TriggerBuyerReviewed, TriggerKey: "k", RawEventJSON: `{}`, LeaseExpiresAt: 1})
_, _ = store.Automation.StartRunAction(ctx, runID, 1, 0, 1)
_ = store.Automation.QuarantineRun(ctx, runID, 1, "unknown")
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// listReq 保存listReq,供当前处理流程使用
// listReq 用于本次流程后续判断的listReq
listReq := httptest.NewRequest(http.MethodGet, "/automation-issues", nil)
listReq.AddCookie(cookie)
// listRec 保存listRec,供当前处理流程使用
// listRec 用于本次流程后续判断的listRec
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK || !strings.Contains(listRec.Body.String(), "unknown") {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
// deleteReq 保存deleteReq,供当前处理流程使用
// deleteReq 用于本次流程后续判断的deleteReq
deleteReq := httptest.NewRequest(http.MethodDelete, "/automation-rules/"+itoa(ruleID), nil)
deleteReq.AddCookie(cookie)
// deleteRec 保存deleteRec,供当前处理流程使用
// deleteRec 用于本次流程后续判断的deleteRec
deleteRec := httptest.NewRecorder()
h.ServeHTTP(deleteRec, deleteReq)
if deleteRec.Code != http.StatusConflict {
t.Fatalf("active delete status=%d body=%s", deleteRec.Code, deleteRec.Body.String())
}
// resolveReq 保存resolveReq,供当前处理流程使用
// resolveReq 用于本次流程后续判断的resolveReq
resolveReq := httptest.NewRequest(http.MethodPost, "/automation-runs/"+itoa(runID)+"/resolve", strings.NewReader(`{"resolution":"cancel"}`))
resolveReq.AddCookie(cookie)
// resolveRec 保存resolveRec,供当前处理流程使用
// resolveRec 用于本次流程后续判断的resolveRec
resolveRec := httptest.NewRecorder()
h.ServeHTTP(resolveRec, resolveReq)
if resolveRec.Code != http.StatusOK {
@@ -375,20 +375,20 @@ func TestAutomationIssueEndpointsAndActiveDeleteConflict(t *testing.T) {
// TestAutomationRuleNoActions 缺动作 400。
func TestAutomationRuleNoActions(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -396,21 +396,21 @@ func TestAutomationRuleNoActions(t *testing.T) {
}
}
// TestAutomationRuleRejectsIncompatibleTriggerActions 负责Test自动化规则RejectsIncompatibleTrigger动作列表相关处理。
// TestAutomationRuleRejectsIncompatibleTriggerActions 封装Test自动化规则RejectsIncompatibleTrigger动作列表业务协调。
func TestAutomationRuleRejectsIncompatibleTriggerActions(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// cardID、err 保存卡密ID、err,供当前处理流程使用
// cardID、err 用于本次流程后续判断的卡密ID、err
cardID, err := store.Cards.Create(context.Background(), &db.CardFull{Name: "card", Type: "text", TextContent: "x", Enabled: true, UserID: 1})
if err != nil {
t.Fatal(err)
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// tests 保存tests,供当前处理流程使用
// tests 用于本次流程后续判断的tests
tests := []string{
`{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_text","message_template":"x"}]}`,
`{"cookie_id":"acc1","trigger_type":"buyer_reviewed","actions":[{"action_type":"confirm_shipment"}]}`,
@@ -418,10 +418,10 @@ func TestAutomationRuleRejectsIncompatibleTriggerActions(t *testing.T) {
}
// body 表示当前遍历过程中的请求体
for _, body := range tests {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -432,18 +432,18 @@ func TestAutomationRuleRejectsIncompatibleTriggerActions(t *testing.T) {
// TestAutomationRuleBadJSON 非法 JSON 400。
func TestAutomationRuleBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -453,20 +453,20 @@ func TestAutomationRuleBadJSON(t *testing.T) {
// TestAutomationRuleUpdateBadID 无效 ID 400。
func TestAutomationRuleUpdateBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"confirm_shipment"}]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/automation-rules/abc", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -476,18 +476,18 @@ func TestAutomationRuleUpdateBadID(t *testing.T) {
// TestAutomationRuleDeleteBadID 无效 ID 400。
func TestAutomationRuleDeleteBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/automation-rules/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -497,18 +497,18 @@ func TestAutomationRuleDeleteBadID(t *testing.T) {
// TestAutomationRuleDeleteNotFound 不存在规则 404。
func TestAutomationRuleDeleteNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/automation-rules/999999", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -518,7 +518,7 @@ func TestAutomationRuleDeleteNotFound(t *testing.T) {
// TestDefaultAutomationRuleName 默认规则名。
func TestDefaultAutomationRuleName(t *testing.T) {
// cases 保存cases,供当前处理流程使用
// cases 用于本次流程后续判断的cases
cases := map[string]string{
automation.TriggerOrderPaid: "付款后自动发货",
automation.TriggerBuyerReviewed: "评价后发送赠品",
@@ -527,13 +527,13 @@ func TestDefaultAutomationRuleName(t *testing.T) {
}
// trigger、want 表示当前遍历过程中的trigger、want
for trigger, want := range cases {
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
got := defaultAutomationRuleName(trigger, "")
if got != want {
t.Errorf("defaultAutomationRuleName(%q)=%q want %q", trigger, got, want)
}
}
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := defaultAutomationRuleName(automation.TriggerOrderPaid, "item-x"); got != "付款后自动发货 - item-x" {
t.Errorf("带 itemID 的默认名异常: %q", got)
}
@@ -541,7 +541,7 @@ func TestDefaultAutomationRuleName(t *testing.T) {
// TestIsJSONObject isJSONObject 表驱动。
func TestIsJSONObject(t *testing.T) {
// cases 保存cases,供当前处理流程使用
// cases 用于本次流程后续判断的cases
cases := map[string]bool{
`{}`: true,
`{"a":1}`: true,
@@ -553,7 +553,7 @@ func TestIsJSONObject(t *testing.T) {
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := isJSONObject(in); got != want {
t.Errorf("isJSONObject(%q)=%v want %v", in, got, want)
}
@@ -562,11 +562,11 @@ func TestIsJSONObject(t *testing.T) {
// TestFirstNonZero firstNonZero 表驱动。
func TestFirstNonZero(t *testing.T) {
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := firstNonZero(0, 5); got != 5 {
t.Fatalf("got %d", got)
}
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := firstNonZero(3, 5); got != 3 {
t.Fatalf("got %d", got)
}
+24 -22
View File
@@ -12,7 +12,13 @@ import (
"xianyu-go/internal/auth"
)
// mountAutomation 负责mount自动化相关处理。
// automationIssueResolutionRequest 是处理自动化异常或延期任务的 HTTP 请求 DTO。
type automationIssueResolutionRequest struct {
// Resolution 是 retry、dismiss 等由应用服务校验的处理动作。
Resolution string `json:"resolution"`
}
// mountAutomation 封装mount自动化业务协调。
func (s *Server) mountAutomation(r chi.Router) {
r.Get("/automation-rules", s.listAutomationRules)
r.Post("/automation-rules", s.createAutomationRule)
@@ -23,11 +29,11 @@ func (s *Server) mountAutomation(r chi.Router) {
r.Post("/automation-pending-tasks/{task_id}/resolve", s.resolveDeferredAutomationTask)
}
// listAutomationIssues 负责list自动化问题列表相关处理。
// listAutomationIssues 封装list自动化问题列表业务协调。
func (s *Server) listAutomationIssues(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// runs、tasks、err 保存runs、tasks、err,供当前处理流程使用
// runs、tasks、err 用于本次流程后续判断的runs、tasks、err
runs, tasks, err := s.automationIssuesApplication().ListIssues(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化异常任务失败")
@@ -69,26 +75,24 @@ func deferredAutomationIssueDTOs(issues []automationapp.DeferredIssue) []deferre
return result
}
// resolveAutomationRun 负责resolve自动化运行相关处理。
// resolveAutomationRun 封装resolve自动化运行业务协调。
func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
// runID、err 保存运行ID、err,供当前处理流程使用
// runID、err 用于本次流程后续判断的运行ID、err
runID, err := strconv.ParseInt(chi.URLParam(r, "run_id"), 10, 64)
if err != nil || runID <= 0 {
writeErr(w, http.StatusBadRequest, "无效运行ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Resolution string `json:"resolution"`
}
if // err 保存err,供当前处理流程使用
// req 是自动化运行异常处理请求的具名传输 DTO。
var req automationIssueResolutionRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.automationIssuesApplication().ResolveRunIssue(r.Context(), sess.UserID, runID, strings.TrimSpace(req.Resolution)); err != nil {
if errors.Is(err, automationapp.ErrNotFound) {
writeErr(w, http.StatusNotFound, "异常运行不存在或已处理")
@@ -100,26 +104,24 @@ func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// resolveDeferredAutomationTask 负责resolveDeferred自动化任务相关处理。
// resolveDeferredAutomationTask 封装resolveDeferred自动化任务业务协调。
func (s *Server) resolveDeferredAutomationTask(w http.ResponseWriter, r *http.Request) {
// taskID、err 保存任务ID、err,供当前处理流程使用
// taskID、err 用于本次流程后续判断的任务ID、err
taskID, err := strconv.ParseInt(chi.URLParam(r, "task_id"), 10, 64)
if err != nil || taskID <= 0 {
writeErr(w, http.StatusBadRequest, "无效任务ID")
return
}
// req 保存req,供当前处理流程使用
var req struct {
Resolution string `json:"resolution"`
}
if // err 保存err,供当前处理流程使用
// req 是延期自动化任务处理请求的具名传输 DTO。
var req automationIssueResolutionRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "处理方式必须是 retry 或 dismiss")
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.automationIssuesApplication().ResolveDeferredIssue(r.Context(), sess.UserID, taskID, req.Resolution); err != nil {
if errors.Is(err, automationapp.ErrInvalidDeferredResolution) {
writeErr(w, http.StatusBadRequest, err.Error())
+37 -37
View File
@@ -13,7 +13,7 @@ import (
"xianyu-go/internal/auth"
)
// automationActionRequest 保存自动化动作请求,供当前处理流程使用
// automationActionRequest 用于本次流程后续判断的自动化动作请求
type automationActionRequest struct {
ActionType string `json:"action_type"`
CardID int64 `json:"card_id"`
@@ -25,7 +25,7 @@ type automationActionRequest struct {
SortOrder int `json:"sort_order"`
}
// automationRuleRequest 保存自动化规则请求,供当前处理流程使用
// automationRuleRequest 用于本次流程后续判断的自动化规则请求
type automationRuleRequest struct {
CookieID string `json:"cookie_id"`
ItemID string `json:"item_id"`
@@ -37,16 +37,16 @@ type automationRuleRequest struct {
Actions []automationActionRequest `json:"actions"`
}
// listAutomationRules 负责list自动化规则列表相关处理。
// listAutomationRules 封装list自动化规则列表业务协调。
func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// query 保存查询,供当前处理流程使用
// query 用于本次流程后续判断的查询
query := r.URL.Query()
// paginated 保存paginated,供当前处理流程使用
// paginated 用于本次流程后续判断的paginated
_, paginated := query["page"]
if !paginated {
// rules、err 保存rules、err,供当前处理流程使用
// rules、err 用于本次流程后续判断的rules、err
rules, err := s.automationRulesApplication().ListForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
@@ -56,9 +56,9 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
return
}
// page 保存页码,供当前处理流程使用
// page 用于本次流程后续判断的页码
page := atoiDefault(query.Get("page"), 1)
// pageSize 保存每页数量,供当前处理流程使用
// pageSize 用于本次流程后续判断的每页数量
pageSize := atoiDefault(query.Get("page_size"), 10)
if page < 1 {
page = 1
@@ -69,7 +69,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
if pageSize > 100 {
pageSize = 100
}
// cookieID 保存登录凭证ID,供当前处理流程使用
// cookieID 用于本次流程后续判断的登录凭证ID
cookieID := strings.TrimSpace(query.Get("cookie_id"))
if cookieID != "" {
if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) {
@@ -77,7 +77,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
return
}
}
// triggerType 保存trigger类型,供当前处理流程使用
// triggerType 用于本次流程后续判断的trigger类型
triggerType := strings.TrimSpace(query.Get("trigger_type"))
if triggerType != "" {
switch triggerType {
@@ -87,11 +87,11 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
return
}
}
// enabled 保存启用状态,供当前处理流程使用
// enabled 用于本次流程后续判断的启用状态
var enabled *bool
if // rawEnabled 保存原始启用状态,供当前处理流程使用
if // rawEnabled 用于本次流程后续判断的原始启用状态
rawEnabled := strings.TrimSpace(query.Get("enabled")); rawEnabled != "" {
// value、parseErr 保存value、parseErr,供当前处理流程使用
// value、parseErr 用于本次流程后续判断的value、parseErr
value, parseErr := strconv.ParseBool(rawEnabled)
if parseErr != nil {
writeErr(w, http.StatusBadRequest, "启用状态必须是 true 或 false")
@@ -100,7 +100,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
enabled = &value
}
// rules、total、err 保存rules、total、err,供当前处理流程使用
// rules、total、err 用于本次流程后续判断的rules、total、err
rules, total, err := s.automationRulesApplication().ListPageForUser(r.Context(), automationapp.RuleFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
@@ -109,18 +109,18 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
// filter 保存filter,供当前处理流程使用
// filter 用于本次流程后续判断的filter
filter := automationapp.RuleFilter{
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
Search: query.Get("search"),
}
// triggerCounts、err 保存triggerCounts、err,供当前处理流程使用
// triggerCounts、err 用于本次流程后续判断的triggerCounts、err
triggerCounts, err := s.automationRulesApplication().CountByTriggerForUser(r.Context(), filter)
if err != nil {
writeErr(w, http.StatusInternalServerError, "统计自动化规则失败")
return
}
// totalPages 保存总数Pages,供当前处理流程使用
// totalPages 用于本次流程后续判断的总数Pages
totalPages := (total + pageSize - 1) / pageSize
if totalPages > 0 && page > totalPages {
page = totalPages
@@ -139,13 +139,13 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
})
}
// automationRulesJSON 负责自动化规则列表JSON相关处理。
// automationRulesJSON 封装自动化规则列表JSON业务协调。
func automationRulesJSON(rules []automationapp.Rule) []automationRuleResponse {
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make([]automationRuleResponse, 0, len(rules))
// rule 表示当前遍历过程中的规则
for _, rule := range rules {
// actions 保存动作列表,供当前处理流程使用
// actions 用于本次流程后续判断的动作列表
actions := make([]automationActionResponse, 0, len(rule.Actions))
// action 表示当前遍历过程中的动作
for _, action := range rule.Actions {
@@ -167,22 +167,22 @@ func automationRulesJSON(rules []automationapp.Rule) []automationRuleResponse {
// createAutomationRule 创建自动化规则并返回数值主键 DTO。
func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
var req automationRuleRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// in、err 保存in、err,供当前处理流程使用
// in、err 用于本次流程后续判断的in、err
in, err := s.automationRulesApplication().Normalize(r.Context(), sess.UserID, automationRuleDraft(req))
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// id、err 保存id、err,供当前处理流程使用
// id、err 用于本次流程后续判断的id、err
id, err := s.automationRulesApplication().Create(r.Context(), in)
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建自动化规则失败")
@@ -191,30 +191,30 @@ func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
// updateAutomationRule 负责update自动化规则相关处理。
// updateAutomationRule 封装update自动化规则业务协调。
func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
// ruleID、err 保存规则ID、err,供当前处理流程使用
// ruleID、err 用于本次流程后续判断的规则ID、err
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
var req automationRuleRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// in、err 保存in、err,供当前处理流程使用
// in、err 用于本次流程后续判断的in、err
in, err := s.automationRulesApplication().Normalize(r.Context(), sess.UserID, automationRuleDraft(req))
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.automationRulesApplication().Update(r.Context(), sess.UserID, ruleID, in); err != nil {
if errors.Is(err, automationapp.ErrRuleNotFound) {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
@@ -226,17 +226,17 @@ func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteAutomationRule 负责delete自动化规则相关处理。
// deleteAutomationRule 封装delete自动化规则业务协调。
func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) {
// ruleID、err 保存规则ID、err,供当前处理流程使用
// ruleID、err 用于本次流程后续判断的规则ID、err
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.automationRulesApplication().Delete(r.Context(), sess.UserID, ruleID); err != nil {
if errors.Is(err, automationapp.ErrRuleNotFound) {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
+14 -14
View File
@@ -13,10 +13,10 @@ import (
"xianyu-go/internal/auth"
)
// maxCardBatchRows 保存max卡密批次Rows,供当前处理流程使用
// maxCardBatchRows 用于本次流程后续判断的max卡密批次Rows
const maxCardBatchRows = 200
// cardBatchResultRow 保存卡密批次结果Row,供当前处理流程使用
// cardBatchResultRow 用于本次流程后续判断的卡密批次结果Row
type cardBatchResultRow struct {
RowNo int `json:"row_no"`
Success bool `json:"success"`
@@ -28,7 +28,7 @@ type cardBatchResultRow struct {
// batchCreateCards 上传表格批量创建卡密组。每行一个组定义。
func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// 表格最大 5 MiB(卡密组定义都很小)。
r.Body = http.MaxBytesReader(w, r.Body, maxCardBatchUploadBytes)
@@ -37,14 +37,14 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "解析上传文件失败")
return
}
// source、sourceHeader、err 保存source、sourceHeader、err,供当前处理流程使用
// source、sourceHeader、err 用于本次流程后续判断的source、sourceHeader、err
source, sourceHeader, err := r.FormFile("file")
if err != nil {
writeErr(w, http.StatusBadRequest, "缺少卡密表格文件")
return
}
defer source.Close()
// sourceBytes、tooLarge、err 保存sourceBytes、tooLarge、err,供当前处理流程使用
// sourceBytes、tooLarge、err 用于本次流程后续判断的sourceBytes、tooLarge、err
sourceBytes, tooLarge, err := readLimitedBytes(source, 5<<20)
if err != nil {
writeErr(w, http.StatusBadRequest, "读取卡密表格失败")
@@ -54,12 +54,12 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "卡密表格不能超过 5 MiB")
return
}
// sourceName 保存source名称,供当前处理流程使用
// sourceName 用于本次流程后续判断的source名称
sourceName := safeBaseName(sourceHeader.Filename)
if sourceName == "" {
sourceName = "cards.csv"
}
// maps、err 保存maps、err,供当前处理流程使用
// maps、err 用于本次流程后续判断的maps、err
maps, err := parsePublishSheetBytesWithLimit(sourceBytes, sourceName, maxCardBatchRows)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
@@ -70,19 +70,19 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
return
}
// results 保存results,供当前处理流程使用
// results 用于本次流程后续判断的results
results := make([]cardBatchResultRow, 0, len(maps))
// created、failed 保存created、failed,供当前处理流程使用
// created、failed 用于本次流程后续判断的created、failed
created, failed := 0, 0
// i、m 表示当前遍历过程中的i、m
for i, m := range maps {
// rowNo 保存rowNo,供当前处理流程使用
// rowNo 用于本次流程后续判断的rowNo
rowNo := i + 2
// name 保存名称,供当前处理流程使用
// name 用于本次流程后续判断的名称
name := strings.TrimSpace(firstImportString(m, "name", "名称", "卡密组名称", "卡密名称"))
// cardType 保存卡密类型,供当前处理流程使用
// cardType 用于本次流程后续判断的卡密类型
cardType := strings.ToLower(strings.TrimSpace(firstImportString(m, "type", "类型", "卡密类型")))
// content 保存内容,供当前处理流程使用
// content 用于本次流程后续判断的内容
content := firstImportString(m, "content", "内容", "卡密内容")
// 校验
@@ -107,7 +107,7 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
failed++
continue
}
// delaySeconds 保存延迟秒数,供当前处理流程使用
// delaySeconds 用于本次流程后续判断的延迟秒数
delaySeconds := atoiPublishDefault(firstImportString(m, "delay_seconds", "延迟秒"), 0)
if delaySeconds < 0 || delaySeconds > 3600 {
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "延时发货必须在 0 到 3600 秒之间"})
+29 -29
View File
@@ -15,27 +15,27 @@ import (
"xianyu-go/internal/db"
)
// TestChatHistoryAndAccountTaskSettingsEndpoints 负责Test聊天HistoryAnd账号任务设置Endpoints相关处理。
// TestChatHistoryAndAccountTaskSettingsEndpoints 封装Test聊天HistoryAnd账号任务设置Endpoints业务协调。
func TestChatHistoryAndAccountTaskSettingsEndpoints(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServerWithChat(t)
defer cleanup()
// handler 保存handler,供当前处理流程使用
// handler 用于本次流程后续判断的handler
handler := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, handler)
// err 保存err,供当前处理流程使用
// err 用于本次流程后续判断的err
_, _, err := store.Chats.SaveMessage(context.Background(), db.ChatSession{CookieID: "acc1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家甲"},
db.ChatMessage{MessageKey: "platform-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家甲", MessageType: "text", Content: "你好", Status: "received", SentAt: 1000}, true)
if err != nil {
t.Fatal(err)
}
// request 保存请求,供当前处理流程使用
// request 用于本次流程后续判断的请求
request := httptest.NewRequest(http.MethodGet, "/api/chat/sessions?account_id=acc1", nil)
request.AddCookie(cookie)
// recorder 保存recorder,供当前处理流程使用
// recorder 用于本次流程后续判断的recorder
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "买家甲") {
@@ -60,70 +60,70 @@ func TestChatHistoryAndAccountTaskSettingsEndpoints(t *testing.T) {
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "交易愉快") {
t.Fatalf("task settings status=%d body=%s", recorder.Code, recorder.Body.String())
}
// settings、err 保存settings、err,供当前处理流程使用
// settings、err 用于本次流程后续判断的settings、err
settings, err := store.AccountTasks.Get(context.Background(), "acc1")
if err != nil || !settings.AutoRateEnabled || !settings.AutoPolishEnabled || settings.PolishTime != "04:30" {
t.Fatalf("settings=%+v err=%v", settings, err)
}
}
// TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents 负责Test聊天WebSocketStreamsOnlyAuthenticated账号Events相关处理。
// TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents 封装Test聊天WebSocketStreamsOnlyAuthenticated账号Events业务协调。
func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServerWithChat(t)
defer cleanup()
// service 保存service,供当前处理流程使用
// service 用于本次流程后续判断的service
service := srv.chat
// handler 保存handler,供当前处理流程使用
// handler 用于本次流程后续判断的handler
handler := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, handler)
// httpServer 保存httpServer,供当前处理流程使用
// httpServer 用于本次流程后续判断的httpServer
httpServer := httptest.NewServer(handler)
defer httpServer.Close()
// header 保存header,供当前处理流程使用
// header 用于本次流程后续判断的header
header := make(http.Header)
header.Set("Cookie", cookie.String())
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
// ctx、cancel 用于本次流程后续判断的ctx、cancel
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// conn、err 保存conn、err,供当前处理流程使用
// conn、err 用于本次流程后续判断的conn、err
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/chat/ws", &websocket.DialOptions{HTTPHeader: header})
if err != nil {
t.Fatal(err)
}
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
// ready 保存ready,供当前处理流程使用
// ready 用于本次流程后续判断的ready
var ready map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := wsjson.Read(ctx, conn, &ready); err != nil || ready["type"] != "ready" {
t.Fatalf("ready=%+v err=%v", ready, err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, _, err := service.RecordIncoming(ctx, chat.Incoming{AccountID: "acc1", ChatID: "chat-live", BuyerID: "buyer",
BuyerName: "实时买家", Text: "实时消息", Raw: map[string]any{"messageId": "live-1"}}); err != nil {
t.Fatal(err)
}
// event 保存event,供当前处理流程使用
// event 用于本次流程后续判断的event
var event chat.Event
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := wsjson.Read(ctx, conn, &event); err != nil || event.Type != "message.created" || event.Message.Content != "实时消息" {
t.Fatalf("event=%+v err=%v", event, err)
}
}
// TestChatAndTaskEndpointsEnforceOwnershipAndValidation 负责Test聊天And任务EndpointsEnforceOwnershipAndValidation相关处理。
// TestChatAndTaskEndpointsEnforceOwnershipAndValidation 封装Test聊天And任务EndpointsEnforceOwnershipAndValidation业务协调。
func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServerWithChat(t)
defer cleanup()
// handler 保存handler,供当前处理流程使用
// handler 用于本次流程后续判断的handler
handler := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, handler)
// cases 保存cases,供当前处理流程使用
// cases 用于本次流程后续判断的cases
cases := []struct {
method, path, body string
want int
@@ -135,11 +135,11 @@ func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
// request 保存请求,供当前处理流程使用
// request 用于本次流程后续判断的请求
request := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(cookie)
// recorder 保存recorder,供当前处理流程使用
// recorder 用于本次流程后续判断的recorder
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != tc.want {
+52 -46
View File
@@ -19,7 +19,17 @@ import (
"xianyu-go/internal/auth"
)
// mountChat 负责mount聊天相关处理。
// markChatReadRequest 是提交聊天已读状态的 HTTP 请求 DTO。
type markChatReadRequest struct {
// AccountID 是当前用户有权操作的账号标识。
AccountID string `json:"account_id"`
// ChatID 是会话标识。
ChatID string `json:"chat_id"`
// MessageIDs 是平台已读接口需要的消息标识集合。
MessageIDs []map[string]any `json:"message_ids"`
}
// mountChat 封装mount聊天业务协调。
func (s *Server) mountChat(r chi.Router) {
r.Get("/api/chat/sessions", s.listChatSessions)
r.Get("/api/chat/messages", s.listChatMessages)
@@ -34,23 +44,23 @@ func (s *Server) chatApplication() *chatapp.Service {
return s.applicationServiceSet().chat
}
// listChatSessions 负责list聊天Sessions相关处理。
// listChatSessions 封装list聊天Sessions业务协调。
func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// accountID 保存账号ID,供当前处理流程使用
// accountID 用于本次流程后续判断的账号ID
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
if !s.ownsAccount(r, accountID) {
writeErr(w, http.StatusForbidden, "无权访问该账号")
return
}
// cursor 保存游标,供当前处理流程使用
// cursor 用于本次流程后续判断的游标
cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64)
// refresh 保存refresh,供当前处理流程使用
// refresh 用于本次流程后续判断的refresh
refresh := r.URL.Query().Get("refresh") == "1"
// hasMore 保存hasMore,供当前处理流程使用
// hasMore 用于本次流程后续判断的hasMore
var hasMore bool
// nextCursor 保存next游标,供当前处理流程使用
// nextCursor 用于本次流程后续判断的next游标
var nextCursor int64
if // err 保存清理空会话的错误。
err := s.chatApplication().CleanupEmptySessions(r.Context(), accountID); err != nil {
@@ -92,23 +102,23 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOsFromApplication(rows), HasMore: hasMore, NextCursor: nextCursor})
}
// sendChatImage 负责send聊天图片相关处理。
// sendChatImage 封装send聊天图片业务协调。
func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
if !s.chatApplication().ImageUploadAvailable() {
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
return
}
r.Body = http.MaxBytesReader(w, r.Body, 10<<20)
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := r.ParseMultipartForm(10 << 20); err != nil {
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
return
}
// accountID 保存账号ID,供当前处理流程使用
// accountID 用于本次流程后续判断的账号ID
accountID := strings.TrimSpace(r.FormValue("account_id"))
// chatID 保存聊天ID,供当前处理流程使用
// chatID 用于本次流程后续判断的聊天ID
chatID := strings.TrimSpace(r.FormValue("chat_id"))
// buyerID 保存买家ID,供当前处理流程使用
// buyerID 用于本次流程后续判断的买家ID
buyerID := strings.TrimSpace(r.FormValue("buyer_id"))
if !s.ownsAccount(r, accountID) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
@@ -118,20 +128,20 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "会话和买家不能为空")
return
}
// file、header、err 保存file、header、err,供当前处理流程使用
// file、header、err 用于本次流程后续判断的file、header、err
file, header, err := r.FormFile("image")
if err != nil {
writeErr(w, http.StatusBadRequest, "请选择图片")
return
}
defer file.Close()
// contentType 保存内容类型,供当前处理流程使用
// contentType 用于本次流程后续判断的内容类型
contentType := header.Header.Get("Content-Type")
if !strings.HasPrefix(strings.ToLower(contentType), "image/") {
writeErr(w, http.StatusBadRequest, "只支持图片文件")
return
}
// data、err 保存data、err,供当前处理流程使用
// data、err 用于本次流程后续判断的data、err
data, err := io.ReadAll(io.LimitReader(file, (10<<20)+1))
if err != nil || len(data) == 0 || len(data) > 10<<20 {
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
@@ -141,7 +151,7 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
session := chatapp.Session{AccountID: accountID, ChatID: chatID, BuyerID: buyerID,
BuyerName: r.FormValue("buyer_name"), BuyerAvatar: r.FormValue("buyer_avatar_url"),
ItemID: r.FormValue("item_id"), ItemTitle: r.FormValue("item_title")}
// sent、err 保存sent、err,供当前处理流程使用
// sent、err 用于本次流程后续判断的sent、err
sent, err := s.chatApplication().SendImage(r.Context(), chatapp.ImageInput{Session: session, Filename: header.Filename, ContentType: contentType, Data: data})
if err != nil {
if errors.Is(err, chatapp.ErrUnavailable) {
@@ -160,13 +170,13 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromApplication(sent)})
}
// listChatMessages 负责list聊天消息列表相关处理。
// listChatMessages 封装list聊天消息列表业务协调。
func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// accountID 保存账号ID,供当前处理流程使用
// accountID 用于本次流程后续判断的账号ID
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
// chatID 保存聊天ID,供当前处理流程使用
// chatID 用于本次流程后续判断的聊天ID
chatID := strings.TrimSpace(r.URL.Query().Get("chat_id"))
if !s.ownsAccount(r, accountID) {
writeErr(w, http.StatusForbidden, "无权访问该账号")
@@ -176,11 +186,11 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "缺少 chat_id")
return
}
// beforeID 保存beforeID,供当前处理流程使用
// beforeID 用于本次流程后续判断的beforeID
beforeID, _ := strconv.ParseInt(r.URL.Query().Get("before_id"), 10, 64)
// cursor 保存游标,供当前处理流程使用
// cursor 用于本次流程后续判断的游标
cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64)
// limit 保存上限,供当前处理流程使用
// limit 用于本次流程后续判断的上限
limit := parsePositiveInt(r.URL.Query().Get("limit"), 50)
// current 保存刷新前的本地会话摘要,供平台历史写入和响应展示使用。
current, _ := s.chatApplication().FindSession(r.Context(), sess.UserID, accountID, chatID)
@@ -205,7 +215,7 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
if !errors.Is(fetchErr, chatapp.ErrRefreshUnavailable) && !errors.Is(fetchErr, chatapp.ErrOffline) {
s.recoverExpiredSession(r.Context(), accountID, fetchErr)
}
// page、err 保存page、err,供当前处理流程使用
// page、err 用于本次流程后续判断的page、err
page, err := s.chatApplication().ListStoredMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, limit)
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取聊天消息失败")
@@ -224,7 +234,7 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTOFromApplication(session)})
}
// sendChatMessageRequest 保存send聊天消息请求,供当前处理流程使用
// sendChatMessageRequest 用于本次流程后续判断的send聊天消息请求
type sendChatMessageRequest struct {
AccountID string `json:"account_id"`
ChatID string `json:"chat_id"`
@@ -235,15 +245,15 @@ type sendChatMessageRequest struct {
Text string `json:"text"`
}
// sendChatMessage 负责send聊天消息相关处理。
// sendChatMessage 封装send聊天消息业务协调。
func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
if !s.chatApplication().SendingAvailable() {
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
return
}
// input 保存input,供当前处理流程使用
// input 用于本次流程后续判断的input
var input sendChatMessageRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &input); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -281,14 +291,10 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromApplication(sent)})
}
// markChatRead 负责mark聊天Read相关处理。
// markChatRead 封装mark聊天Read业务协调。
func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
// input 保存input,供当前处理流程使用
var input struct {
AccountID string `json:"account_id"`
ChatID string `json:"chat_id"`
MessageIDs []map[string]any `json:"message_ids"`
}
// input 是聊天已读请求的具名传输 DTO。
var input markChatReadRequest
if decodeJSON(r, &input) != nil || input.ChatID == "" {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -382,7 +388,7 @@ func findChatPlatformMessageID(value any, chatID, legacyID string) string {
// chatWebSocket 将应用层聊天事件转发到当前认证用户的 WebSocket 连接。
func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// events、unsubscribe、err 保存应用层实时事件、清理函数和订阅错误。
events, unsubscribe, err := s.chatApplication().Subscribe(r.Context(), sess.UserID)
@@ -394,13 +400,13 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
}
return
}
// conn、err 保存conn、err,供当前处理流程使用
// conn、err 用于本次流程后续判断的conn、err
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionContextTakeover})
if err != nil {
unsubscribe()
return
}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
// ctx、cancel 用于本次流程后续判断的ctx、cancel
ctx, cancel := context.WithCancel(r.Context())
conn.SetReadLimit(8 << 10)
// readerWG 等待读取 goroutine 在连接关闭后退出,避免请求返回时遗留后台任务。
@@ -409,7 +415,7 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
go func() {
defer readerWG.Done()
for {
if // readErr 保存readErr,供当前处理流程使用
if // readErr 用于本次流程后续判断的readErr
_, _, readErr := conn.Read(ctx); readErr != nil {
cancel()
return
@@ -424,7 +430,7 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
unsubscribe()
}
defer cleanup()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := wsjson.Write(ctx, conn, map[string]any{"type": "ready", "at": time.Now().UTC().UnixMilli()}); err != nil {
return
}
@@ -432,7 +438,7 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
select {
case <-ctx.Done():
return
case // event、ok 保存event、ok,供当前处理流程使用
case // event、ok 用于本次流程后续判断的event、ok
event, ok := <-events:
if !ok || wsjson.Write(ctx, conn, newChatEventDTOFromApplication(event)) != nil {
return
@@ -441,12 +447,12 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
}
}
// ownsAccount 负责owns账号相关处理。
// ownsAccount 封装owns账号业务协调。
func (s *Server) ownsAccount(r *http.Request, accountID string) bool {
if accountID == "" {
return false
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// owned 和 err 表示聊天应用端口返回的账号归属及查询错误。
owned, err := s.chatApplication().OwnsAccount(r.Context(), sess.UserID, accountID)
@@ -457,9 +463,9 @@ func (s *Server) ownsAccount(r *http.Request, accountID string) bool {
账号查询已采用所有权窄接口。
*/
// parsePositiveInt 将正整数文本转换为整数,无法解析时返回备用值。
// parsePositiveInt 负责parsePositiveInt相关处理。
// parsePositiveInt 封装parsePositiveInt业务协调。
func parsePositiveInt(raw string, fallback int) int {
// value、err 保存value、err,供当前处理流程使用
// value、err 用于本次流程后续判断的value、err
value, err := strconv.Atoi(raw)
if err != nil || value <= 0 {
return fallback
+107 -73
View File
@@ -37,9 +37,9 @@ func (s *Server) mountCookies(r chi.Router) {
r.Get("/cookies/{cid}/pause-duration", s.getCookiePauseDuration)
}
// getLongLoginSettings 负责getLong登录设置相关处理。
// getLongLoginSettings 封装getLong登录设置业务协调。
func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
// ownedDetail、ok 保存账号摘要和归属校验结果。
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
@@ -55,20 +55,18 @@ func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, longLoginResponse{CanOpenLongLogin: result.CanOpenLongLogin, Enabled: result.Enabled})
}
// setLongLoginSettings 负责setLong登录设置相关处理。
// setLongLoginSettings 封装setLong登录设置业务协调。
func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
// ownedDetail、ok 保存ownedDetail、ok,供当前处理流程使用
// ownedDetail、ok 用于本次流程后续判断的ownedDetail、ok
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Enabled *bool `json:"enabled"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req longLoginSettingsRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil || req.Enabled == nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -99,7 +97,7 @@ func (s *Server) writeLongLoginError(w http.ResponseWriter, err error) {
writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
}
// updateRunningCookie 负责updateRunning登录凭证相关处理。
// updateRunningCookie 封装updateRunning登录凭证业务协调。
func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string) {
// runtimeService 负责唤醒凭证阻塞任务并将 Cookie 同步到账号运行实例。
runtimeService := s.accountRuntimeApplication()
@@ -112,7 +110,7 @@ func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string
}
}
// updateCookieSettingsRequest 保存update登录凭证设置请求,供当前处理流程使用
// updateCookieSettingsRequest 用于本次流程后续判断的update登录凭证设置请求
type updateCookieSettingsRequest struct {
Cookie *string `json:"cookie"`
Remark *string `json:"remark"`
@@ -125,18 +123,72 @@ type updateCookieSettingsRequest struct {
ChannelIDs *[]int64 `json:"channel_ids"`
}
// longLoginSettingsRequest 是更新账号长登录开关的 HTTP 请求 DTO。
type longLoginSettingsRequest struct {
// Enabled 是必须明确提供的长登录开关值。
Enabled *bool `json:"enabled"`
}
// createCookieRequest 是创建账号 Cookie 的 HTTP 请求 DTO。
type createCookieRequest struct {
// ID 是调用方提供的账号标识。
ID string `json:"id"`
// Value 是仅在本次请求作用域内写入的明文 Cookie。
Value string `json:"value"`
// LoginMethod 是用于审计的可选登录方式。
LoginMethod string `json:"login_method"`
}
// cookieLoginInfoRequest 是更新账号登录资料的 HTTP 请求 DTO。
type cookieLoginInfoRequest struct {
// Username 是可选的平台登录用户名。
Username string `json:"username"`
// Password 是当前客户端使用的登录密码字段。
Password string `json:"password"`
// LoginPassword 是历史客户端使用的兼容密码字段。
LoginPassword string `json:"login_password"`
// ShowBrowser 表示密码登录时是否展示浏览器窗口。
ShowBrowser bool `json:"show_browser"`
// ClearPassword 明确请求清除已保存的登录密码。
ClearPassword bool `json:"clear_password"`
}
// cookieStatusRequest 是启用或停用账号运行时的 HTTP 请求 DTO。
type cookieStatusRequest struct {
// Enabled 表示账号是否应保持启用状态。
Enabled bool `json:"enabled"`
}
// cookieAutoConfirmRequest 是更新自动确认发货开关的 HTTP 请求 DTO。
type cookieAutoConfirmRequest struct {
// AutoConfirm 表示是否允许系统自动确认发货。
AutoConfirm bool `json:"auto_confirm"`
}
// cookieRemarkRequest 是更新账号备注的 HTTP 请求 DTO。
type cookieRemarkRequest struct {
// Remark 是用户维护的非敏感账号显示备注。
Remark string `json:"remark"`
}
// cookiePauseDurationRequest 是更新账号自动化暂停时长的 HTTP 请求 DTO。
type cookiePauseDurationRequest struct {
// PauseDuration 是暂停自动化操作的分钟数。
PauseDuration int `json:"pause_duration"`
}
// updateCookieSettings 原子保存编辑弹窗中的账号字段和通知绑定。
func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
// detail、ok 保存detail、ok,供当前处理流程使用
// detail、ok 用于本次流程后续判断的detail、ok
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
var req updateCookieSettingsRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -340,7 +392,7 @@ func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) {
func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid") // cid 是请求路径中的账号 ID。
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
// profile、err 保存profile、err,供当前处理流程使用
// profile、err 用于本次流程后续判断的profile、err
profile, err := s.accountProfileApplication().RefreshProfile(r.Context(), sess.UserID, cid)
if err != nil {
if errors.Is(err, accountapp.ErrForbidden) {
@@ -380,20 +432,16 @@ func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
// addCookie 添加账号 cookie。
func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
ID string `json:"id"`
Value string `json:"value"`
LoginMethod string `json:"login_method"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req createCookieRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil || req.ID == "" || req.Value == "" {
writeErr(w, http.StatusBadRequest, "缺少 id 或 value")
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.accountLoginApplication().CreateCookie(r.Context(), accountLoginInput{AccountID: req.ID, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
if errors.Is(err, accountapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "该账号ID已存在且不属于当前用户")
@@ -421,23 +469,23 @@ type updateCookieRequest struct {
// updateCookie 更新 cookie 值。
func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
// ok 保存ok,供当前处理流程使用
// ok 用于本次流程后续判断的ok
_, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// req 保存请求中的 Cookie、登录方式和可选凭证版本。
var req updateCookieRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.accountLoginApplication().UpdateCookie(r.Context(), accountCookieUpdateInput{AccountID: cid, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod, ExpectedRevision: req.LastRefreshAt}); err != nil {
if errors.Is(err, accountapp.ErrCredentialConflict) {
writeErr(w, http.StatusConflict, err.Error())
@@ -455,22 +503,16 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
// updateCookieLoginInfo 更新账号登录信息(用户名/密码/显示浏览器)。
func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
// detail、ok 保存非敏感账号摘要和归属校验结果。
detail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Username string `json:"username"`
Password string `json:"password"`
LoginPassword string `json:"login_password"`
ShowBrowser bool `json:"show_browser"`
ClearPassword bool `json:"clear_password"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req cookieLoginInfoRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -497,18 +539,16 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
// setCookieStatus 启用/禁用账号。
func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
// ownedDetail、ok 保存ownedDetail、ok,供当前处理流程使用
// ownedDetail、ok 用于本次流程后续判断的ownedDetail、ok
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Enabled bool `json:"enabled"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req cookieStatusRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -535,9 +575,9 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
// deleteCookie 删除账号。
func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
// ownedDetail、ok 保存ownedDetail、ok,供当前处理流程使用
// ownedDetail、ok 用于本次流程后续判断的ownedDetail、ok
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
@@ -582,16 +622,14 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
// setCookieAutoConfirm 设置自动确认发货。
func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
AutoConfirm bool `json:"auto_confirm"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req cookieAutoConfirmRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -612,9 +650,9 @@ func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
// getCookieAutoConfirm 获取自动确认发货设置。
func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
// d、ok 保存d、ok,供当前处理流程使用
// d、ok 用于本次流程后续判断的d、ok
d, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
@@ -624,16 +662,14 @@ func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
// setCookieRemark 设置备注。
func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
Remark string `json:"remark"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req cookieRemarkRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -654,16 +690,14 @@ func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
// setCookiePauseDuration 设置暂停时长。
func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存req,供当前处理流程使用
var req struct {
PauseDuration int `json:"pause_duration"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req cookiePauseDurationRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -691,7 +725,7 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request)
// getCookiePauseDuration 获取暂停时长。
func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cid")
if !s.requireCookieOwnership(w, r, cid) {
return
@@ -716,7 +750,7 @@ func cachedAccountSummaryNickname(summary accountapp.AccountSummary) string {
return "账号 " + truncate(summary.ID, 6)
}
// normalizeProfileAvatarURL 负责normalizeProfileAvatarURL相关处理。
// normalizeProfileAvatarURL 封装normalizeProfileAvatarURL业务协调。
func normalizeProfileAvatarURL(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
@@ -731,7 +765,7 @@ func normalizeProfileAvatarURL(raw string) string {
return raw
}
// truncate 负责truncate相关处理。
// truncate 封装truncate业务协调。
func truncate(s string, n int) string {
if len(s) <= n {
return s
File diff suppressed because it is too large. Load diff
+45 -45
View File
@@ -11,20 +11,20 @@ import (
// TestListDefaultReplies 列表(数组形式)。
func TestListDefaultReplies(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 设置。
body := `{"enabled":true,"reply_content":"你好","reply_once":false}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -34,13 +34,13 @@ func TestListDefaultReplies(t *testing.T) {
// 列表(数组)。
req2 := httptest.NewRequest(http.MethodGet, "/default-replies", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("list status=%d", rec2.Code)
}
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["reply_content"] != "你好" {
@@ -50,13 +50,13 @@ func TestListDefaultReplies(t *testing.T) {
// 列表(map 形式,兼容路径)。
req3 := httptest.NewRequest(http.MethodGet, "/api/default-replies", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
t.Fatalf("map status=%d", rec3.Code)
}
// m 保存m,供当前处理流程使用
// m 用于本次流程后续判断的m
var m map[string]map[string]any
json.Unmarshal(rec3.Body.Bytes(), &m)
if m["acc1"]["reply_content"] != "你好" {
@@ -66,18 +66,18 @@ func TestListDefaultReplies(t *testing.T) {
// TestSetDefaultReplyBadJSON 非法 JSON 400。
func TestSetDefaultReplyBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -85,20 +85,20 @@ func TestSetDefaultReplyBadJSON(t *testing.T) {
}
}
// TestGetDefaultReplyMissingAccountIsNotFound 负责TestGetDefault回复Missing账号IsNotFound相关处理。
// TestGetDefaultReplyMissingAccountIsNotFound 封装TestGetDefault回复Missing账号IsNotFound业务协调。
func TestGetDefaultReplyMissingAccountIsNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/default-replies/no-such", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -106,26 +106,26 @@ func TestGetDefaultReplyMissingAccountIsNotFound(t *testing.T) {
}
}
// TestGetDefaultReplyExistingAccountWithoutConfigReturnsDefault 负责TestGetDefault回复Existing账号Without配置ReturnsDefault相关处理。
// TestGetDefaultReplyExistingAccountWithoutConfigReturnsDefault 封装TestGetDefault回复Existing账号Without配置ReturnsDefault业务协调。
func TestGetDefaultReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/default-replies/acc1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["enabled"] != false || got["reply_content"] != "" {
@@ -133,35 +133,35 @@ func TestGetDefaultReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T)
}
}
// TestGetDefaultReplyRejectsCrossUserAccount 负责TestGetDefault回复RejectsCross用户账号相关处理。
// TestGetDefaultReplyRejectsCrossUserAccount 封装TestGetDefault回复RejectsCross用户账号业务协调。
func TestGetDefaultReplyRejectsCrossUserAccount(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.Users.Create(ctx, "default-other", "[email protected]", "pw"); err != nil {
t.Fatalf("create other user: %v", err)
}
// other、err 保存other、err,供当前处理流程使用
// other、err 用于本次流程后续判断的other、err
other, err := store.Users.GetByUsername(ctx, "default-other")
if err != nil {
t.Fatalf("get other user: %v", err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.Cookies.Save(ctx, "other-acc", "unb=456; _m_h5_tk=tk2_1;", other.ID); err != nil {
t.Fatalf("save other cookie: %v", err)
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/default-replies/other-acc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
@@ -171,27 +171,27 @@ func TestGetDefaultReplyRejectsCrossUserAccount(t *testing.T) {
// TestDeleteDefaultReply 删除。
func TestDeleteDefaultReply(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 设置。
body := `{"enabled":true,"reply_content":"你好"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// 删除。
req2 := httptest.NewRequest(http.MethodDelete, "/default-replies/acc1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -211,11 +211,11 @@ func TestBtoi(t *testing.T) {
// TestNullIfEmpty nullIfEmpty 表驱动。
func TestNullIfEmpty(t *testing.T) {
if // v 保存v,供当前处理流程使用
if // v 用于本次流程后续判断的v
v := nullIfEmpty(""); v != nil {
t.Fatalf("空串应为 nil,got %v", v)
}
if // v 保存v,供当前处理流程使用
if // v 用于本次流程后续判断的v
v := nullIfEmpty("x"); v != "x" {
t.Fatalf("非空应原样返回,got %v", v)
}
+1 -1
View File
@@ -39,7 +39,7 @@ func (s *Server) mountDefaultRepliesReal(r chi.Router) {
r.Post("/api/default-reply/{cid}/clear-records", s.clearDefaultReplyRecords)
}
// getDefaultReply 负责getDefault回复相关处理。
// getDefaultReply 封装getDefault回复业务协调。
func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
// cid 是路径中的默认回复所属账号标识。
cid := chi.URLParam(r, "cid")
+31 -31
View File
@@ -15,17 +15,17 @@ func loginHelper(t *testing.T, h http.Handler) *http.Cookie {
return loginAsHelper(t, h, "admin", "pw")
}
// loginAsHelper 负责登录AsHelper相关处理。
// loginAsHelper 封装登录AsHelper业务协调。
func loginAsHelper(t *testing.T, h http.Handler, username, password string) *http.Cookie {
t.Helper()
// body、err 保存body、err,供当前处理流程使用
// body、err 用于本次流程后续判断的body、err
body, err := json.Marshal(map[string]string{"username": username, "password": password})
if err != nil {
t.Fatal(err)
}
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(string(body)))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || len(rec.Result().Cookies()) == 0 {
@@ -36,30 +36,30 @@ func loginAsHelper(t *testing.T, h http.Handler, username, password string) *htt
// TestOrderListAndDetail 订单列表 + 详情 + 状态码归一。
func TestOrderListAndDetail(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// 插入一条订单(order_status 用数字码 "2" 测试归一)。
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id) VALUES ('ord1','item1','buyer1','2','acc1')`)
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_detail) VALUES ('acc1','item1','测试商品','{"pic_info":{"picUrl":"https://img.example/item.png"}}')`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 列表。
req := httptest.NewRequest(http.MethodGet, "/api/orders", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("list status=%d body=%s", rec.Code, rec.Body.String())
}
// resp 保存resp,供当前处理流程使用
// resp 用于本次流程后续判断的resp
var resp struct {
Success bool `json:"success"`
Total int `json:"total"`
@@ -82,13 +82,13 @@ func TestOrderListAndDetail(t *testing.T) {
// 详情。
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/ord1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("detail status=%d", rec2.Code)
}
// det 保存det,供当前处理流程使用
// det 用于本次流程后续判断的det
var det map[string]any
json.Unmarshal(rec2.Body.Bytes(), &det)
if det["order_id"] != "ord1" {
@@ -101,19 +101,19 @@ func TestOrderListAndDetail(t *testing.T) {
// 删除。
req3 := httptest.NewRequest(http.MethodDelete, "/api/orders/ord1", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
t.Fatalf("delete status=%d", rec3.Code)
}
// deletedAt 保存deletedAt,供当前处理流程使用
// deletedAt 用于本次流程后续判断的deletedAt
var deletedAt string
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.DB.QueryRowContext(ctx, `SELECT COALESCE(deleted_at,'') FROM orders WHERE order_id=?`, "ord1").Scan(&deletedAt); err != nil || deletedAt == "" {
t.Fatalf("订单删除应为逻辑删除,deleted_at=%q err=%v", deletedAt, err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.Orders.Get(ctx, "ord1"); err == nil {
t.Fatal("逻辑删除订单不应再出现在活动订单查询中")
}
@@ -121,29 +121,29 @@ func TestOrderListAndDetail(t *testing.T) {
// TestCardCRUD 卡券增删改查。
func TestCardCRUD(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 创建。
body := `{"name":"测试卡","type":"text","text_content":"卡密ABC","enabled":true}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
}
// cr 保存cr,供当前处理流程使用
// cr 用于本次流程后续判断的cr
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
// id 保存标识,供当前处理流程使用
// id 用于本次流程后续判断的标识
id := cr["id"].(float64)
if id == 0 {
t.Fatal("应返回 id")
@@ -152,10 +152,10 @@ func TestCardCRUD(t *testing.T) {
// 列表。
req2 := httptest.NewRequest(http.MethodGet, "/cards", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["name"] != "测试卡" {
@@ -164,10 +164,10 @@ func TestCardCRUD(t *testing.T) {
// 更新。
updBody := `{"name":"改名卡","type":"text","text_content":"卡密XYZ","enabled":true}`
// req3 保存req3,供当前处理流程使用
// req3 用于本次流程后续判断的req3
req3 := httptest.NewRequest(http.MethodPut, "/cards/"+itoa(int64(id)), strings.NewReader(updBody))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -177,10 +177,10 @@ func TestCardCRUD(t *testing.T) {
// 获取验证改名。
req4 := httptest.NewRequest(http.MethodGet, "/cards/"+itoa(int64(id)), nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
json.Unmarshal(rec4.Body.Bytes(), &got)
if got["name"] != "改名卡" {
@@ -190,7 +190,7 @@ func TestCardCRUD(t *testing.T) {
// 删除。
req5 := httptest.NewRequest(http.MethodDelete, "/cards/"+itoa(int64(id)), nil)
req5.AddCookie(cookie)
// rec5 保存rec5,供当前处理流程使用
// rec5 用于本次流程后续判断的rec5
rec5 := httptest.NewRecorder()
h.ServeHTTP(rec5, req5)
if rec5.Code != 200 {
@@ -198,5 +198,5 @@ func TestCardCRUD(t *testing.T) {
}
}
// itoa 负责itoa相关处理。
// itoa 封装itoa业务协调。
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
+108 -108
View File
@@ -11,20 +11,20 @@ import (
// TestKeywordsCRUD 关键字增删查。
func TestKeywordsCRUD(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 添加(普通 + 商品ID)。
post := func(body string) {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -37,10 +37,10 @@ func TestKeywordsCRUD(t *testing.T) {
// 列表(带类型)。
req := httptest.NewRequest(http.MethodGet, "/keywords-with-type/acc1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec.Body.Bytes(), &arr)
if len(arr) != 2 {
@@ -50,7 +50,7 @@ func TestKeywordsCRUD(t *testing.T) {
// 按索引删除第一条。
req2 := httptest.NewRequest(http.MethodDelete, "/keywords/acc1/0", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -60,20 +60,20 @@ func TestKeywordsCRUD(t *testing.T) {
// TestDefaultReplyCRUD 默认回复。
func TestDefaultReplyCRUD(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 设置。
body := `{"enabled":true,"reply_content":"你好老板","reply_once":true}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -83,10 +83,10 @@ func TestDefaultReplyCRUD(t *testing.T) {
// 读取。
req2 := httptest.NewRequest(http.MethodGet, "/default-replies/acc1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// dr 保存dr,供当前处理流程使用
// dr 用于本次流程后续判断的dr
var dr map[string]any
json.Unmarshal(rec2.Body.Bytes(), &dr)
if dr["enabled"] != true || dr["reply_content"] != "你好老板" || dr["reply_once"] != true {
@@ -96,28 +96,28 @@ func TestDefaultReplyCRUD(t *testing.T) {
// 前端兼容路径:/api/default-reply/* 与 /api/default-replies。
req3 := httptest.NewRequest(http.MethodPut, "/api/default-reply/acc1", strings.NewReader(body))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
t.Fatalf("compat set status=%d", rec3.Code)
}
// req4 保存req4,供当前处理流程使用
// req4 用于本次流程后续判断的req4
req4 := httptest.NewRequest(http.MethodGet, "/api/default-replies", nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
// all 保存all,供当前处理流程使用
// all 用于本次流程后续判断的all
var all map[string]map[string]any
json.Unmarshal(rec4.Body.Bytes(), &all)
if all["acc1"]["reply_content"] != "你好老板" {
t.Fatalf("兼容默认回复列表异常: %+v", all)
}
// req5 保存req5,供当前处理流程使用
// req5 用于本次流程后续判断的req5
req5 := httptest.NewRequest(http.MethodPost, "/api/default-reply/acc1/clear-records", nil)
req5.AddCookie(cookie)
// rec5 保存rec5,供当前处理流程使用
// rec5 用于本次流程后续判断的rec5
rec5 := httptest.NewRecorder()
h.ServeHTTP(rec5, req5)
if rec5.Code != 200 {
@@ -127,37 +127,37 @@ func TestDefaultReplyCRUD(t *testing.T) {
// TestNotificationChannelCRUD 通知渠道 + 绑定。
func TestNotificationChannelCRUD(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 创建渠道。
body := `{"name":"我的钉钉","type":"dingtalk","config":"{\"webhook_url\":\"http://x\"}","enabled":true}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("create channel status=%d body=%s", rec.Code, rec.Body.String())
}
// cr 保存cr,供当前处理流程使用
// cr 用于本次流程后续判断的cr
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
// id 保存标识,供当前处理流程使用
// id 用于本次流程后续判断的标识
id := int64(cr["id"].(float64))
// 绑定到账号。
bindBody := `{"channel_ids":[` + itoa(id) + `]}`
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(bindBody))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -167,13 +167,13 @@ func TestNotificationChannelCRUD(t *testing.T) {
// 查询绑定。
req3 := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// b 保存b,供当前处理流程使用
// b 用于本次流程后续判断的b
var b map[string]any
json.Unmarshal(rec3.Body.Bytes(), &b)
// ids 保存ids,供当前处理流程使用
// ids 用于本次流程后续判断的ids
ids, _ := b["channel_ids"].([]any)
if len(ids) != 1 {
t.Fatalf("绑定数异常: %+v", b)
@@ -182,49 +182,49 @@ func TestNotificationChannelCRUD(t *testing.T) {
// TestSystemSettings 系统设置。
func TestSystemSettings(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 公开设置无需登录。
req := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("public settings status=%d", rec.Code)
}
// pub 保存pub,供当前处理流程使用
// pub 用于本次流程后续判断的pub
var pub map[string]any
json.Unmarshal(rec.Body.Bytes(), &pub)
if // ok 保存ok,供当前处理流程使用
if // ok 用于本次流程后续判断的ok
_, ok := pub["theme_color"]; !ok {
t.Fatalf("公开设置应含 theme_color: %+v", pub)
}
// 已认证:设置 + 读取全部。
body := `{"value":"green"}`
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader(body))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("set status=%d", rec2.Code)
}
// req3 保存req3,供当前处理流程使用
// req3 用于本次流程后续判断的req3
req3 := httptest.NewRequest(http.MethodGet, "/system-settings", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// all 保存all,供当前处理流程使用
// all 用于本次流程后续判断的all
var all map[string]any
json.Unmarshal(rec3.Body.Bytes(), &all)
if all["theme_color"] != "green" {
@@ -234,20 +234,20 @@ func TestSystemSettings(t *testing.T) {
// TestAIReplySettings AI 回复设置。
func TestAIReplySettings(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"按商品信息回复"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -257,10 +257,10 @@ func TestAIReplySettings(t *testing.T) {
// 账号级设置只包含开关、议价策略和自定义提示词;模型/API Key/URL 走系统设置。
req2 := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// cfg 保存cfg,供当前处理流程使用
// cfg 用于本次流程后续判断的cfg
var cfg map[string]any
json.Unmarshal(rec2.Body.Bytes(), &cfg)
if cfg["ai_enabled"] != true ||
@@ -270,22 +270,22 @@ func TestAIReplySettings(t *testing.T) {
cfg["custom_prompts"] != "按商品信息回复" {
t.Fatalf("AI 设置异常: %+v", cfg)
}
if // ok 保存ok,供当前处理流程使用
if // ok 用于本次流程后续判断的ok
_, ok := cfg["model_name"]; ok {
t.Fatalf("账号级 AI 设置不应返回模型: %+v", cfg)
}
if // ok 保存ok,供当前处理流程使用
if // ok 用于本次流程后续判断的ok
_, ok := cfg["api_key"]; ok {
t.Fatalf("账号级 AI 设置不应返回 API Key: %+v", cfg)
}
// req3 保存req3,供当前处理流程使用
// req3 用于本次流程后续判断的req3
req3 := httptest.NewRequest(http.MethodGet, "/ai-reply-settings", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// all 保存all,供当前处理流程使用
// all 用于本次流程后续判断的all
var all map[string]map[string]any
json.Unmarshal(rec3.Body.Bytes(), &all)
if all["acc1"]["ai_enabled"] != true {
@@ -293,14 +293,14 @@ func TestAIReplySettings(t *testing.T) {
}
}
// TestAIReplySettingsRejectInvalidBargainLimits 负责TestAI回复设置RejectInvalidBargainLimits相关处理。
// TestAIReplySettingsRejectInvalidBargainLimits 封装TestAI回复设置RejectInvalidBargainLimits业务协调。
func TestAIReplySettingsRejectInvalidBargainLimits(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 表示当前遍历过程中的请求体
@@ -309,10 +309,10 @@ func TestAIReplySettingsRejectInvalidBargainLimits(t *testing.T) {
`{"ai_enabled":true,"max_discount_percent":1,"max_discount_amount":-1,"max_bargain_rounds":1}`,
`{"ai_enabled":true,"max_discount_percent":1,"max_discount_amount":1,"max_bargain_rounds":0}`,
} {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -321,14 +321,14 @@ func TestAIReplySettingsRejectInvalidBargainLimits(t *testing.T) {
}
}
// TestParseOpenAIModels 负责TestParseOpenAI模型列表相关处理。
// TestParseOpenAIModels 封装TestParseOpenAI模型列表业务协调。
func TestParseOpenAIModels(t *testing.T) {
// models、err 保存models、err,供当前处理流程使用
// models、err 用于本次流程后续判断的models、err
models, err := parseOpenAIModels([]byte(`{"data":[{"id":"qwen-plus"},{"id":"qwen-max"},{"name":"fallback-name"}]}`))
if err != nil {
t.Fatalf("parse models: %v", err)
}
// want 保存want,供当前处理流程使用
// want 用于本次流程后续判断的want
want := []string{"qwen-plus", "qwen-max", "fallback-name"}
if len(models) != len(want) {
t.Fatalf("models length=%d want=%d: %+v", len(models), len(want), models)
@@ -343,24 +343,24 @@ func TestParseOpenAIModels(t *testing.T) {
// TestItems 物品列表 + 多规格设置。
func TestItems(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it1','商品A')`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 列表。
req := httptest.NewRequest(http.MethodGet, "/items", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["item_title"] != "商品A" {
@@ -369,10 +369,10 @@ func TestItems(t *testing.T) {
// 设置多规格。
body := `{"is_multi_spec":true}`
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodPut, "/items/acc1/it1/multi-spec", strings.NewReader(body))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -389,45 +389,45 @@ func TestItems(t *testing.T) {
}
}
// TestOrderImportCompat 负责Test订单ImportCompat相关处理。
// TestOrderImportCompat 封装Test订单ImportCompat业务协调。
func TestOrderImportCompat(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `[{"order_id":"order-import-1","item_id":"item-import-1","item_title":"导入商品","buyer_id":"buyer1","status":"pending_ship","quantity":2,"amount":"19.90"}]`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("import status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success_count"] != float64(1) {
t.Fatalf("导入结果异常: %+v", res)
}
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/order-import-1", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("get imported order status=%d body=%s", rec2.Code, rec2.Body.String())
}
// order 保存订单,供当前处理流程使用
// order 用于本次流程后续判断的订单
var order map[string]any
json.Unmarshal(rec2.Body.Bytes(), &order)
if order["cookie_id"] != "acc1" || order["status"] != "pending_ship" {
@@ -435,34 +435,34 @@ func TestOrderImportCompat(t *testing.T) {
}
}
// TestOrderImportReportsPartialFailure 负责Test订单ImportReportsPartialFailure相关处理。
// TestOrderImportReportsPartialFailure 封装Test订单ImportReportsPartialFailure业务协调。
func TestOrderImportReportsPartialFailure(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `[{"order_id":"order-ok","status":"pending_ship"},{"item_id":"missing-order-id"}]`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// result 保存结果,供当前处理流程使用
// result 用于本次流程后续判断的结果
var result struct {
PartialFailure bool `json:"partial_failure"`
SuccessCount int `json:"success_count"`
FailedCount int `json:"failed_count"`
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
@@ -473,25 +473,25 @@ func TestOrderImportReportsPartialFailure(t *testing.T) {
// TestAdminEndpoints 管理员统计 + 用户列表 + 非 admin 被拒。
func TestAdminEndpoints(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// stats。
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("stats status=%d", rec.Code)
}
// stats 保存stats,供当前处理流程使用
// stats 用于本次流程后续判断的stats
var stats map[string]any
json.Unmarshal(rec.Body.Bytes(), &stats)
if stats["total_users"] == nil || stats["total_cookies"] == nil {
@@ -501,10 +501,10 @@ func TestAdminEndpoints(t *testing.T) {
// 用户列表。
req2 := httptest.NewRequest(http.MethodGet, "/admin/users", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// users 保存用户列表,供当前处理流程使用
// users 用于本次流程后续判断的用户列表
var users []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &users)
if len(users) != 1 || users[0]["username"] != "admin" {
@@ -516,10 +516,10 @@ func TestAdminEndpoints(t *testing.T) {
// 普通用户不应能访问 admin(需单独登录验证,此处仅验证 admin 能看到)。
req3 := httptest.NewRequest(http.MethodGet, "/admin/users", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// users2 保存users2,供当前处理流程使用
// users2 用于本次流程后续判断的users2
var users2 []map[string]any
json.Unmarshal(rec3.Body.Bytes(), &users2)
if len(users2) != 2 {
@@ -529,15 +529,15 @@ func TestAdminEndpoints(t *testing.T) {
// TestPublicSettingsNoAuth 公开设置无需登录。
func TestPublicSettingsNoAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
+39 -39
View File
@@ -10,18 +10,18 @@ import (
// TestOrderDetailNotFound 查询不存在的订单应 404。
func TestOrderDetailNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/api/orders/no-such-order", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -31,20 +31,20 @@ func TestOrderDetailNotFound(t *testing.T) {
// TestCardEndpointsErrorBranches 卡券相关错误分支:
// 无效 ID → 400;不存在 → 404;请求体非法 → 400。
// TestCardEndpointsErrorBranches 负责Test卡密Endpoints错误Branches相关处理。
// TestCardEndpointsErrorBranches 封装Test卡密Endpoints错误Branches业务协调。
func TestCardEndpointsErrorBranches(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 无效 card_id(非数字)→ 400。
req := httptest.NewRequest(http.MethodGet, "/cards/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -54,7 +54,7 @@ func TestCardEndpointsErrorBranches(t *testing.T) {
// 合法但不存在的 ID → 404。
req2 := httptest.NewRequest(http.MethodGet, "/cards/999999", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusNotFound {
@@ -64,7 +64,7 @@ func TestCardEndpointsErrorBranches(t *testing.T) {
// 创建卡券请求体非法 → 400。
req3 := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader("not-json"))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != http.StatusBadRequest {
@@ -74,7 +74,7 @@ func TestCardEndpointsErrorBranches(t *testing.T) {
// 创建卡券缺类型 → 400(decodeCard 校验)。
req4 := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(`{"name":"无类型卡"}`))
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != http.StatusBadRequest {
@@ -82,14 +82,14 @@ func TestCardEndpointsErrorBranches(t *testing.T) {
}
}
// TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay 负责TestCreate卡密RejectsUnsupportedAPI类型AndInvalid延迟相关处理。
// TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay 封装TestCreate卡密RejectsUnsupportedAPI类型AndInvalid延迟业务协调。
func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 表示当前遍历过程中的请求体
@@ -101,10 +101,10 @@ func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) {
`{"name":"空库存","type":"data","data_content":"\n","enabled":true}`,
`{"name":"空图片","type":"image","image_url":"","enabled":true}`,
} {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -115,10 +115,10 @@ func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) {
// TestProtectedEndpointsRequireAuth 受保护端点未登录应 401。
func TestProtectedEndpointsRequireAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// path 表示当前遍历过程中的路径
@@ -131,9 +131,9 @@ func TestProtectedEndpointsRequireAuth(t *testing.T) {
"/admin/stats",
"/ai-reply-settings",
} {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, path, nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
@@ -144,31 +144,31 @@ func TestProtectedEndpointsRequireAuth(t *testing.T) {
// TestAdminEndpointRejectsNonAdmin 非 admin 用户访问管理端点应 403。
func TestAdminEndpointRejectsNonAdmin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// 创建普通用户并登录。
store.Users.Create(context.Background(), "user2", "[email protected]", "pw")
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"username":"user2","password":"pw"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("普通用户登录 status=%d", rec.Code)
}
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := rec.Result().Cookies()[0]
// 访问 admin 端点 → 403。
req2 := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusForbidden {
@@ -178,19 +178,19 @@ func TestAdminEndpointRejectsNonAdmin(t *testing.T) {
// TestOrderImportEmptyBody 空导入内容应 400。
func TestOrderImportEmptyBody(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(""))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -200,15 +200,15 @@ func TestOrderImportEmptyBody(t *testing.T) {
// TestLoginMalformedJSON 登录请求体非法 JSON 应不致命(400 或失败响应)。
func TestLoginMalformedJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader("not-json"))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
+37 -37
View File
@@ -16,20 +16,20 @@ import (
// TestAddKeywordWithItemID 带商品ID的关键词添加 + 缺 keyword 400。
func TestAddKeywordWithItemID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 正常添加。
body := `{"keyword":"价格","reply":"50元","item_id":"item1"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -39,7 +39,7 @@ func TestAddKeywordWithItemID(t *testing.T) {
// 缺 keyword → 400。
req2 := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(`{"reply":"x"}`))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusBadRequest {
@@ -49,7 +49,7 @@ func TestAddKeywordWithItemID(t *testing.T) {
// 非法 JSON → 400。
req3 := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader("not-json"))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != http.StatusBadRequest {
@@ -59,36 +59,36 @@ func TestAddKeywordWithItemID(t *testing.T) {
// TestBatchCreateCards CSV 批量建卡密组。
func TestBatchCreateCards(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// csv 保存csv,供当前处理流程使用
// csv 用于本次流程后续判断的csv
csv := "name,type,content,delay_seconds\n卡A,text,内容A,0\n卡B,text,内容B,5\nAPI卡,api,https://example.com,0\n延时异常,text,内容,-1\n"
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := &bytes.Buffer{}
// mw 保存mw,供当前处理流程使用
// mw 用于本次流程后续判断的mw
mw := multipart.NewWriter(body)
// fw 保存fw,供当前处理流程使用
// fw 用于本次流程后续判断的fw
fw, _ := mw.CreateFormFile("file", "cards.csv")
fw.Write([]byte(csv))
mw.Close()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/cards/batch", body)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("batch status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["created"].(float64) != 2 {
@@ -102,7 +102,7 @@ func TestBatchCreateCards(t *testing.T) {
req2 := httptest.NewRequest(http.MethodPost, "/cards/batch", &bytes.Buffer{})
req2.Header.Set("Content-Type", "multipart/form-data; boundary=x")
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusBadRequest {
@@ -112,27 +112,27 @@ func TestBatchCreateCards(t *testing.T) {
// TestAppendCardData 追加批量卡密号 + 校验分支。
func TestAppendCardData(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// admin 保存admin,供当前处理流程使用
// admin 用于本次流程后续判断的admin
admin, _ := store.Users.GetByUsername(ctx, "admin")
// 建一个 data 类型卡密组。
id, _ := store.Cards.Create(ctx, &db.CardFull{Name: "批量卡", Type: "data", DataContent: "K1\nK2", Enabled: true, UserID: admin.ID})
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 追加。
body := `{"content":"K3\nK4"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/cards/"+itoa(id)+"/append-data", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -142,7 +142,7 @@ func TestAppendCardData(t *testing.T) {
// 空 content → 400。
req2 := httptest.NewRequest(http.MethodPost, "/cards/"+itoa(id)+"/append-data", strings.NewReader(`{"content":""}`))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != http.StatusBadRequest {
@@ -152,7 +152,7 @@ func TestAppendCardData(t *testing.T) {
// 无效 card_id → 400。
req3 := httptest.NewRequest(http.MethodPost, "/cards/abc/append-data", strings.NewReader(`{"content":"x"}`))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != http.StatusBadRequest {
@@ -161,10 +161,10 @@ func TestAppendCardData(t *testing.T) {
// 非 data 类型卡密组追加 → 400。建一个 text 类型。
textID, _ := store.Cards.Create(ctx, &db.CardFull{Name: "文本卡", Type: "text", TextContent: "T", Enabled: true, UserID: admin.ID})
// req4 保存req4,供当前处理流程使用
// req4 用于本次流程后续判断的req4
req4 := httptest.NewRequest(http.MethodPost, "/cards/"+itoa(textID)+"/append-data", strings.NewReader(`{"content":"x"}`))
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != http.StatusBadRequest {
@@ -174,9 +174,9 @@ func TestAppendCardData(t *testing.T) {
// TestParseXLSXPublishSheet 解析 XLSX 表格(复用 buildMinimalXLSX 构造)。
func TestParseXLSXPublishSheet(t *testing.T) {
// xlsx 保存xlsx,供当前处理流程使用
// xlsx 用于本次流程后续判断的xlsx
xlsx := buildMinimalXLSXForPublish(t, [][]string{{"title", "price"}, {"商品A", "9.9"}})
// rows、err 保存rows、err,供当前处理流程使用
// rows、err 用于本次流程后续判断的rows、err
rows, err := parseXLSXPublishSheet(xlsx)
if err != nil {
t.Fatalf("parseXLSX: %v", err)
@@ -193,7 +193,7 @@ func TestParseXLSXPublishSheet(t *testing.T) {
// TestPublicHTTPClient 公网 HTTP 客户端拒绝非公网地址 + 重定向协议校验。
func TestPublicHTTPClient(t *testing.T) {
// cli 保存cli,供当前处理流程使用
// cli 用于本次流程后续判断的cli
cli := publicHTTPClient()
if cli == nil {
t.Fatal("应返回非 nil client")
@@ -207,19 +207,19 @@ func TestPublicHTTPClient(t *testing.T) {
// TestPublishBatchToMap 批次转具名 DTO 序列化并校验状态计数。
func TestPublishBatchToMap(t *testing.T) {
// batch 保存批次,供当前处理流程使用
// batch 用于本次流程后续判断的批次
batch := itemapp.BatchInfo{ID: "b1", Status: "running", Filename: "x.csv"}
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows := []itemapp.BatchRow{
{ID: 1, RowNo: 1, CookieID: "c1", Title: "t1", Status: "pending", ImagesJSON: `["a.png"]`},
{ID: 2, RowNo: 2, CookieID: "c1", Title: "t2", Status: "running"},
}
// m 保存m,供当前处理流程使用
// m 用于本次流程后续判断的m
m := publishBatchApplicationToResponse(batch, rows)
if m.ID != "b1" || m.Status != "running" {
t.Fatalf("batch 字段异常: %+v", m)
}
// rs 保存rs,供当前处理流程使用
// rs 用于本次流程后续判断的rs
rs := m.Rows
if len(rs) != 2 {
t.Fatalf("rows 数异常: %d", len(rs))
@@ -228,7 +228,7 @@ func TestPublishBatchToMap(t *testing.T) {
// buildMinimalXLSXForPublish 构造最小 xlsx 供 parseXLSXPublishSheet 测试。
// 复用 parser_test.go 的 buildMinimalXLSX 但独立命名避免冲突。
// buildMinimalXLSXForPublish 负责buildMinimalXLSXFor发布相关处理。
// buildMinimalXLSXForPublish 封装buildMinimalXLSXFor发布业务协调。
func buildMinimalXLSXForPublish(t *testing.T, grid [][]string) []byte {
t.Helper()
return buildMinimalXLSX(t, grid)
+6 -6
View File
@@ -9,7 +9,7 @@ import (
"net/http"
)
// maxJSONRequestBytes 保存maxJSON请求Bytes,供当前处理流程使用
// maxJSONRequestBytes 用于本次流程后续判断的maxJSON请求Bytes
const maxJSONRequestBytes = 1 << 20
// writeJSON 写 JSON 响应。
@@ -31,7 +31,7 @@ func writeErr(w http.ResponseWriter, status int, msg string) {
// decodeJSON 解析请求体 JSON。
func decodeJSON(r *http.Request, v any) error {
// body、err 保存body、err,供当前处理流程使用
// body、err 用于本次流程后续判断的body、err
body, err := io.ReadAll(io.LimitReader(r.Body, maxJSONRequestBytes+1))
if err != nil {
return err
@@ -39,15 +39,15 @@ func decodeJSON(r *http.Request, v any) error {
if len(body) > maxJSONRequestBytes {
return fmt.Errorf("JSON 请求体超过 %d 字节", maxJSONRequestBytes)
}
// dec 保存dec,供当前处理流程使用
// dec 用于本次流程后续判断的dec
dec := json.NewDecoder(bytes.NewReader(body))
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := dec.Decode(v); err != nil {
return err
}
// trailing 保存trailing,供当前处理流程使用
// trailing 用于本次流程后续判断的trailing
var trailing any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := dec.Decode(&trailing); !errors.Is(err, io.EOF) {
if err == nil {
return errors.New("JSON 请求体只能包含一个值")
+6 -6
View File
@@ -6,21 +6,21 @@ import (
"testing"
)
// TestDecodeJSONLimitsAndRejectsTrailingValues 负责TestDecodeJSONLimitsAndRejectsTrailingValues相关处理。
// TestDecodeJSONLimitsAndRejectsTrailingValues 封装TestDecodeJSONLimitsAndRejectsTrailingValues业务协调。
func TestDecodeJSONLimitsAndRejectsTrailingValues(t *testing.T) {
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
var out map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(httptest.NewRequest("POST", "/", strings.NewReader(`{"ok":true}`)), &out); err != nil {
t.Fatalf("valid JSON: %v", err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(httptest.NewRequest("POST", "/", strings.NewReader(`{} {}`)), &out); err == nil {
t.Fatal("trailing JSON value should fail")
}
// oversized 保存oversized,供当前处理流程使用
// oversized 用于本次流程后续判断的oversized
oversized := `{"value":"` + strings.Repeat("x", maxJSONRequestBytes) + `"}`
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(httptest.NewRequest("POST", "/", strings.NewReader(oversized)), &out); err == nil {
t.Fatal("oversized JSON should fail")
}
+62 -62
View File
@@ -48,51 +48,51 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误,请使用 multipart/form-data")
return
}
// cookieID 保存登录凭证ID,供当前处理流程使用
// cookieID 用于本次流程后续判断的登录凭证ID
cookieID := strings.TrimSpace(r.FormValue("cookie_id"))
if cookieID == "" {
writeErr(w, http.StatusBadRequest, "请选择发布账号")
return
}
// userID、ok 保存用户ID、ok,供当前处理流程使用
// userID、ok 用于本次流程后续判断的用户ID、ok
_, userID, ok := s.cookieForCurrentUser(w, r, cookieID)
if !ok {
return
}
// title 保存标题,供当前处理流程使用
// title 用于本次流程后续判断的标题
title := strings.TrimSpace(r.FormValue("title"))
// description 保存description,供当前处理流程使用
// description 用于本次流程后续判断的description
description := strings.TrimSpace(r.FormValue("description"))
// priceCents、err 保存priceCents、err,供当前处理流程使用
// priceCents、err 用于本次流程后续判断的priceCents、err
priceCents, err := parseMoneyCents(r.FormValue("price"))
if err != nil || priceCents <= 0 {
writeErr(w, http.StatusBadRequest, "商品价格必须大于 0")
return
}
// origCents、err 保存origCents、err,供当前处理流程使用
// origCents、err 用于本次流程后续判断的origCents、err
origCents, err := parseMoneyCents(r.FormValue("original_price"))
if err != nil || origCents < 0 {
writeErr(w, http.StatusBadRequest, "商品原价格式错误")
return
}
// quantity、err 保存quantity、err,供当前处理流程使用
// quantity、err 用于本次流程后续判断的quantity、err
quantity, err := strconv.Atoi(strings.TrimSpace(r.FormValue("quantity")))
if err != nil || quantity <= 0 {
writeErr(w, http.StatusBadRequest, "库存数量必须大于 0")
return
}
// postageMode 保存postage模式,供当前处理流程使用
// postageMode 用于本次流程后续判断的postage模式
postageMode := strings.TrimSpace(r.FormValue("postage_mode"))
if postageMode == "" {
postageMode = "free"
}
// postageCents、err 保存postageCents、err,供当前处理流程使用
// postageCents、err 用于本次流程后续判断的postageCents、err
postageCents, err := parseMoneyCents(r.FormValue("postage"))
if err != nil || postageCents < 0 || (postageMode == "fixed" && postageCents <= 0) {
writeErr(w, http.StatusBadRequest, "固定邮费必须大于 0")
return
}
// images、err 保存images、err,供当前处理流程使用
// images、err 用于本次流程后续判断的images、err
images, err := readPublishImages(r, 9)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
@@ -102,9 +102,9 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
var location itemPublishLocationRequest
// selectedLocation 保存解析成功、待转换为应用模型的发货地。
var selectedLocation *itemPublishLocationRequest
if // rawLocation 保存原始地址,供当前处理流程使用
if // rawLocation 用于本次流程后续判断的原始地址
rawLocation := strings.TrimSpace(r.FormValue("location")); rawLocation != "" {
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal([]byte(rawLocation), &location); err != nil {
writeErr(w, http.StatusBadRequest, "发货地格式错误,请重新定位")
return
@@ -132,15 +132,15 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
PriceCents: priceCents, OriginalPriceCents: origCents, Quantity: quantity,
PostageMode: postageMode, PostageCents: postageCents, Location: applicationLocation, Images: applicationImages,
})
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
res := outcome.Result
if callErr != nil {
// perr 保存perr,供当前处理流程使用
// perr 用于本次流程后续判断的perr
var perr *itemapp.PublishError
if errors.As(callErr, &perr) {
// status 保存状态,供当前处理流程使用
// status 用于本次流程后续判断的状态
status := http.StatusBadGateway
// msg 保存msg,供当前处理流程使用
// msg 用于本次流程后续判断的msg
msg := perr.Error()
if perr.Code == itemapp.PublishErrorStockPermissionMissing {
status = http.StatusForbidden
@@ -176,12 +176,12 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
})
}
// readPublishImages 负责read发布Images相关处理。
// readPublishImages 封装read发布Images业务协调。
func readPublishImages(r *http.Request, maxImages int) ([]itemapp.Image, error) {
if r.MultipartForm == nil || r.MultipartForm.File == nil {
return nil, errors.New("至少上传 1 张商品图片")
}
// files 保存文件列表,供当前处理流程使用
// files 用于本次流程后续判断的文件列表
files := r.MultipartForm.File["images"]
if len(files) == 0 {
files = r.MultipartForm.File["image"]
@@ -192,16 +192,16 @@ func readPublishImages(r *http.Request, maxImages int) ([]itemapp.Image, error)
if len(files) > maxImages {
return nil, fmt.Errorf("商品图片最多 %d 张", maxImages)
}
// images 保存images,供当前处理流程使用
// images 用于本次流程后续判断的images
images := make([]itemapp.Image, 0, len(files))
// fh 表示当前遍历过程中的fh
for _, fh := range files {
// f、err 保存f、err,供当前处理流程使用
// f、err 用于本次流程后续判断的f、err
f, err := fh.Open()
if err != nil {
return nil, fmt.Errorf("读取图片失败: %w", err)
}
// data、tooLarge、err 保存data、tooLarge、err,供当前处理流程使用
// data、tooLarge、err 用于本次流程后续判断的data、tooLarge、err
data, tooLarge, err := readLimitedBytes(f, 10<<20)
_ = f.Close()
if err != nil {
@@ -213,7 +213,7 @@ func readPublishImages(r *http.Request, maxImages int) ([]itemapp.Image, error)
if len(data) == 0 {
return nil, errors.New("图片文件为空")
}
// contentType 保存内容类型,供当前处理流程使用
// contentType 用于本次流程后续判断的内容类型
contentType := fh.Header.Get("Content-Type")
if contentType == "" {
contentType = http.DetectContentType(data)
@@ -226,7 +226,7 @@ func readPublishImages(r *http.Request, maxImages int) ([]itemapp.Image, error)
return images, nil
}
// parseMoneyCents 负责parseMoneyCents相关处理。
// parseMoneyCents 封装parseMoneyCents业务协调。
func parseMoneyCents(raw string) (int64, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
@@ -234,7 +234,7 @@ func parseMoneyCents(raw string) (int64, error) {
}
raw = strings.TrimPrefix(raw, "¥")
raw = strings.TrimPrefix(raw, "¥")
// sign 保存sign,供当前处理流程使用
// sign 用于本次流程后续判断的sign
sign := int64(1)
if strings.HasPrefix(raw, "-") {
sign = -1
@@ -242,20 +242,20 @@ func parseMoneyCents(raw string) (int64, error) {
} else {
raw = strings.TrimPrefix(raw, "+")
}
// parts 保存parts,供当前处理流程使用
// parts 用于本次流程后续判断的parts
parts := strings.Split(raw, ".")
if len(parts) > 2 {
return 0, fmt.Errorf("金额格式错误")
}
// yuan、err 保存yuan、err,供当前处理流程使用
// yuan、err 用于本次流程后续判断的yuan、err
yuan, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64)
if err != nil {
return 0, err
}
// cents 保存cents,供当前处理流程使用
// cents 用于本次流程后续判断的cents
cents := int64(0)
if len(parts) == 2 {
// frac 保存frac,供当前处理流程使用
// frac 用于本次流程后续判断的frac
frac := strings.TrimSpace(parts[1])
if len(frac) > 2 {
return 0, fmt.Errorf("金额最多支持两位小数")
@@ -291,13 +291,13 @@ type itemPublishLocationRequest struct {
Province string `json:"province"`
}
// listItems 负责list商品列表相关处理。
// listItems 封装list商品列表业务协调。
func (s *Server) listItems(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// cookieID 是可选的账号筛选条件。
cookieID := strings.TrimSpace(r.URL.Query().Get("cookie_id"))
// cookieID 保存登录凭证ID,供当前处理流程使用
// cookieID 用于本次流程后续判断的登录凭证ID
if cookieID != "" {
if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
@@ -310,7 +310,7 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// result 保存结果,供当前处理流程使用。
// result 用于本次流程后续判断的结果。
result := make([]itemListResponse, 0, len(items))
// it 表示当前遍历过程中的商品行。
for _, it := range items {
@@ -397,9 +397,9 @@ func (s *Server) writeItemSyncError(w http.ResponseWriter, err error) {
writeErr(w, http.StatusInternalServerError, "商品同步失败")
}
// cookieForCurrentUser 负责登录凭证ForCurrent用户相关处理。
// cookieForCurrentUser 封装登录凭证ForCurrent用户业务协调。
func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, cookieID string) (string, int64, bool) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// service 提供消费者定义的平台凭证只读端口;本校验不会把 Cookie 明文带入 HTTP 层。
service := s.platformCredentialApplication()
@@ -424,9 +424,9 @@ func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, co
return value, sess.UserID, true
}
// listItemsByCookie 负责list商品列表By登录凭证相关处理。
// listItemsByCookie 封装list商品列表By登录凭证业务协调。
func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
@@ -437,7 +437,7 @@ func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make([]itemListResponse, 0, len(items))
// it 表示当前遍历过程中的it
for _, it := range items {
@@ -446,16 +446,16 @@ func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, out)
}
// getItem 负责get商品相关处理。
// getItem 封装get商品业务协调。
func (s *Server) getItem(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
// itemID 用于本次流程后续判断的商品ID
itemID := chi.URLParam(r, "item_id")
// it、err 保存it、err,供当前处理流程使用
// it、err 用于本次流程后续判断的it、err
it, err := s.itemCatalogApplication().Get(r.Context(), cid, itemID)
if err != nil {
writeErr(w, http.StatusNotFound, "商品不存在")
@@ -524,14 +524,14 @@ type itemMultiQuantityRequest struct {
// createItem 创建本地商品记录并返回统一操作结果。
func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// req 保存解码后的创建商品请求。
var req itemCreateRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil || req.ItemID == "" {
writeErr(w, http.StatusBadRequest, "缺少商品 ID")
return
@@ -553,16 +553,16 @@ func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
// updateItem 更新本地商品的部分字段并保留未提交字段。
func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
// itemID 用于本次流程后续判断的商品ID
itemID := chi.URLParam(r, "item_id")
// req 保存解码后的局部更新商品请求。
var req itemUpdateRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -588,14 +588,14 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteItem 负责delete商品相关处理。
// deleteItem 封装delete商品业务协调。
func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
// itemID 用于本次流程后续判断的商品ID
itemID := chi.URLParam(r, "item_id")
// err 保存商品删除应用服务返回的错误。
if err := s.itemCatalogMutationApplication().Delete(r.Context(), cid, itemID); err != nil {
@@ -605,18 +605,18 @@ func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// setItemMultiSpec 负责set商品MultiSpec相关处理。
// setItemMultiSpec 封装set商品MultiSpec业务协调。
func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
// itemID 用于本次流程后续判断的商品ID
itemID := chi.URLParam(r, "item_id")
// req 保存解码后的多规格开关请求。
var req itemMultiSpecRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -629,18 +629,18 @@ func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// setItemMultiQuantity 负责set商品MultiQuantity相关处理。
// setItemMultiQuantity 封装set商品MultiQuantity业务协调。
func (s *Server) setItemMultiQuantity(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
return
}
// itemID 保存商品ID,供当前处理流程使用
// itemID 用于本次流程后续判断的商品ID
itemID := chi.URLParam(r, "item_id")
// req 保存解码后的多数量交付开关请求。
var req itemMultiQuantityRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -670,20 +670,20 @@ func itemImageFromDetail(detail string) string {
if detail == "" {
return ""
}
// m 保存m,供当前处理流程使用
// m 用于本次流程后续判断的m
var m map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal([]byte(detail), &m); err != nil {
return ""
}
if // pic、ok 保存pic、ok,供当前处理流程使用
if // pic、ok 用于本次流程后续判断的pic、ok
pic, ok := m["pic_info"].(map[string]any); ok {
if // url、ok 保存url、ok,供当前处理流程使用
if // url、ok 用于本次流程后续判断的url、ok
url, ok := pic["picUrl"].(string); ok {
return url
}
}
if // url、ok 保存url、ok,供当前处理流程使用
if // url、ok 用于本次流程后续判断的url、ok
url, ok := m["item_image"].(string); ok {
return url
}
File diff suppressed because it is too large. Load diff
+85 -75
View File
@@ -22,31 +22,31 @@ import (
"xianyu-go/internal/auth"
)
// maxPublishBatchRows 保存max发布批次Rows,供当前处理流程使用
// maxPublishBatchRows 用于本次流程后续判断的max发布批次Rows
const (
maxPublishBatchRows = 50
publishBatchLease = 5 * time.Minute
)
// postPublishError 保存post发布错误,供当前处理流程使用
// postPublishError 用于本次流程后续判断的post发布错误
type postPublishError struct{ err error }
// Error 负责错误相关处理。
// Error 封装错误业务协调。
func (e *postPublishError) Error() string { return e.err.Error() }
// Unwrap 负责Unwrap相关处理。
// Unwrap 封装Unwrap业务协调。
func (e *postPublishError) Unwrap() error { return e.err }
// uncertainRemotePublishError 保存uncertainRemote发布错误,供当前处理流程使用
// uncertainRemotePublishError 用于本次流程后续判断的uncertainRemote发布错误
type uncertainRemotePublishError struct{ err error }
// Error 负责错误相关处理。
// Error 封装错误业务协调。
func (e *uncertainRemotePublishError) Error() string { return e.err.Error() }
// Unwrap 负责Unwrap相关处理。
// Unwrap 封装Unwrap业务协调。
func (e *uncertainRemotePublishError) Unwrap() error { return e.err }
// publishBatchPreviewRow 保存发布批次PreviewRow,供当前处理流程使用
// publishBatchPreviewRow 用于本次流程后续判断的发布批次PreviewRow
type publishBatchPreviewRow struct {
RowNo int `json:"row_no"`
Valid bool `json:"valid"`
@@ -60,6 +60,22 @@ type publishBatchPreviewRow struct {
Automation publishAutomationConfig `json:"automation"`
}
// publishCategoryRecommendationRequest 是请求指定账号商品类目推荐的 HTTP 请求 DTO。
type publishCategoryRecommendationRequest struct {
// CookieID 是发起平台类目推荐的已归属账号标识。
CookieID string `json:"cookie_id"`
// Keyword 是用于匹配平台类目的用户输入关键词。
Keyword string `json:"keyword"`
}
// itemPublishBatchStartRequest 是启动已预检批次的 HTTP 请求 DTO,保留 batch_id 兼容旧客户端。
type itemPublishBatchStartRequest struct {
// PreviewID 是当前客户端使用的预检批次标识。
PreviewID string `json:"preview_id"`
// BatchID 是历史客户端发送的兼容批次标识。
BatchID string `json:"batch_id"`
}
// publishBatchPreviewApplicationResponse 将应用预检结果映射为既有 HTTP DTO。
func publishBatchPreviewApplicationResponse(result itemapp.BatchPreviewPersistenceResult) itemPublishBatchPreviewResponse {
// rows 保存兼容前端字段命名的逐行预检结果。
@@ -92,12 +108,9 @@ func publishBatchPreviewApplicationResponse(result itemapp.BatchPreviewPersisten
// recommendItemPublishCategory 解析类目关键词并返回平台推荐类目。
func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Request) {
// req 保存req,供当前处理流程使用
var req struct {
CookieID string `json:"cookie_id"`
Keyword string `json:"keyword"`
}
if // err 保存err,供当前处理流程使用
// req 是商品类目推荐请求的具名传输 DTO。
var req publishCategoryRecommendationRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -112,12 +125,12 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req
writeErr(w, http.StatusBadRequest, "请输入类目关键词")
return
}
// userID、ok 保存用户ID、ok,供当前处理流程使用
// userID、ok 用于本次流程后续判断的用户ID、ok
_, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
if !ok {
return
}
// category、callErr 保存category、callErr,供当前处理流程使用
// category、callErr 用于本次流程后续判断的category、callErr
category, callErr := s.itemCategoryRecommendationApplication().Recommend(r.Context(), userID, req.CookieID, req.Keyword)
if callErr != nil {
if errors.Is(callErr, itemapp.ErrCategoryUnsupported) {
@@ -144,7 +157,7 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req
// previewItemPublishBatch 处理表格上传、图片归档和批量发布预检。
func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
s.cleanupExpiredPublishUploads(r.Context())
// 表格最大 20 MiB,图片压缩包最大 200 MiB,额外预留 multipart 元数据空间。
@@ -154,7 +167,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusBadRequest, "解析上传文件失败")
return
}
// defaultCookieID 保存default登录凭证ID,供当前处理流程使用
// defaultCookieID 用于本次流程后续判断的default登录凭证ID
defaultCookieID := strings.TrimSpace(r.FormValue("default_cookie_id"))
if defaultCookieID == "" {
writeErr(w, http.StatusBadRequest, "请选择默认发布账号")
@@ -170,16 +183,16 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusForbidden, "默认账号不属于当前用户")
return
}
// fallbackCategory 保存fallback分类,供当前处理流程使用
// fallbackCategory 用于本次流程后续判断的fallback分类
fallbackCategory := publishCategoryResponse{
CatID: strings.TrimSpace(r.FormValue("fallback_category_id")),
CatName: strings.TrimSpace(r.FormValue("fallback_category_name")),
ChannelCatID: strings.TrimSpace(r.FormValue("fallback_channel_category_id")),
TBCatID: strings.TrimSpace(r.FormValue("fallback_tb_category_id")),
}
// batchLocation 保存批次地址,供当前处理流程使用
// batchLocation 用于本次流程后续判断的批次地址
var batchLocation publishBatchLocation
// locationJSON 保存地址JSON,供当前处理流程使用
// locationJSON 用于本次流程后续判断的地址JSON
locationJSON := strings.TrimSpace(r.FormValue("location"))
if locationJSON != "" {
if json.Unmarshal([]byte(locationJSON), &batchLocation) != nil {
@@ -187,20 +200,20 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
return
}
}
// hasDefaultCategory 保存hasDefault分类,供当前处理流程使用
// hasDefaultCategory 用于本次流程后续判断的hasDefault分类
hasDefaultCategory := fallbackCategory.CatID != "" || fallbackCategory.CatName != "" || fallbackCategory.ChannelCatID != "" || fallbackCategory.TBCatID != ""
if hasDefaultCategory && (fallbackCategory.CatID == "" || fallbackCategory.CatName == "" || fallbackCategory.ChannelCatID == "") {
writeErr(w, http.StatusBadRequest, "默认类目信息不完整,请重新通过关键词获取")
return
}
// source、sourceHeader、err 保存source、sourceHeader、err,供当前处理流程使用
// source、sourceHeader、err 用于本次流程后续判断的source、sourceHeader、err
source, sourceHeader, err := r.FormFile("file")
if err != nil {
writeErr(w, http.StatusBadRequest, "缺少商品表格文件")
return
}
defer source.Close()
// sourceBytes、tooLarge、err 保存sourceBytes、tooLarge、err,供当前处理流程使用
// sourceBytes、tooLarge、err 用于本次流程后续判断的sourceBytes、tooLarge、err
sourceBytes, tooLarge, err := readLimitedBytes(source, 20<<20)
if err != nil {
writeErr(w, http.StatusBadRequest, "读取商品表格失败")
@@ -210,37 +223,37 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusBadRequest, "商品表格不能超过 20 MiB")
return
}
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := "batch_" + randomHex(12)
// uploadDir 保存uploadDir,供当前处理流程使用
// uploadDir 用于本次流程后续判断的uploadDir
uploadDir := filepath.Join(s.publishUploadRoot(), "publish_batches", batchID)
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := os.MkdirAll(uploadDir, 0o750); err != nil {
writeErr(w, http.StatusInternalServerError, "创建上传目录失败")
return
}
// keepUpload 保存keepUpload,供当前处理流程使用
// keepUpload 用于本次流程后续判断的keepUpload
keepUpload := false
defer func() {
if !keepUpload {
_ = os.RemoveAll(uploadDir)
}
}()
// sourceName 保存source名称,供当前处理流程使用
// sourceName 用于本次流程后续判断的source名称
sourceName := safeBaseName(sourceHeader.Filename)
if sourceName == "" {
sourceName = "products.csv"
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := writeFileWithinRoot(uploadDir, sourceName, sourceBytes); err != nil {
writeErr(w, http.StatusInternalServerError, "保存商品表格失败")
return
}
if // zipFile、zipHeader、err 保存zipFile、zipHeader、err,供当前处理流程使用
if // zipFile、zipHeader、err 用于本次流程后续判断的zipFile、zipHeader、err
zipFile, zipHeader, err := r.FormFile("images_zip"); err == nil {
defer zipFile.Close()
// zipBytes、tooLarge、err 保存zipBytes、tooLarge、err,供当前处理流程使用
// zipBytes、tooLarge、err 用于本次流程后续判断的zipBytes、tooLarge、err
zipBytes, tooLarge, err := readLimitedBytes(zipFile, 200<<20)
if err != nil {
writeErr(w, http.StatusBadRequest, "读取图片 zip 失败")
@@ -250,24 +263,24 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusBadRequest, "图片 zip 不能超过 200 MiB")
return
}
// zipName 保存zip名称,供当前处理流程使用
// zipName 用于本次流程后续判断的zip名称
zipName := safeBaseName(zipHeader.Filename)
if zipName == "" {
zipName = "images.zip"
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := writeFileWithinRoot(uploadDir, zipName, zipBytes); err != nil {
writeErr(w, http.StatusInternalServerError, "保存图片 zip 失败")
return
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := extractPublishImagesZip(zipBytes, uploadDir); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
}
// maps、err 保存maps、err,供当前处理流程使用
// maps、err 用于本次流程后续判断的maps、err
maps, err := itemapp.ParseSheet(sourceBytes, sourceName, maxPublishBatchRows)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
@@ -310,19 +323,16 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
// startItemPublishBatch 启动指定批次的后台发布 worker。
func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// req 保存req,供当前处理流程使用
var req struct {
PreviewID string `json:"preview_id"`
BatchID string `json:"batch_id"`
}
if // err 保存err,供当前处理流程使用
// req 是启动商品批量发布请求的具名传输 DTO。
var req itemPublishBatchStartRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := strings.TrimSpace(req.PreviewID)
if batchID == "" {
batchID = strings.TrimSpace(req.BatchID)
@@ -331,7 +341,7 @@ func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "缺少 preview_id")
return
}
// startedID、err 保存startedID、err,供当前处理流程使用
// startedID、err 用于本次流程后续判断的startedID、err
startedID, err := s.itemBatchManagementApplication().StartBatch(r.Context(), sess.UserID, batchID, publishBatchLease)
if err != nil {
switch {
@@ -353,11 +363,11 @@ func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// listItemPublishBatches 返回当前用户的批量发布任务列表。
func (s *Server) listItemPublishBatches(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// limit 保存上限,供当前处理流程使用
// limit 用于本次流程后续判断的上限
limit := atoiDefault(r.URL.Query().Get("limit"), 20)
// result、err 保存result、err,供当前处理流程使用
// result、err 用于本次流程后续判断的result、err
batches, err := s.itemBatchManagementApplication().ListBatches(r.Context(), sess.UserID, limit)
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取批量任务失败")
@@ -374,11 +384,11 @@ func (s *Server) listItemPublishBatches(w http.ResponseWriter, r *http.Request)
// getItemPublishBatch 返回指定批次及其发布明细。
func (s *Server) getItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := chi.URLParam(r, "batch_id")
// result、err 保存result、err,供当前处理流程使用
// result、err 用于本次流程后续判断的result、err
details, err := s.itemBatchManagementApplication().GetBatch(r.Context(), sess.UserID, batchID)
if err != nil {
if errors.Is(err, itemapp.ErrBatchNotFound) {
@@ -393,11 +403,11 @@ func (s *Server) getItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// cancelItemPublishBatch 请求取消指定批次并通知运行中的 worker。
func (s *Server) cancelItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := chi.URLParam(r, "batch_id")
// status、err 保存status、err,供当前处理流程使用
// status、err 用于本次流程后续判断的status、err
status, err := s.itemBatchManagementApplication().CancelBatch(r.Context(), sess.UserID, batchID)
if err != nil {
if errors.Is(err, itemapp.ErrBatchNotFound) {
@@ -414,11 +424,11 @@ func (s *Server) cancelItemPublishBatch(w http.ResponseWriter, r *http.Request)
// deleteItemPublishBatch 删除已结束的批次及其上传目录。
func (s *Server) deleteItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := chi.URLParam(r, "batch_id")
// uploadDir、err 保存uploadDir、err,供当前处理流程使用
// uploadDir、err 用于本次流程后续判断的uploadDir、err
err := s.itemBatchManagementApplication().DeleteBatch(r.Context(), sess.UserID, batchID)
if err != nil {
if errors.Is(err, itemapp.ErrBatchNotFound) {
@@ -435,11 +445,11 @@ func (s *Server) deleteItemPublishBatch(w http.ResponseWriter, r *http.Request)
// retryFailedItemPublishBatch 重置失败明细并启动批次重试 worker。
func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := chi.URLParam(r, "batch_id")
// startedID、err 保存startedID、err,供当前处理流程使用
// startedID、err 用于本次流程后续判断的startedID、err
startedID, err := s.itemBatchManagementApplication().RetryFailedBatch(r.Context(), sess.UserID, batchID, publishBatchLease)
if err != nil {
if errors.Is(err, itemapp.ErrBatchNotFound) {
@@ -456,11 +466,11 @@ func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Requ
writeJSON(w, http.StatusOK, batchIDResponse{Success: true, BatchID: startedID})
}
// downloadItemPublishBatchResult 负责download商品发布批次结果相关处理。
// downloadItemPublishBatchResult 封装download商品发布批次结果业务协调。
func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := chi.URLParam(r, "batch_id")
// details、err 保存应用服务返回的批次及明细。
details, err := s.itemBatchManagementApplication().GetBatch(r.Context(), sess.UserID, batchID)
@@ -474,15 +484,15 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R
}
// rows 保存应用层批次明细,后续只负责转换为下载 DTO。
rows := details.Rows
// buf 保存buf,供当前处理流程使用
// buf 用于本次流程后续判断的buf
var buf bytes.Buffer
buf.WriteString("\xEF\xBB\xBF")
// cw 保存cw,供当前处理流程使用
// cw 用于本次流程后续判断的cw
cw := csv.NewWriter(&buf)
_ = cw.Write([]string{"行号", "状态", "账号ID", "标题", "价格", "库存", "默认类目ID", "默认类目名称", "商品ID", "商品URL", "错误原因"})
// row 表示当前导出的批量明细行。
for _, row := range rows {
// category 保存分类,供当前处理流程使用
// category 用于本次流程后续判断的分类
var category publishCategoryResponse
_ = json.Unmarshal([]byte(row.CategoryJSON), &category)
_ = cw.Write([]string{
@@ -492,7 +502,7 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R
})
}
cw.Flush()
// filename 保存filename,供当前处理流程使用
// filename 用于本次流程后续判断的filename
filename := fmt.Sprintf("publish_result_%s.csv", details.Batch.ID)
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(filename))
@@ -501,9 +511,9 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R
// safeCSVCell 防止用户可控内容被电子表格应用解释为公式。开头的单引号
// 在 Excel/LibreOffice 中作为文本标记,不改变导出的可见内容。
// safeCSVCell 负责safeCSVCell相关处理。
// safeCSVCell 封装safeCSVCell业务协调。
func safeCSVCell(value string) string {
// trimmed 保存trimmed,供当前处理流程使用
// trimmed 用于本次流程后续判断的trimmed
trimmed := strings.TrimLeft(value, " \t\r\n")
if trimmed == "" {
return value
@@ -516,15 +526,15 @@ func safeCSVCell(value string) string {
}
}
// publishBatchFailure 负责发布批次Failure相关处理。
// publishBatchFailure 封装发布批次Failure业务协调。
func publishBatchFailure(err error, batchStatus string) (string, string) {
// message 保存消息,供当前处理流程使用
// message 用于本次流程后续判断的消息
message := err.Error()
// failureKind 保存failure类型,供当前处理流程使用
// failureKind 用于本次流程后续判断的failure类型
failureKind := "publish"
// postErr 保存postErr,供当前处理流程使用
// postErr 用于本次流程后续判断的postErr
var postErr *postPublishError
// uncertainErr 保存uncertainErr,供当前处理流程使用
// uncertainErr 用于本次流程后续判断的uncertainErr
var uncertainErr *uncertainRemotePublishError
// appUncertainErr 保存应用批量端口返回的远端不确定错误。
var appUncertainErr *itemapp.UncertainRemotePublishError
@@ -612,7 +622,7 @@ func publishBatchApplicationToResponse(batch itemapp.BatchInfo, rows []itemapp.B
}
}
// cleanupExpiredPublishUploads 负责cleanupExpired发布Uploads相关处理。
// cleanupExpiredPublishUploads 封装cleanupExpired发布Uploads业务协调。
func (s *Server) cleanupExpiredPublishUploads(ctx context.Context) {
// err 表示过期上传目录清理结果;清理失败不影响当前预检请求。
if err := s.itemBatchManagementApplication().CleanupExpiredUploads(ctx, time.Now().UTC(), 100); err != nil && s.Logger != nil {
+44 -44
View File
@@ -25,16 +25,16 @@ import (
// isPublicIP 保留给同包校验调用;实际策略统一由 netguard 维护。
func isPublicIP(ip net.IP) bool { return netguard.IsPublicIP(ip) }
// extractPublishImagesZip 负责extract发布ImagesZip相关处理。
// extractPublishImagesZip 封装extract发布ImagesZip业务协调。
func extractPublishImagesZip(raw []byte, dest string) error {
// zr、err 保存zr、err,供当前处理流程使用
// zr、err 用于本次流程后续判断的zr、err
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return fmt.Errorf("解析图片 zip 失败: %w", err)
}
// extractedFiles 保存extracted文件列表,供当前处理流程使用
// extractedFiles 用于本次流程后续判断的extracted文件列表
extractedFiles := 0
// extractedBytes 保存extractedBytes,供当前处理流程使用
// extractedBytes 用于本次流程后续判断的extractedBytes
extractedBytes := int64(0)
// f 表示当前遍历过程中的f
for _, f := range zr.File {
@@ -45,28 +45,28 @@ func extractPublishImagesZip(raw []byte, dest string) error {
if extractedFiles > maxItemPublishZipFiles {
return fmt.Errorf("图片 zip 文件数不能超过 %d", maxItemPublishZipFiles)
}
// rel、err 保存rel、err,供当前处理流程使用
// rel、err 用于本次流程后续判断的rel、err
rel, err := safeZipPath(f.Name)
if err != nil {
return err
}
// root、err 保存root、err,供当前处理流程使用
// root、err 用于本次流程后续判断的root、err
root, err := os.OpenRoot(dest)
if err != nil {
return err
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := root.MkdirAll(filepath.Dir(rel), 0o750); err != nil {
_ = root.Close()
return err
}
// rc、err 保存rc、err,供当前处理流程使用
// rc、err 用于本次流程后续判断的rc、err
rc, err := f.Open()
if err != nil {
_ = root.Close()
return err
}
// data、err 保存data、err,供当前处理流程使用
// data、err 用于本次流程后续判断的data、err
data, err := io.ReadAll(io.LimitReader(rc, (10<<20)+1))
_ = rc.Close()
if err != nil {
@@ -90,11 +90,11 @@ func extractPublishImagesZip(raw []byte, dest string) error {
_ = root.Close()
return fmt.Errorf("图片 zip 解压后总大小不能超过 %d MiB", maxItemPublishZipExtractBytes>>20)
}
// file、err 保存file、err,供当前处理流程使用
// file、err 用于本次流程后续判断的file、err
file, err := root.OpenFile(rel, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err == nil {
_, err = file.Write(data)
// closeErr 保存closeErr,供当前处理流程使用
// closeErr 用于本次流程后续判断的closeErr
closeErr := file.Close()
if err == nil {
err = closeErr
@@ -108,26 +108,26 @@ func extractPublishImagesZip(raw []byte, dest string) error {
return nil
}
// readBatchImageFile 负责read批次图片文件相关处理。
// readBatchImageFile 封装read批次图片文件业务协调。
func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
// rel、err 保存rel、err,供当前处理流程使用
// rel、err 用于本次流程后续判断的rel、err
rel, err := safeZipPath(ref)
if err != nil {
return nil, "", "", err
}
// root、err 保存root、err,供当前处理流程使用
// root、err 用于本次流程后续判断的root、err
root, err := os.OpenRoot(uploadDir)
if err != nil {
return nil, "", "", fmt.Errorf("打开图片目录失败")
}
defer root.Close()
// file、err 保存file、err,供当前处理流程使用
// file、err 用于本次流程后续判断的file、err
file, err := root.Open(rel)
if err != nil {
return nil, "", "", fmt.Errorf("读取图片失败: %s", ref)
}
defer file.Close()
// data、err 保存data、err,供当前处理流程使用
// data、err 用于本次流程后续判断的data、err
data, err := io.ReadAll(io.LimitReader(file, (10<<20)+1))
if err != nil || len(data) > 10<<20 {
return nil, "", "", fmt.Errorf("读取图片失败或文件过大: %s", ref)
@@ -135,7 +135,7 @@ func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
if len(data) == 0 {
return nil, "", "", fmt.Errorf("图片文件为空: %s", ref)
}
// contentType 保存内容类型,供当前处理流程使用
// contentType 用于本次流程后续判断的内容类型
contentType := http.DetectContentType(data)
if !strings.HasPrefix(contentType, "image/") {
return nil, "", "", fmt.Errorf("不是有效图片: %s", ref)
@@ -145,18 +145,18 @@ func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) {
// writeFileWithinRoot 将上传文件限制在指定根目录内,拒绝符号链接和路径逃逸。
func writeFileWithinRoot(rootDir, name string, data []byte) error {
// root、err 保存root、err,供当前处理流程使用
// root、err 用于本次流程后续判断的root、err
root, err := os.OpenRoot(rootDir)
if err != nil {
return err
}
defer root.Close()
// file、err 保存file、err,供当前处理流程使用
// file、err 用于本次流程后续判断的file、err
file, err := root.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err != nil {
return err
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := file.Write(data); err != nil {
_ = file.Close()
return err
@@ -164,16 +164,16 @@ func writeFileWithinRoot(rootDir, name string, data []byte) error {
return file.Close()
}
// downloadImageURL 负责download图片URL相关处理。
// downloadImageURL 封装download图片URL业务协调。
func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error) {
// req、err 保存req、err,供当前处理流程使用
// req、err 用于本次流程后续判断的req、err
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil || (req.URL.Scheme != "http" && req.URL.Scheme != "https") || req.URL.Hostname() == "" {
return nil, "", fmt.Errorf("图片 URL 无效: %s", rawURL)
}
// client 保存client,供当前处理流程使用
// client 用于本次流程后续判断的client
client := publicHTTPClient()
// resp、err 保存resp、err,供当前处理流程使用
// resp、err 用于本次流程后续判断的resp、err
resp, err := client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("下载图片失败: %s", rawURL)
@@ -182,7 +182,7 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, "", fmt.Errorf("下载图片失败: %s HTTP %d", rawURL, resp.StatusCode)
}
// data、err 保存data、err,供当前处理流程使用
// data、err 用于本次流程后续判断的data、err
data, err := io.ReadAll(io.LimitReader(resp.Body, (10<<20)+1))
if err != nil {
return nil, "", fmt.Errorf("读取远程图片失败: %s", rawURL)
@@ -190,9 +190,9 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
if len(data) > 10<<20 {
return nil, "", fmt.Errorf("远程图片不能超过 10 MiB: %s", rawURL)
}
// contentType 保存内容类型,供当前处理流程使用
// contentType 用于本次流程后续判断的内容类型
contentType := resp.Header.Get("Content-Type")
if // i 保存i,供当前处理流程使用
if // i 用于本次流程后续判断的i
i := strings.Index(contentType, ";"); i >= 0 {
contentType = contentType[:i]
}
@@ -210,19 +210,19 @@ func publicHTTPClient() *http.Client {
return netguard.PublicHTTPClient(30 * time.Second)
}
// validateBatchImageRef 负责validate批次图片Ref相关处理。
// validateBatchImageRef 封装validate批次图片Ref业务协调。
func validateBatchImageRef(uploadDir, ref string) error {
if isHTTPURL(ref) {
return nil
}
// rel、err 保存rel、err,供当前处理流程使用
// rel、err 用于本次流程后续判断的rel、err
rel, err := safeZipPath(ref)
if err != nil {
return err
}
// path 保存路径,供当前处理流程使用
// path 用于本次流程后续判断的路径
path := filepath.Join(uploadDir, rel)
// info、err 保存info、err,供当前处理流程使用
// info、err 用于本次流程后续判断的info、err
info, err := os.Stat(path)
if err != nil || info.IsDir() {
return fmt.Errorf("图片文件不存在: %s", ref)
@@ -230,18 +230,18 @@ func validateBatchImageRef(uploadDir, ref string) error {
return nil
}
// isHTTPURL 负责isHTTPURL相关处理。
// isHTTPURL 封装isHTTPURL业务协调。
func isHTTPURL(ref string) bool {
ref = strings.ToLower(strings.TrimSpace(ref))
return strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://")
}
// pathBaseFromURL 负责路径BaseFromURL相关处理。
// pathBaseFromURL 封装路径BaseFromURL业务协调。
func pathBaseFromURL(rawURL string) string {
// base 保存base,供当前处理流程使用
// base 用于本次流程后续判断的base
base := filepath.Base(strings.Split(rawURL, "?")[0])
if base == "." || base == "/" || base == "" {
// exts 保存exts,供当前处理流程使用
// exts 用于本次流程后续判断的exts
exts, _ := mime.ExtensionsByType(http.DetectContentType(nil))
if len(exts) > 0 {
return "image" + exts[0]
@@ -251,18 +251,18 @@ func pathBaseFromURL(rawURL string) string {
return base
}
// randomHex 负责randomHex相关处理。
// randomHex 封装randomHex业务协调。
func randomHex(n int) string {
// buf 保存buf,供当前处理流程使用
// buf 用于本次流程后续判断的buf
buf := make([]byte, n)
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := rand.Read(buf); err != nil {
return strconv.FormatInt(time.Now().UnixNano(), 36)
}
return hex.EncodeToString(buf)
}
// safeBaseName 负责safeBase名称相关处理。
// safeBaseName 封装safeBase名称业务协调。
func safeBaseName(name string) string {
name = strings.TrimSpace(filepath.Base(name))
name = strings.ReplaceAll(name, string(os.PathSeparator), "_")
@@ -272,13 +272,13 @@ func safeBaseName(name string) string {
return name
}
// safeZipPath 负责safeZip路径相关处理。
// safeZipPath 封装safeZip路径业务协调。
func safeZipPath(raw string) (string, error) {
raw = strings.TrimSpace(strings.ReplaceAll(raw, "\\", "/"))
if raw == "" || strings.HasPrefix(raw, "/") {
return "", fmt.Errorf("图片路径不安全: %s", raw)
}
// clean 保存clean,供当前处理流程使用
// clean 用于本次流程后续判断的clean
clean := filepath.Clean(raw)
if clean == "." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) || clean == ".." {
return "", fmt.Errorf("图片路径不安全: %s", raw)
@@ -286,13 +286,13 @@ func safeZipPath(raw string) (string, error) {
return clean, nil
}
// splitImageRefs 负责split图片Refs相关处理。
// splitImageRefs 封装split图片Refs业务协调。
func splitImageRefs(raw string) []string {
raw = strings.ReplaceAll(raw, "\n", ";")
raw = strings.ReplaceAll(raw, ";", ";")
// parts 保存parts,供当前处理流程使用
// parts 用于本次流程后续判断的parts
parts := strings.Split(raw, ";")
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := []string{}
// p 表示当前遍历过程中的p
for _, p := range parts {
+34 -34
View File
@@ -12,12 +12,12 @@ import (
"strings"
)
// parsePublishSheetBytes 负责parse发布SheetBytes相关处理。
// parsePublishSheetBytes 封装parse发布SheetBytes业务协调。
func parsePublishSheetBytes(raw []byte, filename string) ([]map[string]any, error) {
return parsePublishSheetBytesWithLimit(raw, filename, 0)
}
// parsePublishSheetBytesWithLimit 负责parse发布SheetBytesWith上限相关处理。
// parsePublishSheetBytesWithLimit 封装parse发布SheetBytesWith上限业务协调。
func parsePublishSheetBytesWithLimit(raw []byte, filename string, maxRows int) ([]map[string]any, error) {
if len(bytes.TrimSpace(raw)) == 0 {
return nil, fmt.Errorf("导入内容为空")
@@ -36,26 +36,26 @@ func parsePublishSheetBytesWithLimit(raw []byte, filename string, maxRows int) (
}
}
// parseDelimitedPublishSheet 负责parseDelimited发布Sheet相关处理。
// parseDelimitedPublishSheet 封装parseDelimited发布Sheet业务协调。
func parseDelimitedPublishSheet(raw []byte, comma rune, maxRows int) ([]map[string]any, error) {
// reader 保存reader,供当前处理流程使用
// reader 用于本次流程后续判断的reader
reader := csv.NewReader(bytes.NewReader(raw))
reader.Comma = comma
reader.FieldsPerRecord = -1
reader.LazyQuotes = true
// header、err 保存header、err,供当前处理流程使用
// header、err 用于本次流程后续判断的header、err
header, err := reader.Read()
if err != nil {
return nil, fmt.Errorf("解析表格失败: %w", err)
}
// keys 保存keys,供当前处理流程使用
// keys 用于本次流程后续判断的keys
keys := publishHeaderKeys(header)
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows := make([]map[string]any, 0, 64)
// seenDataRow 保存seen数据Row,供当前处理流程使用
// seenDataRow 用于本次流程后续判断的seen数据Row
seenDataRow := false
for {
// record、err 保存record、err,供当前处理流程使用
// record、err 用于本次流程后续判断的record、err
record, err := reader.Read()
if err == io.EOF {
break
@@ -64,7 +64,7 @@ func parseDelimitedPublishSheet(raw []byte, comma rune, maxRows int) ([]map[stri
return nil, fmt.Errorf("解析表格失败: %w", err)
}
seenDataRow = true
// row、nonEmpty 保存row、nonEmpty,供当前处理流程使用
// row、nonEmpty 用于本次流程后续判断的row、nonEmpty
row, nonEmpty := publishRowToMap(keys, record)
if !nonEmpty {
continue
@@ -80,24 +80,24 @@ func parseDelimitedPublishSheet(raw []byte, comma rune, maxRows int) ([]map[stri
return rows, nil
}
// parseXLSXPublishSheet 负责parseXLSX发布Sheet相关处理。
// parseXLSXPublishSheet 封装parseXLSX发布Sheet业务协调。
func parseXLSXPublishSheet(raw []byte) ([]map[string]any, error) {
return parseXLSXPublishSheetWithLimit(raw, 0)
}
// parseXLSXPublishSheetWithLimit 负责parseXLSX发布SheetWith上限相关处理。
// parseXLSXPublishSheetWithLimit 封装parseXLSX发布SheetWith上限业务协调。
func parseXLSXPublishSheetWithLimit(raw []byte, maxRows int) ([]map[string]any, error) {
// zr、err 保存zr、err,供当前处理流程使用
// zr、err 用于本次流程后续判断的zr、err
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return nil, fmt.Errorf("解析 xlsx 失败: %w", err)
}
// shared、err 保存shared、err,供当前处理流程使用
// shared、err 用于本次流程后续判断的shared、err
shared, err := xlsxSharedStrings(zr)
if err != nil {
return nil, err
}
// sheet 保存sheet,供当前处理流程使用
// sheet 用于本次流程后续判断的sheet
var sheet *zip.File
// f 表示当前遍历过程中的f
for _, f := range zr.File {
@@ -109,26 +109,26 @@ func parseXLSXPublishSheetWithLimit(raw []byte, maxRows int) ([]map[string]any,
if sheet == nil {
return nil, fmt.Errorf("xlsx 中未找到工作表")
}
// rawSheet、err 保存原始Sheet、err,供当前处理流程使用
// rawSheet、err 用于本次流程后续判断的原始Sheet、err
rawSheet, err := readXLSXPart(sheet)
if err != nil {
return nil, err
}
// ws 保存ws,供当前处理流程使用
// ws 用于本次流程后续判断的ws
var ws xlsxWorksheet
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := xmlUnmarshalXLSX(rawSheet, &ws); err != nil {
return nil, fmt.Errorf("解析工作表失败: %w", err)
}
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows := make([][]string, 0, len(ws.SheetData.Rows))
// row 表示当前遍历过程中的row
for _, row := range ws.SheetData.Rows {
// values 保存values,供当前处理流程使用
// values 用于本次流程后续判断的values
values := []string{}
// cell 表示当前遍历过程中的cell
for _, cell := range row.Cells {
// idx 保存idx,供当前处理流程使用
// idx 用于本次流程后续判断的idx
idx := xlsxCellIndex(cell.Ref)
for len(values) <= idx {
values = append(values, "")
@@ -140,7 +140,7 @@ func parseXLSXPublishSheetWithLimit(raw []byte, maxRows int) ([]map[string]any,
if len(rows) < 2 {
return nil, fmt.Errorf("xlsx 至少需要表头和一行数据")
}
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := rowsToPublishMaps(rows[0], rows[1:])
if maxRows > 0 && len(out) > maxRows {
return nil, fmt.Errorf("单次最多解析 %d 行数据", maxRows)
@@ -148,15 +148,15 @@ func parseXLSXPublishSheetWithLimit(raw []byte, maxRows int) ([]map[string]any,
return out, nil
}
// rowsToPublishMaps 负责rowsTo发布Maps相关处理。
// rowsToPublishMaps 封装rowsTo发布Maps业务协调。
func rowsToPublishMaps(headers []string, rows [][]string) []map[string]any {
// keys 保存keys,供当前处理流程使用
// keys 用于本次流程后续判断的keys
keys := publishHeaderKeys(headers)
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make([]map[string]any, 0, len(rows))
// row 表示当前遍历过程中的row
for _, row := range rows {
// m、nonEmpty 保存m、nonEmpty,供当前处理流程使用
// m、nonEmpty 用于本次流程后续判断的m、nonEmpty
m, nonEmpty := publishRowToMap(keys, row)
if nonEmpty {
out = append(out, m)
@@ -165,9 +165,9 @@ func rowsToPublishMaps(headers []string, rows [][]string) []map[string]any {
return out
}
// publishHeaderKeys 负责发布HeaderKeys相关处理。
// publishHeaderKeys 封装发布HeaderKeys业务协调。
func publishHeaderKeys(headers []string) []string {
// keys 保存keys,供当前处理流程使用
// keys 用于本次流程后续判断的keys
keys := make([]string, len(headers))
// i、h 表示当前遍历过程中的i、h
for i, h := range headers {
@@ -176,18 +176,18 @@ func publishHeaderKeys(headers []string) []string {
return keys
}
// publishRowToMap 负责发布RowToMap相关处理。
// publishRowToMap 封装发布RowToMap业务协调。
func publishRowToMap(keys []string, row []string) (map[string]any, bool) {
// m 保存m,供当前处理流程使用
// m 用于本次流程后续判断的m
m := map[string]any{}
// nonEmpty 保存nonEmpty,供当前处理流程使用
// nonEmpty 用于本次流程后续判断的nonEmpty
nonEmpty := false
// i、key 表示当前遍历过程中的i、key
for i, key := range keys {
if key == "" || i >= len(row) {
continue
}
// value 保存值,供当前处理流程使用
// value 用于本次流程后续判断的值
value := strings.TrimSpace(row[i])
if value != "" {
nonEmpty = true
@@ -197,9 +197,9 @@ func publishRowToMap(keys []string, row []string) (map[string]any, bool) {
return m, nonEmpty
}
// normalizePublishHeader 负责normalize发布Header相关处理。
// normalizePublishHeader 封装normalize发布Header业务协调。
func normalizePublishHeader(header string) string {
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := strings.ToLower(strings.TrimSpace(header))
h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h)
switch h {
@@ -0,0 +1,109 @@
package server
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
// TestLegacyAPITelemetryAddsDeprecationHeaders 验证历史 API 保留行为会提供可供客户端迁移的弃用元数据。
func TestLegacyAPITelemetryAddsDeprecationHeaders(t *testing.T) {
// server 保存仅用于中间件测试的 HTTP 服务实例;该测试不依赖业务装配。
server := &Server{}
// next 保存模拟历史 handler 的下游响应实现。
next := http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
writer.WriteHeader(http.StatusNoContent)
})
// handler 保存附加旧 API 观测元数据后的请求处理链。
handler := server.legacyAPITelemetry(next)
// legacyRequest 保存命中历史订单入口的测试请求。
legacyRequest := httptest.NewRequest(http.MethodGet, "/api/orders", nil)
// legacyRecorder 保存历史入口的 HTTP 响应与弃用头。
legacyRecorder := httptest.NewRecorder()
handler.ServeHTTP(legacyRecorder, legacyRequest)
// sunsetValue 是历史 API 响应写入的标准退场时间字符串。
sunsetValue := legacyRecorder.Header().Get("Sunset")
// sunsetTime、sunsetErr 分别是标准 HTTP-date 解析结果及其错误。
sunsetTime, sunsetErr := http.ParseTime(sunsetValue)
if legacyRecorder.Code != http.StatusNoContent || legacyRecorder.Header().Get("Deprecation") != "true" || sunsetErr != nil || sunsetTime.IsZero() || legacyRecorder.Header().Get("Link") != legacyAPISuccessorLink {
t.Fatalf("历史 API 遥测头错误: status=%d header=%v", legacyRecorder.Code, legacyRecorder.Header())
}
// expectedSunset 是兼容矩阵当前约定的历史 API 最晚保留时间。
expectedSunset, expectedSunsetErr := time.Parse(time.RFC1123, legacyAPISunsetDate)
if expectedSunsetErr != nil || !sunsetTime.Equal(expectedSunset) {
t.Fatalf("Sunset=%q,期望标准时间 %q", sunsetValue, legacyAPISunsetDate)
}
}
// TestLegacyAPITelemetryLeavesVersionedAndPublicPathsUntouched 验证版本化与公开端点不会收到错误的历史 API 弃用信号。
func TestLegacyAPITelemetryDistinguishesVersionedAndSPARoutes(t *testing.T) {
// server 保存仅用于中间件测试的 HTTP 服务实例。
server := &Server{}
// next 保存返回成功状态的固定下游处理器。
next := http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusOK) })
// handler 保存当前待验证的中间件链。
handler := server.legacyAPITelemetry(next)
// requests 保存不应被判定为历史 API 的版本化、健康与 SPA 客户端路由请求。
requests := []struct {
// method 是当前测试请求的 HTTP 方法。
method string
// path 是当前测试请求的路径。
path string
}{
{method: http.MethodGet, path: "/api/v1/orders"},
{method: http.MethodGet, path: "/health"},
{method: http.MethodGet, path: "/version"},
{method: http.MethodGet, path: "/login"},
}
// requestCase 表示当前待验证的不弃用请求方法与路径组合。
for _, requestCase := range requests {
// requestCase 保存闭包独占的测试输入,避免循环变量复用。
requestCase := requestCase
t.Run(requestCase.method+" "+requestCase.path, func(t *testing.T) {
// request 保存当前非历史 API 测试请求。
request := httptest.NewRequest(requestCase.method, requestCase.path, nil)
// recorder 保存当前响应头,确保中间件未写入弃用信息。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Header().Get("Deprecation") != "" || recorder.Header().Get("Sunset") != "" || recorder.Header().Get("Link") != "" {
t.Fatalf("非历史路径不应有弃用头: %v", recorder.Header())
}
})
}
}
// TestLegacyAPIRequestCoverage 验证所有保留历史入口类型都会进入遥测,认证入口不会误伤 SPA GET。
func TestLegacyAPIRequestCoverage(t *testing.T) {
// cases 保存各类历史业务与认证请求的遥测预期。
cases := []struct {
// name 是子测试名称,包含方法与路径便于失败定位。
name string
// method 是当前测试请求的方法。
method string
// path 是当前测试请求的路径。
path string
// want 表示当前请求是否应产生历史 API 遥测。
want bool
}{
{name: "legacy api", method: http.MethodGet, path: "/api/orders", want: true},
{name: "legacy dashboard", method: http.MethodGet, path: "/dashboard/stats", want: true},
{name: "legacy analytics", method: http.MethodGet, path: "/analytics/orders", want: true},
{name: "legacy item replies", method: http.MethodGet, path: "/itemReplays", want: true},
{name: "legacy login", method: http.MethodPost, path: "/login", want: true},
{name: "legacy verify", method: http.MethodGet, path: "/verify", want: true},
{name: "spa login", method: http.MethodGet, path: "/login", want: false},
}
// testCase 表示当前待验证的历史入口识别用例。
for _, testCase := range cases {
// testCase 保存闭包独占的用例值,避免循环变量复用。
testCase := testCase
t.Run(testCase.name, func(t *testing.T) {
// got 是当前请求经方法和路径判断后的遥测结果。
got := isLegacyAPIRequest(testCase.method, testCase.path)
if got != testCase.want {
t.Fatalf("isLegacyAPIRequest(%q, %q)=%t, want %t", testCase.method, testCase.path, got, testCase.want)
}
})
}
}
+15 -15
View File
@@ -8,14 +8,14 @@ import (
"time"
)
// loginFailureWindow 保存登录FailureWindow,供当前处理流程使用
// loginFailureWindow 用于本次流程后续判断的登录FailureWindow
const (
loginFailureWindow = 5 * time.Minute
loginFailuresPerIP = 30
loginFailuresPerPrincipal = 10
)
// loginFailureBucket 保存登录FailureBucket,供当前处理流程使用
// loginFailureBucket 用于本次流程后续判断的登录FailureBucket
type loginFailureBucket struct {
count int
expires time.Time
@@ -23,7 +23,7 @@ type loginFailureBucket struct {
// loginFailureLimiter 仅记录失败登录。IP 和账号两个维度同时限制,避免攻击者
// 通过轮换账号绕过 IP 限制,或通过轮换 IP 集中爆破单个账号。
// loginFailureLimiter 保存登录FailureLimiter,供当前处理流程使用
// loginFailureLimiter 用于本次流程后续判断的登录FailureLimiter
type loginFailureLimiter struct {
mu sync.Mutex
buckets map[string]loginFailureBucket
@@ -32,7 +32,7 @@ type loginFailureLimiter struct {
perPrincipal int
}
// newLoginFailureLimiter 负责new登录FailureLimiter相关处理。
// newLoginFailureLimiter 封装new登录FailureLimiter业务协调。
func newLoginFailureLimiter() *loginFailureLimiter {
return &loginFailureLimiter{
buckets: make(map[string]loginFailureBucket),
@@ -42,9 +42,9 @@ func newLoginFailureLimiter() *loginFailureLimiter {
}
}
// loginClientIP 负责登录ClientIP相关处理。
// loginClientIP 封装登录ClientIP业务协调。
func loginClientIP(r *http.Request) string {
// host、err 保存host、err,供当前处理流程使用
// host、err 用于本次流程后续判断的host、err
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil {
return host
@@ -52,29 +52,29 @@ func loginClientIP(r *http.Request) string {
return r.RemoteAddr
}
// loginPrincipal 负责登录Principal相关处理。
// loginPrincipal 封装登录Principal业务协调。
func loginPrincipal(username, email string) string {
if // value 保存值,供当前处理流程使用
if // value 用于本次流程后续判断的值
value := strings.TrimSpace(username); value != "" {
return strings.ToLower(value)
}
return strings.ToLower(strings.TrimSpace(email))
}
// allow 负责allow相关处理。
// allow 封装allow业务协调。
func (l *loginFailureLimiter) allow(ip, principal string, now time.Time) (bool, time.Duration) {
l.mu.Lock()
defer l.mu.Unlock()
// retry 保存重试,供当前处理流程使用
// retry 用于本次流程后续判断的重试
var retry time.Duration
// key 表示当前遍历过程中的key
for _, key := range []string{"ip:" + ip, "principal:" + principal} {
// bucket、ok 保存bucket、ok,供当前处理流程使用
// bucket、ok 用于本次流程后续判断的bucket、ok
bucket, ok := l.buckets[key]
if !ok || !now.Before(bucket.expires) {
continue
}
// limit 保存上限,供当前处理流程使用
// limit 用于本次流程后续判断的上限
limit := l.perPrincipal
if strings.HasPrefix(key, "ip:") {
limit = l.perIP
@@ -86,13 +86,13 @@ func (l *loginFailureLimiter) allow(ip, principal string, now time.Time) (bool,
return retry == 0, retry
}
// failure 负责failure相关处理。
// failure 封装failure业务协调。
func (l *loginFailureLimiter) failure(ip, principal string, now time.Time) {
l.mu.Lock()
defer l.mu.Unlock()
// key 表示当前遍历过程中的key
for _, key := range []string{"ip:" + ip, "principal:" + principal} {
// bucket 保存bucket,供当前处理流程使用
// bucket 用于本次流程后续判断的bucket
bucket := l.buckets[key]
if !now.Before(bucket.expires) {
bucket = loginFailureBucket{expires: now.Add(l.window)}
@@ -110,7 +110,7 @@ func (l *loginFailureLimiter) failure(ip, principal string, now time.Time) {
}
}
// success 负责success相关处理。
// success 封装success业务协调。
func (l *loginFailureLimiter) success(ip, principal string) {
l.mu.Lock()
delete(l.buckets, "ip:"+ip)
+8 -8
View File
@@ -5,40 +5,40 @@ import (
"time"
)
// TestLoginFailureLimiterScopesExpiresAndResets 负责Test登录FailureLimiterScopesExpiresAndResets相关处理。
// TestLoginFailureLimiterScopesExpiresAndResets 封装Test登录FailureLimiterScopesExpiresAndResets业务协调。
func TestLoginFailureLimiterScopesExpiresAndResets(t *testing.T) {
// limiter 保存limiter,供当前处理流程使用
// limiter 用于本次流程后续判断的limiter
limiter := newLoginFailureLimiter()
limiter.perIP = 3
limiter.perPrincipal = 2
limiter.window = time.Minute
// now 保存now,供当前处理流程使用
// now 用于本次流程后续判断的now
now := time.Unix(100, 0)
limiter.failure("10.0.0.1", "admin", now)
limiter.failure("10.0.0.1", "admin", now)
if // allowed、retry 保存allowed、retry,供当前处理流程使用
if // allowed、retry 用于本次流程后续判断的allowed、retry
allowed, retry := limiter.allow("10.0.0.2", "admin", now); allowed || retry != time.Minute {
t.Fatalf("principal limit: allowed=%v retry=%v", allowed, retry)
}
if // allowed 保存allowed,供当前处理流程使用
if // allowed 用于本次流程后续判断的allowed
allowed, _ := limiter.allow("10.0.0.1", "other", now); !allowed {
t.Fatal("IP should remain below its independent limit")
}
limiter.failure("10.0.0.1", "other", now)
if // allowed 保存allowed,供当前处理流程使用
if // allowed 用于本次流程后续判断的allowed
allowed, _ := limiter.allow("10.0.0.1", "third", now); allowed {
t.Fatal("IP limit should apply across principals")
}
limiter.success("10.0.0.1", "admin")
if // allowed 保存allowed,供当前处理流程使用
if // allowed 用于本次流程后续判断的allowed
allowed, _ := limiter.allow("10.0.0.1", "admin", now); !allowed {
t.Fatal("successful authentication should reset matching buckets")
}
limiter.failure("10.0.0.3", "blocked", now)
limiter.failure("10.0.0.3", "blocked", now)
if // allowed 保存allowed,供当前处理流程使用
if // allowed 用于本次流程后续判断的allowed
allowed, _ := limiter.allow("10.0.0.4", "blocked", now.Add(time.Minute)); !allowed {
t.Fatal("expired failure window should allow a new attempt")
}
+5 -5
View File
@@ -19,7 +19,7 @@ type mtopResp struct {
// withMTopTransport 用自定义 transport 构造 *mtop.ClientImpl(按 URL 分发用闭包)。
func withMTopTransport(rt roundTripFunc) *mtop.ClientImpl {
// cli 保存cli,供当前处理流程使用
// cli 用于本次流程后续判断的cli
cli := mtop.NewClient()
cli.HTTPClient = &http.Client{Transport: rt}
return cli
@@ -28,20 +28,20 @@ func withMTopTransport(rt roundTripFunc) *mtop.ClientImpl {
// 默认对未匹配 URL 返回 SUCCESS。
func newMockMTop(t *testing.T, resp mtopResp) *mtop.ClientImpl {
t.Helper()
// cli 保存cli,供当前处理流程使用
// cli 用于本次流程后续判断的cli
cli := mtop.NewClient()
cli.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := resp.body
if body == "" {
body = `{"ret":["` + strings.Join(resp.ret, "\",\"") + `"]}`
}
// status 保存状态,供当前处理流程使用
// status 用于本次流程后续判断的状态
status := resp.statusCode
if status == 0 {
status = http.StatusOK
}
// r 保存r,供当前处理流程使用
// r 用于本次流程后续判断的r
r := &http.Response{
StatusCode: status,
Header: make(http.Header),
+1 -1
View File
@@ -13,7 +13,7 @@ import (
// handled 表示本次请求由完整 Cookie Jar 接管,或 session 已产生可持久化更新;
// 此时即使 Jar 未变化,也不得因扁平 Cookie 的顺序/尾分号差异退回
// UpdatedCookies 写回,否则会把刚保存的完整 Jar 清掉。
// persistMTopCookieSessionLocked 负责persistMTop登录凭证会话Locked相关处理。
// persistMTopCookieSessionLocked 封装persistMTop登录凭证会话Locked业务协调。
func (s *Server) persistMTopCookieSessionLocked(
ctx context.Context,
detail *accountapp.CredentialDetail,
+23 -23
View File
@@ -12,47 +12,47 @@ import (
"xianyu-go/internal/xianyu/mtop"
)
// stubProfileMTop 保存stubProfileMTop,供当前处理流程使用
// stubProfileMTop 用于本次流程后续判断的stubProfileMTop
type stubProfileMTop struct {
mtop.Client
profile func(context.Context, string) (*mtop.UserProfileResult, error)
}
// FetchUserProfile 负责Fetch用户Profile相关处理。
// FetchUserProfile 封装Fetch用户Profile业务协调。
func (s *stubProfileMTop) FetchUserProfile(ctx context.Context, cookies string) (*mtop.UserProfileResult, error) {
return s.profile(ctx, cookies)
}
// TestRefreshAccountProfilePersistsCookieSessionOnResponseError 负责TestRefresh账号ProfilePersists登录凭证会话On响应错误相关处理。
// TestRefreshAccountProfilePersistsCookieSessionOnResponseError 封装TestRefresh账号ProfilePersists登录凭证会话On响应错误业务协调。
func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// detail、err 保存detail、err,供当前处理流程使用
// detail、err 用于本次流程后续判断的detail、err
detail, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatal(err)
}
// snapshot 保存snapshot,供当前处理流程使用
// snapshot 用于本次流程后续判断的snapshot
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "tk1_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "keep", Value: "yes", Domain: "www.goofish.com", Path: "/im", Secure: true},
}
// metadata 保存metadata,供当前处理流程使用
// metadata 用于本次流程后续判断的metadata
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.Cookies.UpdateRenewalCookie(ctx, detail.ID, detail.Value, metadata, time.Now().Unix()); err != nil {
t.Fatal(err)
}
// client 保存client,供当前处理流程使用
// client 用于本次流程后续判断的client
client := mtop.NewClient()
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
// header 保存header,供当前处理流程使用
// header 用于本次流程后续判断的header
header := make(http.Header)
header.Add("Set-Cookie", "rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly")
return &http.Response{
@@ -79,7 +79,7 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T)
t.Fatal("无效响应应返回解析错误")
}
// updated、err 保存updated、err,供当前处理流程使用
// updated、err 用于本次流程后续判断的updated、err
updated, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatal(err)
@@ -87,12 +87,12 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T)
if !strings.Contains(updated.Value, "rotated=fresh") {
t.Fatalf("响应错误时仍应保存 canonical Cookie: %q", updated.Value)
}
// updatedSnapshot、ok 保存updatedSnapshot、ok,供当前处理流程使用
// updatedSnapshot、ok 用于本次流程后续判断的updatedSnapshot、ok
updatedSnapshot, ok := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON)
if !ok {
t.Fatal("响应错误时不应清除权威 Cookie Jar")
}
// values 保存values,供当前处理流程使用
// values 用于本次流程后续判断的values
values := make(map[string]string, len(updatedSnapshot))
// cookie 表示当前遍历过程中的登录凭证
for _, cookie := range updatedSnapshot {
@@ -103,9 +103,9 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T)
}
}
// TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock 负责TestRefresh账号ProfileKeepsAuthoritativeSnapshotWithFlatMock相关处理。
// TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock 封装TestRefresh账号ProfileKeepsAuthoritativeSnapshotWithFlatMock业务协调。
func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
seedStaleCookieSnapshot(t, store, "acc1")
@@ -116,14 +116,14 @@ func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.
UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
}, nil
}}
// detail、err 保存detail、err,供当前处理流程使用
// detail、err 用于本次流程后续判断的detail、err
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
_, _ = srv.accountProfileApplication().RefreshProfile(context.Background(), detail.UserID, detail.ID)
// updated、err 保存updated、err,供当前处理流程使用
// updated、err 用于本次流程后续判断的updated、err
updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
@@ -131,15 +131,15 @@ func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.
if strings.Contains(updated.Value, "_m_h5_tk=mockfresh_2") {
t.Fatalf("完整 Jar 不得被 mock 扁平 Cookie 覆盖: %q", updated.Value)
}
if // complete 保存complete,供当前处理流程使用
if // complete 用于本次流程后续判断的complete
_, complete := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON); !complete {
t.Fatalf("完整 Jar 未发生变化时不得清除: %s", updated.MetadataJSON)
}
}
// TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot 负责TestRefresh账号ProfileKeepsFlatMockFallbackWithoutSnapshot相关处理。
// TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot 封装TestRefresh账号ProfileKeepsFlatMockFallbackWithoutSnapshot业务协调。
func TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
@@ -149,14 +149,14 @@ func TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot(t *testing.T)
UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
}, nil
}}
// detail、err 保存detail、err,供当前处理流程使用
// detail、err 用于本次流程后续判断的detail、err
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
_, _ = srv.accountProfileApplication().RefreshProfile(context.Background(), detail.UserID, detail.ID)
// updated、err 保存updated、err,供当前处理流程使用
// updated、err 用于本次流程后续判断的updated、err
updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
+125 -125
View File
@@ -13,20 +13,20 @@ import (
// TestListChannels 列出通知渠道。
func TestListChannels(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 先创建一个渠道。
body := `{"name":"钉钉","type":"dingtalk","config":"{}","enabled":true}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -36,13 +36,13 @@ func TestListChannels(t *testing.T) {
// 列出。
req2 := httptest.NewRequest(http.MethodGet, "/notification-channels", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("list status=%d", rec2.Code)
}
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["name"] != "钉钉" {
@@ -52,20 +52,20 @@ func TestListChannels(t *testing.T) {
// TestCreateChannelMissingName 缺 name/type 400。
func TestCreateChannelMissingName(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"type":"dingtalk"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -75,18 +75,18 @@ func TestCreateChannelMissingName(t *testing.T) {
// TestCreateChannelBadJSON 非法 JSON 400。
func TestCreateChannelBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -96,40 +96,40 @@ func TestCreateChannelBadJSON(t *testing.T) {
// TestUpdateChannel 更新渠道。
func TestUpdateChannel(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 创建。
body := `{"name":"钉钉","type":"dingtalk","config":"{\"webhook_url\":\"https://example.com\"}","event_types":"[\"account_offline\"]","enabled":true}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cr 保存cr,供当前处理流程使用
// cr 用于本次流程后续判断的cr
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
// id 保存标识,供当前处理流程使用
// id 用于本次流程后续判断的标识
id := int64(cr["id"].(float64))
// 部分更新:只切换 enabled,不应清空 name/type/config/event_types。
upd := `{"enabled":false}`
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(id), strings.NewReader(upd))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("update status=%d body=%s", rec2.Code, rec2.Body.String())
}
// row、err 保存row、err,供当前处理流程使用
// row、err 用于本次流程后续判断的row、err
row, err := store.Notifications.GetChannelRowForUser(context.Background(), id, 1)
if err != nil {
t.Fatalf("get channel row: %v", err)
@@ -145,7 +145,7 @@ func TestUpdateChannel(t *testing.T) {
// 显式传空 event_types 表示恢复为接收全部事件,其它字段仍保留。
req3 := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(id), strings.NewReader(`{"event_types":""}`))
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -162,18 +162,18 @@ func TestUpdateChannel(t *testing.T) {
// TestUpdateChannelBadID 无效 ID 400。
func TestUpdateChannelBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/notification-channels/abc", strings.NewReader(`{}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -183,18 +183,18 @@ func TestUpdateChannelBadID(t *testing.T) {
// TestUpdateChannelBadJSON 非法 JSON 400。
func TestUpdateChannelBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/notification-channels/1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -204,32 +204,32 @@ func TestUpdateChannelBadJSON(t *testing.T) {
// TestDeleteChannel 删除渠道。
func TestDeleteChannel(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"name":"钉钉","type":"dingtalk","config":"{}","enabled":true}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cr 保存cr,供当前处理流程使用
// cr 用于本次流程后续判断的cr
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
// id 保存标识,供当前处理流程使用
// id 用于本次流程后续判断的标识
id := int64(cr["id"].(float64))
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodDelete, "/notification-channels/"+itoa(id), nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -239,18 +239,18 @@ func TestDeleteChannel(t *testing.T) {
// TestDeleteChannelBadID 无效 ID 400。
func TestDeleteChannelBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/notification-channels/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -260,18 +260,18 @@ func TestDeleteChannelBadID(t *testing.T) {
// TestTestChannelNoNotifier 未注入通知器 503。
func TestTestChannelNoNotifier(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/notification-channels/1/test", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
@@ -281,18 +281,18 @@ func TestTestChannelNoNotifier(t *testing.T) {
// TestTestChannelBadID 无效 ID 400。
func TestTestChannelBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/notification-channels/abc/test", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -302,29 +302,29 @@ func TestTestChannelBadID(t *testing.T) {
// TestListMessageNotifications 列出消息通知绑定。
func TestListMessageNotifications(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// 创建渠道 + 绑定。
store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES ('钉钉','dingtalk','{}',1,1)`)
store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1',1,1)`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/message-notifications", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// m 保存m,供当前处理流程使用
// m 用于本次流程后续判断的m
var m map[string][]map[string]any
json.Unmarshal(rec.Body.Bytes(), &m)
if len(m["acc1"]) != 1 {
@@ -332,59 +332,59 @@ func TestListMessageNotifications(t *testing.T) {
}
}
// TestMessageNotificationsFilterCrossUserChannels 负责Test消息通知列表FilterCross用户渠道列表相关处理。
// TestMessageNotificationsFilterCrossUserChannels 封装Test消息通知列表FilterCross用户渠道列表业务协调。
func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.Users.Create(ctx, "notif2", "[email protected]", "pw"); err != nil {
t.Fatalf("create user: %v", err)
}
// u2 保存u2,供当前处理流程使用
// u2 用于本次流程后续判断的u2
u2, _ := store.Users.GetByUsername(ctx, "notif2")
// ownID、err 保存ownID、err,供当前处理流程使用
// ownID、err 用于本次流程后续判断的ownID、err
ownID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
Name: "own", Type: "webhook", Config: `{}`, Enabled: true, UserID: 1,
})
if err != nil {
t.Fatalf("create own channel: %v", err)
}
// otherID、err 保存otherID、err,供当前处理流程使用
// otherID、err 用于本次流程后续判断的otherID、err
otherID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
Name: "other-secret", Type: "webhook", Config: `{}`, Enabled: true, UserID: u2.ID,
})
if err != nil {
t.Fatalf("create other channel: %v", err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1', ?, 1)`, ownID); err != nil {
t.Fatalf("insert own binding: %v", err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1', ?, 1)`, otherID); err != nil {
t.Fatalf("insert dirty binding: %v", err)
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// listReq 保存listReq,供当前处理流程使用
// listReq 用于本次流程后续判断的listReq
listReq := httptest.NewRequest(http.MethodGet, "/message-notifications", nil)
listReq.AddCookie(cookie)
// listRec 保存listRec,供当前处理流程使用
// listRec 用于本次流程后续判断的listRec
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
// listed 保存listed,供当前处理流程使用
// listed 用于本次流程后续判断的listed
var listed map[string][]map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(listRec.Body.Bytes(), &listed); err != nil {
t.Fatalf("decode list: %v", err)
}
@@ -392,37 +392,37 @@ func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
t.Fatalf("list should filter dirty binding: %+v", listed)
}
// getReq 保存getReq,供当前处理流程使用
// getReq 用于本次流程后续判断的getReq
getReq := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil)
getReq.AddCookie(cookie)
// getRec 保存getRec,供当前处理流程使用
// getRec 用于本次流程后续判断的getRec
getRec := httptest.NewRecorder()
h.ServeHTTP(getRec, getReq)
if getRec.Code != http.StatusOK {
t.Fatalf("get status=%d body=%s", getRec.Code, getRec.Body.String())
}
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(getRec.Body.Bytes(), &got); err != nil {
t.Fatalf("decode get: %v", err)
}
// ids 保存ids,供当前处理流程使用
// ids 用于本次流程后续判断的ids
ids, _ := got["channel_ids"].([]any)
if len(ids) != 1 || int64(ids[0].(float64)) != ownID {
t.Fatalf("bindings should filter dirty binding: %+v", got)
}
// updateOtherReq 保存updateOtherReq,供当前处理流程使用
// updateOtherReq 用于本次流程后续判断的updateOtherReq
updateOtherReq := httptest.NewRequest(http.MethodPut, "/notification-channels/"+itoa(otherID), strings.NewReader(`{"enabled":false}`))
updateOtherReq.AddCookie(cookie)
// updateOtherRec 保存updateOtherRec,供当前处理流程使用
// updateOtherRec 用于本次流程后续判断的updateOtherRec
updateOtherRec := httptest.NewRecorder()
h.ServeHTTP(updateOtherRec, updateOtherReq)
if updateOtherRec.Code != http.StatusForbidden {
t.Fatalf("cross-user update should be 403, got %d body=%s", updateOtherRec.Code, updateOtherRec.Body.String())
}
// otherRow、err 保存otherRow、err,供当前处理流程使用
// otherRow、err 用于本次流程后续判断的otherRow、err
otherRow, err := store.Notifications.GetChannelRowForUser(ctx, otherID, u2.ID)
if err != nil {
t.Fatalf("get other channel: %v", err)
@@ -431,10 +431,10 @@ func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
t.Fatalf("cross-user update should not mutate other channel: %+v", otherRow)
}
// deleteOtherReq 保存deleteOtherReq,供当前处理流程使用
// deleteOtherReq 用于本次流程后续判断的deleteOtherReq
deleteOtherReq := httptest.NewRequest(http.MethodDelete, "/notification-channels/"+itoa(otherID), nil)
deleteOtherReq.AddCookie(cookie)
// deleteOtherRec 保存deleteOtherRec,供当前处理流程使用
// deleteOtherRec 用于本次流程后续判断的deleteOtherRec
deleteOtherRec := httptest.NewRecorder()
h.ServeHTTP(deleteOtherRec, deleteOtherReq)
if deleteOtherRec.Code != http.StatusForbidden {
@@ -444,22 +444,22 @@ func TestMessageNotificationsFilterCrossUserChannels(t *testing.T) {
// TestDeleteMessageNotification 删除单条消息通知。
func TestDeleteMessageNotification(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES ('钉钉','dingtalk','{}',1,1)`)
store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1',1,1)`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/message-notifications/1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -469,18 +469,18 @@ func TestDeleteMessageNotification(t *testing.T) {
// TestDeleteMessageNotificationBadID 无效 ID 400。
func TestDeleteMessageNotificationBadID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/message-notifications/abc", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -490,22 +490,22 @@ func TestDeleteMessageNotificationBadID(t *testing.T) {
// TestDeleteAccountNotifications 删除账号的所有通知绑定。
func TestDeleteAccountNotifications(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES ('钉钉','dingtalk','{}',1,1)`)
store.DB.ExecContext(ctx, `INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES ('acc1',1,1)`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/message-notifications/account/acc1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -515,18 +515,18 @@ func TestDeleteAccountNotifications(t *testing.T) {
// TestSetAccountBindingsBadJSON 非法 JSON 400。
func TestSetAccountBindingsBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -536,23 +536,23 @@ func TestSetAccountBindingsBadJSON(t *testing.T) {
// TestSetAccountBindingsSingleChannel 单渠道绑定。
func TestSetAccountBindingsSingleChannel(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES ('钉钉','dingtalk','{}',1,1)`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"channel_id":1,"enabled":true}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
+12 -12
View File
@@ -101,7 +101,7 @@ func (s *Server) listAdminUncertainNotifications(w http.ResponseWriter, r *http.
writeJSON(w, http.StatusOK, newNotificationUncertainOutboxResponse(items, total, true))
}
// listChannels 负责list渠道列表相关处理。
// listChannels 封装list渠道列表业务协调。
func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
@@ -114,7 +114,7 @@ func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, newNotificationChannelResponses(chs))
}
// createChannel 负责create渠道相关处理。
// createChannel 封装create渠道业务协调。
func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
@@ -136,7 +136,7 @@ func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
// updateChannel 负责update渠道相关处理。
// updateChannel 封装update渠道业务协调。
func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
// id、err 保存路径中的渠道 ID 及解析错误。
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
@@ -171,7 +171,7 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteChannel 负责delete渠道相关处理。
// deleteChannel 封装delete渠道业务协调。
func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
// id、err 保存路径中的渠道 ID 及解析错误。
id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64)
@@ -222,7 +222,7 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// getAccountBindings 负责get账号Bindings相关处理。
// getAccountBindings 封装get账号Bindings业务协调。
func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
// cid 保存路径中的账号标识。
cid := chi.URLParam(r, "cid")
@@ -241,7 +241,7 @@ func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, accountBindingsResponse{CookieID: cid, ChannelIDs: ids})
}
// listMessageNotifications 负责list消息通知列表相关处理。
// listMessageNotifications 封装list消息通知列表业务协调。
func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
@@ -251,7 +251,7 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make(notificationBindingListResponse, len(rows))
// cookieID、bindings 表示当前遍历过程中的登录凭证ID、bindings
// binding 表示当前遍历到的通知绑定摘要。
@@ -261,19 +261,19 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
writeJSON(w, http.StatusOK, out)
}
// setAccountBindings 负责set账号Bindings相关处理。
// setAccountBindings 封装set账号Bindings业务协调。
func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
// cid 保存路径中的账号标识。
cid := chi.URLParam(r, "cid")
// req 保存具名账号通知绑定请求。
var req notificationBindingRequest
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if req.ChannelID != 0 {
// enabled 保存启用状态,供当前处理流程使用
// enabled 用于本次流程后续判断的启用状态
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
@@ -311,7 +311,7 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteMessageNotification 负责delete消息通知相关处理。
// deleteMessageNotification 封装delete消息通知业务协调。
func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
@@ -330,7 +330,7 @@ func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Reques
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteAccountNotifications 负责delete账号通知列表相关处理。
// deleteAccountNotifications 封装delete账号通知列表业务协调。
func (s *Server) deleteAccountNotifications(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证用户,用于应用层归属隔离。
sess := authSess(r)
+40 -40
View File
@@ -12,10 +12,10 @@ import (
"xianyu-go/internal/auth"
)
// refreshOrderChunkSize 保存refresh订单Chunk数量,供当前处理流程使用
// refreshOrderChunkSize 用于本次流程后续判断的refresh订单Chunk数量
const refreshOrderChunkSize = 100
// refreshTarget 保存refreshTarget,供当前处理流程使用
// refreshTarget 用于本次流程后续判断的refreshTarget
type refreshTarget struct {
OrderID string
CurrentStatus string
@@ -35,9 +35,9 @@ func (s *Server) mountOrdersReal(r chi.Router) {
// listOrders 分页查询当前用户订单。
func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
// result、err 用于本次流程后续判断的result、err
result, err := s.orders().List(r.Context(), orderListQuery{
UserID: sess.UserID, CookieID: r.URL.Query().Get("cookie_id"),
Status: r.URL.Query().Get("status"), Search: r.URL.Query().Get("search"),
@@ -63,11 +63,11 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
// getOrder 订单详情。
func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
// orderID 保存订单ID,供当前处理流程使用
// orderID 用于本次流程后续判断的订单ID
orderID := chi.URLParam(r, "order_id")
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
// result、err 用于本次流程后续判断的result、err
result, err := s.orders().GetView(r.Context(), sess.UserID, orderID)
if err != nil {
if errors.Is(err, orderapp.ErrForbidden) {
@@ -82,16 +82,16 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
})
}
// chunkRefreshTargets 负责chunkRefreshTargets相关处理。
// chunkRefreshTargets 封装chunkRefreshTargets业务协调。
func chunkRefreshTargets(targets []refreshTarget, size int) [][]refreshTarget {
if size <= 0 {
size = refreshOrderChunkSize
}
// chunks 保存chunks,供当前处理流程使用
// chunks 用于本次流程后续判断的chunks
chunks := make([][]refreshTarget, 0, (len(targets)+size-1)/size)
for // start 保存开始,供当前处理流程使用
for // start 用于本次流程后续判断的开始
start := 0; start < len(targets); start += size {
// end 保存结束,供当前处理流程使用
// end 用于本次流程后续判断的结束
end := start + size
if end > len(targets) {
end = len(targets)
@@ -101,13 +101,13 @@ func chunkRefreshTargets(targets []refreshTarget, size int) [][]refreshTarget {
return chunks
}
// missingRefreshTargetIDs 负责missingRefreshTargetIDs相关处理。
// missingRefreshTargetIDs 封装missingRefreshTargetIDs业务协调。
func missingRefreshTargetIDs(targets []refreshTarget, seen map[string]struct{}) []string {
// missing 保存missing,供当前处理流程使用
// missing 用于本次流程后续判断的missing
missing := make([]string, 0)
// target 表示当前遍历过程中的target
for _, target := range targets {
if // ok 保存ok,供当前处理流程使用
if // ok 用于本次流程后续判断的ok
_, ok := seen[target.OrderID]; !ok {
missing = append(missing, target.OrderID)
}
@@ -117,9 +117,9 @@ func missingRefreshTargetIDs(targets []refreshTarget, seen map[string]struct{})
func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { // refreshSingleOrder 保持单订单刷新与批量刷新使用相同的详情 DTO。
orderID := chi.URLParam(r, "order_id")
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
// result、err 用于本次流程后续判断的result、err
result, err := s.orders().RefreshSingle(r.Context(), sess.UserID, orderID)
if errors.Is(err, orderapp.ErrNotFound) {
writeErr(w, http.StatusNotFound, "订单不存在")
@@ -150,11 +150,11 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { //
// deleteOrder 逻辑删除订单,保留订单历史,避免破坏自动化审计数据。
func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
// orderID 保存订单ID,供当前处理流程使用
// orderID 用于本次流程后续判断的订单ID
orderID := chi.URLParam(r, "order_id")
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.orders().Delete(r.Context(), sess.UserID, orderID); err != nil {
if errors.Is(err, orderapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权操作此订单")
@@ -168,11 +168,11 @@ func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
// updateOrder 更新订单(手动发货等)。
func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
// orderID 保存订单ID,供当前处理流程使用
// orderID 用于本次流程后续判断的订单ID
orderID := chi.URLParam(r, "order_id")
// req 保存具名订单更新请求,兼容旧客户端的状态别名和数值字段。
var req orderUpdateRequestDTO
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -182,27 +182,27 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
if status == nil {
status = req.Status
}
// stringPtrFromAny 保存stringPtrFromAny,供当前处理流程使用
// stringPtrFromAny 用于本次流程后续判断的stringPtrFromAny
stringPtrFromAny := func(value *any) *string {
if value == nil {
return nil
}
// v 保存v,供当前处理流程使用
// v 用于本次流程后续判断的v
v := stringFromAny(*value)
return &v
}
// amount 保存兼容 JSON 数值转换后的订单金额。
amount := stringPtrFromAny(req.Amount)
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.orders().Update(r.Context(), sess.UserID, orderID, orderUpdateRequest{
OrderStatus: status, ItemID: req.ItemID, BuyerID: req.BuyerID, SpecName: req.SpecName,
SpecValue: req.SpecValue, Quantity: stringPtrFromAny(req.Quantity), Amount: amount,
ReceiverName: req.ReceiverName, ReceiverPhone: req.ReceiverPhone, ReceiverAddress: req.ReceiverAddress,
ReceiverCity: req.ReceiverCity, ChatID: req.ChatID, SystemShipped: req.SystemShipped, ItemTitle: req.ItemTitle,
}); err != nil {
if // kind、classified 保存kind、classified,供当前处理流程使用
if // kind、classified 用于本次流程后续判断的kind、classified
kind, classified := orderErrorKindOf(err); classified && kind == orderErrorBadRequest {
writeErr(w, http.StatusBadRequest, err.Error())
} else if errors.Is(err, orderapp.ErrForbidden) {
@@ -217,23 +217,23 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// validOrderAmount 负责有效订单Amount相关处理。
// validOrderAmount 封装有效订单Amount业务协调。
func validOrderAmount(raw string) bool {
// ok 保存ok,供当前处理流程使用
// ok 用于本次流程后续判断的ok
_, ok := normalizeOrderAmount(raw)
return ok
}
// normalizeOrderAmount 负责normalize订单Amount相关处理。
// normalizeOrderAmount 封装normalize订单Amount业务协调。
func normalizeOrderAmount(raw string) (string, bool) {
return orderapp.NormalizeOrderAmount(raw)
}
// manualShipOrders 负责manualShip订单列表相关处理。
// manualShipOrders 封装manualShip订单列表业务协调。
func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
// req 保存具名批量发货请求。
var req manualShipRequestDTO
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -249,9 +249,9 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "发货模式必须是 status_only 或 full_delivery")
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
// result、err 用于本次流程后续判断的result、err
result, err := s.orders().ManualShip(r.Context(), manualShipRequest{
UserID: sess.UserID, OrderIDs: req.OrderIDs, ShipMode: req.ShipMode,
})
@@ -267,17 +267,17 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
})
}
// importOrders 负责import订单列表相关处理。
// importOrders 封装import订单列表业务协调。
func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
// orders、err 保存orders、err,供当前处理流程使用
// orders、err 用于本次流程后续判断的orders、err
orders, err := parseImportedOrders(w, r)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
// result、err 用于本次流程后续判断的result、err
result, err := s.orders().Import(r.Context(), sess.UserID, orders)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询账号失败")
@@ -292,12 +292,12 @@ func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
})
}
// atoiDefault 负责atoiDefault相关处理。
// atoiDefault 封装atoiDefault业务协调。
func atoiDefault(s string, def int) int {
if s == "" {
return def
}
// n、err 保存n、err,供当前处理流程使用
// n、err 用于本次流程后续判断的n、err
n, err := strconv.Atoi(s)
if err != nil {
return def
@@ -305,7 +305,7 @@ func atoiDefault(s string, def int) int {
return n
}
// isStableOrderStatus 负责isStable订单状态相关处理。
// isStableOrderStatus 封装isStable订单状态业务协调。
func isStableOrderStatus(status string) bool {
switch status {
case "shipped", "completed", "cancelled":
File diff suppressed because it is too large. Load diff
+69 -69
View File
@@ -22,9 +22,9 @@ import (
// parseImportedOrders 从 HTTP 请求体解析导入的订单。
// 支持两种入口:multipart/form-data 上传文件(按扩展名分流),或 raw body(按内容分流)。
// 上限 maxOrderImportBytes(32 MiB),由调用方在更上层用 MaxBytesReader 强制。
// parseImportedOrders 负责parseImported订单列表相关处理。
// parseImportedOrders 封装parseImported订单列表业务协调。
func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]any, error) {
// ct 保存ct,供当前处理流程使用
// ct 用于本次流程后续判断的ct
ct := r.Header.Get("Content-Type")
if strings.HasPrefix(ct, "multipart/form-data") {
// 订单文件上限 32 MiB;MaxBytesReader 必须在 ParseMultipartForm 前应用。
@@ -33,13 +33,13 @@ func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]a
if err := r.ParseMultipartForm(maxOrderImportBytes); err != nil {
return nil, fmt.Errorf("解析上传文件失败: %w", err)
}
// file、header、err 保存file、header、err,供当前处理流程使用
// file、header、err 用于本次流程后续判断的file、header、err
file, header, err := r.FormFile("file")
if err != nil {
return nil, fmt.Errorf("缺少上传文件")
}
defer file.Close()
// raw、err 保存raw、err,供当前处理流程使用
// raw、err 用于本次流程后续判断的raw、err
raw, err := io.ReadAll(io.LimitReader(file, int64(maxOrderImportBytes)+1))
if err != nil {
return nil, fmt.Errorf("读取上传文件失败: %w", err)
@@ -49,7 +49,7 @@ func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]a
}
return parseImportedOrderBytes(raw, header.Filename)
}
// raw、err 保存raw、err,供当前处理流程使用
// raw、err 用于本次流程后续判断的raw、err
raw, err := io.ReadAll(io.LimitReader(r.Body, int64(maxOrderImportBytes)+1))
if err != nil {
return nil, fmt.Errorf("读取请求失败: %w", err)
@@ -84,7 +84,7 @@ func parseImportedOrderBytes(raw []byte, filename string) ([]map[string]any, err
// parseJSONOrders 解析 JSON 数组或单对象。
func parseJSONOrders(raw []byte) ([]map[string]any, error) {
// trimmed 保存trimmed,供当前处理流程使用
// trimmed 用于本次流程后续判断的trimmed
trimmed := bytes.TrimSpace(raw)
if len(trimmed) == 0 {
return nil, fmt.Errorf("导入内容为空")
@@ -92,34 +92,34 @@ func parseJSONOrders(raw []byte) ([]map[string]any, error) {
if trimmed[0] == '[' {
return parseJSONOrderArray(trimmed)
}
// single 保存single,供当前处理流程使用
// single 用于本次流程后续判断的single
var single map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(trimmed, &single); err != nil {
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
}
return normalizeImportOrderMaps([]map[string]any{single}), nil
}
// parseJSONOrderArray 负责parseJSON订单Array相关处理。
// parseJSONOrderArray 封装parseJSON订单Array业务协调。
func parseJSONOrderArray(raw []byte) ([]map[string]any, error) {
// dec 保存dec,供当前处理流程使用
// dec 用于本次流程后续判断的dec
dec := json.NewDecoder(bytes.NewReader(raw))
// tok、err 保存tok、err,供当前处理流程使用
// tok、err 用于本次流程后续判断的tok、err
tok, err := dec.Token()
if err != nil {
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
}
if // delim、ok 保存delim、ok,供当前处理流程使用
if // delim、ok 用于本次流程后续判断的delim、ok
delim, ok := tok.(json.Delim); !ok || delim != '[' {
return nil, fmt.Errorf("解析 JSON 失败: 不是数组")
}
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make([]map[string]any, 0, 256)
for dec.More() {
// row 保存row,供当前处理流程使用
// row 用于本次流程后续判断的row
var row map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := dec.Decode(&row); err != nil {
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
}
@@ -130,13 +130,13 @@ func parseJSONOrderArray(raw []byte) ([]map[string]any, error) {
}
if tok, err = dec.Token(); err != nil {
return nil, fmt.Errorf("解析 JSON 失败: %w", err)
} else if // delim、ok 保存delim、ok,供当前处理流程使用
} else if // delim、ok 用于本次流程后续判断的delim、ok
delim, ok := tok.(json.Delim); !ok || delim != ']' {
return nil, fmt.Errorf("解析 JSON 失败: 数组未闭合")
}
// extra 保存extra,供当前处理流程使用
// extra 用于本次流程后续判断的extra
var extra any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := dec.Decode(&extra); err != io.EOF {
if err == nil {
return nil, fmt.Errorf("解析 JSON 失败: 存在额外内容")
@@ -148,24 +148,24 @@ func parseJSONOrderArray(raw []byte) ([]map[string]any, error) {
// parseDelimitedOrders 解析 CSV/TSV(按 comma 分隔)。首行为表头,其余为数据行。
// 全空行跳过。
// parseDelimitedOrders 负责parseDelimited订单列表相关处理。
// parseDelimitedOrders 封装parseDelimited订单列表业务协调。
func parseDelimitedOrders(raw []byte, comma rune) ([]map[string]any, error) {
// reader 保存reader,供当前处理流程使用
// reader 用于本次流程后续判断的reader
reader := csv.NewReader(bytes.NewReader(raw))
reader.Comma = comma
reader.FieldsPerRecord = -1
reader.LazyQuotes = true
// headerRow、err 保存headerRow、err,供当前处理流程使用
// headerRow、err 用于本次流程后续判断的headerRow、err
headerRow, err := reader.Read()
if err != nil {
return nil, fmt.Errorf("解析表格失败: %w", err)
}
// headers 保存headers,供当前处理流程使用
// headers 用于本次流程后续判断的headers
headers := normalizeImportHeaders(headerRow)
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows := make([][]string, 0, 256)
for {
// record、err 保存record、err,供当前处理流程使用
// record、err 用于本次流程后续判断的record、err
record, err := reader.Read()
if err == io.EOF {
break
@@ -186,19 +186,19 @@ func parseDelimitedOrders(raw []byte, comma rune) ([]map[string]any, error) {
// parseXLSXOrders 解析 .xlsx(OOXML):读取 sharedStrings + 第一个 worksheet,
// 按 cell ref(如 "C3")定位列索引,支持共享字符串、内联字符串、数字三种 cell 类型。
// parseXLSXOrders 负责parseXLSX订单列表相关处理。
// parseXLSXOrders 封装parseXLSX订单列表业务协调。
func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
// zr、err 保存zr、err,供当前处理流程使用
// zr、err 用于本次流程后续判断的zr、err
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return nil, fmt.Errorf("解析 xlsx 失败: %w", err)
}
// shared、err 保存shared、err,供当前处理流程使用
// shared、err 用于本次流程后续判断的shared、err
shared, err := xlsxSharedStrings(zr)
if err != nil {
return nil, err
}
// sheet 保存sheet,供当前处理流程使用
// sheet 用于本次流程后续判断的sheet
var sheet *zip.File
// f 表示当前遍历过程中的f
for _, f := range zr.File {
@@ -210,26 +210,26 @@ func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
if sheet == nil {
return nil, fmt.Errorf("xlsx 中未找到工作表")
}
// rawSheet、err 保存原始Sheet、err,供当前处理流程使用
// rawSheet、err 用于本次流程后续判断的原始Sheet、err
rawSheet, err := readXLSXPart(sheet)
if err != nil {
return nil, err
}
// ws 保存ws,供当前处理流程使用
// ws 用于本次流程后续判断的ws
var ws xlsxWorksheet
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := xmlUnmarshalXLSX(rawSheet, &ws); err != nil {
return nil, fmt.Errorf("解析工作表失败: %w", err)
}
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows := make([][]string, 0, len(ws.SheetData.Rows))
// row 表示当前遍历过程中的row
for _, row := range ws.SheetData.Rows {
// values 保存values,供当前处理流程使用
// values 用于本次流程后续判断的values
values := []string{}
// cell 表示当前遍历过程中的cell
for _, cell := range row.Cells {
// idx 保存idx,供当前处理流程使用
// idx 用于本次流程后续判断的idx
idx := xlsxCellIndex(cell.Ref)
for len(values) <= idx {
values = append(values, "")
@@ -241,9 +241,9 @@ func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
if len(rows) < 2 {
return nil, fmt.Errorf("xlsx 至少需要表头和一行数据")
}
// headers 保存headers,供当前处理流程使用
// headers 用于本次流程后续判断的headers
headers := normalizeImportHeaders(rows[0])
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := rowsToMaps(headers, rows[1:])
if len(out) > maxOrderImportRows {
return nil, fmt.Errorf("单次最多导入 %d 条订单", maxOrderImportRows)
@@ -253,20 +253,20 @@ func parseXLSXOrders(raw []byte) ([]map[string]any, error) {
// rowsToMaps 把表头 + 数据行转为 map 列表,全空行跳过。
func rowsToMaps(headers []string, rows [][]string) []map[string]any {
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make([]map[string]any, 0, len(rows))
// row 表示当前遍历过程中的row
for _, row := range rows {
// m 保存m,供当前处理流程使用
// m 用于本次流程后续判断的m
m := make(map[string]any)
// nonEmpty 保存nonEmpty,供当前处理流程使用
// nonEmpty 用于本次流程后续判断的nonEmpty
nonEmpty := false
// i、h 表示当前遍历过程中的i、h
for i, h := range headers {
if h == "" || i >= len(row) {
continue
}
// v 保存v,供当前处理流程使用
// v 用于本次流程后续判断的v
v := strings.TrimSpace(row[i])
if v != "" {
nonEmpty = true
@@ -282,19 +282,19 @@ func rowsToMaps(headers []string, rows [][]string) []map[string]any {
// ---- XLSX OOXML 内部结构 ----
// xlsxWorksheet 保存xlsxWorksheet,供当前处理流程使用
// xlsxWorksheet 用于本次流程后续判断的xlsxWorksheet
type xlsxWorksheet struct {
SheetData struct {
Rows []xlsxRow `xml:"row"`
} `xml:"sheetData"`
}
// xlsxRow 保存xlsxRow,供当前处理流程使用
// xlsxRow 用于本次流程后续判断的xlsxRow
type xlsxRow struct {
Cells []xlsxCell `xml:"c"`
}
// xlsxCell 保存xlsxCell,供当前处理流程使用
// xlsxCell 用于本次流程后续判断的xlsxCell
type xlsxCell struct {
Ref string `xml:"r,attr"`
Type string `xml:"t,attr"`
@@ -302,7 +302,7 @@ type xlsxCell struct {
InlineStr string `xml:"is>t"`
}
// xlsxSST 保存xlsxSST,供当前处理流程使用
// xlsxSST 用于本次流程后续判断的xlsxSST
type xlsxSST struct {
Items []struct {
Inner string `xml:",innerxml"`
@@ -316,18 +316,18 @@ func xlsxSharedStrings(zr *zip.Reader) ([]string, error) {
if f.Name != "xl/sharedStrings.xml" {
continue
}
// raw、err 保存raw、err,供当前处理流程使用
// raw、err 用于本次流程后续判断的raw、err
raw, err := readXLSXPart(f)
if err != nil {
return nil, err
}
// sst 保存sst,供当前处理流程使用
// sst 用于本次流程后续判断的sst
var sst xlsxSST
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := xmlUnmarshalXLSX(raw, &sst); err != nil {
return nil, err
}
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make([]string, 0, len(sst.Items))
// item 表示当前遍历过程中的商品
for _, item := range sst.Items {
@@ -338,9 +338,9 @@ func xlsxSharedStrings(zr *zip.Reader) ([]string, error) {
return nil, nil
}
// readXLSXPart 负责readXLSXPart相关处理。
// readXLSXPart 封装readXLSXPart业务协调。
func readXLSXPart(f *zip.File) ([]byte, error) {
// rc、err 保存rc、err,供当前处理流程使用
// rc、err 用于本次流程后续判断的rc、err
rc, err := f.Open()
if err != nil {
return nil, err
@@ -349,9 +349,9 @@ func readXLSXPart(f *zip.File) ([]byte, error) {
return readLimitedXLSXXML(rc)
}
// readLimitedXLSXXML 负责readLimitedXLSXXML相关处理。
// readLimitedXLSXXML 封装readLimitedXLSXXML业务协调。
func readLimitedXLSXXML(r io.Reader) ([]byte, error) {
// raw、err 保存raw、err,供当前处理流程使用
// raw、err 用于本次流程后续判断的raw、err
raw, err := io.ReadAll(io.LimitReader(r, maxXLSXXMLPartBytes+1))
if err != nil {
return nil, err
@@ -362,7 +362,7 @@ func readLimitedXLSXXML(r io.Reader) ([]byte, error) {
return raw, nil
}
// xmlUnmarshalXLSX 负责xmlUnmarshalXLSX相关处理。
// xmlUnmarshalXLSX 封装xmlUnmarshalXLSX业务协调。
func xmlUnmarshalXLSX(raw []byte, v any) error {
return xml.Unmarshal(raw, v)
}
@@ -371,7 +371,7 @@ func xmlUnmarshalXLSX(raw []byte, v any) error {
func xlsxCellValue(cell xlsxCell, shared []string) string {
switch cell.Type {
case "s":
// idx 保存idx,供当前处理流程使用
// idx 用于本次流程后续判断的idx
idx, _ := strconv.Atoi(strings.TrimSpace(cell.Value))
if idx >= 0 && idx < len(shared) {
return shared[idx]
@@ -384,7 +384,7 @@ func xlsxCellValue(cell xlsxCell, shared []string) string {
// xlsxCellIndex 把 cell ref 的列部分(如 "C3" → "C")转为 0-based 列索引。
func xlsxCellIndex(ref string) int {
// idx 保存idx,供当前处理流程使用
// idx 用于本次流程后续判断的idx
idx := 0
// r 表示当前遍历过程中的r
for _, r := range ref {
@@ -401,17 +401,17 @@ func xlsxCellIndex(ref string) int {
// xmlCharData 从 innerxml 片段中抽取所有字符数据(拼接富文本格式的单元格内容)。
func xmlCharData(inner string) string {
// dec 保存dec,供当前处理流程使用
// dec 用于本次流程后续判断的dec
dec := xml.NewDecoder(strings.NewReader("<x>" + inner + "</x>"))
// parts 保存parts,供当前处理流程使用
// parts 用于本次流程后续判断的parts
var parts []string
for {
// tok、err 保存tok、err,供当前处理流程使用
// tok、err 用于本次流程后续判断的tok、err
tok, err := dec.Token()
if err != nil {
break
}
if // data、ok 保存data、ok,供当前处理流程使用
if // data、ok 用于本次流程后续判断的data、ok
data, ok := tok.(xml.CharData); ok {
parts = append(parts, string(data))
}
@@ -423,7 +423,7 @@ func xmlCharData(inner string) string {
// normalizeImportOrderMaps 归一化 JSON 解析结果的 key(中文/英文别名 → 标准字段名)。
func normalizeImportOrderMaps(in []map[string]any) []map[string]any {
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make([]map[string]any, 0, len(in))
// raw 表示当前遍历过程中的原始
for _, raw := range in {
@@ -432,9 +432,9 @@ func normalizeImportOrderMaps(in []map[string]any) []map[string]any {
return out
}
// normalizeImportOrderMap 负责normalizeImport订单Map相关处理。
// normalizeImportOrderMap 封装normalizeImport订单Map业务协调。
func normalizeImportOrderMap(raw map[string]any) map[string]any {
// m 保存m,供当前处理流程使用
// m 用于本次流程后续判断的m
m := make(map[string]any)
// k、v 表示当前遍历过程中的k、v
for k, v := range raw {
@@ -443,9 +443,9 @@ func normalizeImportOrderMap(raw map[string]any) map[string]any {
return m
}
// normalizeImportHeaders 负责normalizeImportHeaders相关处理。
// normalizeImportHeaders 封装normalizeImportHeaders业务协调。
func normalizeImportHeaders(headers []string) []string {
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make([]string, len(headers))
// i、h 表示当前遍历过程中的i、h
for i, h := range headers {
@@ -456,9 +456,9 @@ func normalizeImportHeaders(headers []string) []string {
// normalizeImportHeader 把表头归一为小写无分隔的标准字段名。
// 支持中英文别名(如 "订单号"→"order_id"、"商品标题"→"item_title")。
// normalizeImportHeader 负责normalizeImportHeader相关处理。
// normalizeImportHeader 封装normalizeImportHeader业务协调。
func normalizeImportHeader(header string) string {
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := strings.ToLower(strings.TrimSpace(header))
h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h)
switch h {
@@ -505,9 +505,9 @@ func normalizeImportHeader(header string) string {
func firstImportString(m map[string]any, keys ...string) string {
// k 表示当前遍历过程中的k
for _, k := range keys {
if // v、ok 保存v、ok,供当前处理流程使用
if // v、ok 用于本次流程后续判断的v、ok
v, ok := m[k]; ok {
// s 保存s,供当前处理流程使用
// s 用于本次流程后续判断的s
s := strings.TrimSpace(stringFromAny(v))
if s != "" {
return s
@@ -519,7 +519,7 @@ func firstImportString(m map[string]any, keys ...string) string {
// stringFromAny 把 any 安全转为字符串(nil→"",数字/布尔格式化)。
func stringFromAny(v any) string {
switch // x 保存x,供当前处理流程使用
switch // x 用于本次流程后续判断的x
x := v.(type) {
case nil:
return ""
+7 -7
View File
@@ -267,10 +267,10 @@ func refreshResultsFromApplication(items []orderapp.RefreshOrderResult) []orderR
return results
}
// errOrderDetailUnsupported 保存err订单DetailUnsupported,供当前处理流程使用
// errOrderDetailUnsupported 用于本次流程后续判断的err订单DetailUnsupported
var errOrderDetailUnsupported = errors.New("当前 Go MTOP 客户端不支持订单详情接口")
// errOrderCredentialChanged 保存err订单CredentialChanged,供当前处理流程使用
// errOrderCredentialChanged 用于本次流程后续判断的err订单CredentialChanged
var errOrderCredentialChanged = errors.New("账号凭证已变化,请重试")
// orderErrorKind 标识应用服务错误的业务分类,避免 HTTP 层依赖错误文本判断状态码。
@@ -302,7 +302,7 @@ func newOrderBadRequest(message string) error {
// orderErrorKindOf 读取订单应用服务错误分类。
func orderErrorKindOf(err error) (orderErrorKind, bool) {
// applicationErr 保存applicationErr,供当前处理流程使用
// applicationErr 用于本次流程后续判断的applicationErr
var applicationErr *orderApplicationError
if !errors.As(err, &applicationErr) {
return 0, false
@@ -347,7 +347,7 @@ type orderListResult struct {
// orderDTOFromRow 把数据库订单列表行转换为稳定的订单响应视图。
func orderDTOFromRow(row orderapp.OrderRow) orderDTO {
// status 保存状态,供当前处理流程使用
// status 用于本次流程后续判断的状态
status := orderapp.NormalizeOrderStatus(row.OrderStatus)
return orderDTO{
OrderID: row.OrderID, ItemID: row.ItemID, ItemTitle: row.ItemTitle,
@@ -363,13 +363,13 @@ func orderDTOFromRow(row orderapp.OrderRow) orderDTO {
// orderDTOFromOrder 把订单实体和关联商品信息转换为详情响应视图。
func orderDTOFromOrder(order *orderapp.Order, item *orderapp.ItemInfo) orderDTO {
// itemTitle、itemImage 保存商品Title、item图片,供当前处理流程使用
// itemTitle、itemImage 用于本次流程后续判断的商品Title、item图片
itemTitle, itemImage := "", ""
if item != nil {
itemTitle = item.ItemTitle
itemImage = itemImageFromDetail(item.ItemDetail)
}
// status 保存状态,供当前处理流程使用
// status 用于本次流程后续判断的状态
status := orderapp.NormalizeOrderStatus(order.OrderStatus)
return orderDTO{
OrderID: order.OrderID, ItemID: order.ItemID, ItemTitle: itemTitle, ItemImage: itemImage,
@@ -402,7 +402,7 @@ func (a *orderHTTPAdapter) List(ctx context.Context, query orderListQuery) (orde
if err != nil {
return orderListResult{}, err
}
// orders 保存订单列表,供当前处理流程使用
// orders 用于本次流程后续判断的订单列表
orders := make([]orderDTO, 0, len(result.Rows))
// row 表示当前遍历过程中的row
for _, row := range result.Rows {
+3 -3
View File
@@ -13,15 +13,15 @@ func authSess(r *http.Request) *auth.SessionIdentity {
return auth.IdentityFromContext(r.Context())
}
// requireCookieOwner 负责require登录凭证所有者相关处理。
// requireCookieOwner 封装require登录凭证所有者业务协调。
func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cookieID string) (accountapp.AccountSummary, bool) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return accountapp.AccountSummary{}, false
}
// d、err 保存d、err,供当前处理流程使用
// d、err 用于本次流程后续判断的d、err
d, err := s.loadCookieSummaryDetail(r.Context(), sess.UserID, cookieID)
if err != nil {
writeErr(w, http.StatusNotFound, "账号不存在")
+54 -54
View File
@@ -12,29 +12,29 @@ import (
"testing"
)
// TestParseMoneyCents 负责TestParseMoneyCents相关处理。
// TestParseMoneyCents 封装TestParseMoneyCents业务协调。
func TestParseMoneyCents(t *testing.T) {
// cases 保存cases,供当前处理流程使用
// cases 用于本次流程后续判断的cases
cases := map[string]int64{"1": 100, "1.2": 120, "¥12.34": 1234, "¥0.01": 1, "-0.50": -50, "+2.05": 205, "": 0}
// raw、want 表示当前遍历过程中的raw、want
for raw, want := range cases {
// got、err 保存got、err,供当前处理流程使用
// got、err 用于本次流程后续判断的got、err
got, err := parseMoneyCents(raw)
if err != nil || got != want {
t.Errorf("parseMoneyCents(%q) = %d, %v; want %d", raw, got, err, want)
}
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := parseMoneyCents("1.2.3"); err == nil {
t.Fatal("invalid money should fail")
}
}
// TestOrderImportParsers 负责Test订单ImportParsers相关处理。
// TestOrderImportParsers 封装Test订单ImportParsers业务协调。
func TestOrderImportParsers(t *testing.T) {
// csvData 保存csv数据,供当前处理流程使用
// csvData 用于本次流程后续判断的csv数据
csvData := []byte("订单号,商品ID,买家ID,金额,状态\no1,i1,b1,12.50,已付款\n")
// rows、err 保存rows、err,供当前处理流程使用
// rows、err 用于本次流程后续判断的rows、err
rows, err := parseImportedOrderBytes(csvData, "orders.csv")
if err != nil || len(rows) != 1 {
t.Fatalf("parse csv = %#v, %v", rows, err)
@@ -46,7 +46,7 @@ func TestOrderImportParsers(t *testing.T) {
if err != nil || len(rows) != 1 || rows[0]["order_id"] != "o2" {
t.Fatalf("parse json = %#v, %v", rows, err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := parseImportedOrderBytes(nil, "orders.csv"); err == nil {
t.Fatal("empty import should fail")
}
@@ -55,9 +55,9 @@ func TestOrderImportParsers(t *testing.T) {
// TestOrderImportFormats 覆盖 TSV、单对象 JSON、.xls 拒绝、无扩展名默认 CSV。
func TestOrderImportFormats(t *testing.T) {
// TSV
// tsv 保存tsv,供当前处理流程使用
// tsv 用于本次流程后续判断的tsv
tsv := []byte("order_id\tamount\no1\t1.5\n")
// rows、err 保存rows、err,供当前处理流程使用
// rows、err 用于本次流程后续判断的rows、err
rows, err := parseImportedOrderBytes(tsv, "orders.tsv")
if err != nil || len(rows) != 1 || rows[0]["order_id"] != "o1" {
t.Fatalf("parse tsv = %#v, %v", rows, err)
@@ -92,23 +92,23 @@ func TestOrderImportFormats(t *testing.T) {
}
}
// TestOrderImportRejectsTooManyRows 负责Test订单ImportRejectsTooManyRows相关处理。
// TestOrderImportRejectsTooManyRows 封装Test订单ImportRejectsTooManyRows业务协调。
func TestOrderImportRejectsTooManyRows(t *testing.T) {
// b 保存b,供当前处理流程使用
// b 用于本次流程后续判断的b
var b strings.Builder
b.WriteString("order_id\n")
for // i 保存i,供当前处理流程使用
for // i 用于本次流程后续判断的i
i := 0; i < maxOrderImportRows+1; i++ {
_, _ = fmt.Fprintf(&b, "o%d\n", i)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := parseImportedOrderBytes([]byte(b.String()), "orders.csv"); err == nil {
t.Fatal("too many import rows should fail")
}
b.Reset()
b.WriteString("[")
for // i 保存i,供当前处理流程使用
for // i 用于本次流程后续判断的i
i := 0; i < maxOrderImportRows+1; i++ {
if i > 0 {
b.WriteString(",")
@@ -116,7 +116,7 @@ func TestOrderImportRejectsTooManyRows(t *testing.T) {
_, _ = fmt.Fprintf(&b, `{"order_id":"o%d"}`, i)
}
b.WriteString("]")
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := parseImportedOrderBytes([]byte(b.String()), "orders.json"); err == nil {
t.Fatal("too many JSON import rows should fail")
}
@@ -124,9 +124,9 @@ func TestOrderImportRejectsTooManyRows(t *testing.T) {
// TestParseXLSXOrders 构造一个最小 xlsx,验证 shared string + 数字 cell 解析。
func TestParseXLSXOrders(t *testing.T) {
// xlsx 保存xlsx,供当前处理流程使用
// xlsx 用于本次流程后续判断的xlsx
xlsx := buildMinimalXLSX(t, [][]string{{"order_id", "amount"}, {"o1", "12.5"}})
// rows、err 保存rows、err,供当前处理流程使用
// rows、err 用于本次流程后续判断的rows、err
rows, err := parseXLSXOrders(xlsx)
if err != nil {
t.Fatalf("parseXLSX: %v", err)
@@ -136,16 +136,16 @@ func TestParseXLSXOrders(t *testing.T) {
}
}
// TestReadLimitedXLSXXMLRejectsOversizedPart 负责TestReadLimitedXLSXXMLRejectsOversizedPart相关处理。
// TestReadLimitedXLSXXMLRejectsOversizedPart 封装TestReadLimitedXLSXXMLRejectsOversizedPart业务协调。
func TestReadLimitedXLSXXMLRejectsOversizedPart(t *testing.T) {
// err 保存err,供当前处理流程使用
// err 用于本次流程后续判断的err
_, err := readLimitedXLSXXML(io.LimitReader(endlessByteReader{}, maxXLSXXMLPartBytes+1))
if err == nil {
t.Fatal("oversized xlsx XML should fail")
}
}
// endlessByteReader 保存endlessByteReader,供当前处理流程使用
// endlessByteReader 用于本次流程后续判断的endlessByteReader
type endlessByteReader struct{}
// Read 读取当前值。
@@ -159,7 +159,7 @@ func (endlessByteReader) Read(p []byte) (int, error) {
// TestNormalizeImportHeader 表驱动验证中英文别名归一。
func TestNormalizeImportHeader(t *testing.T) {
// cases 保存cases,供当前处理流程使用
// cases 用于本次流程后续判断的cases
cases := map[string]string{
"订单号": "order_id",
"OrderID": "order_id",
@@ -173,7 +173,7 @@ func TestNormalizeImportHeader(t *testing.T) {
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := normalizeImportHeader(in); got != want {
t.Errorf("normalizeImportHeader(%q) = %q; want %q", in, got, want)
}
@@ -182,20 +182,20 @@ func TestNormalizeImportHeader(t *testing.T) {
// buildMinimalXLSX 构造一个仅含 sheet1 + sharedStrings 的最小 .xlsx 字节流。
// cell 用 shared string(t="s")引用,与 Excel 默认导出一致。
// buildMinimalXLSX 负责buildMinimalXLSX相关处理。
// buildMinimalXLSX 封装buildMinimalXLSX业务协调。
func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
t.Helper()
// shared 保存shared,供当前处理流程使用
// shared 用于本次流程后续判断的shared
var shared []string
// sharedIdx 保存sharedIdx,供当前处理流程使用
// sharedIdx 用于本次流程后续判断的sharedIdx
sharedIdx := map[string]int{}
// addShared 保存addShared,供当前处理流程使用
// addShared 用于本次流程后续判断的addShared
addShared := func(s string) int {
if // i、ok 保存i、ok,供当前处理流程使用
if // i、ok 用于本次流程后续判断的i、ok
i, ok := sharedIdx[s]; ok {
return i
}
// i 保存i,供当前处理流程使用
// i 用于本次流程后续判断的i
i := len(shared)
shared = append(shared, s)
sharedIdx[s] = i
@@ -210,9 +210,9 @@ func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
fmt.Fprintf(&rowsXML, `<row r="%d">`, r+1)
// c、val 表示当前遍历过程中的c、val
for c, val := range row {
// ref 保存ref,供当前处理流程使用
// ref 用于本次流程后续判断的ref
ref := fmt.Sprintf("%c%d", 'A'+c, r+1)
// idx 保存idx,供当前处理流程使用
// idx 用于本次流程后续判断的idx
idx := addShared(val)
fmt.Fprintf(&rowsXML, `<c r="%s" t="s"><v>%d</v></c>`, ref, idx)
}
@@ -220,7 +220,7 @@ func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
}
rowsXML.WriteString(`</sheetData></worksheet>`)
// sstXML 保存sstXML,供当前处理流程使用
// sstXML 用于本次流程后续判断的sstXML
var sstXML strings.Builder
sstXML.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
// s 表示当前遍历过程中的s
@@ -229,18 +229,18 @@ func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
}
sstXML.WriteString(`</sst>`)
// buf 保存buf,供当前处理流程使用
// buf 用于本次流程后续判断的buf
var buf bytes.Buffer
// zw 保存zw,供当前处理流程使用
// zw 用于本次流程后续判断的zw
zw := zip.NewWriter(&buf)
// must 保存must,供当前处理流程使用
// must 用于本次流程后续判断的must
must := func(name, content string) {
// f、err 保存f、err,供当前处理流程使用
// f、err 用于本次流程后续判断的f、err
f, err := zw.Create(name)
if err != nil {
t.Fatal(err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := f.Write([]byte(content)); err != nil {
t.Fatal(err)
}
@@ -254,35 +254,35 @@ func buildMinimalXLSX(t *testing.T, grid [][]string) []byte {
return buf.Bytes()
}
// TestPublishBatchPathAndZipSafety 负责Test发布批次路径AndZipSafety相关处理。
// TestPublishBatchPathAndZipSafety 封装Test发布批次路径AndZipSafety业务协调。
func TestPublishBatchPathAndZipSafety(t *testing.T) {
// raw 表示当前遍历过程中的原始
for _, raw := range []string{"../secret.png", "/etc/passwd", `..\\secret.png`, ""} {
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := safeZipPath(raw); err == nil {
t.Errorf("safeZipPath(%q) should fail", raw)
}
}
if // got、err 保存got、err,供当前处理流程使用
if // got、err 用于本次流程后续判断的got、err
got, err := safeZipPath("images/a.png"); err != nil || got != filepath.Join("images", "a.png") {
t.Fatalf("safe path = %q, %v", got, err)
}
// dest 保存dest,供当前处理流程使用
// dest 用于本次流程后续判断的dest
dest := t.TempDir()
// buf 保存buf,供当前处理流程使用
// buf 用于本次流程后续判断的buf
var buf bytes.Buffer
// zw 保存zw,供当前处理流程使用
// zw 用于本次流程后续判断的zw
zw := zip.NewWriter(&buf)
// f 保存f,供当前处理流程使用
// f 用于本次流程后续判断的f
f, _ := zw.Create("images/a.png")
_, _ = f.Write([]byte("not-an-image"))
_ = zw.Close()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := extractPublishImagesZip(buf.Bytes(), dest); err != nil {
t.Fatalf("extract non-image: %v", err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := os.Stat(filepath.Join(dest, "images", "a.png")); !os.IsNotExist(err) {
t.Fatal("non-image must not be extracted")
}
@@ -292,15 +292,15 @@ func TestPublishBatchPathAndZipSafety(t *testing.T) {
f, _ = zw.Create("../escape.png")
_, _ = f.Write([]byte("x"))
_ = zw.Close()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := extractPublishImagesZip(buf.Bytes(), dest); err == nil {
t.Fatal("zip traversal should fail")
}
}
// TestPublishBatchHelpers 负责Test发布批次Helpers相关处理。
// TestPublishBatchHelpers 封装Test发布批次Helpers业务协调。
func TestPublishBatchHelpers(t *testing.T) {
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := splitImageRefs("a.png; b.png\nc.png"); len(got) != 3 {
t.Fatalf("splitImageRefs = %#v", got)
}
@@ -310,7 +310,7 @@ func TestPublishBatchHelpers(t *testing.T) {
t.Errorf("parseLooseBool(%q) = false", value)
}
}
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := atoiPublishDefault("2.9", 1); got != 2 {
t.Fatalf("atoiPublishDefault = %d", got)
}
@@ -324,9 +324,9 @@ func TestNormalizePublishCardHeader(t *testing.T) {
}
}
// TestNormalizePublishHeaderCategoryFallbackLabels 负责TestNormalize发布Header分类FallbackLabels相关处理。
// TestNormalizePublishHeaderCategoryFallbackLabels 封装TestNormalize发布Header分类FallbackLabels业务协调。
func TestNormalizePublishHeaderCategoryFallbackLabels(t *testing.T) {
// cases 保存cases,供当前处理流程使用
// cases 用于本次流程后续判断的cases
cases := map[string]string{
"类目ID": "category_id",
"类目名称": "category_name",
@@ -336,14 +336,14 @@ func TestNormalizePublishHeaderCategoryFallbackLabels(t *testing.T) {
}
// input、want 表示当前遍历过程中的input、want
for input, want := range cases {
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := normalizePublishHeader(input); got != want {
t.Fatalf("normalizePublishHeader(%q)=%q want %q", input, got, want)
}
}
}
// TestPublicIPValidation 负责TestPublicIPValidation相关处理。
// TestPublicIPValidation 封装TestPublicIPValidation业务协调。
func TestPublicIPValidation(t *testing.T) {
// raw 表示当前遍历过程中的原始
for _, raw := range []string{"127.0.0.1", "10.0.0.1", "169.254.1.1", "::1"} {
+1 -1
View File
@@ -11,7 +11,7 @@ import (
// mountPasswordLogin 保留历史 API 路径,避免旧前端收到 404。Go 客户端的
// 登录凭证只允许由扫码流程产生;这里永远不会调用 Chromium 密码登录。
// mountPasswordLogin 负责mount密码登录相关处理。
// mountPasswordLogin 封装mount密码登录业务协调。
func (s *Server) mountPasswordLogin(r chi.Router) {
r.Post("/password-login", s.passwordLoginDisabled)
r.Get("/password-login/check/{session_id}", s.passwordLoginDisabled)
@@ -8,17 +8,17 @@ import (
"testing"
)
// TestPasswordLoginAPIsArePermanentlyDisabled 负责Test密码登录APIsArePermanentlyDisabled相关处理。
// TestPasswordLoginAPIsArePermanentlyDisabled 封装Test密码登录APIsArePermanentlyDisabled业务协调。
func TestPasswordLoginAPIsArePermanentlyDisabled(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// authCookie 保存auth登录凭证,供当前处理流程使用
// authCookie 用于本次流程后续判断的auth登录凭证
authCookie := loginHelper(t, h)
// requests 保存请求列表,供当前处理流程使用
// requests 用于本次流程后续判断的请求列表
requests := []*http.Request{
httptest.NewRequest(http.MethodPost, "/password-login", strings.NewReader(`{"account_id":"acc1","account":"u","password":"p"}`)),
httptest.NewRequest(http.MethodGet, "/password-login/check/legacy", nil),
@@ -27,15 +27,15 @@ func TestPasswordLoginAPIsArePermanentlyDisabled(t *testing.T) {
// req 表示当前遍历过程中的req
for _, req := range requests {
req.AddCookie(authCookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotImplemented {
t.Fatalf("%s %s status=%d body=%s", req.Method, req.URL.Path, rec.Code, rec.Body.String())
}
// result 保存结果,供当前处理流程使用
// result 用于本次流程后续判断的结果
var result map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
+111 -111
View File
@@ -25,9 +25,9 @@ import (
// minimalPNG 是一张 1x1 PNG,供发布批次图片 zip 复用。
var minimalPNG = []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
// TestFinalPublishBatchStatus 负责TestFinal发布批次状态相关处理。
// TestFinalPublishBatchStatus 封装TestFinal发布批次状态业务协调。
func TestFinalPublishBatchStatus(t *testing.T) {
// cases 保存cases,供当前处理流程使用
// cases 用于本次流程后续判断的cases
cases := []struct {
name string
in itemapp.BatchInfo
@@ -40,7 +40,7 @@ func TestFinalPublishBatchStatus(t *testing.T) {
// tt 表示当前遍历过程中的tt
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := finalPublishBatchStatus(&tt.in); got != tt.want {
t.Fatalf("got %q want %q", got, tt.want)
}
@@ -48,9 +48,9 @@ func TestFinalPublishBatchStatus(t *testing.T) {
}
}
// TestPublishBatchFailurePreservesUncertainRemoteWarningWhenCanceled 负责Test发布批次FailurePreservesUncertainRemoteWarningWhenCanceled相关处理。
// TestPublishBatchFailurePreservesUncertainRemoteWarningWhenCanceled 封装Test发布批次FailurePreservesUncertainRemoteWarningWhenCanceled业务协调。
func TestPublishBatchFailurePreservesUncertainRemoteWarningWhenCanceled(t *testing.T) {
// message、kind 保存message、kind,供当前处理流程使用
// message、kind 用于本次流程后续判断的message、kind
message, kind := publishBatchFailure(&uncertainRemotePublishError{err: context.Canceled}, "canceling")
if kind != "uncertain_remote" || !strings.Contains(message, "任务已取消") ||
!strings.Contains(message, "禁止自动重试") || !strings.Contains(message, "人工核对") {
@@ -65,11 +65,11 @@ func TestPublishBatchFailurePreservesUncertainRemoteWarningWhenCanceled(t *testi
// buildImageZip 构造含一张图片的 zip 字节流。
func buildImageZip(t *testing.T) []byte {
t.Helper()
// buf 保存buf,供当前处理流程使用
// buf 用于本次流程后续判断的buf
var buf bytes.Buffer
// zw 保存zw,供当前处理流程使用
// zw 用于本次流程后续判断的zw
zw := zip.NewWriter(&buf)
// f 保存f,供当前处理流程使用
// f 用于本次流程后续判断的f
f, _ := zw.Create("img/a.png")
f.Write(minimalPNG)
_ = zw.Close()
@@ -79,33 +79,33 @@ func buildImageZip(t *testing.T) []byte {
// previewPublishBatch 构造一个预检批次(单行商品 + 1 张图片),返回 preview_id。
func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) string {
t.Helper()
// buf 保存buf,供当前处理流程使用
// buf 用于本次流程后续判断的buf
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
// mw 用于本次流程后续判断的mw
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
_ = mw.WriteField("fallback_category_id", "5001")
_ = mw.WriteField("fallback_category_name", "虚拟商品")
_ = mw.WriteField("fallback_channel_category_id", "6001")
// csvField 保存csv字段,供当前处理流程使用
// csvField 用于本次流程后续判断的csv字段
csvField, _ := mw.CreateFormFile("file", "products.csv")
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
// zipField 保存zip字段,供当前处理流程使用
// zipField 用于本次流程后续判断的zip字段
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
zipField.Write(buildImageZip(t))
_ = mw.Close()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["valid"].(float64) != 1 {
@@ -114,36 +114,36 @@ func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) stri
return res["preview_id"].(string)
}
// previewTwoRowPublishBatch 负责previewTwoRow发布批次相关处理。
// previewTwoRowPublishBatch 封装previewTwoRow发布批次业务协调。
func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) string {
t.Helper()
// buf 保存buf,供当前处理流程使用
// buf 用于本次流程后续判断的buf
var buf bytes.Buffer
// mw 保存mw,供当前处理流程使用
// mw 用于本次流程后续判断的mw
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
_ = mw.WriteField("fallback_category_id", "5001")
_ = mw.WriteField("fallback_category_name", "虚拟商品")
_ = mw.WriteField("fallback_channel_category_id", "6001")
// csvField 保存csv字段,供当前处理流程使用
// csvField 用于本次流程后续判断的csv字段
csvField, _ := mw.CreateFormFile("file", "products.csv")
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\nacc1,商品B,13.50,5,img/a.png\n"))
// zipField 保存zip字段,供当前处理流程使用
// zipField 用于本次流程后续判断的zip字段
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
zipField.Write(buildImageZip(t))
_ = mw.Close()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["valid"].(float64) != 2 {
@@ -154,9 +154,9 @@ func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie
// TestRunItemPublishBatch_FailureMarksRowFailed 启动批次后,mock mtop 对发布请求返回失败,
// 验证应用层批量 worker 把远端发布失败的行标记为 failed。
// TestRunItemPublishBatch_FailureMarksRowFailed 负责Test运行商品发布批次FailureMarksRow失败相关处理。
// TestRunItemPublishBatch_FailureMarksRowFailed 封装Test运行商品发布批次FailureMarksRow失败业务协调。
func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// 注入 mock mtop:所有请求返回非成功 ret(触发 PublishError)。
@@ -169,17 +169,17 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
}, nil
}))
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := previewPublishBatch(t, h, cookie)
// 启动批次。
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
startReq.AddCookie(cookie)
// startRec 保存开始Rec,供当前处理流程使用
// startRec 用于本次流程后续判断的开始Rec
startRec := httptest.NewRecorder()
h.ServeHTTP(startRec, startReq)
if startRec.Code != 200 {
@@ -188,20 +188,20 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
// 轮询批次状态,等待 running 结束(最多 5 秒)。
deadline := time.Now().Add(5 * time.Second)
// status 保存状态,供当前处理流程使用
// status 用于本次流程后续判断的状态
var status any
for time.Now().Before(deadline) {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
time.Sleep(50 * time.Millisecond)
continue
}
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
status = got["status"]
@@ -217,10 +217,10 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
// 验证至少一行被标记 failed(或 completed)。
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["status"] != "failed" {
@@ -229,21 +229,21 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
if got["failed"] != float64(1) {
t.Fatalf("failed=%v want 1 body=%+v", got["failed"], got)
}
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows, _ := got["rows"].([]any)
if len(rows) != 1 {
t.Fatalf("rows=%+v want 1 row", got["rows"])
}
// row 保存row,供当前处理流程使用
// row 用于本次流程后续判断的row
row, _ := rows[0].(map[string]any)
if row["status"] != "failed" || row["error_message"] == "" {
t.Fatalf("row should be failed with error message: %+v", row)
}
}
// TestCancelItemPublishBatchMarksUnfinishedRowsFailed 负责Test取消商品发布批次MarksUnfinishedRows失败相关处理。
// TestCancelItemPublishBatchMarksUnfinishedRowsFailed 封装Test取消商品发布批次MarksUnfinishedRows失败业务协调。
func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
@@ -260,42 +260,42 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
}, nil
}))
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := previewTwoRowPublishBatch(t, h, cookie)
// startReq 保存开始Req,供当前处理流程使用
// startReq 用于本次流程后续判断的开始Req
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
startReq.AddCookie(cookie)
// startRec 保存开始Rec,供当前处理流程使用
// startRec 用于本次流程后续判断的开始Rec
startRec := httptest.NewRecorder()
h.ServeHTTP(startRec, startReq)
if startRec.Code != http.StatusOK {
t.Fatalf("start status=%d body=%s", startRec.Code, startRec.Body.String())
}
// cancelReq 保存取消Req,供当前处理流程使用
// cancelReq 用于本次流程后续判断的取消Req
cancelReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches/"+batchID+"/cancel", nil)
cancelReq.AddCookie(cookie)
// cancelRec 保存取消Rec,供当前处理流程使用
// cancelRec 用于本次流程后续判断的取消Rec
cancelRec := httptest.NewRecorder()
h.ServeHTTP(cancelRec, cancelReq)
if cancelRec.Code != http.StatusOK {
t.Fatalf("cancel status=%d body=%s", cancelRec.Code, cancelRec.Body.String())
}
// deadline 保存deadline,供当前处理流程使用
// deadline 用于本次流程后续判断的deadline
deadline := time.Now().Add(2 * time.Second)
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
for time.Now().Before(deadline) {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -316,7 +316,7 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
if got["failed"] != got["total"] {
t.Fatalf("取消后未完成行应全部失败: total=%v failed=%v body=%+v", got["total"], got["failed"], got)
}
// batch、err 保存batch、err,供当前处理流程使用
// batch、err 用于本次流程后续判断的batch、err
batch, err := store.PublishBatches.Get(context.Background(), 1, batchID)
if err != nil {
t.Fatal(err)
@@ -324,7 +324,7 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
if strings.TrimSpace(batch.UploadDir) == "" {
t.Fatal("取消运行中的任务后应保留 upload_dir 供失败项重试")
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := os.Stat(batch.UploadDir); err != nil {
t.Fatalf("取消运行中的任务后应保留图片目录: %v", err)
}
@@ -332,16 +332,16 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
// TestRunItemPublishBatch_Success 启动批次,mock mtop 全程返回 SUCCESS,验证行最终成功。
func TestRunItemPublishBatch_Success(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// publishedCategory 保存published分类,供当前处理流程使用
// publishedCategory 用于本次流程后续判断的published分类
var publishedCategory map[string]any
// 所有 mtop 调用返回 SUCCESS;发布调用返回 itemId。
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
// u 保存u,供当前处理流程使用
// u 用于本次流程后续判断的u
u := req.URL.String()
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"ret":["SUCCESS::调用成功"],"data":{}}`
switch {
case strings.Contains(u, "stream-upload.goofish.com"):
@@ -349,11 +349,11 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
body = `{"ret":["SUCCESS::调用成功"],"data":{}}`
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
// rawBody 保存原始请求体,供当前处理流程使用
// rawBody 用于本次流程后续判断的原始请求体
rawBody, _ := io.ReadAll(req.Body)
// form 保存表单,供当前处理流程使用
// form 用于本次流程后续判断的表单
form, _ := url.ParseQuery(string(rawBody))
// publishData 保存发布数据,供当前处理流程使用
// publishData 用于本次流程后续判断的发布数据
var publishData map[string]any
_ = json.Unmarshal([]byte(form.Get("data")), &publishData)
publishedCategory, _ = publishData["itemCatDTO"].(map[string]any)
@@ -367,17 +367,17 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
}, nil
}))
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := previewPublishBatch(t, h, cookie)
// startReq 保存开始Req,供当前处理流程使用
// startReq 用于本次流程后续判断的开始Req
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
startReq.AddCookie(cookie)
// startRec 保存开始Rec,供当前处理流程使用
// startRec 用于本次流程后续判断的开始Rec
startRec := httptest.NewRecorder()
h.ServeHTTP(startRec, startReq)
if startRec.Code != 200 {
@@ -386,20 +386,20 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
// 轮询至完成。
deadline := time.Now().Add(8 * time.Second)
// status 保存状态,供当前处理流程使用
// status 用于本次流程后续判断的状态
var status any
for time.Now().Before(deadline) {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
time.Sleep(50 * time.Millisecond)
continue
}
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
status = got["status"]
@@ -411,16 +411,16 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
if status == "running" {
t.Fatal("批次应在 8s 内完成")
}
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("detail status=%d body=%s", rec.Code, rec.Body.String())
}
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["status"] != "completed" {
@@ -429,12 +429,12 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
if got["success"] != float64(1) {
t.Fatalf("success=%v want 1 body=%+v", got["success"], got)
}
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows, _ := got["rows"].([]any)
if len(rows) != 1 {
t.Fatalf("rows=%+v want 1 row", got["rows"])
}
// row 保存row,供当前处理流程使用
// row 用于本次流程后续判断的row
row, _ := rows[0].(map[string]any)
if row["status"] != "success" || row["item_id"] == "" {
t.Fatalf("row should be success with item_id: %+v", row)
@@ -444,63 +444,63 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
}
}
// TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain 负责Test发布批次重试ResumesSavedRemote结果WithoutPublishingAgain相关处理。
// TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain 封装Test发布批次重试ResumesSavedRemote结果WithoutPublishingAgain业务协调。
func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// admin、err 保存admin、err,供当前处理流程使用
// admin、err 用于本次流程后续判断的admin、err
admin, err := store.Users.GetByUsername(ctx, "admin")
if err != nil {
t.Fatal(err)
}
// batch 保存批次,供当前处理流程使用
// batch 用于本次流程后续判断的批次
batch := &db.ItemPublishBatch{
ID: "resume-remote", UserID: admin.ID, DefaultCookieID: "acc1", Filename: "resume.csv", Status: "pending",
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.PublishBatches.Create(ctx, batch, []db.ItemPublishBatchRow{{
BatchID: batch.ID, RowNo: 1, CookieID: "acc1", Title: "已发布商品", Description: "详情",
Price: "12.50", Quantity: 1, PostageMode: "free", AutomationJSON: `{}`,
}}); err != nil {
t.Fatal(err)
}
// lease 保存lease,供当前处理流程使用
// lease 用于本次流程后续判断的lease
lease := time.Now().UTC().Add(time.Minute).Unix()
if // claimed、err 保存claimed、err,供当前处理流程使用
if // claimed、err 用于本次流程后续判断的claimed、err
claimed, err := store.PublishBatches.ClaimBatch(ctx, batch.ID, "worker-1", lease); err != nil || !claimed {
t.Fatalf("claim first worker: claimed=%v err=%v", claimed, err)
}
// rows、err 保存rows、err,供当前处理流程使用
// rows、err 用于本次流程后续判断的rows、err
rows, err := store.PublishBatches.Rows(ctx, batch.ID)
if err != nil || len(rows) != 1 {
t.Fatalf("rows=%+v err=%v", rows, err)
}
// rowID 保存rowID,供当前处理流程使用
// rowID 用于本次流程后续判断的rowID
rowID := rows[0].ID
if // claimed、err 保存claimed、err,供当前处理流程使用
if // claimed、err 用于本次流程后续判断的claimed、err
claimed, err := store.PublishBatches.ClaimRow(ctx, rowID, "worker-1"); err != nil || !claimed {
t.Fatalf("claim row: claimed=%v err=%v", claimed, err)
}
if // saved、err 保存saved、err,供当前处理流程使用
if // saved、err 用于本次流程后续判断的saved、err
saved, err := store.PublishBatches.SaveClaimedRemoteResult(ctx, rowID, "worker-1", "remote-123", "https://x/item/remote-123", `{"remote":true}`); err != nil || !saved {
t.Fatalf("save remote result: saved=%v err=%v", saved, err)
}
if // marked、err 保存marked、err,供当前处理流程使用
if // marked、err 用于本次流程后续判断的marked、err
marked, err := store.PublishBatches.MarkClaimedRowFailed(ctx, rowID, "worker-1", "local database unavailable", "post_publish"); err != nil || !marked {
t.Fatalf("mark post publish failure: marked=%v err=%v", marked, err)
}
if // finished、err 保存finished、err,供当前处理流程使用
if // finished、err 用于本次流程后续判断的finished、err
finished, err := store.PublishBatches.FinishBatchStatus(ctx, batch.ID, "worker-1", "failed"); err != nil || !finished {
t.Fatalf("finish first batch: finished=%v err=%v", finished, err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.PublishBatches.ResetFailed(ctx, batch.ID); err != nil {
t.Fatal(err)
}
if // claimed、err 保存claimed、err,供当前处理流程使用
if // claimed、err 用于本次流程后续判断的claimed、err
claimed, err := store.PublishBatches.ClaimBatch(ctx, batch.ID, "worker-2", lease); err != nil || !claimed {
t.Fatalf("claim retry worker: claimed=%v err=%v", claimed, err)
}
@@ -508,13 +508,13 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test
if rows[0].ItemID != "remote-123" || rows[0].Status != "pending" {
t.Fatalf("retry checkpoint lost: %+v", rows[0])
}
if // claimed、err 保存claimed、err,供当前处理流程使用
if // claimed、err 用于本次流程后续判断的claimed、err
claimed, err := store.PublishBatches.ClaimRow(ctx, rowID, "worker-2"); err != nil || !claimed {
t.Fatalf("retry claim row: claimed=%v err=%v", claimed, err)
}
// remoteCalls 保存remoteCalls,供当前处理流程使用
// remoteCalls 用于本次流程后续判断的remoteCalls
remoteCalls := 0
// client 保存client,供当前处理流程使用
// client 用于本次流程后续判断的client
client := withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
remoteCalls++
return nil, context.Canceled
@@ -544,18 +544,18 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test
}
}
// TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow 负责Test发布批次RecoveryAutomaticallyResumesInterruptedRow相关处理。
// TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow 封装Test发布批次RecoveryAutomaticallyResumesInterruptedRow业务协调。
func TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// admin 保存admin,供当前处理流程使用
// admin 用于本次流程后续判断的admin
admin, _ := store.Users.GetByUsername(ctx, "admin")
// batchID 保存批次ID,供当前处理流程使用
// batchID 用于本次流程后续判断的批次ID
batchID := "auto-recover-batch"
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{
ID: batchID, UserID: admin.ID, DefaultCookieID: "acc1", Filename: "recover.csv", Status: "failed",
}, []db.ItemPublishBatchRow{{
@@ -569,13 +569,13 @@ func TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow(t *testing.T) {
if err := srv.applications.itemBatchCoordinator.RunRecovery(ctx); err != nil {
t.Fatalf("批量恢复扫描: %v", err)
}
// deadline 保存deadline,供当前处理流程使用
// deadline 用于本次流程后续判断的deadline
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
// batch、err 保存batch、err,供当前处理流程使用
// batch、err 用于本次流程后续判断的batch、err
batch, err := store.PublishBatches.Get(ctx, admin.ID, batchID)
if err == nil && batch.Status == "completed" {
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows, _ := store.PublishBatches.Rows(ctx, batchID)
if len(rows) != 1 || rows[0].Status != "success" || rows[0].ItemID != "remote-recovered" {
t.Fatalf("rows=%+v", rows)
@@ -584,38 +584,38 @@ func TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow(t *testing.T) {
}
time.Sleep(20 * time.Millisecond)
}
// batch 保存批次,供当前处理流程使用
// batch 用于本次流程后续判断的批次
batch, _ := store.PublishBatches.Get(ctx, admin.ID, batchID)
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows, _ := store.PublishBatches.Rows(ctx, batchID)
t.Fatalf("batch=%+v rows=%+v", batch, rows)
}
// TestCreatePublishAutomationRules 覆盖自动化规则创建(通过成功发布路径间接覆盖)。
// 这里直接验证 runItemPublishBatch 在成功路径上调用了 createPublishAutomationRules。
// TestCreatePublishAutomationRules 负责TestCreate发布自动化规则列表相关处理。
// TestCreatePublishAutomationRules 封装TestCreate发布自动化规则列表业务协调。
func TestCreatePublishAutomationRules(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
// 预置一个自动化规则配置的批次行,直接调 createPublishAutomationRules 验证不 panic + 写规则。
// 先建一个卡密组供规则引用。
// admin 保存admin,供当前处理流程使用
// admin 用于本次流程后续判断的admin
admin, _ := store.Users.GetByUsername(ctx, "admin")
// cardID 保存卡密ID,供当前处理流程使用
// cardID 用于本次流程后续判断的卡密ID
cardID, _ := store.Cards.Create(ctx, &db.CardFull{Name: "卡", Type: "text", TextContent: "K", Enabled: true, UserID: admin.ID})
// automationJSON 保存自动化JSON,供当前处理流程使用
// automationJSON 用于本次流程后续判断的自动化JSON
automationJSON := `{"paid_delivery":{"enabled":true,"actions":[{"card_id":` + itoa(cardID) + `,"delivery_count":1,"delay_seconds":23}]}}`
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := srv.createPublishAutomationRules(ctx, admin.ID, itemapp.BatchRow{
CookieID: "acc1", Title: "商品A", AutomationJSON: automationJSON,
}, &itemapp.BatchPublishResult{ItemID: "published-delay-item", Title: "商品A"}); err != nil {
t.Fatal(err)
}
// rules、err 保存rules、err,供当前处理流程使用
// rules、err 用于本次流程后续判断的rules、err
rules, err := store.Automation.Match(ctx, "acc1", "published-delay-item", automation.TriggerOrderPaid)
if err != nil || len(rules) != 1 {
t.Fatalf("rules=%+v err=%v", rules, err)
File diff suppressed because it is too large. Load diff
+31 -31
View File
@@ -13,7 +13,7 @@ import (
"xianyu-go/internal/auth"
)
// qrLoginGenerateTimeout 保存qr登录GenerateTimeout,供当前处理流程使用
// qrLoginGenerateTimeout 用于本次流程后续判断的qr登录GenerateTimeout
const qrLoginGenerateTimeout = 2 * time.Minute
// mountQRLoginReal 扫码登录端点(纯 HTTP,不需要浏览器)。
@@ -26,7 +26,7 @@ func (s *Server) mountQRLoginReal(r chi.Router) {
// generateQRLogin 生成扫码登录二维码。
func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
@@ -35,7 +35,7 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
s.cleanupQRLoginSessions()
// 风控后的闲鱼匿名 token 接口偶尔会明显变慢。二维码生成需要连续完成
// token、登录参数和二维码请求,不能沿用前端通用接口的短超时。
// generateCtx、cancel 保存generateCtx、cancel,供当前处理流程使用
// generateCtx、cancel 用于本次流程后续判断的generateCtx、cancel
generateCtx, cancel := context.WithTimeout(r.Context(), qrLoginGenerateTimeout)
defer cancel()
// qrService 是通过显式平台依赖边界取得的二维码服务;为空时拒绝执行平台调用。
@@ -44,10 +44,10 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
return
}
// sessionID、qrCodeURL、err 保存会话ID、qrCodeURL、err,供当前处理流程使用
// sessionID、qrCodeURL、err 用于本次流程后续判断的会话ID、qrCodeURL、err
sessionID, qrCodeURL, err := qrService.GenerateQRCode(generateCtx)
if err != nil {
// message 保存消息,供当前处理流程使用
// message 用于本次流程后续判断的消息
message := "生成二维码失败: " + err.Error()
switch {
case errors.Is(err, context.Canceled):
@@ -81,7 +81,7 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
// checkQRLoginStatus 检查扫码登录状态。
func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) {
// sessionID 保存会话ID,供当前处理流程使用
// sessionID 用于本次流程后续判断的会话ID
sessionID := chi.URLParam(r, "session_id")
if sessionID == "" {
writeErr(w, http.StatusBadRequest, "缺少 session_id")
@@ -96,14 +96,14 @@ func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
return
}
// result 保存结果,供当前处理流程使用
// result 用于本次流程后续判断的结果
result := publicQRStatus(qrService.GetSessionStatus(sessionID))
writeJSON(w, http.StatusOK, result)
}
// checkQRLoginStatusAndPersist 兼容上游 /status 语义:扫码成功后由后端幂等保存账号。
func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Request) {
// sessionID 保存会话ID,供当前处理流程使用
// sessionID 用于本次流程后续判断的会话ID
sessionID := chi.URLParam(r, "session_id")
if sessionID == "" {
writeErr(w, http.StatusBadRequest, "缺少 session_id")
@@ -118,19 +118,19 @@ func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Req
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
return
}
// result 保存结果,供当前处理流程使用
// result 用于本次流程后续判断的结果
result := cloneQRStatus(qrService.GetSessionStatus(sessionID))
if qrStatus(result) != "success" {
writeJSON(w, http.StatusOK, publicQRStatus(result))
return
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// persisted、err 保存persisted、err,供当前处理流程使用
// persisted、err 用于本次流程后续判断的persisted、err
persisted, err := s.accountLoginApplication().PersistQRLoginSuccess(r.Context(), sess.UserID, sessionID, result, "")
if err != nil {
if s.Logger != nil {
@@ -150,7 +150,7 @@ func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Req
// completeQRVerification 用户完成风控验证后调用,提取真实 cookie 并入库。
func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request) {
// sessionID 保存会话ID,供当前处理流程使用
// sessionID 用于本次流程后续判断的会话ID
sessionID := chi.URLParam(r, "session_id")
if sessionID == "" {
writeErr(w, http.StatusBadRequest, "缺少 session_id")
@@ -165,7 +165,7 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusInternalServerError, "二维码服务未初始化")
return
}
// cookies、unb、err 保存cookies、unb、err,供当前处理流程使用
// cookies、unb、err 用于本次流程后续判断的cookies、unb、err
cookies, unb, err := qrService.CompleteVerification(r.Context(), sessionID)
if err != nil {
s.Logger.Error("验证完成处理失败", "err", err)
@@ -178,7 +178,7 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
// req 保存具名扫码验证完成请求。
var req qrVerificationRequestDTO
if r.Body != nil && r.ContentLength != 0 {
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -193,28 +193,28 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
"", map[string]any{"scanned_account_id": unb})
return
}
// resp 保存resp,供当前处理流程使用
// resp 用于本次流程后续判断的resp
resp := qrLoginVerificationResponse{
Success: true, UNB: unb,
// 验证完成响应保留平台账号标识,兼容旧客户端。
}
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if sess != nil {
// result 保存结果,供当前处理流程使用
// result 用于本次流程后续判断的结果
result := map[string]any{
"status": "success",
"cookies": cookies,
"unb": unb,
}
if // current 保存current,供当前处理流程使用
if // current 用于本次流程后续判断的current
current := qrService.GetSessionStatus(sessionID); current != nil {
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
if // snapshot、ok 用于本次流程后续判断的snapshot、ok
snapshot, ok := current["cookie_snapshot"]; ok {
result["cookie_snapshot"] = snapshot
}
}
// persisted、persistErr 保存persisted、persistErr,供当前处理流程使用
// persisted、persistErr 用于本次流程后续判断的persisted、persistErr
persisted, persistErr := s.accountLoginApplication().PersistQRLoginSuccess(r.Context(), sess.UserID, sessionID, result, req.TargetAccountID)
if persistErr != nil {
if s.Logger != nil {
@@ -231,9 +231,9 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, resp)
}
// requireQRSessionOwner 负责requireQR会话所有者相关处理。
// requireQRSessionOwner 封装requireQR会话所有者业务协调。
func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, sessionID string) bool {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
@@ -259,7 +259,7 @@ func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, s
return true
}
// cleanupQRLoginSessions 负责cleanupQR登录Sessions相关处理。
// cleanupQRLoginSessions 封装cleanupQR登录Sessions业务协调。
func (s *Server) cleanupQRLoginSessions() {
// qrSessions 提供应用层扫码会话过期清理能力。
qrSessions := s.accountLoginApplication().qrSessions
@@ -268,7 +268,7 @@ func (s *Server) cleanupQRLoginSessions() {
}
// expired 保存应用层报告的过期扫码会话标识。
expired := qrSessions.Cleanup(time.Now().UTC())
if // cleaner、ok 保存cleaner、ok,供当前处理流程使用
if // cleaner、ok 用于本次流程后续判断的cleaner、ok
cleaner, ok := s.qrLoginService().(interface{ DeleteSession(string) }); ok {
// id 表示当前遍历过程中的标识
for _, id := range expired {
@@ -277,9 +277,9 @@ func (s *Server) cleanupQRLoginSessions() {
}
}
// cloneQRStatus 负责cloneQR状态相关处理。
// cloneQRStatus 封装cloneQR状态业务协调。
func cloneQRStatus(src map[string]any) map[string]any {
// dst 保存dst,供当前处理流程使用
// dst 用于本次流程后续判断的dst
dst := make(map[string]any, len(src))
// k、v 表示当前遍历过程中的k、v
for k, v := range src {
@@ -290,7 +290,7 @@ func cloneQRStatus(src map[string]any) map[string]any {
// publicQRStatus 返回可暴露给浏览器的扫码状态。闲鱼 Cookie 只在服务端持久化,
// 永远不进入前端、浏览器日志或代理响应。
// publicQRStatus 负责publicQR状态相关处理。
// publicQRStatus 封装publicQR状态业务协调。
func publicQRStatus(src map[string]any) qrLoginStatusResponse {
// status 保存允许传输到浏览器的扫码状态;Cookie 和快照字段刻意不映射。
status := qrLoginStatusResponse{Status: qrStatus(src)}
@@ -317,16 +317,16 @@ func publicQRStatus(src map[string]any) qrLoginStatusResponse {
return status
}
// qrStatus 负责qr状态相关处理。
// qrStatus 封装qr状态业务协调。
func qrStatus(result map[string]any) string {
// status 保存状态,供当前处理流程使用
// status 用于本次流程后续判断的状态
status, _ := result["status"].(string)
return status
}
// qrString 负责qrString相关处理。
// qrString 封装qrString业务协调。
func qrString(result map[string]any, key string) string {
// value 保存值,供当前处理流程使用
// value 用于本次流程后续判断的值
value, _ := result[key].(string)
return strings.TrimSpace(value)
}
+157 -157
View File
@@ -15,7 +15,7 @@ import (
"xianyu-go/internal/xianyu/cookierefresh"
)
// fakeQRLoginService 保存fakeQR登录Service,供当前处理流程使用
// fakeQRLoginService 用于本次流程后续判断的fakeQR登录Service
type fakeQRLoginService struct {
status map[string]any
generateErr error
@@ -25,7 +25,7 @@ type fakeQRLoginService struct {
completeErr error
}
// GenerateQRCode 负责GenerateQRCode相关处理。
// GenerateQRCode 封装GenerateQRCode业务协调。
func (f *fakeQRLoginService) GenerateQRCode(ctx context.Context) (string, string, error) {
f.generateDeadline, _ = ctx.Deadline()
if f.generateErr != nil {
@@ -39,20 +39,20 @@ func (f *fakeQRLoginService) GetSessionStatus(sessionID string) map[string]any {
if sessionID == "no-such-session" {
return map[string]any{"status": "not_found"}
}
// out 保存out,供当前处理流程使用
// out 用于本次流程后续判断的out
out := make(map[string]any, len(f.status)+1)
// k、v 表示当前遍历过程中的k、v
for k, v := range f.status {
out[k] = v
}
if // ok 保存ok,供当前处理流程使用
if // ok 用于本次流程后续判断的ok
_, ok := out["session_id"]; !ok {
out["session_id"] = sessionID
}
return out
}
// CompleteVerification 负责CompleteVerification相关处理。
// CompleteVerification 封装CompleteVerification业务协调。
func (f *fakeQRLoginService) CompleteVerification(context.Context, string) (string, string, error) {
if f.completeErr != nil {
return "", "", f.completeErr
@@ -62,80 +62,80 @@ func (f *fakeQRLoginService) CompleteVerification(context.Context, string) (stri
// TestGenerateQRLogin 生成扫码登录二维码。
func TestGenerateQRLogin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// qr 保存qr,供当前处理流程使用
// qr 用于本次流程后续判断的qr
qr := &fakeQRLoginService{}
srv.QRLogin = qr
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != true || res["session_id"] == nil || res["session_id"] == "" {
t.Fatalf("生成二维码响应异常: %+v", res)
}
// remaining 保存remaining,供当前处理流程使用
// remaining 用于本次流程后续判断的remaining
remaining := time.Until(qr.generateDeadline)
if remaining < qrLoginGenerateTimeout-time.Second || remaining > qrLoginGenerateTimeout {
t.Fatalf("二维码生成超时窗口=%v want≈%v", remaining, qrLoginGenerateTimeout)
}
}
// TestQRLoginSessionCannotBeReadByAnotherUser 负责TestQR登录会话CannotBeReadByAnother用户相关处理。
// TestQRLoginSessionCannotBeReadByAnotherUser 封装TestQR登录会话CannotBeReadByAnother用户业务协调。
func TestQRLoginSessionCannotBeReadByAnotherUser(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
if // ok、err 保存ok、err,供当前处理流程使用
if // ok、err 用于本次流程后续判断的ok、err
ok, err := store.Users.Create(context.Background(), "member", "[email protected]", "memberpw"); err != nil || !ok {
t.Fatalf("create member: ok=%v err=%v", ok, err)
}
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "waiting"}}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// adminCookie 保存admin登录凭证,供当前处理流程使用
// adminCookie 用于本次流程后续判断的admin登录凭证
adminCookie := loginHelper(t, h)
// memberCookie 保存member登录凭证,供当前处理流程使用
// memberCookie 用于本次流程后续判断的member登录凭证
memberCookie := loginAsHelper(t, h, "member", "memberpw")
// generateReq 保存generateReq,供当前处理流程使用
// generateReq 用于本次流程后续判断的generateReq
generateReq := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil)
generateReq.AddCookie(adminCookie)
// generateRec 保存generateRec,供当前处理流程使用
// generateRec 用于本次流程后续判断的generateRec
generateRec := httptest.NewRecorder()
h.ServeHTTP(generateRec, generateReq)
if generateRec.Code != http.StatusOK {
t.Fatalf("generate status=%d body=%s", generateRec.Code, generateRec.Body.String())
}
// memberReq 保存memberReq,供当前处理流程使用
// memberReq 用于本次流程后续判断的memberReq
memberReq := httptest.NewRequest(http.MethodGet, "/qr-login/check/qr-session", nil)
memberReq.AddCookie(memberCookie)
// memberRec 保存memberRec,供当前处理流程使用
// memberRec 用于本次流程后续判断的memberRec
memberRec := httptest.NewRecorder()
h.ServeHTTP(memberRec, memberReq)
if memberRec.Code != http.StatusNotFound {
t.Fatalf("cross-user QR session read status=%d body=%s", memberRec.Code, memberRec.Body.String())
}
// adminReq 保存adminReq,供当前处理流程使用
// adminReq 用于本次流程后续判断的adminReq
adminReq := httptest.NewRequest(http.MethodGet, "/qr-login/check/qr-session", nil)
adminReq.AddCookie(adminCookie)
// adminRec 保存adminRec,供当前处理流程使用
// adminRec 用于本次流程后续判断的adminRec
adminRec := httptest.NewRecorder()
h.ServeHTTP(adminRec, adminReq)
if adminRec.Code != http.StatusOK {
@@ -143,9 +143,9 @@ func TestQRLoginSessionCannotBeReadByAnotherUser(t *testing.T) {
}
}
// TestQRLoginStatusNeverExposesCookies 负责TestQR登录状态NeverExposesCookies相关处理。
// TestQRLoginStatusNeverExposesCookies 封装TestQR登录状态NeverExposesCookies业务协调。
func TestQRLoginStatusNeverExposesCookies(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
@@ -154,56 +154,56 @@ func TestQRLoginStatusNeverExposesCookies(t *testing.T) {
"cookie_snapshot": []cookierefresh.BrowserCookie{{Name: "secret", Value: "value", Domain: ".goofish.com", Path: "/"}},
}}
ownQRSession(t, srv, store, "redacted")
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// path 表示当前遍历过程中的路径
for _, path := range []string{"/qr-login/check/redacted", "/qr-login/status/redacted"} {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("%s status=%d body=%s", path, rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode %s: %v", path, err)
}
if // exists 保存exists,供当前处理流程使用
if // exists 用于本次流程后续判断的exists
_, exists := res["cookies"]; exists {
t.Fatalf("%s must redact cookies: %+v", path, res)
}
if // exists 保存exists,供当前处理流程使用
if // exists 用于本次流程后续判断的exists
_, exists := res["cookie_snapshot"]; exists {
t.Fatalf("%s must redact cookie snapshot: %+v", path, res)
}
}
}
// TestQRLoginSessionExpiresWithoutAnotherGenerateRequest 负责TestQR登录会话ExpiresWithoutAnotherGenerate请求相关处理。
// TestQRLoginSessionExpiresWithoutAnotherGenerateRequest 封装TestQR登录会话ExpiresWithoutAnotherGenerate请求业务协调。
func TestQRLoginSessionExpiresWithoutAnotherGenerateRequest(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "waiting"}}
// admin 保存admin,供当前处理流程使用
// admin 用于本次流程后续判断的admin
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
srv.accountLoginApplication().qrSessions.Register("expired-session", admin.ID, time.Now().UTC().Add(-31*time.Minute))
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/qr-login/check/expired-session", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -213,21 +213,21 @@ func TestQRLoginSessionExpiresWithoutAnotherGenerateRequest(t *testing.T) {
// TestCheckQRLoginStatusEmptySession 缺 session_id 400。
func TestCheckQRLoginStatusEmptySession(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// chi 路由 /qr-login/check/{session_id};空 session 走不到 handler(404)。
// 用一个不存在的 session 验证不 panic。
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/qr-login/check/no-such-session", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -237,19 +237,19 @@ func TestCheckQRLoginStatusEmptySession(t *testing.T) {
// TestCompleteQRVerificationBadSession 不存在的 session 应返回失败响应(不 panic)。
func TestCompleteQRVerificationBadSession(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{completeErr: errors.New("会话不存在")}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/no-such-session", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -257,10 +257,10 @@ func TestCompleteQRVerificationBadSession(t *testing.T) {
}
}
// ownQRSession 负责ownQR会话相关处理。
// ownQRSession 封装ownQR会话业务协调。
func ownQRSession(t *testing.T, srv *Server, store *db.Store, sessionID string) {
t.Helper()
// admin、err 保存admin、err,供当前处理流程使用
// admin、err 用于本次流程后续判断的admin、err
admin, err := store.Users.GetByUsername(context.Background(), "admin")
if err != nil {
t.Fatalf("GetByUsername admin: %v", err)
@@ -268,9 +268,9 @@ func ownQRSession(t *testing.T, srv *Server, store *db.Store, sessionID string)
srv.accountLoginApplication().qrSessions.Register(sessionID, admin.ID, time.Now().UTC())
}
// TestQRLoginStatusPersistsSuccessIdempotently 负责TestQR登录状态PersistsSuccessIdempotently相关处理。
// TestQRLoginStatusPersistsSuccessIdempotently 封装TestQR登录状态PersistsSuccessIdempotently业务协调。
func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
@@ -283,30 +283,30 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
{Name: "_m_h5_tk", Value: "qr-token", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
},
}}
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
if // snapshot、ok 用于本次流程后续判断的snapshot、ok
snapshot, ok := adapter.CookieSnapshotsFromResult(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 {
t.Fatalf("测试扫码 Cookie 快照异常: ok=%v snapshot=%+v", ok, snapshot)
}
ownQRSession(t, srv, store, "s1")
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
for // i 保存i,供当前处理流程使用
for // i 用于本次流程后续判断的i
i := 0; i < 2; i++ {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/qr-login/status/s1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode response: %v", err)
}
@@ -315,7 +315,7 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
}
}
// d、err 保存d、err,供当前处理流程使用
// d、err 用于本次流程后续判断的d、err
d, err := store.Cookies.GetDetails(context.Background(), "qr-new")
if err != nil {
t.Fatalf("GetDetails qr-new: %v", err)
@@ -323,23 +323,23 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
if d.LoginMethod != "qr_scan" || d.LastLoginAt == 0 {
t.Fatalf("扫码登录应标记登录审计字段: %+v", d)
}
if // snapshot、ok 保存snapshot、ok,供当前处理流程使用
if // snapshot、ok 用于本次流程后续判断的snapshot、ok
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(d.MetadataJSON); !ok || len(snapshot) != 2 {
t.Fatalf("纯 Go 扫码完整 Cookie Jar 未持久化: ok=%v snapshot=%+v metadata=%s", ok, snapshot, d.MetadataJSON)
}
// logs、err 保存logs、err,供当前处理流程使用
// logs、err 用于本次流程后续判断的logs、err
logs, err := store.LoginLogs.ListByCookie(context.Background(), "qr-new", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" || logs[0].Method != "qr_scan" {
t.Fatalf("重复轮询不应重复记录登录日志: logs=%#v err=%v", logs, err)
}
}
// TestCompleteQRVerificationPersistsAndReenablesAccount 负责TestCompleteQRVerificationPersistsAndReenables账号相关处理。
// TestCompleteQRVerificationPersistsAndReenablesAccount 封装TestCompleteQRVerificationPersistsAndReenables账号业务协调。
func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{
@@ -347,39 +347,39 @@ func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
completeUNB: "acc1",
}
ownQRSession(t, srv, store, "s1")
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.Cookies.SetStatusWithReason(ctx, "acc1", false, "token 失效"); err != nil {
t.Fatalf("SetStatusWithReason: %v", err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.Tokens.Save(ctx, "acc1", "did", "token", 9999999999); err != nil {
t.Fatalf("Save token: %v", err)
}
seedStaleCookieSnapshot(t, store, "acc1")
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/s1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode response: %v", err)
}
if res["success"] != true || res["account_id"] != "acc1" {
t.Fatalf("完成验证响应异常: %+v", res)
}
if // exists 保存exists,供当前处理流程使用
if // exists 用于本次流程后续判断的exists
_, exists := res["cookies"]; exists {
t.Fatalf("完成验证响应不得暴露 cookies: %+v", res)
}
@@ -387,15 +387,15 @@ func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
t.Fatal("扫码验证成功后应重新启用账号")
}
requireCookieSnapshotCleared(t, store, "acc1")
if // tk、err 保存tk、err,供当前处理流程使用
if // tk、err 用于本次流程后续判断的tk、err
tk, err := store.Tokens.Get(ctx, "acc1"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did" {
t.Fatalf("扫码验证成功后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
}
// TestCompleteQRVerificationRejectsDifferentTarget 负责TestCompleteQRVerificationRejectsDifferentTarget相关处理。
// TestCompleteQRVerificationRejectsDifferentTarget 封装TestCompleteQRVerificationRejectsDifferentTarget业务协调。
func TestCompleteQRVerificationRejectsDifferentTarget(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
@@ -404,39 +404,39 @@ func TestCompleteQRVerificationRejectsDifferentTarget(t *testing.T) {
completeUNB: "scanned-other",
}
ownQRSession(t, srv, store, "s-mismatch")
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// request 保存请求,供当前处理流程使用
// request 用于本次流程后续判断的请求
request := func() map[string]any {
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"target_account_id":"acc1"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/s-mismatch", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// result 保存结果,供当前处理流程使用
// result 用于本次流程后续判断的结果
var result map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
return result
}
// result 保存结果,供当前处理流程使用
// result 用于本次流程后续判断的结果
result := request()
if result["code"] != "qr_account_mismatch" || result["details"].(map[string]any)["scanned_account_id"] != "scanned-other" {
t.Fatalf("response=%+v", result)
}
// original 保存original,供当前处理流程使用
// original 用于本次流程后续判断的original
original, _ := store.Cookies.GetValue(context.Background(), "acc1")
if strings.Contains(original, "qr-fresh") {
t.Fatal("mismatched account must never overwrite the target account")
@@ -445,20 +445,20 @@ func TestCompleteQRVerificationRejectsDifferentTarget(t *testing.T) {
// TestKeywordsListAndDelete 关键字列表与删除(覆盖 listKeywords / listKeywordsWithItemID / listKeywordsWithType)。
func TestKeywordsListAndDelete(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 添加(普通 + 带 item_id)。
post := func(body string) {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -470,16 +470,16 @@ func TestKeywordsListAndDelete(t *testing.T) {
// path 表示当前遍历过程中的路径
for _, path := range []string{"/keywords/acc1", "/keywords-with-item-id/acc1", "/keywords-with-type/acc1"} {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("GET %s status=%d", path, rec.Code)
}
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec.Body.Bytes(), &arr)
if len(arr) != 2 {
@@ -490,18 +490,18 @@ func TestKeywordsListAndDelete(t *testing.T) {
// TestAddKeywordMissingKeyword 缺 keyword 400。
func TestAddKeywordMissingKeyword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader(`{"reply":"x"}`))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -511,18 +511,18 @@ func TestAddKeywordMissingKeyword(t *testing.T) {
// TestAddKeywordBadJSON 非法 JSON 400。
func TestAddKeywordBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -530,47 +530,47 @@ func TestAddKeywordBadJSON(t *testing.T) {
}
}
// TestReplaceKeywordsWithItemID 负责TestReplaceKeywordsWith商品ID相关处理。
// TestReplaceKeywordsWithItemID 封装TestReplaceKeywordsWith商品ID业务协调。
func TestReplaceKeywordsWithItemID(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// postBatch 保存post批次,供当前处理流程使用
// postBatch 用于本次流程后续判断的post批次
postBatch := func(body string) []map[string]any {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("replace status=%d body=%s", rec.Code, rec.Body.String())
}
// listReq 保存listReq,供当前处理流程使用
// listReq 用于本次流程后续判断的listReq
listReq := httptest.NewRequest(http.MethodGet, "/keywords-with-item-id/acc1", nil)
listReq.AddCookie(cookie)
// listRec 保存listRec,供当前处理流程使用
// listRec 用于本次流程后续判断的listRec
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
var rows []map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(listRec.Body.Bytes(), &rows); err != nil {
t.Fatal(err)
}
return rows
}
// rows 保存rows,供当前处理流程使用
// rows 用于本次流程后续判断的rows
rows := postBatch(`{"keywords":[{"keyword":"在吗","reply":"在的","item_id":""},{"keyword":"价格","reply":"50","item_id":"it1"}]}`)
if len(rows) != 2 || rows[1]["item_id"] != "it1" {
t.Fatalf("批量新增异常: %+v", rows)
@@ -587,14 +587,14 @@ func TestReplaceKeywordsWithItemID(t *testing.T) {
}
}
// TestReplaceKeywordsValidatesReplyTypeContent 负责TestReplaceKeywordsValidates回复类型内容相关处理。
// TestReplaceKeywordsValidatesReplyTypeContent 封装TestReplaceKeywordsValidates回复类型内容业务协调。
func TestReplaceKeywordsValidatesReplyTypeContent(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 表示当前遍历过程中的请求体
for _, body := range []string{
@@ -602,10 +602,10 @@ func TestReplaceKeywordsValidatesReplyTypeContent(t *testing.T) {
`{"keywords":[{"keyword":"图片","type":"image","image_url":""}]}`,
`{"keywords":[{"keyword":"未知","type":"api","reply":"x"}]}`,
} {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -613,12 +613,12 @@ func TestReplaceKeywordsValidatesReplyTypeContent(t *testing.T) {
}
}
// valid 保存有效,供当前处理流程使用
// valid 用于本次流程后续判断的有效
valid := `{"keywords":[{"keyword":"图片","type":"image","reply":"stale","image_url":"https://example.com/a.png"}]}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(valid))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -628,18 +628,18 @@ func TestReplaceKeywordsValidatesReplyTypeContent(t *testing.T) {
// TestDeleteKeywordNotFound 不存在关键字 404。
func TestDeleteKeywordNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodDelete, "/keywords/acc1/999", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -649,23 +649,23 @@ func TestDeleteKeywordNotFound(t *testing.T) {
// TestItemRepliesCRUD 指定商品回复增删查。
func TestItemRepliesCRUD(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it-reply','商品R')`)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 设。
body := `{"reply_content":"这是专属回复"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/it-reply", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -675,13 +675,13 @@ func TestItemRepliesCRUD(t *testing.T) {
// 查。
req2 := httptest.NewRequest(http.MethodGet, "/item-reply/acc1/it-reply", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("get status=%d", rec2.Code)
}
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
json.Unmarshal(rec2.Body.Bytes(), &got)
if got["reply_content"] != "这是专属回复" {
@@ -691,7 +691,7 @@ func TestItemRepliesCRUD(t *testing.T) {
// 列表。
req3 := httptest.NewRequest(http.MethodGet, "/itemReplays", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -701,7 +701,7 @@ func TestItemRepliesCRUD(t *testing.T) {
// 删除。
req4 := httptest.NewRequest(http.MethodDelete, "/item-reply/acc1/it-reply", nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != 200 {
@@ -711,24 +711,24 @@ func TestItemRepliesCRUD(t *testing.T) {
// TestGetItemReplyNotFound 不存在回复返回空。
func TestGetItemReplyNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/item-reply/acc1/no-such", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d", rec.Code)
}
// got 保存got,供当前处理流程使用
// got 用于本次流程后续判断的got
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["reply_content"] != "" {
@@ -738,18 +738,18 @@ func TestGetItemReplyNotFound(t *testing.T) {
// TestSetItemReplyBadJSON 非法 JSON 400。
func TestSetItemReplyBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/it1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
+54 -26
View File
@@ -9,18 +9,19 @@ import (
"time"
"xianyu-go/internal/adapter"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
)
// freeAddr 获取一个空闲 TCP 端口(立即释放,供测试绑定)。
func freeAddr(t *testing.T) string {
t.Helper()
// l、err 保存l、err,供当前处理流程使用
// l、err 用于本次流程后续判断的l、err
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
// addr 保存addr,供当前处理流程使用
// addr 用于本次流程后续判断的addr
addr := l.Addr().String()
l.Close()
return addr
@@ -28,25 +29,25 @@ func freeAddr(t *testing.T) string {
// TestRun_ServesHealthAndShutdowns 启动 HTTP 服务,/health 可访问,ctx 取消后优雅退出。
func TestRun_ServesHealthAndShutdowns(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.Addr = freeAddr(t)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
// ctx、cancel 用于本次流程后续判断的ctx、cancel
ctx, cancel := context.WithCancel(context.Background())
// runDone 保存运行Done,供当前处理流程使用
// runDone 用于本次流程后续判断的运行Done
runDone := make(chan error, 1)
go func() { runDone <- srv.Run(ctx) }()
// 轮询 /health 直到可用(最多 3s)。
url := "http://" + srv.Addr + "/health"
// ok 保存ok,供当前处理流程使用
// ok 用于本次流程后续判断的ok
var ok bool
// deadline 保存deadline,供当前处理流程使用
// deadline 用于本次流程后续判断的deadline
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
// resp、err 保存resp、err,供当前处理流程使用
// resp、err 用于本次流程后续判断的resp、err
resp, err := http.Get(url)
if err == nil {
resp.Body.Close()
@@ -65,7 +66,7 @@ func TestRun_ServesHealthAndShutdowns(t *testing.T) {
// 取消 ctx → Run 应优雅退出。
cancel()
select {
case // err 保存err,供当前处理流程使用
case // err 用于本次流程后续判断的err
err := <-runDone:
if err != nil {
t.Fatalf("Run 应返回 nil,got %v", err)
@@ -75,19 +76,19 @@ func TestRun_ServesHealthAndShutdowns(t *testing.T) {
}
}
// TestPublishRecoveryLifecycleStopsBeforeWorkerWait 负责Test发布RecoveryLifecycleStopsBefore工作器Wait相关处理。
// TestPublishRecoveryLifecycleStopsBeforeWorkerWait 封装Test发布RecoveryLifecycleStopsBefore工作器Wait业务协调。
func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
// ctx、cancel 用于本次流程后续判断的ctx、cancel
ctx, cancel := context.WithCancel(context.Background())
// err 表示测试批量恢复组件启动失败的原因。
if err := srv.applications.itemBatchCoordinator.StartRecovery(ctx); err != nil {
t.Fatalf("启动批量发布恢复扫描器: %v", err)
}
cancel()
// done 保存done,供当前处理流程使用
// done 用于本次流程后续判断的done
done := make(chan struct{})
go func() {
srv.applications.itemBatchCoordinator.Wait()
@@ -154,6 +155,8 @@ func TestNewRejectsMissingRequiredDependencies(t *testing.T) {
chatDependencies := adapter.NewChatDependencies(store)
// systemDependencies 保存平台缺失校验所需的系统专用依赖。
systemDependencies := adapter.NewSystemDependencies(store)
// databaseHealth 是进程组合根提供给 Server 的数据库健康检查端口。
databaseHealth := systemDependencies.NewDatabaseHealth()
// automationDependencies 保存平台缺失校验所需的自动化专用依赖及构造错误。
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
if automationDependencyErr != nil {
@@ -166,28 +169,53 @@ func TestNewRejectsMissingRequiredDependencies(t *testing.T) {
}
// adminSettingsDependencies 保存平台缺失校验所需的管理员设置依赖。
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil {
if chatDependencies == nil || systemDependencies == nil || databaseHealth == nil || adminSettingsDependencies == nil {
t.Fatal("显式 Server 依赖构造失败")
}
// err 是聊天或系统等显式依赖缺失时的构造校验错误。
// transportApplications 是构造失败测试使用的完整 transport-facing 服务集合。
transportApplications, transportApplicationsErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
AutomationDependencies: automationDependencies,
MiscDependencies: miscDependencies,
AdminSettingsDependencies: adminSettingsDependencies,
AccountTaskRunner: adapter.NewAccountTaskRunner(nil),
ModelClient: adapter.NewAIModelClient(),
})
if transportApplicationsErr != nil {
t.Fatalf("NewTransportApplicationServices: %v", transportApplicationsErr)
}
// orderReconciliationRecovery 是完整构造路径需要的订单补偿扫描应用服务。
orderReconciliationRecovery, reconciliationErr := orderapp.NewReconciliationRecoveryCoordinator(systemDependencies.NewReconciliationService(nil))
if reconciliationErr != nil {
t.Fatalf("NewReconciliationRecoveryCoordinator: %v", reconciliationErr)
}
// err 是聊天或健康检查端口等显式依赖缺失时的构造校验错误。
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies)); err == nil {
t.Fatal("缺少聊天或系统专用依赖时应返回构造错误")
t.Fatal("缺少聊天或健康检查端口时应返回构造错误")
}
// err 是全部业务依赖齐全但遗漏健康检查端口时的构造错误。
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少数据库健康检查端口时应返回构造错误")
}
// err 是缺少平台依赖注入时的构造校验错误。
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies)); err == nil {
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications)); err == nil {
t.Fatal("缺少平台依赖时应返回构造错误")
}
// err 是缺少自动化专用依赖时的构造校验错误。
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies)); err == nil {
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少自动化专用依赖时应返回构造错误")
}
// err 是缺少杂项专用依赖时的构造校验错误。
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少杂项专用依赖时应返回构造错误")
// err 是缺少 transport 应用服务集合时的构造校验错误。
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少 transport 应用服务集合时应返回构造错误")
}
// err 是缺少管理员设置专用依赖时的构造校验错误。
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少管理员设置专用依赖时应返回构造错误")
// err 是全部基础设施依赖齐全但遗漏进程装配应用服务时的构造错误。
if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies)); err == nil {
t.Fatal("缺少订单补偿扫描应用服务时应返回构造错误")
}
// fullyConstructedServer、constructErr 分别是完整注入后的 HTTP 服务及构造错误。
fullyConstructedServer, constructErr := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies))
if constructErr != nil || fullyConstructedServer == nil {
t.Fatalf("完整依赖注入应构造成功: server=%v err=%v", fullyConstructedServer, constructErr)
}
}
@@ -197,11 +225,11 @@ func TestServerStartStopIsIdempotentAndWaitsForWorkers(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.Addr = freeAddr(t)
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := srv.Start(context.Background()); err != nil {
t.Fatalf("Start: %v", err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := srv.Start(context.Background()); err != nil {
t.Fatalf("重复 Start: %v", err)
}
+24 -24
View File
@@ -10,14 +10,14 @@ import (
"time"
)
// TestProtectedRouteGroupsRequireAuthentication 负责TestProtectedRouteGroupsRequireAuthentication相关处理。
// TestProtectedRouteGroupsRequireAuthentication 封装TestProtectedRouteGroupsRequireAuthentication业务协调。
func TestProtectedRouteGroupsRequireAuthentication(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// routes 保存routes,供当前处理流程使用
// routes 用于本次流程后续判断的routes
routes := []struct {
method string
path string
@@ -38,9 +38,9 @@ func TestProtectedRouteGroupsRequireAuthentication(t *testing.T) {
// route 表示当前遍历过程中的route
for _, route := range routes {
t.Run(route.method+" "+route.path, func(t *testing.T) {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(route.method, route.path, nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
@@ -50,17 +50,17 @@ func TestProtectedRouteGroupsRequireAuthentication(t *testing.T) {
}
}
// TestCookiePreferenceEndpoints 负责Test登录凭证PreferenceEndpoints相关处理。
// TestCookiePreferenceEndpoints 封装Test登录凭证PreferenceEndpoints业务协调。
func TestCookiePreferenceEndpoints(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// requests 保存请求列表,供当前处理流程使用
// requests 用于本次流程后续判断的请求列表
requests := []struct {
path string
body string
@@ -71,11 +71,11 @@ func TestCookiePreferenceEndpoints(t *testing.T) {
}
// tc 表示当前遍历过程中的tc
for _, tc := range requests {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, tc.path, strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -85,48 +85,48 @@ func TestCookiePreferenceEndpoints(t *testing.T) {
// path 表示当前遍历过程中的路径
for _, path := range []string{"/cookies/acc1/auto-confirm", "/cookies/acc1/pause-duration", "/cookie/acc1/details"} {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, path, nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("GET %s status=%d body=%s", path, rec.Code, rec.Body.String())
}
}
// paused、pausedUntil、err 保存paused、pausedUntil、err,供当前处理流程使用
// paused、pausedUntil、err 用于本次流程后续判断的paused、pausedUntil、err
paused, pausedUntil, err := store.Cookies.IsPaused(context.Background(), "acc1")
if err != nil || !paused || pausedUntil <= time.Now().UTC().Unix() {
t.Fatalf("pause deadline not persisted: paused=%v until=%d err=%v", paused, pausedUntil, err)
}
// pauseReq 保存pauseReq,供当前处理流程使用
// pauseReq 用于本次流程后续判断的pauseReq
pauseReq := httptest.NewRequest(http.MethodGet, "/cookies/acc1/pause-duration", nil)
pauseReq.AddCookie(cookie)
// pauseRec 保存pauseRec,供当前处理流程使用
// pauseRec 用于本次流程后续判断的pauseRec
pauseRec := httptest.NewRecorder()
h.ServeHTTP(pauseRec, pauseReq)
// pauseResponse 保存pause响应,供当前处理流程使用
// pauseResponse 用于本次流程后续判断的pause响应
var pauseResponse map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(pauseRec.Body.Bytes(), &pauseResponse); err != nil || pauseResponse["paused"] != true {
t.Fatalf("pause response=%+v err=%v", pauseResponse, err)
}
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/pause-duration", strings.NewReader(`{"pause_duration":-1}`))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("negative pause status=%d body=%s", rec.Code, rec.Body.String())
}
// tooLongReq 保存tooLongReq,供当前处理流程使用
// tooLongReq 用于本次流程后续判断的tooLongReq
tooLongReq := httptest.NewRequest(http.MethodPut, "/cookies/acc1/pause-duration", strings.NewReader(`{"pause_duration":1441}`))
tooLongReq.AddCookie(cookie)
// tooLongRec 保存tooLongRec,供当前处理流程使用
// tooLongRec 用于本次流程后续判断的tooLongRec
tooLongRec := httptest.NewRecorder()
h.ServeHTTP(tooLongRec, tooLongReq)
if tooLongRec.Code != http.StatusBadRequest {
+144 -67
View File
@@ -33,10 +33,10 @@ import (
"xianyu-go/internal/webui"
)
// qrLoginService 保存qr登录Service,供当前处理流程使用
// qrLoginService 用于本次流程后续判断的qr登录Service
type qrLoginService = adapter.QRLoginService
// qrLoginPersistence 保存qr登录Persistence,供当前处理流程使用
// qrLoginPersistence 用于本次流程后续判断的qr登录Persistence
type qrLoginPersistence struct {
AccountID string
IsNew bool
@@ -93,15 +93,15 @@ type itemDependencyFactory interface {
NewItemSyncRepository(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error)) *adapter.ItemSyncRepository
}
// databaseHealth 定义健康检查需要的最小数据库连通性能力。
type databaseHealth interface {
// DatabaseHealthPort 定义健康检查需要的最小数据库连通性能力。
type DatabaseHealthPort interface {
// Ping 在调用方 Context 内探测数据库连接是否可用。
Ping(context.Context) error
}
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
// 不再允许外部直接改字段,避免运行时被替换成 nil。
// Server 保存Server,供当前处理流程使用
// Server 用于本次流程后续判断的Server
type Server struct {
// orderDependencies 保存订单应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
orderDependencies orderDependencyFactory
@@ -111,19 +111,17 @@ type Server struct {
itemDependencies itemDependencyFactory
// chatDependencies 保存聊天应用服务专用的显式装配能力,不允许从通用设施容器回退获取。
chatDependencies *adapter.ChatDependencies
// systemDependencies 保存健康检查与补偿扫描的显式装配能力。
systemDependencies *adapter.SystemDependencies
// orderReconciliationRecovery 是进程装配层创建后注入的订单补偿扫描应用生命周期组件。
orderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator
// automationDependencies 保存自动化、默认回复和关键词的显式装配能力。
automationDependencies *adapter.AutomationDependencies
// miscDependencies 保存通知、分析和卡券的显式装配能力。
miscDependencies *adapter.MiscDependencies
// adminSettingsDependencies 保存管理员与系统设置的显式装配能力。
adminSettingsDependencies *adapter.AdminSettingsDependencies
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
notifier *notify.Notifier
chat *chat.Service
// transportApplications 保存进程装配层创建的 transport-facing 应用服务集合。
transportApplications *adapter.TransportApplicationServices
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
notifier *notify.Notifier
chat *chat.Service
// platformDependencies 保存构造阶段校验通过的平台能力;生产调用必须通过下方访问器读取。
platformDependencies *adapter.PlatformDependencies
// MTop 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。
@@ -140,7 +138,7 @@ type Server struct {
// applicationLifecycle 保存由 cmd 拥有的应用生命周期协调器;Server 只读取其共享 Context。
applicationLifecycle *lifecycleapp.Coordinator
// databaseHealth 提供健康检查所需的数据库探测能力,避免 handler 直接触碰 SQL 连接。
databaseHealth databaseHealth
databaseHealth DatabaseHealthPort
// backgroundMu 保护 Server 后台任务计数与完成信号,避免关闭等待创建不可取消的等待 goroutine。
backgroundMu sync.Mutex
backgroundCount int
@@ -212,11 +210,19 @@ func WithChatDependencies(dependencies *adapter.ChatDependencies) ServerOption {
}
}
// WithSystemDependencies 注入健康检查与订单补偿扫描所需的专用适配器工厂。
func WithSystemDependencies(dependencies *adapter.SystemDependencies) ServerOption {
// WithDatabaseHealth 注入由进程装配层构造的数据库健康检查端口。
func WithDatabaseHealth(health DatabaseHealthPort) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入系统专用依赖的 HTTP 服务实例。
server.systemDependencies = dependencies
// server 是当前构造流程中待注入健康检查端口的 HTTP 服务实例。
server.databaseHealth = health
}
}
// WithOrderReconciliationRecovery 注入由进程装配层拥有的订单补偿扫描应用服务。
func WithOrderReconciliationRecovery(recovery *orderapp.ReconciliationRecoveryCoordinator) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入订单补偿扫描服务的 HTTP 服务实例。
server.orderReconciliationRecovery = recovery
}
}
@@ -228,19 +234,17 @@ func WithAutomationDependencies(dependencies *adapter.AutomationDependencies) Se
}
}
// WithMiscDependencies 注入通知、分析和卡券领域所需的专用适配器工厂。
func WithMiscDependencies(dependencies *adapter.MiscDependencies) ServerOption {
// WithTransportApplicationServices 注入进程装配层构造完成的 transport-facing 应用服务集合。
func WithTransportApplicationServices(services *adapter.TransportApplicationServices) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入杂项领域依赖的 HTTP 服务实例。
server.miscDependencies = dependencies
}
}
// WithAdminSettingsDependencies 注入管理员与系统设置所需的专用适配器工厂。
func WithAdminSettingsDependencies(dependencies *adapter.AdminSettingsDependencies) ServerOption {
return func(server *Server) {
// server 是当前构造流程中待注入管理员设置依赖的 HTTP 服务实例。
server.adminSettingsDependencies = dependencies
if services == nil {
// server 是当前构造流程中应清空 transport-facing 应用服务集合的 HTTP 服务实例。
server.transportApplications = nil
return
}
// copiedServices 是构造期冻结的浅拷贝,避免调用方替换集合容器影响 Server。
copiedServices := *services
server.transportApplications = &copiedServices
}
}
@@ -304,8 +308,11 @@ func New(authentication *auth.Service, manager *account.Manager, webDir, addr st
if server.chatDependencies == nil {
return nil, fmt.Errorf("server 聊天专用依赖不能为空")
}
if server.systemDependencies == nil {
return nil, fmt.Errorf("server 系统专用依赖不能为空")
if server.databaseHealth == nil {
return nil, fmt.Errorf("server 数据库健康检查端口不能为空")
}
if server.orderReconciliationRecovery == nil {
return nil, fmt.Errorf("server 订单补偿扫描应用服务不能为空")
}
if server.platformDependencies == nil {
return nil, fmt.Errorf("server 平台依赖不能为空")
@@ -313,14 +320,16 @@ func New(authentication *auth.Service, manager *account.Manager, webDir, addr st
if server.automationDependencies == nil {
return nil, fmt.Errorf("server 自动化依赖不能为空")
}
if server.miscDependencies == nil {
return nil, fmt.Errorf("server 通知、分析和卡券依赖不能为空")
// validationErr 表示进程组合根未提供完整 transport-facing 服务集合。
if validationErr := server.transportApplications.Validate(); validationErr != nil {
return nil, fmt.Errorf("server transport 应用服务无效: %w", validationErr)
}
if server.adminSettingsDependencies == nil {
return nil, fmt.Errorf("server 管理员与设置依赖不能为空")
// applications、applicationErr 分别是构造期应用服务集合及其装配错误。
applications, applicationErr := newApplicationServices(server)
if applicationErr != nil {
return nil, fmt.Errorf("server 应用服务装配失败: %w", applicationErr)
}
server.applications = newApplicationServices(server)
server.databaseHealth = server.systemDependencies.NewDatabaseHealth()
server.applications = applications
return server, nil
}
@@ -388,10 +397,12 @@ func (s *Server) recoverExpiredSession(ctx context.Context, cookieID string, err
// Router 构建完整路由树。
func (s *Server) Router() http.Handler {
// r 保存r,供当前处理流程使用
// r 用于本次流程后续判断的r
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Recoverer)
// legacyAPITelemetry 为保留的历史 API 写入弃用元数据并提供结构化观测,不参与版本化入口或 SPA 路由。
r.Use(s.legacyAPITelemetry)
// 请求日志(精简)。
r.Use(s.requestLogger)
@@ -476,18 +487,18 @@ func (s *Server) authMiddleware(h http.Handler) http.Handler {
// requestLogger 记录请求完成状态、耗时和 chi request_id。
func (s *Server) requestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// start 保存开始,供当前处理流程使用
// start 用于本次流程后续判断的开始
start := time.Now()
// ww 保存ww,供当前处理流程使用
// ww 用于本次流程后续判断的ww
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
// status 保存状态,供当前处理流程使用
// status 用于本次流程后续判断的状态
status := ww.Status()
if status == 0 {
status = http.StatusOK
}
// level 保存level,供当前处理流程使用
// level 用于本次流程后续判断的level
level := slog.LevelDebug
if status >= 500 {
level = slog.LevelError
@@ -502,22 +513,87 @@ func (s *Server) requestLogger(next http.Handler) http.Handler {
slog.Duration("duration", time.Since(start)),
slog.String("request_id", middleware.GetReqID(r.Context())),
slog.String("remote", r.RemoteAddr),
slog.Bool("legacy_api", isLegacyAPIRequest(r.Method, r.URL.Path)),
)
})
}
const (
// legacyAPISunsetDate 是历史 API 的标准 HTTP-date 退场时间;实际删除仍须满足兼容矩阵中的观测窗口。
legacyAPISunsetDate = "Thu, 31 Dec 2026 23:59:59 GMT"
// legacyAPISuccessorLink 是带计划版本标识的版本化后继 API 链接。
legacyAPISuccessorLink = "</api/v1>; rel=\"successor-version\"; title=\"v2.0\""
)
// legacyAPITelemetry 为历史 API 请求写入标准弃用响应头,供客户端、日志和发布观测统一识别。
// next 保持原有 handler、鉴权及错误映射;只有 isLegacyAPIPath 判定为真时才附加元数据。
func (s *Server) legacyAPITelemetry(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// legacyPath 表示当前请求是否命中仍受兼容矩阵保护的旧 API,而非 /api/v1 或公开页面。
legacyPath := isLegacyAPIRequest(r.Method, r.URL.Path)
if legacyPath {
w.Header().Set("Deprecation", "true")
w.Header().Set("Sunset", legacyAPISunsetDate)
w.Header().Set("Link", legacyAPISuccessorLink)
}
next.ServeHTTP(w, r)
})
}
// isLegacyAPIRequest 判断请求是否为需要遥测并保留到 Sunset 条件满足的历史 API。
// method 用于区分 SPA 的 GET /login 与同路径的历史认证 POST;/api/v1、健康检查、版本信息和静态页面不属于旧 API。
func isLegacyAPIRequest(method, path string) bool {
if isLegacyAPIPath(path) {
return true
}
// normalizedMethod 是标准化后的请求方法,避免空白输入意外匹配历史认证入口。
normalizedMethod := strings.ToUpper(strings.TrimSpace(method))
// normalizedPath 是标准化后的请求路径,用于与有限的历史认证入口精确比较。
normalizedPath := strings.TrimSpace(path)
switch normalizedPath {
case "/login", "/logout", "/initialize", "/change-admin-password", "/change-password":
return normalizedMethod == http.MethodPost
case "/verify":
return normalizedMethod == http.MethodGet
default:
return false
}
}
// isLegacyAPIPath 判断不与 SPA 客户端路由重名的历史业务路径是否需要遥测。
// 调用方还必须通过 isLegacyAPIRequest 处理认证入口的 HTTP 方法语义。
func isLegacyAPIPath(path string) bool {
// normalizedPath 保存去除首尾空白后的请求路径,路由路径本身不允许以空白构成兼容入口。
normalizedPath := strings.TrimSpace(path)
if strings.HasPrefix(normalizedPath, "/api/v1/") || normalizedPath == "/health" || normalizedPath == "/version" {
return false
}
return strings.HasPrefix(normalizedPath, "/api/") ||
strings.HasPrefix(normalizedPath, "/cookies") || strings.HasPrefix(normalizedPath, "/cookie/") ||
strings.HasPrefix(normalizedPath, "/items") || strings.HasPrefix(normalizedPath, "/orders") ||
strings.HasPrefix(normalizedPath, "/automation-") || strings.HasPrefix(normalizedPath, "/keywords") ||
strings.HasPrefix(normalizedPath, "/default-repl") || strings.HasPrefix(normalizedPath, "/item-reply") ||
strings.HasPrefix(normalizedPath, "/notification-") || strings.HasPrefix(normalizedPath, "/message-notifications") ||
strings.HasPrefix(normalizedPath, "/system-settings") || strings.HasPrefix(normalizedPath, "/user-settings") ||
strings.HasPrefix(normalizedPath, "/ai-") || strings.HasPrefix(normalizedPath, "/cards") ||
strings.HasPrefix(normalizedPath, "/admin/") || strings.HasPrefix(normalizedPath, "/qr-login") ||
strings.HasPrefix(normalizedPath, "/password-login") || strings.HasPrefix(normalizedPath, "/account/") ||
strings.HasPrefix(normalizedPath, "/dashboard/") || strings.HasPrefix(normalizedPath, "/analytics/") ||
strings.HasPrefix(normalizedPath, "/itemReplays")
}
// mountSPA 挂载前端静态资源与 SPA catch-all。
//
// 前端 vite base 为 /static/,构建后 index.html 引用 /static/assets/...、/static/favicon.svg。
// 故静态资源统一从 /static/ 前缀提供;非 API 的 GET 请求(/、/login 等客户端路由)
// 返回 /static/index.html,交给 React Router 接管。
// mountSPA 负责mountSPA相关处理。
// mountSPA 封装mountSPA业务协调。
func (s *Server) mountSPA(r chi.Router) {
if s.WebDir != "" {
s.mountDirSPA(r)
return
}
// embedded、err 保存embedded、err,供当前处理流程使用
// embedded、err 用于本次流程后续判断的embedded、err
embedded, err := webui.Static()
if err != nil {
return
@@ -525,13 +601,13 @@ func (s *Server) mountSPA(r chi.Router) {
s.mountFSSPA(r, embedded)
}
// mountDirSPA 负责mountDirSPA相关处理。
// mountDirSPA 封装mountDirSPA业务协调。
func (s *Server) mountDirSPA(r chi.Router) {
// indexFile 保存index文件,供当前处理流程使用
// indexFile 用于本次流程后续判断的index文件
indexFile := filepath.Join(s.WebDir, "index.html")
// /static/* 直接作为静态文件服务(assets/、favicon.svg 等)。
// StripPrefix("/static/") 后,URL /static/assets/x.js → WebDir/assets/x.js。
// staticFiles 保存static文件列表,供当前处理流程使用
// staticFiles 用于本次流程后续判断的static文件列表
staticFiles := http.StripPrefix("/static/", http.FileServer(http.Dir(s.WebDir)))
r.Handle("/static/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/static/" || r.URL.Path == "/static/index.html" {
@@ -546,7 +622,7 @@ func (s *Server) mountDirSPA(r chi.Router) {
writeErrRequest(w, r, http.StatusNotFound, "接口不存在")
return
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := os.Stat(indexFile); err != nil {
writeErrRequest(w, r, http.StatusNotFound, "前端未构建")
return
@@ -556,9 +632,9 @@ func (s *Server) mountDirSPA(r chi.Router) {
})
}
// mountFSSPA 负责mountFSSPA相关处理。
// mountFSSPA 封装mountFSSPA业务协调。
func (s *Server) mountFSSPA(r chi.Router, staticFS fs.FS) {
// staticFiles 保存static文件列表,供当前处理流程使用
// staticFiles 用于本次流程后续判断的static文件列表
staticFiles := http.StripPrefix("/static/", http.FileServer(http.FS(staticFS)))
r.Handle("/static/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/static/" || r.URL.Path == "/static/index.html" {
@@ -572,7 +648,7 @@ func (s *Server) mountFSSPA(r chi.Router, staticFS fs.FS) {
writeErrRequest(w, r, http.StatusNotFound, "接口不存在")
return
}
// index、err 保存index、err,供当前处理流程使用
// index、err 用于本次流程后续判断的index、err
index, err := fs.ReadFile(staticFS, "index.html")
if err != nil {
writeErrRequest(w, r, http.StatusNotFound, "前端未构建")
@@ -584,7 +660,7 @@ func (s *Server) mountFSSPA(r chi.Router, staticFS fs.FS) {
})
}
// setNoStore 负责setNoStore相关处理。
// setNoStore 封装setNoStore业务协调。
func setNoStore(w http.ResponseWriter) {
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
w.Header().Set("Pragma", "no-cache")
@@ -593,9 +669,9 @@ func setNoStore(w http.ResponseWriter) {
// isAPIPath 判断是否为 API 路径(不应被 SPA 拦截)。
// 仅保留实际挂载的路由前缀,与 Router() 中的 mount* 一一对应。
// isAPIPath 负责isAPI路径相关处理。
// isAPIPath 封装isAPI路径业务协调。
func isAPIPath(path string) bool {
// apiPrefixes 保存apiPrefixes,供当前处理流程使用
// apiPrefixes 用于本次流程后续判断的apiPrefixes
apiPrefixes := []string{
"/api/", "/admin/", "/health", "/login", "/initialize", "/logout", "/verify",
"/change-password", "/change-admin-password", "/account/",
@@ -619,7 +695,7 @@ func isAPIPath(path string) bool {
// health 健康检查。
func (s *Server) health(w http.ResponseWriter, r *http.Request) {
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
// ctx、cancel 用于本次流程后续判断的ctx、cancel
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if s.databaseHealth == nil || s.databaseHealth.Ping(ctx) != nil {
@@ -675,10 +751,10 @@ func (s *Server) Start(ctx context.Context) error {
<-ctx.Done()
// stopCtx 是自动关闭 HTTP 服务时使用的有限时长上下文。
// cancel 释放 stopCtx 的定时器资源。
// stopCtx、cancel 保存stopCtx、cancel,供当前处理流程使用
// stopCtx、cancel 用于本次流程后续判断的stopCtx、cancel
stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := s.Stop(stopCtx); err != nil && s.Logger != nil {
s.Logger.Warn("HTTP 服务关闭异常", "err", err)
}
@@ -718,7 +794,8 @@ func (s *Server) Wait() error {
return err
}
// Stop 幂等关闭 HTTP 服务,并等待 Server 自有后台任务和批量 worker 退出。
// Stop 幂等关闭 HTTP 服务,并等待 Server 自有后台任务退出。
// 应用 worker 由进程生命周期协调器在独立 Context 中取消和 Join,避免 HTTP 超时耗尽其关闭预算。
func (s *Server) Stop(ctx context.Context) error {
if s == nil {
return nil
@@ -747,9 +824,9 @@ func (s *Server) Stop(ctx context.Context) error {
s.stopped = true
// httpServer 是需要执行优雅关闭的标准库 HTTP 服务。
// httpDone 是监听 goroutine 退出的完成信号。
// httpServer 保存httpServer,供当前处理流程使用
// httpServer 用于本次流程后续判断的httpServer
httpServer := s.httpServer
// httpDone 保存httpDone,供当前处理流程使用
// httpDone 用于本次流程后续判断的httpDone
httpDone := s.httpDone
s.lifecycleMu.Unlock()
// shutdownErr 是 HTTP 优雅关闭返回的错误;后台等待错误由 worker 自身记录。
@@ -783,15 +860,15 @@ func (s *Server) WaitForBackground() {
_ = s.waitForBackgroundContext(context.Background())
}
// closedSignal 负责closedSignal相关处理。
// closedSignal 封装closedSignal业务协调。
func closedSignal() chan struct{} {
// done 保存done,供当前处理流程使用
// done 用于本次流程后续判断的done
done := make(chan struct{})
close(done)
return done
}
// lifecycleContext 负责lifecycle上下文相关处理。
// lifecycleContext 封装lifecycle上下文业务协调。
func (s *Server) lifecycleContext() context.Context {
if s == nil || s.applicationLifecycle == nil {
return context.Background()
+149 -107
View File
@@ -12,6 +12,7 @@ import (
"xianyu-go/internal/account"
"xianyu-go/internal/adapter"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/chat"
@@ -57,6 +58,8 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
chatDependencies := adapter.NewChatDependencies(store)
// systemDependencies 保存健康检查与补偿扫描测试使用的显式适配器工厂。
systemDependencies := adapter.NewSystemDependencies(store)
// databaseHealth 是测试进程组合根创建后注入 Server 的健康检查端口。
databaseHealth := systemDependencies.NewDatabaseHealth()
// automationDependencies 保存自动化测试使用的显式适配器工厂及构造错误。
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
if automationDependencyErr != nil {
@@ -69,9 +72,22 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
}
// adminSettingsDependencies 保存管理员和系统设置测试使用的显式适配器工厂。
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil {
if chatDependencies == nil || systemDependencies == nil || databaseHealth == nil || adminSettingsDependencies == nil {
t.Fatal("显式 Server 依赖构造失败")
}
// transportApplications 是测试组合根构造的 transport-facing 应用服务集合。
transportApplications, transportApplicationsErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
AutomationDependencies: automationDependencies,
MiscDependencies: miscDependencies,
AdminSettingsDependencies: adminSettingsDependencies,
AccountTaskRunner: adapter.NewAccountTaskRunner(nil),
ModelClient: adapter.NewAIModelClient(),
})
if transportApplicationsErr != nil {
t.Fatalf("NewTransportApplicationServices: %v", transportApplicationsErr)
}
// orderReconciliationRecovery 是按生产组合根路径创建的订单补偿扫描应用服务。
orderReconciliationRecovery := newTestOrderReconciliationRecovery(t, systemDependencies)
// platformDependencies 保存测试服务器显式注入的平台客户端集合。
platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil)
if platformDependencyErr != nil {
@@ -80,11 +96,11 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
// authentication 保存测试 HTTP 会话中间件需要的认证服务。
authentication := &auth.Service{Store: store}
// srv、err 保存测试 HTTP 服务构造结果及失败原因。
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies))
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies))
if err != nil {
t.Fatalf("New: %v", err)
}
// mtopClient 保存mtopClient,供当前处理流程使用
// mtopClient 用于本次流程后续判断的mtopClient
mtopClient := mtop.NewClient()
mtopClient.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
@@ -116,10 +132,10 @@ func newTestServerWithChat(t *testing.T) (*Server, *db.Store, func()) {
return srv, store, cleanup
}
// newUninitializedTestServer 负责newUninitializedTestServer相关处理。
// newUninitializedTestServer 封装newUninitializedTestServer业务协调。
func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
t.Helper()
// dbPath 保存db路径,供当前处理流程使用
// dbPath 用于本次流程后续判断的db路径
dbPath := filepath.Join(t.TempDir(), "test.db")
// d 是当前未初始化测试使用的数据库连接;err 是打开错误。
d, _, err := db.Open(context.Background(), dbPath)
@@ -150,6 +166,8 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
chatDependencies := adapter.NewChatDependencies(store)
// systemDependencies 保存未初始化测试使用的系统适配器工厂。
systemDependencies := adapter.NewSystemDependencies(store)
// databaseHealth 是测试进程组合根创建后注入 Server 的健康检查端口。
databaseHealth := systemDependencies.NewDatabaseHealth()
// automationDependencies 保存未初始化测试使用的自动化适配器工厂及构造错误。
automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store)
if automationDependencyErr != nil {
@@ -162,9 +180,22 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
}
// adminSettingsDependencies 保存未初始化测试使用的管理员设置适配器工厂。
adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store)
if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil {
if chatDependencies == nil || systemDependencies == nil || databaseHealth == nil || adminSettingsDependencies == nil {
t.Fatal("显式 Server 依赖构造失败")
}
// transportApplications 是未初始化测试组合根构造的 transport-facing 应用服务集合。
transportApplications, transportApplicationsErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
AutomationDependencies: automationDependencies,
MiscDependencies: miscDependencies,
AdminSettingsDependencies: adminSettingsDependencies,
AccountTaskRunner: adapter.NewAccountTaskRunner(nil),
ModelClient: adapter.NewAIModelClient(),
})
if transportApplicationsErr != nil {
t.Fatalf("NewTransportApplicationServices: %v", transportApplicationsErr)
}
// orderReconciliationRecovery 是按生产组合根路径创建的订单补偿扫描应用服务。
orderReconciliationRecovery := newTestOrderReconciliationRecovery(t, systemDependencies)
// platformDependencies 保存未初始化测试服务器显式注入的平台客户端集合。
platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil)
if platformDependencyErr != nil {
@@ -173,7 +204,7 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
// authentication 保存未初始化数据库上的会话中间件依赖。
authentication := &auth.Service{Store: store}
// srv、err 保存未初始化测试服务构造结果及失败原因。
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies))
srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithDatabaseHealth(databaseHealth), WithOrderReconciliationRecovery(orderReconciliationRecovery), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithTransportApplicationServices(transportApplications), WithPlatformDependencies(platformDependencies))
if err != nil {
t.Fatalf("New: %v", err)
}
@@ -183,15 +214,26 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
}
}
// roundTripFunc 保存roundTripFunc,供当前处理流程使用
// newTestOrderReconciliationRecovery 以与进程组合根一致的路径构造订单补偿扫描应用服务。
func newTestOrderReconciliationRecovery(t *testing.T, dependencies *adapter.SystemDependencies) *orderapp.ReconciliationRecoveryCoordinator {
t.Helper()
// recovery 是订单补偿扫描应用服务;测试不启动它,因此无需额外关闭。
recovery, recoveryErr := orderapp.NewReconciliationRecoveryCoordinator(dependencies.NewReconciliationService(nil))
if recoveryErr != nil {
t.Fatalf("NewReconciliationRecoveryCoordinator: %v", recoveryErr)
}
return recovery
}
// roundTripFunc 用于本次流程后续判断的roundTripFunc
type roundTripFunc func(*http.Request) (*http.Response, error)
// RoundTrip 负责RoundTrip相关处理。
// RoundTrip 封装RoundTrip业务协调。
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
// noopHandler 保存noopHandler,供当前处理流程使用
// noopHandler 用于本次流程后续判断的noopHandler
type noopHandler struct{}
// HandleChatMessage 处理聊天消息。
@@ -200,37 +242,37 @@ func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error
// HandleSystemEvent 处理系统Event。
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
// OnPasswordLoginRefresh 负责On密码登录Refresh相关处理。
// OnPasswordLoginRefresh 封装On密码登录Refresh业务协调。
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
// OnAccountAlert 负责On账号Alert相关处理。
// OnAccountAlert 封装On账号Alert业务协调。
func (noopHandler) OnAccountAlert(context.Context, string, string, string, string) {}
// TestLoginVerifyLogout 登录→verify→登出 全链路。
func TestLoginVerifyLogout(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// 1) 登录(用户名密码)。
body := `{"username":"admin","password":"pw"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("login status=%d body=%s", rec.Code, rec.Body.String())
}
// lr 保存lr,供当前处理流程使用
// lr 用于本次流程后续判断的lr
var lr loginResponse
json.Unmarshal(rec.Body.Bytes(), &lr)
if !lr.Success || !lr.IsAdmin {
t.Fatalf("登录响应异常: %+v", lr)
}
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := rec.Result().Cookies()[0]
if cookie.Name != "session" || cookie.Value == "" || !cookie.HttpOnly {
t.Fatalf("Cookie 异常: %+v", cookie)
@@ -239,10 +281,10 @@ func TestLoginVerifyLogout(t *testing.T) {
// 2) verify 带 cookie 应 authenticated。
req2 := httptest.NewRequest(http.MethodGet, "/verify", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
// v 保存v,供当前处理流程使用
// v 用于本次流程后续判断的v
var v map[string]any
json.Unmarshal(rec2.Body.Bytes(), &v)
if v["authenticated"] != true || v["initialized"] != true {
@@ -251,7 +293,7 @@ func TestLoginVerifyLogout(t *testing.T) {
// 3) 无 cookie verify 应未认证。
req3 := httptest.NewRequest(http.MethodGet, "/verify", nil)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
json.Unmarshal(rec3.Body.Bytes(), &v)
@@ -262,12 +304,12 @@ func TestLoginVerifyLogout(t *testing.T) {
// 4) 登出。
req4 := httptest.NewRequest(http.MethodPost, "/logout", nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
// 登出后 cookie 应被清除(MaxAge=-1)。
dc := rec4.Result().Cookies()
// cleared 保存cleared,供当前处理流程使用
// cleared 用于本次流程后续判断的cleared
cleared := false
// c 表示当前遍历过程中的c
for _, c := range dc {
@@ -282,20 +324,20 @@ func TestLoginVerifyLogout(t *testing.T) {
// TestLoginWrongPassword 错误密码。
func TestLoginWrongPassword(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"username":"admin","password":"wrong"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// lr 保存lr,供当前处理流程使用
// lr 用于本次流程后续判断的lr
var lr loginResponse
json.Unmarshal(rec.Body.Bytes(), &lr)
if lr.Success {
@@ -303,34 +345,34 @@ func TestLoginWrongPassword(t *testing.T) {
}
}
// TestInitializeFromWebUI 负责TestInitializeFromWebUI相关处理。
// TestInitializeFromWebUI 封装TestInitializeFromWebUI业务协调。
func TestInitializeFromWebUI(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newUninitializedTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// shortReq 保存shortReq,供当前处理流程使用
// shortReq 用于本次流程后续判断的shortReq
shortReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"short"}`))
// shortRec 保存shortRec,供当前处理流程使用
// shortRec 用于本次流程后续判断的shortRec
shortRec := httptest.NewRecorder()
h.ServeHTTP(shortRec, shortReq)
if shortRec.Code != http.StatusBadRequest {
t.Fatalf("短密码应返回 400,got %d body=%s", shortRec.Code, shortRec.Body.String())
}
// initReq 保存initReq,供当前处理流程使用
// initReq 用于本次流程后续判断的initReq
initReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"newpassword"}`))
// initRec 保存initRec,供当前处理流程使用
// initRec 用于本次流程后续判断的initRec
initRec := httptest.NewRecorder()
h.ServeHTTP(initRec, initReq)
if initRec.Code != http.StatusOK {
t.Fatalf("初始化 status=%d body=%s", initRec.Code, initRec.Body.String())
}
// initResult 保存init结果,供当前处理流程使用
// initResult 用于本次流程后续判断的init结果
var initResult loginResponse
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(initRec.Body.Bytes(), &initResult); err != nil {
t.Fatalf("解析初始化响应: %v", err)
}
@@ -338,30 +380,30 @@ func TestInitializeFromWebUI(t *testing.T) {
t.Fatalf("初始化响应异常: %+v", initResult)
}
// admin、err 保存admin、err,供当前处理流程使用
// admin、err 用于本次流程后续判断的admin、err
admin, err := store.Users.GetAdmin(context.Background())
if err != nil || admin == nil {
t.Fatalf("初始化后 admin 不存在: admin=%+v err=%v", admin, err)
}
if // ok、err 保存ok、err,供当前处理流程使用
if // ok、err 用于本次流程后续判断的ok、err
_, ok, err := store.Users.VerifyAndUpgrade(context.Background(), "admin", "newpassword"); err != nil || !ok {
t.Fatalf("初始化密码不可用: ok=%v err=%v", ok, err)
}
// cookies 保存cookies,供当前处理流程使用
// cookies 用于本次流程后续判断的cookies
cookies := initRec.Result().Cookies()
if len(cookies) == 0 || cookies[0].Name != "session" || cookies[0].Value == "" {
t.Fatalf("初始化后应自动建立会话: %+v", cookies)
}
// verifyReq 保存verifyReq,供当前处理流程使用
// verifyReq 用于本次流程后续判断的verifyReq
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(cookies[0])
// verifyRec 保存verifyRec,供当前处理流程使用
// verifyRec 用于本次流程后续判断的verifyRec
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verifyResult 保存verify结果,供当前处理流程使用
// verifyResult 用于本次流程后续判断的verify结果
var verifyResult map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult); err != nil {
t.Fatalf("解析 verify 响应: %v", err)
}
@@ -369,9 +411,9 @@ func TestInitializeFromWebUI(t *testing.T) {
t.Fatalf("初始化后 verify 异常: %+v", verifyResult)
}
// secondReq 保存secondReq,供当前处理流程使用
// secondReq 用于本次流程后续判断的secondReq
secondReq := httptest.NewRequest(http.MethodPost, "/initialize", strings.NewReader(`{"password":"anotherpw"}`))
// secondRec 保存secondRec,供当前处理流程使用
// secondRec 用于本次流程后续判断的secondRec
secondRec := httptest.NewRecorder()
h.ServeHTTP(secondRec, secondReq)
if secondRec.Code != http.StatusConflict {
@@ -379,71 +421,71 @@ func TestInitializeFromWebUI(t *testing.T) {
}
}
// TestUpdateCredentialsRenamesUserAndRevokesSessions 负责TestUpdateCredentialsRenames用户AndRevokesSessions相关处理。
// TestUpdateCredentialsRenamesUserAndRevokesSessions 封装TestUpdateCredentialsRenames用户AndRevokesSessions业务协调。
func TestUpdateCredentialsRenamesUserAndRevokesSessions(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// loginReq 保存登录Req,供当前处理流程使用
// loginReq 用于本次流程后续判断的登录Req
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
// loginRec 用于本次流程后续判断的登录Rec
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
// sessionCookie 保存会话登录凭证,供当前处理流程使用
// sessionCookie 用于本次流程后续判断的会话登录凭证
sessionCookie := loginRec.Result().Cookies()[0]
// updateReq 保存updateReq,供当前处理流程使用
// updateReq 用于本次流程后续判断的updateReq
updateReq := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(
`{"current_password":"pw","new_username":"operator","new_password":"newpassword"}`,
))
updateReq.AddCookie(sessionCookie)
// updateRec 保存updateRec,供当前处理流程使用
// updateRec 用于本次流程后续判断的updateRec
updateRec := httptest.NewRecorder()
h.ServeHTTP(updateRec, updateReq)
if updateRec.Code != http.StatusOK {
t.Fatalf("update status=%d body=%s", updateRec.Code, updateRec.Body.String())
}
// updateResult 保存update结果,供当前处理流程使用
// updateResult 用于本次流程后续判断的update结果
var updateResult map[string]any
json.Unmarshal(updateRec.Body.Bytes(), &updateResult)
if updateResult["success"] != true || updateResult["requires_relogin"] != true {
t.Fatalf("update result=%+v", updateResult)
}
// verifyReq 保存verifyReq,供当前处理流程使用
// verifyReq 用于本次流程后续判断的verifyReq
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
verifyReq.AddCookie(sessionCookie)
// verifyRec 保存verifyRec,供当前处理流程使用
// verifyRec 用于本次流程后续判断的verifyRec
verifyRec := httptest.NewRecorder()
h.ServeHTTP(verifyRec, verifyReq)
// verifyResult 保存verify结果,供当前处理流程使用
// verifyResult 用于本次流程后续判断的verify结果
var verifyResult map[string]any
json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult)
if verifyResult["authenticated"] == true || verifyResult["initialized"] != true {
t.Fatalf("旧会话应失效且系统仍已初始化: %+v", verifyResult)
}
// oldLoginReq 保存old登录Req,供当前处理流程使用
// oldLoginReq 用于本次流程后续判断的old登录Req
oldLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
// oldLoginRec 保存old登录Rec,供当前处理流程使用
// oldLoginRec 用于本次流程后续判断的old登录Rec
oldLoginRec := httptest.NewRecorder()
h.ServeHTTP(oldLoginRec, oldLoginReq)
// oldLogin 保存old登录,供当前处理流程使用
// oldLogin 用于本次流程后续判断的old登录
var oldLogin loginResponse
json.Unmarshal(oldLoginRec.Body.Bytes(), &oldLogin)
if oldLogin.Success {
t.Fatal("旧用户名不应继续登录")
}
// newLoginReq 保存new登录Req,供当前处理流程使用
// newLoginReq 用于本次流程后续判断的new登录Req
newLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"operator","password":"newpassword"}`))
// newLoginRec 保存new登录Rec,供当前处理流程使用
// newLoginRec 用于本次流程后续判断的new登录Rec
newLoginRec := httptest.NewRecorder()
h.ServeHTTP(newLoginRec, newLoginReq)
// newLogin 保存new登录,供当前处理流程使用
// newLogin 用于本次流程后续判断的new登录
var newLogin loginResponse
json.Unmarshal(newLoginRec.Body.Bytes(), &newLogin)
if !newLogin.Success {
@@ -453,15 +495,15 @@ func TestUpdateCredentialsRenamesUserAndRevokesSessions(t *testing.T) {
// TestCookiesDetailsRequiresAuth 未登录访问受保护端点应 401。
func TestCookiesDetailsRequiresAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
@@ -471,32 +513,32 @@ func TestCookiesDetailsRequiresAuth(t *testing.T) {
// TestCookiesDetailsWithAuth 登录后能取账号详情。
func TestCookiesDetailsWithAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// 登录拿 cookie。
body := `{"username":"admin","password":"pw"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := rec.Result().Cookies()[0]
// 取详情。
req2 := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("status=%d body=%s", rec2.Code, rec2.Body.String())
}
// arr 保存arr,供当前处理流程使用
// arr 用于本次流程后续判断的arr
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 || arr[0]["id"] != "acc1" {
@@ -511,34 +553,34 @@ func TestCookiesDetailsWithAuth(t *testing.T) {
}
}
// TestCookieRuntimeStatusWithAuth 负责Test登录凭证Runtime状态WithAuth相关处理。
// TestCookieRuntimeStatusWithAuth 封装Test登录凭证Runtime状态WithAuth业务协调。
func TestCookieRuntimeStatusWithAuth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// loginReq 保存登录Req,供当前处理流程使用
// loginReq 用于本次流程后续判断的登录Req
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
// loginRec 用于本次流程后续判断的登录Rec
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginRec.Result().Cookies()[0]
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/cookies/runtime-status", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// statuses 保存statuses,供当前处理流程使用
// statuses 用于本次流程后续判断的statuses
var statuses map[string]engine.RuntimeStatus
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &statuses); err != nil {
t.Fatal(err)
}
@@ -549,28 +591,28 @@ func TestCookieRuntimeStatusWithAuth(t *testing.T) {
// TestAddAndDeleteCookie 添加/删除账号。
func TestAddAndDeleteCookie(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"username":"admin","password":"pw"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := rec.Result().Cookies()[0]
// 添加。
addBody := `{"id":"acc2","value":"unb=456; _m_h5_tk=tk2_2;"}`
// req2 保存req2,供当前处理流程使用
// req2 用于本次流程后续判断的req2
req2 := httptest.NewRequest(http.MethodPost, "/cookies", strings.NewReader(addBody))
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -580,7 +622,7 @@ func TestAddAndDeleteCookie(t *testing.T) {
// 删除。
req3 := httptest.NewRequest(http.MethodDelete, "/cookies/acc2", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -590,15 +632,15 @@ func TestAddAndDeleteCookie(t *testing.T) {
// TestHealth 健康检查无需认证。
func TestHealth(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/health", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -609,28 +651,28 @@ func TestHealth(t *testing.T) {
}
}
// TestHealthReportsUnavailableDatabase 负责TestHealthReportsUnavailableDatabase相关处理。
// TestHealthReportsUnavailableDatabase 封装TestHealthReportsUnavailableDatabase业务协调。
func TestHealthReportsUnavailableDatabase(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.DB.Close(); err != nil {
t.Fatal(err)
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/health", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("health status=%d body=%s", rec.Code, rec.Body.String())
}
// response 保存响应,供当前处理流程使用
// response 用于本次流程后续判断的响应
var response map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
+110 -110
View File
@@ -14,7 +14,7 @@ import (
// TestListAIModels 通过 mock OpenAI 端点返回模型列表。
func TestListAIModels(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// 注入一个本地 HTTP server 作为 ai_api_url。
@@ -24,26 +24,26 @@ func TestListAIModels(t *testing.T) {
}))
defer ts.Close()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{"base_url":"` + ts.URL + `","api_key":"sk-test"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/ai-models", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
// models 保存模型列表,供当前处理流程使用
// models 用于本次流程后续判断的模型列表
models, _ := res["models"].([]any)
if len(models) != 2 {
t.Fatalf("应2个模型,got %+v", res)
@@ -63,9 +63,9 @@ func TestListAIModels(t *testing.T) {
}
}
// TestReadOpenAIModelsBodyRejectsOversizedResponse 负责TestReadOpenAI模型列表请求体RejectsOversized响应相关处理。
// TestReadOpenAIModelsBodyRejectsOversizedResponse 封装TestReadOpenAI模型列表请求体RejectsOversized响应业务协调。
func TestReadOpenAIModelsBodyRejectsOversizedResponse(t *testing.T) {
// err 保存err,供当前处理流程使用
// err 用于本次流程后续判断的err
_, err := readOpenAIModelsBody(strings.NewReader(strings.Repeat("x", maxOpenAIModelsResponseBytes+1)))
if err == nil {
t.Fatal("oversized models response should fail")
@@ -74,18 +74,18 @@ func TestReadOpenAIModelsBodyRejectsOversizedResponse(t *testing.T) {
// TestListAIModelsBadJSON 非法 JSON 400。
func TestListAIModelsBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/ai-models", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -95,7 +95,7 @@ func TestListAIModelsBadJSON(t *testing.T) {
// TestListAIModelsEmptyBaseURL 空地址使用默认并失败(默认阿里云地址不可达或返回非 2xx)。
func TestListAIModelsEmptyBaseURL(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// 注入一个返回错误状态码的本地 server。
@@ -106,17 +106,17 @@ func TestListAIModelsEmptyBaseURL(t *testing.T) {
// 设置系统设置 ai_api_url 指向该 server。
store.Settings.Set(context.Background(), "ai_api_url", ts.URL)
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// body 保存请求体,供当前处理流程使用
// body 用于本次流程后续判断的请求体
body := `{}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPost, "/ai-models", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadGateway {
@@ -126,18 +126,18 @@ func TestListAIModelsEmptyBaseURL(t *testing.T) {
// TestSetSettingBadJSON 非法 JSON 400。
func TestSetSettingBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -145,72 +145,72 @@ func TestSetSettingBadJSON(t *testing.T) {
}
}
// TestSetLogLevelValidatesAndAppliesRuntimeLevel 负责TestSetLogLevelValidatesAndAppliesRuntimeLevel相关处理。
// TestSetLogLevelValidatesAndAppliesRuntimeLevel 封装TestSetLogLevelValidatesAndAppliesRuntimeLevel业务协调。
func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) {
defer logging.Level.Set(slog.LevelInfo)
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// badReq 保存badReq,供当前处理流程使用
// badReq 用于本次流程后续判断的badReq
badReq := httptest.NewRequest(http.MethodPut, "/system-settings/log_level", strings.NewReader(`{"value":"verbose"}`))
badReq.AddCookie(cookie)
// badRec 保存badRec,供当前处理流程使用
// badRec 用于本次流程后续判断的badRec
badRec := httptest.NewRecorder()
h.ServeHTTP(badRec, badReq)
if badRec.Code != http.StatusBadRequest {
t.Fatalf("invalid log level should be 400, got %d body=%s", badRec.Code, badRec.Body.String())
}
// goodReq 保存goodReq,供当前处理流程使用
// goodReq 用于本次流程后续判断的goodReq
goodReq := httptest.NewRequest(http.MethodPut, "/system-settings/log_level", strings.NewReader(`{"value":"debug"}`))
goodReq.AddCookie(cookie)
// goodRec 保存goodRec,供当前处理流程使用
// goodRec 用于本次流程后续判断的goodRec
goodRec := httptest.NewRecorder()
h.ServeHTTP(goodRec, goodReq)
if goodRec.Code != http.StatusOK {
t.Fatalf("valid log level should be 200, got %d body=%s", goodRec.Code, goodRec.Body.String())
}
if // got 保存got,供当前处理流程使用
if // got 用于本次流程后续判断的got
got := logging.Level.Level(); got != slog.LevelDebug {
t.Fatalf("runtime log level=%v want debug", got)
}
// saved、err 保存saved、err,供当前处理流程使用
// saved、err 用于本次流程后续判断的saved、err
saved, err := store.Settings.Get(context.Background(), "log_level")
if err != nil || saved != "debug" {
t.Fatalf("saved log_level=%q err=%v", saved, err)
}
}
// TestSystemSettingsRequireAdmin 负责Test系统设置RequireAdmin相关处理。
// TestSystemSettingsRequireAdmin 封装Test系统设置RequireAdmin业务协调。
func TestSystemSettingsRequireAdmin(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.Users.Create(context.Background(), "user-settings", "[email protected]", "pw"); err != nil {
t.Fatalf("create user: %v", err)
}
// loginReq 保存登录Req,供当前处理流程使用
// loginReq 用于本次流程后续判断的登录Req
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"user-settings","password":"pw"}`))
// loginRec 保存登录Rec,供当前处理流程使用
// loginRec 用于本次流程后续判断的登录Rec
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
if loginRec.Code != http.StatusOK || len(loginRec.Result().Cookies()) == 0 {
t.Fatalf("login status=%d body=%s", loginRec.Code, loginRec.Body.String())
}
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginRec.Result().Cookies()[0]
// cases 保存cases,供当前处理流程使用
// cases 用于本次流程后续判断的cases
cases := []struct {
method string
path string
@@ -222,10 +222,10 @@ func TestSystemSettingsRequireAdmin(t *testing.T) {
}
// tc 表示当前遍历过程中的tc
for _, tc := range cases {
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
@@ -234,44 +234,44 @@ func TestSystemSettingsRequireAdmin(t *testing.T) {
}
}
// TestBulkSystemSettingsAreAtomic 负责TestBulk系统设置AreAtomic相关处理。
// TestBulkSystemSettingsAreAtomic 封装TestBulk系统设置AreAtomic业务协调。
func TestBulkSystemSettingsAreAtomic(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// badReq 保存badReq,供当前处理流程使用
// badReq 用于本次流程后续判断的badReq
badReq := httptest.NewRequest(http.MethodPut, "/system-settings", strings.NewReader(`{"theme_color":"red","log_level":"verbose"}`))
badReq.AddCookie(cookie)
// badRec 保存badRec,供当前处理流程使用
// badRec 用于本次流程后续判断的badRec
badRec := httptest.NewRecorder()
h.ServeHTTP(badRec, badReq)
if badRec.Code != http.StatusBadRequest {
t.Fatalf("status=%d body=%s", badRec.Code, badRec.Body.String())
}
if // value 保存值,供当前处理流程使用
if // value 用于本次流程后续判断的值
value, _ := store.Settings.Get(context.Background(), "theme_color"); value == "red" {
t.Fatal("invalid bulk request partially saved theme_color")
}
// goodReq 保存goodReq,供当前处理流程使用
// goodReq 用于本次流程后续判断的goodReq
goodReq := httptest.NewRequest(http.MethodPut, "/system-settings", strings.NewReader(`{"theme_color":"blue","renewal_log_retention_days":15}`))
goodReq.AddCookie(cookie)
// goodRec 保存goodRec,供当前处理流程使用
// goodRec 用于本次流程后续判断的goodRec
goodRec := httptest.NewRecorder()
h.ServeHTTP(goodRec, goodReq)
if goodRec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", goodRec.Code, goodRec.Body.String())
}
if // value 保存值,供当前处理流程使用
if // value 用于本次流程后续判断的值
value, _ := store.Settings.Get(context.Background(), "theme_color"); value != "blue" {
t.Fatalf("theme_color=%q", value)
}
if // value 保存值,供当前处理流程使用
if // value 用于本次流程后续判断的值
value, _ := store.Settings.Get(context.Background(), "renewal_log_retention_days"); value != "15" {
t.Fatalf("retention=%q", value)
}
@@ -279,20 +279,20 @@ func TestBulkSystemSettingsAreAtomic(t *testing.T) {
// TestListUserSettings 用户设置增删查。
func TestListUserSettings(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// 设。
body := `{"value":"dark"}`
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/user-settings/theme", strings.NewReader(body))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -302,13 +302,13 @@ func TestListUserSettings(t *testing.T) {
// 查全部。
req2 := httptest.NewRequest(http.MethodGet, "/user-settings", nil)
req2.AddCookie(cookie)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("list status=%d", rec2.Code)
}
// m 保存m,供当前处理流程使用
// m 用于本次流程后续判断的m
var m map[string]string
json.Unmarshal(rec2.Body.Bytes(), &m)
if m["theme"] != "dark" {
@@ -318,10 +318,10 @@ func TestListUserSettings(t *testing.T) {
// 查单。
req3 := httptest.NewRequest(http.MethodGet, "/user-settings/theme", nil)
req3.AddCookie(cookie)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
// one 保存one,供当前处理流程使用
// one 用于本次流程后续判断的one
var one map[string]any
json.Unmarshal(rec3.Body.Bytes(), &one)
if one["value"] != "dark" {
@@ -331,10 +331,10 @@ func TestListUserSettings(t *testing.T) {
// 查不存在的 key。
req4 := httptest.NewRequest(http.MethodGet, "/user-settings/no-such-key", nil)
req4.AddCookie(cookie)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
// miss 保存miss,供当前处理流程使用
// miss 用于本次流程后续判断的miss
var miss map[string]any
json.Unmarshal(rec4.Body.Bytes(), &miss)
if miss["value"] != "" {
@@ -344,18 +344,18 @@ func TestListUserSettings(t *testing.T) {
// TestSetUserSettingBadJSON 非法 JSON 400。
func TestSetUserSettingBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/user-settings/theme", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -365,18 +365,18 @@ func TestSetUserSettingBadJSON(t *testing.T) {
// TestSetAIReplyBadJSON 非法 JSON 400。
func TestSetAIReplyBadJSON(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader("not-json"))
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
@@ -384,20 +384,20 @@ func TestSetAIReplyBadJSON(t *testing.T) {
}
}
// TestGetAIReplyMissingAccountIsNotFound 负责TestGetAI回复Missing账号IsNotFound相关处理。
// TestGetAIReplyMissingAccountIsNotFound 封装TestGetAI回复Missing账号IsNotFound业务协调。
func TestGetAIReplyMissingAccountIsNotFound(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/no-such", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
@@ -405,26 +405,26 @@ func TestGetAIReplyMissingAccountIsNotFound(t *testing.T) {
}
}
// TestGetAIReplyExistingAccountWithoutConfigReturnsDefault 负责TestGetAI回复Existing账号Without配置ReturnsDefault相关处理。
// TestGetAIReplyExistingAccountWithoutConfigReturnsDefault 封装TestGetAI回复Existing账号Without配置ReturnsDefault业务协调。
func TestGetAIReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil)
req.AddCookie(cookie)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// res 保存响应,供当前处理流程使用
// res 用于本次流程后续判断的响应
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["ai_enabled"] != false || res["max_discount_percent"] != float64(10) {
@@ -432,73 +432,73 @@ func TestGetAIReplyExistingAccountWithoutConfigReturnsDefault(t *testing.T) {
}
}
// TestAIReplySettingsAreUserScoped 负责TestAI回复设置Are用户Scoped相关处理。
// TestAIReplySettingsAreUserScoped 封装TestAI回复设置Are用户Scoped业务协调。
func TestAIReplySettingsAreUserScoped(t *testing.T) {
// srv、store、cleanup 保存srv、store、cleanup,供当前处理流程使用
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ctx 保存ctx,供当前处理流程使用
// ctx 用于本次流程后续判断的ctx
ctx := context.Background()
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.Users.Create(ctx, "user2", "[email protected]", "pw"); err != nil {
t.Fatalf("create user2: %v", err)
}
// user2、err 保存user2、err,供当前处理流程使用
// user2、err 用于本次流程后续判断的user2、err
user2, err := store.Users.GetByUsername(ctx, "user2")
if err != nil {
t.Fatalf("get user2: %v", err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := store.Cookies.Save(ctx, "other-acc", "unb=456; _m_h5_tk=tk2_1;", user2.ID); err != nil {
t.Fatalf("save other cookie: %v", err)
}
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
_, err := store.DB.ExecContext(ctx,
`INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('other-acc', 1, 'secret')`); err != nil {
t.Fatalf("insert ai settings: %v", err)
}
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// cookie 保存登录凭证,供当前处理流程使用
// cookie 用于本次流程后续判断的登录凭证
cookie := loginHelper(t, h)
// listReq 保存listReq,供当前处理流程使用
// listReq 用于本次流程后续判断的listReq
listReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings", nil)
listReq.AddCookie(cookie)
// listRec 保存listRec,供当前处理流程使用
// listRec 用于本次流程后续判断的listRec
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
// listed 保存listed,供当前处理流程使用
// listed 用于本次流程后续判断的listed
var listed map[string]any
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := json.Unmarshal(listRec.Body.Bytes(), &listed); err != nil {
t.Fatalf("decode list: %v", err)
}
if // ok 保存ok,供当前处理流程使用
if // ok 用于本次流程后续判断的ok
_, ok := listed["other-acc"]; ok {
t.Fatalf("list leaked other user's AI settings: %+v", listed)
}
// getReq 保存getReq,供当前处理流程使用
// getReq 用于本次流程后续判断的getReq
getReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/other-acc", nil)
getReq.AddCookie(cookie)
// getRec 保存getRec,供当前处理流程使用
// getRec 用于本次流程后续判断的getRec
getRec := httptest.NewRecorder()
h.ServeHTTP(getRec, getReq)
if getRec.Code != http.StatusForbidden {
t.Fatalf("cross-user get should be 403, got %d body=%s", getRec.Code, getRec.Body.String())
}
// setReq 保存setReq,供当前处理流程使用
// setReq 用于本次流程后续判断的setReq
setReq := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/other-acc", strings.NewReader(
`{"ai_enabled":true,"max_discount_percent":20,"max_discount_amount":200,"max_bargain_rounds":5,"custom_prompts":"override"}`,
))
setReq.AddCookie(cookie)
// setRec 保存setRec,供当前处理流程使用
// setRec 用于本次流程后续判断的setRec
setRec := httptest.NewRecorder()
h.ServeHTTP(setRec, setReq)
if setRec.Code != http.StatusForbidden {
@@ -508,7 +508,7 @@ func TestAIReplySettingsAreUserScoped(t *testing.T) {
// TestFetchOpenAIModelsEmptyBaseURL 空地址错误。
func TestFetchOpenAIModelsEmptyBaseURL(t *testing.T) {
// err 保存err,供当前处理流程使用
// err 用于本次流程后续判断的err
_, err := fetchOpenAIModels(context.Background(), "", "")
if err == nil {
t.Fatal("空地址应报错")
+70 -50
View File
@@ -22,6 +22,42 @@ type systemSettingSecretChangeRequest struct {
Value string `json:"value,omitempty"`
}
// systemSettingUpdateRequest 是保存普通或敏感系统设置的 HTTP 请求 DTO。
type systemSettingUpdateRequest struct {
// Value 是普通设置值或 replace 操作的新秘密。
Value string `json:"value"`
// Action 是敏感设置的 retain、replace 或 clear 命令。
Action string `json:"action"`
}
// aiReplySettingsUpdateRequest 是保存账号 AI 回复策略的 HTTP 请求 DTO。
type aiReplySettingsUpdateRequest struct {
// AIEnabled 是账号 AI 自动回复开关。
AIEnabled bool `json:"ai_enabled"`
// MaxDiscountPercent 是允许自动接受的最大折扣百分比。
MaxDiscountPercent int `json:"max_discount_percent"`
// MaxDiscountAmount 是允许自动让价的最大金额。
MaxDiscountAmount int `json:"max_discount_amount"`
// MaxBargainRounds 是自动砍价允许的最大轮次。
MaxBargainRounds int `json:"max_bargain_rounds"`
// CustomPrompts 是账号专用的补充提示词。
CustomPrompts string `json:"custom_prompts"`
}
// aiModelListRequest 是读取指定 AI 服务模型目录的 HTTP 请求 DTO。
type aiModelListRequest struct {
// BaseURL 是目标 AI 服务的基础地址。
BaseURL string `json:"base_url"`
// APIKey 是仅在请求作用域内转交给模型目录适配器的访问密钥。
APIKey string `json:"api_key"`
}
// userSettingUpdateRequest 是保存用户范围设置的 HTTP 请求 DTO。
type userSettingUpdateRequest struct {
// Value 是需要持久化的用户设置值。
Value string `json:"value"`
}
// mountSettingsReal 系统设置端点(管理员专用)。public 单独挂载在顶层。
func (s *Server) mountSettingsReal(r chi.Router) {
r.Group(func(r chi.Router) {
@@ -33,7 +69,7 @@ func (s *Server) mountSettingsReal(r chi.Router) {
})
}
// setSettings 负责set设置相关处理。
// setSettings 封装set设置业务协调。
func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
// raw 保存兼容旧客户端和显式 DTO 的原始请求字段。
var raw map[string]json.RawMessage
@@ -174,9 +210,9 @@ func validSecretSettingAction(action string) bool {
}
}
// publicSettings 负责public设置相关处理。
// publicSettings 封装public设置业务协调。
func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
// m、err 保存m、err,供当前处理流程使用
// m、err 用于本次流程后续判断的m、err
m, err := s.settingsApplication().PublicSystem(r.Context())
if err != nil {
writeErrRequest(w, r, http.StatusInternalServerError, "查询失败")
@@ -185,7 +221,7 @@ func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, newSettingsResponse(m))
}
// allSettings 负责all设置相关处理。
// allSettings 封装all设置业务协调。
func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) {
// sess 保存当前管理员会话,用于应用服务执行敏感配置读取审计。
sess := authSess(r)
@@ -202,18 +238,13 @@ func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, newSettingsResponse(m))
}
// setSetting 负责set设置相关处理。
// setSetting 封装set设置业务协调。
func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
// key 保存key,供当前处理流程使用
// key 用于本次流程后续判断的key
key := chi.URLParam(r, "key")
// req 保存req,供当前处理流程使用
var req struct {
// Value 是普通设置值或 replace 命令的新秘密。
Value string `json:"value"`
// Action 是敏感设置的显式 retain、replace、clear 命令。
Action string `json:"action"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req systemSettingUpdateRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -240,7 +271,7 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
return
}
if key == "log_level" {
if // err 保存err,供当前处理流程使用
if // err 用于本次流程后续判断的err
err := logging.SetLevel(req.Value); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
@@ -262,14 +293,14 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
// ---- AI 回复设置 ----
// mountAIReplyReal 负责mountAI回复Real相关处理。
// mountAIReplyReal 封装mountAI回复Real业务协调。
func (s *Server) mountAIReplyReal(r chi.Router) {
r.Get("/ai-reply-settings", s.listAIReply)
r.Get("/ai-reply-settings/{cookie_id}", s.getAIReply)
r.Put("/ai-reply-settings/{cookie_id}", s.setAIReply)
}
// listAIReply 负责listAI回复相关处理。
// listAIReply 封装listAI回复业务协调。
func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证会话,用于应用服务执行用户范围查询。
sess := authSess(r)
@@ -279,7 +310,7 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
// result 保存结果,供当前处理流程使用
// result 用于本次流程后续判断的结果
result := make(map[string]aiReplySettingsResponse)
// row 表示当前遍历过程中的row
for _, row := range rows {
@@ -295,9 +326,9 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, result)
}
// getAIReply 负责getAI回复相关处理。
// getAIReply 封装getAI回复业务协调。
func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cookie_id")
// sess 保存当前认证会话,用于应用服务执行账号归属校验。
sess := authSess(r)
@@ -305,7 +336,7 @@ func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// cfg、err 保存cfg、err,供当前处理流程使用
// cfg、err 用于本次流程后续判断的cfg、err
cfg, err := s.settingsApplication().GetAIReply(r.Context(), sess.UserID, cid)
if err != nil {
if errors.Is(err, settingsapp.ErrConfigNotFound) {
@@ -329,19 +360,13 @@ func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, aiReplySettingsResponse{CookieID: cfg.CookieID, AIEnabled: cfg.AIEnabled, MaxDiscountPercent: cfg.MaxDiscountPercent, MaxDiscountAmount: cfg.MaxDiscountAmount, MaxBargainRounds: cfg.MaxBargainRounds, CustomPrompts: cfg.CustomPrompts})
}
// setAIReply 负责setAI回复相关处理。
// setAIReply 封装setAI回复业务协调。
func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
// cid 保存cid,供当前处理流程使用
// cid 用于本次流程后续判断的cid
cid := chi.URLParam(r, "cookie_id")
// req 保存req,供当前处理流程使用
var req struct {
AIEnabled bool `json:"ai_enabled"`
MaxDiscountPercent int `json:"max_discount_percent"`
MaxDiscountAmount int `json:"max_discount_amount"`
MaxBargainRounds int `json:"max_bargain_rounds"`
CustomPrompts string `json:"custom_prompts"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req aiReplySettingsUpdateRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -401,14 +426,11 @@ func writeSettingsAccountError(w http.ResponseWriter, err error) bool {
return false
}
// listAIModels 负责listAI模型列表相关处理。
// listAIModels 封装listAI模型列表业务协调。
func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
// req 保存 HTTP 层接收的模型目录查询参数。
var req struct {
BaseURL string `json:"base_url"`
APIKey string `json:"api_key"`
}
if // err 保存err,供当前处理流程使用
var req aiModelListRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
@@ -430,14 +452,14 @@ func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
// ---- 用户设置 ----
// mountUserReal 负责mount用户Real相关处理。
// mountUserReal 封装mount用户Real业务协调。
func (s *Server) mountUserReal(r chi.Router) {
r.Get("/user-settings", s.listUserSettings)
r.Put("/user-settings/{key}", s.setUserSetting)
r.Get("/user-settings/{key}", s.getUserSetting)
}
// listUserSettings 负责list用户设置相关处理。
// listUserSettings 封装list用户设置业务协调。
func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证会话,用于应用服务执行用户范围查询。
sess := authSess(r)
@@ -450,11 +472,11 @@ func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, newSettingsResponse(settings))
}
// getUserSetting 负责get用户设置相关处理。
// getUserSetting 封装get用户设置业务协调。
func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证会话,用于应用服务执行用户范围查询。
sess := authSess(r)
// key 保存key,供当前处理流程使用
// key 用于本次流程后续判断的key
key := chi.URLParam(r, "key")
// v、err 保存用户设置值及查询错误。
v, err := s.settingsApplication().GetUser(r.Context(), sess.UserID, key)
@@ -465,17 +487,15 @@ func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, userSettingResponse{Value: v})
}
// setUserSetting 负责set用户设置相关处理。
// setUserSetting 封装set用户设置业务协调。
func (s *Server) setUserSetting(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
// sess 用于本次流程后续判断的sess
sess := authSess(r)
// key 保存key,供当前处理流程使用
// key 用于本次流程后续判断的key
key := chi.URLParam(r, "key")
// req 保存req,供当前处理流程使用
var req struct {
Value string `json:"value"`
}
if // err 保存err,供当前处理流程使用
// req 用于本次流程后续判断的req
var req userSettingUpdateRequest
if // err 用于本次流程后续判断的err
err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
+13 -13
View File
@@ -19,16 +19,16 @@ func TestSPAServing(t *testing.T) {
os.WriteFile(filepath.Join(webDir, "assets", "app.js"), []byte("console.log(1)"), 0644)
os.WriteFile(filepath.Join(webDir, "favicon.svg"), []byte("<svg/>"), 0644)
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.WebDir = webDir
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// 1) / 应返回 index.html。
req := httptest.NewRequest(http.MethodGet, "/", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
@@ -40,7 +40,7 @@ func TestSPAServing(t *testing.T) {
// 2) /static/assets/app.js 应返回 JS(vite base=/static/)。
req2 := httptest.NewRequest(http.MethodGet, "/static/assets/app.js", nil)
// rec2 保存rec2,供当前处理流程使用
// rec2 用于本次流程后续判断的rec2
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
@@ -51,9 +51,9 @@ func TestSPAServing(t *testing.T) {
}
// 3) /static/favicon.svg。
// req3 保存req3,供当前处理流程使用
// req3 用于本次流程后续判断的req3
req3 := httptest.NewRequest(http.MethodGet, "/static/favicon.svg", nil)
// rec3 保存rec3,供当前处理流程使用
// rec3 用于本次流程后续判断的rec3
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
@@ -62,7 +62,7 @@ func TestSPAServing(t *testing.T) {
// 4) 客户端路由(如 /dashboard)应返回 index.html(React Router 接管)。
req4 := httptest.NewRequest(http.MethodGet, "/dashboard", nil)
// rec4 保存rec4,供当前处理流程使用
// rec4 用于本次流程后续判断的rec4
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != 200 || rec4.Body.String() != "<html>SPA</html>" {
@@ -71,7 +71,7 @@ func TestSPAServing(t *testing.T) {
// 5) API 路径不应返回 index.html。
req5 := httptest.NewRequest(http.MethodGet, "/api/orders", nil)
// rec5 保存rec5,供当前处理流程使用
// rec5 用于本次流程后续判断的rec5
rec5 := httptest.NewRecorder()
h.ServeHTTP(rec5, req5)
// /api/orders 需认证,应 401(不是 index.html)。
@@ -82,16 +82,16 @@ func TestSPAServing(t *testing.T) {
// TestSPAEmbeddedWithoutWebDir 未配置 WebDir 时使用内嵌 SPA。
func TestSPAEmbeddedWithoutWebDir(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
// srv、cleanup 用于本次流程后续判断的srv、cleanup
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.WebDir = ""
// h 保存h,供当前处理流程使用
// h 用于本次流程后续判断的h
h := srv.Router()
// req 保存req,供当前处理流程使用
// req 用于本次流程后续判断的req
req := httptest.NewRequest(http.MethodGet, "/", nil)
// rec 保存rec,供当前处理流程使用
// rec 用于本次流程后续判断的rec
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
@@ -102,7 +102,7 @@ func TestSPAEmbeddedWithoutWebDir(t *testing.T) {
}
}
// init 负责init相关处理。
// init 封装init业务协调。
func init() {
// newTestServer 用 context.Background,确保可用。
_ = context.Background
+1
View File
@@ -38,6 +38,7 @@ func TestChatEventDTOUsesFrontendContract(t *testing.T) {
}
// payload 保存浏览器实际接收的 JSON 对象。
var payload map[string]any
// unmarshalErr 表示将聊天事件 JSON 解码为契约断言对象时的错误。
if unmarshalErr := json.Unmarshal(encoded, &payload); unmarshalErr != nil {
t.Fatalf("解码聊天实时事件: %v", unmarshalErr)
}
+2 -2
View File
@@ -2,9 +2,9 @@ package server
import "io"
// readLimitedBytes 负责readLimitedBytes相关处理。
// readLimitedBytes 封装readLimitedBytes业务协调。
func readLimitedBytes(r io.Reader, maxBytes int64) ([]byte, bool, error) {
// data、err 保存data、err,供当前处理流程使用
// data、err 用于本次流程后续判断的data、err
data, err := io.ReadAll(io.LimitReader(r, maxBytes+1))
if err != nil {
return nil, false, err