API契约:迁移剩余认证与公共错误

This commit is contained in:
Christ committed 2026-08-14 13:55:51 +08:00
1 parent 4e7abf61be
commit 1efe44e921
5 files changed
+89 -10

No files matched your search

+65
View File
@@ -1,6 +1,7 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -116,3 +117,67 @@ func TestAPIContractAccountList(t *testing.T) {
t.Fatalf("account list exposes credential field: %s", rec.Body.String())
}
}
// assertUnifiedAPIError 验证指定请求返回统一错误 DTO 和预期 HTTP 状态。
func assertUnifiedAPIError(t *testing.T, handler http.Handler, method, path, body string, sessionCookie *http.Cookie, status int, code, message string, requireRequestID bool) {
t.Helper()
// req 是待验证统一错误契约的 HTTP 请求。
req := httptest.NewRequest(method, path, strings.NewReader(body))
if sessionCookie != nil {
req.AddCookie(sessionCookie)
}
// rec 是捕获错误响应的测试记录器。
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != status {
t.Fatalf("%s %s status=%d body=%s", method, path, rec.Code, rec.Body.String())
}
// response 是统一错误响应 DTO。
var response httpapi.ErrorResponse
// decodeErr 表示错误响应 JSON 反序列化失败的原因。
if decodeErr := json.Unmarshal(rec.Body.Bytes(), &response); decodeErr != nil {
t.Fatalf("%s %s decode error: %v", method, path, decodeErr)
}
if response.Code != code || response.Message != message {
t.Fatalf("%s %s response=%+v", method, path, response)
}
if requireRequestID && response.RequestID == "" {
t.Fatalf("%s %s 缺少 request_id: %+v", method, path, response)
}
}
// TestAPIContractRemainingAuthenticationErrors 验证初始化和密码凭据错误统一使用非 2xx 响应。
func TestAPIContractRemainingAuthenticationErrors(t *testing.T) {
// srv 是用于验证剩余认证错误边界的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// created 表示用于验证用户名冲突的占位用户是否成功创建。
created, createErr := srv.Store.Users.Create(context.Background(), "taken-user", "[email protected]", "pw")
if createErr != nil || !created {
t.Fatalf("create conflict user: created=%v err=%v", created, createErr)
}
assertUnifiedAPIError(t, handler, http.MethodPost, "/initialize", `{"password":"another-password"}`, nil, http.StatusConflict, httpapi.CodeConflict, "系统已经初始化,请直接登录", false)
assertUnifiedAPIError(t, handler, http.MethodPost, "/change-admin-password", `{"current_password":"wrong","new_password":"newpw123"}`, sessionCookie, http.StatusUnauthorized, "authentication_failed", "当前密码错误", false)
assertUnifiedAPIError(t, handler, http.MethodPost, "/change-password", `{"current_password":"wrong","new_password":"newpw123"}`, sessionCookie, http.StatusUnauthorized, "authentication_failed", "当前密码错误", false)
assertUnifiedAPIError(t, handler, http.MethodPut, "/account/credentials", `{"current_password":"wrong","new_username":"admin-renamed"}`, sessionCookie, http.StatusUnauthorized, "authentication_failed", "当前密码错误", false)
assertUnifiedAPIError(t, handler, http.MethodPut, "/account/credentials", `{"current_password":"pw","new_username":"taken-user"}`, sessionCookie, http.StatusConflict, "username_taken", "用户名已被占用", false)
}
// TestAPIContractPublicAndSPAErrors 验证公开设置故障和 SPA API 404 均返回统一错误 DTO。
func TestAPIContractPublicAndSPAErrors(t *testing.T) {
// srv 和 store 是用于模拟公开 API 数据库故障的测试服务及其存储。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// closeErr 表示主动关闭测试数据库连接的结果。
if closeErr := store.DB.Close(); closeErr != nil {
t.Fatalf("close test database: %v", closeErr)
}
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)
}