API契约:迁移聊天商品与自动化错误

This commit is contained in:
Christ committed 2026-08-14 14:17:15 +08:00
1 parent 4d92e8e919
commit 82da4d8bb5
8 files changed
+134 -29

No files matched your search

@@ -0,0 +1,57 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"xianyu-go/internal/httpapi"
"xianyu-go/internal/xianyu/mtop"
)
// TestAPIContractChatAutomationAndItemErrors 验证聊天、自动化和商品失败均返回统一错误 DTO。
func TestAPIContractChatAutomationAndItemErrors(t *testing.T) {
// srv 是用于验证聊天、自动化和商品错误契约的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// srv.MTop 是返回缺少商品 ID 结果的测试平台客户端。
srv.MTop = &stubPublishMTop{publish: func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return &mtop.PublishItemResult{Title: "测试商品"}, nil
}}
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
assertUnifiedAPIError(t, handler, http.MethodPost, "/api/chat/messages", `{}`, sessionCookie, http.StatusServiceUnavailable, httpapi.CodeServiceUnavailable, "聊天服务未启用", false)
assertUnifiedAPIError(t, handler, http.MethodPost, "/api/account-tasks/acc1/run", `{"task_type":"auto_rate"}`, sessionCookie, http.StatusServiceUnavailable, httpapi.CodeServiceUnavailable, "自动化中心未启用", false)
// body 和 contentType 是有效商品发布表单及其 multipart 类型。
body, contentType := buildPublishMultipart(t, map[string]string{"cookie_id": "acc1", "title": "测试商品", "price": "12.50", "quantity": "1"})
// req 是触发远端结果缺少商品 ID 的发布请求。
req := httptest.NewRequest(http.MethodPost, "/items/publish", body)
req.Header.Set("Content-Type", contentType)
req.AddCookie(sessionCookie)
// recorder 是捕获商品发布错误响应的测试记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != http.StatusBadGateway {
t.Fatalf("publish status=%d body=%s", recorder.Code, recorder.Body.String())
}
// response 是商品发布失败的统一错误 DTO。
var response httpapi.ErrorResponse
// decodeErr 表示商品发布错误响应 JSON 反序列化失败的原因。
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &response); decodeErr != nil {
t.Fatalf("decode publish error: %v", decodeErr)
}
if response.Code != "publish_result_missing_item_id" || response.Message == "" {
t.Fatalf("response=%+v", response)
}
if response.Details != nil {
t.Fatalf("unexpected details=%+v", response.Details)
}
if strings.Contains(recorder.Body.String(), `"success"`) {
t.Fatalf("publish error contains legacy success field: %s", recorder.Body.String())
}
}
+5
View File
@@ -91,6 +91,11 @@ func writeErrCode(w http.ResponseWriter, status int, code, msg, requestID string
httpapi.WriteError(w, status, code, msg, requestID)
}
// writeErrDetails 写带恢复信息的统一错误响应,详情只作为附加数据返回。
func writeErrDetails(w http.ResponseWriter, status int, code, msg, requestID string, details map[string]any) {
httpapi.WriteErrorDetails(w, status, code, msg, requestID, details)
}
// writeCredentialVerificationError 将当前密码校验失败区分为认证失败或内部故障。
func writeCredentialVerificationError(w http.ResponseWriter, err error) {
if errors.Is(err, db.ErrPasswordMismatch) {
+2 -2
View File
@@ -207,7 +207,7 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
}
if err := sender.SendImage(engine.WithOutgoingMessageKey(r.Context(), message.MessageKey), chatID, buyerID, upload.URL, 0); err != nil {
failed, _ := s.chat.SetOutgoingStatus(context.Background(), accountID, message.MessageKey, "failed")
writeJSON(w, http.StatusBadGateway, map[string]any{"message": failed, "error": "图片发送失败,请重试"})
writeErrDetails(w, http.StatusBadGateway, "chat_image_send_failed", "图片发送失败,请重试", "", map[string]any{"outgoing_message": failed})
return
}
sent, err := s.chat.SetOutgoingStatus(r.Context(), accountID, message.MessageKey, "sent")
@@ -354,7 +354,7 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
sendContext := engine.WithOutgoingMessageKey(r.Context(), message.MessageKey)
if err := sender.SendText(sendContext, input.ChatID, input.BuyerID, input.Text); err != nil {
failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.AccountID, message.MessageKey, "failed")
writeJSON(w, http.StatusBadGateway, map[string]any{"message": failed, "error": "发送失败,请重试"})
writeErrDetails(w, http.StatusBadGateway, "chat_message_send_failed", "发送失败,请重试", "", map[string]any{"outgoing_message": failed})
return
}
sent, err := s.chat.SetOutgoingStatus(r.Context(), input.AccountID, message.MessageKey, "sent")
+25 -25
View File
@@ -160,23 +160,23 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
status = http.StatusForbidden
msg = "该账号没有库存发布权限,无法按库存数量发布商品"
}
writeJSON(w, status, map[string]any{
"success": false,
"code": perr.Code,
"message": msg,
"ret": perr.Ret,
})
writeErrCode(
w,
status,
string(perr.Code),
msg,
"")
return
}
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
if res == nil || strings.TrimSpace(res.ItemID) == "" {
writeJSON(w, http.StatusBadGateway, map[string]any{
"success": false,
"code": "publish_result_missing_item_id",
"message": "平台返回发布成功,但缺少商品 ID,无法确认发布结果",
})
writeErrCode(w, http.StatusBadGateway,
"publish_result_missing_item_id",
"平台返回发布成功,但缺少商品 ID,无法确认发布结果",
"",
)
return
}
detail := map[string]any{
@@ -200,23 +200,23 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
if s.Logger != nil {
s.Logger.Error("平台已发布但保存本地商品失败", "cookie_id", cookieID, "item_id", res.ItemID, "err", err)
}
writeJSON(w, http.StatusInternalServerError, map[string]any{
"success": false,
"code": "remote_published_local_save_failed",
"message": "商品已在平台发布,但本地保存失败,请勿重复发布并根据商品 ID 人工核对",
"item_id": res.ItemID,
"item_url": res.ItemURL,
})
writeErrDetails(
w,
http.StatusInternalServerError,
"remote_published_local_save_failed",
"商品已在平台发布,但本地保存失败,请勿重复发布并根据商品 ID 人工核对",
"",
map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL})
return
}
if responseCookieErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]any{
"success": false,
"code": "remote_published_cookie_save_failed",
"message": "商品已在平台发布并保存到本地,但登录凭证更新保存失败,请勿重复发布并尽快重新登录",
"item_id": res.ItemID,
"item_url": res.ItemURL,
})
writeErrDetails(
w,
http.StatusInternalServerError,
"remote_published_cookie_save_failed",
"商品已在平台发布并保存到本地,但登录凭证更新保存失败,请勿重复发布并尽快重新登录",
"",
map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL})
return
}
writeJSON(w, http.StatusOK, map[string]any{