API契约:迁移订单与账号业务错误
This commit is contained in:
1 parent
1efe44e921
commit
4d92e8e919
6 files changed
+87
-31
No files matched your search
@@ -100,7 +100,7 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
summary, err := s.automation.RunAccountTask(r.Context(), cid, input.TaskType)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"summary": summary, "error": err.Error()})
|
||||
writeErr(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "summary": summary})
|
||||
|
||||
@@ -144,6 +144,9 @@ func assertUnifiedAPIError(t *testing.T, handler http.Handler, method, path, bod
|
||||
if requireRequestID && response.RequestID == "" {
|
||||
t.Fatalf("%s %s 缺少 request_id: %+v", method, path, response)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), `"detail"`) || strings.Contains(rec.Body.String(), `"msg"`) || strings.Contains(rec.Body.String(), `"error"`) {
|
||||
t.Fatalf("%s %s 包含旧错误字段: %s", method, path, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIContractRemainingAuthenticationErrors 验证初始化和密码凭据错误统一使用非 2xx 响应。
|
||||
@@ -181,3 +184,54 @@ func TestAPIContractPublicAndSPAErrors(t *testing.T) {
|
||||
assertUnifiedAPIError(t, handler, http.MethodGet, "/system-settings/public", "", nil, http.StatusInternalServerError, httpapi.CodeInternalError, "查询失败", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodGet, "/api/not-found", "", nil, http.StatusNotFound, httpapi.CodeNotFound, "接口不存在", true)
|
||||
}
|
||||
|
||||
// TestAPIContractOrderAndAccountErrors 验证订单和账号业务错误使用统一状态码及错误字段。
|
||||
func TestAPIContractOrderAndAccountErrors(t *testing.T) {
|
||||
// srv 是用于验证订单和账号业务错误的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
assertUnifiedAPIError(t, handler, http.MethodGet, "/api/orders/not-found", "", sessionCookie, http.StatusNotFound, httpapi.CodeNotFound, "订单不存在", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodPost, "/api/orders/manual-ship", `{"order_ids":["order-1"],"ship_mode":"invalid"}`, sessionCookie, http.StatusBadRequest, httpapi.CodeBadRequest, "发货模式必须是 status_only 或 full_delivery", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodGet, "/cookie/not-found/details", "", sessionCookie, http.StatusForbidden, httpapi.CodeForbidden, "无权限操作该Cookie", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodGet, "/api/account-tasks/not-found", "", sessionCookie, http.StatusForbidden, httpapi.CodeForbidden, "无权访问该账号", false)
|
||||
}
|
||||
|
||||
// TestAPIContractOrderBatchPartialFailure 验证订单批量接口用 partial_failure 表示逐项失败,不再返回顶层 success=false。
|
||||
func TestAPIContractOrderBatchPartialFailure(t *testing.T) {
|
||||
// srv 是用于验证订单批量失败响应的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
// req 是包含不存在订单的手动发货请求。
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(`{"order_ids":["not-found"],"ship_mode":"status_only"}`))
|
||||
req.AddCookie(sessionCookie)
|
||||
// rec 是捕获批量操作响应的测试记录器。
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("batch status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// response 是批量操作的兼容响应对象。
|
||||
var response map[string]any
|
||||
// decodeErr 表示批量响应 JSON 反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(rec.Body.Bytes(), &response); decodeErr != nil {
|
||||
t.Fatalf("decode batch response: %v", decodeErr)
|
||||
}
|
||||
if response["partial_failure"] != true {
|
||||
t.Fatalf("batch response=%+v", response)
|
||||
}
|
||||
// exists 表示兼容响应是否仍暴露顶层 success 字段。
|
||||
if _, exists := response["success"]; exists {
|
||||
t.Fatalf("batch response must not expose top-level success: %s", rec.Body.String())
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), `"error"`) {
|
||||
t.Fatalf("batch response contains legacy error field: %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -363,14 +363,14 @@ func TestOrderImportReportsPartialFailure(t *testing.T) {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
SuccessCount int `json:"success_count"`
|
||||
FailedCount int `json:"failed_count"`
|
||||
PartialFailure bool `json:"partial_failure"`
|
||||
SuccessCount int `json:"success_count"`
|
||||
FailedCount int `json:"failed_count"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Success || result.SuccessCount != 1 || result.FailedCount != 1 {
|
||||
if !result.PartialFailure || result.SuccessCount != 1 || result.FailedCount != 1 {
|
||||
t.Fatalf("result=%+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,7 +202,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
failed++
|
||||
results = append(results, map[string]any{
|
||||
"cookie_id": cid, "stage": "discover", "success": false, "error": latestErr.Error(),
|
||||
"cookie_id": cid, "stage": "discover", "success": false, "message": latestErr.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -250,7 +250,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
} else {
|
||||
failed++
|
||||
results = append(results, map[string]any{"stage": "discover", "success": false, "error": "当前 MTop 客户端不支持订单列表发现"})
|
||||
results = append(results, map[string]any{"stage": "discover", "success": false, "message": "当前 MTop 客户端不支持订单列表发现"})
|
||||
}
|
||||
|
||||
ordersByCookie := map[string][]refreshTarget{}
|
||||
@@ -295,8 +295,8 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
message += fmt.Sprintf(";当前 Go MTOP 客户端不支持详情接口,已跳过 %d 个订单", total)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": failed == 0,
|
||||
"message": message,
|
||||
"partial_failure": failed > 0,
|
||||
"message": message,
|
||||
"summary": map[string]int{
|
||||
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
|
||||
"total": total, "updated": 0, "no_change": 0, "failed": failed,
|
||||
@@ -307,8 +307,8 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if total == 0 {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": failed == 0,
|
||||
"message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
|
||||
"partial_failure": failed > 0,
|
||||
"message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
|
||||
"summary": map[string]int{
|
||||
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": 0,
|
||||
"total": 0, "updated": 0, "no_change": 0, "failed": failed,
|
||||
@@ -327,7 +327,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
if latestErr != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) {
|
||||
credentialUnlock()
|
||||
failed += len(chunk)
|
||||
results = append(results, map[string]any{"cookie_id": cid, "success": false, "error": "账号凭证已变化"})
|
||||
results = append(results, map[string]any{"cookie_id": cid, "success": false, "message": "账号凭证已变化"})
|
||||
continue
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
|
||||
@@ -344,7 +344,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
results = append(results, map[string]any{
|
||||
"order_id": target.OrderID,
|
||||
"success": false,
|
||||
"error": message,
|
||||
"message": message,
|
||||
})
|
||||
if mtop.IsSessionExpiredErr(fetchErr) {
|
||||
sessionErr = fetchErr
|
||||
@@ -366,7 +366,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
if err != nil {
|
||||
failed++
|
||||
results = append(results, map[string]any{"order_id": target.OrderID, "success": false, "error": "更新数据库失败"})
|
||||
results = append(results, map[string]any{"order_id": target.OrderID, "success": false, "message": "更新数据库失败"})
|
||||
continue
|
||||
}
|
||||
changed := newStatus != "" && newStatus != target.CurrentStatus
|
||||
@@ -387,7 +387,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
credentialUnlock()
|
||||
if persistErr != nil {
|
||||
failed++
|
||||
results = append(results, map[string]any{"cookie_id": cid, "stage": "persist_cookie", "success": false, "error": persistErr.Error()})
|
||||
results = append(results, map[string]any{"cookie_id": cid, "stage": "persist_cookie", "success": false, "message": persistErr.Error()})
|
||||
} else if valueChanged {
|
||||
s.updateRunningCookie(r.Context(), cid, value)
|
||||
}
|
||||
@@ -402,8 +402,8 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": failed == 0,
|
||||
"message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
|
||||
"partial_failure": failed > 0,
|
||||
"message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
|
||||
"summary": map[string]int{
|
||||
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
|
||||
"total": total, "updated": updated, "no_change": noChange, "failed": failed,
|
||||
@@ -856,11 +856,11 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Sprintf("手动确认发货成功(订单 %s)", orderID))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": failedCount == 0,
|
||||
"message": fmt.Sprintf("手动发货完成: 成功%d个, 失败%d个", successCount, failedCount),
|
||||
"success_count": successCount,
|
||||
"failed_count": failedCount,
|
||||
"results": results,
|
||||
"partial_failure": failedCount > 0,
|
||||
"message": fmt.Sprintf("手动发货完成: 成功%d个, 失败%d个", successCount, failedCount),
|
||||
"success_count": successCount,
|
||||
"failed_count": failedCount,
|
||||
"results": results,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1013,12 +1013,12 @@ func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
|
||||
results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "订单已导入"})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": failedCount == 0,
|
||||
"message": fmt.Sprintf("导入完成: 成功%d个, 失败%d个", successCount, failedCount),
|
||||
"total": len(orders),
|
||||
"success_count": successCount,
|
||||
"failed_count": failedCount,
|
||||
"results": results,
|
||||
"partial_failure": failedCount > 0,
|
||||
"message": fmt.Sprintf("导入完成: 成功%d个, 失败%d个", successCount, failedCount),
|
||||
"total": len(orders),
|
||||
"success_count": successCount,
|
||||
"failed_count": failedCount,
|
||||
"results": results,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -448,7 +448,7 @@ func TestManualShipOrdersStatusOnlySuccess(t *testing.T) {
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != true {
|
||||
if res["partial_failure"] != false {
|
||||
t.Fatalf("应成功: %+v", res)
|
||||
}
|
||||
results, _ := res["results"].([]any)
|
||||
@@ -511,7 +511,7 @@ func TestManualShipOrdersConsignFail(t *testing.T) {
|
||||
}
|
||||
var res map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["success"] != false {
|
||||
if res["partial_failure"] != true {
|
||||
t.Fatalf("整体应失败: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user